Posts

Showing posts with the label spring

How to log slf4j to a file in cuba Framework

How to log slf4j to a file in cuba Framework I'm trying to configure cuba framework in order to write the logs in a file, but at the moment I cannot. I have in the java files: private static final Logger LOG = LoggerFactory.getLogger(BlisterauftragServiceImpl.class); LOG.info("This is a, info log"); In the build.gradle file I have: logbackConfigurationFile = 'etc/war-logback.xml' Then in the folder etc, I have the file war-logback.xml <?xml version="1.0" encoding="UTF-8"?> <configuration debug="false" packagingData="true"> <property name="logDir" value="${app.home}/logs"/> <appender name="File" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${logDir}/app.log</file> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>DEBUG</level> </filter> ...

actuator /refresh is not being provided in SpringBoot 2.0.1

actuator /refresh is not being provided in SpringBoot 2.0.1 I am creating a demo project for Spring-Config-Server and Spring-Config-Client . Spring-Config-Server Spring-Config-Client In SpringBoot 1.5.6.RELEASE everything is working fine. SpringBoot 1.5.6.RELEASE However, when I am upgrading project to 2.0.1.RELEASE it does not provide the actuator endpoints. 2.0.1.RELEASE Actuator endpoint provided in 1.5.6.RELEASE Mapped "{[/refresh || /refresh.json],methods=[POST]}" Mapped "{[/dump || /dump.json],methods=[GET] Mapped "{[/heapdump || /heapdump.json],methods=[GET] Mapped "{[/autoconfig || /autoconfig.json],methods=[GET] Mapped "{[/resume || /resume.json],methods=[POST]}" Mapped "{[/configprops || /configprops.json],methods=[GET] Mapped "{[/features || /features.json],methods=[GET] Mapped "{[/loggers/{name:.*}],methods=[GET] Mapped "{[/restart || /restart.json],methods=[POST]}" ...and many more Actuator endpoint provided in...

How to allow anonymous users to access a certain function only using spring security

How to allow anonymous users to access a certain function only using spring security I'm using spring security in my project. I have a condition where the anonymous users should be able to read from database whereas only authorized users to add/update/delete. How can we mention such situation in the security-config? .antMatchers("/user/**").permitAll() permit all requires to be authenticated but I want even none authenticated users to access via the GET method. @RequestMapping("/user") @PreAuthorize("hasAuthority('USER')") public List<UserAll> getAll() { return userService.getAll(); } And here how do I mention that this function should be accessed by anonymous users too? you can change to hasAnyRole('USER', 'ANONYMOUS') – fg78nc Jul 2 at 4:18 hasAnyR...

Spring boot security login verify failed

Spring boot security login verify failed I want to verify the user's identity when he or she send a localhost:8080/submit request, so I added the following to SecurityConfig class: localhost:8080/submit @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/submit").access("hasRole('WORKER')") .antMatchers("/**").permitAll() .and() .formLogin() .loginPage("/login") .and() .logout() .logoutSuccessUrl("/") .and() .rememberMe() .tokenValiditySeconds(4838400) .key("workerKey"); } I wish the page could redirect to localhost:8080/login when I input localhost:8080/submit in the address field. My Worker entity has the role "WORKER": localhost:8080/login localhost:8080/submit @Override public Col...

Spring Boot Embedded Tomcat Performance

Spring Boot Embedded Tomcat Performance I am developing Microservices API for my application. I started with Spring Boot application. I created two artifacts - "business code with embedded tomcat" and "business code without embedded tomcat" . When I compare the performance results, I can see that the "non-embedded tomcat" (i.e. executing on standalone tomcat) gives good output because of native execution. So basically what is the difference between the embedded tomcat and the standalone tomcat regarding implementation? How the performance varies between two executions? How you did the tests? Could you explain? Thanks. – Rudge Oct 30 '16 at 18:46 @Rudge: Using Jmeter i simulated load on both scenarios. I am using camel in my business-code. At the end of transaction, i am printin...

Spring boot 2.0 custom converter being ignored

Spring boot 2.0 custom converter being ignored I've either completely miss-understood converters, or all the examples/blogs/docs I've found are assuming I've done a step... My understanding is that when I post a String , the converter will pick it up and give the Controller a POJO instead. String Controller The problem I have is the converter is never being called. The payload coming into the controller is a standard JSON API string { "data":{ "attributes":{ "created-date":null, }, "type":"steaks" } } The converter: @Slf4j @Configuration public class SteakConverter implements Converter<String, Steak> { @Override public Steak convert(String value) { log.info("converter value {}", value); return new Steak.builder().build(); } } The controller: @Slf4j @CrossOrigin @RestController public class SteakController { @PostMapping("/steaks") ...

IgnoreCase Finder Not Working with Spring Data Rest and Neo4J

IgnoreCase Finder Not Working with Spring Data Rest and Neo4J I am unable to coax Spring Data Neo4J (with Spring Data Rest) to ignore case with a finder method. Here's an example repository: @RepositoryRestResource public interface WidgetRepository extends PagingAndSortingRepository<Widget, Long> { Optional<Widget> findByNameIgnoreCase(String name); } This example will only find widgets by exact case even though I have the IgnoreCase keyword. I would appreciate advice on how to get a finder method to ignore case with Neo4J. Thanks! IgnoreCase 1 Answer 1 The case specific keywords are not implemented in Spring Data Neo4j yet. But it is possible to use regex in a derived query method. Define a regex finder method Optional<Widget> findByNameMatchesRegex(String name); Optional<Widget> findByNameMatchesRegex(String name); and use it like this widgetRepository.findByNameMa...

Using Pebble template engine with Spring Boot

Using Pebble template engine with Spring Boot So I'm trying to integrate Pebble templating engine to my spring boot application but I'm confused on how to implement this. So I've read through their site on how to implement it however it says for Spring MVC which I think not similar with Spring Boot. I also go to their github page then trying to add their maven dependency to POM.xml but I don't know if I will configure something or it is the same as Thymeleaf or Mustache that are autoconfigured. Link to their site: http://mitchellbosecke.com/pebble/ They provide an example on their github that you can try, to get an idea of how it works: github.com/PebbleTemplates/pebble-example-spring – Dovmo May 14 at 3:17 1 Answer 1 Add the starter depe...

How to load geojson from controller to google api with thymeleaf on Spring Boot?

How to load geojson from controller to google api with thymeleaf on Spring Boot? I´m trying to load or add my json (with GeoJson format) from my controller sending to HTML page by Thymeleaf to display on Google API MAP but i can´t do it (nothing happend, the map don´t load the geojson, there is no error on the Console, just nothing append. Just appear the Map but without any Mark of my Json .) On my Controller i generate my GeoJson with Json Objects, and then i send to the page with Model. This is my controller (i already validate my json on geojson.io and it works): @GetMapping("/test") public String Json( Model model) throws JSONException { JSONObject featureCollection = new JSONObject(); featureCollection.put("type", "FeatureCollection"); JSONObject properties = new JSONObject(); properties.put("name", "ESPG:4326"); JSONObject crs = new JSONObject(); crs.put("type", ...

How to catch exceptions from spring webflux controller?

How to catch exceptions from spring webflux controller? I am using javax validations in my controller with @Valid @RequestBody . When the server receives invalid data it throws error but I want to handle that error and return custom formatted error. I am unable to catch exception in my controller advice. I am using spring webFlux so can't use the bindingResult. How can I handle that exception? Here is my code @Valid @RequestBody Controller @PostMapping fun createPerson(@Valid @RequestBody resource: PersonResource): Mono<Person> { return personService.save(resource.toPerson()) } Resource data class PersonResource( val id: String?, @field:NotEmpty val name: String, ... } ErrorHandler @ControllerAdvice class ApiErrorHandler { @ExceptionHandler(IllegalArgumentException::class) fun handleValidationErrors(e: IllegalArgumentException): ResponseEntity<*> { // never reaches here } } Maybe this stackoverf...

Spring MVC Bean Validation --Data Type Validation

Spring MVC Bean Validation --Data Type Validation public class User { @NotNull(message="Age is Required") @Min(value = 18, message = "Age must be greater than or equal to 18") @Max(value = 150, message = "Age must be less than or equal to 150") private Integer age; } If the User enters "String Value" in age, I want to validate them and should provide error message "Age is Invalid". @OnlyNumber(message = "Age is Invalid") //Like This Which Annotation helps in validating this kind of Type Validation, Similarly if the use enters different type format instead of Date. How do we handle them and provide custom error message. you can create your own @OnlyNumber – Pravin Mar 24 '15 at 15:25 @OnlyNumber 1 Answer 1 ...

How compare date in spring mongo

How compare date in spring mongo I want to fetch result bw two date in Mongo and spring but it show parse exception. If I pass like date as string then no result. How compare date in spring and Mongo application. Aggregation.match(Criteria.where("date").gte(new Date("2018-06-24")).lte(new Date("2018-06-30"))); My collection: { "_id" : ObjectId("5b34a31a68f1b041aa13b82f"), "date" : ISODate("2018-06-28T00:00:00Z"), "eventname" : "app open" } 1 Answer 1 You can try something like: DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date startDate = df.parse("2018-06-24"); Date endDate = df.parse("2018-06-30"); Aggregation.match(Criteria.where("date").gte(startDate).lte(endDate)); Please see also Spring Data MongoDB Date Between and Spring data mongodb search for ...

Spring Boot Integration Tests override custom .properties file

Spring Boot Integration Tests override custom .properties file I am implementing integration tests and I have a problem with overriding custom properties that my application use. Integration test sample: @RunWith(SpringRunner.class) @SpringBootTest( classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT ) @TestPropertySource(locations = "classpath:test.properties") public abstract class BaseIntegrationTest { @Autowired protected TestRestTemplate restClient; The @TestPropertySource(locations = "classpath:test.properties") will override application.properties of my application with one that is provided @TestPropertySource(locations = "classpath:test.properties") application.properties However, my application use custom property file like this: @Configuration @PropertySource("classpath:fileProvider/custom.properties") @ConfigurationProperties(prefix = "com.sample.config") public class Sample...

LazyInitializationException with graphql-spring

LazyInitializationException with graphql-spring I am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY. I am using: https://github.com/graphql-java/graphql-spring-boot and https://github.com/graphql-java/graphql-java-tools for the integration. Here is an example: Entities: @Entity class Show { private Long id; private String name; @OneToMany private List<Competition> competition; } @Entity class Competition { private Long id; private String name; } Schema: type Show { id: ID! name: String! competitions: [Competition] } type Competition { id: ID! name: String } extend type Query { shows : [Show] } Resolver: @Component public class ShowResolver implements GraphQLQueryResolver { @Autowired private ShowRepository showRepository; public List...