Example usage for javax.json Json createReader

List of usage examples for javax.json Json createReader

Introduction

In this page you can find the example usage for javax.json Json createReader.

Prototype

public static JsonReader createReader(InputStream in) 

Source Link

Document

Creates a JSON reader from a byte stream.

Usage

From source file:org.openstreetmap.josm.plugins.mapillary.actions.MapillarySubmitCurrentChangesetAction.java

@Override
public void actionPerformed(ActionEvent event) {
    String token = Main.pref.get("mapillary.access-token");
    if (token == null || token.trim().isEmpty()) {
        PluginState.notLoggedInToMapillaryDialog();
        return;// ww w  . j  ava2  s.  co  m
    }
    PluginState.setSubmittingChangeset(true);
    MapillaryUtils.updateHelpText();
    HttpClientBuilder builder = HttpClientBuilder.create();
    HttpPost httpPost = new HttpPost(MapillaryURL.submitChangesetURL().toString());
    httpPost.addHeader("content-type", "application/json");
    httpPost.addHeader("Authorization", "Bearer " + token);
    JsonArrayBuilder changes = Json.createArrayBuilder();
    MapillaryLocationChangeset locationChangeset = MapillaryLayer.getInstance().getLocationChangeset();
    for (MapillaryImage image : locationChangeset) {
        changes.add(Json.createObjectBuilder().add("image_key", image.getKey()).add("values",
                Json.createObjectBuilder()
                        .add("from", Json.createObjectBuilder().add("ca", image.getCa())
                                .add("lat", image.getLatLon().getY()).add("lon", image.getLatLon().getX()))
                        .add("to",
                                Json.createObjectBuilder().add("ca", image.getTempCa())
                                        .add("lat", image.getTempLatLon().getY())
                                        .add("lon", image.getTempLatLon().getX()))));
    }
    String json = Json.createObjectBuilder().add("change_type", "location").add("changes", changes)
            .add("request_comment", "JOSM-created").build().toString();
    try (CloseableHttpClient httpClient = builder.build()) {
        httpPost.setEntity(new StringEntity(json));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            String key = Json.createReader(response.getEntity().getContent()).readObject().getString("key");
            synchronized (MapillaryUtils.class) {
                Main.map.statusLine.setHelpText(
                        String.format("%s images submitted, Changeset key: %s", locationChangeset.size(), key));
            }
            locationChangeset.cleanChangeset();

        }

    } catch (IOException e) {
        logger.error("got exception", e);
        synchronized (MapillaryUtils.class) {
            Main.map.statusLine.setHelpText("Error submitting Mapillary changeset: " + e.getMessage());
        }
    } finally {
        PluginState.setSubmittingChangeset(false);
    }
}

From source file:dk.dma.msinm.user.security.oauth.GoogleOAuthProvider.java

/**
 * {@inheritDoc}//  w w w . j  ava  2 s .c  o  m
 */
@Override
public User authenticateUser(HttpServletRequest request) throws Exception {

    OAuthService service = getOAuthService(settings, app.getBaseUri());
    if (service == null) {
        log.warn("OAuth service not available for " + getOAuthProviderId());
        throw new Exception("OAuth service not available for " + getOAuthProviderId());
    }

    String oauthVerifier = request.getParameter("code");
    Verifier verifier = new Verifier(oauthVerifier);

    Token accessToken = service.getAccessToken(OAuthConstants.EMPTY_TOKEN, verifier);
    log.info("Access Granted to Google with token " + accessToken);

    // check
    // https://github.com/haklop/myqapp/blob/b005df2e100f8aff7c1529097b651b1fd7ce6a4c/src/main/java/com/infoq/myqapp/controller/GoogleController.java
    String idToken = GoogleApiProvider.getIdToken(accessToken.getRawResponse());
    String userIdToken = idToken.split("\\.")[1];
    log.info("Received ID token " + userIdToken);

    String profile = new String(Base64.getDecoder().decode(userIdToken));
    log.info("Decoded " + profile);

    try (JsonReader jsonReader = Json.createReader(new StringReader(profile))) {
        JsonObject json = jsonReader.readObject();

        String email = json.containsKey("email") ? json.getString("email") : null;
        String firstName = json.containsKey("given_name") ? json.getString("given_name") : null;
        String lastName = json.containsKey("family_name") ? json.getString("family_name") : null;
        if (StringUtils.isBlank(email)) {
            throw new Exception("No email found in OAuth token");
        }
        log.info("Email  " + email);

        User user = userService.findByEmail(email);
        if (user == null) {
            user = new User();
            user.setEmail(email);
            user.setLanguage("en");
            user.setFirstName(firstName);
            user.setLastName(StringUtils.isBlank(lastName) ? email : lastName);
            user = userService.registerOAuthOnlyUser(user);
        }
        return user;
    }
}

From source file:prod.products.java

@PUT
@Consumes("application/json")
public void put(String str) {
    JsonObject json = Json.createReader(new StringReader(str)).readObject();
    int newid = json.getInt("PRODUCT_ID");
    String id = String.valueOf(newid);
    String name = json.getString("PRODUCT_NAME");
    String description = json.getString("PRODUCT_DESCRIPTION");
    int newqty = json.getInt("QUANTITY");
    String qty = String.valueOf(newqty);
    System.out.println(id + name + description + qty);
    doUpdate(/*from   w ww .  ja  v a2 s.c  o  m*/
            "UPDATE PRODUCT SET PRODUCT_ID= ?, PRODUCT_NAME = ?, PRODUCT_DESCRIPTION = ?, QUANTITY = ? WHERE PRODUCT_ID = ?",
            id, name, description, qty, id);
}

From source file:de.pksoftware.springstrap.cms.util.CmsUtils.java

public static String getModelProperty(CmsModel model, String path, String defaultValue)
        throws InvalidPathException {
    if (null == model) {
        return defaultValue;
    }/* ww  w .j a  v  a 2  s  .  c o  m*/

    Pattern pattern = Pattern.compile("^(\\/\\w+)+$");
    Matcher matcher = pattern.matcher(path);

    if (!matcher.matches()) {
        throw new RuntimeException(
                "Path must start with /, must not end with / and must only contain letters and numbers.");
    }

    String value = defaultValue;

    logger.info("Trying to get " + model.getModelName() + ">" + path);

    String data = model.getData();

    String[] pathParts = path.split("\\/");
    int partsLength = pathParts.length;

    JsonReader jsonReader = Json.createReader(new StringReader(data));
    JsonObject jsonObject = jsonReader.readObject();

    boolean pointerIsArray = false;
    Object pointer = jsonObject;

    for (int i = 1; i < partsLength; i++) {
        String pathPart = pathParts[i];
        logger.info("Testing property: " + pathPart);
        JsonValue jsonValue = null;
        Assert.notNull(pointer);
        if (pointerIsArray) {
            if (!NumberUtils.isNumber(pathPart)) {
                throw new InvalidPathException("Path element '" + pathPart + "' should be numeric.");
            }
            jsonValue = ((JsonArray) pointer).get(Integer.parseInt(pathPart));
        } else {
            jsonValue = ((JsonObject) pointer).get(pathPart);
        }

        if (null == jsonValue) {
            logger.info(model.getModelName() + " has no property: " + path);

            break;
        }

        JsonValue.ValueType valueType = jsonValue.getValueType();
        if (i < partsLength - 1) {
            //Must be Object or Array
            if (valueType == JsonValue.ValueType.ARRAY) {
                logger.info(pathPart + " is an array.");
                pointer = (JsonArray) jsonValue;
                pointerIsArray = true;
            } else if (valueType == JsonValue.ValueType.OBJECT) {
                logger.info(pathPart + " is an object.");
                pointer = (JsonObject) jsonValue;
                pointerIsArray = false;
            } else {
                throw new InvalidPathException("Path element '" + pathPart
                        + "' should be a be an object or array, but " + valueType.toString() + " found.");
            }
        } else {
            if (valueType == JsonValue.ValueType.STRING) {
                logger.info(pathPart + " is an string.");
                value = ((JsonString) jsonValue).getString();
                break;
            } else {
                throw new InvalidPathException("Path element '" + pathPart + "' should be a string, but "
                        + valueType.toString() + " found.");
            }
        }
    }

    jsonReader.close();

    return value;
}

From source file:org.bsc.confluence.rest.AbstractRESTConfluenceService.java

protected Stream<JsonObject> mapToStream(Response res) {

    final ResponseBody body = res.body();

    try (Reader r = body.charStream()) {

        final JsonReader rdr = Json.createReader(r);

        final JsonObject root = rdr.readObject();

        final Stream.Builder<JsonObject> stream = Stream.builder();

        // Check for Array
        if (root.containsKey("results")) {
            final JsonArray results = root.getJsonArray("results");

            if (results != null) {
                for (int ii = 0; ii < results.size(); ++ii)
                    stream.add(results.getJsonObject(ii));
            }//w w  w  .j a va 2 s .c  o  m
        } else {
            stream.add(root);
        }

        return stream.build();

    } catch (IOException | JsonParsingException e) {
        throw new Error(e);
    }

}

From source file:uk.theretiredprogrammer.nbpcglibrary.remoteclient.RemotePersistenceUnitProvider.java

/**
 * Execute Multiple Commands - send multiple commands in a single message to
 * be executed by remote data source.//  w w  w . j ava 2  s .co m
 *
 * @param request the set of command objects
 * @return the set of response objects
 * @throws IOException if problems with parsing command data or problems
 * executing the command
 */
public synchronized JsonArray executeMultipleCommands(JsonArray request) throws IOException {
    JsonStructure res = null;
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new StringEntity(request.toString(), APPLICATION_JSON));
    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity responsebody = response.getEntity();
            try (JsonReader jsonReader = Json.createReader(responsebody.getContent())) {
                res = jsonReader.read();
            }
            EntityUtils.consume(responsebody);
        }
    }
    if (res instanceof JsonArray) {
        return (JsonArray) res;
    } else {
        throw new JsonConversionException();
    }
}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Gets the parameters of the bulletin board from the bulletin board and converts the recieved Json in a Parameters object and returns it
 * @return returns bulletin board's parameters in form of a parameter object
 *//*ww  w  .ja va 2 s .  c o m*/
public Parameters getParameters() {
    try {
        //Get parameters json with a get request 
        URL url = new URL(bulletinBoardUrl + "/parameters");

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonObject obj = jsonReader.readObject();
        //Json contains String representations of the parameter elements
        String oString = obj.getString("o");
        String pString = obj.getString("p");
        String h0String = obj.getString("h0");
        String h1String = obj.getString("h1");
        String h2String = obj.getString("h2");
        String g0String = obj.getString("g0");
        String g1String = obj.getString("g1");

        //Converting the parameter Element Strings into Parameters Object containing the restored Parameter Elements
        Parameters parameters = new Parameters(oString, pString, h0String, h1String, h2String, g0String,
                g1String);
        return parameters;
    } catch (Exception x) {
        System.err.println(x);
        return null;
    }

}

From source file:com.dhenton9000.jersey.client.BasicTests.java

/**
 * this demonstrates writing headers to the request
 *///w w w .  ja  v a 2 s .  co m
@Test
public void testConfigRequestFilter() {
    ClientConfig config = new ClientConfig();
    config.register(RequestFilter.class);
    Client client = ClientBuilder.newClient(config);
    WebTarget target = client.target(getBaseURI());
    Response response = target.path("restaurant").request().accept(MediaType.APPLICATION_JSON)
            .get(Response.class);
    if (response.getStatus() != 200) {
        fail("status problem for request " + response.getStatus());
    }

    InputStream jsonStringResponse = response.readEntity(InputStream.class);
    JsonReader myreader = Json.createReader(jsonStringResponse);
    JsonArray restaurants = myreader.readArray();
    assertTrue(restaurants.size() > 5);
    assertTrue(RequestFilter.gotHit);
    RequestFilter.gotHit = false;

}

From source file:io.bitgrillr.gocddockerexecplugin.utils.GoTestUtils.java

/**
 * Returns the status of the named pipeline instance.
 *
 * @param pipeline Name of the pipeline.
 * @param counter Counter of the pipeline instance.
 * @return The status.// w w w .  j a v  a 2  s  .  com
 * @throws GoError If Go.CD returns a non 2XX reponse.
 * @throws IOException If a communication error occurs.
 */
public static String getPipelineStatus(String pipeline, int counter) throws GoError, IOException {
    final HttpResponse response = executor
            .execute(Request.Get(PIPELINES + pipeline + "/instance/" + Integer.toString(counter)))
            .returnResponse();
    final int status = response.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_OK) {
        throw new GoError(status);
    }
    final JsonArray stages = Json.createReader(response.getEntity().getContent()).readObject()
            .getJsonArray("stages");
    String pipelineStatus = "Completed";
    for (JsonValue stage : stages) {
        final JsonArray jobs = ((JsonObject) stage).getJsonArray("jobs");
        for (JsonValue job : jobs) {
            pipelineStatus = job.asJsonObject().getString("state");
            if (!"Completed".equals(pipelineStatus)) {
                return pipelineStatus;
            }
        }
    }
    return pipelineStatus;
}

From source file:org.grogshop.services.endpoints.impl.ShopUserProfileServiceImpl.java

public Response setInterests(@NotNull @PathParam("user_id") Long user_id,
        @FormParam("interests") String interests) throws ServiceException {
    log.info("Storing from the database: (" + user_id + ") " + interests);
    if (interests != null) {
        JsonReader reader = Json.createReader(new ByteArrayInputStream(interests.getBytes()));
        JsonArray array = reader.readArray();
        reader.close();/* w  w w .j  a  v  a  2s .  c o  m*/

        List<Interest> interestsList = new ArrayList<Interest>(array.size());

        if (array != null) {

            for (int i = 0; i < array.size(); i++) {
                log.info("Interest[" + i + "]: " + array.getJsonObject(i).getString("name"));
                interestsList.add(interestService.get(array.getJsonObject(i).getString("name")));
            }

        }

        profileService.setInterests(user_id, interestsList);
    }

    return Response.ok().build();
}