Example usage for javax.json JsonObject getJsonObject

List of usage examples for javax.json JsonObject getJsonObject

Introduction

In this page you can find the example usage for javax.json JsonObject getJsonObject.

Prototype

JsonObject getJsonObject(String name);

Source Link

Document

Returns the object value to which the specified name is mapped.

Usage

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

/**
 * Get shared secret for player/*  www .  j a va2 s  .  c  o m*/
 * @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:joachimeichborn.geotag.geocode.MapQuestGeocoder.java

private Geocoding extractLocationInformation(final JsonObject aJsonRepresentation) {
    final JsonString location = aJsonRepresentation.getJsonString("display_name");
    final JsonObject addressDetails = aJsonRepresentation.getJsonObject("address");

    return createTextualRepresentation(location.getString(), addressDetails);
}

From source file:fr.ortolang.diffusion.client.cmd.ReindexAllRootCollectionCommand.java

@Override
public void execute(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;//from w w w .  j  a  v a2s  .c om
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
        }

        String[] credentials = getCredentials(cmd);
        String username = credentials[0];
        String password = credentials[1];

        boolean fakeMode = cmd.hasOption("F");

        OrtolangClient client = OrtolangClient.getInstance();
        if (username.length() > 0) {
            client.getAccountManager().setCredentials(username, password);
            client.login(username);
        }
        System.out.println("Connected as user: " + client.connectedProfile());
        System.out.println("Looking for root collection ...");

        // Looking for root collection
        List<String> rootCollectionKeys = new ArrayList<>();

        int offset = 0;
        int limit = 100;
        JsonObject listOfObjects = client.listObjects("core", "collection", "PUBLISHED", offset, limit);
        JsonArray keys = listOfObjects.getJsonArray("entries");

        while (!keys.isEmpty()) {
            for (JsonString objectKey : keys.getValuesAs(JsonString.class)) {
                JsonObject objectRepresentation = client.getObject(objectKey.getString());
                JsonObject objectProperty = objectRepresentation.getJsonObject("object");
                boolean isRoot = objectProperty.getBoolean("root");
                if (isRoot) {
                    rootCollectionKeys.add(objectKey.getString());
                }
            }
            offset += limit;
            listOfObjects = client.listObjects("core", "collection", "PUBLISHED", offset, limit);
            keys = listOfObjects.getJsonArray("entries");
        }

        System.out.println("Reindex keys : " + rootCollectionKeys);
        if (!fakeMode) {
            for (String key : rootCollectionKeys) {
                client.reindex(key);
            }
        }

        client.logout();
        client.close();

    } catch (ParseException e) {
        System.out.println("Failed to parse command line properties " + e.getMessage());
        help();
    } catch (OrtolangClientException | OrtolangClientAccountException e) {
        System.out.println("Unexpected error !!");
        e.printStackTrace();
    }
}

From source file:org.traccar.geolocation.UniversalGeolocationProvider.java

@Override
public void getLocation(Network network, final LocationProviderCallback callback) {
    try {//  ww  w  . j a  v  a2  s  .co  m
        String request = Context.getObjectMapper().writeValueAsString(network);
        Context.getAsyncHttpClient().preparePost(url)
                .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                .setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(request.length())).setBody(request)
                .execute(new AsyncCompletionHandler() {
                    @Override
                    public Object onCompleted(Response response) throws Exception {
                        try (JsonReader reader = Json.createReader(response.getResponseBodyAsStream())) {
                            JsonObject json = reader.readObject();
                            if (json.containsKey("error")) {
                                callback.onFailure(new GeolocationException(
                                        json.getJsonObject("error").getString("message")));
                            } else {
                                JsonObject location = json.getJsonObject("location");
                                callback.onSuccess(location.getJsonNumber("lat").doubleValue(),
                                        location.getJsonNumber("lng").doubleValue(),
                                        json.getJsonNumber("accuracy").doubleValue());
                            }
                        }
                        return null;
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        callback.onFailure(t);
                    }
                });
    } catch (JsonProcessingException e) {
        callback.onFailure(e);
    }
}

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
     *///ww  w .  java  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:com.open.shift.support.controller.SupportResource.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*from w w  w  . j  a  v  a  2  s . c  om*/
@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();

}

From source file:io.bitgrillr.gocddockerexecplugin.DockerExecPlugin.java

private GoPluginApiResponse handleExecuteRequest(JsonObject requestBody) {
    final String image = requestBody.getJsonObject(CONFIG).getJsonObject(IMAGE).getString(VALUE);
    final String command = requestBody.getJsonObject(CONFIG).getJsonObject("COMMAND").getString(VALUE);
    final JsonString argumentsJson = requestBody.getJsonObject(CONFIG).getJsonObject("ARGUMENTS")
            .getJsonString(VALUE);//from  w w  w .  ja  v  a 2 s .c  o  m
    final String[] arguments;
    if (argumentsJson != null) {
        arguments = argumentsJson.getString().split("\\r?\\n");
    } else {
        arguments = new String[0];
    }
    Map<String, String> envVars = requestBody.getJsonObject("context").getJsonObject("environmentVariables")
            .entrySet().stream()
            .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), ((JsonString) e.getValue()).getString()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    final String workingDir = requestBody.getJsonObject("context").getString("workingDirectory");
    final String pwd = Paths.get(System.getProperty("user.dir"), workingDir).toAbsolutePath().toString();

    final Map<String, Object> responseBody = new HashMap<>();
    try {
        final int exitCode = executeBuild(image, pwd, envVars, command, arguments);

        responseBody.put(MESSAGE,
                (new StringBuilder()).append("Command ")
                        .append(DockerUtils.getCommandString(command, arguments))
                        .append(" completed with status ").append(exitCode).toString());
        if (exitCode == 0) {
            responseBody.put(SUCCESS, Boolean.TRUE);
        } else {
            responseBody.put(SUCCESS, Boolean.FALSE);
        }
    } catch (DockerCleanupException dce) {
        responseBody.clear();
        responseBody.put(SUCCESS, Boolean.FALSE);
        if (dce.getNested() == null) {
            responseBody.put(MESSAGE, dce.getCause().getMessage());
        } else {
            responseBody.put(MESSAGE, dce.getNested().getMessage());
        }
    } catch (ImageNotFoundException infe) {
        responseBody.put(SUCCESS, Boolean.FALSE);
        responseBody.put(MESSAGE,
                (new StringBuilder()).append("Image '").append(image).append("' not found").toString());
    } catch (Exception e) {
        responseBody.clear();
        responseBody.put(SUCCESS, Boolean.FALSE);
        responseBody.put(MESSAGE, e.getMessage());
    }

    return DefaultGoPluginApiResponse.success(Json.createObjectBuilder(responseBody).build().toString());
}

From source file:br.com.argonavis.jaspictut.service.FacebookConnectService.java

@Override
public UserData authenticate(Map<String, String> credentials, HttpServletRequest request,
        HttpServletResponse response) throws AuthenticationException {

    String token = credentials.get("accessToken");

    // If already authenticated via client API -
    // just retrieve token to set data object to
    // set the principal and group-mapping
    String authDataUrl = "https://graph.facebook.com/me" + "?access_token=" + token + "&appsecret_proof="
            + calculateAppSecretProof(token, facebookAppSecret) + "&fields=id,name,email,picture";

    HttpURLConnection connection = null;
    try {/*from w ww .ja  va2s .  c om*/
        URL url = new URL(authDataUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
    } catch (IOException ex) {
        Logger.getLogger(FacebookConnectService.class.getName()).log(Level.SEVERE, null, ex);
    }

    try (InputStream is = connection.getInputStream(); JsonReader rdr = Json.createReader(is)) {

        JsonObject data = rdr.readObject();
        String userid = data.getString("id");
        String email = data.getString("email");
        String name = data.getString("name");
        String picture = data.getJsonObject("picture").getJsonObject("data").getString("url");

        System.out.println("userid: " + userid);
        System.out.println("email: " + email);
        System.out.println("name: " + name);
        System.out.println("picture: " + picture);

        UserData userData = new UserData();

        userData.setUserid(email); // in our app we are using the email as the principal
        userData.setEmail(email);
        userData.setAvatar(picture);
        userData.setName(name);

        request.getSession().setAttribute("userData", userData);

        return userData;
    } catch (IOException ex) {
        Logger.getLogger(FacebookConnectService.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.buffalokiwi.aerodrome.jet.orders.OrderRec.java

/**
 * Build the ship to objects from jet json 
 * @param b builder//ww  w . j a v  a2 s. c  om
 * @param json json 
 */
private static void buildShipTo(final Builder b, final JsonObject json) {
    if (json == null)
        return;

    final JsonObject r = json.getJsonObject("recipient");
    final JsonObject s = json.getJsonObject("address");

    if (r == null) {
        throw new IllegalArgumentException("missing recipient property for shipping_to");
    }

    if (s == null) {
        throw new IllegalArgumentException("missing address property for shipping_to");
    }

    b.setShippingTo(PersonRec.fromJson(r));
    b.setShippingToAddress(AddressRec.fromJson(s));
}

From source file:DesignGUI.java

private void parseStackExchange(String jsonStr) {
    JsonReader reader = null;//from   w  w  w .  j av a2s. c o  m
    StringBuilder content = new StringBuilder();

    this.jEditorPane_areaShow.setContentType("text/html");

    content.append("<html></body>");
    try {
        reader = Json.createReader(new StringReader(jsonStr));
        JsonObject jsonObject = reader.readObject();
        reader.close();
        JsonArray array = jsonObject.getJsonArray("items");
        for (JsonObject result : array.getValuesAs(JsonObject.class)) {

            JsonObject ownerObject = result.getJsonObject("owner");
            //   int ownerReputation = ownerObject.getInt("reputation");
            //  System.out.println("Reputation:"+ownerReputation);
            int viewCount = result.getInt("view_count");
            content.append("<br>View Count :" + viewCount + "<br>");

            int answerCount = result.getInt("answer_count");
            content.append("Answer Count :" + answerCount + "<br>");

            String title = result.getString("title");
            content.append("Title: <FONT COLOR=green>" + title + "</FONT>.<br>");

            String link = result.getString("link");

            content.append("URL :<a href=");
            content.append("'link'>" + link);
            content.append("</a>.<br>");

            //  String body = result.getString("body"); 
            //  content.append("Body:"+body);

            /* JsonArray tagsArray = result.getJsonArray("tags");
             StringBuilder tagBuilder = new StringBuilder();
             int i = 1;
             for(JsonValue tag : tagsArray){
            tagBuilder.append(tag.toString());
            if(i < tagsArray.size())
                tagBuilder.append(",");
            i++;
             }
            content.append("Tags: "+tagBuilder.toString());*/
        }

        content.append("</body></html>");
        this.jEditorPane_areaShow.setText(content.toString());
        System.out.println(content.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}