Adding Authentication Token to Spring Data Neo4j Rest - spring

How do I add the authentication token created by Neo4j Server to Spring Neo4j Rest configuration
context.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<import resource="spring-data-context.xml" />
<bean id="graphDatabaseService"
class="org.springframework.data.neo4j.rest.SpringRestGraphDatabase">
<constructor-arg index="0" value="http://localhost:7474/db/data" />
</bean>
</beans>

As per the SpringRestGraphDatabase class, there are two more parameters which can be passed into Constructor which are username and password.
Here is how you should configure it.
<bean id="graphDatabaseService" class="org.springframework.data.neo4j.rest.SpringRestGraphDatabase">
<constructor-arg value="http://localhost:7474/db/data"/>
<constructor-arg name="user" value="neo4j"/>
<constructor-arg name="password" value="******"/>
</bean>

Ended using Jersey Client's HttpBasicAuthFilter
Your parameters should be something like:
public static final String DATABASE_ENDPOINT = "http://localhost:7474/db/data";
public static final String DATABASE_USERNAME = "neo4j";
public static final String DATABASE_PASSWORD = "3c0a0a6ea1sdsdsdsdsdsdsdsdf2a94d";
private String callRest(String query) {
final String cypherUrl = ENDPOINT + "/cypher";
Client c = Client.create();
c.addFilter(new HTTPBasicAuthFilter(USERNAME, PASSWORD));
WebResource resource = c.resource(cypherUrl);
String request = "{\"query\":\"" + query + "\"}";
ClientResponse response = resource.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON).entity(request)
.post(ClientResponse.class);
String object = response.getEntity(String.class);
response.close();
return object;
}
Latest Jersey client can be found by adding this to your mvn pom if its not already in your dependency tree.
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.3</version>
</dependency>

Related

Configure Gson in Spring before using GsonHttpMessageConverter

How to configure Gson before constructing a GsonHttpMessageConverter?
I need to use #Expose and specify Date format.
(New Method) Using Java Config
Extend WebMvcConfigurerAdapter or if you need more control use WebMvcConfigurationSupport.
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(createGsonHttpMessageConverter());
super.configureMessageConverters(converters);
}
private GsonHttpMessageConverter createGsonHttpMessageConverter() {
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
.create();
GsonHttpMessageConverter gsonConverter = new GsonHttpMessageConverter();
gsonConverter.setGson(gson);
return gsonConverter;
}
}
You can read more on how to customize provided configuration.
(Old Method) Using XML configuration
In DispatcherServlet context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="gsonBuilder" class="com.google.gson.GsonBuilder">
<property name="dateFormat" value="yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'" />
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="gsonBuilder" />
<property name="targetMethod" value="excludeFieldsWithoutExposeAnnotation" />
</bean>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.GsonHttpMessageConverter">
<property name="gson">
<bean class="com.google.gson.Gson" factory-bean="gsonBuilder" factory-method="create" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>

406 Not Acceptable Spring Rest WS

I am writing a spring rest WS to return response as XML. Below are my classes and pom file.
I am getting Http 406 Error on executing the service as below:
http://localhost:8080/SpringRestExample/rest/emp/dummy.xml
However, I am getting the JSON response back when executing
http://localhost:8080/SpringRestExample/rest/emp/dummy.json
Please advise
pom.xml
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson.version}</version>
</dependency>
EmployeeController:
#RequestMapping(value = "/rest/emp/dummy", method = RequestMethod.GET,produces={"application/xml"})
public #ResponseBody Employee getDummyEmployeeXML() {
logger.info("Start getDummyEmployee");
Employee emp = new Employee();
emp.setId(9999);
emp.setName("Dummy");
emp.setCreatedDate(new Date());
empData.put(9999, emp);
return emp;
}
app-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.skanda.spring.controller" />
<beans:bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<beans:property name="favorPathExtension" value="true" />
<beans:property name="favorParameter" value="true" />
<beans:property name="parameterName" value="mediaType" />
<beans:property name="ignoreAcceptHeader" value="true"/>
<beans:property name="useJaf" value="false"/>
<beans:property name="defaultContentType" value="application/json" />
<beans:property name="mediaTypes">
<beans:map>
<beans:entry key="json" value="application/json" />
<beans:entry key="xml" value="application/xml" />
</beans:map>
</beans:property>
</beans:bean>
Employee:
public class Employee implements Serializable{
private static final long serialVersionUID = -7788619177798333712L;
private int id;
private String name;
private Date createdDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#JsonSerialize(using=DateSerializer.class)
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
406 means that the server is not able to produce a response in the content type asked by the client. Check the Accept header of your HTTP request, and make sure it contains application/xml.
Maybe it contains text/xml, and that's what you should use in the producesattribute of your #RequestMappingannotation. BTW, you should use the constants in org.springframework.http.MediaType instead of hard-coding the string as you're doing.
for any type of xml conversion you need to add #XmlRootElement annotation on top of Model class. i have done the changes and run the above program and got the result.Just add #XmlRootElement above Employee class and you are done.

Creating a repository instance in Spring Data

I'm new to Spring Data and to Spring in general, so don't be hard on me.
I can't find a way to instantiate a repository. I read the documentation:
http://docs.spring.io/spring-data/data-solr/docs/1.0.0.RC1/reference/htmlsingle/#repositories.create-instances
It describes different ways of declaring repositories (xml, filters, etc), but doesn't say how I can get an instance of it in my code.
Here is my configuration xml file:
<?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:solr="http://www.springframework.org/schema/data/solr"
xsi:schemaLocation="http://www.springframework.org/schema/data/solr http://www.springframework.org/schema/data/solr/spring-solr-1.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<solr:repositories base-package="spring" />
<solr:solr-server id="solrServer" url="http://localhost:8983/solr" />
<bean id="taskRepo" class="spring.SolrTaskRepository">
</bean>
<bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate">
<constructor-arg index="0" ref="solrServer"/>
</bean>
</beans>
And SolrTaskRepository:
public interface SolrTaskRepository<T, ID extends Serializable> extends SolrCrudRepository<T, ID> {
Page<T> findByOrigin(String origin, Pageable page);
}
Could someone help me out?
If you want to use the repo(or any spring bean) somewhere out of the context:
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
MyRepo obj = (MyRepo) context.getBean("myRepo");
If you use the repo in some other bean managed by spring(some service) you can autowire it
#Autowire
private MyRepo myRepo;// + setter
or inject it in the context:
<bean id="someService" class="com.org.core.SomeService">
<property name="myRepo" ref="myRepo" />
</bean>
For both ways you need the bean defined in the context:
<bean id="myRepo" class="com.org.core.MyRepo">
</bean>
Example context file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="myRepo" class="com.org.core.MyRepo">
</bean>
</beans>
IF you load the context with ClassPathXmlApplicationContext you need the file in the classpath.

Spring mvc RestTemplate postForObject doesn't send parameter to REST API

I have a REST API. I'm making a client.
I configured spring security to authentication by my rest service.
My REST API controller
#RequestMapping(value = "/login", method = RequestMethod.POST, headers="content-type=application/json")
public #ResponseBody
UserDetails loginUser(WebRequest request)
throws LoginOrPasswordException {
logger.info("login user");
logger.info(request);
String username = request.getParameter("username");
logger.info(username);
UserDetails uDetails = userRepository.login(username);
System.out.println(uDetails.getPassword());
return uDetails;
}
Application context of API
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.zayats." />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
<!-- Http Json MessageConverter -->
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
<import resource="jdbc-config.xml" />
Next is client method with restTemplate
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> httpEntity = new HttpEntity<Object>(params, requestHeaders);
logger.info("Create map and doing request.");
UserDetails matchingUser = restTemplate.postForObject(
"http://localhost:8080/ApiFamilyShoplist/user/login", httpEntity,
UserDetails.class);
Rest Template config
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
</list>
</property>
</bean>
When I call my API with postForObject in controller of API doesn't receive any parameters.
Please, give me some advice how to make it to send data to API.
Thanks.
You need to have another parameter in your method to accept the string parameter and annotate it with #RequestBody (inside the method signature):
#ResponseBody
#Consumes("text/plain")
public UserDetails loginUser(WebRequest request, #RequestBody String userName)
Also, if you're passing a string, I suggest to add a simple http string converter to the converters of the rest template and annotate the server method with #Consumes(text/plain). This way you'll get it as a simple string.

Spring - using static final fields (constants) for bean initialization

is it possible to define a bean with the use of static final fields of CoreProtocolPNames class like this:
<bean id="httpParamBean" class="org.apache.http.params.HttpProtocolParamBean">
<constructor-arg ref="httpParams"/>
<property name="httpElementCharset" value="CoreProtocolPNames.HTTP_ELEMENT_CHARSET" />
<property name="version" value="CoreProtocolPNames.PROTOCOL_VERSION">
</bean>
public interface CoreProtocolPNames {
public static final String PROTOCOL_VERSION = "http.protocol.version";
public static final String HTTP_ELEMENT_CHARSET = "http.protocol.element-charset";
}
If it is possible, what is the best way of doing this ?
Something like this (Spring 2.5)
<bean id="foo" class="Bar">
<property name="myValue">
<util:constant static-field="java.lang.Integer.MAX_VALUE"/>
</property>
</bean>
Where util namespace is from xmlns:util="http://www.springframework.org/schema/util"
But for Spring 3, it would be cleaner to use the #Value annotation and the expression language. Which looks like this:
public class Bar {
#Value("T(java.lang.Integer).MAX_VALUE")
private Integer myValue;
}
Or, as an alternative, using Spring EL directly in XML:
<bean id="foo1" class="Foo" p:someOrgValue="#{T(org.example.Bar).myValue}"/>
This has the additional advantage of working with namespace configuration:
<tx:annotation-driven order="#{T(org.example.Bar).myValue}"/>
don't forget to specify the schema location..
<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
</beans>
One more example to add for the instance above. This is how you can use a static constant in a bean using Spring.
<bean id="foo1" class="Foo">
<property name="someOrgValue">
<util:constant static-field="org.example.Bar.myValue"/>
</property>
</bean>
package org.example;
public class Bar {
public static String myValue = "SOME_CONSTANT";
}
package someorg.example;
public class Foo {
String someOrgValue;
foo(String value){
this.someOrgValue = value;
}
}
<util:constant id="MANAGER"
static-field="EmployeeDTO.MANAGER" />
<util:constant id="DIRECTOR"
static-field="EmployeeDTO.DIRECTOR" />
<!-- Use the static final bean constants here -->
<bean name="employeeTypeWrapper" class="ClassName">
<property name="manager" ref="MANAGER" />
<property name="director" ref="DIRECTOR" />
</bean>

Resources