Inconsistent response from Spring Security HTTP Basic between GET and POST

Why do I get a 401 from the POST but always get what I expect from the GET?

GET http://localhost:8080/user/3
Authorization: Basic username password

<> 2021-07-21T205654.200.json
<> 2021-07-21T205029.200.json

POST http://localhost:8080/user
Authorization: Basic username password
Content-Type: application/json


How to design a rest api for updating collection(ArrayList) of Resource in Spring boot?

I have a resource called Client and it has the following attributes id, name, redirect URLs(ArrayList).

class Client{
   int id;
   String name;
   List<String> redirectUrls;

I have all CRUD http request mappings over resource Client. In the get method I fetch the resource from database and give to client, however my firewall blocks the put requerst when user submits the put request to update the resource since it carries collections of urls(redirectUrls) within the request body.

So, I have this requrement to design an API only to update the collection of given Client. Let’s say for a given Client I have 10 redirectUrls(loaded in the Client UI) and as soon as the client adds a new redirectUrl, my client calls this new API with the redirectUrl and it gets added to collection in the backend. At any given point of time when client adds new redirectUrl the API gets called.

The question here is how should I design my API so that only this particular attribute(redirectUrl list) gets updated with the coming redirectUrl. One option is PATCH API but this one should ideally replace the whole attribute value with new vlaue, which is not what supposed to happen in my case.

Any help is much appreciated. Thanks.

tomcat – Recover IP BEFORE loging in Spring Boot

I made an app using Spring Boot wich uses Spring Security to login. I can recover the IP after the login because I put the next code in my controller and share the objets in my model:

@GetMapping("/") //http://localhost:8080/  tipo GET
    //Principio de Hollywood: "No me llames, yo te voy a llamar B)"
    public String inicio(Model model, @AuthenticationPrincipal User user) {//para recuperar el usuario que se inició sesión
        List<Persona> personas = (List<Persona>) ps.listarPersonas();
       "Ejecutando el controlador Spring MVC");"Usuario" + user);
        model.addAttribute("personas", personas);//en lugar de request.setAttribute
        double saldoTotal =0;
        for (Persona p : personas) {
            saldoTotal += p.getSaldo();
        model.addAttribute("saldoTotal", saldoTotal);
        model.addAttribute("totalClientes", personas.size());//comparte el numero total de clientes
        Recuperación de la ip interna y externa:
        String errorReport = "Sin Errores :)";
        StringBuilder mainMessage = new StringBuilder();
        try {
            URL conexion = new URL("");
            URLConnection con = conexion.openConnection();
            String str = null;
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            str = reader.readLine();
            mainMessage.append("IP Real: " + str);
            // Local address
            mainMessage.append(" | Local Host Address: " + InetAddress.getLocalHost().getHostAddress());
            mainMessage.append(" Local Host Name: " + InetAddress.getLocalHost().getHostName());
            // Remote address
            mainMessage.append(" | Remote Host Address: " + InetAddress.getLoopbackAddress().getHostAddress());
            mainMessage.append(" | Remote Host Address: " + InetAddress.getLoopbackAddress().getHostName());
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            errorReport = e.getMessage(); 
            model.addAttribute("error", errorReport);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        model.addAttribute("ip", mainMessage.toString());
        return "index"; //el nombre de la pagina a donde redirige este controlador

And the result is the next:
Shared IP in my footer


But I need to have it in the login page too , the thing is when i try to acces the url “/” spring security brings me to “/login”, so I am not be able to get the IP from begining:
footer without IP

This is my security config, if helps:

public class SecurityConfig extends WebSecurityConfigurerAdapter{
    private UserDetailsService userDetailsService;
    @Bean //con esto el objeto va a estar disponible dentro del contenedor de spring
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    public void configurerGlobal(AuthenticationManagerBuilder build) throws Exception{ //este objeto se agrega de manera automatica 
    protected void configure(HttpSecurity http) throws Exception{ //restricción de URLs (autorización)
            .antMatchers("/editar/**", "/agregar/**", "/eliminar")//con esto restringiremos todos los paths dentro de editar
                .hasAnyRole("USER", "ADMIN")
//            .and()
//                .csrf().disable()


mysql – Implementing transactional entity lockouts with Spring and JPA

Spring Boot/Java 8/MySQL here.

I have a widgets table in my MySQL DB that is modeled by a JPA entity like so:

@Table(name = "widgets")
public class Widget {

    @Column(name = "widget_property")
    private String property;

    // all remaining fields here...


And which has a matching, typical, repository:

public interface WidgetRepository extends CrudRepository<Long,Widget> {
  // JPA methods here...

And which also has corresponding controller and service classes as well:

public class WidgetResource {

  private WidgetService widgetService;

  // API endpoint methods to CRUD widgets using the service...


public class WidgetService {
  // widget methods here...

Pretty standard stuff. I now need to present my users with a list of all Widgets and allow a user to “lock” a particular Widget for editing. The idea/flow I’m thinking here is:

  1. A user “locks” a widget, perhaps by clicking a button or selecting a drop-down in the UI
  2. While the widget is “locked” it will not appear as being available to any other users; also, if another user happened to view the screen (list of available widgets) just before the first user locked a particular widget, and this other user just happens to try and lock the same widget, they will not be allowed to do so. In general, if a widget is locked, no other user can lock it.
  3. A user can only edit a widget they have “locked”
  4. When a user is done editing it they may “unlock” it which allows it to be listed, re-locked and re-edited by other users. Or, after 12 hrs, a widget automatically unlocks itself (in case the locking user forgot about it and went home)

I know there’s probably all sorts of tricks with optimistic locking that can be done here, but I’m wondering if Spring has anything out of the box (perhaps that leverages @Transactional?) that would help me out here. I’m not opposed to implementing some type of blocking-queue-with-competing-consumers pattern, however I cannot add any infrastructure or deployment complexity, so it would have to be an in-memory, transactional queuing solution.

Any ideas as to how I can implement this using my tech stack, data model and required user flow?

java – Spring Boot API Key Filter

After this didn’t work for me (filter did nothing) and I couldn’t find any useful tutorial with api keys and spring boot i just wrote my own filter:

// (imports)

public class ApiKeyRequestFilter extends GenericFilterBean {

private String principalRequestHeader;

private String principalRequestValue;

private void returnNoAPIKeyError(ServletResponse response) throws IOException {
    HttpServletResponse resp = (HttpServletResponse) response;
    String error = "Nonexistent or invalid API KEY";

    response.setContentLength(error .length());

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    boolean apiKeyGiven = false;

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    Enumeration headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        if(key.equals(principalRequestHeader)) {
            apiKeyGiven = true;

            String value = httpRequest.getHeader(key);
            if(!value.equals(principalRequestValue)) {
            else {
                chain.doFilter(request, response);

    if(!apiKeyGiven) {
    else {
        chain.doFilter(request, response);


My questions are what to improve and is it safe?

spring – How can I rewrite the below parser code in Java

spring – How can I rewrite the below parser code in Java – Code Review Stack Exchange

register webhook tg bot using spring boot

I am using telegrambots-spring-boot-starter v 5.2.0 and trying register my bot
Here’s my bot config:



public class BotConfig {
  private String BOT_URL;

  public SetWebhook setWebhookInstance() {
    return SetWebhook.builder().url(BOT_URL).build();
  // Create it as
  public AdamSmithBot adamSmithBot(SetWebhook setWebhookInstance) throws TelegramApiException {
    AdamSmithBot adamSmithBot = new AdamSmithBot(setWebhookInstance);
    //        DefaultWebhook defaultWebhook = new DefaultWebhook();
    //        defaultWebhook.setInternalUrl(BOT_URL);
    //        defaultWebhook.registerWebhook(adamSmithBot);

    TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class);"SetWebHook from AdamSmith bot {}", adamSmithBot.getSetWebhook());
    telegramBotsApi.registerBot(adamSmithBot, adamSmithBot.getSetWebhook());
    return adamSmithBot;

But it dont working, but when i send this request, it working perfectly and updates recieve to me

I think my mistake in BotConfig,but i also publush my other clases bot and controller:

    public class AdamSmithBot extends SpringWebhookBot {
  private String TOKEN;

  private String BOT_USERNAME;

  private String BOT_PATH;

  public AdamSmithBot(SetWebhook setWebhook) {


  public AdamSmithBot(DefaultBotOptions options, SetWebhook setWebhook) {
    super(options, setWebhook);

  public String getBotUsername() {
    return BOT_USERNAME;

  public String getBotToken() {
    return TOKEN;

  public BotApiMethod<?> onWebhookUpdateReceived(Update update) {

    if (update.getMessage() != null && update.getMessage().hasText()) {
      Long chatId = update.getMessage().getChatId();
      try {
        execute(new SendMessage(chatId.toString(), "HI HANDSOME " + update.getMessage().getText()));

      } catch (TelegramApiException e) {
        throw new IllegalStateException(e);
    return null;

  public String getBotPath() {
    return "adam";


public class WebHookBotRecieveController {
    private AdamSmithBot adamSmithBot;
    public void getUpdate(@RequestBody Update update){"some update recieved {}",update.toString());

    public void getUpdateWithDifferentUrl(@RequestBody Update update){"some update recieved {}",update.toString());


NOTE: I seemd some info here:

They do that:

But when i trying put DefaultWebhook class instead it produce NullPointerException
What i made wrong?

spring – Is Java Stream connected to the Database?

public List<Post> getPosts(String city) {
    // if City parameter is presented(When searched by an user)
    if (!Strings.isNullOrEmpty(city)) {
        return postRepository.findAllByCityOrderByIdDesc(city).stream().map(obj -> {
            return obj;
    } else {
        return postRepository.findAllByOrderByIdDesc().stream().map(obj -> {
            return obj;

I tried to change object values with the stream map function after fetching data from the DB, and the values in the DB changed too.

are they two connected?

spring – Cannot access java.util.function.Predicate

I use swagger to generate code for spring server and try to run with intelliJ. However I got the following error message. Any help is appreciated.

java: cannot access java.util.function.Predicate
  class file for java.util.function.Predicate not found

on the line


java – ¿Cómo utilizar archivos .mdb en Spring Batch para después almacenarlo en mi BBDD?

básicamente lo que estoy intentando y quiero es pasar automáticamente los archivos .mdb a mi base de datos que está en Postgresql todo a través de Spring Batch. El caso es que según me he estado informando no hay soporte Spring Batch para archivos .mdb, entonces basandome en otra respuesta de la comunidad inglesa he conseguido traerme los datos de uno de los archivos .mdb, y quiero estos insertarlos en mi tabla que se llama País en Postgresql. ¿Cómo podría realizar esto para se pudiera hacer con Spring Batch y pueda automzar el proceso? He mirado en bastantes lados pero no me queda claro.

            // variables
            Connection connection = null;
            Statement statement = null;
            ResultSet resultSet = null;

            // Step 1: Loading or registering Oracle JDBC driver class
            try {

            catch(ClassNotFoundException cnfex) {

                System.out.println("Problem in loading or "
                        + "registering MS Access JDBC driver");

            // Step 2: Opening database connection
            try {

                String msAccDB = "C:/Users/xxxx/Desktop/prueba/paises.mdb";
                String dbURL = "jdbc:ucanaccess://" + msAccDB; 

                // Step 2.A: Create and get connection using DriverManager class
                connection = DriverManager.getConnection(dbURL); 

                // Step 2.B: Creating JDBC Statement 
                statement = connection.createStatement();

                // Step 2.C: Executing SQL & retrieve data into ResultSet
                resultSet = statement.executeQuery("SELECT * FROM PAIS");


                // processing returned data and printing into console
            //    ResultSetMetaData rsmd = resultSet.getMetaData();
           //     System.out.println(rsmd.getColumnName(0));
                while( {
                    System.out.println( //pais,abre,nombre
                            resultSet.getString(1) + "t" + 
                            resultSet.getString(2) + "t" + 
                            resultSet.getString(3) + "t" +
            catch(SQLException sqlex){
            finally {

                // Step 3: Closing database connection
                try {
                    if(null != connection) {

                        // cleanup resources, once after processing

                        // and then finally close connection
                catch (SQLException sqlex) {

Los datos que he conseguido traerme:

introducir la descripción de la imagen aquí

DreamProxies - Cheapest USA Elite Private Proxies 100 Private Proxies 200 Private Proxies 400 Private Proxies 1000 Private Proxies 2000 Private Proxies 5000 Private Proxies - Buy Cheap Private Proxies Buy 50 Private Proxies Buy 100 Private Proxies Buy 200 Private Proxies Buy 500 Private Proxies Buy 1000 Private Proxies Buy 2000 Private Proxies New Proxy Lists Every Day Buy Cheap Private Proxies; Best Quality USA Private Proxies