FAQ Database Discussion Community


How to catch socket exceptions on TcpInboundGateway?

java,spring,sockets,spring-integration
I'm using TcpInboundGateway from spring-integration for a socket client. In TcpInboundGateway.doOnMessage() the stream is send via the socket connection. If an exception occurs eg because the socket is closed, there is just a spring error log "Failed to send reply". BUT I'd like to handle those socket errors explicit. How...

Spring service and Spring web app in one

spring,web-services,rest,spring-mvc,web
I'm making a Spring RESTFUL service and i wonder. Can I make a Spring RESTFUL service combine with a web app in a project. If it is possible, how to configure it? ....

Bean Creation exception, Injection of autowired dependency failed

java,spring,hibernate,spring-mvc
I'm using spring hibernate in my application. I used all the required jar files but still getting bean creation exception saying the following: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'voteController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mindtree.service.VoteService com.mindtree.controller.VoteController.voteService; nested exception is...

Difference between isAuthenticated and isFullyAuthenticated

spring,spring-security
I'm trying to learn spring security, and I have question: what is the difference between isAuthenticated and isFullyAuthenticated in spring security

Spring Resttemplate login fails

java,spring,spring-mvc,spring-security,csrf
after an update to spring-4.1.6 i'am not able to login to my rest services any more. I looked on different sides, but couldn't solve the problem... so i ask for help. Here is my my web.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- The definition of the...

Spring Data Rest executes query but returns 500 internal Server Error

java,spring,rest,spring-boot,spring-data-rest
I am using spring boot and spring data rest and I am facing a 500 internal server error, but no messages are displayed in console. I have the following: ProdutoVendaRepository.java public interface ProdutoVendaRepository extends PagingAndSortingRepository<ProdutoVenda, Integer> { @Query("SELECT new br.com.contoso.model.VendaPorFamilia(b.nome, SUM(i.valorMultiplicado)) FROM ProdutoVenda i JOIN i.produto o JOIN o.familia b...

How to get some utf-8 characters using hibernate and spring mvc in database?

java,spring,hibernate,spring-mvc,tomcat
I have developed small server program. When I extract tuple from database, some characters become ÇѱÛÃàÁ¦. I modify server.xml. However ÇѱÛÃàÁ¦ characters still appear. Help me. How can I get correct characters? This is my server.xml. (I use apache tomcat 7.0 server.) <?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache...

Spring Boot REST display id of parent only in a JSON response

json,spring,rest,spring-boot
Assume I have the following class: public class ChildEntity { ... @ManyToOne private ParentEntity parent; ... } Now, I have a REST endpoint that retrieves a child entity object from the database, thus my JSON is the following: {"id": "123", "name":"someName", "parent": { //parent fields here } ... } I...

Override Spring form error messages

java,spring,default,custom-errors
In Spring how do I override default form error massages ? I'm using a Validator and a properties file to add my own error messages, but how do I override messages that get printed on conversion/encoding error for example ? They seem to be generated automatically and I don't think...

Spring Core-Setter Injection

spring
I need help regarding mechanism of setter injection in Spring 3.0 Following is my code package com.common; class B{ public B(){} } class A{ B b; public A(){} public void setB(B b){ syso("I am in setter of B"); } } In XML,I have, <bean id="A" class="com.common.A"> <property name="b" ref="B" />...

Test XML content without using mock mvc

xml,spring,unit-testing,xpath,spring-test
I am using spring test with mockmvc and it works like a charm to test xml output! Example: ResultActions actions = this.mockMvc.perform(get("/entry/NX_P38398/overview.xml")); actions.andExpect(xpath("entry/overview/gene-name-list/gene-name[@type='recommended']").exists()); actions.andExpect(xpath("entry/overview/gene-name-list/gene-name[@type='recommended']").string("BRCA1")); I would like to take advantage of the same features to test an OutputStream without using mockmvc and controllers. Is it possible to use the same...

AbstractStatelessSessionBean missing from SpringFramework 4

java,spring,spring-4,spring2.x
I'm trying to update a big projekt from Spring 2 to Spring 4. On the deep end of the Beans hierarchy i found a class called CustomAbstractStatelessSessionBean and that extends the AbstractStatelessSessionBean class from org.springframework.ejb.support.AbstractStatelessSessionBean. The content of the class: public abstract class CustomAbstractStatelessSessionBean extends AbstractStatelessSessionBean{ /** * */ private...

Spring Cloud Config Globals

java,spring,spring-boot,spring-cloud
I have a scenario where I need to set some properties globally for several applications. Is there support for default or global configs in spring cloud config? Example: #default.properties setting=global_setting #myapp.properties something_else=app_setting #anotherapp.properties prop=different_app_setting Here I would want for "myapp" to have setting set. Any help would be greatly appreciated....

Why is my Spring Boot autowired JPA Repository failing JUnit test?

java,spring,junit,spring-boot
My JUnit test is failing with the following error: "java.lang.IllegalArgumentException: Could not find field [userRepository] of type [null] on target [[email protected]]" Here is the Test class: @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = App.class) @WebAppConfiguration @IntegrationTest public class UserResourceTest { @Autowired private UserRepository userRepository; private MockMvc restUserMockMvc; @Before public void setup() { UserResource userResource...

Using static href with query string in Thymeleaf

spring,apache,thymeleaf
I have a html prototype of an application, this prototype is on an Apache server, I used Apache Server Side Includes to include different pages for the template layouts. Now I'm adding labels Thymeleaf that prototype for use in an application with Spring. The problem is that many of the...

Spring @Autowired vs using 'new' keyword to create Object [closed]

java,spring,autowired
I am learning Spring and building some experiment application. I am confused on where to use @Autowired for creating the Object. I get the part that it promotes loose coupling and also does create a new Object Every time as opposed to what 'new' keyword do. But what should we...

How to apply HandlerInterceptor to Spring Boot Actuator endpoints?

java,spring,spring-mvc,spring-boot
I'm working with Java 8 and Spring 1.2.3 to build an application running inside a Tomcat 7 container. I do intercept every single call to my web application using a very simple HandlerInterceptor, that logs the overall time taken to create a response and the return code for every request....

Transaction error in Spring

java,spring,jpa
I have a project https://github.com/ivartanian/onlinecontrol in Spring MVC + JPA, initially worked with the Spring configuration through XML. Now I am trying to set up the project through JAVA Config (without XML). The project starts, but when I create a new user(entity User), an error transaction. But if I create...

How to set property using “tasklet ref” tag

spring,spring-batch
I have a tasklet ValidarSituacaoTasklet that has an property situacao. This tasklet is used in 2 steps in distinct values for situacao. I declared steps as like: and the bean: <bean id="validarSituacaoTasklet" class="my.package.tasklet.ValidarSituacaoTasklet" scope="step"> </bean> I have to pass 'situacao' to tasklet . I tried: <step id="validaSituacaoStep"> <tasklet ref="validarSituacaoTasklet ">...

viewResolver with more folders inside of WEB-INF/jsp is not working in spring

java,spring,jsp,spring-mvc
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- avoid '???' --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp"/> </bean> if i create other subfolders under jsp , for instance /WEB-INF/jsp/reports , /WEB-INF/jsp/insertions how should i configure now the viewResolver to can resolve these new sub folders??...

Jersey serializing null values to json : How to skip

java,json,spring,serialization,jersey-2.0
I am using Jersey 2.4 with spring. When I am returning a response from a method with an annotation @Produces(MediaType.APPLICATION_JSON) on it, it also serialize the null values to json. I don't want to serialize the fields that contains the null values. Is there any solution for the same?...

How to implement customer subdomain in Spring framework

spring,saas,multi-tenancy
In many of the SaaS web applications (ex, Atlassian JIRA), a user can have dedicated subdomain. For example, if my user name is helloworld, then after I log in to the web application, I am redirected to helloworld.atlassian.net How to implement this in Spring Framework? Do I have to have...

Is it possible to construct an object partially with Spring DI and partially with Jersey DI?

spring,dependency-injection,jersey,jersey-2.0,hk2
I have a class JerseyWebService which uses Jersey DI to inject dependency @Path("/baskets") public class JerseyWebService { @Inject ExternalApiServiceInterface api; ... } The dependency is specified in the binder public class CustomBinder extends AbstractBinder { @Override protected void configure() { bind(ExternalApiService.class).to(ExternalApiServiceInterface.class); ... } But the problem here is that ExternalApiService...

SEVERE: Exception starting filter springSecurityFilterChain

spring,spring-security
I am trying to write spring application, and I have this code, but when run this code using Tomcat 8, This error appeared, I don't know what is the root cause of error, please help Error: 01:15:02.681 [localhost-startStop-1] INFO o.s.web.context.ContextLoader - Root WebApplicationContext: initialization started 01:15:02.756 [localhost-startStop-1] DEBUG o.s.w.c.s.StandardServletEnvironment -...

Spring Data JPA user posts

java,spring,jpa,data
I have user login and profile view, I would like the users to have posts. Can someone guide me in the right direction? I have a user entity: @Entity @Table(name = "usr", indexes = { @Index(columnList = "email", unique = true) }) // using usr because in may conflict with...

Grails 2.4.4 spring security role doesn't apply to user

java,spring,grails,spring-security,spring-annotations
I have controller: class AdminController { def springSecurityService @Secured(['ROLE_ADMIN', 'ROLE_USER']) def index() { render "test"; } And user with role ROLE_ADMIN in the table: But, when I use: springSecurityService.getPrincipal().getAuthorities() There is only one role: ROLE_NO_ROLES Why? def loggedInUser = springSecurityService.currentUser; returns correct user. Config: ... grails.plugin.springsecurity.userLookup.userDomainClassName = '...' grails.plugin.springsecurity.userLookup.authorityJoinClassName =...

understand spring-ws, integration with spring-mvc and automatic generation of wsdl

java,spring,web-services,wsdl,spring-ws
i want learn spring-ws with automatic generation of wsdl files, i know that is a lot of tutorials, i tried them, my favorite example is : github projet It works well, but i tried to ajust that solution for my needs, and it doesnt work, i dont know why, and...

Spring data repository QueryDslPredicateExecutor without pageable count

spring,spring-data,spring-data-jpa,querydsl
I'm trying to create a spring data repository with a method to list a page of entities and a QueryDSL predicate using this: public interface EntityRespository extends JpaRepository<Entity, Integer>, QueryDslPredicateExecutor<Entity> { List<Entity> findAllBy(Predicate predicate, Pageable pageable); } As mentioned here Way to disable count query from PageRequest for getting total...

Sending images with AndroidAnnotations RestService

android,spring,android-annotations
What is the best way to send a file using the RestService? I have an image that I have to send to the server. The API expects the following POST data: image -> image I want to send description -> text title -> text Can I just send an object...

Importing Spring MVC Project Manually to Eclipse

java,eclipse,spring,spring-mvc
I have a little problem. I had googled for this problem and I haven't found any solution related. My problem is, my office internet using proxy that banned me to download zip file. I need Spring MVC Project template in Spring Tool Suite (STS). So I downloaded the zip file...

Cron expression must consist of 6 fields (found 1 in “#{systemEnvironment['db_cron']}”)

spring,groovy,cron,spring-el
I'm trying to set a cron Scheduled annotation as follows: @Scheduled(cron = "#{systemEnvironment['db_cron']}") def void schedule() { } Next set the environment variable as: export db_cron="0 19 21 * * *" However, I get the runtime error: Cron expression must consist of 6 fields (found 1 in "#{systemEnvironment['db_cron']}") What can...

JdbcTemplate Mockito ClassCastException

spring,mockito,classcastexception
I am trying to mock a method of the Spring framework's JdbcTemplate class. The method has the following signature: public <T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException {...} The mocking is being done as mentioned below: when(jdbcTemplate.queryForObject(anyString(), eq(String.class))).thenReturn("data"); However, this call throws the following exception java.lang.ClassCastException:...

shall I use Spring framework for a performance-critical proxy application? [closed]

java,spring,authentication,servlets
I've created a servlet (Tomcat) application which has these functions: It performs HTTP Basic Authentication. It connects to a user and role database. It works as "security facade" for some geodata servers behind It forwards requests after doing some authorization tests In case the response contains XML data, it performs...

Spring: Response time

java,spring,spring-ws
I have a SOAP webservice(spring ws)and need to save the response time of every request that I receive. I could create a servlet filter that measures time difference between HTTP Request and HTTP Response. But, I need to log the response time together with some values that I read from...

Spring RestTemplate dependency issue in Ear

spring,classpath,resttemplate,skinny-war
The organisation I work for has a few standalone services using Spring Boot and RestTemplate to communicate with each other and the main monolith (classical skinny War in Ear). However, we are running into problems with the classpath when we try to get RestTemplate running inside the Ear, but not...

Spring Boot extending CrudRepository

java,spring,hibernate,spring-boot,spring-data-jpa
I'm using Hibernate in a Spring Boot app. I'm making a new CrudRepository for all my Model objects, to do basic CRUD tasks. They look like this: @Repository public interface FoobarCrudRepo extends CrudRepository<Foobar, Long> { } But then I always need to do some additional things, like custom search queries...

Not Able to Resolve View Using Spring boot

spring,spring-mvc,spring-boot
I have put all jsp on classpath in views folder. Folder structure is : src/main/resources/ src/main/resources/static/ src/main/resources/static/views/ src/main/resources/static/views/*.jsp src/main/resources/static/views/*.png I am able to retrieve images file from static folder. But When It comes to jsp I am getting following error. While hitting url:http://localhost:9001/login There was an unexpected error (type=Not Found,...

AndroidAnnotations Rest view response data

android,spring,android-annotations
I am doing an API call using the Android Annotations RestService. The only problem is that I receive a JSON but I don't know how to see that JSON string. Is there a way I can view the response data so I can see the JSON string/content? I tried using...

Spring Mobile apps to be deployed in emulator

javascript,android,html5,spring,spring-mvc
I'm trying to develop an application based on Spring MVC for mobile device. Spring Mobile do provide such features to view our application in mobile browser. But how can I run/deploy the application in emulator since it's non-android based application? Also if can anybody tell me, how can I test...

Spring Security login with UserDetailsService and Java config

java,spring,spring-mvc,spring-security
I am trying to add login functionality with a database lookup with Spring Security, and I am really struggling. I want to look up the user by implementing the UserDetailsService interface. I have read a ton of documentation and Googled for hours, but I am still stuck. Most of the...

Is it possible to have “connection preparation” with Spring / JPA persistency

java,spring,jpa,spring-data
I have a Spring CrudRepository that is just an interface, and I have a persistence context class where I have defined my data source: @Configuration @EnableTransactionManagement public class PersistenceContext { @Bean(name="dataSource", destroyMethod = "close") public DataSource dataSource() throws SQLException { return ... public interface DataRepository extends CrudRepository<Data, Long> { Data...

Logging all network traffic in Spring mvc

java,spring,spring-mvc,logging,slf4j
I have spring mvc application using RequestBody and ResponseBody annotations. They are configured with MappingJackson2HttpMessageConverter. I also have slf4j set up. I would like to log all json as it comes in and out from my controller. I did extend MappingJackson2HttpMessageConverter @Override public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)...

Error handling with Spring CommandName

spring
when using Spring framework and binding a form on a commandName object to add let's say a person with the following fields. <form method="POST" action="addPerson.htm" commandName="person"> <input id="firstname" name="firstname"value="${person.firstname}"/> <br> <input id="name" name="name" value="${person.name}"/> <br> <input id="age" name="age" value="${person.age}"/> </form> On the server I've got the following code @RequestMapping(value="/addPerson", method={RequestMethod.POST})...

Spring 4 + JPA (Hibernate 4) + JTA transaction manager doesn't flush automatically

java,spring,hibernate,jpa,transactions
I am migrating an application from Spring 3.0.5 + JPA 2.0 to Spring 4 + JPA (Hibernate 4) I have followed the migration guide : https://github.com/spring-projects/spring-framework/wiki/Migrating-from-earlier-versions-of-the-spring-framework. The application is using a JTA transaction manager : a Jencks / GeronimoPlatformTransactionManager (because of transactions distributed on datasources and ESB). The Spring /...

How to access spring.application.instance_id programatically?

java,spring,spring-boot,spring-cloud,netflix-eureka
I have the following content in my "applicationname.yml" file of my Spring Boot/Cloud application. How can i get the value of spring.application.instance_id in my java code ? This "applicationname.yml" file is hosted in the 'Spring Cloud Config Server'. eureka: password: password client: registryFetchIntervalSeconds: 5 serviceUrl: defaultZone: ${vcap.services.${PREFIX:}eureka.credentials.uri:http://user:[email protected]:8761}/eureka/ instance: preferIpAddress: true...

Spring MVC - How to return simple String as JSON in Rest Controller

java,json,spring,rest,spring-mvc
My question is essentially a follow-up to this question. @RestController public class TestController { @RequestMapping("/getString") public String getString() { return "Hello World"; } } In the above, Spring would add "Hello World" into the response body. How can I return a String as a JSON response? I understand that I...

Write Spock test cases for Spring boot application

java,spring,groovy,spock
I am working on spring boot application. I have to write test cases for it. I haven't written test cases before, so someone suggested using spock framework for it. I explored spock and i think it is more related to groovy language. Can i write spock test cases for my...

setMaxTotal and setDefaultMaxPerRoute in HttpClient?

java,spring,connection-pooling,apache-httpclient-4.x,resttemplate
I am using RestTemplate with HttpComponentsClientHttpRequestFactory as shown below: private RestTemplate restTemplate = new RestTemplate(); // singleton class so only one instance public DataProcess() { restTemplate.setRequestFactory(clientHttpRequestFactory()); } private ClientHttpRequestFactory clientHttpRequestFactory() { HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000).setConnectTimeout(1000)...

Error while setting targetConnectionFactory in UserCredentialsConnectionFactoryAdapter Spring 4

java,spring,jms,spring-boot,spring-jms
We are receiving a compilation error in the following code, while trying to set the targetConnectionFactory. According to the example given in Spring 4 documentation for UserCredentialsConnectionFactoryAdapter, the setTargetConnectionFactory() method takes the object of JndiObjectFactoryBean as an argument. But, looks like the JndiObjectFactoryBean hasn't implemented the 'ConnectionFactory' interface, which is...

Hibernate - Setting null in entity collection is automatically persisted at transaction commit

java,spring,hibernate,dozer
Due to architecture requirements we can't use our Hibernate entities as DTOs, so we use Dozer to transform those entities to POJOs. Our typical service looks like this: @Transactional(readOnly=true) @Override public Task loadTask(int taskId){ TaskEntity taskE = taskDAO.load(taskId); if (taskE != null){ taskE.setAttachments(null) Task task = objectMapper.convert(taskE, Task.class); return task;...

GenericApplicationContext cannot be cast to WebApplicationContext : Spring Web Flow

java,spring,spring-mvc,classcastexception,spring-webflow-2
I'm trying to set up Spring Web Flow using only Java annotations in a Spring environment that also uses only Java annotations. However when I attempt to access my flow I get the following exception SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/forms] threw exception [Request processing failed;...

Sending text file to client through Spring MVC web application

java,spring,jsp,spring-mvc,servlets
After doing some research online on the subject I currently managed to get things working with this code: @RequestMapping(value = "/report040Generated", method = RequestMethod.GET) public String index(Model model, HttpServletResponse response, HttpServletRequest request) throws IOException { String myString = "Hello"; response.setContentType("text/plain"); response.setHeader("Content-Disposition","attachment;filename=myFile.txt"); ServletOutputStream out = response.getOutputStream(); out.println(myString); out.flush(); out.close(); return...

Logging operations in lightadmin

java,spring,logging,lightadmin
I have a Java web application which use Spring and Hibernate and I plan to use lightadmin to provide an administration interface. However, I found very little information about the logging part of lightadmin : if I have such an adminsitration interface, I would like that any operation made to...

Spring Security 4 with custom provider and handlers not caching the url before authentication

java,spring,spring-security
I've configured a custom authentication provider, a success handler and a failure handler in Spring Security (v4.0.1). When using the default ones, after displaying the login page, the user was redirected to the previously requested url. However, I lost that behaviour when implementing my own ones, so I'm trying to...

Spring Data Rest: Return Resources of User

java,spring,spring-security,spring-data-rest
I'm creating a simple CRUD-App (a shoppinglist) with Spring Boot and Spring Data Rest. I have a resource: ShoppingItem. Is there an easy way to only return the resources which belong to the user who send the request? (Multiple User support) So a User only get his own ShoppingItems and...

how to Autowire the applicationContext early?

spring,spring-boot
Using spring boot, how to Autowire the applicationContext ? It must be autowired before the call of endpoint() @Configuration @EnableTransactionManagement @EnableAutoConfiguration @ComponentScan({"com.dev.core.services", "com.dev.core.wservices"}) @ImportResource({ "classpath:META-INF/cxf/cxf.xml" }) public class ContextConfig extends SpringBootServletInitializer { @Autowired private static ApplicationContext applicationContext; @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return...

Cannot create bean when start the application

java,spring,javabeans,sftp,job-scheduling
I am facing some issue while creating the bean it gives error. Can someone please assist me. I will retrieve the files from sftp resource and will read those file with a spring task scheduler job. App-Config.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task"...

Logging with log4j2 in Spring Boot app

java,spring,maven,logging,log4j2
I am trying to learn Spring Boot. But I completely mess up with a loggers dependencies. I have a simple pom: <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Logging --> <dependency>...

spring- How to invoke model attribute methods as done by spring in application specific class

java,spring
I have an issue, model attributes are not retained if any exceptions raised in jsp since they are request scope. How to resolve the above issue? As my initial thought, spring will invoke the model attribute methods before controller method gets executed, similarly if i could invoke the model attribute...

Can't Override Equals method on Java when calling contains

java,spring,hibernate
I have the following funtion that checks if a List of codigos contains a single codigos object: if (!concorrente.getJcodigoses().contains(cod)) { return "redirect:" + referrer; } I read that i need to Override the equals method like so: @Override public boolean equals(Object object) { boolean isEqual= false; if (object != null...

Use $or operator in @Query annotation in spring data mongodb repository

java,spring,mongodb,spring-data-mongodb
I am using spring-data-mongodb. I want to use $or operator in my repository. This is my query: @Query("{'type':?0}") List<Doc> findByType(String type, Pageable pageable); How do use $or in @Query so as it can match either type or name and fetch me a document. Please help....

DIfference between @Autowired and New Keword and Application context to create a object

java,spring
Please any one tell me the difference between @Autowired CustomerService cService; And CustomerService cService=new CustomerService(); And private static ApplicationContext applicationContext; DefaultValueBean defaultValueBean = (DefaultValueBean) applicationContext.getBean("defaultValue"); ...

Using Spring Security, what's the right way to manage authorization to query responses?

java,spring,spring-security
Using Spring Security (v. 3.2.5), what's the right way to manage authorization to query responses? I have configured Spring Security to regulate access to different parts of the system based on user roles. But in many places, the principal is querying for data (e.g. looking up previously persisted details "owned"...

Why my predcondition is not serialized?

java,spring,liquibase
I have a problem. I autogenerate my changelog. I try to add some precondition on a changeset. But when i serialize mys changeset, the precondition rule doesn't appear in my XML changelog. I see only the addcolumn section Here how i generate my changeset: final ChangeSet changeset = new CustomChangeSet("myId",...

How to avoid Hibernate Validator ConstraintDeclarationException?

java,spring,hibernate,validation,hibernate-validator
I have my WebService based on Spring 4, and I am using Hibernate Validator (beyond MethodValidationPostProcessor). My problem is that I have my ClientService interface, and its implementation. So I put Bean Validation constraints on the implementation and it forces me to put that constraints on the interface (throwing ConstraintDeclarationException)...

How to Fetch Data using Spring Data

spring,jpa,spring-boot,spring-data
Hey i want to create a repository extending JpaRepository and fetch result without writing actual query, In my example i have 2 tables Book and Author mapped by many to many relationship, suppose i want to fetch list of books by a particular author_id, since in my book entity, i...

Is it possible to permit all users except anonymous one?

java,spring,spring-security
How can I permit access to URL such that only anonymous one can't get the page? I'm using Spring security. <intercept-url pattern="/pattern/page.html" access="__WHAT_SHOULD_BE_HERE__"/> ...

Spring Webservices gives 406 error

java,spring,web-services,spring-mvc
I have created a simple Spring with webservices example but when I try to get the response I am getting error as : HTTP Status 406 - The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers. This...

Can't deserialize json response from Flurry API

java,json,spring,flurry
I am trying to read in some stats using Flurry's REST API in to my Spring application. However my objects are coming back with null values for all fields. I think this is because the JSON response prepends @ symbols to the non-array fields in the response. The responses I'm...

How do I combine Facet and FilterQueries using Spring data Solr?

spring,solr,filtering,facet
Is it possible to combine a facet and field query in spring data solr? Something that would build a query like this: > http://localhost:8983/solr/myCore/select?q=lastName%3AHarris*&fq=filterQueryField%3Ared&wt=json&indent=true&facet=true&facet.field=state In other words, how do I add FilterParameters to a SimpleFacetQuery? Any/all replies welcome, thanks in advance, -- Griff...

spring data null arguments

spring,spring-data,spring-data-jpa
I am trying to implement the service for a rest controller that takes optional filter parameters like first name, last name, age, etc. I want to use a JpaRepository method like below. The problem is, if a parameter is null then no records are found. When a argument is null...

Spring, Java : Passing Generic object List as return type

java,spring,spring-mvc,generics,casting
I am working on a Spring-MVC application in which depending upon the mode set by the user, I have to return a List of either Object1 or Object2. Ideally, I can create two controller methods and send the List appropriately, but I would like to know is there any way,...

Spring Batch : custom ItemReader

java,spring,spring-batch
I have a Spring Batch project with a simple custom reader and writer. When i run the code i end up with an endeless loop printing the first item "item 1". What am i doing wrong? Here is my code: Reader.java public class Reader implements ItemReader<SimpleItem> { public SimpleItem read()...

Spring OAuth2 not giving refresh token

java,spring,spring-security,spring-security-oauth2
I am running a OAuth Provider using Spring and "password" grant type. Running this (provider is on port 8080): curl -u "app:appclientsecret" "http://localhost:8080/oauth/token" --data "grant_type=password&username=marissa&password=koala" returns: {"access_token":"56da4d2b-7e66-483e-b88d-c1a58ee5a453","token_type":"bearer","expires_in":43199,"scope":"read"} For some reason there is no refresh token. I know according to the spec, the refresh token is optional; is there some way...

@RestController throws HTTP Status 406

java,spring,rest,maven
I am working on a basic Hello World program using Spring and Restful webservices. But when I try to call my service I am getting below error message: HTTP Status 406 - description - The resource identified by this request is only capable of generating responses with characteristics not acceptable...

Spring-MVC, Hibernate : Creating DTO objects from Domain objects

java,spring,hibernate,spring-mvc,dto
I am working on a Spring-MVC application in which I am trying to search for List of GroupNotes in database. The mapping in my project is GroupCanvas has one-to-many mapping with GroupSection and GroupSection has one-to-many mapping with GroupNotes. Because of these mappings, I was getting LazyInitializationException. As suggested on...

Checking for multiple child constraint violations in Hibernate/JPA

spring,hibernate,jpa
TL;DR: Is it possible to perform nested transactions in Hibernate that use SavePoints to rollback to specific states? So I am attempting to persist a parent entity with a OneToMany mapping to child entities. This is working fine. During this persistence, I would like to catch and log ALL constraint...

Send Mail using Spring MVC

spring,spring-mvc,spring-integration
I have a custom MailDto object in which I set the to,cc, bCc field and send it using RestTemplate to Spring MVC controller as below @RequestMapping(value = "/SendMail" ) public ResponseEntity<String> SendMail( @RequestBody MailMessageDto mailDto) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException From the controller I invoke the Gateway (Spring integration). The...

Spring Boot - How to set the default schema for PostgreSQL?

java,spring,hibernate,postgresql
What I am currently doing in my application.properties file is: spring.datasource.url=jdbc:postgresql://localhost:5432/myDB?currentSchema=mySchema Isn't there another property for this? Since it looks hacky and according to a post (still finding the link sorry, will update later), it is only applicable to PostgreSQL 9.4....

how to autowire in spring for test classes?

spring,testing
I am making some test for my classes in spring. I am making the mockups and all, but I want to include certain services, I was wondering if there is any annotation to make this @autowire for test cases. I checked for the @contextConfiguration but I dont know if is...

Dynamic fields thymeleaf list iteration

spring,spring-mvc,spring-boot,thymeleaf
I'm getting a really weird error ! while iterating on list thymeleaf identified index as a property of my bean and not an index value ! <div th:each="phoneStat : *{phones}"> <select th:field="*{phones[__${phoneStat.index}__].variety}" > <option> </option> </select> <div class=" input-field col s4" > <input th:field="*{phones[__${phoneStat.index}__].number}" th:id="${'phonenumber-'+ phones[__${phoneStat.index}__]}" type="text" class="validate" /> <label...

How do I display JSON response in below mentioned format using Spring?

java,json,spring,response
public class Country { @Column(name = "name") private String name; @Id @Column(name = "code") private String Code; //Getters & Setters ... } current response : [{"name":"Andorra","code":"AD"},{"name":"United Arab Emirates","code":"AE"}] Expected response : [ { "countries" : [{"name":"Andorra","code":"AD"},{"name":"United Arab Emirates","code":"AE"}], "status" : "ok", "message":"success", etc..etc...}] instead of status and message, it could...

Spring Security OAuth2 - Add parameter to Authorization URL

spring,spring-security,oauth-2.0,spring-security-oauth2
I am using Spring Security with OAuth2 for authentication/authorization using following project. http://projects.spring.io/spring-security-oauth/ I have a requirement to add parameter to OAuth2 authorization url. I am not sure how should I add it to AuthorizationCodeResourceDetails bean? The problem is I want to start the user journey by login or registration...

Spring batch FileItemWriter not creating file at correct path

java,linux,spring,websphere,spring-batch
I have a spring batch service containing a FileItemReader,FileItemProcessor and FileItemWriter.When creating the FileItemWriter I have to set the Resource that will be my output file. I am running the batch service on websphere on a Linux machine.The problem is if I set the resource as new FileSystemResource(new File("opt\temp1\myFile.txt")), the...

spring.xml not packaged in executable jar

java,spring,maven,executable-jar
I created a simple java application using maven, spring and used log4j for logging. Following are the files. public class TestCrawler { public static final String SPRING_CONFIGURATION_FILE = "spring.xml"; private static final String INITIAL_URL = "http://yahoo.com/"; private static final String SPIDER_BEAN = "spider"; public static void main(String[] args) { System.out.println();...

Returning Map> as a JSON from Spring. Map key elements do not parse into JSON format

json,spring,dictionary,jackson
I have a question connected to returning Map<T, List<V>> as a JSON response. I have a spring server which returns JSON objects, but now I'm exploring problem with returning Map in this format. I want return a Map<T, List<V>> from my server as a JSON and display it in the...

Spring Boot - How to kill current Spring Security session?

spring,spring-security,spring-boot
Currently I know that my setup is working because I was able to login properly using the basic HTTP authentication. I used these properties: security.basic.enabled=true security.user.name=user security.user.password=1qaz2wsx security.user.role=USER However, I want to relogin again. I tried clearing cookies (I assumed it was saved there), I checked my local/session storage and...

How can implement long running process in spring hibernate?

java,spring,hibernate
as we know the struts interceptor execute and wait will take care of long running process by not getting the request to timeout and destroy it sends wait and at last the desired response i want to implement the same for long running process in spring and hibernate. Thanks....

cleanest way to create multiple beans of the same class with different properties

java,spring,dependency-injection,spring-bean,spring-properties
Say I have this properties file: students.bill.firstname=John students.bill.lastname=Doe students.bill.age=20 students.jim.firstname=Jim students.jim.lastname=Wright students.jim.age=21 . . . I want an xml bean that contains a map of students that has their firstname as the key. Object example: Student.java public class Student { String firstname; String lastname; Integer age; } Classroom.java public class...

Spring Portlet Jquery Ajax post json dateTime conversion error

jquery,json,spring,jodatime,spring-portlet-mvc
This question is related to: Spring Portlet Jquery Ajax post to Controller I'm submitting a form from Jquery Ajax to Spring Portlet MVC Controller. The issue is startTimestamp and endTimestamp are dateTime in the POJO. The json sends it as a string and the conversion is not happeinng. The error...

Spring app throwing java.sql.SQLRecoverableException: Closed Connection

spring
Long running Stand-alone Spring app on a weekly schedule (not on any App server) usually takes few days to complete but failed due to java.net.SocketException: Broken pipe. Here's stack trace: Caused by: java.sql.SQLRecoverableException: IO Error: Broken pipe at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:876) at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1153) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1275) at...

Default Spring bean when profile is not present

java,spring,spring-mvc,spring-profiles
I'm using Spring MVC controllers, and I'd like to make some extra request-mapped methods available during development. I can do this using Spring profiles: @Controller @Profile("!dev") public class DefaultController { } @Controller @Profile("dev") public class DevController extends DefaultController { } But ideally, I'd rather not pollute the production classes' code...

How to conditionally invoke spring validators

java,spring,validation
I have a model like below. Existing code already has validations on individual properties. Now I have a requirement to ignore existing validations on billing_country and address if buyer.method is foo. I was thinking I could have a custom validator at buyer level, check for method and invoke validations only...

Trouble with Login using Spring Boot and JDBC Security

spring,spring-security,spring-boot
My build.gradle file: task wrapper(type: Wrapper) { gradleVersion = '2.4' } buildscript { repositories { mavenCentral() maven { url "http://repo.spring.io/release" } } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.3.RELEASE") } } apply plugin: 'java' apply plugin: 'spring-boot' repositories { mavenCentral() maven { url "http://repo.spring.io/release" } } dependencies { compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-jdbc")...

Hibernate : Stale state exception

java,spring,hibernate,spring-mvc,transactions
I am working on a Spring-MVC application in which I am trying to delete an object from the database. Some days back, this error all of a sudden started, and now I am unable to delete. I checked on net, but I cannot find what am I doing wrong and...

Hibernate Primary Key annotation returns null value

sql,spring,hibernate
i am following http://viralpatel.net/blogs/hibernate-one-to-one-mapping-tutorial-using-annotation/ for learning primary key annotation. I have two classes @Id @Column @GeneratedValue(strategy=GenerationType.AUTO) private int id; private String firstName; private String lastName; private String email; private String password; private String profession; @OneToOne(mappedBy="user" , cascade=CascadeType.ALL) private Profile profile; and my profile class @Id @Column @GeneratedValue(strategy = GenerationType.AUTO) private...

Cannot import correctly maven properties with PropertiesFactoryBean and PropertyPlaceholderConfigurer in spring

spring,maven,datasource,placeholder,jrebel
I'm facing problems with a jdbc dynamic properties configurer. I try to explain what exactly the problem is. When I do mvn clean install and right after I deploy the applications in my server (Weblogic 10.3.3), everything is correct, and all the applications work fine. But, every morning, when I...

Is spring transaction is only working in entering service method?

mysql,spring,transactions,spring-transactions
I have read many stackoverflow's pages about spring transaction. My spring transaction config is <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> My service is like this. @Service public class TestServiceImpl implements TestService { @Override public void testRollback() { testRollbackSecondLevel(); } @Transactional @Override public void testRollbackSecondLevel() { // any update sql in here carCostService.testUpdate(); throw...

Get the currently used protocol name from HttpServletRequest?

java,spring,tomcat
I'm constructing a new URL in a Spring MVC controller, to be passed back to the client. Currently I'm trying this: // httpRequest is the current HttpServletRequest new URL(httpRequest.getProtocol(), httpRequest.getServerName(), httpRequest.getServerPort(), httpRequest.getContextPath().concat("/foo/bar.html")); Problem is that httpRequest.getProtocol() gives me "HTTP/1.1" instead of just "HTTP". I can trim it but wondered if...

Spring: @NestedConfigurationProperty List in @ConfigurationProperties

spring,properties,configuration,spring-boot
Hi I am trying to get the following configuration up and running. @ConfigurationProperties(prefix="my") public class Config { @NestedConfigurationProperty private List<ServerConfiguration> servers = new ArrayList<ServerConfiguration>(); public List<ServerConfiguration> getServers() { return this.servers; } } @ConfigurationProperties(prefix = "server") public class ServerConfiguration { private String name; private String description; } So, I want to...