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();
        
        log.info("Ejecutando el controlador Spring MVC");
        log.info("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("https://checkip.amazonaws.com/");
            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);
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        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:

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

THX

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:

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

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

    // all remaining fields here...

}

And which has a matching, typical, repository:

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

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

@RestController
@RequestMapping("/v1/widgets")
public class WidgetResource {

  @Autowired
  private WidgetService widgetService;

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

}

@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 https://stackoverflow.com/questions/48446708/securing-spring-boot-api-with-api-key-and-secret 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)

@Component
public class ApiKeyRequestFilter extends GenericFilterBean {

@Value("${espd.http.auth-token-header-name}")
private String principalRequestHeader;

@Value("${espd.http.auth-token}")
private String principalRequestValue;

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

    resp.reset();
    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.setContentLength(error .length());
    response.getWriter().write(error);
}

@Override
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)) {
                returnNoAPIKeyError(response);
                return;
            }
            else {
                chain.doFilter(request, response);
            }
        }
    }

    if(!apiKeyGiven) {
        returnNoAPIKeyError(response);
    }
    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:

bot.url=https://74e437885ee9.ngrok.io

bot.path=adam

    @Slf4j
@Configuration
public class BotConfig {
  @Value("${bot.url}")
  private String BOT_URL;

  @Bean
  public SetWebhook setWebhookInstance() {
    return SetWebhook.builder().url(BOT_URL).build();
  }
  // Create it as
  @Bean
  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);
    log.info("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
https://api.telegram.org/MY_TOKEN_HERE/setWebhook?url=https://74e437885ee9.ngrok.io

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

    public class AdamSmithBot extends SpringWebhookBot {
  @Value("${bot.token}")
  private String TOKEN;

  @Value("${bot.name}")
  private String BOT_USERNAME;

  @Value("${bot.path}")
  private String BOT_PATH;

  public AdamSmithBot(SetWebhook setWebhook) {

    super(setWebhook);
  }

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

  @Override
  public String getBotUsername() {
    return BOT_USERNAME;
  }

  @Override
  public String getBotToken() {
    return TOKEN;
  }

  @Override
  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;
  }

  @Override
  public String getBotPath() {
    return "adam";
  }
}

Constroller:

    @Slf4j
@RestController
public class WebHookBotRecieveController {
    @Autowired
    private AdamSmithBot adamSmithBot;
    @PostMapping("/")
    public void getUpdate(@RequestBody Update update){
        log.info("some update recieved {}",update.toString());
        adamSmithBot.onWebhookUpdateReceived(update);

    }
    @PostMapping("/callback/adam")
    public void getUpdateWithDifferentUrl(@RequestBody Update update){
        log.info("some update recieved {}",update.toString());
        adamSmithBot.onWebhookUpdateReceived(update);

    }
}

NOTE: I seemd some info here:
https://github.com/rubenlagus/TelegramBots/wiki/How-To-Update

They do that:
https://i.stack.imgur.com/9JKRT.png

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 -> {
            obj.getUser().setPassword("");
            return obj;
        }).collect((Collectors.toList()));
    } else {
        return postRepository.findAllByOrderByIdDesc().stream().map(obj -> {
            obj.getUser().setPassword("");
            return obj;
        }).collect((Collectors.toList()));
    }
}

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

.apis(RequestHandlerSelectors.basePackage("io.swagger.api"))

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 {

                Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
            }
            catch(ClassNotFoundException cnfex) {

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

            // 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(resultSet.next()) {
                    System.out.println( //pais,abre,nombre
                            resultSet.getString(1) + "t" + 
                            resultSet.getString(2) + "t" + 
                            resultSet.getString(3) + "t" +
                            resultSet.getString(4));
                }
            }
            catch(SQLException sqlex){
                sqlex.printStackTrace();
            }
            finally {

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

                        // cleanup resources, once after processing
                        resultSet.close();
                        statement.close();

                        // and then finally close connection
                        connection.close();
                    }
                }
                catch (SQLException sqlex) {
                    sqlex.printStackTrace();
                }
            }

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 ExtraProxies.com - 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 ProxiesLive.com Proxies-free.com New Proxy Lists Every Day Proxies123.com Buy Cheap Private Proxies; Best Quality USA Private Proxies