Example usage for org.json.simple.parser JSONParser JSONParser

List of usage examples for org.json.simple.parser JSONParser JSONParser

Introduction

In this page you can find the example usage for org.json.simple.parser JSONParser JSONParser.

Prototype

JSONParser

Source Link

Usage

From source file:eu.celarcloud.celar_ms.ServerPack.AgentRegister.java

public void run() {
    if (this.server.inDebugMode())
        System.out.println(/*  w ww  . j ava 2 s.  c o m*/
                "AgentRegister>> processing the following message...\n" + msg[0] + " " + msg[1] + " " + msg[2]);
    try {
        JSONParser parser = new JSONParser();
        JSONObject json;

        json = (JSONObject) parser.parse(msg[2]); //parse content

        if (msg[1].equals("AGENT.CONNECT"))
            connect(json);
        else if (msg[1].equals("AGENT.METRICS"))
            metrics(json);
        else
            this.response(Status.ERROR, msg[1] + " request does not exist");
    } catch (NullPointerException e) {
        this.server.writeToLog(Level.SEVERE, e);
    } catch (Exception e) {
        this.server.writeToLog(Level.SEVERE, e);
    }
}

From source file:com.pearson.eidetic.driver.threads.RefreshAwsAccountVolumes.java

@Override
public void run() {

    ConcurrentHashMap<Region, ArrayList<Volume>> localVolumeNoTime;

    localVolumeNoTime = awsAccount_.getVolumeNoTime_Copy();

    ConcurrentHashMap<Region, ArrayList<Volume>> localVolumeTime;

    localVolumeTime = awsAccount_.getVolumeTime_Copy();

    ConcurrentHashMap<Region, ArrayList<Volume>> localCopyVolumeSnapshots;

    localCopyVolumeSnapshots = awsAccount_.getCopyVolumeSnapshots_Copy();

    JSONParser parser = new JSONParser();

    for (Map.Entry<com.amazonaws.regions.Region, ArrayList<Volume>> entry : localVolumeNoTime.entrySet()) {
        com.amazonaws.regions.Region region = entry.getKey();
        AmazonEC2Client ec2Client = connect(region, awsAccount_.getAwsAccessKeyId(),
                awsAccount_.getAwsSecretKey());

        List<Volume> volumes = initialization(ec2Client, localVolumeNoTime, localVolumeTime,
                localCopyVolumeSnapshots, region);

        for (Volume volume : volumes) {

            JSONObject eideticParameters;
            eideticParameters = getEideticParameters(volume, parser);
            if (eideticParameters == null) {
                continue;
            }//ww  w.ja  va2s. c  o m

            JSONObject createSnapshot;
            createSnapshot = getCreateSnapshot(volume, eideticParameters);
            if (createSnapshot == null) {
                continue;
            }

            HashMap<Integer, ConcurrentHashMap<Region, ArrayList<Volume>>> resultSet;
            resultSet = refreshCreateSnapshotVolumes(volume, createSnapshot, localVolumeTime, localVolumeNoTime,
                    region);
            if (resultSet == null) {
                continue;
            }
            if (resultSet.isEmpty()) {
                continue;
            }

            try {
                localVolumeTime = resultSet.get(0);
                localVolumeNoTime = resultSet.get(1);
            } catch (Exception e) {
                logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=\"Error\", Error=\"error getting from resultSet\", Volume_id=\""
                        + volume.getVolumeId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
            }

            //Time for CopyVolumeSnapshots
            //If this volume does not have copysnapshot
            localCopyVolumeSnapshots = refreshCopyVolumeSnapshots(volume, eideticParameters,
                    localCopyVolumeSnapshots, region);

        }

        localVolumeTime = processLocalVolumeTime(localVolumeTime, region);

        localVolumeNoTime = processLocalVolumeNoTime(localVolumeNoTime, region);

        localCopyVolumeSnapshots = processLocalCopyVolumeSnapshots(localCopyVolumeSnapshots, region);

        ec2Client.shutdown();

    }

    awsAccount_.replaceVolumeNoTime(localVolumeNoTime);

    awsAccount_.replaceVolumeTime(localVolumeTime);

    awsAccount_.replaceCopyVolumeSnapshots(localCopyVolumeSnapshots);

}

From source file:ClubImpl.java

public String getFAQ() {
    JSONParser parser = new JSONParser();

    Object obj = null;//from  w ww .ja  va2s.  c o  m
    try {
        File f = new File(".");
        System.out.println(f.getAbsolutePath());
        File relative = new File("FAQs.json");
        obj = parser.parse(new FileReader(relative));
    } catch (Exception ex) {
        Logger.getLogger(ClubImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    JSONObject jsonObject = (JSONObject) obj;
    return jsonObject.toJSONString();

}

From source file:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingHttpClient(String URL, JSONObject jsonObjSend) {

    try {//from w  ww . j a v a 2 s .  c om
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 60 * 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 60 * 1000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        //httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        //httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        Log.d(TAG, "httpPostReuest = " + httpPostRequest.toString());
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;
        }

    } catch (Exception e) {
        Log.d(TAG, "catch block");
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    Log.d(TAG, "SendHttpPostUsingHttpClient returning null");
    return null;
}

From source file:fi.aalto.drumbeat.apicalls.marmotta.MarmottaAPI.java

@SuppressWarnings("unchecked")
public void httpGetMarmottaContexts(Table table) {

    try {/*ww w .j a  v  a 2  s  .c o m*/
        if (table.isVisible())
            table.removeAllItems();
    } catch (Exception e) {
        //update before table initalization?
        return;
    }
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpGet request = new HttpGet(DrumbeatConstants.marmotta_context_query_url);
        HttpResponse http_result = httpClient.execute(request);

        String json = EntityUtils.toString(http_result.getEntity(), "UTF-8");
        try {
            JSONParser parser = new JSONParser();
            Object resultObject = parser.parse(json);
            if (resultObject instanceof JSONArray) {
                JSONArray result = (JSONArray) resultObject;
                if (result != null) {
                    for (Object obj : result) {

                        // Add a row the hard way
                        Object newItemId = table.addItem();
                        Item row = table.getItem(newItemId);

                        JSONObject project = (JSONObject) obj;
                        String name = (String) project.get("label");
                        if (name != null)
                            row.getItemProperty("Graph").setValue(name);
                        else
                            row.getItemProperty("Graph").setValue("-");

                        Long size = (Long) project.get("size");
                        if (size != null)
                            row.getItemProperty("Size").setValue(size);
                        else
                            row.getItemProperty("Size").setValue("-");

                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    }
    // Show exactly the currently contained rows (items)
    table.setPageLength(table.size());
}

From source file:org.exoplatform.social.client.core.util.SocialJSONDecodingSupport.java

/**
 * Parse JSON text into java Map object from the input source.
 *  /*from w  ww  .j  ava  2s.c om*/
 * @param jsonContent Json content which you need to create the Model
 * @throws ParseException Throw this exception if any
 */
public static Map parser(String jsonContent) throws ParseException {
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        public List creatArrayContainer() {
            return new LinkedList();
        }

        public Map createObjectContainer() {
            return new LinkedHashMap();
        }
    };
    return (Map) parser.parse(jsonContent, containerFactory);
}

From source file:eu.celarcloud.jcatascopia.serverpack.AgentRegister.java

public void run() {
    if (this.server.inDebugMode())
        System.out.println(//from w  w  w.  jav a  2  s . com
                "AgentRegister>> processing the following message...\n" + msg[0] + " " + msg[1] + " " + msg[2]);
    try {
        JSONParser parser = new JSONParser();
        JSONObject json;

        json = (JSONObject) parser.parse(msg[2]); //parse content
        if (msg[1].equals("AGENT.JOIN"))
            joinM(json);
        else if (msg[1].equals("AGENT.CONNECT"))
            connect(json);
        else if (msg[1].equals("AGENT.METRICS"))
            metrics(json);
        else
            this.response(Status.ERROR, msg[1] + " request does not exist");
    } catch (NullPointerException e) {
        this.server.writeToLog(Level.SEVERE, e);
        e.printStackTrace();
    } catch (Exception e) {
        this.server.writeToLog(Level.SEVERE, e);
    }
}

From source file:jp.co.applibot.backup.BackupController.java

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String json = "";
    String className = "";
    String key = "";
    Long now = new Date().getTime();
    if (request != null) {
        BufferedReader bufferReaderBody = new BufferedReader(request.getReader());
        String body = bufferReaderBody.readLine();
        json = body;// w  w w  .  j a va  2s . c o m
    }

    int indexLast = json.indexOf("\":");
    if (indexLast > 0) {
        className = json.substring(1, indexLast);
    }
    className = className.replaceAll("\"", "");

    JSONParser parser = new JSONParser();
    //      try {
    //          
    //         Object wrapObj = parser.parse(json);
    //   
    //         JSONObject jsonWrapObject = (JSONObject) wrapObj;
    //    
    //         String jsonObj = jsonWrapObject.get(className).toString();
    //         
    //         Object obj = parser.parse(jsonObj);
    //         
    //         JSONObject jsonObject = (JSONObject) obj;
    //         
    //         key = jsonObject.get("id").toString();
    //    
    //      } catch (ParseException e) {
    //         e.printStackTrace();
    //      }

    JSch jsch = new JSch();
    String host = "107.167.177.138";
    String user = "dmlogging";
    String passwd = "Applibot12345";
    try {
        Session session = jsch.getSession(user, host, 22);
        session.setPassword(passwd);
        session.connect(30000);
        Channel channel = session.openChannel("exec");
        // ((ChannelExec)channel).setCommand("\"" + json +"\"" +  ">> /home/komiya_sakura_applibot_co_jp/test.txt");
        ((ChannelExec) channel).setCommand("mkdir /home/komiya_sakura_applibot_co_jp/logfiles");
        LOGGER.warning("command set");
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);

        InputStream in = channel.getInputStream();

        channel.connect();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                LOGGER.warning(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                if (in.available() > 0)
                    continue;
                LOGGER.warning("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
    } catch (JSchException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    GcsFilename fileName = new GcsFilename(BUCKETNAME, className + "_" + now.toString() + "_" + key);
    GcsFileOptions options = new GcsFileOptions.Builder().mimeType("text/html").acl("public-read").build();
    GcsOutputChannel outputChannel = gcsService.createOrReplace(fileName, options);

    outputChannel.write(ByteBuffer.wrap(json.getBytes("UTF8")));
    outputChannel.close();

    //reply
    PrintWriter out = response.getWriter();
    out.println(json);
}

From source file:com.acmeair.jmeter.functions.ExtrackBookingInfoFunction.java

private void processJSonString(SampleResult sample) {

    try {//www .ja  va  2 s. c o m
        Object returnObject = new JSONParser().parse(sample.getResponseDataAsString());
        JSONArray jsonArray;
        if (returnObject instanceof JSONArray) {
            jsonArray = (JSONArray) returnObject;
        } else {
            throw new RuntimeException("failed to parse booking information: " + returnObject.toString());
        }
        int bookingNum = jsonArray.size();

        context.setNUMBER_OF_BOOKINGS(bookingNum + "");

        if (bookingNum > 2) {
            context.setNUMBER_TO_CANCEL(bookingNum - 2 + "");
        } else {
            context.setNUMBER_TO_CANCEL("0");
        }
        String[] bookingIds = new String[bookingNum];
        for (int counter = 0; counter < bookingNum; counter++) {
            JSONObject booking = (JSONObject) jsonArray.get(counter);// .pkey.id;
            String bookingId;
            if (ExtractFlightsInfoFunction.pureIDs) {
                bookingId = (String) booking.get("_id");
            } else {
                JSONObject bookingPkey = (JSONObject) booking.get("pkey");
                bookingId = (String) bookingPkey.get("id");
            }
            bookingIds[counter] = bookingId;
        }
        context.setBOOKING_IDs(bookingIds);
        BookingThreadLocal.set(context);

    } catch (ParseException e) {
        System.out.println("responseDataAsString = " + sample.getResponseDataAsString());
        e.printStackTrace();
    } catch (NullPointerException e) {
        System.out.println("NullPointerException in ExtrackBookingInfoFunction - ResponseData ="
                + sample.getResponseDataAsString());
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.kitodo.data.index.elasticsearch.type.UserTypeTest.java

@Test
public void shouldCreateDocument() throws Exception {
    UserType userType = new UserType();
    JSONParser parser = new JSONParser();

    User user = prepareData().get(0);//from  w  w w  .ja v  a 2 s.co  m
    HttpEntity document = userType.createDocument(user);
    JSONObject userObject = (JSONObject) parser.parse(EntityUtils.toString(document));
    String actual = String.valueOf(userObject.get("name"));
    String excepted = "Jan";
    assertEquals("User value for name key doesn't match to given plain text!", excepted, actual);

    actual = String.valueOf(userObject.get("surname"));
    excepted = "Kowalski";
    assertEquals("User value for surname key doesn't match to given plain text!", excepted, actual);

    actual = String.valueOf(userObject.get("login"));
    excepted = "jkowalski";
    assertEquals("User value for login key doesn't match to given plain text!", excepted, actual);

    actual = String.valueOf(userObject.get("ldapLogin"));
    excepted = "null";
    assertEquals("User value for ldapLogin key doesn't match to given plain text!", excepted, actual);

    actual = String.valueOf(userObject.get("location"));
    excepted = "Dresden";
    assertEquals("User value for location key doesn't match to given plain text!", excepted, actual);

    actual = String.valueOf(userObject.get("active"));
    excepted = "true";
    assertEquals("User JSON string doesn't match to given plain text!", excepted, actual);

    user = prepareData().get(1);
    document = userType.createDocument(user);
    actual = EntityUtils.toString(document);
    excepted = "{\"ldapLogin\":null,\"userGroups\":[{\"id\":\"1\"},{\"id\":\"2\"}],\"ldapGroup\":\"null\","
            + "\"surname\":\"Nowak\",\"name\":\"Anna\",\"metadataLanguage\":null,\"active\":\"true\","
            + "\"location\":\"Berlin\",\"login\":\"anowak\",\"properties\":[{\"title\":\"first\",\"value\":\"1\"},"
            + "{\"title\":\"second\",\"value\":\"2\"}]}";
    assertEquals("User JSON string doesn't match to given plain text!", excepted, actual);

    user = prepareData().get(2);
    document = userType.createDocument(user);
    actual = EntityUtils.toString(document);
    excepted = "{\"ldapLogin\":null,\"userGroups\":[],\"ldapGroup\":\"null\",\"surname\":\"Mller\",\"name\":\"Peter\","
            + "\"metadataLanguage\":null,\"active\":\"true\",\"location\":null,\"login\":\"pmueller\","
            + "\"properties\":[{\"title\":\"first\",\"value\":\"1\"},{\"title\":\"second\",\"value\":\"2\"}]}";
    assertEquals("User JSON string doesn't match to given plain text!", excepted, actual);
}