org.json.simple.parser.ParseException Java Examples

The following examples show how to use org.json.simple.parser.ParseException. 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: 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 #2
Source File: CiviRestService.java    From civicrm-data-integration with GNU General Public License v3.0 6 votes vote down vote up
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 #3
Source File: AGDISTISTest.java    From NLIWOD with 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 #4
Source File: BasicBroParserTest.java    From metron with 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 #5
Source File: DcEngineDao.java    From io with 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 #6
Source File: APIManager.java    From seppuku with 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 #7
Source File: BasicBroParserTest.java    From opensoc-streaming with 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 #8
Source File: LDAPAuthenticationService.java    From proxylive with 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 #9
Source File: Vocab.java    From JFoolNLTK with 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 #10
Source File: RequestModule.java    From nomulus with 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 #11
Source File: JSONRecordReader.java    From incubator-retired-pirk with 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 #12
Source File: FavoritesHandler.java    From sakai with 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 #13
Source File: EsTest.java    From io with 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 File: BasicBroParserTest.java    From metron with 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 #15
Source File: DatasetUtil.java    From BPR with 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 #16
Source File: MultComponentService.java    From singleton with 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 #17
Source File: HttpResponse.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #18
Source File: ImportManager.java    From Statz with 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 #19
Source File: Redis.java    From AntiVPN with MIT License 5 votes vote down vote up
private VPNResult getVPNResultIP(long longIPID, String json, Jedis redis, long cacheTimeMillis) throws StorageException, JedisException, ParseException, ClassCastException {
    if (json == null) {
        return null;
    }

    JSONObject obj = JSONUtil.parseObject(json);
    long id = ((Number) obj.get("id")).longValue();
    Optional<Boolean> cascade = obj.get("cascade") == null ? Optional.empty() : Optional.of((Boolean) obj.get("cascade"));
    Optional<Double> consensus = obj.get("consensus") == null ? Optional.empty() : Optional.of(((Number) obj.get("consensus")).doubleValue());
    long created = ((Number) obj.get("created")).longValue();

    if (created < getTime(redis.time()) - cacheTimeMillis) {
        return null;
    }

    String ipJSON = redis.get(prefix + "ips:" + longIPID);
    if (ipJSON == null) {
        throw new StorageException(false, "Could not get IP data for ID " + longIPID + ".");
    }
    JSONObject ipObj = JSONUtil.parseObject(ipJSON);
    String ip = (String) ipObj.get("ip");
    if (!ValidationUtil.isValidIp(ip)) {
        redis.del(prefix + "ips:" + longIPID);
        throw new StorageException(false, "IP ID " + longIPID + " has an invalid IP \"" + ip + "\".");
    }

    return new VPNResult(
            id,
            ip,
            cascade,
            consensus,
            created
    );
}
 
Example #20
Source File: SubscriptionThrottlePolicyMappingUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #21
Source File: BlockingConditionMappingUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a List of Block Condition in to REST API LIST DTO Object
 *
 * @param blockConditionList A List of Block Conditions
 * @return REST API List DTO object derived from Block Condition list
 */
public static BlockingConditionListDTO fromBlockConditionListToListDTO(
        List<BlockConditionsDTO> blockConditionList) throws ParseException {
    BlockingConditionListDTO listDTO = new BlockingConditionListDTO();
    List<BlockingConditionDTO> blockingConditionDTOList = new ArrayList<>();
    if (blockConditionList != null) {
        for (BlockConditionsDTO blockCondition : blockConditionList) {
            BlockingConditionDTO dto = fromBlockingConditionToDTO(blockCondition);
            blockingConditionDTOList.add(dto);
        }
    }
    listDTO.setCount(blockingConditionDTOList.size());
    listDTO.setList(blockingConditionDTOList);
    return listDTO;
}
 
Example #22
Source File: JsonSimpleSerializerTest.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void serializeConversionWithSessionId() throws IOException, ParseException {
    EventBatch conversion = generateConversionWithSessionId();
    // can't compare JSON strings since orders could vary so compare JSONObjects instead
    JSONObject actual = (JSONObject) parser.parse(serializer.serialize(conversion));
    JSONObject expected = (JSONObject) parser.parse(generateConversionWithSessionIdJson());

    assertThat(actual, is(expected));
}
 
Example #23
Source File: RabbitMQ.java    From AntiVPN with MIT License 5 votes vote down vote up
private void receiveIP(AMQP.BasicProperties props, String json) throws UnsupportedEncodingException, ParseException, ClassCastException {
    if (props.getHeaders() == null || props.getHeaders().isEmpty()) {
        logger.warn("Properties for received IP was null or empty.");
        return;
    }
    String sender = new String(((LongString) props.getHeaders().get("sender")).getBytes(), props.getContentEncoding());
    if (!ValidationUtil.isValidUuid(sender)) {
        logger.warn("Non-valid sender received in IP: \"" + sender + "\".");
        return;
    }
    if (serverID.equals(sender)) {
        return;
    }

    if (!ValidationUtil.isValidUuid(props.getMessageId())) {
        logger.warn("Non-valid message ID received in IP: \"" + props.getMessageId() + "\".");
        return;
    }

    JSONObject obj = JSONUtil.parseObject(json);
    String ip = (String) obj.get("ip");
    if (!ValidationUtil.isValidIp(ip)) {
        logger.warn("Non-valid IP received in IP: \"" + ip + "\".");
        return;
    }

    handler.ipCallback(
            UUID.fromString(props.getMessageId()),
            ip,
            ((Number) obj.get("longID")).longValue(),
            this
    );
}
 
Example #24
Source File: LocalJSONTestSuiteTest.java    From ethereumj with MIT License 5 votes vote down vote up
@Test // AccountState parsing  //
public void test1() throws ParseException {

    String expectedNonce  = "01";
    String expectedBalance = "0de0b6b3a763ff6c";
    String expectedCode    = "6000600060006000604a3360c85c03f1";

    ByteArrayWrapper expectedKey1 = new ByteArrayWrapper(Hex.decode("ffaa"));
    ByteArrayWrapper expectedKey2 = new ByteArrayWrapper(Hex.decode("ffab"));

    ByteArrayWrapper expectedVal1 = new ByteArrayWrapper(Hex.decode("c8"));
    ByteArrayWrapper expectedVal2 = new ByteArrayWrapper(Hex.decode("b2b2b2"));

    JSONParser parser = new JSONParser();
    String accountString = "{'balance':999999999999999852,'nonce':1," +
            "'code':'0x6000600060006000604a3360c85c03f1'," +
            "'storage':{'0xffaa' : '0xc8', '0xffab' : '0xb2b2b2'}}";
    accountString = accountString.replace("'", "\"");

    JSONObject accountJSONObj = (JSONObject)parser.parse(accountString);

    AccountState state =
            new AccountState(Hex.decode("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"),
                    accountJSONObj);

    Assert.assertEquals(expectedNonce, Hex.toHexString(state.nonce));
    Assert.assertEquals(expectedBalance, Hex.toHexString(state.balance));
    Assert.assertEquals(expectedCode, Hex.toHexString(state.code));

    Assert.assertTrue(state.storage.keySet().contains(expectedKey1));
    Assert.assertTrue(state.storage.keySet().contains(expectedKey2));

    Assert.assertTrue(state.storage.values().contains(expectedVal1));
    Assert.assertTrue(state.storage.values().contains(expectedVal2));
}
 
Example #25
Source File: PetsciiArtGallery.java    From petscii-bbs with Mozilla Public License 2.0 5 votes vote down vote up
private void displayAuthor(Path p, boolean randomize) throws IOException, URISyntaxException, ParseException {
    boolean statusLine = false;
    cls();
    List<Path> drawings = getDirContent(p.toString());
    if (randomize) Collections.shuffle(drawings);
    int size = drawings.size();
    int i = 0;
    while (i < size) {
        write(CLR, RETURN, CLR, UPPERCASE, REVOFF);
        String filename = drawings.get(i).toString();
        if (startsWith(filename,"/")) filename = filename.substring(1);
        log("PETSCII ("+i+") FILENAME=" + filename);
        if (lowerCase(filename).endsWith(".json")) {
            final String content = new String(readBinaryFile(filename), UTF_8);
            printPetmateJson(content);
        } else {
            writeRawFile(filename);
        }
        if (statusLine) {
            write(HOME, WHITE, REVOFF);
            print((i+1)+"/"+size);
        }
        flush();
        resetInput();
        int key = readKey();
        if (key == '.')
            break;
        else if (key == 'x' || key == 'X')
            statusLine = !statusLine;
        else if (key == '-' && i > 0)
            --i;
        else
            ++i;
    }
    write(CLR, RETURN, CLR, LOWERCASE, REVOFF);
}
 
Example #26
Source File: BukkitPlayerInfo.java    From AntiVPN with MIT License 5 votes vote down vote up
private static String nameExpensive(UUID uuid) throws IOException {
    // Currently-online lookup
    Player player = Bukkit.getPlayer(uuid);
    if (player != null) {
        nameCache.put(player.getName(), uuid);
        return player.getName();
    }

    // Network lookup
    HttpURLConnection conn = JSONWebUtil.getConnection(new URL("https://api.mojang.com/user/profiles/" + uuid.toString().replace("-", "") + "/names"), "GET", 5000, "egg82/PlayerInfo", headers);;
    int status = conn.getResponseCode();

    if (status == 204) {
        // No data exists
        return null;
    } else if (status == 200) {
        try {
            JSONArray json = getJSONArray(conn, status);
            JSONObject last = (JSONObject) json.get(json.size() - 1);
            String name = (String) last.get("name");
            nameCache.put(name, uuid);
            return name;
        } catch (ParseException | ClassCastException ex) {
            throw new IOException(ex.getMessage(), ex);
        }
    }

    throw new IOException("Could not load player data from Mojang (rate-limited?)");
}
 
Example #27
Source File: IPWarner.java    From AntiVPN with MIT License 5 votes vote down vote up
public boolean getResult(String ip) throws APIException {
    if (ip == null) {
        throw new IllegalArgumentException("ip cannot be null.");
    }
    if (!ValidationUtil.isValidIp(ip)) {
        throw new IllegalArgumentException("ip is invalid.");
    }

    ConfigurationNode sourceConfigNode = getSourceConfigNode();

    String key = sourceConfigNode.getNode("key").getString();
    if (key == null || key.isEmpty()) {
        throw new APIException(true, "Key is not defined for " + getName());
    }

    JSONObject json;
    try {
        json = JSONWebUtil.getJSONObject(new URL("https://api.ipwarner.com/" + key + "/" + ip), "GET", (int) getCachedConfig().getTimeout(), "egg82/AntiVPN");
    } catch (IOException | ParseException | ClassCastException ignored) {
        try {
            json = JSONWebUtil.getJSONObject(new URL("http://api.ipwarner.com/" + key + "/" + ip), "GET", (int) getCachedConfig().getTimeout(), "egg82/AntiVPN"); // Temporary (hopefully) hack
        } catch (IOException | ParseException | ClassCastException ex) {
            throw new APIException(false, ex);
        }
    }
    if (json == null || json.get("goodIp") == null) {
        throw new APIException(false, "Could not get result from " + getName());
    }

    short retVal = ((Number) json.get("goodIp")).shortValue();
    if (retVal < 0) {
        throw new APIException(false, "Could not get result from " + getName());
    }

    return retVal == 1;
}
 
Example #28
Source File: UserDataWithNPDeclaredDoublePropertyTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * AST対ONEのUserDataをNavigationProperty経由で取得して対象データが取得できること.
 * @throws ParseException パース例外
 */
@Test
public final void AST対ONEのUserDataをNavigationProperty経由で取得して対象データが取得できること() throws ParseException {
    try {
        String sourceMultiplicity = "*";
        String targetMultiplicity = "1";
        checkSchemaTypeDouble(sourceMultiplicity, targetMultiplicity);
    } finally {
        CellUtils.bulkDeletion(BEARER_MASTER_TOKEN, CELL_NAME);
    }
}
 
Example #29
Source File: BasicBroParserTest.java    From metron with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
       public void testX509BroMessage() throws ParseException {
               Map rawMessageMap = (Map) jsonParser.parse(x509BroMessage);
               JSONObject rawJson = (JSONObject) rawMessageMap.get(rawMessageMap.keySet().iterator().next());

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

               assertEquals(broJson.get("id").toString(), rawJson.get("id").toString());
               assertEquals(broJson.get("certificate.version").toString(), rawJson.get("certificate.version").toString());
               assertEquals(broJson.get("certificate.serial").toString(), rawJson.get("certificate.serial").toString());
               assertEquals(broJson.get("certificate.subject").toString(), rawJson.get("certificate.subject").toString());
               assertEquals(broJson.get("certificate.issuer").toString(), rawJson.get("certificate.issuer").toString());
               assertEquals(broJson.get("certificate.not_valid_before").toString(), rawJson.get("certificate.not_valid_before").toString());
               assertEquals(broJson.get("certificate.not_valid_after").toString(), rawJson.get("certificate.not_valid_after").toString());
               assertEquals(broJson.get("certificate.key_alg").toString(), rawJson.get("certificate.key_alg").toString());
               assertEquals(broJson.get("certificate.sig_alg").toString(), rawJson.get("certificate.sig_alg").toString());
               assertEquals(broJson.get("certificate.key_type").toString(), rawJson.get("certificate.key_type").toString());
               assertEquals(broJson.get("certificate.key_length").toString(), rawJson.get("certificate.key_length").toString());
               assertEquals(broJson.get("certificate.exponent").toString(), rawJson.get("certificate.exponent").toString());
               assertEquals(broJson.get("basic_constraints.ca").toString(), rawJson.get("basic_constraints.ca").toString());
               assertEquals(broJson.get("basic_constraints.path_len").toString(), rawJson.get("basic_constraints.path_len").toString());

	assertTrue(broJson.get("original_string").toString().startsWith("X509"));
       }
 
Example #30
Source File: JsonSimpleConfigParser.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
private List<Audience> parseTypedAudiences(JSONArray audienceJson) throws ParseException {
    List<Audience> audiences = new ArrayList<Audience>(audienceJson.size());

    for (Object obj : audienceJson) {
        JSONObject audienceObject = (JSONObject) obj;
        String id = (String) audienceObject.get("id");
        String key = (String) audienceObject.get("name");
        Object conditionObject = audienceObject.get("conditions");
        Condition conditions = ConditionUtils.<UserAttribute>parseConditions(UserAttribute.class, conditionObject);
        audiences.add(new Audience(id, key, conditions));
    }

    return audiences;
}