Java Play framework parsing JSON error - java

I want to setup Janrain authentication to my Play! project which is hosted on GAE and uses GAE module. But I get the following error while I try to login:
RuntimeException occured : Cannot parse JSON (check logs)
And Play highlighs the following line as error:
JsonElement rpxJson = rpxRequest.get().getJson();
Here is method that I use for token callback:
public static void tokenCallback(String token) {
Properties p = Play.configuration;
// Try the driver
String rpxApi = p.getProperty("login.rpx.apiKey");
WSRequest rpxRequest = WS.url("http://rpxnow.com/api/v2/auth_info");
// get RPX
rpxRequest.setParameter("token", token);
rpxRequest.setParameter("apiKey", rpxApi);
JsonElement rpxJson = rpxRequest.get().getJson();
JsonElement profile = rpxJson.getAsJsonObject().get("profile");
String identifier = profile.getAsJsonObject().getAsJsonPrimitive("identifier").getAsString();
welcome(identifier);
}
And here is the error that I get from terminal:
Internal Server Error (500) for request POST /login/tokencallback
Execution exception (In /app/controllers/Login.java around line 27)
RuntimeException occured : Cannot parse JSON (check logs)
play.exceptions.JavaExecutionException: Cannot parse JSON (check logs)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:237)
at Invocation.HTTP Request(Play!)
Caused by: java.lang.RuntimeException: Cannot parse JSON (check logs)
at play.libs.WS$HttpResponse.getJson(WS.java:668)
at controllers.Login.tokenCallback(Login.java:27)
at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:557)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:508)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:484)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:479)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:161)
... 1 more
Caused by: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected EOF at line 2 column 1
at com.google.gson.JsonParser.parse(JsonParser.java:65)
at com.google.gson.JsonParser.parse(JsonParser.java:45)
at play.libs.WS$HttpResponse.getJson(WS.java:665)
... 7 more
Caused by: com.google.gson.stream.MalformedJsonException: Expected EOF at line 2 column 1
at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1310)
at com.google.gson.stream.JsonReader.peek(JsonReader.java:390)
at com.google.gson.JsonParser.parse(JsonParser.java:60)
... 9 more
What can I do? Please, help me to solve this problem.
Thanks in advance.

OK, Here is my first suggestion. Try using the HTTPS connection for the URL. I ran into some problems with the HTTP connection. Here is how I do the Janrain connection:
WSRequest rpxRequest = WS.url("https://rpxnow.com/api/v2/auth_info");
// get RPX
rpxRequest.setParameter("token", token);
rpxRequest.setParameter("apiKey", rpxApi);
HttpResponse res = null;
try {
res = rpxRequest.post();
} catch (JavaExecutionException ex) {
Log.error("unknown error ", ex);
Validation.addError("", "Unknown Error: please try again");
Validation.keep();
Secure.login();
} catch (Exception ex) {
Log.error("Most likely SSL error", ex);
Validation.addError("", "SSL Error: please try again");
Validation.keep();
Secure.login();
}
if (res.getStatus() != 200) {
Log.error("status 200 error");
Validation.addError("", "Status 200 error: please try again");
Validation.keep();
Secure.login();
}
JsonElement rpxJson = res.getJson();
JsonElement profile = rpxJson.getAsJsonObject().get("profile");
JsonObject profileJson = profile.getAsJsonObject();

Having called the URL http://rpxnow.com/api/v2/auth_info , it immediately redirects to https://rpxnow.com/api/v2/auth_info (http s ). I suspect you don't get the JSON answer, but a http redirect code in your call to the web service.
Two possibilites:
1) Change the web service call to https://rpxnow.com/api/v2/auth_info , this probably solves your problem, failing that;
2) Change the line JsonElement rpxJson = rpxRequest.get().getJson(); into something like
HttpResponse httpResponse = rpxRequest.get();
Logger.log ( httpResponse.getString() );
if ( httpResponse.success() ) {
JsonElement rpxJson = httpResponse.getJson();
} else {
// fail gracefully
}
and report back on the contents of the answer which gets logged in the second line.

Related

Getting 400 as status code in cosmo DB batch Operation

I am trying to store multiple types of Records in Cosmo DB using batch operation. But I am getting 400 status in CosmoBatchResponse object and errorMessage is null. Internally , one item is giving 400 , all the other operations have a 424 status code (failed dependency). From this [document] https://learn.microsoft.com/en-us/rest/api/cosmos-db/http-status-codes-for-cosmosdb I can see there could be many reason of 400 , but if errorMessage is null then how to find what went wrong . Also , same msg is getting stored via create call ,facing issue while batch save only.
PartitionKey partitionKey = new PartitionKey("customerNo");
CosmosBatch batch = CosmosBatch.createCosmosBatch(partitionKey);
batch.createItemOperation(customer);
I have tried to store via create method only looping on CosmosItemOperation and it is getting stored.
CosmosBatchResponse response=paymentRepository.createBatch(cosmosBatch);
for(CosmosItemOperation itemOp:cosmosBatch.getOperations()) {
System.out.println(paymentRepository.create(itemOp.getItem(),""));// Here it is getting stored.
}
public CosmosBatchResponse createBatch(CosmosBatch cosmosBatch) {
CosmosBatchResponse response = null;
try {
response = container.executeCosmosBatch(cosmosBatch);
System.out.println(response.isSuccessStatusCode()); -- returns false
System.out.println(response.getErrorMessage()); -- returns null
return response;
} catch (final Exception e) {
int statusCode = CosmosUtils.getCosmosStatusCode(e);
if (CONFLICT_RESOURCE == statusCode) {
log.error(
"CosmosCreateDocumentException: Resource already exists for Document : {}",
response.getErrorMessage());
}
shouldRetryOnException(e);
log.error(
"CosmosCreateDocumentException for Document {} - {}, {}", cosmosBatch, e.getMessage(), e);
throw new GenericRepositoryException(e.getMessage(), e);
}
}

Exception in thread "main" java.io.EOFException in Google my business

I am writing a code to extract insights for all the locations according to what is described here:
https://developers.google.com/my-business/content/insight-data?hl=en
Sometimes (and NOT always) while running the code I have this Exception:
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2736)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3211)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:896)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:358)
at com.google.api.client.util.IOUtils.deserialize(IOUtils.java:171)
at com.google.api.client.util.store.FileDataStoreFactory$FileDataStore.<init>(FileDataStoreFactory.java:102)
at com.google.api.client.util.store.FileDataStoreFactory.createDataStore(FileDataStoreFactory.java:73)
at com.google.api.client.util.store.AbstractDataStoreFactory.getDataStore(AbstractDataStoreFactory.java:55)
at com.google.api.client.auth.oauth2.StoredCredential.getDefaultDataStore(StoredCredential.java:171)
at com.google.api.client.auth.oauth2.AuthorizationCodeFlow$Builder.setDataStoreFactory(AuthorizationCodeFlow.java:744)
at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow$Builder.setDataStoreFactory(GoogleAuthorizationCodeFlow.java:209)
Does anyone have any idea how I can fix this? Is it possible that the error is because I have many locations in my account and it is sending too many requests to GMB?
I try to share some abstract parts of the code:
JSONObject jObj=new JSONObject();
ReportLocationInsightsRequest content = new ReportLocationInsightsRequest();
content.setFactory(JSON_FACTORY);
BasicMetricsRequest basicRequest = new BasicMetricsRequest();
content.setLocationNames(locationNamelist); // locationNamelist is provided previousely in another function
List<MetricRequest> metricRequests= new ArrayList<MetricRequest>();
MetricRequest metricR=new MetricRequest();
String metric="ALL";
metricR.setMetric(metric);
metricRequests.add(metricR);
timeRange.setStartTime(MyStartTime); // desired start time
timeRange.setEndTime(MyEndTime); // desired end time
basicRequest.setTimeRange(timeRange);
basicRequest.setMetricRequests(metricRequests);
content.setBasicRequest(basicRequest );
TimeRange timeRange=new TimeRange();
try {
MyBusiness.Accounts.Locations.ReportInsights locationReportInsight=
mybusiness.accounts().locations().reportInsights(accName, content);
ReportLocationInsightsResponse response= locationReportInsight.execute();
jObj=new JSONObject(response);
}catch(Exception e) {
System.out.println(" Exception "+ e);
}
Thank you in advance

Why isn't try/catch Exceptions working for Gson.fromJson()?

I've been getting com.google.gson.JsonSyntaxException from calling Gson.fromJson(), so added a catch(Exception) logic, but the error is never getting caught and just getting thrown!
Here's what I have:
Request request = new Request.Builder()
.url(getOrderUrlWithId)
.get()
.build();
try {
Response response = this.okHttpClient.newCall(request).execute();
GetOrderResult orderResult = gson.fromJson(gson.toJson(response.body().string()), GetOrderResult.class);
response.close();
} catch (IOException e) {
log.error("Error retrieving order : " + e.getMessage(), e);
throw new RuntimeException(e);
} catch (Exception e) {
log.error("Error happening for client PO: " + clientPO, e);
return null;
}
When I run the test I get "com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
"
Why isn't the error getting caught?
Here's the Stack trace:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
at com.google.gson.Gson.fromJson(Gson.java:927)
at com.google.gson.Gson.fromJson(Gson.java:892)
at com.google.gson.Gson.fromJson(Gson.java:841)
at com.google.gson.Gson.fromJson(Gson.java:813)
at com.hub.fulfill.circlegraphics.getOrdersByCgOrderId(CircleGraphicsApi.java:164)
You need to catch JsonSyntaxException like this
For Kotlin
catch(e: JsonSyntaxException){
//show toast/snackabar/log here
}
For Java
catch(JsonSyntaxException e){
//show toast/snackabar/log here
}
Earlier I was also catching java.lang.IllegalStateException but it didn't worked.
Seems the root exception here is JsonSyntaxException and thus, we need to catch this one.
It worked for me!
when(...).thenReturn(null) points that you use some mocking library (jMock, Mockery or simular). And you define that if fromJson("test", Fulfillment.class) is called mock should return null. Actual method fromJson is not invoked as you already defined result.
If you want expection to be thrown, then remove line
when(gson.fromJson("test", Fulfillment.class)).thenReturn(null);
Figured it out. So turns out #Slf4j's log.error() call shows the exception as an error in Google StackDriver, hence telling me I've been getting millions of errors.

program throws CharConversionException in Java?

I am getting the below mentioned error in my catch block when i print using e.printStackTrace();This only occurs for few records when i read it from the DB2 database. So basically only few records throw the error rest work fine.
I have almost 1000 line of code and i am not sure were do i start from in order to understand/debug this error ? IS there any hint that i can get from the error message i should use to solve it ?
from the method getDataFromEMPHCForEmployeeDetails()----- com.ibm.db2.jcc.am.SqlException: [jcc][t4][1065][12306][3.63.123] Caught java.io.CharConversionException. See attached Throwable for details. ERRORCODE=-4220, SQLSTATE=null
at com.ibm.db2.jcc.am.fd.a(fd.java:663)
at com.ibm.db2.jcc.am.fd.a(fd.java:60)
at com.ibm.db2.jcc.am.fd.a(fd.java:112)
at com.ibm.db2.jcc.am.ic.a(ic.java:2820)
at com.ibm.db2.jcc.am.ic.p(ic.java:521)
at com.ibm.db2.jcc.am.ic.N(ic.java:1558)
at com.ibm.db2.jcc.am.vn.e(vn.java:1147)
at com.ibm.db2.jcc.am.vn.getString(vn.java:1122)
at com.ibm.db2.jcc.am.vn.getString(vn.java:1698)
at CreateChart.getDataFromEMPHCForEmployeeDetails(CreateChart.java:330)
at CreateChart.iterateDirectReportNamesFromArrayList(CreateChart.java:594)
at CreateChart.getDataFromEMPHCForDirectReport(CreateChart.java:295)
at CreateChart.iterateSecondLineManagerNamesFromArrayList(CreateChart.java:562)
at CreateChart.getDataFromEMPHCForSecondLine(CreateChart.java:251)
at CreateChart.iterateThirdLineManagerNamesFromArrayList(CreateChart.java:533)
at CreateChart.getDataFromEMPHCForThirdLine(CreateChart.java:208)
at CreateChart.iterateDirectorNamesFromArrayList(CreateChart.java:506)
at CreateChart.getDataFromEMPHCForDirector(CreateChart.java:168)
at CreateChart.iterateVPNamesFromArrayList(CreateChart.java:472)
at CreateChart.getDataFromEMPHCForVp(CreateChart.java:126)
at CreateChart.iterateFuncVPNamesFromArrayList(CreateChart.java:434)
at CreateChart.getDataFromEMPHCForFuncVp(CreateChart.java:95)
at CreateChart.main(CreateChart.java:613)
Caused by: java.nio.charset.MalformedInputException: Input length = 186
at com.ibm.db2.jcc.am.t.a(t.java:19)
at com.ibm.db2.jcc.am.ic.a(ic.java:2816)
... 19 more
Caused by: sun.io.MalformedInputException
at sun.io.ByteToCharUTF8.convert(Unknown Source)
at com.ibm.db2.jcc.am.t.a(t.java:16)
... 20 more
.
public void getDataFromEMPHCForEmployeeDetails(String funcvp_name11, String vp_name11, String director_name11, String thirdline_name11, String secondline_name11, String directreport_name11){
String myQuery11;
if(directreport_name11 == ""){directreport_name11 = " AND DIRECT_REPORT IS NULL";}
else{directreport_name11 =" AND DIRECT_REPORT ='"+ directreport_name11.replace("'", "''")+"'";}
myQuery11 = "SELECT DISTINCT(SERIAL_NUM) FROM DB2INST1.EMP_HC WHERE "+funcvp_name11+" "+vp_name11+" "+director_name11+" "+thirdline_name11+" "+ secondline_name11+""+directreport_name11;
arraylistofEmployeeDetails = new ArrayList<String>();
try {
resultSet = st.executeQuery(myQuery11);
while (resultSet.next())
{
String SERIAL_NUM = resultSet.getString("SERIAL_NUM");
if(SERIAL_NUM == null){SERIAL_NUM="";}
if (SERIAL_NUM.length() > 40){SERIAL_NUM = "Too Long";}
arraylistofEmployeeDetails.add(SERIAL_NUM);
System.out.println(SERIAL_NUM+"\n");
}
if(! (arraylistofEmployeeDetails.isEmpty())){
writeEmployeeDetailsToJsonFile(arraylistofEmployeeDetails);
}
} catch (SQLException e) {
e.printStackTrace();
StringWriter wtr = new StringWriter();
PrintWriter pwtr = new PrintWriter(wtr);
e.printStackTrace(pwtr);
String stackTrace = wtr.toString();
error_logs.append("from getDataFromEMPHCForEmployeeDetails()----- "+stackTrace+"\n");
}
}
I had similar problem with CharConversionException on DB2 jdbc driver with 1.8 Oracle Java with same error code, once updated to a never version it worked fine.
I downloaded db2jcc_license_cu and db2jcc.jar from these links.
Maybe it is worth of trying.
Try adding a JVM parameter -Ddb2.jcc.charsetDecoderEncoder=3, it solved the issue for me.
After setting the parameter db2.jcc.charsetDecoderEncoder=3, an exception will not be thrown when a non-UTF8 character is encountered but rather it will be substituted by its equivalent Unicode replacement character.
See the IBM Support article for more details https://www.ibm.com/support/pages/sqlexception-message-caught-javaiocharconversionexception-and-errorcode-4220

DocumentList API FullTextQuery ServiceException - An unknown error has occured

For some queries I receive this ServiceException after 10 seconds of
waiting for the response.
I also tried with direct http get request and the same result.
Ex: Contract%20Colectiv%20de%20Munc%C4%83
1. My code:
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/ full/folder%3A" + folderId + "/contents/-/pdf");
DocumentQuery query = new DocumentQuery(feedUrl);
query.setFullTextQuery(searchText);
client.setConnectTimeout(0);// with or without this line I receive the same result (I also put 30000 value - same result)
client.setReadTimeout(0);// with or without this line I receive the same result
DocumentListFeed feed = client.getFeed(query, DocumentListFeed.class);
2. This is the stacktrace for the exception that I receive with documentlist api query:
com.google.gdata.util.ServiceException: An unknown error has occurred.
<errors xmlns='http://schemas.google.com/g/2005'>
<error><domain>GData</domain><code>ServiceException</code>
<internalReason>An unknown error has occurred</internalReason>
</error></errors>
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:624)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:563)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java: 552)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java: 530)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
...
3. This is the exception I receive with direct http get request:
java.io.IOException: Server returned HTTP response code: 500 for URL: https://docs.google.com/feeds/default/private/full/folder%3[my_folder_doc-id]/contents/-/pdf?q="[query_text]"&max-results=25
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java: 1436)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java: 379)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java: 318)
at GoogleDocsManager.googleSearch(GoogleDocsManager.java:281)
Additional information:
1. My folder contains almost 300k files. Could this be the problem?
2. In ~85% of searches I get the correct response ()
3. In browser the same interogation returns "The server encountered an error. Please try again later", but after refresh works fine.
Can anyone help me to get a "workaround" for this problem? Or how to
avoid it?
I posted this issue some months ago on documentlist api group but since this group is read-only I can't get any information about this issue.
This is the 500 response I get with direct http request (after ~10 seconds):
<errors xmlns='http://schemas.google.com/g/2005'>
<error>
<domain>GData</domain>
<code>ServiceException</code>
<internalReason>An unknown error has occurred.</internalReason>
</error>
</errors>
This is the code:
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/folder%3A" + folderId + "/contents/-/pdf?max-results=25&q=" + searchText);
HttpURLConnection copyHttpUrlConn = (HttpURLConnection) feedUrl.openConnection();
copyHttpUrlConn.setDoOutput(true);
copyHttpUrlConn.setRequestMethod("GET");
copyHttpUrlConn.setRequestProperty("GData-Version", "3.0");
copyHttpUrlConn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
int respCode = copyHttpUrlConn.getResponseCode();
System.out.println("Response code: " + respCode);
InputStreamReader isr = null;
if(respCode != 200){
isr = new InputStreamReader(copyHttpUrlConn.getErrorStream());
}
else{
isr = new InputStreamReader(copyHttpUrlConn.getInputStream());
}
BufferedReader br = new BufferedReader(isr);
String line = null;
while((line = br.readLine()) != null){
System.out.println(line);
}
Other recent queries with problems:
title:2012-05 "exceptii de neconstitutionalitate penal"
"litigii de munca"
"moş crăciun srl"
"bil terenuri sa bucuresti"
"ordonanta de plata"
As a workaround you can consider fetching the large document list offline using a task queue, and serializing the information you want to display in the datastore.
Using task queue will give you give you automatic retry if there is an error, and up to 10 minutes deadline for the urlfetch and processing deadline.

Categories