Java Code Examples for org.json.simple.parser.ParseException#printStackTrace()

The following examples show how to use org.json.simple.parser.ParseException#printStackTrace() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResponseUtil.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
public static Object getMessagesFromResponse(String responseStr, String node) {
    Object msgObject = null;
    if (responseStr == null || responseStr.equalsIgnoreCase(""))
        return msgObject;
    try {
        JSONObject responseObj = (JSONObject) JSONValue
                .parseWithException(responseStr);
        if (responseObj != null) {
            JSONObject dataObj = (JSONObject) responseObj
                    .get(ConstantsForTest.DATA);
            if (dataObj != null) {
                msgObject = dataObj.get(node);
            }
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return msgObject;
}
 
Example 2
Source File: JSONUtil.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked" })
public static Map<String, Object> string2SortMap(String jsonStr) {
	Map<String, Object> sortMap = new TreeMap<String, Object>(new Comparator<String>() {
		@Override
		public int compare(String o1, String o2) {
			if (o1.toLowerCase().compareTo(o2.toLowerCase()) == 0) {
				return 1;// Avoid being covered, such as h and H
			}
			return o1.toLowerCase().compareTo(o2.toLowerCase());
		}
	});
	try {
		Map<String, Object> genreJsonObject = (Map<String, Object>) JSONValue.parseWithException(jsonStr);
		sortMap.putAll(genreJsonObject);
	} catch (ParseException e) {
		e.printStackTrace();
	}
	return sortMap;
}
 
Example 3
Source File: ResponseUtil.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
public static Object getMessagesFromResponse(String responseStr, String node) {
    Object msgObject = null;
    if (responseStr == null || responseStr.equalsIgnoreCase(""))
        return msgObject;
    try {
        JSONObject responseObj = (JSONObject) JSONValue
                .parseWithException(responseStr);
        if (responseObj != null) {
            JSONObject dataObj = (JSONObject) responseObj
                    .get(ConstantsForTest.DATA);
            if (dataObj != null) {
                msgObject = dataObj.get(node);
            }
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return msgObject;
}
 
Example 4
Source File: BundlesGenerator.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This function performs: 1. Parse the remote's responding result, the result would be like:
 * {"locales":"en, ja, zh_CN","components":"default","bundles":"[{ \"en\":
 * {\"cancel\":\"Abbrechen\"}, \"ja\": {\"cancel\":\"Abbrechen\"}, \"zh_CN\":
 * {\"cancel\":\"Abbrechen\"}, \"component\":\"default\"
 * }]","version":"1.0.0","productName":"devCenter"} 2. Convert the packaged JSON content with
 * multiple component messages to multiple JSO resource files 3. Write the translation to path
 * src-generated/main/resources/l10n/bundles/";
 * 
 * @param remoteRusult the remote's string
 */
public void handleRemoteRusult(String remoteRusult) {
    MultiComponentsDTO baseTranslationDTO = TranslationUtil.getBaseTranslationDTO(remoteRusult);
    List bundles = baseTranslationDTO.getBundles();
    Iterator<?> it = bundles.iterator();
    String jsonFilePathDir = this.getJsonPath(baseTranslationDTO);
    while (it.hasNext()) {
        try {
            JSONObject bundleObj = (JSONObject) JSONValue.parseWithException(it.next()
                    .toString());
            String component = (String) bundleObj.get(ConstantsKeys.COMPONENT);
            List<String> locales = baseTranslationDTO.getLocales();
            String componentPath = jsonFilePathDir + ConstantsChar.BACKSLASH + component;
            new File(componentPath).mkdir();
            for (String locale : locales) {
                String tLocale = StringUtils.trim(locale);
                this.writeToBundle(
                        componentPath + ConstantsChar.BACKSLASH
                                + TranslationUtil.genernateJsonLocalizedFileName(tLocale),
                        component, tLocale, (JSONObject) bundleObj.get(tLocale));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
 
Example 5
Source File: WorldIO.java    From TerraLegion with MIT License 6 votes vote down vote up
public static Player loadPlayer() {
	try {
		FileHandle handle = Gdx.files.external("player.save");
		if (!handle.exists()) {
			// not saved player yet
			return null;
		}

		String JSONString = handle.readString();

		JSONObject playerInfo = (JSONObject) new JSONParser().parse(JSONString);

		JSONObject playerPosition = (JSONObject) playerInfo.get("playerPosition");
		Player player = new Player(Float.parseFloat(playerPosition.get("x").toString()), Float.parseFloat(playerPosition.get("y").toString()));

		JSONObject jsonInventory = (JSONObject) playerInfo.get("playerInventory");

		Inventory inventory = JSONConverter.getInventoryFromJSON(jsonInventory);

		player.setInventory(inventory);
		return player;
	} catch(ParseException ex) {
		ex.printStackTrace();
	}
	return null;
}
 
Example 6
Source File: QSGUtils.java    From product-emm with Apache License 2.0 6 votes vote down vote up
private static ClientCredentials getClientCredentials() {
    ClientCredentials clientCredentials = null;
    HashMap<String, String> headers = new HashMap<String, String>();
    String dcrEndPoint = EMMQSGConfig.getInstance().getDcrEndPoint();
    //Set the DCR payload
    JSONObject obj = new JSONObject();
    obj.put("owner", "admin");
    obj.put("clientName", "qsg");
    obj.put("grantType", "refresh_token password client_credentials");
    obj.put("tokenScope", "user:view,user:manage,user:admin:reset-password,role:view,role:manage,policy:view," +
                          "policy:manage,application:manage,appm:create,appm:publish,appm:update,appm:read");
    //Set the headers
    headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON);
    HTTPResponse httpResponse = HTTPInvoker.sendHTTPPost(dcrEndPoint, obj.toJSONString(), headers);
    if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) {
        try {
            JSONObject jsonObject = (JSONObject) new JSONParser().parse(httpResponse.getResponse());
            clientCredentials = new ClientCredentials();
            clientCredentials.setClientKey((String) jsonObject.get("client_id"));
            clientCredentials.setClientSecret((String) jsonObject.get("client_secret"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return clientCredentials;
}
 
Example 7
Source File: ActionsAWSHandler.java    From dialogflow-webhook-boilerplate-java with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(InputStream inputStream,
                          OutputStream outputStream,
                          Context context) throws IOException {
  BufferedReader reader = new BufferedReader(
          new InputStreamReader(inputStream));
  JSONObject awsResponse = new JSONObject();
  LambdaLogger logger = context.getLogger();
  try {
    JSONObject awsRequest = (JSONObject) parser.parse(reader);
    JSONObject headers = (JSONObject) awsRequest.get("headers");
    String body = (String) awsRequest.get("body");
    logger.log("AWS request body = " + body);

    actionsApp.handleRequest(body, headers)
            .thenAccept((webhookResponseJson) -> {
              logger.log("Generated json = " + webhookResponseJson);

              JSONObject responseHeaders = new JSONObject();
              responseHeaders.put("Content-Type", "application/json");

              awsResponse.put("statusCode", "200");
              awsResponse.put("headers", responseHeaders);
              awsResponse.put("body", webhookResponseJson);
              writeResponse(outputStream, awsResponse);
            }).exceptionally((throwable -> {
      awsResponse.put("statusCode", "500");
      awsResponse.put("exception", throwable);
      writeResponse(outputStream, awsResponse);
      return null;
    }));

  } catch (ParseException e) {
    e.printStackTrace();
  }
}
 
Example 8
Source File: JSONUtil.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Convert Json string to Map<String, Object>
 * @param json
 * @return Map<String, Object> obj
 */
@SuppressWarnings("unchecked")
public static Map<String, Object> getMapFromJson(String json) {
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = getContainerFactory();
    Map<String, Object> result = null;
    try {
        result = (Map<String, Object>) parser.parse(json, containerFactory);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 9
Source File: NotesLoader.java    From MercuryTrade with MIT License 5 votes vote down vote up
public String getVersionFrom(String source) {
    String version = "";
    JSONParser parser = new JSONParser();
    try {
        JSONObject root = (JSONObject) parser.parse(source);
        version = (String) root.get("version");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return version;
}
 
Example 10
Source File: QSGUtils.java    From product-iots with Apache License 2.0 5 votes vote down vote up
private static ClientCredentials getClientCredentials() {
    ClientCredentials clientCredentials = null;
    HashMap<String, String> headers = new HashMap<String, String>();
    EMMQSGConfig emmqsgConfig = EMMQSGConfig.getInstance();
    String dcrEndPoint = emmqsgConfig.getDcrEndPoint();
    //Set the DCR payload
    JSONObject obj = new JSONObject();
    JSONArray arr = new JSONArray();
    arr.add("android");
    arr.add("device_management");
    obj.put("applicationName", "qsg");
    obj.put("tags", arr);
    obj.put("isAllowedToAllDomains", false);
    obj.put("isMappingAnExistingOAuthApp", false);
    String authorizationStr = emmqsgConfig.getUsername() + ":" + emmqsgConfig.getPassword();
    String authHeader = "Basic " + new String(Base64.encodeBase64(authorizationStr.getBytes()));
    headers.put(Constants.Header.AUTH, authHeader);

    //Set the headers
    headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON);
    HTTPResponse httpResponse = HTTPInvoker.sendHTTPPost(dcrEndPoint, obj.toJSONString(), headers);
    if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) {
        try {
            JSONObject jsonObject = (JSONObject) new JSONParser().parse(httpResponse.getResponse());
            clientCredentials = new ClientCredentials();
            clientCredentials.setClientKey((String) jsonObject.get("client_id"));
            clientCredentials.setClientSecret((String) jsonObject.get("client_secret"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return clientCredentials;
}
 
Example 11
Source File: QSGUtils.java    From product-iots with Apache License 2.0 5 votes vote down vote up
public static String getOAuthToken() {
    QSGUtils.initConfig();
    ClientCredentials clientCredentials = getClientCredentials();
    String authorizationStr = clientCredentials.getClientKey() + ":" + clientCredentials.getClientSecret();
    String authHeader = "Basic " + new String(Base64.encodeBase64(authorizationStr.getBytes()));
    HashMap<String, String> headers = new HashMap<String, String>();
    //Set the form params
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("username", EMMQSGConfig.getInstance().getUsername()));
    urlParameters.add(new BasicNameValuePair("password", EMMQSGConfig.getInstance().getPassword()));
    urlParameters.add(new BasicNameValuePair("grant_type", "password"));
    urlParameters.add(new BasicNameValuePair("scope",
                                             "user:view user:manage user:admin:reset-password role:view role:manage policy:view policy:manage " +
                                             "application:manage appm:administration appm:create appm:publish appm:update appm:read"));
    //Set the headers
    headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_URL_ENCODED);
    headers.put(Constants.Header.AUTH, authHeader);
    HTTPResponse httpResponse = HTTPInvoker
            .sendHTTPPostWithURLParams(EMMQSGConfig.getInstance().getOauthEndPoint(), urlParameters, headers);
    if (httpResponse.getResponseCode() == Constants.HTTPStatus.OK) {
        try {
            JSONObject jsonObject = (JSONObject) new JSONParser().parse(httpResponse.getResponse());
            return (String) jsonObject.get("access_token");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example 12
Source File: QSGUtils.java    From product-emm with Apache License 2.0 5 votes vote down vote up
public static String getOAuthToken() {
    QSGUtils.initConfig();
    ClientCredentials clientCredentials = getClientCredentials();
    String authorizationStr = clientCredentials.getClientKey() + ":" + clientCredentials.getClientSecret();
    String authHeader = "Basic " + new String(Base64.encodeBase64(authorizationStr.getBytes()));
    HashMap<String, String> headers = new HashMap<String, String>();
    //Set the form params
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("username", EMMQSGConfig.getInstance().getUsername()));
    urlParameters.add(new BasicNameValuePair("password", EMMQSGConfig.getInstance().getPassword()));
    urlParameters.add(new BasicNameValuePair("grant_type", "password"));
    urlParameters.add(new BasicNameValuePair("scope",
                                             "user:view user:manage user:admin:reset-password role:view role:manage policy:view policy:manage " +
                                             "application:manage appm:create appm:publish appm:update appm:read"));
    //Set the headers
    headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_URL_ENCODED);
    headers.put(Constants.Header.AUTH, authHeader);
    HTTPResponse httpResponse = HTTPInvoker
            .sendHTTPPostWithURLParams(EMMQSGConfig.getInstance().getOauthEndPoint(), urlParameters, headers);
    if (httpResponse.getResponseCode() == Constants.HTTPStatus.OK) {
        try {
            JSONObject jsonObject = (JSONObject) new JSONParser().parse(httpResponse.getResponse());
            return (String) jsonObject.get("access_token");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example 13
Source File: CiviRestService.java    From civicrm-data-integration with GNU General Public License v3.0 5 votes vote down vote up
public boolean isValidJSONObject(String json) {
    boolean valid;

    try {
        Object obj = parser.parse(json);
        //new JSONObject(json);
        valid = true;
    } catch (ParseException e) {
        valid = false;
        e.printStackTrace();
    }

    return valid;
}
 
Example 14
Source File: I18nUtilTest.java    From singleton with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testLocalesExtract() {
	
	String languages="zh,en,zh-Hant,zh-Hans-HK";
	
	try {
		String[] languageArray=languages.split(",");
		for(int i=0;i<languageArray.length;i++) {
			String regions = PatternUtil.getRegionFromLib(languageArray[i]);
			Map<String, Object> genreJsonObject = null;
			genreJsonObject = (Map<String, Object>) JSONValue.parseWithException(regions);
			Map<String, Object> territoriesObject = (Map<String, Object>) JSONValue.parseWithException(genreJsonObject.get("territories").toString());
			if (languageArray[i].equals("zh")) {
				Assert.assertEquals("zh", genreJsonObject.get("language"));
				Assert.assertNotNull(territoriesObject.get("TW"));
				Assert.assertEquals("台湾", territoriesObject.get("TW"));

				Assert.assertEquals("阿森松岛", territoriesObject.get("AC"));
				Assert.assertEquals("南极洲", territoriesObject.get("AQ"));
				Assert.assertEquals("布韦岛", territoriesObject.get("BV"));
				Assert.assertEquals("克利珀顿岛", territoriesObject.get("CP"));

				Assert.assertEquals("南乔治亚和南桑威奇群岛", territoriesObject.get("GS"));
				Assert.assertEquals("赫德岛和麦克唐纳群岛", territoriesObject.get("HM"));
				Assert.assertEquals("马尔代夫", territoriesObject.get("MV"));
				Assert.assertEquals("特里斯坦-达库尼亚群岛", territoriesObject.get("TA"));

				Assert.assertEquals("法属南部领地", territoriesObject.get("TF"));
				Assert.assertEquals("未知地区", territoriesObject.get("ZZ"));
				Assert.assertEquals("", genreJsonObject.get("defaultRegionCode"));
			}
			if (languageArray[i].equals("zh-Hant")) {
				Assert.assertEquals("zh", genreJsonObject.get("language"));
				Assert.assertNotNull(territoriesObject.get("TW"));
				Assert.assertEquals("台灣", territoriesObject.get("TW"));
				Assert.assertEquals("義大利", territoriesObject.get("IT"));
				Assert.assertEquals("TW", genreJsonObject.get("defaultRegionCode"));

			}
			if (languageArray[i].equals("en")) {
				Assert.assertEquals("en", genreJsonObject.get("language"));
				Assert.assertNotNull(territoriesObject.get("TW"));
				Assert.assertEquals("Taiwan", territoriesObject.get("TW"));
				Assert.assertEquals("North Korea", territoriesObject.get("KP"));
				Assert.assertEquals("US", genreJsonObject.get("defaultRegionCode"));
			}
			if (languageArray[i].equals("zh-Hans-HK")) {
				Assert.assertEquals("HK", genreJsonObject.get("defaultRegionCode"));
			}

		}	
	} catch (ParseException e) {
		e.printStackTrace();
	}
}
 
Example 15
Source File: CiviRestService.java    From civicrm-data-integration with GNU General Public License v3.0 4 votes vote down vote up
public ArrayList<String> getEntityActions(boolean input) throws IOException, CiviCRMException {
    ArrayList<String> actions = new ArrayList<String>();
    try {
        String params = "&options[limit]=0";

        URL url = getUrl(this.entity, this.action, params);
        HttpURLConnection conn = getHttpConnection("GET", url);
        String json = getCiviResponse(conn);

        JSONObject jsonObject = (JSONObject) parser.parse(json);

        // Aqui debo chequear si hay un error de acceso
        if ((Long)jsonObject.get("is_error") == 1L) {
            throw new CiviCRMException("CiviCRM API Error: " + jsonObject.get("error_message").toString());
        } else if ((Long)jsonObject.get("is_error") == 0L && (Long)jsonObject.get("count") == 0L) {
            throw new CiviCRMException("CiviCRM Error: Entity [" + this.entity + "] has not fields or not exists ");
        } else {
            JSONArray values = (JSONArray) jsonObject.get("values");
            actions.addAll(values.subList(0, values.size()));

            if (input) {
                actions.removeAll(this.noInputActions);
                if (!actions.contains("get")) {
                    actions.add(0, "get");
                }
            } else {
                actions.removeAll(this.noOutputActions);
            }
            HashSet<String> set = new HashSet<String>(actions);
            String stringArray[] = new String[0];
            stringArray = set.toArray(stringArray);
            Arrays.sort(stringArray);
            actions.clear();
            actions.addAll(Arrays.asList(stringArray));
        }
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    }
    return actions;
}