Java 类org.json.simple.parser.JSONParser 实例源码

项目:VoxelGamesLibv2    文件:MojangUtil.java   
/**
 * Tries to fetch the current display name for the user
 *
 * @param id the id of the user to check
 * @return the current display name of that user
 * @throws IOException           if something goes wrong
 * @throws VoxelGameLibException if the user has no display name
 */
@Nonnull
public static String getDisplayName(@Nonnull UUID id) throws IOException, VoxelGameLibException {
    URL url = new URL(NAME_HISTORY_URL.replace("%1", id.toString().replace("-", "")));
    System.out.println(url.toString());
    Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(url.openStream())));
    if (scanner.hasNext()) {
        String json = scanner.nextLine();
        try {
            JSONArray jsonArray = (JSONArray) new JSONParser().parse(json);
            if (json.length() > 0) {
                return (String) ((JSONObject) jsonArray.get(0)).get("name");
            }
        } catch (ParseException ignore) {
        }
    }

    throw new VoxelGameLibException("User has no name! " + id);
}
项目:edgex-java-connector    文件:JSONUtil.java   
public static int sizeJSON(String s) {
    Object obj;
    try {
        obj = new JSONParser().parse(new StringReader(s));
    } catch (IOException | ParseException e) {
        return 0;
    }

    if (obj instanceof JSONObject) {
        JSONObject jo = (JSONObject) obj;
        return jo.entrySet().size();
    }

    if (obj instanceof JSONArray) {
        JSONArray ja = (JSONArray) obj;
        return ja.size();
    }

    return 0;
}
项目:hono-weather-demo    文件:WeatherDataConsumer.java   
/**
 * handleWeatherMessage takes received telemetry message and processes it to be printed to command line.
 * @param msg Telemetry message received through hono server.
 */
private void handleWeatherMessage(final Message msg) {
    final Section body = msg.getBody();
    //Ensures that message is Data (type of AMQP messaging). Otherwise exits method.
    if (!(body instanceof Data))
        return;
    //Gets deviceID.
    final String deviceID = MessageHelper.getDeviceId(msg);
    //Creates JSON parser to read input telemetry weather data. Prints data to console output.
    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(((Data) msg.getBody()).getValue().toString());
        JSONObject payload = (JSONObject) obj;
        System.out.println(new StringBuilder("Device: ").append(deviceID).append("; Location: ").
                append(payload.get("location")).append("; Temperature:").append(payload.get("temperature")));
    } catch (ParseException e) {
        System.out.println("Data was not sent in a readable way. Check telemetry input.");
        e.printStackTrace();
    }
}
项目:nectar-server    文件:SessionToken.java   
public static SessionToken fromJSON(String json) {
    JSONParser parser = new JSONParser();

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

        if(!obj.containsKey("TOKENTYPE") || !obj.get("TOKENTYPE").equals(TOKEN_TYPE)) {
            return null;
        }

        if(!obj.containsKey("serverID") || !obj.containsKey("uuid") ||
                !obj.containsKey("timestamp") || !obj.containsKey("expires"))
            throw new IllegalArgumentException("JSON is invalid: missing keys!");

        return new SessionToken((String) obj.get("serverID"), (String) obj.get("uuid"), (long) obj.get("timestamp"), (long) obj.get("expires"));
    } catch (ParseException e) {
        throw new IllegalArgumentException(e);
    }
}
项目:open-kilda    文件:FlowFFRTest.java   
private String getController(String topologyFile) throws Exception {
    ClassLoader classLoader = getClass().getClassLoader();
    URL resource = classLoader.getResource(topologyFile);
    if (resource == null) {
        throw new IllegalArgumentException(String.format("No such topology json file: %s", topologyFile));
    }

    File file = new File(resource.getFile());
    String json = new String(Files.readAllBytes(file.toPath()));
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(json);
    JSONArray controllers = (JSONArray) jsonObject.get("controllers");

    JSONObject controller = (JSONObject) controllers.get(0);
    return  (String) controller.get("host");
}
项目:Habanero    文件:JSONReportMerger.java   
/**
 * merge source file into target
 *
 * @param target
 * @param source
 */
public void mergeFiles(File target, File source) throws Throwable {
    String targetReport = FileUtils.readFileToString(target);
    String sourceReport = FileUtils.readFileToString(source);

    JSONParser jp = new JSONParser();

    try {
        JSONArray parsedTargetJSON = (JSONArray) jp.parse(targetReport);
        JSONArray parsedSourceJSON = (JSONArray) jp.parse(sourceReport);
        // Merge two JSON reports
        parsedTargetJSON.addAll(parsedSourceJSON);
        // this is a new writer that adds JSON indentation.
        Writer writer = new JSONWriter();
        // convert our parsedJSON to a pretty form
        parsedTargetJSON.writeJSONString(writer);
        // and save the pretty version to disk
        FileUtils.writeStringToFile(target, writer.toString());
    } catch (ParseException pe) {
        pe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:alfresco-repository    文件:RemoteConnectorServiceImpl.java   
public static JSONObject doExecuteJSONRequest(RemoteConnectorRequest request, RemoteConnectorService service) throws ParseException, IOException, AuthenticationException
{
    // Set as JSON
    request.setContentType(MimetypeMap.MIMETYPE_JSON);

    // Perform the request
    RemoteConnectorResponse response = service.executeRequest(request);

    // Parse this as JSON
    JSONParser parser = new JSONParser();
    String jsonText = response.getResponseBodyAsString();
    Object json = parser.parse(jsonText);

    // Check it's the right type and return
    if (json instanceof JSONObject)
    {
        return (JSONObject)json;
    }
    else
    {
        throw new ParseException(0, json);
    }
}
项目:java-gps-tracking-server    文件:DBPropertiesResource.java   
/**
 *
 * @return @throws FileNotFoundException
 * @throws IOException
 * @throws ParseException
 */
public static DBProperties getInstance() throws FileNotFoundException, IOException, ParseException {
    DBProperties properties = new DBProperties();
    JSONParser jsonParser = new JSONParser();
    Object file = jsonParser.parse(new FileReader(new File(Context.getDbConfig())));

    JSONObject jsonObject = (JSONObject) file;

    properties.setDbhost((String) jsonObject.get("db_host"));
    properties.setDbname((String) jsonObject.get("db_name"));
    properties.setDbport((String) jsonObject.get("db_port"));
    properties.setDbuser((String) jsonObject.get("db_user"));
    properties.setPassword((String) jsonObject.get("password"));
    properties.setUrl((String) jsonObject.get("access_url"));
    properties.setDriver((String) jsonObject.get("jdbc_driver_class"));

    LOGGER.debug("DB Connection: " + properties.getConnectionUrl());
    return properties;
}
项目:JodelAPI    文件:JodelAccount.java   
/**
 * Refreshes the Access Token of the currently used account
 */
public void refreshAccessToken() {
    this.updateHTTPParameter();
    JodelHTTPResponse requestResponse = this.httpAction.getNewAccessToken();
    if (requestResponse.responseCode == 200) {
        String responseMessage = requestResponse.responseMessage;
        JSONParser parser = new JSONParser();
        try {
            JSONObject responseJson = (JSONObject) parser.parse(responseMessage);
            this.accessToken = responseJson.get("access_token").toString();
            this.expirationDate = responseJson.get("expiration_date").toString();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
项目:JodelAPI    文件:JodelAccount.java   
/**
 * Get share url
 * @param postID ID of the post to share
 * @return The requestResponse of type JodelRequestResponse
 */
public JodelRequestResponse getJodelShareLink(String postID) {
    JodelRequestResponse requestResponse = new JodelRequestResponse();
    this.updateHTTPParameter();
    JodelHTTPResponse getShareLink = this.httpAction.getJodelShareURL(postID);
    requestResponse.httpResponseCode = getShareLink.responseCode;
    if (getShareLink.responseCode == 200) {
        String responseJodelsMessage = getShareLink.responseMessage;
        requestResponse.rawResponseMessage = responseJodelsMessage;
        JSONParser parser = new JSONParser();
        try {
            JSONObject responseJson = (JSONObject) parser.parse(responseJodelsMessage);
            String url = (String) responseJson.get("url");
            requestResponse.responseValues.put("shareLink", url);
        } catch (Exception e) {
            requestResponse.rawErrorMessage = e.getMessage();
            e.printStackTrace();
            requestResponse.error = true;
            requestResponse.errorMessage = "Could not parse response JSON!";
        }
    } else {
        requestResponse.error = true;
    }
    return requestResponse;
}
项目:JodelAPI    文件:JodelAccount.java   
/**
 * Gets your karma
 * @return The requestResponse of type JodelRequestResponse
 */
public JodelRequestResponse getKarma() {
    JodelRequestResponse requestResponse = new JodelRequestResponse();
    this.updateHTTPParameter();
    JodelHTTPResponse karmaResponse = this.httpAction.getKarma();
    requestResponse.httpResponseCode = karmaResponse.responseCode;
    if (requestResponse.httpResponseCode == 200) {
        String responseKarma = karmaResponse.responseMessage;
        requestResponse.rawResponseMessage = responseKarma;
        JSONParser parserCaptcha = new JSONParser();
        try {
            JSONObject responseCaptchaJson = (JSONObject) parserCaptcha.parse(responseKarma);
            String karma = responseCaptchaJson.get("karma").toString();
            requestResponse.responseValues.put("karma", karma);

        } catch (ParseException e) {
            requestResponse.rawErrorMessage = e.getMessage();
            e.printStackTrace();
            requestResponse.error = true;
            requestResponse.errorMessage = "Could not parse response JSON!";
        }
    } else {
        requestResponse.error = true;
    }
    return requestResponse;
}
项目:Cognizant-Intelligent-Test-Scripter    文件:AbstractHttpClient.java   
/**
 * Builds URL params from input JSON string
 *
 * @param builder
 * @param jsonStr
 * @return
 * @throws ParseException
 */
public URIBuilder setParams(URIBuilder builder, String jsonStr) throws ParseException {

    if (jsonStr != null && !"".equals(jsonStr)) {
        try {
            JSONParser parser = new JSONParser();
            JSONObject json = (JSONObject) parser.parse(jsonStr);
            json.keySet().forEach((Key) -> {
                builder.setParameter(Key.toString(), (String) json.get(Key));
            });
        } catch (Exception ex) {
            DLogger.LogE(ex.getMessage());
            LOG.log(Level.SEVERE, ex.getMessage(), ex);
        }

    }

    return builder;
}
项目:durafficpark    文件:OSMNode.java   
@Override
public JSONObject getJSON() {
    try {
        JSONObject nodeJSON = new JSONObject();
        JSONParser parser = new JSONParser();

        nodeJSON.put("id", id);
        nodeJSON.put("lat", lat);
        nodeJSON.put("lon", lon);
        nodeJSON.put("tags", parser.parse(gson.toJson(tags)));
        return nodeJSON;
    }
    catch (ParseException e){
        System.err.println("Error caught in parsing gson object");
        return null;
    }
}
项目:rskj    文件:RemascConfigFactory.java   
public RemascConfig createRemascConfig(String config) {
    RemascConfig remascConfig;

    try (InputStream is = RemascConfigFactory.class.getClassLoader()
            .getResourceAsStream(this.configPath); InputStreamReader fileReader = new InputStreamReader(is)){

        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(fileReader);
        JSONObject jsonConfig = (JSONObject) jsonObject.get(config);
        String remascString = jsonConfig.toString();
        remascConfig = mapper.readValue(remascString, RemascConfig.class);
    } catch (Exception ex) {
        logger.error("Error reading REMASC configuration[{}]: {}", config, ex);
        throw new RemascException("Error reading REMASC configuration[" + config +"]: ", ex);
    }

    return remascConfig;
}
项目:rskj    文件:AccountFileLoader.java   
public ConcurrentMap<String, AccountData> load() {
    ConcurrentHashMap<String, AccountData> accounts = new ConcurrentHashMap<>();
    if(Files.exists(filePath)) {
        try (FileReader fileReader = new FileReader(this.filePath.toString())){
            JSONParser parser = new JSONParser();
            Object json = parser.parse(fileReader);
            JSONObject jsonObject = (JSONObject) json;
            JSONArray jsonAccounts = (JSONArray) jsonObject.get("accounts");

            for(Object obj : jsonAccounts) {
                JSONObject jobj = (JSONObject) obj;
                String acc  = (String) jobj.get("account");
                String add  = (String) jobj.get("address");
                accounts.put((String) jobj.get("ip"), new AccountData(stringHexToByteArray(add), stringHexToByteArray(acc)));
            }
        } catch (ParseException | IOException e) {
            logger.error("Error reading accounts file", e);
        }
    }
    return accounts;
}
项目:eXperDB-DB2PG    文件:MySqlConvertMapper.java   
@Override
protected void init() throws FileNotFoundException, IOException, ParseException {
    JSONParser jsonParser = new JSONParser();

    JSONObject convMapObj = (JSONObject)jsonParser.parse(new InputStreamReader(MySqlConvertMapper.class.getResourceAsStream("/convert_map.json")));

    convertPatternValues = new ArrayList<ConvertVO>(30);
    convertDefaultValues = new ArrayList<ConvertVO>(5);
    for(Object key : convMapObj.keySet().toArray()) {
        JSONObject jobj = (JSONObject)convMapObj.get(key);
        String toValue = (String)jobj.get("postgres");
        JSONArray asValues = (JSONArray) jobj.get("mysql");
        if(toValue != null && asValues != null) {
            for (Object asValue : asValues) {
                if(asValue instanceof String) {
                    ConvertVO convVal = new ConvertVO((String)asValue,toValue);
                    if(convVal.getPattern() != null) convertPatternValues.add(convVal);
                    else convertDefaultValues.add(convVal);
                }
            }
        }
    }
}
项目:httpjson    文件:HttpJson.java   
private void taskDone(String response)
{
    // If just post call then return
    if (this.taskHandler == null) return;

    if (response != null) response = response.replace("\uFEFF", "");
    JSONParser jsonParser = new JSONParser();

    try
    {
        JSONObject root = (JSONObject) jsonParser.parse(response);
        taskHandler.done(new HttpJsonObject(root));
    }
    catch (ParseException e)
    {
        e.printStackTrace();
        taskHandler.done(new HttpJsonObject(response));
    }
}
项目:scorekeeperfrontend    文件:MergeServer.java   
public MergeServer(ResultSet rs) throws SQLException
{
    serverid    = (UUID)rs.getObject("serverid");
    hostname    = rs.getString("hostname");
    address     = rs.getString("address");
    lastcheck   = rs.getTimestamp("lastcheck", Database.utc);
    nextcheck   = rs.getTimestamp("nextcheck", Database.utc);
    waittime    = rs.getInt("waittime");
    ctimeout    = rs.getInt("ctimeout");
    cfailures   = rs.getInt("cfailures");
    String hs   = rs.getString("hoststate");
    switch (hs) {
        case "A": hoststate = HostState.ACTIVE; break;
        case "1": hoststate = HostState.ONESHOT; break;
        case "I": hoststate = HostState.INACTIVE; break;
        default:  hoststate = HostState.UNKNOWN; break;
    }
    seriesstate = new HashMap<String, JSONObject>();
    try {
        JSONObject mergestate = (JSONObject)new JSONParser().parse(rs.getString("mergestate"));
        for (Object o : mergestate.keySet()) {
            seriesstate.put((String)o, (JSONObject)mergestate.get(o));
        }
    } catch (ParseException e) {
    }
}
项目:Locked    文件:MerchantManager.java   
public static ArrayList<String> getAllNPCs() {
    ArrayList<String> a = new ArrayList<>();
    try {
        File file = plugin.getPath().getAbsoluteFile();
        JSONParser parser = new JSONParser();
        Object parsed = parser.parse(new FileReader(file.getPath()));
        JSONObject jsonObject = (JSONObject) parsed;
        JSONArray npcsArray = (JSONArray) jsonObject.get("npcs");
        for (Object npc : npcsArray) {
            a.add((String) ((JSONObject) npc).get("name"));

        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    }
    return a;
}
项目:legendarybot    文件:IlvlCommand.java   
public long getM5(String json) throws ParseException {
    long m5 = 0;
    if (json != null) {
        JSONParser parser = new JSONParser();
        JSONObject battleNetCharacter = (JSONObject) parser.parse(json);
        JSONObject achivements = (JSONObject) battleNetCharacter.get("achievements");
        JSONArray criteriaObject = (JSONArray) achivements.get("criteria");
        int criteriaNumber = -1;
        for (int i = 0; i < criteriaObject.size(); i++) {
            if ((long)criteriaObject.get(i) == 33097) {
                criteriaNumber = i;
            }
        }

        if (criteriaNumber != -1) {
            m5 = (long) ((JSONArray)achivements.get("criteriaQuantity")).get(criteriaNumber);
            if (m5 >= 1) {
                m5 += 1;
            }
        }
    }
    return m5;
}
项目:legendarybot    文件:IlvlCommand.java   
public long getM10(String json) throws ParseException {
    long m10 = 0;
    if (json != null) {
        JSONParser parser = new JSONParser();
        JSONObject battleNetCharacter = (JSONObject) parser.parse(json);
        JSONObject achivements = (JSONObject) battleNetCharacter.get("achievements");
        JSONArray criteriaObject = (JSONArray) achivements.get("criteria");
        int criteriaNumber = -1;
        for (int i = 0; i < criteriaObject.size(); i++) {
            if ((long)criteriaObject.get(i) == 33098) {
                criteriaNumber = i;
            }
        }

        if (criteriaNumber != -1) {
            m10 = (long) ((JSONArray)achivements.get("criteriaQuantity")).get(criteriaNumber);
            if (m10 >= 1) {
                m10 += 1;
            }
        }
    }
    return m10;
}
项目:legendarybot    文件:IlvlCommand.java   
public long getM15(String json) throws ParseException {
    long m15 = 0;
    if (json != null) {
        JSONParser parser = new JSONParser();
        JSONObject battleNetCharacter = (JSONObject) parser.parse(json);
        JSONObject achivements = (JSONObject) battleNetCharacter.get("achievements");
        JSONArray criteriaObject = (JSONArray) achivements.get("criteria");
        int criteriaNumber = -1;
        for (int i = 0; i < criteriaObject.size(); i++) {
            if ((long)criteriaObject.get(i) == 32028    ) {
                criteriaNumber = i;
            }
        }

        if (criteriaNumber != -1) {
            m15 = (long) ((JSONArray)achivements.get("criteriaQuantity")).get(criteriaNumber);
            if (m15 >= 1) {
                m15 += 1;
            }
        }
    }
    return m15;
}
项目:aws-lambda-proxy-java    文件:LambdaProxyHandlerTest.java   
@Test
public void shouldReturnServerErrorAndReasonWhenMisconfigured() throws ParseException {
    ApiGatewayProxyRequest request = new ApiGatewayProxyRequestBuilder()
            .withHttpMethod(METHOD)
            .build();
    LambdaProxyHandler<Configuration> handlerWithFailingConguration = new TestLambdaProxyHandlerWithFailingConguration();
    handlerWithFailingConguration.registerMethodHandler(METHOD, c -> methodHandler);

    ApiGatewayProxyResponse actual = handlerWithFailingConguration.handleRequest(request, context);

    assertThat(actual).isNotNull();
    assertThat(actual.getStatusCode()).isEqualTo(INTERNAL_SERVER_ERROR.getStatusCode());
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = (JSONObject) jsonParser.parse(actual.getBody());
    assertThat(jsonObject.keySet()).contains("message", "cause");
    assertThat((String) jsonObject.get("message")).contains("This service is mis-configured. Please contact your system administrator.");
    assertThat((String) jsonObject.get("cause")).contains("NullPointerException");
}
项目:ServerlessPlatform    文件:ServiceGateway.java   
@SuppressWarnings("unchecked")
JSONObject doAuthentication(JSONObject svcReq, String reqId){
    JSONObject reply = null;
    JSONObject authReq = new JSONObject();
    communicateWithMQ mqHandler = new communicateWithMQ();
    mqHandler.connectToBroker();
    String replyMq = mqHandler.createMq("svcQueueServiceGatewayAuthnReply");

    authReq.put("svcName", "AuthenticationService");
    authReq.put("funcName", "authenticateUser");
    authReq.put("usrId", svcReq.get("usrId").toString());
    authReq.put("reqId", reqId);

    JSONArray params = new JSONArray();
    JSONObject tmp = new JSONObject();
    tmp.put("name", "param1");  //usrId
    tmp.put("type", "String");
    tmp.put("value", svcReq.get("usrId").toString());
    params.add(tmp);
    JSONObject tmp1 = new JSONObject();
    tmp1.put("name", "param2"); //passwd
    tmp1.put("type", "String");
    tmp1.put("value", svcReq.get("passwd").toString());
    params.add(tmp1);
    authReq.put("params", params);
    System.out.println(authReq);
    mqHandler.send("svcQueueAuthenticationService", authReq, replyMq);
    JSONParser parser = new JSONParser();
    try {
        String str = mqHandler.listenAndFilter().get("response").toString();
        mqHandler.disconnect();
        System.out.println("Response from Auth svc "+str);
        reply = (JSONObject) parser.parse(str);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return reply;
}
项目:open-weather-retriever-z    文件:OpenWeatherRetrieverZ.java   
private JSONObject readJsonFromUrl(String url) throws IOException, ParseException{
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      JSONParser jParser = new JSONParser();
      return (JSONObject) jParser.parse(rd);
    } finally {
      is.close();
    }
}
项目:edgex-java-connector    文件:JSONUtil.java   
public static JSONObject parseJSON(String s) {
    Object obj;
    try {
        obj = new JSONParser().parse(new StringReader(s));
    } catch (IOException | ParseException e) {
        return null;
    }

       JSONObject jo = (JSONObject) obj;
       return jo;
}
项目:uppercore    文件:Flatfile.java   
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> ask() {
    JSONParser parser = new JSONParser();
    try {
        return (Map<String, Object>) parser.parse(new FileReader(file));
    } catch (IOException | ParseException e) {
        return new HashMap<>();
    }
}
项目:incubator-netbeans    文件:DOMTest.java   
/**
 * Test of {@code handleAttributeModified} method.
 */
@Test
public void testHandleAttributeModified() 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 String ATTR_VALUE = "myclass"; // NOI18N
    final int[] eventsFired = new int[1];
    DOM.Listener listener = new DOMAdapter() {
        @Override
        public void attributeModified(Node node, String attrName, String attrValue) {
            eventsFired[0]++;
            assertEquals(ATTR_NAME, attrName);
            assertEquals(root, node);
            Node.Attribute attr = node.getAttribute(attrName);
            assertNotNull(attr);
            assertEquals(ATTR_VALUE, attr.getValue());
            assertEquals(ATTR_VALUE, attrValue);
        }
    };
    dom.addListener(listener);
    JSONParser parser = new JSONParser();

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

    // Modification of an unknown node
    json = parser.parse("{\"nodeId\":" + (ROOT_NODE_ID+1) + ",\"name\":\"someName\",\"value\":\"someValue\"}"); // NOI18N
    dom.handleAttributeModified((JSONObject)json);
    assertEquals(1, eventsFired[0]);
}
项目:incubator-netbeans    文件:DOMTest.java   
/**
 * 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]);
}
项目:incubator-netbeans    文件:DOMTest.java   
/**
 * Test of {@code handleCharacterDataModified} method.
 */
@Test
public void testHandleCharacterDataModified() throws ParseException {
    TransportImplementation transport = new DummyTransportImplementation();
    DOM dom = new DOM(new TransportHelper(transport), null);
    final Node root = dom.getDocument();
    final String DATA = "myData"; // NOI18N
    final int[] eventsFired = new int[1];
    DOM.Listener listener = new DOMAdapter() {
        @Override
        public void characterDataModified(Node node) {
            eventsFired[0]++;
            assertEquals(root, node);
            String value = root.getNodeValue();
            assertEquals(DATA, value);
        }
    };
    dom.addListener(listener);
    JSONParser parser = new JSONParser();

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

    // Modification of an unknown node
    json = parser.parse("{\"nodeId\":" + (ROOT_NODE_ID+1) + ",\"characterData\":\"someData\"}"); // NOI18N
    dom.handleCharacterDataModified((JSONObject)json);
    assertEquals(1, eventsFired[0]);
}
项目:incubator-netbeans    文件:DOMTest.java   
/**
 * Test of {@code handleSetChildNodes} method.
 */
@Test
public void testHandleSetChildNodes1() throws ParseException {
    TransportImplementation transport = new DummyTransportImplementation();
    DOM dom = new DOM(new TransportHelper(transport), null);
    final Node root = dom.getDocument();
    final int[] eventsFired = new int[1];
    DOM.Listener listener = new DOMAdapter() {
        @Override
        public void childNodesSet(Node parent) {
            eventsFired[0]++;
            assertEquals(root, parent);
            List<Node> children = parent.getChildren();
            assertNotNull(children);
            assertEquals(0, children.size());
        }
    };
    dom.addListener(listener);
    JSONParser parser = new JSONParser();

    // Modification of a known node
    Object json = parser.parse("{\"parentId\":" + ROOT_NODE_ID + ",\"nodes\":[]}"); // NOI18N
    assertNull(root.getChildren());
    dom.handleSetChildNodes((JSONObject)json);
    assertEquals(1, eventsFired[0]);

    // Modification of an unknown node
    json = parser.parse("{\"parentId\":" + (ROOT_NODE_ID+1) + ",\"nodes\":[]}"); // NOI18N
    dom.handleSetChildNodes((JSONObject)json);
    assertEquals(1, eventsFired[0]);
}
项目:incubator-netbeans    文件:DOMTest.java   
/**
 * Test of {@code handleChildNodeInserted} method.
 */
@Test
public void testHandleChildNodeInserted() throws ParseException {
    TransportImplementation transport = new DummyTransportImplementation();
    DOM dom = new DOM(new TransportHelper(transport), null);
    final Node root = dom.getDocument();
    final int CHILD_ID = 2;
    final String CHILD_NAME = "DIV"; // NOI18N
    final int[] eventsFired = new int[1];
    DOM.Listener listener = new DOMAdapter() {
        @Override
        public void childNodeInserted(Node parent, Node child) {
            eventsFired[0]++;
            assertEquals(root, parent);
            List<Node> children = parent.getChildren();
            assertNotNull(children);
            assertEquals(1, children.size());
            assertEquals(child, children.get(0));
            assertEquals(CHILD_ID, child.getNodeId());
            assertEquals(CHILD_NAME, child.getNodeName());
        }
    };
    dom.addListener(listener);
    JSONParser parser = new JSONParser();

    // Modification of a known node
    Object json = parser.parse("{\"node\":{\"childNodeCount\":0,\"localName\":\"div\",\"nodeId\":" + // NOI18N
            CHILD_ID + ",\"nodeValue\":\"\",\"nodeName\":\"" + // NOI18N
            CHILD_NAME + "\",\"attributes\":[],\"nodeType\":1},\"parentNodeId\":" + // NOI18N
            ROOT_NODE_ID + ",\"previousNodeId\":0}"); // NOI18N
    assertNull(root.getChildren());
    dom.handleChildNodeInserted((JSONObject)json);
    assertEquals(1, eventsFired[0]);

    // Modification of an unknown node
    json = parser.parse("{\"node\":{\"childNodeCount\":0,\"localName\":\"div\",\"nodeId\":5,\"nodeValue\":\"\",\"nodeName\":\"DIV\",\"attributes\":[],\"nodeType\":1},\"parentNodeId\":5,\"previousNodeId\":0}"); // NOI18N
    dom.handleChildNodeInserted((JSONObject)json);
    assertEquals(1, eventsFired[0]);
}
项目:r8    文件:Marker.java   
private static Marker internalParse(Tool tool, String str) {
  try {
    Object result =  new JSONParser().parse(str);
    if (result instanceof JSONObject) {
      return new Marker(tool, (JSONObject) result);
    }
  } catch (ParseException e) {
    // Fall through.
  }
  return null;
}
项目:nectar-server    文件:ManagementSessionToken.java   
public static ManagementSessionToken fromJSON(String json) {
    JSONParser parser = new JSONParser();

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

        if(!obj.containsKey("TOKENTYPE") || !obj.get("TOKENTYPE").equals(TOKEN_TYPE)) {
            return null;
        }

        if(!obj.containsKey("serverID") || !obj.containsKey("clientIP") ||
                !obj.containsKey("timestamp") || !obj.containsKey("expires"))
            throw new IllegalArgumentException("JSON is invalid: missing keys!");

        return new ManagementSessionToken((String) obj.get("serverID"), (String) obj.get("clientIP"), (long) obj.get("timestamp"), (long) obj.get("expires"));
    } catch (ParseException e) {
        throw new IllegalArgumentException(e);
    }
}
项目:streamsx.jmxclients    文件:JobDetails.java   
private String resolvePortNames(String metricsSnapshot) {
    if (metricsSnapshot != null) {

        JSONParser parser = new JSONParser();
        try {
            JSONObject metricsObject = (JSONObject) parser.parse(metricsSnapshot);

            JSONArray peArray = (JSONArray) metricsObject.get("pes");

            for (int i = 0; i < peArray.size(); i++) {
                JSONObject pe = (JSONObject) peArray.get(i);

                // resolvePeInputPortNames(pe);
                // resolvePeOutputPortNames(pe);

                JSONArray operatorArray = (JSONArray) pe.get("operators");

                for (int j = 0; j < operatorArray.size(); j++) {
                    JSONObject operator = (JSONObject) operatorArray.get(j);

                    resolveOperatorInputPortNames(operator);
                    resolveOperatorOutputPortNames(operator);
                }
            }

            metricsSnapshot = metricsObject.toJSONString();
        } catch (ParseException e) {
            throw new IllegalStateException(e);
        }
    }

    return metricsSnapshot;
}
项目:hadoop    文件:TestHttpFSServer.java   
/**
 * Given the JSON output from the GETACLSTATUS call, return the
 * 'entries' value as a List<String>.
 * @param statusJson JSON from GETACLSTATUS
 * @return A List of Strings which are the elements of the ACL entries
 * @throws Exception
 */
private List<String> getAclEntries ( String statusJson ) throws Exception {
  List<String> entries = new ArrayList<String>();
  JSONParser parser = new JSONParser();
  JSONObject jsonObject = (JSONObject) parser.parse(statusJson);
  JSONObject details = (JSONObject) jsonObject.get("AclStatus");
  JSONArray jsonEntries = (JSONArray) details.get("entries");
  if ( jsonEntries != null ) {
    for (Object e : jsonEntries) {
      entries.add(e.toString());
    }
  }
  return entries;
}
项目:otus_java_2017_06    文件:SocketMsgClient.java   
private static Msg getMsgFromJSON(String json) throws ParseException, ClassNotFoundException {
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = (JSONObject) jsonParser.parse(json);
    String className = (String) jsonObject.get(Msg.CLASS_NAME_VARIABLE);
    Class<?> msgClass = Class.forName(className);
    return (Msg) new Gson().fromJson(json, msgClass);
}
项目:otus_java_2017_04    文件:SocketClientChannel.java   
private Msg getMsgFromJSON(String json) throws ParseException, ClassNotFoundException {
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = (JSONObject) jsonParser.parse(json);
    String className = (String) jsonObject.get(Msg.CLASS_NAME_VARIABLE);
    Class<?> msgClass = Class.forName(className);
    return (Msg) new Gson().fromJson(json, msgClass);
}
项目:ServerlessPlatform    文件:coreServiceFramework.java   
public void doLogging(String logStr, String severity){
       try {
        JSONParser parser = new JSONParser();
        JSONObject reqJson = (JSONObject)parser.parse(new FileReader(tmpDir+"request.json"));
        //System.out.println(reqJson);
        doLogging(reqJson, "service", reqJson.get("serverId").toString(), 
                reqJson.get("processId").toString(), (String)reqJson.get("funcName"), logStr, severity);
       }
       catch(Exception e){
        e.printStackTrace();
       }    
}
项目:acmeair-modular    文件:FlightServiceImpl.java   
@Override 
public void storeFlightSegment(String flightSeg){
    try {
        JSONObject flightSegJson = (JSONObject) new JSONParser().parse(flightSeg);
        storeFlightSegment ((String)flightSegJson.get("_id"), 
                (String)flightSegJson.get("originPort"), 
                (String)flightSegJson.get("destPort"), 
                (int)flightSegJson.get("miles"));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}