List of usage examples for org.json.simple.parser ParseException getMessage
public String getMessage()
From source file:org.exoplatform.addon.pulse.service.ws.RestActivitiesStatistic.java
private long getTotalPlfDownloadDataFromJson(String json, Date startDate) { Date today = new Date(); Calendar cal = Calendar.getInstance(); cal.clear();//from w ww . j a v a 2s. c o m cal.setTime(today); cal.add(Calendar.DATE, 1); Date nexDate = cal.getTime(); cal.clear(); if (startDate.after(nexDate)) return 0L; // Do not get data of future try { org.json.simple.JSONObject jsonObj = (org.json.simple.JSONObject) JSONValue.parseWithException(json); //in case request to get data in future, return 0 String startDateStr = partString(startDate, "yyyy-MM-dd"); String returnStartDateStr = jsonObj.get("start_date").toString(); if (returnStartDateStr.substring(0, 10).equalsIgnoreCase(startDateStr) == false) { return 0L; } Long total = Long.parseLong(jsonObj.get("total") + ""); return total; } catch (ParseException e) { // TODO Auto-generated catch block LOG.error(e.getMessage()); } catch (Exception e) { LOG.error(e.getMessage()); } return 0l; }
From source file:org.mitre.demo.client.MitreConnectClient.java
@Override public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException { AccessTokenInfo tokenInfo = new AccessTokenInfo(); KeyManagerConfiguration config = KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration(); String introspectionURL = config.getParameter(MITREConstants.INTROSPECTION_URL); //base64_encode(clientid:secret) String introspectionSecret = config.getParameter(MITREConstants.INTROSPECTION_SECRET); HttpPost post = new HttpPost(introspectionURL.trim()); HttpClient client = new DefaultHttpClient(); List<NameValuePair> tokParams = new ArrayList<NameValuePair>(); tokParams.add(new BasicNameValuePair(ResourceConstants.AUTH_TOKEN_PARAM_NAME, accessToken)); post.setHeader(HTTPConstants.HEADER_AUTHORIZATION, ResourceConstants.BASIC_TOKEN_NAME + " " + introspectionSecret.trim()); try {/* www .jav a 2 s . com*/ post.setEntity(new UrlEncodedFormEntity(tokParams, ResourceConstants.UTF8_PARAM_NAME)); log.debug("Sending post request to introspect : " + "Introspect URI = " + introspectionURL + ", Token: " + ResourceConstants.INTROSPECTION_TOKEN); HttpResponse response = client.execute(post); int responseCode = response.getStatusLine().getStatusCode(); log.debug("HTTP Response code : " + responseCode); HttpEntity entity = response.getEntity(); JSONObject parsedObject; BufferedReader reader = new BufferedReader( new InputStreamReader(entity.getContent(), MITREConstants.UTF_8)); try { if (HttpStatus.SC_CREATED == responseCode || HttpStatus.SC_OK == responseCode) { //pass bufferReader object and get read it and retrieve the parsedJson object parsedObject = getParsedObjectByReader(reader); if (parsedObject != null) { Map valueMap = parsedObject; Object value = valueMap.get(ResourceConstants.ACTIVE_PARAM_NAME); Object issuedTime = System.currentTimeMillis() / 1000; Object expiryTime = valueMap.get(ResourceConstants.EXP_PARAM_NAME); if (value != null) { boolean active = Boolean.parseBoolean(value.toString()); log.debug("is token active ? " + active); tokenInfo.setTokenValid((Boolean) valueMap.get(ResourceConstants.ACTIVE_PARAM_NAME)); tokenInfo.setEndUserName((String) valueMap.get("user_id")); tokenInfo.setConsumerKey((String) valueMap.get(ResourceConstants.CLIENT_ID_PARAM_NAME)); tokenInfo.setValidityPeriod(((Long) expiryTime - (Long) issuedTime) * 1000); tokenInfo.setIssuedTime(System.currentTimeMillis()); String scopes[] = new String[] { (String) valueMap.get("scope") }; tokenInfo.setScope(scopes); } } else { handleException("Error while validating access token. Response is empty."); } } else if (HttpStatus.SC_BAD_REQUEST == responseCode || HttpStatus.SC_UNAUTHORIZED == responseCode) { handleFailedResponse(reader, responseCode); } else { handleException("Some thing wrong here when updating resource. Error code" + responseCode); } } catch (ParseException e) { handleException("Error while parsing response json " + e.getMessage(), e); } finally { if (reader != null) { reader.close(); } } } catch (UnsupportedEncodingException e) { handleException("The Character Encoding is not supported. " + e.getMessage(), e); } catch (ClientProtocolException e) { handleException("Error occurred while sending request to introspect URL. " + e.getMessage(), e); } catch (IOException e) { handleException("Error occurred while reading or closing buffer reader. " + e.getMessage(), e); } return tokenInfo; }
From source file:org.netbeans.modules.php.cake3.editor.completion.Parameter.java
private static void loadValues(Map<String, Map<String, Map<String, List<String>>>> map, String resourcePath) { try (InputStream is = ConstantParameter.class.getResourceAsStream(resourcePath)) { try (Reader reader = new InputStreamReader(is, CakePHP3Constants.UTF8)) { JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory() { @Override// www .j a v a2 s . c om public List creatArrayContainer() { return new LinkedList(); } @Override public Map createObjectContainer() { return new LinkedHashMap(); } }; try { map.putAll((Map) parser.parse(reader, containerFactory)); } catch (ParseException e) { LOGGER.log(Level.SEVERE, e.getMessage()); } } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage()); } }
From source file:org.perf.log.logger.PerfLogData.java
public static PerfLogData fromJSON(String messageContent) { PerfLogData perfLogData = new PerfLogData(); JSONObject perfLogDataJSONObj = null; // deserialize the JSON Object JSONParser parser = new JSONParser(); try {/*from www . j a va 2s .com*/ if (messageContent != null) { perfLogDataJSONObj = (JSONObject) parser.parse(messageContent); // transactionStart if (perfLogDataJSONObj.get("txnDate") != null) { java.util.Date timeStamp = new java.util.Date( ((Long) perfLogDataJSONObj.get("txnDate")).longValue()); perfLogData.setTransactionDate(new java.sql.Timestamp(timeStamp.getTime())); } else perfLogData.setTransactionDate(null); // GUID if (perfLogDataJSONObj.get("guid") != null) { perfLogData.setGuid(perfLogDataJSONObj.get("guid").toString()); } else perfLogData.setGuid(null); // SID (Session ID) if (perfLogDataJSONObj.get("sid") != null) { perfLogData.setSessionId(perfLogDataJSONObj.get("sid").toString()); } else perfLogData.setSessionId(null); // THREAD_NAME if (perfLogDataJSONObj.get("threadName") != null) { perfLogData.setThreadName(perfLogDataJSONObj.get("threadName").toString()); } else perfLogData.setThreadName(null); // THREAD_ID if (perfLogDataJSONObj.get("threadId") != null) { perfLogData.setThreadId(perfLogDataJSONObj.get("threadId").toString()); } else perfLogData.setThreadId(null); // cloneName (InstanceName) if (perfLogDataJSONObj.get("cloneName") != null) { perfLogData.setCloneName(perfLogDataJSONObj.get("cloneName").toString()); } else perfLogData.setCloneName(null); // jvmDepth if (perfLogDataJSONObj.get("jvmDepth") != null) { perfLogData.setJvmDepth(((Integer) (perfLogDataJSONObj.get("jvmDepth"))).intValue()); } else perfLogData.setJvmDepth(0); // txnFilterDepth if (perfLogDataJSONObj.get("txnFilterDepth") != null) { perfLogData .setTxnFilterDepth(((Integer) (perfLogDataJSONObj.get("txnFilterDepth"))).intValue()); } else perfLogData.setTxnFilterDepth(0); // serverName if (perfLogDataJSONObj.get("serverName") != null) { perfLogData.setServerName(perfLogDataJSONObj.get("serverName").toString()); } else perfLogData.setServerName(null); // serverIp if (perfLogDataJSONObj.get("serverIp") != null) { perfLogData.setServerIp(perfLogDataJSONObj.get("serverIp").toString()); } else perfLogData.setServerIp(null); // userId if (perfLogDataJSONObj.get("userid") != null) { perfLogData.setUserId(perfLogDataJSONObj.get("userid").toString()); } else perfLogData.setUserId(null); // pageId if (perfLogDataJSONObj.get("txnName") != null) { perfLogData.setTransactionName(perfLogDataJSONObj.get("txnName").toString()); } else perfLogData.setTransactionName(null); // action if (perfLogDataJSONObj.get("subTxnName") != null) { perfLogData.setSubTransactionName(perfLogDataJSONObj.get("subTxnName").toString()); } else perfLogData.setSubTransactionName(null); // txnClass if (perfLogDataJSONObj.get("txnClass") != null) { perfLogData.setTransactionClass(perfLogDataJSONObj.get("txnClass").toString()); } else perfLogData.setTransactionClass(null); // transactionTimeInMilliSeconds if (perfLogDataJSONObj.get("txnTime") != null) { perfLogData.setTransactionTime(((Long) perfLogDataJSONObj.get("txnTime")).longValue()); } else perfLogData.setTransactionTime(0); // get throwableMessage and throwableClass String throwableMessage = (String) perfLogDataJSONObj.get("throwableMessage"); perfLogData.setThrowableMessage(throwableMessage); perfLogData.setThrowableClassName((String) perfLogDataJSONObj.get("throwableClass")); // Transaction Type perfLogData.setTransactionType((String) perfLogDataJSONObj.get("txnType")); // InfoContext String perfLogData.setInfoContextString((String) perfLogDataJSONObj.get("infoCtxStr")); // Message String perfLogData.setMessage((String) perfLogDataJSONObj.get("message")); } } catch (ParseException parseException) { logger.error("JSON Parser Exception" + parseException.getMessage()); // parseException.printStackTrace(); } return perfLogData; }
From source file:org.PrimeSoft.MCPainter.utils.HttpUtils.java
public static JSONObject downloadJson(String url) { String content = downloadPage(url); if (content == null || content.isEmpty()) { return null; }/*w w w .j a v a 2s. c o m*/ try { return (JSONObject) JSONValue.parseWithException(content); } catch (ParseException e) { MCPainterMain.log("Unable to parse JSON for " + url + " " + e.getMessage()); return null; } }
From source file:org.ScripterRon.JavaBitcoin.RpcHandler.java
/** * Handle a JSON-RPC request//from www. j av a 2 s. c o m * * @param exchange HTTP exchange * @throws IOException I/O exception * @return The response in JSON format */ private String processRequest(HttpExchange exchange) throws IOException { String method = ""; Object params = null; Object id = null; Object result = null; int errorCode = 0; String errorMessage = ""; // // Parse the request // try (InputStreamReader in = new InputStreamReader(exchange.getRequestBody(), "UTF-8")) { JSONParser parser = new JSONParser(); Object object = parser.parse(in); if (object == null || !(object instanceof JSONObject)) { errorCode = RPC_INVALID_REQUEST; errorMessage = "The request must be a JSON structured object"; } else { JSONObject request = (JSONObject) object; object = request.get("method"); if (object == null || !(object instanceof String)) { errorCode = RPC_INVALID_REQUEST; errorMessage = "The request must include the 'method' field"; } else { method = (String) object; params = request.get("params"); id = request.get("id"); } } } catch (ParseException exc) { errorCode = RPC_INVALID_REQUEST; errorMessage = String.format("Parse exception: Position %d, Code %d", exc.getPosition(), exc.getErrorType()); log.error(errorMessage); } catch (Throwable exc) { errorCode = RPC_INTERNAL_ERROR; errorMessage = "Unable to parse request"; log.error(errorMessage, exc); } // // Process the request // if (errorCode == 0) { try { switch (method.toLowerCase()) { case "getinfo": result = getInfo(); break; case "getlog": result = getLog(); break; case "getpeerinfo": result = getPeerInfo(); break; case "getblock": result = getBlock(params); break; case "getblockhash": result = getBlockHash(params); break; case "getstacktraces": result = getStackTraces(); break; default: errorCode = RPC_METHOD_NOT_FOUND; errorMessage = String.format("Method '%s' is not recognized", method); } } catch (BlockStoreException exc) { errorCode = RPC_DATABASE_ERROR; errorMessage = "Unable to access database"; } catch (RequestException exc) { errorCode = exc.getCode(); errorMessage = exc.getMessage(); } catch (IllegalArgumentException exc) { errorCode = RPC_INVALID_PARAMETER; errorMessage = exc.getMessage(); } } // // Return the response // JSONObject response = new JSONObject(); if (errorCode != 0) { JSONObject error = new JSONObject(); error.put("code", errorCode); error.put("message", errorMessage); response.put("error", error); } else { response.put("result", result); } if (id != null) response.put("id", id); return response.toJSONString(); }
From source file:org.talend.components.splunk.runtime.TSplunkEventCollectorWriter.java
private void handleResponse(String jsonResponseString) throws IOException { if (jsonResponseString == null || jsonResponseString.trim().isEmpty()) { throw new IOException(getMessage("error.emptyResponse")); }/*from w ww . j av a 2 s . c o m*/ try { JSONParser jsonParser = new JSONParser(); JSONObject json = (JSONObject) jsonParser.parse(jsonResponseString); LOGGER.debug("Response String:/r/n" + String.valueOf(json)); lastErrorCode = ((Long) json.get("code")).intValue(); lastErrorMessage = (String) json.get("text"); if (lastErrorCode != 0) { throw new IOException(getMessage("error.codeMessage", lastErrorCode, lastErrorMessage)); } successCount += splunkObjectsForBulk.size(); } catch (ParseException e) { throw new IOException(getMessage("error.responseParseException", e.getMessage())); } }
From source file:org.wso2.das.javaagent.worker.AgentConnectionWorker.java
/** * Obtain the current schema and obtain the key set of schema using JSON parser. * /*from www . ja v a 2s.c o m*/ * @param currentSchema current schema of the persisted table * @throws InstrumentationAgentException */ @SuppressWarnings("unchecked") public void filterCurrentSchemaFields(String currentSchema) throws InstrumentationAgentException { try { JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(currentSchema); JSONObject keys = (JSONObject) json.get("columns"); Set keySet = keys.keySet(); Iterator i = keySet.iterator(); while (i.hasNext()) { setCurrentSchemaFieldsSet(String.valueOf(i.next())); } } catch (ParseException e) { throw new InstrumentationAgentException("Failed to obtain fields in current schema : " + e.getMessage(), e); } }
From source file:pl.nask.hsn2.service.JsonRenderingResultTest.java
/** * Performs validation.//from w w w . j a v a 2 s. com */ @Test public final void validate() { try { fullJsonResult.validate(); } catch (ParseException e) { Assert.fail(e.getMessage()); } }
From source file:rs.htec.rest.entities.services.FileUpload.java
@POST @Path("/upload-on-server") @Consumes("multipart/form-data") public Response uploadFileOnServer(MultipartFormDataInput slika) throws IOException { // @MultipartForm FileUploadForm form2 HttpClient client = new DefaultHttpClient(); try {/*from w w w . j av a 2 s.c o m*/ HttpPost post = new HttpPost(KeycloakUriBuilder.fromUri("http://10.10.0.40:8080/auth") .path(ServiceUrlConstants.TOKEN_PATH).build("demo")); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("username", "marko@htec.rs")); formparams.add(new BasicNameValuePair("password", "mikimaus8")); formparams.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, "password")); formparams.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, "RESTEasyTestPublic")); UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8"); post.setEntity(form); HttpResponse response = client.execute(post); int status = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (status != 200) { String json = getContent(entity); throw new IOException("Bad status: " + status + " response: " + json); } if (entity == null) { throw new IOException("No Entity"); } String json = getContent(entity); JSONParser parser = new JSONParser(); JSONObject job = (JSONObject) parser.parse(json); System.out.println("JSON *************** " + json); // HttpPost post2 = new HttpPost("http://10.10.0.40:8080/RESTEasyTest/rest/multipart/upload"); // saljiSliku.setHeader("Authorization", "bearer " + (String) job.get("access_token")); return Response.ok().entity("").build(); } catch (ParseException ex) { Logger.getLogger(FileUpload.class.getName()).log(Level.SEVERE, null, ex); return Response.ok().entity(ex.getMessage()).build(); } finally { client.getConnectionManager().shutdown(); } }