Java Code Examples for org.json.simple.parser.ParseException

The following examples show how to use org.json.simple.parser.ParseException. These examples are extracted from open source projects. 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 Project: io   Source File: DcEngineDao.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * クライアントライブラリで、JavaのJSONObjectを直接扱えないためラップして返す.
 * @param jsonStr JSON文字列
 * @return JSONObjectのラッパー
 * @throws ParseException ParseException
 */
public final DcJSONObject newDcJSONObject(final String jsonStr) throws ParseException {
    DcJSONObject json = (DcJSONObject) (new JSONParser().parse(jsonStr, new ContainerFactory() {

        @SuppressWarnings("rawtypes")
        @Override
        public Map createObjectContainer() {
            return new DcJSONObject();
        }

        @SuppressWarnings("rawtypes")
        @Override
        public List creatArrayContainer() {
            return null;
        }
    }));
    return json;
}
 
Example 2
Source Project: metron   Source File: BasicBroParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnwrappedBroMessage() throws ParseException {
       JSONObject rawJson = (JSONObject)jsonParser.parse(unwrappedBroMessage);
       JSONObject broJson = broParser.parse(unwrappedBroMessage.getBytes(StandardCharsets.UTF_8)).get(0);

String expectedBroTimestamp = "1449511228.474";
     	assertEquals(broJson.get("bro_timestamp"), expectedBroTimestamp);
       String expectedTimestamp = "1449511228474";
assertEquals(broJson.get("timestamp").toString(), expectedTimestamp);

assertEquals(broJson.get("ip_src_addr").toString(), rawJson.get("id.orig_h").toString());
assertEquals(broJson.get("ip_dst_addr").toString(), rawJson.get("id.resp_h").toString());
assertEquals(broJson.get("ip_src_port"), rawJson.get("id.orig_p"));
       assertEquals(broJson.get("ip_dst_port"), rawJson.get("id.resp_p"));
       assertEquals(broJson.get("uid").toString(), rawJson.get("uid").toString());
       assertEquals(broJson.get("trans_id").toString(), rawJson.get("trans_id").toString());
       assertEquals(broJson.get("sensor").toString(), rawJson.get("sensor").toString());
       assertEquals(broJson.get("type").toString(), rawJson.get("type").toString());
       assertEquals(broJson.get("rcode").toString(), rawJson.get("rcode").toString());
       assertEquals(broJson.get("rcode_name").toString(), rawJson.get("rcode_name").toString());

assertTrue(broJson.get("original_string").toString().startsWith("DNS"));
   }
 
Example 3
public ArrayList<String> getEntityList(boolean refresh) throws IOException, ParseException, CiviCRMException {
    if (entityList.size() == 0 || refresh) {
        entityList = new ArrayList<String>();
        URL url = getUrl("Entity", "get", "");
        HttpURLConnection conn = getHttpConnection("GET", url);
        String jsonString = getCiviResponse(conn);

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

        // 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 {
            JSONArray values = (JSONArray) jsonObject.get("values");

            Iterator<String> valueIterator = values.iterator();
            String entityName;
            // take each value from the json array separately
            while (valueIterator.hasNext()) {
                entityName = valueIterator.next();
                entityList.add(entityName);
            }
        }
    }
    return entityList;
}
 
Example 4
Source Project: seppuku   Source File: APIManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public String resolveName(String uuid) {
    uuid = uuid.replace("-", "");
    if (uuidNameCache.containsKey(uuid)) {
        return uuidNameCache.get(uuid);
    }

    final String url = "https://api.mojang.com/user/profiles/" + uuid + "/names";
    try {
        final String nameJson = IOUtils.toString(new URL(url));
        if (nameJson != null && nameJson.length() > 0) {
            final JSONArray jsonArray = (JSONArray) JSONValue.parseWithException(nameJson);
            if (jsonArray != null) {
                final JSONObject latestName = (JSONObject) jsonArray.get(jsonArray.size() - 1);
                if (latestName != null) {
                    return latestName.get("name").toString();
                }
            }
        }
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 5
Source Project: opensoc-streaming   Source File: BasicBroParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public void testDnsBroMessage() throws ParseException {
	String rawMessage = "{\"dns\":{\"ts\":1402308259609,\"uid\":\"CuJT272SKaJSuqO0Ia\",\"id.orig_h\":\"10.122.196.204\",\"id.orig_p\":33976,\"id.resp_h\":\"144.254.71.184\",\"id.resp_p\":53,\"proto\":\"udp\",\"trans_id\":62418,\"query\":\"www.cisco.com\",\"qclass\":1,\"qclass_name\":\"C_INTERNET\",\"qtype\":28,\"qtype_name\":\"AAAA\",\"rcode\":0,\"rcode_name\":\"NOERROR\",\"AA\":true,\"TC\":false,\"RD\":true,\"RA\":true,\"Z\":0,\"answers\":[\"www.cisco.com.akadns.net\",\"origin-www.cisco.com\",\"2001:420:1201:2::a\"],\"TTLs\":[3600.0,289.0,14.0],\"rejected\":false}}";
	
	Map rawMessageMap = (Map) jsonParser.parse(rawMessage);
	JSONObject rawJson = (JSONObject) rawMessageMap.get(rawMessageMap.keySet().iterator().next());
	
	JSONObject broJson = broParser.parse(rawMessage.getBytes());
	assertEquals(broJson.get("timestamp").toString(), rawJson.get("ts").toString());
	assertEquals(broJson.get("ip_src_addr").toString(), rawJson.get("id.orig_h").toString());
	assertEquals(broJson.get("ip_dst_addr").toString(), rawJson.get("id.resp_h").toString());
	assertEquals(broJson.get("ip_src_port").toString(), rawJson.get("id.orig_p").toString());
	assertEquals(broJson.get("ip_dst_port").toString(), rawJson.get("id.resp_p").toString());
	assertTrue(broJson.get("original_string").toString().startsWith(rawMessageMap.keySet().iterator().next().toString().toUpperCase()));
	
	assertEquals(broJson.get("qtype").toString(), rawJson.get("qtype").toString());
	assertEquals(broJson.get("trans_id").toString(), rawJson.get("trans_id").toString());
}
 
Example 6
Source Project: nomulus   Source File: RequestModule.java    License: Apache License 2.0 6 votes vote down vote up
@Provides
@JsonPayload
@SuppressWarnings("unchecked")
static Map<String, Object> provideJsonPayload(
    @Header("Content-Type") MediaType contentType,
    @Payload String payload) {
  if (!JSON_UTF_8.is(contentType.withCharset(UTF_8))) {
    throw new UnsupportedMediaTypeException(
        String.format("Expected %s Content-Type", JSON_UTF_8.withoutParameters()));
  }
  try {
    return (Map<String, Object>) JSONValue.parseWithException(payload);
  } catch (ParseException e) {
    throw new BadRequestException(
        "Malformed JSON", new VerifyException("Malformed JSON:\n" + payload, e));
  }
}
 
Example 7
Source Project: incubator-retired-pirk   Source File: JSONRecordReader.java    License: Apache License 2.0 6 votes vote down vote up
public void toMapWritable(Text line) throws ParseException
{
  JSONObject jsonObj = (JSONObject) jsonParser.parse(line.toString());
  for (Object key : jsonObj.keySet())
  {
    Text mapKey = new Text(key.toString());
    Text mapValue = new Text();
    if (jsonObj.get(key) != null)
    {
      if (dataSchema.isArrayElement(key.toString()))
      {
        String[] elements = StringUtils.jsonArrayStringToList(jsonObj.get(key).toString());
        TextArrayWritable aw = new TextArrayWritable(elements);
        value.put(mapKey, aw);
      }
      else
      {
        mapValue.set(jsonObj.get(key).toString());
        value.put(mapKey, mapValue);
      }
    }
  }
}
 
Example 8
Source Project: sakai   Source File: FavoritesHandler.java    License: Educational Community License v2.0 6 votes vote down vote up
public static UserFavorites fromJSON(String json) throws ParseException {
	JSONParser parser = new JSONParser();

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

	UserFavorites result = new UserFavorites();
	result.favoriteSiteIds = new LinkedHashSet<String>();

	if (obj.get("favoriteSiteIds") != null) {
		// Site IDs might be numeric, so coerce everything to strings.
		for (Object siteId : (List<String>)obj.get("favoriteSiteIds")) {
			if (siteId != null) {
				result.favoriteSiteIds.add(siteId.toString());
			}
		}
	}

	result.autoFavoritesEnabled = (Boolean)obj.get("autoFavoritesEnabled");

	return result;
}
 
Example 9
Source Project: singleton   Source File: MultComponentService.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked" })
private TranslationDTO getTranslation(TranslationDTO translationDTO)
		throws ParseException, DataException {
	List<String> locales = translationDTO.getLocales();
	List<String> components = translationDTO.getComponents();
	List<String> bundles = multipleComponentsDao.get2JsonStrs(
			translationDTO.getProductName(), translationDTO.getVersion(),
			components, locales);
	JSONArray ja = new JSONArray();
	for (int i = 0; i < bundles.size(); i++) {
		String s = (String) bundles.get(i);
		if (s.equalsIgnoreCase("")) {
			continue;
		}
		JSONObject jo = (JSONObject) new JSONParser().parse(s);
		ja.add(jo);
	}
	translationDTO.setBundles(ja);
	return translationDTO;
}
 
Example 10
Source Project: singleton   Source File: JSONUtil.java    License: 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 11
Source Project: BPR   Source File: DatasetUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param args
 * @throws IOException 
 * @throws ParseException 
 * @throws java.text.ParseException 
 * @throws LangDetectException 
 */
public static void main(String[] args) throws IOException, ParseException, java.text.ParseException {

	DatasetUtil util = new DatasetUtil();
	String Dir = "/Users/xiangnanhe/Workspace/yelp-challenge/";
	int thres = 50;
	//util.ConvertJsonToVotesFile("/Users/xiangnanhe/Workspace/yelp-challenge/all/", "yelp");
	//util.RemoveDuplicateInVotesFile(Dir + "all/", "yelp");
	//util.FilterVotesReviewsByWords("/Users/xiangnanhe/Workspace/yelp-challenge/", "yelp_1M_u3", 20000);
	
	
	util.FilterVotesFileByUsers(Dir +"all/", "yelp", thres);
	util.SplitVotesFileByTimePerUser(Dir,  "yelp_u" + thres, 0.6, 0.2, 0.2);
	
	util.ConvertVotesToRatingFile(Dir + "train/", "yelp_u" + thres);
    util.ConvertVotesToRatingFile(Dir + "test/", "yelp_u" + thres);
    util.ConvertVotesToRatingFile(Dir + "validation/", "yelp_u" + thres); 

	System.out.println("end");
}
 
Example 12
Source Project: metron   Source File: BasicBroParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
       public void testKnownDevicesBroMessage() throws ParseException {
               Map rawMessageMap = (Map) jsonParser.parse(knownDevicesBroMessage);
               JSONObject rawJson = (JSONObject) rawMessageMap.get(rawMessageMap.keySet().iterator().next());

               JSONObject broJson = broParser.parse(knownDevicesBroMessage.getBytes(
                   StandardCharsets.UTF_8)).get(0);
               String expectedBroTimestamp = "1258532046.693816";
               assertEquals(broJson.get("bro_timestamp"), expectedBroTimestamp);
               String expectedTimestamp = "1258532046693";
               assertEquals(broJson.get("timestamp").toString(), expectedTimestamp);
               assertTrue(broJson.get("original_string").toString().startsWith(rawMessageMap.keySet().iterator().next().toString().toUpperCase()));

               assertEquals(broJson.get("mac").toString(), rawJson.get("mac").toString());
               assertEquals(broJson.get("dhcp_host_name").toString(), rawJson.get("dhcp_host_name").toString());

               assertTrue(broJson.get("original_string").toString().startsWith("KNOWN_DEVICES"));
       }
 
Example 13
Source Project: io   Source File: EsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * ドキュメント登録チェックでドキュメントがすでに存在している場合に正常終了すること.
 * @throws ParseException ParseException
 */
@Test
public void ドキュメント登録チェックでドキュメントがすでに存在している場合に正常終了すること() throws ParseException {
    String id = "id00001";
    EsIndex index = esClient.idxAdmin("index_for_test");
    index.create();
    EsTypeImpl type = (EsTypeImpl) esClient.type(index.getName(), "TypeForTest", "TestRoutingId", 5, 500);
    assertNotNull(type);
    JSONObject data = (JSONObject) new JSONParser()
    .parse("{\"u\":1406596187938,\"t\":\"K0QK5DXWT5qKIPDU2eTdhA\",\"b\":\"IKv5hMRPRDGc68BnIcVx6g\","
            + "\"s\":{\"P003\":\"secondDynamicPropertyValue\",\"P002\":\"true\",\"P001\":\"false\","
            + "\"P011\":\"null\",\"P012\":\"123.0\",\"P007\":\"123\",\"P006\":\"false\",\"P005\":null,"
            + "\"P004\":\"dynamicPropertyValue\",\"P009\":\"123.123\",\"P008\":\"true\",\"__id\":\"userdata001:\","
            + "\"P010\":\"123.123\"},\"c\":\"Q1fp4zrWTm-gSSs7zVCJQg\",\"p\":1406596187938,"
            + "\"n\":\"vWy9OQj2ScykYize2d7Z5A\",\"l\":[],\"h\":{}}");
    type.create(id, data);
    IndexResponse response = type.checkDocumentCreated(id, data, null);
    assertNotNull(response);
    assertEquals(id, response.getId());
}
 
Example 14
Source Project: Statz   Source File: ImportManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
private Optional<JSONObject> getUserStatisticsFile(UUID uuid, String worldName)
        throws IOException, ParseException {
    Objects.requireNonNull(uuid);
    Objects.requireNonNull(worldName);

    World world = Bukkit.getWorld(worldName);

    if (world == null) return Optional.empty();

    File worldFolder = new File(world.getWorldFolder(), "stats");
    File playerStatistics = new File(worldFolder, uuid.toString() + ".json");

    if (!playerStatistics.exists()) {
        return Optional.empty();
    }

    JSONObject rootObject = (JSONObject) new JSONParser().parse(new FileReader(playerStatistics));

    if (rootObject == null) return Optional.empty();

    if (rootObject.containsKey("stats")) {
        return Optional.ofNullable((JSONObject) rootObject.get("stats"));
    }

    return Optional.empty();
}
 
Example 15
public JSONObject getJsonResponse()
{
       JSONObject result = null;

       try
       {
		String response = getResponse();
           if (response != null)
           {
               Object object = new JSONParser().parse(response);
               if(object instanceof JSONObject)
               {
                  return (JSONObject) object;
               }
           }
       }
       catch (ParseException error)
       {
           // Ignore errors, returning null
       }
      
       return result;
}
 
Example 16
Source Project: JFoolNLTK   Source File: Vocab.java    License: Apache License 2.0 6 votes vote down vote up
private void parseJson(String content) throws ParseException {
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(content);
    JSONObject jsonObject = (JSONObject) obj;

    Map<String, Integer> wordMap = parseStrMap((JSONObject) jsonObject.get("word_map"));
    Map<String, Integer> charMap = parseStrMap((JSONObject) jsonObject.get("char_map"));

    Map<Integer, String> segMap = parseIdMap((JSONObject) jsonObject.get("seg_map"));
    Map<Integer, String> posMap = parseIdMap((JSONObject) jsonObject.get("pos_map"));
    Map<Integer, String> nerMap = parseIdMap((JSONObject) jsonObject.get("ner_map"));

    charToId.setLabelToid(charMap);
    wordToId.setLabelToid(wordMap);
    idToSeg.setIdTolabel(segMap);
    idToPos.setIdTolabel(posMap);
    idToNer.setIdTolabel(nerMap);
}
 
Example 17
Source Project: proxylive   Source File: LDAPAuthenticationService.java    License: MIT License 6 votes vote down vote up
@PostConstruct
private void initialize() throws MalformedURLException, ProtocolException, IOException, ParseException, NamingException {
    ldapAuthConfig = configuration.getAuthentication().getLdap();
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, ldapAuthConfig.getUser());
    env.put(Context.SECURITY_CREDENTIALS, ldapAuthConfig.getPassword());
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://"+ldapAuthConfig.getServer()+"/"+ldapAuthConfig.getSearchBase());
    env.put("java.naming.ldap.attributes.binary", "objectSID");
    LdapContext ctx = new InitialLdapContext();
    SearchResult srLdapUser = findAccountByAccountName(ctx, ldapAuthConfig.getSearchBase(), "segator");
       String primaryGroupSID = getPrimaryGroupSID(srLdapUser);
 
    
    //3) get the users Primary Group
    String primaryGroupName = findGroupBySID(ctx, ldapAuthConfig.getSearchBase(), primaryGroupSID);
    logger.trace(primaryGroupName);

}
 
Example 18
Source Project: NLIWOD   Source File: AGDISTISTest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testDisambiguation() throws ParseException, IOException {
	AGDISTIS post = new AGDISTIS();
	String subjectString = "Tom Cruise";
	String objectString = "Katie Holmes";

	String preAnnotatedText = "<entity>" + subjectString + "</entity><entity>" + objectString + "</entity>";

	log.debug("Disambiguation for: " + preAnnotatedText);
	
	HashMap<String, String> realResults = new LinkedHashMap<String,String>();
	realResults.put("Katie Holmes", "http://dbpedia.org/resource/Katie_Holmes");
	realResults.put("Tom Cruise", "http://dbpedia.org/resource/Tom_Cruise");
	
	HashMap<String, String> results = post.runDisambiguation(preAnnotatedText);
	for (String namedEntity : results.keySet()) {
		Assert.assertTrue(results.get(namedEntity).equals(realResults.get(namedEntity)));
		log.debug("named entity: " + namedEntity + " -> " + results.get(namedEntity));
	}
}
 
Example 19
/**
 * Converts an array of Subscription Policy objects into a List DTO
 *
 * @param subscriptionPolicies Array of Subscription Policies
 * @return A List DTO of converted Subscription Policies
 * @throws UnsupportedThrottleLimitTypeException
 * @throws ParseException
 */
public static SubscriptionThrottlePolicyListDTO fromSubscriptionPolicyArrayToListDTO(
        SubscriptionPolicy[] subscriptionPolicies) throws UnsupportedThrottleLimitTypeException, ParseException {
    SubscriptionThrottlePolicyListDTO listDTO = new SubscriptionThrottlePolicyListDTO();
    List<SubscriptionThrottlePolicyDTO> subscriptionPolicyDTOList = new ArrayList<>();
    if (subscriptionPolicies != null) {
        for (SubscriptionPolicy policy : subscriptionPolicies) {
            SubscriptionThrottlePolicyDTO dto = fromSubscriptionThrottlePolicyToDTO(policy);
            subscriptionPolicyDTOList.add(dto);
        }
    }
    listDTO.setCount(subscriptionPolicyDTOList.size());
    listDTO.setList(subscriptionPolicyDTOList);
    return listDTO;
}
 
Example 20
Source Project: netbeans   Source File: DOMTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test of {@code handleAttributeRemoved} method.
 */
@Test
public void testHandleAttributeRemoved() throws ParseException {
    TransportImplementation transport = new DummyTransportImplementation();
    DOM dom = new DOM(new TransportHelper(transport), null);
    final Node root = dom.getDocument();
    final String ATTR_NAME = "class"; // NOI18N
    final int[] eventsFired = new int[1];
    DOM.Listener listener = new DOMAdapter() {
        @Override
        public void attributeRemoved(Node node, String attrName) {
            eventsFired[0]++;
            assertEquals(ATTR_NAME, attrName);
            assertEquals(root, node);
            Node.Attribute attr = node.getAttribute(attrName);
            assertNull(attr);
        }
    };
    dom.addListener(listener);
    JSONParser parser = new JSONParser();

    // Modification of a known node
    Object json = parser.parse("{\"nodeId\":" + ROOT_NODE_ID + ",\"name\":\"" + ATTR_NAME + "\"}"); // NOI18N
    dom.handleAttributeRemoved((JSONObject)json);
    assertEquals(1, eventsFired[0]);

    // Modification of an unknown node
    json = parser.parse("{\"nodeId\":" + (ROOT_NODE_ID+1) + ",\"name\":\"someName\"}"); // NOI18N
    dom.handleAttributeRemoved((JSONObject)json);
    assertEquals(1, eventsFired[0]);
}
 
Example 21
Source Project: product-iots   Source File: QSGUtils.java    License: 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 22
Source Project: HongsCORE   Source File: Dawn.java    License: MIT License 5 votes vote down vote up
/**
 * 将JSON字符串解析成Java对象
 * @param str JSON字符串
 * @return 基础类型,集合框架
 */
public static Object toObject(String str)
{
  try
  {
    return new JSONParser().parse(str,CF);
  }
  catch (ParseException ex)
  {
    throw new HongsExemption(0x1150, "Can not parse data by json", ex);
  }
}
 
Example 23
Source Project: java-sdk   Source File: JsonSimpleSerializerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void serializeImpressionWithSessionId() throws IOException, ParseException {
    EventBatch impression = generateImpressionWithSessionId();
    // can't compare JSON strings since orders could vary so compare JSONObjects instead
    JSONObject actual = (JSONObject) parser.parse(serializer.serialize(impression));
    JSONObject expected = (JSONObject) parser.parse(generateImpressionWithSessionIdJson());

    assertThat(actual, is(expected));
}
 
Example 24
Source Project: wisdom   Source File: NodeManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Category(LongRun.class)
public void testSkipPostInstall() throws IOException, ParseException, MojoExecutionException {
    manager.installIfNotInstalled();
    AbstractWisdomMojo mojo = mock(AbstractWisdomMojo.class);
    when(mojo.getLog()).thenReturn(log);
    when(mojo.getNodeManager()).thenReturn(manager);

    NPM npm = NPM.npm(mojo, "optipng-bin", "1.0.0", "--ignore-scripts");
    assertThat(npm).isNotNull();
}
 
Example 25
Source Project: proxylive   Source File: PlexAuthenticationService.java    License: MIT License 5 votes vote down vote up
private JSONObject getUserData(String user, String pass) throws MalformedURLException, IOException, ParseException {
    URL url = new URL(String.format("https://%s:%[email protected]/users/sign_in.json", URLEncoder.encode(user,"UTF-8"),  URLEncoder.encode(pass,"UTF-8")));
    HttpURLConnection connection = createConnection(url);
    connection.setRequestProperty("X-Plex-Client-Identifier", "proxylive");
    connection.setRequestMethod("POST");
    connection.connect();
    if (connection.getResponseCode() != 201) {
        return null;
    }
    JSONParser jsonParser = new JSONParser();
    JSONObject response = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    return (JSONObject) response.get("user");
}
 
Example 26
Source Project: AntiVPN   Source File: Redis.java    License: MIT License 5 votes vote down vote up
private void receivePostMCLeaks(String json) throws ParseException, ClassCastException {
    JSONObject obj = JSONUtil.parseObject(json);
    String sender = (String) obj.get("sender");
    if (!ValidationUtil.isValidUuid(sender)) {
        logger.warn("Non-valid sender received in post MCLeaks: \"" + sender + "\".");
        return;
    }
    if (serverID.equals(sender)) {
        return;
    }

    String messageID = (String) obj.get("messageID");
    if (!ValidationUtil.isValidUuid(messageID)) {
        logger.warn("Non-valid message ID received in post MCLeaks: \"" + messageID + "\".");
        return;
    }

    String playerID = (String) obj.get("playerID");
    if (!ValidationUtil.isValidUuid(playerID)) {
        logger.warn("Non-valid UUID received in post MCLeaks: \"" + playerID + "\".");
        return;
    }

    handler.postMCLeaksCallback(
            UUID.fromString(messageID),
            ((Number) obj.get("id")).longValue(),
            ((Number) obj.get("longPlayerID")).longValue(),
            UUID.fromString(playerID),
            (Boolean) obj.get("value"),
            ((Number) obj.get("created")).longValue(),
            this
    );
}
 
Example 27
Source Project: tutorials   Source File: APIDemoHandler.java    License: MIT License 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 responseJson = new JSONObject();

    AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient();
    DynamoDB dynamoDb = new DynamoDB(client);

    try {
        JSONObject event = (JSONObject) parser.parse(reader);

        if (event.get("body") != null) {

            Person person = new Person((String) event.get("body"));

            dynamoDb.getTable(DYNAMODB_TABLE_NAME)
                .putItem(new PutItemSpec().withItem(new Item().withNumber("id", person.getId())
                    .withString("name", person.getName())));
        }

        JSONObject responseBody = new JSONObject();
        responseBody.put("message", "New item created");

        JSONObject headerJson = new JSONObject();
        headerJson.put("x-custom-header", "my custom header value");

        responseJson.put("statusCode", 200);
        responseJson.put("headers", headerJson);
        responseJson.put("body", responseBody.toString());

    } catch (ParseException pex) {
        responseJson.put("statusCode", 400);
        responseJson.put("exception", pex);
    }

    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
    writer.write(responseJson.toString());
    writer.close();
}
 
Example 28
public static JSONObject loadTestQuestions(){
	String loadeddata;
	try {			
		Path datapath = Paths.get("./src/main/resources/qald-6-test-multilingual.json");
		loadeddata = Files.lines(datapath).collect(Collectors.joining());
		JSONParser parser = new JSONParser();
		JSONObject arr = (JSONObject) parser.parse(loadeddata);
		return arr;
	} catch (IOException | ParseException  e) {
		e.printStackTrace();
		log.debug("loading failed.");
		return new JSONObject();
	}
}
 
Example 29
Source Project: apogen   Source File: UtilsStaticAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * get slaves objects from cluster.json file
 * 
 * @param state
 * @param out_dir
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 * @throws ParseException
 */
private static List<String> getSlaves(String state, final String out_dir) throws ParseException {

	List<String> result = new LinkedList<String>();

	JSONParser parser = new JSONParser();
	Object obj;
	try {
		obj = parser.parse(new FileReader(out_dir + "cluster.json"));
	} catch (IOException e) {
		System.out.println("[LOG]\tcluster.json file missing for slaves calculation");
		return new LinkedList<String>();
	}
	JSONObject jsonObject = (JSONObject) obj;

	JSONArray clusters = (JSONArray) jsonObject.get("clusters");

	for (int i = 0; i < clusters.size(); i++) {
		JSONObject aCluster = (JSONObject) clusters.get(i);

		if (aCluster.get("master").equals(state)) {

			JSONArray arrayOfSlaves = (JSONArray) aCluster.get("slaves");

			for (Object o : arrayOfSlaves) {
				// JSONObject aSlave = (JSONObject) o;
				result.add(o.toString());
			}
		}
	}

	return result;
}
 
Example 30
Source Project: singleton   Source File: ProductService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Merge the translation in the componentMessagesDTO and in the local
 * bundle.
 *
 * @param componentMessagesDTO
 *            the object of ComponentMessagesDTO, containing the latest
 *            translation.
 * @return ComponentMessagesDTO a DTO object of ComponentMessagesDTO,
 *         containing the all translation.
 * @throws ParseException
 * @throws DataException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private ComponentMessagesDTO mergeComponentMessagesDTOWithFile(
		ComponentMessagesDTO componentMessagesDTO) throws DataException,
		ParseException {
	ComponentMessagesDTO paramComponentMessagesDTO = new ComponentMessagesDTO();
	BeanUtils.copyProperties(componentMessagesDTO,
			paramComponentMessagesDTO);
	ComponentMessagesDTO result = null;
	try {
		result = this.getLinkedTranslation(paramComponentMessagesDTO);
	} catch (DataException e1) {
		logger.error(e1.getMessage(), e1);
	} catch (ParseException e2) {
		logger.error(e2.getMessage(), e2);
	}

	if (result != null) {
		Object messageObj = result.getMessages();
		if (!StringUtils.isEmpty(messageObj)) {
			Map<String, Object> messages = (Map<String, Object>) messageObj;
			Iterator<Map.Entry<String, Object>> it = ((Map) componentMessagesDTO
					.getMessages()).entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String, Object> entry = it.next();
				messages.put(entry.getKey(), entry.getValue());
			}
			componentMessagesDTO.setMessages(messages);
			return componentMessagesDTO;
		} else {
			return componentMessagesDTO;
		}
	} else {
		return componentMessagesDTO;
	}
}