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:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Posts the given ballot to the bulletin board
 * @param ballot Ballot to be posted to the bulletin board
 * @param useTor Boolean indicating if Ballot should be posted over the Tor network
 *//*  w w  w  .j av  a  2 s  . c om*/
public void postBallot(Ballot ballot, Boolean useTor) {
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();
    //Translate ballot object into a json string 
    JsonArrayBuilder optionsBuilder = Json.createArrayBuilder();
    for (String option : ballot.getSelectedOptions()) {
        optionsBuilder.add(option);
    }
    jBuilder.add("e", optionsBuilder);
    jBuilder.add("u_Hat", ballot.getU_HatString());
    jBuilder.add("c", ballot.getCString());
    jBuilder.add("d", ballot.getDString());
    jBuilder.add("pi1", ballot.getPi1String());
    jBuilder.add("pi2", ballot.getPi2String());
    jBuilder.add("pi3", ballot.getPi3String());

    JsonObject model = jBuilder.build();

    //josn gets posted to the bulletin board
    try {
        boolean requestOK = postJsonStringToURL(
                bulletinBoardUrl + "/elections/" + ballot.getElection().getId() + "/ballots", model.toString(),
                useTor);
        if (requestOK) {
            System.out.println("Ballot posted!");
        } else {
            System.out.println("Was not able to post Ballot!");
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Ballot!");
    }
}

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

private Optional<String> enhanceInputDataResource(final String inputDataResourceFile,
        final JsonObject configurationJSON) throws Exception {

    final JsonObject parameters = configurationJSON.getJsonObject(DswarmBackendStatics.PARAMETERS_IDENTIFIER);

    if (parameters == null) {

        LOG.debug("could not find parameters in configuration '{}'", configurationJSON.toString());

        return Optional.empty();
    }// www .j a  v  a 2s  .  c  om

    final String storageType = parameters.getString(DswarmBackendStatics.STORAGE_TYPE_IDENTIFIER);

    if (storageType == null || storageType.trim().isEmpty()) {

        LOG.debug("could not find storage in parameters of configuration '{}'", configurationJSON.toString());

        return Optional.empty();
    }

    switch (storageType) {

    case DswarmBackendStatics.XML_STORAGE_TYPE:
    case DswarmBackendStatics.MABXML_STORAGE_TYPE:
    case DswarmBackendStatics.MARCXML_STORAGE_TYPE:
    case DswarmBackendStatics.PNX_STORAGE_TYPE:
    case DswarmBackendStatics.OAI_PMH_DC_ELEMENTS_STORAGE_TYPE:
    case DswarmBackendStatics.OAI_PMH_DCE_AND_EDM_ELEMENTS_STORAGE_TYPE:
    case DswarmBackendStatics.OAIPMH_DC_TERMS_STORAGE_TYPE:
    case DswarmBackendStatics.OAIPMH_MARCXML_STORAGE_TYPE:

        // only XML is supported right now

        break;
    default:

        LOG.debug("storage type '{}' is currently not supported for input data resource enhancement",
                storageType);

        return Optional.empty();
    }

    final Path inputDataResourcePath = Paths.get(inputDataResourceFile);

    final Path inputDataResourceFileNamePath = inputDataResourcePath.getFileName();
    final String inputDataResourceFileName = inputDataResourceFileNamePath.toString();
    final String newInputDataResourcePath = OS_TEMP_DIR + File.separator + inputDataResourceFileName;

    LOG.debug("try to enhance input data resource '{}'", inputDataResourceFile);

    XMLEnhancer.enhanceXML(inputDataResourceFile, newInputDataResourcePath);

    LOG.debug("enhanced input data resource for '{}' can be found at ''{}", inputDataResourceFile,
            newInputDataResourcePath);

    return Optional.of(newInputDataResourcePath);
}

From source file:sample.products.java

private String getResults(String query, String... params) {
    StringBuilder sb = new StringBuilder();
    //  return "s";  
    StringWriter out = new StringWriter();
    ResultSet rs;/*  w  w w  .ja va2s . co m*/
    int rows = 0;
    JSONArray products = new JSONArray();
    try (Connection cn = connection.getConnection()) {
        PreparedStatement pstmt = cn.prepareStatement(query);
        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
        }
        rs = pstmt.executeQuery();
        if (rs.last()) {
            rows = rs.getRow();
        }
        System.out.println(rows);
        rs.beforeFirst();
        if (rows > 1) {
            while (rs.next()) {
                //sb.append(String.format("%s\t%s\t%s\t%s\n", rs.getInt("productId"), rs.getString("name"), rs.getString("description"), rs.getInt("quantity"))); 
                JsonObject json = Json.createObjectBuilder().add("Product Id", rs.getInt("productId"))
                        .add("Name", rs.getString("name")).add("Description", rs.getString("description"))
                        .add("Quantity", rs.getString("quantity")).build();
                products.add(json);

            }
        } else {
            while (rs.next()) {
                JsonObject json = Json.createObjectBuilder().add("Product Id", rs.getInt("productId"))
                        .add("Name", rs.getString("name")).add("Description", rs.getString("description"))
                        .add("Quantity", rs.getString("quantity")).build();
                return json.toString();
            }
        }
    } catch (SQLException ex) {
        Logger.getLogger(products.class.getName()).log(Level.SEVERE, null, ex);
    }
    return products.toString();
}

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

/**
 * Registers a new voter with the given email address and the given public credentials u on the bulletin board
 * @param email/*from   www . j av  a 2  s  . c  o m*/
 * email address under which the new voter should be registered
 * @param parameters
 * parameters used by the bulletin board
 * @param u 
 * public voter credential u
 * @return returns true if a new voter could be registered
 */
//TODO check if parameters are still needed
public boolean registerNewVoter(String email, Parameters parameters, Element u) {

    //create Voter json
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();

    jBuilder.add("email", email);
    jBuilder.add("publicCredential", u.convertToString());
    jBuilder.add("appVersion", "1.15");

    JsonObject model = jBuilder.build();

    SignatureController signController = new SignatureController();
    JsonObject signedModel = null;

    try {
        signedModel = signController.signJson(model);
    } catch (Exception ex) {
        Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
    }

    //post Voter
    try {
        boolean requestOK = postJsonStringToURL(bulletinBoardUrl + "/voters", signedModel.toString(), false);
        if (requestOK) {
            System.out.println("Voter posted!");
            return true;
        } else {
            System.out.println("Was not able to post Voter!");
            return false;
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Voter!");
        return false;
    }

}

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

/**
 * Converts the given election object to a Json String. The Json string is then signed.
 * The resulting JWS gets posted to the bulletin board
 * @param election/*from  w w  w  . j  av a 2 s  . c  o m*/
 * election object to be posted to the bulletin board
 */
public void postElection(Election election) {
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    //Add Header information to the json object
    //TODO get email address from certificate 
    jBuilder.add("author", "alice@bfh.ch");
    jBuilder.add("electionTitle", election.getTitle());
    jBuilder.add("beginDate", election.getStartDate().format(format));
    jBuilder.add("endDate", election.getEndDate().format(format));
    //toDo: get AppVersion dynamically from build 
    jBuilder.add("appVersion", "0.15");

    jBuilder.add("coefficients", election.getCredentialPolynomialString());
    jBuilder.add("electionGenerator", election.getH_HatString());

    //Add votingTopic to the Json Object
    JsonObjectBuilder votingTopicBuilder = Json.createObjectBuilder();
    votingTopicBuilder.add("topic", election.getTopic().getTitle());
    votingTopicBuilder.add("pick", election.getTopic().getPick());

    JsonArrayBuilder optionsBuilder = Json.createArrayBuilder();
    for (String option : election.getTopic().getOptions()) {
        optionsBuilder.add(option);
    }
    votingTopicBuilder.add("options", optionsBuilder);

    jBuilder.add("votingTopic", votingTopicBuilder);

    //Add the list of selected Voters to the Json object
    JsonArrayBuilder votersBuilder = Json.createArrayBuilder();

    for (Voter voter : election.getVoterList()) {
        JsonObjectBuilder voterBuilder = Json.createObjectBuilder();
        voterBuilder.add("email", voter.getEmail());
        voterBuilder.add("publicCredential", voter.getPublicCredential());
        voterBuilder.add("appVersion", voter.getAppVersion());

        votersBuilder.add(voterBuilder);
    }

    jBuilder.add("voters", votersBuilder);

    JsonObject model = jBuilder.build();
    //finished Json gets singed
    SignatureController signController = new SignatureController();
    JsonObject signedModel = null;

    try {
        signedModel = signController.signJson(model);
    } catch (Exception ex) {
        Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
    }

    //JWS gets posted to the bulletin board
    try {
        boolean requestOK = postJsonStringToURL(bulletinBoardUrl + "/elections", signedModel.toString(), false);
        if (requestOK) {
            System.out.println("Election posted!");
        } else {
            System.out.println("Was not able to post Election! Did not receive expected http 200 status.");
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Election! IOException");
    }

}

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

@Test
public void handleExecuteImageNotFound() throws Exception {
    UnitTestUtils.mockJobConsoleLogger();
    PowerMockito.mockStatic(DockerUtils.class);
    PowerMockito.doThrow(new ImageNotFoundException("idont:exist")).when(DockerUtils.class);
    DockerUtils.pullImage(anyString());//from  www .  jav a2  s.c om

    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "execute");
    JsonObject requestBody = Json.createObjectBuilder()
            .add("config",
                    Json.createObjectBuilder()
                            .add("IMAGE", Json.createObjectBuilder().add("value", "idont:exist").build())
                            .add("COMMAND", Json.createObjectBuilder().add("value", "ls").build())
                            .add("ARGUMENTS", Json.createObjectBuilder().build()).build())
            .add("context", Json.createObjectBuilder().add("workingDirectory", "pipelines/test")
                    .add("environmentVariables", Json.createObjectBuilder().build()).build())
            .build();
    request.setRequestBody(requestBody.toString());
    final GoPluginApiResponse response = new DockerExecPlugin().handle(request);

    assertEquals("Expected 2xx response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());
    final JsonObject responseBody = Json.createReader(new StringReader(response.responseBody())).readObject();
    assertEquals("Expected failure", Boolean.FALSE, responseBody.getBoolean("success"));
    assertEquals("Message wrong", "Image 'idont:exist' not found", responseBody.getString("message"));
}

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

@Test
public void handleExecuteNoArgs() throws Exception {
    UnitTestUtils.mockJobConsoleLogger();
    PowerMockito.mockStatic(DockerUtils.class);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.pullImage(anyString());/*from  www . j av a  2 s .  c  om*/
    when(DockerUtils.createContainer(anyString(), anyString(), anyMap())).thenReturn("123");
    when(DockerUtils.getContainerUid(anyString())).thenReturn("4:5");
    when(DockerUtils.execCommand(anyString(), any(), any())).thenReturn(0);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.removeContainer(anyString());
    PowerMockito.mockStatic(SystemHelper.class);
    when(SystemHelper.getSystemUid()).thenReturn("7:8");

    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "execute");
    JsonObject requestBody = Json.createObjectBuilder()
            .add("config",
                    Json.createObjectBuilder()
                            .add("IMAGE", Json.createObjectBuilder().add("value", "ubuntu:latest").build())
                            .add("COMMAND", Json.createObjectBuilder().add("value", "ls").build())
                            .add("ARGUMENTS", Json.createObjectBuilder().build()).build())
            .add("context", Json.createObjectBuilder().add("workingDirectory", "pipelines/test")
                    .add("environmentVariables", Json.createObjectBuilder().build()).build())
            .build();
    request.setRequestBody(requestBody.toString());
    final GoPluginApiResponse response = new DockerExecPlugin().handle(request);

    assertEquals("Expected 2xx response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.execCommand("123", null, "ls");
}

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

/**
 * Post the given result to a election to the bulletin board
 * @param result //  w w w  . jav a2s  .co  m
 * result to be posted to the bulletin board
 */
public void postResult(ElectionResult result) {
    Election election = result.getElection();
    ElectionTopic topic = election.getTopic();
    HashMap<String, Integer> optionResults = result.getOptionCount();
    //translate the ElectionResult object into a json String
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();

    //TODO get email address from certificate 
    jBuilder.add("author", "alice@bfh.ch");

    JsonArrayBuilder resultBuilder = Json.createArrayBuilder();

    JsonObjectBuilder topicBuilder = Json.createObjectBuilder();

    topicBuilder.add("topic", topic.getTitle());
    topicBuilder.add("pick", topic.getPick());

    JsonArrayBuilder optionsBuilder = Json.createArrayBuilder();

    for (String option : topic.getOptions()) {
        JsonObjectBuilder optionBuilder = Json.createObjectBuilder();
        optionBuilder.add("optTitle", option);
        optionBuilder.add("count", optionResults.get(option));
        optionsBuilder.add(optionBuilder);
    }
    topicBuilder.add("options", optionsBuilder);

    resultBuilder.add(topicBuilder);

    jBuilder.add("result", resultBuilder);
    JsonArrayBuilder ballotsBuilder = Json.createArrayBuilder();
    for (Ballot ballot : result.getBallots()) {
        JsonObjectBuilder ballotBuilder = Json.createObjectBuilder();
        //Translate ballot object into a json string 
        JsonArrayBuilder ballotOptionsBuilder = Json.createArrayBuilder();
        for (String option : ballot.getSelectedOptions()) {
            ballotOptionsBuilder.add(option);
        }
        ballotBuilder.add("id", ballot.getId());
        ballotBuilder.add("e", ballotOptionsBuilder);
        ballotBuilder.add("valid", ballot.isValid());
        ballotBuilder.add("reason", ballot.getReason());

        ballotsBuilder.add(ballotBuilder);
    }

    jBuilder.add("ballots", ballotsBuilder);

    JsonObject model = jBuilder.build();

    //sign json string 
    SignatureController signController = new SignatureController();
    JsonObject signedModel = null;

    try {
        signedModel = signController.signJson(model);
    } catch (Exception ex) {
        Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        //post JWS with the result to the bulletin board
        boolean requestOK = postJsonStringToURL(
                bulletinBoardUrl + "/elections/" + election.getId() + "/results", signedModel.toString(),
                false);
        if (requestOK) {
            System.out.println("Results posted!");
        } else {
            System.out.println("Was not able to post Results! Did not receive expected http 200 status.");
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Results! IOException");
    }

}

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

@Test
public void handleExecuteCleanupError() throws Exception {
    UnitTestUtils.mockJobConsoleLogger();
    PowerMockito.mockStatic(DockerUtils.class);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.pullImage(anyString());//  w ww. ja  v a  2  s .  com
    when(DockerUtils.createContainer(anyString(), anyString(), anyMap())).thenReturn("123");
    when(DockerUtils.getContainerUid(anyString())).thenReturn("4:5");
    when(DockerUtils.execCommand(anyString(), any(), anyString(), any())).thenReturn(0);
    PowerMockito.doThrow(new DockerException("FAIL")).when(DockerUtils.class);
    DockerUtils.removeContainer(anyString());
    PowerMockito.mockStatic(SystemHelper.class);
    when(SystemHelper.getSystemUid()).thenReturn("7:8");

    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "execute");
    JsonObject requestBody = Json.createObjectBuilder()
            .add("config",
                    Json.createObjectBuilder()
                            .add("IMAGE", Json.createObjectBuilder().add("value", "ubuntu:latest").build())
                            .add("COMMAND", Json.createObjectBuilder().add("value", "ls").build())
                            .add("ARGUMENTS", Json.createObjectBuilder().build()).build())
            .add("context", Json.createObjectBuilder().add("workingDirectory", "pipelines/test")
                    .add("environmentVariables", Json.createObjectBuilder().build()).build())
            .build();
    request.setRequestBody(requestBody.toString());
    final GoPluginApiResponse response = new DockerExecPlugin().handle(request);

    assertEquals("Expected 2xx response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());
    final JsonObject responseBody = Json.createReader(new StringReader(response.responseBody())).readObject();
    assertEquals("Expected failure", Boolean.FALSE, responseBody.getBoolean("success"));
    assertEquals("Wrong message", "FAIL", responseBody.getString("message"));
}

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

@Test
public void handleExecuteError() throws Exception {
    UnitTestUtils.mockJobConsoleLogger();
    PowerMockito.mockStatic(DockerUtils.class);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.pullImage(anyString());/*from   w w w.j ava  2  s.  c  o m*/
    when(DockerUtils.createContainer(anyString(), anyString(), anyMap())).thenReturn("123");
    when(DockerUtils.getContainerUid(anyString())).thenReturn("4:5");
    when(DockerUtils.execCommand(anyString(), any(), anyString(), any()))
            .thenThrow(new DockerException("FAIL"));
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.removeContainer(anyString());
    PowerMockito.mockStatic(SystemHelper.class);
    when(SystemHelper.getSystemUid()).thenReturn("7:8");

    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "execute");
    JsonObject requestBody = Json.createObjectBuilder()
            .add("config",
                    Json.createObjectBuilder()
                            .add("IMAGE", Json.createObjectBuilder().add("value", "ubuntu:latest").build())
                            .add("COMMAND", Json.createObjectBuilder().add("value", "ls").build())
                            .add("ARGUMENTS", Json.createObjectBuilder().build()).build())
            .add("context", Json.createObjectBuilder().add("workingDirectory", "pipelines/test")
                    .add("environmentVariables", Json.createObjectBuilder().build()).build())
            .build();
    request.setRequestBody(requestBody.toString());
    final GoPluginApiResponse response = new DockerExecPlugin().handle(request);

    assertEquals("Expected 2xx response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());
    final JsonObject responseBody = Json.createReader(new StringReader(response.responseBody())).readObject();
    assertEquals("Expected failure", Boolean.FALSE, responseBody.getBoolean("success"));
    assertEquals("Wrong message", "FAIL", responseBody.getString("message"));
}