List<?> items =upload.parseRequest(request);
The method parseRequest(HttpServletRequest, int, long, String) in the type DiskFileUpload is not applicable for the arguments (HttpServletRequest)
When i Run as Server...it gives error on console
May 13, 2012 7:47:49 PM org.apache.tomcat.util.digester.Digester startElement
SEVERE: Begin event threw error
java.lang.NoSuchMethodError: org.apache.tomcat.util.ExceptionUtils.unwrapInvocationTargetException(Ljava/lang/Throwable;)Ljava/lang/Throwable;
at org.apache.catalina.core.AprLifecycleListener.init(AprLifecycleListener.java:185)
at org.apache.catalina.core.AprLifecycleListener.isAprAvailable(AprLifecycleListener.java:84)
at org.apache.catalina.connector.Connector.setProtocol(Connector.java:577)
at org.apache.catalina.connector.Connector.(Connector.java:69)
at org.apache.catalina.startup.ConnectorCreateRule.begin(ConnectorCreateRule.java:62)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:506)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1302)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
at org.apache.catalina.startup.Catalina.load(Catalina.java:576)
at org.apache.catalina.startup.Catalina.load(Catalina.java:619)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:281)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:449)
java.lang.NoSuchMethodError: org.apache.tomcat.util.ExceptionUtils.unwrapInvocationTargetException(Ljava/lang/Throwable;)Ljava/lang/Throwable;
at org.apache.catalina.core.AprLifecycleListener.init(AprLifecycleListener.java:185)
at org.apache.catalina.core.AprLifecycleListener.isAprAvailable(AprLifecycleListener.java:84)
at org.apache.catalina.connector.Connector.setProtocol(Connector.java:577)
at org.apache.catalina.connector.Connector.(Connector.java:69)
at org.apache.catalina.startup.ConnectorCreateRule.begin(ConnectorCreateRule.java:62)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:506)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1302)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
at org.apache.catalina.startup.Catalina.load(Catalina.java:576)
at org.apache.catalina.startup.Catalina.load(Catalina.java:619)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:281)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:449)
This is my code in this code
List<?> items =upload.parseRequest(request); Got error as The method parseRequest(HttpServletRequest, int, long, String) in the type DiskFileUpload is not applicable for the arguments
(HttpServletRequest)
package br.com.ecommerce.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.disk.*;
import org.apache.tomcat.util.http.fileupload.servlet.*;
import org.apache.tomcat.util.http.fileupload.util.*;
import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import br.com.ecommerce.bean.Produtos;
import br.com.ecommerce.controller.ExceptionController;
import br.com.ecommerce.dao.CategoriasDao;
import br.com.ecommerce.dao.ProdutosDao;
class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
Produtos produto = new Produtos();
String caminhoTemp = new String("C:\\Users\\vaio\\workspace\\ecommerce\\WebContent\\images\\upload");
String pasta = new String("C:\\Users\\vaio\\workspace\\ecommerce\\WebContent\\images\\upload");
String caminho = new String("images\\upload\\");
if (ServletFileUpload.isMultipartContent( request)){
DiskFileUpload upload = new DiskFileUpload();
upload.setRepositoryPath(caminhoTemp);
try{
List<?> items =upload.parseRequest(request);//In this line i got error..why?..Pls help
Iterator<?> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if(item.isFormField()){
if(item.getFieldName().equals("nome")){
produto.setProdNome(item.getString().toUpperCase());
}
else if (item.getFieldName().equals("categoria")){
produto.setCategorias(new CategoriasDao().findByPK(Integer.valueOf(item.getString())));
}
else if (item.getFieldName().equals("preco")){
produto.setPreco(Double.valueOf(item.getString()));
Double preco = 0d;
preco = Double.valueOf(item.getString());
preco += 10.00;
System.out.println(preco);
}
else if (item.getFieldName().equals("descp")){
produto.setDescPeq(item.getString());
}
else if (item.getFieldName().equals("descg")){
produto.setDescGd(item.getString());
}
else if (item.getFieldName().equals("espec")){
produto.setEspecificacoes(item.getString());
}
else if (item.getFieldName().equals("itens")){
produto.setItensInclusos(item.getString());
}
produto.setPromocao(0);
produto.setDestaque(0);
}
if (!item.isFormField()) {
String nome = item.getName().toString();
String nomeArquivo = nome.substring(nome.lastIndexOf("\\")+1);
File arquivo = new File(pasta + "\\" + nomeArquivo);
produto.setImagem(caminho + nomeArquivo);
item.write(arquivo);
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
new ProdutosDao().insert(produto);
} catch (ExceptionController e) {
e.printStackTrace();
}
response.sendRedirect("/ecommerce/admin/gerenciarProdutos.jsp");
}
}
enter code here
Are you trying to use the DiskFileUpload class from Commons FileUpload? If so, make sure your class is importing org.apache.commons.fileupload.DiskFileUpload, and not some other class called DiskFileUpload.
Related
I'm trying to use distributed states in my application with zookeeper just like in the Spring document, with only one difference. My application works fine with one zookeeper but I need multiple zookeeper address. Here is my configuration:
import jpapersistsm.enums.Events;
import jpapersistsm.enums.States;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.data.jpa.JpaPersistingStateMachineInterceptor;
import org.springframework.statemachine.data.jpa.JpaStateMachineRepository;
import org.springframework.statemachine.ensemble.StateMachineEnsemble;
import org.springframework.statemachine.listener.StateMachineListener;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;
import org.springframework.statemachine.persist.StateMachineRuntimePersister;
import org.springframework.statemachine.service.DefaultStateMachineService;
import org.springframework.statemachine.service.StateMachineService;
import org.springframework.statemachine.state.State;
import org.springframework.statemachine.zookeeper.ZookeeperStateMachineEnsemble;
import java.util.EnumSet;
#Slf4j
#Configuration
#EnableStateMachineFactory
public class JpaPersistStateMachineConfiguration extends StateMachineConfigurerAdapter<States, Events> {
#Autowired
public JpaStateMachineRepository jpaStateMachineRepository;
private Logger logger = LoggerFactory.getLogger(JpaPersistStateMachineConfiguration.class);
#Override
public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception{
states
.withStates()
.initial(States.ORDERED)
.end(States.PAYED)
.end(States.CANCELLED)
.states(EnumSet.allOf(States.class));
}
#Override
public void configure(StateMachineTransitionConfigurer<States,Events> transitions) throws Exception {
transitions
.withExternal().source(States.ORDERED).target(States.ASSEMBLED).event(Events.assemble).and()
.withExternal().source(States.ASSEMBLED).target(States.DELIVERED).event(Events.deliver).and()
.withExternal().source(States.DELIVERED).target(States.PAYED).event(Events.payment_received).and()
.withExternal().source(States.ORDERED).target(States.CANCELLED).event(Events.cancel).and()
.withExternal().source(States.ASSEMBLED).target(States.CANCELLED).event(Events.cancel).and()
.withExternal().source(States.DELIVERED).target(States.CANCELLED).event(Events.cancel);
}
#Override
public void configure(StateMachineConfigurationConfigurer<States,Events> config) throws Exception{
config
.withDistributed()
.ensemble(stateMachineEnsemble())
.and()
.withPersistence()
.runtimePersister(stateMachineRuntimePersister())
.and()
.withConfiguration()
.autoStartup(true);
}
#Bean
public StateMachineEnsemble<States, Events> stateMachineEnsemble() throws Exception {
return new ZookeeperStateMachineEnsemble<States, Events>(curatorClient(), "/app");
}
#Bean
public CuratorFramework curatorClient() throws Exception {
CuratorFramework client = CuratorFrameworkFactory
.builder()
.defaultData(new byte[0])
.retryPolicy(new ExponentialBackoffRetry(1000, 3))
.connectString("localhost:2181,localhost:2182,localhost:2183")
.build();
client.start();
return client;
}
#Bean
public StateMachineRuntimePersister<States,Events,String> stateMachineRuntimePersister(){
return new JpaPersistingStateMachineInterceptor<>(jpaStateMachineRepository);
}
#Bean
public StateMachineService<States,Events> stateMachineService (
StateMachineFactory<States,Events> stateMachineFactory,
StateMachineRuntimePersister<States,Events,String> stateMachineRuntimePersister){
return new DefaultStateMachineService<>(stateMachineFactory, stateMachineRuntimePersister);
}
#Bean
public StateMachineListener<States, Events> listener() {
return new StateMachineListenerAdapter<States, Events>() {
#Override
public void stateChanged(State<States, Events> from, State<States, Events> to) {
logger.info("*** listener: in state changed");
if (from == null) logger.info("*** state machine initialised in state {}", to.getId());
else logger.info("*** state changed from {} to {}", from.getId(), to.getId());
}
};
}
}
And my REST Controller class is:
import jpapersistsm.enums.Events;
import jpapersistsm.enums.States;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.listener.StateMachineListener;
import org.springframework.statemachine.service.StateMachineService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
#RestController
#RequestMapping("/jpapersist")
public class RestServiceController {
#Autowired
public StateMachineService<States, Events> stateMachineService;
#Autowired
public StateMachineListener listener;
public StateMachine<States, Events> stateMachine;
public Logger logger = LoggerFactory.getLogger(RestServiceController.class);
#RequestMapping(value="/init", method= RequestMethod.POST)
public void init(#RequestBody Map<String,String> parameters){
logger.info("\n*** inside of state machine controller : INIT ");
try {
stateMachine = getStateMachine(parameters.get("guid"));
} catch (Exception e) {
e.printStackTrace();
}
logger.info("\n*** state machine initialized to state: {}", stateMachine.getState().getId().name());
}
/***
Synchronized method to obtain persisted state machine from database.
*/
public synchronized StateMachine<States,Events> getStateMachine(String machineId) throws Exception {
if (stateMachine == null) {
stateMachine = stateMachineService.acquireStateMachine(machineId);
stateMachine.addStateListener(listener);
stateMachine.start();
} else if (!ObjectUtils.nullSafeEquals(stateMachine.getId(), machineId)) {
stateMachineService.releaseStateMachine(stateMachine.getId());
stateMachine.stop();
stateMachine = stateMachineService.acquireStateMachine(machineId);
stateMachine.addStateListener(listener);
stateMachine.start();
}
return stateMachine;
}
}
When I send a request for initialize a state machine, getting an error like:
Unable to persist stateMachineContext
Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): org.springframework.statemachine.data.jpa.JpaRepositoryStateMachine
at org.hibernate.id.Assigned.generate(Assigned.java:33) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:119) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:192) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:135) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:62) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:800) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:785) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_222]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_222]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_222]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_222]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at com.sun.proxy.$Proxy117.persist(Unknown Source) ~[na:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_222]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_222]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_222]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_222]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:309) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at com.sun.proxy.$Proxy117.persist(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:535) ~[spring-data-jpa-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_222]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_222]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_222]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_222]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295) ~[spring-tx-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.9.RELEASE.jar:5.1.9.RELEASE]
... 111 common frames omitted
The state of the machine seems to changed, but could not persist on db. As I said, the problem is my curator configuration. Because it works fine when I define connectString with single Zookeeper like
.connectString("localhost:2181")
I'm new to Zookeeper and Curator, and open to any help. Thanks in advance.
The problem is with this configuration:
.withConfiguration()
.autoStartup(true);
Because it tries to start the machine, before having a machine id.
I have developed a simple java program to fetch the data of issues/user stories.
I want to fetch 'description' field of a perticular issue. I have used GET method to get response but I'm getting errors while connecting to JIRA.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class JiraIssueDescription {
public static void main(String[] args) {
try {
URL url = new URL("https://****.atlassian.net/rest/agile/1.0/issue/41459");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("username", "***#abc.com");
conn.setRequestProperty("password", "****");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I run the project I get following error
java.net.UnknownHostException: ****.atlassian.net
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at com.JiraIntegration.bean.JiraIssueDescription.main(JiraIssueDescription.java:24)
Can anyone please help me with the errors. Do I need to implement OAuth ?
UnknownHostException looks like you have a typo in your URL or are facing some proxy issues .
Does it work in your Browser?
It should give you some json in response. Like this:
https://jira.atlassian.com/rest/api/2/issue/JSWCLOUD-11658
You could also test with other tools like curl. Does it work?
curl https://jira.atlassian.com/rest/api/2/issue/JSWCLOUD-11658
Atlassian rest API provides two authentication methods, Basic auth and Oauth. Use this approach to create a valid basic auth header or try the request without parameters.
The following code demonstrates how it should work:
package stack48618849;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.junit.Test;
public class HowToReadFromAnURL {
#Test
public void readFromUrl() {
try (InputStream in = getInputStreamFromUrl("https://jira.atlassian.com/rest/api/2/issue/JSWCLOUD-11658")) {
System.out.println(convertInputStreamToString(in));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#Test(expected = RuntimeException.class)
public void readFromUrlWithBasicAuth() {
String user="aUser";
String passwd="aPasswd";
try (InputStream in = getInputStreamFromUrl("https://jira.atlassian.com/rest/api/2/issue/JSWCLOUD-11658",user,passwd)) {
System.out.println(convertInputStreamToString(in));
} catch (Exception e) {
System.out.println("If basic auth is provided, it should be correct: "+e.getMessage());
throw new RuntimeException(e);
}
}
private InputStream getInputStreamFromUrl(String urlString,String user, String passwd) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
String encoded = Base64.getEncoder().encodeToString((user+":"+passwd).getBytes(StandardCharsets.UTF_8));
conn.setRequestProperty("Authorization", "Basic "+encoded);
return conn.getInputStream();
}
private InputStream getInputStreamFromUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
return conn.getInputStream();
}
private String convertInputStreamToString(InputStream inputStream) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString("UTF-8");
}
}
This prints:
{"expand":"renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations","id":"789521","self":"https://jira.atlassian.com/rest/api/2/issue/789521","key":"JSWCLOUD-11658","fields":{"customfield_18232":...
If basic auth is provided, it should be correct: Server returned HTTP response code: 401 for URL: https://jira.atlassian.com/rest/api/2/issue/JSWCLOUD-11658
Instead of a HttpURLConnection way of implementing, you could use Spring's RestTemplate in an efficient manner to solve your problem:
Providing you a piece of code that I use, with the JIRA REST APIs:
Create a RESTClient that you would want to use in conjunction with JIRA REST APIs as like the below:
public class JIRASpringRESTClient {
private static final String username = "fred";
private static final String password = "fred";
private static final String jiraBaseURL = "https://jira.xxx.com/rest/api/2/";
private RestTemplate restTemplate;
private HttpHeaders httpHeaders;
public JIRASpringRESTClient() {
restTemplate = new RestTemplate();
httpHeaders = createHeadersWithAuthentication();
}
private HttpHeaders createHeadersWithAuthentication() {
String plainCredentials = username + ":" + password;
byte[] base64CredentialsBytes = Base64.getEncoder().encode(plainCredentials.getBytes());
String base64Credentials = new String(base64CredentialsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Credentials);
return headers;
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public ResponseEntity<String> getJIRATicket(String issueId) {
String url = jiraBaseURL + "issue/" + issueId;
HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);
return restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
}
}
Then you can further re-use these methods as like the below:
public class JIRATicketGet {
public static void main(String... args) {
JIRASpringRESTClient restClient = new JIRASpringRESTClient();
ResponseEntity<String> response = restClient.getJIRATicket("XXX-12345");
System.out.println(response.getBody());
}
}
This will provide the GET response from JIRA, which is in JSON format which can be further manipulated to get the specific field from the GET response with the use of com.fasterxml.jackson.databind.ObjectMapper
Using the JSON that you get in the step above, you can create a POJO class (for example, Ticket) and then use it as follows:
ObjectMapper mapper = new ObjectMapper();
try {
Ticket response = mapper.readValue(response.getBody(), Ticket.class);
} catch (IOException e) {
e.printStackTrace();
}
Hope this helps!
I have installed Hadoop 2.6 in centos7 and it's running fine. But when I run a jar exported from Eclipse, it gives the following error:
[root#myspark ~]# hadoop jar fengcount.jar intput output1
17/05/26 21:24:51 INFO client.RMProxy: Connecting to ResourceManager
at myspark/192.168.44.100:8032 17/05/26 21:24:53 INFO mapreduce.JobSubmitter: Cleaning up the staging area /tmp/hadoop-yarn/staging/root/.staging/job_1495765615548_0004 Exception in thread "main" org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://myspark:54310/user/root/intput
at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:321)
at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:264)
at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:385)
at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:302)
at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:319)
at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:197)
at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1297)
at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1294)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:422)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1692)
at org.apache.hadoop.mapreduce.Job.submit(Job.java:1294)
at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1315)
at hdfs.hadoop_hdfs.fengcount.main(fengcount.java:39)
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.apache.hadoop.util.RunJar.run(RunJar.java:221)
at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
The file input/test1.txt actually exists:
[root#myspark ~]# hdfs dfs -ls -R
drwxr-xr-x - root supergroup 0 2017-05-26 21:02 input
-rw-r--r-- 1 root supergroup 16 2017-05-24 01:57 input/test1.txt
My code:
package hdfs.hadoop_hdfs;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class fengcount {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
// TODO Auto-generated method stub
Configuration conf=new Configuration();
String[] otherargs=new GenericOptionsParser(conf,args).getRemainingArgs();
if (otherargs.length!=2) {
System.err.println("Usage:fengcount<int><out>");
System.exit(2);
}
#SuppressWarnings("deprecation")
Job job=new Job(conf, "fengcount");
job.setJarByClass(fengcount.class);
job.setMapperClass(TokerizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherargs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherargs[1]));
System.exit(job.waitForCompletion(true)?0:1);
}
// mapper class
public static class TokerizerMapper extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
#Override
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
// TODO Auto-generated method stub
System.out.println("key=" + key.toString());
System.out.println("value=" + value.toString());
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
//reduce process
public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
#Override
public void reduce(Text key, Iterable<IntWritable> values,
Reducer<Text, IntWritable, Text, IntWritable>.Context context)
throws IOException, InterruptedException {
// TODO Auto-generated method stub
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
//mapreduce process
}
From the error log, I could see hdfs://myspark:54310/user/root/intput, I suspect its incorrect. I guess the path ends with input.
Good luck!
I am using Jersey version 2.23.2 and I am unable to figure out how to use JerseyTest to test the responses for when validation fails. For some reason, the below test throws a ConstraintViolationException which is wrapped in a ProcessingException instead of returning 400 Bad Request. I could modify the test to check that the ProcessingException is thrown, but I really want to test the response. When I run HelloResource in Grizzly without JerseyTest, I get the appropriate 400 Bad Request response. Any ideas on how to fix the badRequestResponse() test below?
package example;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import static org.junit.Assert.assertEquals;
public class BadRequestTest extends JerseyTest {
#XmlAccessorType(XmlAccessType.FIELD)
public static class Hello {
#NotNull(message = "Name is a required field.")
private final String name;
private Hello() {
this(null);
}
public Hello(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
#Path("hello")
public static class HelloResource {
#POST
public String sayHelloToMe(#Valid Hello hello) {
return "Hello " + hello.getName() + "!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class).property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
}
/** Test OK Response. This Works!*/
#Test
public void okResponse() {
Response response = target("hello")
.request(MediaType.TEXT_PLAIN)
.post(Entity.json(new Hello("Tiny Tim")));
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
assertEquals("Hello Tiny Tim!", response.readEntity(String.class));
}
/** Test Bad Request Response. This Fails! */
#Test
public void badRequestResponse() {
Response response = target("hello")
.request(MediaType.TEXT_PLAIN)
.post(Entity.json(new Hello(null)));
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
}
Here's the exception I am getting:
javax.ws.rs.ProcessingException:
Exception Description: Constraints violated on marshalled bean:
example.BadRequestTest$Hello#456abb66
-->Violated constraint on property name: "Name is a required field.".
Internal Exception: javax.validation.ConstraintViolationException
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:261)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:684)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:681)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:681)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:437)
at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:343)
at example.BadRequestTest.badRequestResponse(BadRequestTest.java:70)
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.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: Exception [EclipseLink-7510] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.BeanValidationException
Exception Description: Constraints violated on marshalled bean:
example.BadRequestTest$Hello#456abb66
-->Violated constraint on property name: "Name is a required field.".
Internal Exception: javax.validation.ConstraintViolationException
at org.eclipse.persistence.exceptions.BeanValidationException.constraintViolation(BeanValidationException.java:53)
at org.eclipse.persistence.jaxb.JAXBBeanValidator.buildConstraintViolationException(JAXBBeanValidator.java:385)
at org.eclipse.persistence.jaxb.JAXBBeanValidator.validate(JAXBBeanValidator.java:273)
at org.eclipse.persistence.jaxb.JAXBMarshaller.validateAndTransformIfNeeded(JAXBMarshaller.java:588)
at org.eclipse.persistence.jaxb.JAXBMarshaller.marshal(JAXBMarshaller.java:481)
at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:949)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
at org.glassfish.jersey.client.ClientRequest.doWriteEntity(ClientRequest.java:517)
at org.glassfish.jersey.client.ClientRequest.writeEntity(ClientRequest.java:499)
at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:388)
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:285)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:252)
... 39 more
Caused by: javax.validation.ConstraintViolationException
at org.eclipse.persistence.jaxb.JAXBBeanValidator.buildConstraintViolationException(JAXBBeanValidator.java:383)
... 52 more
This is a client side problem. As you've discovered MOXy has bean validation on by default. So you are getting bean validation on the client. So the request is not even going through as the error is happening on the client. You could test this by just sending a string
Entity.json("{}")
That should get rid of the error. But if you want to use the bean, as you mentioned in the comment, you should disable the bean validation on the client with MOXy
#Override
protected void configureClient(final ClientConfig config) {
super.configureClient(config);
config.register(new MoxyJsonConfig()
.property(MarshallerProperties.BEAN_VALIDATION_MODE,
BeanValidationMode.NONE).resolver());
}
I'm having a problem.
I'm developing web application in Eclipse IDE and using Tomcat 7.
Everything was working fine, when suddenly my debugger doesn't work anymore as it should and everything collapsed to pieces. I was looking for same errors, but I haven't found soulution yet. Please help me.
I'm getting this error:
SEVERE: Servlet.service() for servlet [FitbitApiAuthExampleServlet] in context with path [/Webfit] threw exception
java.lang.NullPointerException
at java.net.URLEncoder.encode(Unknown Source)
at com.fitbit.api.client.http.OAuth.encode(OAuth.java:254)
at com.fitbit.api.client.http.OAuth.encodeParameters(OAuth.java:233)
at com.fitbit.api.client.http.OAuth.encodeParameters(OAuth.java:217)
at com.fitbit.api.client.http.OAuth.normalizeRequestParameters(OAuth.java:196)
at com.fitbit.api.client.http.OAuth.generateAuthorizationHeader(OAuth.java:85)
at com.fitbit.api.client.http.OAuth.generateAuthorizationHeader(OAuth.java:129)
at com.fitbit.api.client.http.HttpClient.setHeaders(HttpClient.java:522)
at com.fitbit.api.client.http.HttpClient.httpRequest(HttpClient.java:422)
at com.fitbit.api.client.http.HttpClient.get(HttpClient.java:398)
at com.fitbit.api.client.FitbitApiClientAgent.httpGet(FitbitApiClientAgent.java:2563)
at com.fitbit.api.client.FitbitApiClientAgent.httpGet(FitbitApiClientAgent.java:2513)
at com.fitbit.api.client.FitbitApiClientAgent.getLoggedHeartRate(FitbitApiClientAgent.java:1779)
at com.fitbit.web.FitbitApiAuthExampleServlet.doGet(FitbitApiAuthExampleServlet.java:108)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Servlet code:
package com.fitbit.web;
import com.fitbit.api.FitbitAPIException;
import com.fitbit.api.client.*;
import com.fitbit.api.client.service.FitbitAPIClientService;
import com.fitbit.api.common.model.body.Body;
import com.fitbit.api.common.model.body.BodyWithGoals;
import com.fitbit.api.common.model.bp.Bp;
import com.fitbit.api.common.model.heart.Heart;
import com.fitbit.api.common.model.user.UserInfo;
import com.fitbit.api.model.APIResourceCredentials;
import com.fitbit.api.model.FitbitUser;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.joda.time.LocalDate;
import java.io.IOException;
import java.util.Properties;
/**
* Created by IntelliJ IDEA.
* User: Kiryl
* Date: 6/22/11
* Time: 7:05 AM
*/
public class FitbitApiAuthExampleServlet extends HttpServlet {
public static final String OAUTH_TOKEN = "oauth_token";
public static final String OAUTH_VERIFIER = "oauth_verifier";
private FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
private FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
private FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
private String apiBaseUrl;
private String fitbitSiteBaseUrl;
private String exampleBaseUrl;
private String clientConsumerKey;
private String clientSecret;
private FitbitUser fitbitUser = new FitbitUser("-");
private int year = 2012;
private int month = 5;
private int day = 5;
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
Properties properties = new Properties();
properties.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
apiBaseUrl = properties.getProperty("apiBaseUrl");
fitbitSiteBaseUrl = properties.getProperty("fitbitSiteBaseUrl");
exampleBaseUrl = properties.getProperty("exampleBaseUrl").replace("/app", "");
clientConsumerKey = properties.getProperty("clientConsumerKey");
clientSecret = properties.getProperty("clientSecret");
} catch (IOException e) {
throw new ServletException("Exception during loading properties", e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
FitbitAPIClientService<FitbitApiClientAgent> apiClientService = new FitbitAPIClientService<FitbitApiClientAgent>(
new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl, credentialsCache),
clientConsumerKey,
clientSecret,
credentialsCache,
entityCache,
subscriptionStore
);
if (request.getParameter("completeAuthorization") != null) {
// Get temporary token and verifier returned by Fitbit from query string
String tempTokenReceived = request.getParameter(OAUTH_TOKEN);
String tempTokenVerifier = request.getParameter(OAUTH_VERIFIER);
// Fetch user credentials from cache by temporary token from query string
APIResourceCredentials resourceCredentials = apiClientService.getResourceCredentialsByTempToken(tempTokenReceived);
/*Handle error when there is no record of credentials in cache for the temporary token provided
As implementation of the credentials cache in this example is not persistant,
this error will popup if you restart application, while user's browser will be on Fitbit*/
if (resourceCredentials == null) {
throw new ServletException("Unrecognized temporary token when attempting to complete authorization: " + tempTokenReceived);
}
// Call method of Fitbit4J to get token credentials only if necessary (they haven't been cached yet)
if (!resourceCredentials.isAuthorized()) {
resourceCredentials.setTempTokenVerifier(tempTokenVerifier); // The verifier token is required in the request to get token credentials
try {
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId())); // get token credentials for user
} catch (FitbitAPIException e) {
throw new ServletException("Unable to finish authorization with Fitbit.", e);
}
}
try {
// get UserInfo
UserInfo userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
request.setAttribute("userInfo", userInfo);
//get HeartRate
Heart heartInfo = apiClientService.getClient().getLoggedHeartRate(new LocalUserDetail(resourceCredentials.getLocalUserId()), fitbitUser, new LocalDate(year,month,day));
//HeartRate heartAverage = new HeartRate(heartInfo.getTrackerAverage());
request.setAttribute("heartRate", heartInfo);
/*double weight = apiClientService.getClient().getWeight(new LocalUserDetail(resourceCredentials.getLocalUserId()), new FitbitUser("-"), new LocalDate(2012,5,5));
request.setAttribute("weight", weight);*/
// get BodyInfo (weight, fat, bmi)
Body bodyInfo = apiClientService.getClient().getBody(new LocalUserDetail(resourceCredentials.getLocalUserId()), fitbitUser, new LocalDate(year,month,day));
//BodyWithGoals bodyGoals = apiClientService.getClient().getBodyWithGoals(new LocalUserDetail(resourceCredentials.getLocalUserId()), new FitbitUser("-"), new LocalDate(year,month,day));
request.setAttribute("bodyInfo", bodyInfo);
// get BloodPressure (BP) Info
Bp bloodPressureInfo = apiClientService.getClient().getLoggedBp(new LocalUserDetail(resourceCredentials.getLocalUserId()), fitbitUser, new LocalDate(year,month,day));
request.setAttribute("bloodPressureInfo", bloodPressureInfo);
// forward result to .jsp page
request.getRequestDispatcher("/fitbitApiAuthExample.jsp").forward(request, response);
} catch (FitbitAPIException e) {
throw new ServletException("Exception during getting user info", e);
}
} else {
try {
response.sendRedirect(apiClientService.getResourceOwnerAuthorizationURL(new LocalUserDetail("-"), exampleBaseUrl + "/fitbitApiAuthExample?completeAuthorization="));
} catch (FitbitAPIException e) {
throw new ServletException("Exception during performing authorization", e);
}
}
}
}