I have Azure logic app with request trigger. I want to trigger this logic app from my java application. So, I am trying to call the request trigger url from my java API.
It is working fine if i am using DefaultHttpClient but getting 401 on calling it using RestTemplate in java.
DefaultHttpClient code:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(
"{url of azure logic app trigger}");
//StringEntity input = new StringEntity("{\"qty\":100,\"name\":\"iPad 4\"}");
//input.setContentType("application/json");
//postRequest.setEntity(input);
HttpResponse response = httpClient.execute(getRequest);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
return("Success");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return("Error");
} catch (UnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return("Error");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return("Error");
}
RestTemplate Code
#Service
public class SampleService {
#Autowired HttpClientService<String, String> httpClientService;
public String callURL() {
ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
#Override
public boolean hasError(ClientHttpResponse response) throws IOException {
System.out.print(response.toString());
return false;
}
#Override
public void handleError(ClientHttpResponse response) throws IOException {
// TODO Auto-generated method stub
}
};
UriComponentsBuilder builder = UriComponentsBuilder
.fromUriString("{logic app url}")
// Add query parameter
.queryParam("api-version", {api-version})
.queryParam("sp", {sp})
.queryParam("sv", {sv})
.queryParam("sig",{sig});
RequestDetailsDAO requestDetails = new RequestDetailsDAO(builder.build().toUri().toString(), HttpMethod.GET);
String response = httpClientService.execute(requestDetails, null, responseErrorHandler, String.class);
return response.toString();
HttpClientService.java
#Service
public class HttpClientService<T, V> {
public RestTemplate restTemplate;
public HttpClientService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(5)).build();
}
public V execute(RequestDetailsDAO requestDetails, HttpEntity<T> entity, ResponseErrorHandler errorHandler,
Class<V> genericClass) {
restTemplate.setErrorHandler(errorHandler);
ResponseEntity<V> response = restTemplate.exchange(requestDetails.getUrl(), requestDetails.getRequestType(), entity, genericClass);
return response.getBody();
}
}
RequestDetailsDAO.java
public class RequestDetailsDAO {
private String url;
private HttpMethod requestType;
public RequestDetailsDAO(String url, HttpMethod requestTyp) {
super();
this.url = url;
this.requestType = requestTyp;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public HttpMethod getRequestType() {
return requestType;
}
public void setRequestType(HttpMethod requestType) {
this.requestType = requestType;
}
#Override
public String toString() {
return "RequestDetails [url=" + url + ", requestType=" + requestType + "]";
}
}
So, it seems that there's nothing special about LogicApps being called using RestTemplate.
It's just that RestTemplate by default URL encode the Uri given in parameter, and DefaultHttpClient does not - reference: apache vs resttemplate
In case of LogicApp URL, there is this "sp" parameter which is already URL endcoded, when you copy it from LogicApp -
"%2Ftriggers%2Fmanual%2Frun", so you need to decode that and pass "/triggers/manual/run" to UriComponentsBuilder. And then it works.
My code:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> request = new HttpEntity<>(requestDto, headers);
UriComponentsBuilder builder = UriComponentsBuilder
.fromUriString("https://prod-123901.westeurope.logic.azure.com:443/workflows/<workflow_id>/triggers/manual/paths/invoke")
.queryParam("api-version", "2016-10-01")
.queryParam("sp", "/triggers/manual/run")
.queryParam("sv", "1.0")
.queryParam("sig", "<your_sig>");
restTemplate.exchange(builder.build().toUri().toString(), HttpMethod.POST, request, Void.class);
update:
requestDto here is your custom dto object that goes in HTTP Body, like for example object of class:
public class RequestDto {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Please try with the simple standalone code with RestTemplate and check. I provide below small snippet.
try {
ResponseEntity<ResponseVO> response = restTemplate.exchange({uri of azure logic app trigger}, HttpMethod.GET, request, ResponseVO.class);
} catch (HttpStatusCodeException ex) {
int statusCode = ex.getStatusCode().value();
System.out.println("Status Code :"+statusCode);
ResponseEntity<?> resEntity = ResponseEntity.status(ex.getRawStatusCode()).headers(ex.getResponseHeaders())
.body(ex.getResponseBodyAsString())
}
Here ResponseVO.class is the Response to be mapped to an object, in this case, you can set your own class. In this catch block, you can find the exception details.
My webservice resource that expects a GET:
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/status")
public Response checkNode() {
boolean status = !NlpHandler.getHandlerQueue().isEmpty();
status = status || !NlpFeeder.getInstance().getFiles().isEmpty();
int statusCode = status ? 200 : 420;
LOG.debug(
"checking status - status: " + statusCode
+ ", node: " + this.context.getAbsolutePath()
);
return Response.status(statusCode).build();
}
The associated client:
public class NodeClient {
private final Client client;
private final WebTarget webTarget;
public NodeClient(String uri) {
this.uri = "some uri";
client = ClientBuilder.newCLient();
webTarget = client.target(uri);
public synchronized boolean checkNode() throws IOException {
String path = "status";
Response response = webTarget
.path(path)
.request(MediaType.APPLICATION_JSON)
.get(Response.class);
int responseCode = response.getStatus();
boolean success = responseCode == 200;
if (!success && responseCode != 420) {
checkResponse(response);
}
return success;
}
}
In my test, I get a nullpointer at int responseCode = response.getStatus() and I'm fairly sure i'm not getting the response in the right way with webTarget. It looks like i'm able to do so correctly with POST responses but not when it's expecting a GET.
#Test
public void testCheckNode() throws Exception {
Response response = Mockito.mock(Response.class);
Mockito
.doReturn(response)
.when(builder)
.get();
NodeClient nodeClient;
Mockito
.doReturn(200)
.when(response)
.getStatus();
try {
boolean success = nodeClient.checkNode();
Assert.assertTrue(success);
} catch (IOException ex) {
Assert.fail("No exception should have been thrown");
}
}
Any ideas why i'm getting a null response?
I think my client clode is fine apparently, the test was wrong. Originally I was mocking the Response class, now I spied it instead and made the mock return the spy of Response.ok().build()) and that fixed my problem.
#Test
public void testCheckNode() throws Exception {
response = Mockito.spy(Response.class);
Mockito
.doReturn(Mockito.spy(Response.ok().build()))
.when(builder)
.get(Response.class);
NodeClient nodeClient;
PowerMockito
.doNothing()
.when(nodeClient, "handleResponse", Mockito.any());
try {
boolean success = nodeClient.checkNode();
Assert.assertTrue(success);
} catch (IOException ex) {
Assert.fail("No exception should have been thrown");
}
}
I have the method:
public HTTPResult get(String url) throws Exception{
try {
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return new HTTPResult(response.getBody(), response.getStatusCode().value());
}
catch (ResourceAccessException e) {
String responseBody = e.getCause().getMessage();
JSONObject obj = new JSONObject(responseBody);
return new HTTPResult(obj.getString("responseBody"), Integer.parseInt(obj.getString("statusCode")));
}
}
I want to do unit testing for it and i am not sure how to proceed:
public class MockHttpServerTest {
private static final int PORT = 51234;
private static final String baseUrl = "http://localhost:" + PORT;
private MockHttpServer server;
private SimpleHttpResponseProvider responseProvider;
private HttpClient client;
#Before
public void setUp() throws Exception {
responseProvider = new SimpleHttpResponseProvider();
server = new MockHttpServer(PORT, responseProvider);
server.start();
client = new DefaultHttpClient();
}
I am getting RED for MockHttpServer & SimpleHttpResponseProvider which should be part of org.apache.wink.client.*; which i am importing. so why do i have red ones? is there some simple way to unit test it?
HTTPResult return me response code and message.
I'm trying to tie Google's Firebase Messaging platform into my app, and I'm trying to use Spring's built in RestTemplate REST abstraction to simplify it.
I'm currently trying to:
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Authorization", "key=" + Constants.FIREBASE_SERVER_KEY);
headers.add("Content-Type", "application/json");
HttpEntity<FireBasePost> entity = new HttpEntity<>(fbp, headers);
URI uri;
uri = new URI(firebaseApi);
FireBaseResponse fbr = restTemplate.postForObject(uri, entity, FireBaseResponse.class);
The FireBasePost object just contains the required fields for the POST Message API: Firebase API - and I have verified the request Entity works by posting with String.class, so the response is unmarshalled JSON.
However, with trying to get the response to marshall directly into the FireBaseResponse object, the call to postForObject hangs and never returns.
#JsonIgnoreProperties(ignoreUnknown = true)
public class FireBaseResponse {
public Integer multicast_id;
public Integer success;
public Integer failure;
public Integer canonical_ids;
public FireBaseResponse() {}
}
I'm having trouble understanding why this call never completes. I would love to be able to have the response directly into an object.
try like this:
package yourpackage;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class FirebaseResponse {
private long multicast_id;
private Integer success;
private Integer failure;
private Object canonical_ids;
public FirebaseResponse() {
}
//---- use this one ----
public boolean is_success() {
if (getSuccess() == 1) {
return true;
} else {
return false;
}
}
public long getMulticast_id() {
return multicast_id;
}
public void setMulticast_id(long multicast_id) {
this.multicast_id = multicast_id;
}
public Integer getSuccess() {
return success;
}
public void setSuccess(Integer success) {
this.success = success;
}
public Integer getFailure() {
return failure;
}
public void setFailure(Integer failure) {
this.failure = failure;
}
public Object getCanonical_ids() {
return canonical_ids;
}
public void setCanonical_ids(Object canonical_ids) {
this.canonical_ids = canonical_ids;
}
#Override
public String toString() {
return "FirebaseResponse{" +
"multicast_id=" + multicast_id +
", success=" + success +
", failure=" + failure +
", canonical_ids=" + canonical_ids +
'}';
}
}
//--------------- USAGE ------------------
ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new HeaderRequestInterceptor("Authorization", "key=" + FIREBASE_SERVER_KEY));
interceptors.add(new HeaderRequestInterceptor("Content-Type", "application/json"));
restTemplate.setInterceptors(interceptors);
JSONObject body = new JSONObject();
// JsonArray registration_ids = new JsonArray();
// body.put("registration_ids", registration_ids);
body.put("to", "cfW930CZxxxxxxxxxxxxxxxxxxxxxxxxxxipdO-bjHLacHRqQzC0aSXlRFKdMHv_aNBxkRZLNxxxxxxxxxxx59sPW4Rw-5MtwKkZxxxxxxxgXlL-LliJuujPwZpLgLpji_");
body.put("priority", "high");
// body.put("dry_run", true);
JSONObject notification = new JSONObject();
notification.put("body", "body string here");
notification.put("title", "title string here");
// notification.put("icon", "myicon");
JSONObject data = new JSONObject();
data.put("key1", "value1");
data.put("key2", "value2");
body.put("notification", notification);
body.put("data", data);
HttpEntity<String> request = new HttpEntity<>(body.toString());
FirebaseResponse firebaseResponse = restTemplate.postForObject("https://fcm.googleapis.com/fcm/send", request, FirebaseResponse.class);
log.info("response is: " + firebaseResponse.toString());
return new ResponseEntity<>(firebaseResponse.toString(), HttpStatus.OK);
//--------------- HELPER CLASS ------------------
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;
import java.io.IOException;
public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {
private final String headerName;
private final String headerValue;
public HeaderRequestInterceptor(String headerName, String headerValue) {
this.headerName = headerName;
this.headerValue = headerValue;
}
#Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpRequest wrapper = new HttpRequestWrapper(request);
wrapper.getHeaders().set(headerName, headerValue);
return execution.execute(wrapper, body);
}
}
Im getting a not so rare error, which happens to many, the thing is that im not using threads in my app. Its just a loop, one task after the other, so i dont understand why im getting out of threads.
Basically for each line of the text file i make a GET request to an api, so i obtain some json data...
Here is the error log:
106
105
104
103
102
ene 06, 2016 4:08:39 PM org.jboss.netty.channel.DefaultChannelFuture
ADVERTENCIA: An exception was thrown by ChannelFutureListener.
java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:714)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:950)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1368)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.start(AbstractNioWorker.java:160)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.executeInIoThread(AbstractNioWorker.java:306)
at org.jboss.netty.channel.socket.nio.NioWorker.executeInIoThread(NioWorker.java:38)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.executeInIoThread(AbstractNioWorker.java:290)
at org.jboss.netty.channel.socket.nio.NioWorker.executeInIoThread(NioWorker.java:38)
at org.jboss.netty.channel.socket.nio.AbstractNioChannelSink.execute(AbstractNioChannelSink.java:34)
at org.jboss.netty.channel.Channels.fireExceptionCaughtLater(Channels.java:504)
at org.jboss.netty.channel.AbstractChannelSink.exceptionCaught(AbstractChannelSink.java:47)
at org.jboss.netty.channel.Channels.close(Channels.java:821)
at org.jboss.netty.channel.AbstractChannel.close(AbstractChannel.java:194)
at org.jboss.netty.channel.ChannelFutureListener$2.operationComplete(ChannelFutureListener.java:52)
at org.jboss.netty.channel.DefaultChannelFuture.notifyListener(DefaultChannelFuture.java:399)
at org.jboss.netty.channel.DefaultChannelFuture.notifyListeners(DefaultChannelFuture.java:385)
at org.jboss.netty.channel.DefaultChannelFuture.setFailure(DefaultChannelFuture.java:352)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.connect(NioClientSocketPipelineSink.java:404)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.processSelectedKeys(NioClientSocketPipelineSink.java:361)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.run(NioClientSocketPipelineSink.java:277)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
ERROR en getML():/orders/1045232034
com.mercadolibre.sdk.MeliException: java.util.concurrent.ExecutionException: java.net.ConnectException: unable to create new native thread to https://api.mercadolibre.com/orders/1045232034?access_token=APP_USR-1978251743308541-010613-c60e34a2a34d0fd5b8c936ccfb3e3732__K_I__-113746522
at com.nubimedia.app.ml.Melis.get(Melis.java:264)
at com.nubimedia.app.ml.Melis.getML(Melis.java:168)
at com.nubimedia.app.ModelML.encontrarMailsLog(ModelML.java:217)
at com.nubimedia.app.Pruebas.main(Pruebas.java:11)
Caused by: java.util.concurrent.ExecutionException: java.net.ConnectException: unable to create new native thread to https://api.mercadolibre.com/orders/1045232034?access_token=APP_USR-1978251743308541-010613-c60e34a2a34d0fd5b8c936ccfb3e3732__K_I__-113746522
at com.ning.http.client.providers.netty.NettyResponseFuture.abort(NettyResponseFuture.java:297)
at com.ning.http.client.providers.netty.NettyConnectListener.operationComplete(NettyConnectListener.java:104)
at org.jboss.netty.channel.DefaultChannelFuture.notifyListener(DefaultChannelFuture.java:399)
at org.jboss.netty.channel.DefaultChannelFuture.notifyListeners(DefaultChannelFuture.java:390)
at org.jboss.netty.channel.DefaultChannelFuture.setFailure(DefaultChannelFuture.java:352)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.connect(NioClientSocketPipelineSink.java:404)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.processSelectedKeys(NioClientSocketPipelineSink.java:361)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.run(NioClientSocketPipelineSink.java:277)
at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: unable to create new native thread to https://api.mercadolibre.com/orders/1045232034?access_token=APP_USR-1978251743308541-010613-c60e34a2a34d0fd5b8c936ccfb3e3732__K_I__-113746522
at com.ning.http.client.providers.netty.NettyConnectListener.operationComplete(NettyConnectListener.java:100)
... 10 more
Caused by: java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:714)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:950)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1368)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.start(AbstractNioWorker.java:160)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.register(AbstractNioWorker.java:131)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.connect(NioClientSocketPipelineSink.java:401)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.processSelectedKeys(NioClientSocketPipelineSink.java:361)
at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink$Boss.run(NioClientSocketPipelineSink.java:277)
... 3 more
Hubo un error
101
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:714)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:950)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1368)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at com.ning.http.client.providers.jdk.JDKAsyncHttpProvider.execute(JDKAsyncHttpProvider.java:159)
at com.ning.http.client.providers.jdk.JDKAsyncHttpProvider.execute(JDKAsyncHttpProvider.java:121)
at com.ning.http.client.AsyncHttpClient.executeRequest(AsyncHttpClient.java:512)
at com.ning.http.client.AsyncHttpClient$BoundRequestBuilder.execute(AsyncHttpClient.java:234)
at com.nubimedia.app.ml.Melis.get(Melis.java:262)
at com.nubimedia.app.ml.Melis.getML(Melis.java:168)
at com.nubimedia.app.ModelML.encontrarMailsLog(ModelML.java:217)
at com.nubimedia.app.Pruebas.main(Pruebas.java:11)
And here is the code:
public static void main(String[] args) throws IOException, MeliException {
ModelML.getInstance().encontrarMailsLog(731);
}
public void encontrarMailsLog(int max) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("/Users/fabrizioguespe/Downloads/catalina.out"));
Set<String> resources=new TreeSet<String>();
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if(line.equals("Nueva Request!")){
String cliente=br.readLine();
String resource=br.readLine();
resources.add(cliente+"-"+resource);
}
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
} finally {
br.close();
}
Log.log(resources.size()+" Para procesar");
int i=resources.size();
for(String s: resources){
i--;
Log.log(i+"");
if(max>0)
if(i>max)continue;
String cliente=s.split("-")[0];
String resource=s.split("-")[1];
//Log.log("Cliente: "+cliente+" "+resource);
ModelML.getInstance().procesarRequest(Melis.getML(resource, null,cliente,false),resource);
}
}
UPDATED: As suggested, and makes sense. I may be doing async request, using the SDK provided by the API
Here is the class
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.mercadolibre.sdk.AuthorizationFailure;
import com.mercadolibre.sdk.MeliException;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.Response;
import com.nubimedia.app.ModelML;
import com.nubimedia.app.util.HibernateUtil;
import com.nubimedia.app.util.Log;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class Melis {
public static String apiUrl = "https://api.mercadolibre.com";
private String accessToken;
private String refreshToken;
private Long clientId;
private String clientSecret;
//public static Map<String,UserML> clientes=new HashMap<String,UserML>();
public static UserML getCliente(String id) {//Solo para inicializar la aplicacion
Session s=HibernateUtil.getSessionFactory().openSession();
s.beginTransaction();
Query query = s.createQuery("from UserML where id = :id");
query.setString("id", id);
UserML q = (UserML) query.uniqueResult();
s.flush();
s.getTransaction().commit();
s.close();
return q;
}
public static List<UserML> getClientes() {
Session s=HibernateUtil.getSessionFactory().openSession();
s.beginTransaction();
Query query = s.createQuery("from UserML");
#SuppressWarnings("unchecked")
List<UserML> q = (List<UserML>) query.list();
s.flush();
s.getTransaction().commit();
s.close();
return q;
}
public static String preguntarML(String item,String pregunta,String idcliente){
UserML cliente=getCliente(idcliente);
if(cliente==null)return null;
Melis m = new Melis(Long.parseLong(ModelML.ml_appid),ModelML.ml_secret,cliente.getToken(),cliente.getToken());
String params="{\"text\":\""+pregunta.trim()+"\",\"item_id\":\""+item+"\"}";
String json=Melis.postML("/questions/"+item+"?access_token="+m.getAccessToken(), null, cliente, params);
return json;
}
public static String postML(String resource,FluentStringsMap params,UserML cliente,String json){
try {
Melis m = new Melis(Long.parseLong(ModelML.ml_appid),ModelML.ml_secret,cliente.getToken(),cliente.getRefresh_token());
if(params==null){
params = new FluentStringsMap();
params.add("access_token", m.getAccessToken());
}
Response respuesta = m.post(resource, params,json);
String jsons=respuesta.getResponseBody();
//jsons=new String(json.getBytes("ISO-8859-1"),"UTF-8");
return jsons;
} catch (Exception e) {
Log.log("ERROR en getML():"+resource);
e.printStackTrace();
}
return null;
}
public static String getUserId(String json){
try{
JsonParser parser = new JsonParser();
JsonObject venta= (JsonObject)parser.parse(json);
if(venta.isJsonNull())return null;
return venta.get("id").getAsString();
}catch(Exception e){
e.printStackTrace();
Log.log("ERROR al parsear json VENTA mercadolibre: ");
}
return null;
}
public static String setToken(String token,String refresh_token,String idcliente) {
UserML a=getCliente(idcliente);
if(a==null)return null;
a.setToken(token);
a.setRefresh_token(refresh_token);
a.setLast_modif(new Date());
Session s=HibernateUtil.getSessionFactory().openSession();
s.beginTransaction();
s.saveOrUpdate(a);
s.flush();
s.getTransaction().commit();
s.close();
return null;
}
public static String getML2(String resource){
Client client = Client.create();
WebResource webResource = client.resource(apiUrl+resource);
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
if (response.getStatus() != 200)
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
return response.getEntity(String.class);
}
public static String remokeAccess(String idcliente){
try {
UserML cliente=getCliente(idcliente);
if(cliente==null)return null;
String resource="/users/"+cliente+"/applications/"+ModelML.ml_appid+"?access_token="+cliente.getToken();
Melis m = new Melis(Long.parseLong(ModelML.ml_appid),ModelML.ml_secret,cliente.getToken());
FluentStringsMap params = new FluentStringsMap();
params.add("access_token", m.getAccessToken());
Response respuesta = m.delete(resource, params);
String json=respuesta.getResponseBody();
json=new String(json.getBytes("ISO-8859-1"),"UTF-8");
return json;
} catch (Exception e) {
Log.log("ERROR en removkeAccess():"+idcliente);
e.printStackTrace();
}
return null;
}
public static String getML(String resource,FluentStringsMap params,String idcliente,boolean access_final){
try {
UserML cliente=getCliente(idcliente);
if(cliente==null)return null;
Melis m = new Melis(Long.parseLong(ModelML.ml_appid),ModelML.ml_secret,cliente.getToken(),cliente.getRefresh_token());
if(params==null){
params = new FluentStringsMap();
params.add("access_token", m.getAccessToken());
}
if(access_final)resource+="?access_token="+cliente.getToken();
Response respuesta = m.get(resource, params);
String json=respuesta.getResponseBody();
json=new String(json.getBytes("ISO-8859-1"),"UTF-8");
return json;
} catch (Exception e) {
Log.log("ERROR en getML():"+resource);
e.printStackTrace();
}
return null;
}
private AsyncHttpClient http;
{
AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder()
.setUserAgent("MELIJAVASDK0.0.1").build();
http = new AsyncHttpClient(cf);
}
public Melis(Long clientId, String clientSecret ) {
this.clientId = clientId;
this.clientSecret = clientSecret;
}
public Melis(Long clientId, String clientSecret, String accessToken) {
this.accessToken = accessToken;
this.clientId = clientId;
this.clientSecret = clientSecret;
}
public Melis(Long clientId, String clientSecret, String accessToken, String refreshToken) {
this.accessToken = accessToken;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.refreshToken = refreshToken;
}
public String getAccessToken() {
return this.accessToken;
}
public Response get(String path) throws MeliException {
return get(path, new FluentStringsMap());
}
private BoundRequestBuilder prepareGet(String path, FluentStringsMap params) {
return http.prepareGet(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params);
}
private BoundRequestBuilder prepareDelete(String path,
FluentStringsMap params) {
return http.prepareDelete(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params);
}
private BoundRequestBuilder preparePost(String path,
FluentStringsMap params, String body) {
return http.preparePost(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params)
.setHeader("ContentType", "application/json").setBody(body)
.setBodyEncoding("UTF8");
}
private BoundRequestBuilder preparePut(String path,
FluentStringsMap params, String body) {
return http.preparePut(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params)
.setHeader("ContentType", "application/json").setBody(body)
.setBodyEncoding("UTF8");
}
private BoundRequestBuilder preparePost(String path, FluentStringsMap params) {
return http.preparePost(apiUrl + path)
.addHeader("Accept", "application/json")
.setQueryParameters(params);
}
public Response get(String path, FluentStringsMap params) throws MeliException {
BoundRequestBuilder r = prepareGet(path, params);
Response response;
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
if (params.containsKey("access_token") && this.hasRefreshToken() && response.getStatusCode() == 401) {
try {
refreshAccessToken();
} catch (AuthorizationFailure e1) {
Log.log("ERROR al refrescar token");
return response;
}
params.replace("access_token", this.accessToken);
r = prepareGet(path, params);
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
}
return response;
}
public void refreshAccessToken() throws AuthorizationFailure {
FluentStringsMap params = new FluentStringsMap();
params.add("grant_type", "refresh_token");
params.add("client_id", String.valueOf(this.clientId));
params.add("client_secret", this.clientSecret);
params.add("refresh_token", this.refreshToken);
BoundRequestBuilder req = preparePost("/oauth/token", params);
parseToken(req);
}
public String getAuthUrl(String callback) {
try {
return "https://auth.mercadolibre.com.ar/authorization?response_type=code&client_id="
+ this.clientId
+ "&redirect_uri="
+ URLEncoder.encode(callback, "UTF8");
} catch (UnsupportedEncodingException e) {
return "https://auth.mercadolibre.com.ar/authorization?response_type=code&client_id="
+ this.clientId + "&redirect_uri=" + callback;
}
}
public String authorize(String code, String redirectUri) throws AuthorizationFailure {
FluentStringsMap params = new FluentStringsMap();
params.add("grant_type", "authorization_code");
params.add("client_id", String.valueOf(this.clientId));
params.add("client_secret", this.clientSecret);
params.add("code", code);
params.add("redirect_uri", redirectUri);
BoundRequestBuilder r = preparePost("/oauth/token", params);
return parseToken(r);
}
private String parseToken(BoundRequestBuilder r) throws AuthorizationFailure {
Response response = null;
String responseBody = "";
try {
response = r.execute().get();
responseBody = response.getResponseBody();
} catch (InterruptedException e) {
throw new AuthorizationFailure(e);
} catch (ExecutionException e) {
throw new AuthorizationFailure(e);
} catch (IOException e) {
throw new AuthorizationFailure(e);
}
JsonParser p = new JsonParser();
JsonObject object;
try {
object = p.parse(responseBody).getAsJsonObject();
} catch (JsonSyntaxException e) {
throw new AuthorizationFailure(responseBody);
}
if (response.getStatusCode() == 200) {
this.accessToken = object.get("access_token").getAsString();
this.refreshToken = object.get("refresh_token").getAsString();
String user_ID = object.get("user_id").getAsString();
Melis.setToken(this.accessToken, this.refreshToken,user_ID);//PERSISTO
return object.toString();
} else return object.get("message").getAsString();
}
private boolean hasRefreshToken() {
return this.refreshToken != null && !this.refreshToken.isEmpty();
}
public Response post(String path, FluentStringsMap params, String body)
throws MeliException {
BoundRequestBuilder r = preparePost(path, params, body);
Response response;
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
if (params.containsKey("access_token") && this.hasRefreshToken() && response.getStatusCode() == 401) {
try {
refreshAccessToken();
} catch (AuthorizationFailure e1) {
return response;
}
params.replace("access_token", this.accessToken);
r = preparePost(path, params, body);
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
}
return response;
}
public Response put(String path, FluentStringsMap params, String body)
throws MeliException {
BoundRequestBuilder r = preparePut(path, params, body);
Response response;
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
if (params.containsKey("access_token") && this.hasRefreshToken()
&& response.getStatusCode() == 401) {
try {
refreshAccessToken();
} catch (AuthorizationFailure e1) {
return response;
}
params.replace("access_token", this.accessToken);
r = preparePut(path, params, body);
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
}
return response;
}
public Response delete(String path, FluentStringsMap params)
throws MeliException {
BoundRequestBuilder r = prepareDelete(path, params);
Response response;
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
if (params.containsKey("access_token") && this.hasRefreshToken()
&& response.getStatusCode() == 401) {
try {
refreshAccessToken();
} catch (AuthorizationFailure e1) {
return response;
}
params.replace("access_token", this.accessToken);
r = prepareDelete(path, params);
try {
response = r.execute().get();
} catch (Exception e) {
throw new MeliException(e);
}
}
return response;
}
public BoundRequestBuilder head(String path) {
return null;
}
public BoundRequestBuilder options(String path) {
return null;
}
}
Disclaimer: AsyncHttpClient author here
First, I don't know why the answer above was validated, it's wrong.
I suspect that you're creating tons of Melis instances. But you completely missed the point that an AsyncHttpClient instance must be used as a singleton (except for very specific use cases).
As every Melis instance creates its own AsyncHttpClient instance, you end up creating tons of them, and you blow off resource usage.
Note that your AsyncHttpClient instance(s) must be closed when you shut your application down so underlying resources get freed.
This is not a memory problem, but an operating system resource problem,this has nothing to do with programming, or linux.