Example usage for javax.json JsonObject toString

List of usage examples for javax.json JsonObject toString

Introduction

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

Prototype

@Override
String toString();

Source Link

Document

Returns JSON text for this JSON value.

Usage

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

protected Optional<JsonObject> updatePage(final String pageId, final JsonObject inputData) {

    final MediaType storageFormat = MediaType.parse("application/json");

    final RequestBody inputBody = RequestBody.create(storageFormat, inputData.toString());

    final HttpUrl url = urlBuilder().addPathSegment("content").addPathSegment(pageId).build();

    return fromUrlPUT(url, inputBody, "update page").map(this::mapToObject).findFirst();
}

From source file:com.bhuwan.eventregistration.business.boundary.EventRegistrationResource.java

@POST
@Path("{id}")
public void saveEventData(@PathParam("id") String id, JsonObject eventData)
        throws IOException, URISyntaxException {
    String path = getClass().getClassLoader().getResource("/eventdata/").getPath();
    String filePath = path + id + ".json";
    while (new File(filePath).exists()) {
        int fileId = Integer.valueOf(id) + 1;
        filePath = (path + fileId) + ".json";
    }//www  .j  av  a2s. co m
    System.out.println(" filepath: " + filePath);
    Files.write(Paths.get(filePath), eventData.toString().getBytes(), StandardOpenOption.CREATE);
}

From source file:org.kitodo.MockDatabase.java

private static String readMapping() {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();

    try (InputStream inputStream = classloader.getResourceAsStream("mapping.json")) {
        if (Objects.nonNull(inputStream)) {
            String mapping = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            try (JsonReader jsonReader = Json.createReader(new StringReader(mapping))) {
                JsonObject jsonObject = jsonReader.readObject();
                return jsonObject.toString();
            }/*w w  w . ja v a2 s.  c o m*/
        } else {
            return "";
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return "";
}

From source file:org.hyperledger.fabric.sdk.NetworkConfig.java

/**
 * Creates a new NetworkConfig instance configured with details supplied in a JSON object
 *
 * @param jsonConfig JSON object containing network configuration details
 * @return A new NetworkConfig instance/*from www .ja  v a 2 s  . co m*/
 * @throws InvalidArgumentException
 */
public static NetworkConfig fromJsonObject(JsonObject jsonConfig)
        throws InvalidArgumentException, NetworkConfigurationException {

    // Sanity check
    if (jsonConfig == null) {
        throw new InvalidArgumentException("jsonConfig must be specified");
    }

    if (logger.isTraceEnabled()) {
        logger.trace(format("NetworkConfig.fromJsonObject: %s", jsonConfig.toString()));
    }

    return NetworkConfig.load(jsonConfig);
}

From source file:de.tu_dortmund.ub.data.dswarm.Transform.java

private JsonObject getDataModel(final String dataModelID, final String serviceName,
        final String engineDswarmAPI) throws Exception {

    try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {

        // Hole Mappings aus dem Projekt mit 'projectID'
        final String uri = engineDswarmAPI + DswarmBackendStatics.DATAMODELS_ENDPOINT + APIStatics.SLASH
                + dataModelID;//from w w w  .j  a v  a  2 s.c o m
        final HttpGet httpGet = new HttpGet(uri);

        LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpGet.getRequestLine()));

        try (CloseableHttpResponse httpResponse = httpclient.execute(httpGet)) {

            final int statusCode = httpResponse.getStatusLine().getStatusCode();
            final String response = TPUUtil.getResponseMessage(httpResponse);

            switch (statusCode) {

            case 200: {

                final JsonObject jsonObject = TPUUtil.getJsonObject(response);

                LOG.debug(
                        String.format("[%s][%d] inputDataModel : %s", serviceName, cnt, jsonObject.toString()));

                final JsonObject dataResourceJSON = jsonObject
                        .getJsonObject(DswarmBackendStatics.DATA_RESOURCE_IDENTIFIER);

                if (dataResourceJSON != null) {

                    final String inputResourceID = dataResourceJSON
                            .getString(DswarmBackendStatics.UUID_IDENTIFIER);

                    LOG.info(String.format("[%s][%d] inout resource ID : %s", serviceName, cnt,
                            inputResourceID));
                }

                return jsonObject;
            }
            default: {

                LOG.error(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode,
                        httpResponse.getStatusLine().getReasonPhrase()));

                throw new Exception("something went wrong at data model retrieval: " + response);
            }
            }
        }
    }
}

From source file:service.NewServlet.java

private String getResults(String query, String... params) {

    StringBuilder sb = new StringBuilder();
    JsonObject obj = null;
    try (Connection conn = Connect.getConnection()) {

        PreparedStatement pstmt = conn.prepareStatement(query);

        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
        }/*from  www  .j  a  v  a2s.  c  o m*/

        ResultSet rs = pstmt.executeQuery();

        while (rs.next()) {

            obj = Json.createObjectBuilder().add("ProductID", rs.getInt("productId"))
                    .add("Name", rs.getString("name")).add("Description", rs.getString("description"))
                    .add("Quantity", rs.getInt("quantity")).build();

            sb.append(obj.toString());

        }

    } catch (SQLException ex) {
        Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return sb.toString();
}

From source file:at.porscheinformatik.sonarqube.licensecheck.webservice.mavenlicense.MavenLicenseAddAction.java

@Override
public void handle(Request request, Response response) throws Exception {
    JsonReader jsonReader = Json.createReader(new StringReader(request.param(MavenLicenseConfiguration.PARAM)));
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();/*from  w w w  .j  a  va  2  s. c  om*/

    boolean keyIsNotBlank = StringUtils
            .isNotBlank(jsonObject.getString(MavenLicenseConfiguration.PROPERTY_KEY));
    boolean regexIsNotBlank = StringUtils
            .isNotBlank(jsonObject.getString(MavenLicenseConfiguration.PROPERTY_REGEX));

    if (keyIsNotBlank && regexIsNotBlank) {
        boolean success = mavenLicenseSettingsService.addMavenLicense(
                jsonObject.getString(MavenLicenseConfiguration.PROPERTY_REGEX),
                jsonObject.getString(MavenLicenseConfiguration.PROPERTY_KEY));

        if (success) {
            LOGGER.info(MavenLicenseConfiguration.INFO_ADD_SUCCESS + jsonObject.toString());
            mavenLicenseSettingsService.sortMavenLicenses();
            response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_OK);
        } else {
            LOGGER.error(MavenLicenseConfiguration.ERROR_ADD_ALREADY_EXISTS + jsonObject.toString());
            response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
        }
    } else {
        LOGGER.error(MavenLicenseConfiguration.ERROR_ADD_INVALID_INPUT + jsonObject.toString());
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
    }
}

From source file:at.porscheinformatik.sonarqube.licensecheck.webservice.mavendependency.MavenDependencyAddAction.java

@Override
public void handle(Request request, Response response) throws Exception {
    JsonReader jsonReader = Json// www . j  a  v a  2s  .c o  m
            .createReader(new StringReader(request.param(MavenDependencyConfiguration.PARAM)));
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();

    boolean keyIsNotBlank = StringUtils
            .isNotBlank(jsonObject.getString(MavenDependencyConfiguration.PROPERTY_KEY));
    boolean licenseIsNotBlank = StringUtils
            .isNotBlank(jsonObject.getString(MavenDependencyConfiguration.PROPERTY_LICENSE));

    if (keyIsNotBlank && licenseIsNotBlank) {
        boolean success = mavenDependencySettingsService.addMavenDependency(
                jsonObject.getString(MavenDependencyConfiguration.PROPERTY_KEY),
                jsonObject.getString(MavenDependencyConfiguration.PROPERTY_LICENSE));

        if (success) {
            LOGGER.info(MavenDependencyConfiguration.INFO_ADD_SUCCESS + jsonObject.toString());
            response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_OK);
        } else {
            LOGGER.error(MavenDependencyConfiguration.ERROR_ADD_ALREADY_EXISTS + jsonObject.toString());
            response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
        }
    } else {
        LOGGER.error(MavenDependencyConfiguration.INFO_ADD_SUCCESS + jsonObject.toString());
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
    }
}

From source file:de.tu_dortmund.ub.data.dswarm.Transform.java

private Optional<JsonObject> getSkipFilter(final String serviceName, final String engineDswarmAPI)
        throws Exception {

    final Optional<String> optionalSkipFilterId = TPUUtil
            .getStringConfigValue(TPUStatics.PROTOTYPE_SKIP_FILTER_IDENTIFIER, config);

    if (!optionalSkipFilterId.isPresent()) {

        return Optional.empty();
    }//from   w ww .ja v  a2 s  . c o m

    final String skipFilterId = optionalSkipFilterId.get();

    try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {

        final String uri = engineDswarmAPI + DswarmBackendStatics.FILTERS_ENDPOINT + APIStatics.SLASH
                + skipFilterId;
        final HttpGet httpGet = new HttpGet(uri);

        LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpGet.getRequestLine()));

        try (CloseableHttpResponse httpResponse = httpclient.execute(httpGet)) {

            final int statusCode = httpResponse.getStatusLine().getStatusCode();
            final String response = TPUUtil.getResponseMessage(httpResponse);

            switch (statusCode) {

            case 200: {

                final JsonObject jsonObject = TPUUtil.getJsonObject(response);

                if (jsonObject != null) {

                    LOG.debug(String.format("[%s][%d] skip filter : %s", serviceName, cnt,
                            jsonObject.toString()));
                } else {

                    LOG.error(String.format(
                            "[%s][%d] skip filter : something went wrong at retrieval of skip filter %s",
                            serviceName, cnt, skipFilterId));
                }

                return Optional.ofNullable(jsonObject);
            }
            default: {

                LOG.error(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode,
                        httpResponse.getStatusLine().getReasonPhrase()));

                throw new Exception("something went wrong at skip filter retrieval: " + response);
            }
            }
        }
    }
}

From source file:be.fedict.dcat.datagovbe.Drupal.java

/**
 * Add a dataset to the Drupal website./*from w w  w.j  ava 2  s.c  o  m*/
 * 
 * @param uri identifier of the dataset
 * @throws RepositoryException
 */
private void add(IRI uri) throws RepositoryException {
    Map<IRI, ListMultimap<String, String>> dataset = store.queryProperties(uri);

    if (dataset.isEmpty()) {
        logger.warn("Empty dataset for {}", uri.stringValue());
        return;
    }

    for (String lang : langs) {
        if (!hasLang(dataset, lang)) {
            continue;
        }

        JsonObjectBuilder builder = Json.createObjectBuilder();

        addDataset(builder, dataset, lang);

        // Get DCAT distributions
        List<String> dists = getMany(dataset, DCAT.DISTRIBUTION, "");
        addDists(builder, dists, lang);

        // Add new or update existing dataset ?
        String id = getOne(dataset, DCTERMS.IDENTIFIER, "");
        String node = checkExistsTrans(builder, id, lang);

        // Build the JSON array
        JsonObject obj = builder.build();
        logger.debug(obj.toString());

        Request r = node.isEmpty() ? prepare(Drupal.POST, Drupal.NODE)
                : prepare(Drupal.PUT, Drupal.NODE + "/" + node);
        r.bodyString(obj.toString(), ContentType.APPLICATION_JSON);

        try {
            StatusLine status = exec.authPreemptive(host).execute(r).returnResponse().getStatusLine();
            logger.debug(status.toString());
        } catch (IOException ex) {
            logger.error("Could not update {}", uri.toString(), ex);
        }
    }
}