List of usage examples for org.json.simple.parser JSONParser parse
public Object parse(Reader in) throws IOException, ParseException
From source file:it.polimi.geinterface.network.MessageUtils.java
/** * Method returning a {@link Set} of oldProperties passing as parameter a message of type {@link MessageType#PROPERTIES_UPDATE} *//*from ww w .ja va2 s . c o m*/ public static JSONObject getOldPropertiesFromMessage(String message) { JSONObject jsonMsg; JSONParser parser = new JSONParser(); MessageType type = getMsgType(message); if (type.ordinal() == MessageType.PROPERTIES_UPDATE.ordinal()) { try { jsonMsg = (JSONObject) parser.parse(message); JSONObject msg = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE); JSONObject jsonEntity = (JSONObject) msg.get(JsonStrings.ENTITY); JSONObject jsonOldProp = (JSONObject) jsonEntity.get(JsonStrings.OLD_PROPERTIES); /* Set<String> oldProperties = new HashSet<String>(); for(Object o : jsonOldProp) if(!o.toString().equals("")) oldProperties.add(o.toString()); */ return jsonOldProp; } catch (ParseException e) { e.printStackTrace(); } } return null; }
From source file:at.ac.tuwien.dsg.rSybl.planningEngine.staticData.ActionEffects.java
public static HashMap<String, List<ActionEffect>> getActionConditionalEffects() { if (applicationSpecificActionEffects.isEmpty() && defaultActionEffects.isEmpty()) { PlanningLogger.logger.info("~~~~~~~~~~Action effects is empty, reading the effects ! "); JSONParser parser = new JSONParser(); try {/* w w w.j ava2 s . c om*/ InputStream inputStream = Configuration.class.getClassLoader() .getResourceAsStream(Configuration.getEffectsPath()); Object obj = parser.parse(new InputStreamReader(inputStream)); JSONObject jsonObject = (JSONObject) obj; for (Object actionName : jsonObject.keySet()) { String myaction = (String) actionName; JSONObject object = (JSONObject) jsonObject.get(myaction); for (Object actions : object.keySet()) { ActionEffect actionEffect = new ActionEffect(); actionEffect.setActionType((String) myaction); actionEffect.setActionName((String) actions); JSONObject scaleinDescription = (JSONObject) object.get(actions); if (scaleinDescription.containsKey("conditions")) { JSONArray conditions = (JSONArray) jsonObject.get("conditions"); for (int i = 0; i < conditions.size(); i++) { actionEffect.addCondition((String) conditions.get(i)); } } String targetUnit = (String) scaleinDescription.get("targetUnit"); actionEffect.setTargetedEntityID(targetUnit); JSONObject effects = (JSONObject) scaleinDescription.get("effects"); for (Object effectPerUnit : effects.keySet()) { //System.out.println(effects.toString()); String affectedUnit = (String) effectPerUnit; JSONObject metriceffects = (JSONObject) effects.get(affectedUnit); for (Object metric : metriceffects.keySet()) { String metricName = (String) metric; try { actionEffect.setActionEffectForMetric(metricName, (Double) metriceffects.get(metricName), affectedUnit); } catch (Exception e) { actionEffect.setActionEffectForMetric(metricName, ((Long) metriceffects.get(metricName)).doubleValue(), affectedUnit); } } } if (applicationSpecificActionEffects.get(actionEffect.getTargetedEntityID()) == null) { List<ActionEffect> l = new ArrayList<ActionEffect>(); l.add(actionEffect); applicationSpecificActionEffects.put(actionEffect.getTargetedEntityID(), l); } else { applicationSpecificActionEffects.get(actionEffect.getTargetedEntityID()) .add(actionEffect); } } } } catch (Exception e) { PlanningLogger.logger.info("~~~~~~~~~~Retrying reading the effects "); parser = new JSONParser(); try { InputStream inputStream = Configuration.class.getClassLoader() .getResourceAsStream(Configuration.getEffectsPath()); Object obj = parser.parse(new InputStreamReader(inputStream)); JSONObject jsonObject = (JSONObject) obj; for (Object actionName : jsonObject.keySet()) { String myaction = (String) actionName; ActionEffect actionEffect = new ActionEffect(); actionEffect.setActionType((String) myaction); actionEffect.setActionName((String) myaction); JSONObject object = (JSONObject) jsonObject.get(myaction); JSONObject metrics = (JSONObject) object.get("effects"); for (Object me : metrics.keySet()) { String metric = (String) me; Double metricEffect = (Double) metrics.get(metric); actionEffect.setActionEffectForMetric(metric, metricEffect, ""); } defaultActionEffects.put(myaction, actionEffect); } } catch (Exception ex) { PlanningLogger.logger .error("Error when reading the effects!!!!!!!!!!!!!!!!!!" + ex.getMessage()); } } } return applicationSpecificActionEffects; }
From source file:it.polimi.diceH2020.plugin.control.FileManager.java
private static boolean setMachineLearningHadoop(InstanceDataMultiProvider data) { // Set mapJobMLProfile - MACHINE LEARNING Map<String, JobMLProfile> jmlMap = new HashMap<String, JobMLProfile>(); JSONParser parser = new JSONParser(); try {// ww w . j av a 2 s.c o m for (ClassDesc cd : Configuration.getCurrent().getClasses()) { Map<String, SVRFeature> map = new HashMap<String, SVRFeature>(); Object obj = parser.parse(new FileReader(cd.getMlPath())); JSONObject jsonObject = (JSONObject) obj; JSONObject parameter = (JSONObject) jsonObject.get("mlFeatures"); Map<String, String> toCheck = cd.getAltDtsmHadoop() .get(cd.getAltDtsmHadoop().keySet().iterator().next()); for (String st : toCheck.keySet()) { if (!st.equals("file")) { if (!parameter.containsKey(st)) { JOptionPane.showMessageDialog(null, "Missing field in machine learning file: " + st + "\n" + "for class: " + cd.getId(), "Error: ", JOptionPane.ERROR_MESSAGE); return false; } } } double b = (double) jsonObject.get("b"); double mu_t = (double) jsonObject.get("mu_t"); double sigma_t = (double) jsonObject.get("sigma_t"); if (!parameter.containsKey("x")) { JOptionPane.showMessageDialog(null, "Missing field in machine learning file: " + "x " + "\n" + "for class: " + cd.getId(), "Error: ", JOptionPane.ERROR_MESSAGE); return false; } if (!parameter.containsKey("h")) { JOptionPane.showMessageDialog(null, "Missing field in machine learning file: " + "h" + "\n" + "for class: " + cd.getId(), "Error: ", JOptionPane.ERROR_MESSAGE); return false; } Iterator<?> iterator = parameter.keySet().iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); if (!toCheck.containsKey(key) && !key.equals("x") && !key.equals("h")) continue; JSONObject locObj = (JSONObject) parameter.get(key); SVRFeature feat = new SVRFeature(); feat.setMu((double) locObj.get("mu")); feat.setSigma((double) locObj.get("sigma")); feat.setW((double) locObj.get("w")); map.put(key, feat); } jmlMap.put(String.valueOf(cd.getId()), new JobMLProfile(map, b, mu_t, sigma_t)); } } catch (Exception e) { e.printStackTrace(); } JobMLProfilesMap jML = JobMLProfilesMapGenerator.build(); jML.setMapJobMLProfile(jmlMap); data.setMapJobMLProfiles(jML); return true; }
From source file:it.polimi.geinterface.network.MessageUtils.java
/** * Method returning the topic to use to send a {@link MessageType#SYNC_RESP} in reply to a corresponding request */// w w w .j a v a 2 s .c o m public static String getRequestTopicFromMessage(String message) { JSONObject jsonMsg; JSONParser parser = new JSONParser(); MessageType type = getMsgType(message); if (type.ordinal() == MessageType.SYNC_REQ.ordinal() || type.ordinal() == MessageType.SYNC_RESP.ordinal()) { try { jsonMsg = (JSONObject) parser.parse(message); JSONObject msg = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE); return (String) msg.get(JsonStrings.TOPIC_REPLY); } catch (ParseException e) { e.printStackTrace(); } } return null; }
From source file:fileoperations.FileOperations.java
public static Object readFromJSONFile(String fileToReadFrom) { loggerObj.log(Level.INFO, "Inside readFromJSONFile method"); JSONParser parser = new JSONParser(); FileReader fileReader = null; try {//from ww w . j av a 2s . co m loggerObj.log(Level.INFO, "file to read from is:" + fileToReadFrom); fileReader = new FileReader(fileToReadFrom); Object obj = parser.parse(fileReader); loggerObj.log(Level.INFO, "JSON Object is validated successfully from" + fileToReadFrom); fileReader.close(); return obj; } catch (IOException ex) { try { loggerObj.log(Level.SEVERE, "Error in reading the JSON from the file " + fileToReadFrom + "\n Exception is: " + ex.toString()); if (fileReader != null) { fileReader.close(); } } catch (IOException ex1) { loggerObj.log(Level.SEVERE, "Error in closing the file after problem in reading the JSON from the file " + fileToReadFrom); } return null; } catch (ParseException ex) { try { loggerObj.log(Level.SEVERE, "Error in validating the JSON from the file" + fileToReadFrom + "Exception " + ex.toString()); if (fileReader != null) { fileReader.close(); } } catch (IOException ex1) { loggerObj.log(Level.SEVERE, "Error in closing the file after problem in parsing the JSON from the file " + fileToReadFrom); } return null; } }
From source file:luceneprueba.utils.FileParser.java
static public void createFilesFromJSONArray() throws IOException { File dir = new File("files/input"); File[] files = dir.listFiles(); if (files == null) { System.out.println("No existe la carpeta \'input\' dentro de la carpeta files."); return;// w w w . j a v a2s .c om } if (files.length == 0) { System.out.println("No hay ningun archivo en la carpeta \'input\' para ser indexado"); return; } BufferedReader br; String fileContent; JSONArray jsonArray = null; JSONParser jsonParser = new JSONParser(); int i = 1; FileWriter datosReviews = null; try { datosReviews = new FileWriter("files/output/datos_reviews.txt"); } catch (IOException ex) { ex.printStackTrace(System.out); } for (File file : files) { if (file.isFile() && file.canRead() && file.getName().endsWith(".txt")) { System.out.println("Leyendo el archivo: " + file.getName()); FileWriter contentReviews; try { br = new BufferedReader(new FileReader(file)); fileContent = br.readLine(); jsonArray = (JSONArray) jsonParser.parse(fileContent); Iterator it = jsonArray.iterator(); DecimalFormat formato = new DecimalFormat("000000"); while (it.hasNext()) { JSONObject json = (JSONObject) it.next(); if (json.get("Genre") != null && json.get("Date") != null) { contentReviews = new FileWriter( "files/output/clasificador/review_clasificador_" + formato.format(i) + ".txt"); datosReviews.write(Integer.toString(i) + "_" + (String) json.get("Date") + "_" + (String) json.get("Genre") + "_" + (String) json.get("Score") + "\n"); contentReviews.write(Integer.toString(i) + " " + (String) json.get("Review")); i++; contentReviews.close(); } } br.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.out); } catch (IOException | ParseException ex) { ex.printStackTrace(System.out); } } } datosReviews.close(); }
From source file:com.fujitsu.dc.common.es.impl.EsIndexImpl.java
/** * ?JSON???????.// www.j av a 2s . co m * @param resPath * @return ???JSON */ private static JSONObject readJsonResource(final String resPath) { JSONParser jp = new JSONParser(); JSONObject json = null; InputStream is = null; try { is = EsIndexImpl.class.getClassLoader().getResourceAsStream(resPath); json = (JSONObject) jp.parse(new InputStreamReader(is, CharEncoding.UTF_8)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { throw new RuntimeException(e); } } } return json; }
From source file:it.polimi.geinterface.network.MessageUtils.java
/** * Method that returns an {@link Entity} from a message, dealing woth different {@link MessageType}. * //from ww w. j a v a2 s. c o m * @param position - possible values are 1 or 2, returning the first or the second {@link Entity} contained in the message. * position = 2 makes sense only in case of {@link MessageType#PROXIMITY_UPDATE}. In case of other {@link MessageType} only * position = 1 can be passed. */ public static Entity getEntityFromMessage(int position, String message) { JSONObject jsonMsg; JSONParser parser = new JSONParser(); MessageType type = getMsgType(message); if (position == 1) { switch (type) { case PROXIMITY_UPDATE: try { jsonMsg = (JSONObject) parser.parse(message); JSONObject msg = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE); JSONObject jsonEntity = (JSONObject) msg.get(JsonStrings.ENTITY_1); return createEntity(type, jsonEntity); } catch (ParseException e) { e.printStackTrace(); } break; case PROPERTIES_UPDATE: case PROX_BEACONS: case SYNC_RESP: case CHECK_IN: case CHECK_OUT: try { jsonMsg = (JSONObject) parser.parse(message); JSONObject msg = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE); JSONObject jsonEntity = (JSONObject) msg.get(JsonStrings.ENTITY); return createEntity(type, jsonEntity); } catch (ParseException e) { e.printStackTrace(); } default: return null; } return null; } if (position == 2) { if (type.ordinal() == MessageType.PROXIMITY_UPDATE.ordinal()) { try { jsonMsg = (JSONObject) parser.parse(message); JSONObject msg = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE); JSONObject jsonEntity = (JSONObject) msg.get(JsonStrings.ENTITY_2); return createEntity(type, jsonEntity); } catch (ParseException e) { e.printStackTrace(); } } return null; } return null; }
From source file:com.fota.Link.sdpApi.java
public static String getCtnInfo(String ncn) throws JDOMException { String resultStr = ""; String logData = ""; try {//w w w . ja v a2 s. c o m String cpId = PropUtil.getPropValue("sdp3g.id"); String cpPw = PropUtil.getPropValue("sdp3g.pw"); String authorization = cpId + ":" + cpPw; logData = "\r\n---------- Get Ctn Req Info start ----------\r\n"; logData += " getCtnRequestInfo - authorization : " + authorization; byte[] encoded = Base64.encodeBase64(authorization.getBytes()); authorization = new String(encoded); String contractType = "0"; String contractNum = ncn.substring(0, 9); String customerId = ncn.substring(10, ncn.length() - 1); JSONObject reqJObj = new JSONObject(); reqJObj.put("transactionid", ""); reqJObj.put("sequenceno", ""); reqJObj.put("userid", ""); reqJObj.put("screenid", ""); reqJObj.put("CONTRACT_NUM", contractNum); reqJObj.put("CUSTOMER_ID", customerId); reqJObj.put("CONTRACT_TYPE", contractType); authorization = "Basic " + authorization; String endPointUrl = PropUtil.getPropValue("sdp.oif555.url"); logData += "\r\n getCtnRequestInfo - endPointUrl : " + endPointUrl; logData += "\r\n getCtnRequestInfo - authorization(encode) : " + authorization; logData += "\r\n getCtnRequestInfo - Content-type : application/json"; logData += "\r\n getCtnRequestInfo - RequestMethod : POST"; logData += "\r\n getCtnRequestInfo - json : " + reqJObj.toString(); logData += "\r\n---------- Get Ctn Req Info end ----------"; logger.info(logData); // connection URL url = new URL(endPointUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", authorization); connection.setRequestProperty("Content-type", "application/json"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); // output DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(reqJObj.toJSONString()); wr.flush(); wr.close(); // input BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine = ""; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONParser jsonParser = new JSONParser(); JSONObject respJsonObject = (JSONObject) jsonParser.parse(response.toString()); // String respTransactionId = (String) respJsonObject.get("transactionid"); // String respSequenceNo = (String) respJsonObject.get("sequenceno"); // String respReturnCode = (String) respJsonObject.get("returncode"); // String respReturnDescription = (String) respJsonObject.get("returndescription"); // String respErrorCode = (String) respJsonObject.get("errorcode"); // String respErrorDescription = (String) respJsonObject.get("errordescription"); String respCtn = (String) respJsonObject.get("ctn"); // String respSubStatus = (String) respJsonObject.get("sub_status"); // String respSubStatusDate = (String) respJsonObject.get("sub_status_date"); resultStr = respCtn; //resultStr = resValue; // resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr"); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return resultStr; }
From source file:it.polimi.geinterface.network.MessageUtils.java
/** * Method returning a list of {@link Entity} objects retrieved from a message having type {@link MessageType#PROX_BEACONS} or * {@link MessageType#SYNC_RESP}//from ww w . ja va2 s . c o m */ public static ArrayList<Entity> getBeaconsFromMsg(String message) { JSONObject jsonMsg; JSONParser parser = new JSONParser(); MessageType type = getMsgType(message); if (type.ordinal() == MessageType.PROX_BEACONS.ordinal() || type.ordinal() == MessageType.SYNC_REQ.ordinal()) try { jsonMsg = (JSONObject) parser.parse(message); JSONObject msg = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE); JSONArray beaconsJsonArray = (JSONArray) msg.get(JsonStrings.BEACONS); ArrayList<Entity> beacons = new ArrayList<>(); for (Object o : beaconsJsonArray) { JSONObject beaconJsonObject = (JSONObject) o; String beaconId = (String) beaconJsonObject.get(JsonStrings.BEACON_ID); String jsonDistance = (String) beaconJsonObject.get(JsonStrings.DISTANCE_RANGE); DistanceRange distance = null; for (DistanceRange d : DistanceRange.values()) if (d.name().equals(jsonDistance)) distance = d; Entity beacon = new Entity.Builder(beaconId, Type.BLE_BEACON).setDistance(distance).build(); beacons.add(beacon); } return beacons; } catch (ParseException e) { e.printStackTrace(); } return null; }