I am new to Queues. I had setup my queue in JBOSS 5.1 EAP and now while trying to inject in tho the queue am getting a ClassCastException (in lookup of JNDI), I use flex on my front end and use Spring framework for flex. When injected into the queue using quartz job it runs well and good. The quartz job is a separate project and has nothing to do with flex and spring.
I read over some where that this could be a jar issue, I had JMS jars in my spring and i tried removing, replacing all types of jars, no luck.
// Step 1. Create an initial context to perform the JNDI lookup.
InputStream in = this.getClass().getResourceAsStream(
"/clv2.properties");
Properties configProp = new Properties();
configProp.load(in);
IpAddress = configProp.getProperty("ipaddress");
port = configProp.getProperty("port");
inQueueName = configProp.getProperty("inQueueName");
Properties props = new Properties();
props.setProperty("java.naming.factory.initial",
"org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.factory.url.pkgs",
"org.jboss.naming");
// props.setProperty("java.naming.provider.url", host + ":" + port);
props.setProperty("java.naming.provider.url", "localhost" + ":"
+ 1099);
// props.setProperty("java.naming.provider.url",
// "16.181.233.61:1399");
initialContext = new InitialContext(props);
// Step 3. Perform a lookup on the Connection Factory
QueueConnectionFactory cf = (QueueConnectionFactory) initialContext
.lookup("/ConnectionFactory");
Queue queue = (Queue) initialContext
.lookup(/* "/queue/CLVInboundQueue" */inQueueName);
// Step 4.Create a JMS Connection
connection = (QueueConnection) cf.createConnection();
// Step 5. Create a JMS Session
session = (QueueSession) connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
// Step 6. Create a JMS Message Producer
// MessageProducer producer = session.createProducer(queue);
QueueSender queueSender = session.createSender(queue);
TextMessage textMessage = session.createTextMessage(message);
textMessage.setLongProperty("Rejected_Message_ID",
rejected_Message_Id);
/*
* BufferedReader reader = new BufferedReader(new
* InputStreamReader(ClassLoader.class.getResourceAsStream(file)));
* StringBuilder sb = new StringBuilder(); String line = null;
*
*
* while ((line = reader.readLine()) != null) { sb.append(line +
* "\n"); } String announcementmsg = sb.toString();
*/
commonlogger.info(textMessage);
connection.start();
// producer.send(session.createTextMessage(announcementmsg));
queueSender.send(textMessage);
This is my piece of coding to inject into the queue. I get the Exception in "//Step 3. Perform a lookup on the Connection Factory" and this is my stack trace.
09:22:20,730 ERROR [STDERR] java.lang.ClassCastException: org.jboss.jms.client.JBossConnectionFactory cannot be cast to javax.jms.QueueConnectionFactory
09:22:20,731 ERROR [STDERR] at com.cat.clv.util.InQueueReinjectMessage.sendMessage(InQueueReinjectMessage.java:63)
09:22:20,731 ERROR [STDERR] at com.cat.clv.util.RejectedMessageReinject.reProcessedMessage(RejectedMessageReinject.java:65)
09:22:20,731 ERROR [STDERR] at com.cat.clv.service.ReinjectMessagesServiceImpl.reinjectRejectedMessages(ReinjectMessagesServiceImpl.java:106)
09:22:20,731 ERROR [STDERR] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
09:22:20,731 ERROR [STDERR] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
09:22:20,732 ERROR [STDERR] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
09:22:20,732 ERROR [STDERR] at java.lang.reflect.Method.invoke(Unknown Source)
09:22:20,732 ERROR [STDERR] at flex.messaging.services.remoting.adapters.JavaAdapter.invoke(JavaAdapter.java:421)
09:22:20,732 ERROR [STDERR] at flex.messaging.services.RemotingService.serviceMessage(RemotingService.java:183)
09:22:20,732 ERROR [STDERR] at flex.messaging.MessageBroker.routeMessageToService(MessageBroker.java:1503)
If you look at the source of JBossConnectionFactory then you will see it implements QueueConnectionFactory.
So this class cast exception can be because of :
Erroneous installation of JBoss
Different jms.jar in client and server
Can you first try out option 2 and see if it works, if not can you check if the examples work in your jboss installation.
Getting classCast Exception at lookup :
classcastexception: weblogic.jms.client.JMSconnectionFactory cannot be cast to javax.jms.QueueConnectionFactory
initialContext = new InitialContext(props);
// Step 3. Perform a lookup on the Connection Factory
QueueConnectionFactory cf = (QueueConnectionFactory) initialContext
.lookup("/ConnectionFactory");
Queue queue = (Queue) initialContext
.lookup(/* "/queue/CLVInboundQueue" */inQueueName);
// Step 4.Create a JMS Connection
connection = (QueueConnection) cf.createConnection();
// Step 5. Create a JMS Session
session = (QueueSession) connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
// Step 6. Create a JMS Message Producer
// MessageProducer producer = session.createProducer(queue);
QueueSender queueSender = session.createSender(queue);
TextMessage textMessage = session.createTextMessage(message);
textMessage.setLongProperty("Rejected_Message_ID",
rejected_Message_Id);
/*
* BufferedReader reader = new BufferedReader(new
* InputStreamReader(ClassLoader.class.getResourceAsStream(file)));
* StringBuilder sb = new StringBuilder(); String line = null;
*
*
* while ((line = reader.readLine()) != null) { sb.append(line +
* "\n"); } String announcementmsg = sb.toString();
*/
commonlogger.info(textMessage);
connection.start();
// producer.send(session.createTextMessage(announcementmsg));
queueSender.send(textMessage);
Related
I want to use kotlin's object as dto
#ResponseBody
fun getBindCar(coachId: Long): List<Any> {
val coach = coachRepository.findById(coachId).get()
var result = mutableListOf<Any>()
coach?.cars.forEach { it ->
var o = object : Serializable {
var id: Long = 0L
var licenceNum = ""
}
o.id = it.id
o.licenceNum = it.licenceNum
result.add(o)
}
return result
}
when it return ,throw exception
2018:04:106:18:35:36.936 [http-nio-8080-exec-4] WARN o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolved exception caused by Handler execution: java.lang.ClassCastException: org.appsugar.archetypes.web.controller.oa.CoachController$getBindCar$1$o$1 cannot be cast to org.springframework.core.io.support.ResourceRegion
2018:04:106:18:35:36.950 [http-nio-8080-exec-4] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: getOutputStream() has already been called for this response] with root cause
java.lang.IllegalStateException: getOutputStream() has already been called for this response
When I update the return type from List<Any> to Any , it works
I am building an application with Spring Boot 1.4.1, Spring Data Jpa and Spring Data Test.
I have the following controller with which I want to return paged accounts:
#RequestMapping(method=RequestMethod.GET)
public HttpEntity<PagedResources<Account>> getAccounts(
Pageable pageable,
PagedResourcesAssembler assembler,
#RequestParam(value="name", required = false) String name,
#RequestParam(value="username", required = false) String username,
#RequestParam(value="email", required = false) String email,
#RequestParam(value="lastName", required = false) String lastName,
#RequestParam(value="size", required = true, defaultValue = "10") Integer size,
#RequestParam(value="page", required = true, defaultValue = "0") int page,
#RequestParam(value="sort", required = false, defaultValue = "username") String sort,
#RequestParam(value="direction", required = false, defaultValue = "asc") String direction,
UriComponentsBuilder uriBuilder,
HttpServletRequest request,
HttpServletResponse response) {
// form page request
AccountList list = null;
Page<Account> resultPage = null;
Direction sortDirection = Direction.ASC;
if(direction.equals("desc")) {
sortDirection = Direction.DESC;
}
PageRequest pReq = new PageRequest(page, size, sortDirection, sort);
resultPage = accountService.findAll(pReq);
return new ResponseEntity<>(assembler.toResource(resultPage), HttpStatus.OK);
}
My test method is:
#Test
public void getAccountsTest() throws Exception {
String uri = uriBase + "/accounts";
List<Account> list = new ArrayList<Account>();
list.add(accountOne);
list.add(accountTwo);
Page<Account> returnPage = new PageImpl<Account>(list, new PageRequest(0,10), list.size());
when(accountService.findAll(any(PageRequest.class))).thenReturn(returnPage);
mockMvc.perform(get(uri))
.andExpect(status().isOk())
.andDo(print())
.andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.accounts", hasSize(2)))
.andExpect(jsonPath("$.accounts[*].username",
hasItems(endsWith(accountOne.getUsername()), endsWith(accountTwo.getUsername()))))
.andExpect(jsonPath("$.accounts[*].email",
hasItems(endsWith(accountOne.getEmail()), endsWith(accountTwo.getEmail()))));
}
My problem is, that when I run the JUnit test it breaks with the error
org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.domain.Pageable]: Specified class is an interface
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:99)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:142)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:80)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:102)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:161)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at de.campuz.platform.rest.controller.AccountControllerTestDoc.getAccountsTest(AccountControllerTestDoc.java:93)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.restdocs.JUnitRestDocumentation$1.evaluate(JUnitRestDocumentation.java:55)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
I added the #EnableSpringDataWebSupport annotation to my web config but the error still persists. When running the application as is the controller works just fine, I'll get the paged accounts as the JSON response. But I can't figure out how I can test my Controllers.
Does anyone have an idea how to fix this specific problem or how to unit test Spring MVC controllers which return paged content in general?
I solved it by removing the Pageable pageable from the Controller constructor, because I didn't need it anyway. Then the PagedResourcesAssembler assembler threw the error
org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.data.web.PagedResourcesAssembler]:
No default constructor found; nested exception is java.lang.NoSuchMethodException:
org.springframework.data.web.PagedResourcesAssembler.<init>()
I digged a bit into the topic of the ResourceAssembler and came up with the following solution:
Controller:
#RequestMapping(method=RequestMethod.GET)
public ResponseEntity<PagedResources<AccountResource>> getAccounts(
#RequestParam(value="name", required = false) String name,
#RequestParam(value="username", required = false) String username,
#RequestParam(value="email", required = false) String email,
#RequestParam(value="lastName", required = false) String lastName,
#RequestParam(value="size", required = true, defaultValue = "10") Integer size,
#RequestParam(value="page", required = true, defaultValue = "0") int page,
#RequestParam(value="sort", required = false, defaultValue = "username") String sort,
#RequestParam(value="direction", required = false, defaultValue = "asc") String direction,
UriComponentsBuilder uriBuilder,
HttpServletRequest request,
HttpServletResponse response) {
// Build page request
AccountList list = null;
Page<Account> resultPage = null;
Direction sortDirection = Direction.ASC;
if(direction.equals("desc")) {
sortDirection = Direction.DESC;
}
PageRequest pReq = new PageRequest(page, size, sortDirection, sort);
resultPage = accountService.findAll(pReq);
HateoasPageableHandlerMethodArgumentResolver resolver = new HateoasPageableHandlerMethodArgumentResolver();
PagedResourcesAssembler<Account> accountPageAssembler = new PagedResourcesAssembler<Account>(resolver, null);
return new ResponseEntity<PagedResources<AccountResource>>(accountPageAssembler.toResource(resultPage, new AccountResourceAsm()), HttpStatus.OK);
}
Where I create the Resource Assembler with the HateoasPageableHandlerMethodArgumentResolver to transform the Page to the PagedResource I wanted to return.
Then I could finally run the controller test (as seen in the question) successfully.
This answer helped me a lot, thanks Oliver Gierke and Patrick Cornelissen.
Having the same problem, I wanted to avoid "manually" fetching the PagedResourcesAssembler in the controller.
Adding this to the test class fixed it for me :
#Import(HateoasAwareSpringDataWebConfiguration.class)
Can anybody answer this?Don't know why i'm getting NullPointerException when trying to execute the below programme.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("image/jpeg");
ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("C:/Users/Public/Pictures/Sample Pictures/Desert.jpg"); --> The picture exists at this location
OutputStream os = response.getOutputStream();
int read = 0;
byte[] bytes = new byte[1024];
System.out.println("bytes :" + bytes);
while((read = is.read(bytes)) != -1) -- Error at this line
{
System.out.println("read :" +read);
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
When running this in tomcat-Apache Getting the below error.
bytes :[B#158f9d3
Sep 19, 2013 7:23:04 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet Newest threw exception
java.lang.NullPointerException
at com.examples.Newest.doPost(Newest.java:69)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:873)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:662)
This
InputStream is = ctx.getResourceAsStream("C:/Users/Public/Pictures/Sample Pictures/Desert.jpg"); --> The picture exists at this location
is not how you access a file on the file system. With that method call you are trying to get the resource from the context root. And, because you obviously don't have a resource called C:/Users/Public/Pictures/Sample Pictures/Desert.jpg relative to the context root, it returns null.
Use Java 7's NIO
Path path = Paths.get("C:/Users/Public/Pictures/Sample Pictures/Desert.jpg");
InputStream is = Files.newInputStream(path);
I'm trying to find a way to avoid the IOException related to the fact that I read on a closed stream.
I'm calling a webservice method that returns a Stream:
InputStream stream = callRestWebService();
try {
parkingState = objectMapper.readValue(stream, ParkingState.class);
} catch (IOException e) {
throw new ParkingMeasurementProviderException("Could not retrieve data.", e);
}
Then, I have my Web Service method where I close the get connection:
public InputStream callRestWebService() {
int parkingId = 2803;
String endpointURL = REST_ENDPOINT + URI_INFO_PATH + parkingId + "/parkingState";
InputStream inputStream = null;
// Create an instance of HttpClient.
HttpClient httpclient = new HttpClient();
// Create a method instance.
GetMethod getMethod = new GetMethod(endpointURL);
getMethod.addRequestHeader("accept", "application/json");
try {
// Execute the method.
int statusCode = httpclient.executeMethod(getMethod);
inputStream = getMethod.getResponseBodyAsStream();
} catch (IOException e) {
e.printStackTrace();
} finally {
// Release the connection.
getMethod.releaseConnection();
}
return inputStream;
}
Is there a way to avoid having this exception without removing the : getMethod.releaseConnection();
The stack trace:
Disconnected from the target VM, address: '127.0.0.1:62152', transport: 'socket'
at be.ixor.itg.server.service.parking.hermesWS.HermesWSParkingControllerMeasurementProvider.getHermesMechelenData(HermesWSParkingControllerMeasurementProvider.java:126)
at be.ixor.itg.server.service.parking.hermesWS.Main.main(Main.java:14)
Caused by: java.io.IOException: Attempted read on closed stream.
at org.apache.commons.httpclient.AutoCloseInputStream.isReadAllowed(AutoCloseInputStream.java:183)
at org.apache.commons.httpclient.AutoCloseInputStream.read(AutoCloseInputStream.java:86)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager$RewindableInputStream.read(XMLEntityManager.java:2977)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:702)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:186)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:772)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:232)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
at be.ixor.itg.server.service.parking.hermesWS.HermesWSParkingControllerMeasurementProvider.getHermesMechelenData(HermesWSParkingControllerMeasurementProvider.java:116)
... 1 more
Because you are calling releaseConnection() in your finally block, the input stream will no longer be available.
If you do not expect the content to be large, you could read the data from the input stream into a buffer and return the buffer instead of the input stream. Otherwise, you will need to change your code to allow the called to process the data from the input stream before releasing the connection.
BufferedReader br = new BufferedReader(new
InputStreamReader((response.getEntity().getContent())));
String response = br.readLine();
System.out.println("response" + response );
This code is working for me.
I am trying to develop an app for Facebook. I wrote a facebook controller and created connectionFactory object, got the oAuth oprations and accessgrant object. I got the access token also But Once I try to create a connection
Connection<Facebook> connection = connectionFactory.createConnection(accessGrant);
I am getting the error :
MissingAuthorizationException: Authorization is required for the operation, but the API binding was created without authorization.
Full stack trace :
[1/25/12 9:18:17:097 IST] 0000001a SystemOut O oauthOperations :org.springframework.social.facebook.connect.FacebookOAuth2Template#46714671
[1/25/12 9:18:17:097 IST] 0000001a SystemOut O authorizeUrl :https://graph.facebook.com/oauth/authorize?client_id=xxxxx&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A80%2FSpringSocial%2Fstart&scope=read_stream%2Cemail%2Cpublish_stream%2Coffline_access
[1/25/12 9:19:15:930 IST] 0000001a SystemOut O oauthOperations authorizationCode :org.springframework.social.facebook.connect.FacebookOAuth2Template#46714671
[1/25/12 9:19:25:197 IST] 0000001a SystemOut O accssTokentemp :xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[1/25/12 9:19:35:541 IST] 0000001a SystemOut O facebook :org.springframework.social.facebook.api.impl.FacebookTemplate#21c221c2
[1/25/12 9:19:35:994 IST] 0000001a RestTemplate W org.springframework.web.client.RestTemplate handleResponseError GET request for "https://graph.facebook.com/me" resulted in 400 (Bad Request); invoking error handler
[1/25/12 9:19:36:041 IST] 0000001a servlet E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0068E: Uncaught exception created in one of the service methods of the servlet SpringSocial in application SpringSocialFacebookEar. Exception created : org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.social.MissingAuthorizationException: Authorization is required for the operation, but the API binding was created without authorization.
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:681)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:718)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
at com.ibm.ws.cache.servlet.ServletWrapper.serviceProxied(ServletWrapper.java:307)
at com.ibm.ws.cache.servlet.CacheHook.handleFragment(CacheHook.java:579)
at com.ibm.ws.cache.servlet.CacheHook.handleServlet(CacheHook.java:250)
at com.ibm.ws.cache.servlet.ServletWrapper.service(ServletWrapper.java:259)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1663)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:939)
Caused by: org.springframework.social.MissingAuthorizationException: Authorization is required for the operation, but the API binding was created without authorization.
at org.springframework.social.facebook.api.impl.FacebookErrorHandler.handleFacebookError(FacebookErrorHandler.java:95)
at org.springframework.social.facebook.api.impl.FacebookErrorHandler.handleError(FacebookErrorHandler.java:60)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:486)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:443)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:415)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:213)
at org.springframework.social.facebook.api.impl.FacebookTemplate.fetchObject(FacebookTemplate.java:165)
at org.springframework.social.facebook.api.impl.UserTemplate.getUserProfile(UserTemplate.java:50)
at org.springframework.social.facebook.api.impl.UserTemplate.getUserProfile(UserTemplate.java:46)
at org.springframework.social.facebook.connect.FacebookAdapter.setConnectionValues(FacebookAdapter.java:42)
at org.springframework.social.facebook.connect.FacebookAdapter.setConnectionValues(FacebookAdapter.java:30)
at org.springframework.social.connect.support.AbstractConnection.setValues(AbstractConnection.java:172)
at org.springframework.social.connect.support.AbstractConnection.initKey(AbstractConnection.java:135)
at org.springframework.social.connect.support.OAuth2Connection.(OAuth2Connection.java:73)
at org.springframework.social.connect.support.OAuth2ConnectionFactory.createConnection(OAuth2ConnectionFactory.java:58)
at com.tgt.social.controller.FaceBookConnectController.facebookConnect(FaceBookConnectController.java:107)
My Controller class :
#Controller
public class FaceBookConnectController {
private static OAuth2Operations oauthOperations = null;
private static FacebookConnectionFactory connectionFactory = null;
private static OAuth2Parameters params = null;
#RequestMapping("/start")
public ModelAndView facebookConnect(Model model,HttpServletRequest request,HttpServletResponse response) {
Security.setProperty("ssl.SocketFactory.provider", "com.ibm.jsse2.SSLSocketFactoryImpl");
Security.setProperty("ssl.ServerSocketFactory.provider", "com.ibm.jsse2.SSLServerSocketFactoryImpl");
System.setProperty("https.proxyHost", "localhost");
System.setProperty("https.proxyPort", "8888");
String clientId = "xxxxxxxxx";
String clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
String redirectUrl = "http://localhost:80/SpringSocial/start";
try {
String authorizationCode = request.getParameter("code");
if(null != authorizationCode){
MultiValueMap paramsMap1 = new LinkedMultiValueMap();
System.out.println("oauthOperations authorizationCode :"+oauthOperations);
//paramsMap.set("client_id", clientId);
//paramsMap.set("client_secret", clientSecret);
//paramsMap.set("code", authorizationCode);
paramsMap1.set("redirect_uri", redirectUrl);
paramsMap1.set("grant_type", "authorization_code");
paramsMap1.set("scope","read_stream,user_about_me,user_birthday,user_likes,user_status,email,publish_stream,offline_access");
//AccessGrant accessGrant = oauthOperations.exchangeForAccess(authorizationCode, redirectUrl, paramsMap1);
System.out.println("connectionFactory authorizationCode :"+connectionFactory);
AccessGrant accessGrant = connectionFactory.getOAuthOperations().exchangeForAccess(authorizationCode, redirectUrl, paramsMap1);
String accssTokentemp = accessGrant.getAccessToken();
System.out.println("accssTokentemp :"+accssTokentemp);
String scope_p = accessGrant.getScope();
System.out.println("scope_p :"+scope_p);
Facebook facebook = new FacebookTemplate(accssTokentemp);
System.out.println("facebook :"+facebook);
Connection<Facebook> connection = connectionFactory.createConnection(accessGrant);
//FacebookProfile userProfile = facebook.userOperations().getUserProfile();
System.out.println("connection :"+connection);
}else{
MultiValueMap paramsMap = new LinkedMultiValueMap();
connectionFactory = new FacebookConnectionFactory(clientId,clientSecret);
System.out.println("connectionFactory :"+connectionFactory);
oauthOperations = connectionFactory.getOAuthOperations();
params = new OAuth2Parameters();
params.setRedirectUri(redirectUrl);
params.setScope("read_stream,user_about_me,user_birthday,user_likes,user_status,email,publish_stream,offline_access");
paramsMap.set("client_id", clientId);
paramsMap.set("client_secret", clientSecret);
paramsMap.set("code", authorizationCode);
paramsMap.set("redirect_uri", redirectUrl);
paramsMap.set("grant_type", "authorization_code");
System.out.println("oauthOperations :"+oauthOperations);
String authorizeUrl = oauthOperations.buildAuthorizeUrl(GrantType.AUTHORIZATION_CODE, params);
System.out.println("authorizeUrl :"+authorizeUrl);
response.sendRedirect(authorizeUrl);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Please let me know what is wrong here?
Is the instantiation is not correct for connectionFactory object.
You need to addConnection to the usersConnectionRepository since social tries to locate a user's already established connection if any, and tries to get it authorized and use it