Example usage for javax.json JsonReader readObject

List of usage examples for javax.json JsonReader readObject

Introduction

In this page you can find the example usage for javax.json JsonReader readObject.

Prototype

JsonObject readObject();

Source Link

Document

Returns a JSON object that is represented in the input source.

Usage

From source file:com.amazon.alexa.avs.auth.companionapp.OAuth2ClientForPkce.java

JsonObject postRequest(HttpURLConnection connection, String data) throws IOException {
    int responseCode = -1;
    InputStream error = null;/*from w  w w.java  2s  .co m*/
    InputStream response = null;
    DataOutputStream outputStream = null;
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setDoOutput(true);

    outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(data.getBytes(StandardCharsets.UTF_8));
    outputStream.flush();
    outputStream.close();
    responseCode = connection.getResponseCode();

    try {
        response = connection.getInputStream();
        JsonReader reader = Json.createReader(new InputStreamReader(response, StandardCharsets.UTF_8));
        return reader.readObject();

    } catch (IOException ioException) {
        error = connection.getErrorStream();
        if (error != null) {
            LWAException lwaException = new LWAException(IOUtils.toString(error), responseCode);
            throw lwaException;
        } else {
            throw ioException;
        }
    } finally {
        IOUtils.closeQuietly(error);
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(response);
    }
}

From source file:org.ocelotds.marshalling.ArgumentServices.java

public Map getJavaResultFromSpecificUnmarshallerMap(String json, IJsonMarshaller marshaller)
        throws JsonUnmarshallingException {
    try {//from w  w w. jav a2 s.  com
        Map<String, Object> result = new HashMap();
        JsonReader createReader = Json.createReader(new StringReader(json));
        JsonObject readObject = createReader.readObject();
        for (Map.Entry<String, JsonValue> entry : readObject.entrySet()) {
            String key = entry.getKey();
            JsonValue jsonValue = entry.getValue();
            result.put(key, marshaller.toJava(jsonValue.toString()));
        }
        return result;
    } catch (Throwable t) {
        throw new JsonUnmarshallingException(t.getMessage());
    }
}

From source file:org.gameontext.mediator.PlayerClient.java

/**
 * Get shared secret for player//from ww  w .j  ava 2s.c om
 * @param playerId
 * @param jwt
 * @param oldRoomId
 * @param newRoomId
 * @return
 */
public String getSharedSecret(String playerId, String jwt) {
    WebTarget target = this.root.path("{playerId}").resolveTemplate("playerId", playerId);

    Log.log(Level.FINER, this, "requesting shared secret using {0}", target.getUri().toString());

    try {
        // Make PUT request using the specified target, get result as a
        // string containing JSON
        Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON);
        builder.header("Content-type", "application/json");
        builder.header("gameon-jwt", jwt);
        String result = builder.get(String.class);

        JsonReader p = Json.createReader(new StringReader(result));
        JsonObject j = p.readObject();
        JsonObject creds = j.getJsonObject("credentials");
        return creds.getString("sharedSecret");
    } catch (ResponseProcessingException rpe) {
        Response response = rpe.getResponse();
        Log.log(Level.FINER, this,
                "Exception obtaining shared secret for player,  uri: {0} resp code: {1} data: {2}",
                target.getUri().toString(),
                response.getStatusInfo().getStatusCode() + " " + response.getStatusInfo().getReasonPhrase(),
                response.readEntity(String.class));

        Log.log(Level.FINEST, this, "Exception obtaining shared secret for player", rpe);
    } catch (ProcessingException | WebApplicationException ex) {
        Log.log(Level.FINEST, this,
                "Exception obtaining shared secret for player (" + target.getUri().toString() + ")", ex);
    }

    // Sadly, badness happened while trying to get the shared secret
    return null;
}

From source file:io.bibleget.VersionsSelect.java

public VersionsSelect() throws ClassNotFoundException {
    biblegetDB = BibleGetDB.getInstance();
    String bibleVersionsStr = biblegetDB.getMetaData("VERSIONS");
    JsonReader jsonReader = Json.createReader(new StringReader(bibleVersionsStr));
    JsonObject bibleVersionsObj = jsonReader.readObject();
    Set<String> versionsabbrev = bibleVersionsObj.keySet();
    bibleVersions = new BasicEventList<>();
    if (!versionsabbrev.isEmpty()) {
        for (String s : versionsabbrev) {
            String versionStr = bibleVersionsObj.getString(s); //store these in an array
            String[] array;//from w  w w  . ja  va  2  s.c  o  m
            array = versionStr.split("\\|");
            bibleVersions.add(new BibleVersion(s, array[0], array[1],
                    StringUtils.capitalize(new Locale(array[2]).getDisplayLanguage())));
        }
    }

    versionsByLang = new SeparatorList<>(bibleVersions, new VersionComparator(), 1, 1000);

    int listLength = versionsByLang.size();
    enabledFlags = new boolean[listLength];

    ListIterator itr = versionsByLang.listIterator();
    while (itr.hasNext()) {
        int idx = itr.nextIndex();
        Object next = itr.next();
        enabledFlags[idx] = !(next.getClass().getSimpleName().equals("GroupSeparator"));
        if (enabledFlags[idx]) {
            versionCount++;
        } else {
            versionLangs++;
        }
    }

    this.setModel(new DefaultEventListModel<>(versionsByLang));
    this.setCellRenderer(new VersionCellRenderer());
    this.setSelectionModel(new DisabledItemSelectionModel());
}

From source file:org.codice.plugin.version.MavenVersionValidationPlugin.java

public void execute() throws MojoExecutionException, MojoFailureException {
    String jsonContents;//from  w w  w .  j  a  v a 2 s  . c om
    File jsonFile;
    boolean hasRangeChars = false;

    JsonObject jsonObject;

    String baseDir = null;
    try {
        baseDir = project.getBasedir().getCanonicalPath();
    } catch (IOException e) {
        getLog().error("Could not find base directory", e);
    }

    if (baseDir != null) {
        String[] fileList = getListOfPackageJsonFiles(baseDir, FILE_NAME);

        for (String filepath : fileList) {
            jsonFile = Paths.get(baseDir, File.separator, filepath).toFile();

            try {
                jsonContents = FileUtils.readFileToString(jsonFile, (Charset) null);
                JsonReader jsonReader = Json.createReader(new StringReader(jsonContents));
                jsonObject = jsonReader.readObject();

                hasRangeChars |= hasRangeChars(jsonObject.getJsonObject("devDependencies"),
                        jsonFile.toString());
                hasRangeChars |= hasRangeChars(jsonObject.getJsonObject("dependencies"), jsonFile.toString());
            } catch (IOException e) {
                getLog().error("Could not find file", e);
            }
        }
        if (hasRangeChars) {
            throw new MojoFailureException(MOJO_EXCEPTION_MESSAGE);
        }
    }
}

From source file:com.open.shift.support.controller.SupportResource.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*  w ww . j  av a  2 s.c  om*/
@Path("piechart")
public JsonObject generatePieChart() throws Exception {
    URL u = ctx.getResource("/WEB-INF/classes/templates/pie.json");
    String pieJson = null;
    if (OS.indexOf("win") >= 0) {
        pieJson = u.toString().substring(6);
    } else if (OS.indexOf("nux") >= 0) {
        pieJson = u.toString().substring(5);
    }

    JsonReader reader = Json.createReader(new FileReader(pieJson));
    JsonObject main = reader.readObject();
    JsonObjectBuilder title = Json.createObjectBuilder().add("text", "Companies Contribution in Deposits");
    JsonArrayBuilder data = Json.createArrayBuilder().add(Json.createArrayBuilder().add("Infosys").add(45.0))
            .add(Json.createArrayBuilder().add("TCS").add(26.8))
            .add(Json.createArrayBuilder().add("Oracle").add(8.5))
            .add(Json.createArrayBuilder().add("Accenture").add(6.2)).add(Json.createObjectBuilder()
                    .add("name", "IBM").add("y", 12.8).add("sliced", true).add("selected", true));
    JsonArrayBuilder series = Json.createArrayBuilder().add(
            Json.createObjectBuilder().add("type", "pie").add("name", "Deposit Contributed").add("data", data));

    JsonObjectBuilder mainJsonObj = Json.createObjectBuilder();
    for (Map.Entry<String, JsonValue> entrySet : main.entrySet()) {
        String key = entrySet.getKey();
        JsonValue value = entrySet.getValue();
        mainJsonObj.add(key, value);
    }
    mainJsonObj.add("title", title.build()).add("series", series.build());

    return mainJsonObj.build();
}

From source file:org.gameontext.mediator.PlayerClient.java

/**
 * Update the player's location. The new location will always be returned
 * from the service, in the face of a conflict between updates for the
 * player across devices, we'll get back the one that won.
 *
 * @param playerId//  w  w  w .  j  av a2 s.c o m
 *            The player id
 * @param jwt
 *            The server jwt for this player id.
 * @param oldRoomId
 *            The old room's id
 * @param newRoomId
 *            The new room's id
 * @return The id of the selected new room, taking contention into account.
 * @throws IOException
 * @throws JsonProcessingException
 */
public String updatePlayerLocation(String playerId, String jwt, String oldRoomId, String newRoomId) {
    WebTarget target = this.root.path("{playerId}/location").resolveTemplate("playerId", playerId)
            .queryParam("jwt", jwt);

    JsonObject parameter = Json.createObjectBuilder().add("oldLocation", oldRoomId)
            .add("newLocation", newRoomId).build();

    Log.log(Level.INFO, this, "updating location using {0} with putdata {1}", target.getUri().toString(),
            parameter.toString());

    try {
        // Make PUT request using the specified target, get result as a
        // string containing JSON
        String resultString = target.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
                .header("Content-type", "application/json").put(Entity.json(parameter), String.class);

        Log.log(Level.INFO, this, "response was {0}", resultString);

        JsonReader r = Json.createReader(new StringReader(resultString));
        JsonObject result = r.readObject();
        String location = result.getString("location");

        Log.log(Level.INFO, this, "response location {0}", location);
        //location should match the 'newRoomId' unless we didn't win the race to change the location.
        return location;
    } catch (ResponseProcessingException rpe) {
        Response response = rpe.getResponse();
        Log.log(Level.WARNING, this, "Exception changing player location,  uri: {0} resp code: {1}",
                target.getUri().toString(),
                response.getStatusInfo().getStatusCode() + " " + response.getStatusInfo().getReasonPhrase());
        Log.log(Level.WARNING, this, "Exception changing player location", rpe);
    } catch (ProcessingException | WebApplicationException ex) {
        Log.log(Level.WARNING, this, "Exception changing player location (" + target.getUri().toString() + ")",
                ex);
    }

    // Sadly, badness happened while trying to set the new room location
    // return to old room
    return oldRoomId;
}

From source file:org.opendaylight.eman.impl.EmanSNMPBinding.java

public String getEoAttrSNMP(String deviceIP, String attribute) {
    LOG.info("EmanSNMPBinding.getEoAttrSNMP: ");

    /* To do: generalize targetURL
        research using Java binding to make reference to 'local' ODL API
     *//*from   w  w w  .  jav a  2 s  .c  om*/
    String targetUrl = "http://localhost:8181/restconf/operations/snmp:snmp-get";
    String bodyString = buildSNMPGetBody(deviceIP, attribute);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String result = null;

    try {
        /* invoke ODL SNMP API */
        HttpPost httpPost = new HttpPost(targetUrl);
        httpPost.addHeader("Authorization", "Basic " + encodedAuthStr);

        StringEntity inputBody = new StringEntity(bodyString);
        inputBody.setContentType(CONTENTTYPE_JSON);
        httpPost.setEntity(inputBody);

        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();
        LOG.info("EmanSNMPBinding.getEoAttrSNMP: Response Status: " + httpResponse.getStatusLine().toString());
        InputStream in = responseEntity.getContent();

        /* Parse response from ODL SNMP API */
        JsonReader rdr = Json.createReader(in);
        JsonObject obj = rdr.readObject();
        JsonObject output = obj.getJsonObject("output");
        JsonArray results = output.getJsonArray("results");
        JsonObject pwr = results.getJsonObject(0);
        String oid = pwr.getString("oid");
        result = pwr.getString("value");
        rdr.close();

        LOG.info("EmanSNMPBinding.getEoAttrSNMP: oid: " + oid + " value " + result);
    } catch (Exception ex) {
        LOG.info("Error: " + ex.getMessage(), ex);
    } finally {
        try {
            httpClient.close();
        } catch (IOException ex) {
            LOG.info("Error: " + ex.getMessage(), ex);
        }
    }
    return (result);
}

From source file:fr.ortolang.diffusion.runtime.engine.task.ImportReferentialEntityTask.java

private String extractField(String jsonContent, String fieldName) {
    String fieldValue = null;/*w w w. j a  va  2  s.  c  om*/
    StringReader reader = new StringReader(jsonContent);
    JsonReader jsonReader = Json.createReader(reader);
    try {
        JsonObject jsonObj = jsonReader.readObject();
        fieldValue = jsonObj.getString(fieldName);
    } catch (IllegalStateException | NullPointerException | ClassCastException | JsonException e) {
        LOGGER.log(Level.WARNING, "No property '" + fieldName + "' in json object", e);
    } finally {
        jsonReader.close();
        reader.close();
    }

    return fieldValue;
}

From source file:com.open.shift.support.controller.SupportResource.java

@GET
@Produces(MediaType.APPLICATION_JSON)//from w  w w  .j  a  va 2 s  . c  o m
@Path("areachart")
public JsonObject generateAreaChart() throws Exception {
    System.out.println("The injected hashcode is " + this.supportDAO);
    int usa[] = { 0, 0, 0, 0, 0, 6, 11, 32, 110, 235, 369, 640, 1005, 1436, 2063, 3057, 4618, 6444, 9822, 15468,
            20434, 24126, 27387, 29459, 31056, 31982, 32040, 31233, 29224, 27342, 26662, 26956, 27912, 28999,
            28965, 27826, 25579, 25722, 24826, 24605, 24304, 23464, 23708, 24099, 24357, 24237, 24401, 24344,
            23586, 22380, 21004, 17287, 14747, 13076, 12555, 12144, 11009, 10950, 10871, 10824, 10577, 10527,
            10475, 10421, 10358, 10295, 10104 };

    int ussr[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 25, 50, 120, 150, 200, 426, 660, 869, 1060, 1605, 2471,
            3322, 4238, 5221, 6129, 7089, 8339, 9399, 10538, 11643, 13092, 14478, 15915, 17385, 19055, 21205,
            23044, 25393, 27935, 30062, 32049, 33952, 35804, 37431, 39197, 45000, 43000, 41000, 39000, 37000,
            35000, 33000, 31000, 29000, 27000, 25000, 24000, 23000, 22000, 21000, 20000, 19000, 18000, 18000,
            17000, 16000 };

    URL u = ctx.getResource("/WEB-INF/classes/templates/area.json");
    String areaJson = null;
    if (OS.indexOf("win") >= 0) {
        areaJson = u.toString().substring(6);
    } else if (OS.indexOf("nux") >= 0) {
        areaJson = u.toString().substring(5);
    }
    System.out.println("The areaJson is " + areaJson);

    JsonReader reader = Json.createReader(new FileReader(areaJson));
    JsonObject main = reader.readObject();

    JsonObject yaxis = main.getJsonObject("yAxis");

    JsonObjectBuilder title = Json.createObjectBuilder().add("text", "US and USSR Deposits");
    JsonObjectBuilder ytitle = Json.createObjectBuilder().add("text", "Amount Deposisted");
    JsonArrayBuilder usaData = Json.createArrayBuilder();
    for (Integer usa1 : usa) {
        usaData.add(usa1);
    }

    JsonArrayBuilder ussrData = Json.createArrayBuilder();
    for (Integer uss1 : ussr) {
        ussrData.add(uss1);
    }

    JsonObjectBuilder usaSeries = Json.createObjectBuilder().add("name", "USA").add("data", usaData);
    JsonObjectBuilder ussrSeries = Json.createObjectBuilder().add("name", "USSR").add("data", ussrData);
    JsonArrayBuilder series = Json.createArrayBuilder().add(usaSeries).add(ussrSeries);

    //main json object builder
    JsonObjectBuilder mainJsonObj = Json.createObjectBuilder();
    for (Map.Entry<String, JsonValue> mainObj : main.entrySet()) {
        String key = mainObj.getKey();
        JsonValue value = mainObj.getValue();

        if (key.equalsIgnoreCase("yAxis")) {
            String yaxisLabel = "labels";
            mainJsonObj.add(key, Json.createObjectBuilder().add(yaxisLabel, yaxis.getJsonObject(yaxisLabel))
                    .add("title", ytitle.build()));
        } else {
            mainJsonObj.add(key, value);
        }

    }
    mainJsonObj.add("title", title.build()).add("series", series.build());

    return mainJsonObj.build();

}