Example usage for javax.json JsonObject getString

List of usage examples for javax.json JsonObject getString

Introduction

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

Prototype

String getString(String name);

Source Link

Document

A convenience method for getJsonString(name).getString()

Usage

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

@Test
public void handleValidateError() throws Exception {
    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "validate");
    Map<String, Object> body = new HashMap<>();
    Map<String, String> image = new HashMap<>();
    image.put("value", "ubuntu:");
    body.put("IMAGE", image);
    request.setRequestBody(Json.createObjectBuilder(body).build().toString());

    GoPluginApiResponse response = new DockerExecPlugin().handle(request);

    assertEquals("Expected successful response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());// w  w  w  . ja v  a2  s.  c o  m
    JsonObject errors = Json.createReader(new StringReader(response.responseBody())).readObject()
            .getJsonObject("errors");
    assertEquals("Expected 1 error", 1, errors.size());
    assertEquals("Wrong message", "'ubuntu:' is not a valid image identifier", errors.getString("IMAGE"));
}

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());/*w ww.j  a v a 2 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:org.jboss.as.test.integration.logging.handlers.SocketHandlerTestCase.java

@Test
public void testProtocolChange() throws Exception {
    final ModelNode address = addSocketHandler("test-log-server", "INFO", "TCP");
    // Create a TCP server and start it
    try (JsonLogServer server = JsonLogServer.createTcpServer(PORT)) {
        server.start(DFT_TIMEOUT);
        // We should end up with a single log INFO log message
        final JsonObject foundMessage = executeRequest("Test TCP message",
                Collections.singletonMap(LoggingServiceActivator.LOG_LEVELS_KEY, "INFO"), server);
        Assert.assertEquals("Test TCP message", foundMessage.getString("message"));
        server.stop();//from  w  ww.  j a  v  a2  s.  c  om
    }

    // Create a new UDP server
    try (JsonLogServer server = JsonLogServer.createUdpServer(PORT)) {
        server.start(DFT_TIMEOUT);

        // Change the protocol and ensure we can connect
        executeOperation(Operations.createWriteAttributeOperation(address, "protocol", "UDP"));
        final JsonObject foundMessage = executeRequest("Test UDP message",
                Collections.singletonMap(LoggingServiceActivator.LOG_LEVELS_KEY, "INFO"), server);
        Assert.assertEquals("Test UDP message", foundMessage.getString("message"));
    }
}

From source file:org.rhwlab.dispim.nucleus.NucleusData.java

public NucleusData(JsonObject jsonObj) {
    this.time = jsonObj.getInt("Time");
    this.name = jsonObj.getString("Name");
    String precString = jsonObj.getJsonString("Precision").getString();
    this.A = precisionFromString(precString);
    this.xC = jsonObj.getJsonNumber("X").longValue();
    this.yC = jsonObj.getJsonNumber("Y").longValue();
    this.zC = jsonObj.getJsonNumber("Z").longValue();
    this.exp = jsonObj.getJsonNumber("Expression").longValue();

    this.eigenA = new EigenDecomposition(A);
    this.adjustedA = this.A.copy();
    this.adjustedEigenA = new EigenDecomposition(adjustedA);

    double[] adj = new double[3];
    adj[0] = adj[1] = adj[2] = 1.0;/*from  www  . j a v  a2  s . c  o  m*/
    this.setAdjustment(adj);
}

From source file:org.jboss.as.test.integration.logging.handlers.SocketHandlerTestCase.java

@Test
public void testOutboundSocketBindingChange() throws Exception {
    // Add a new outbound-socket-binding
    final String altName = "alt-log-server";
    final ModelNode outboundSocketBindingAddress = Operations.createAddress("socket-binding-group",
            "standard-sockets", "remote-destination-outbound-socket-binding", altName);
    ModelNode op = Operations.createAddOperation(outboundSocketBindingAddress);
    op.get("host").set(HOSTNAME);
    op.get("port").set(ALT_PORT);
    executeOperation(op);//ww  w  .  j  a va 2  s.c  o m
    resourcesToRemove.addLast(outboundSocketBindingAddress);

    // Create the server, plus a new server listening on the alternate port
    try (JsonLogServer server = JsonLogServer.createTcpServer(PORT);
            JsonLogServer altServer = JsonLogServer.createTcpServer(ALT_PORT)) {
        server.start(DFT_TIMEOUT);
        altServer.start(DFT_TIMEOUT);
        final ModelNode altAddress = addSocketHandler("test-log-server-alt", null, null);

        // Log a single message to the current log server and validate
        JsonObject foundMessage = executeRequest("Test first message",
                Collections.singletonMap(LoggingServiceActivator.LOG_LEVELS_KEY, "INFO"), server);
        Assert.assertEquals("Test first message", foundMessage.getString("message"));

        // Change the outbound-socket-binding-ref, which should require a reload
        op = Operations.createWriteAttributeOperation(altAddress, "outbound-socket-binding-ref", altName);
        executeOperation(op);
        ServerReload.executeReloadAndWaitForCompletion(client.getControllerClient());

        // Log a single message to the alternate log server and validate
        foundMessage = executeRequest("Test alternate message",
                Collections.singletonMap(LoggingServiceActivator.LOG_LEVELS_KEY, "INFO"), altServer);
        Assert.assertEquals("Test alternate message", foundMessage.getString("message"));
    }
}

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

/**
 * Gets a list of all the posted ballots of the given election form the bulletin board and returns it
 * @param election//  ww  w . j a va2 s. c om
 * Election for which the list of ballots should be retrieved 
 * @return 
 * the list of all posted ballots to the given election
 */
public List<Ballot> getBallotsByElection(Election election) {
    List<Ballot> ballots = new ArrayList<Ballot>();
    try {

        URL url = new URL(bulletinBoardUrl + "/elections/" + election.getId() + "/ballots");

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonArray obj = jsonReader.readArray();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //transforms the recieved json string into a list of ballot objects
        for (JsonObject result : obj.getValuesAs(JsonObject.class)) {

            int id = Integer.parseInt(result.getString("id"));
            LocalDateTime timeStamp = LocalDateTime.parse(result.getString("timestamp"), format);

            JsonObject jsonData = result.getJsonObject("jsonData");
            List<String> selectedOptions = new ArrayList<String>();
            JsonArray optionsArray = jsonData.getJsonArray("e");
            for (int i = 0; i < optionsArray.size(); i++) {
                selectedOptions.add(optionsArray.getString(i));
            }
            String u_HatString = jsonData.getString("u_Hat");
            String cString = jsonData.getString("c");
            String dString = jsonData.getString("d");
            String pi1String = jsonData.getString("pi1");
            String pi2String = jsonData.getString("pi2");
            String pi3String = jsonData.getString("pi3");
            //create ballot object and add it to the list
            Ballot ballot = new Ballot(id, election, selectedOptions, u_HatString, cString, dString, pi1String,
                    pi2String, pi3String, timeStamp);
            System.out.println(ballot.isValid());
            ballots.add(ballot);
        }

    } catch (IOException x) {
        System.err.println(x);
    }
    return ballots;

}

From source file:eu.forgetit.middleware.component.Extractor.java

public void executeImageAnalysis(Exchange exchange) {

    taskStep = "EXTRACTOR_IMAGE_ANALYSIS";

    logger.debug("New message retrieved for " + taskStep);

    JsonObjectBuilder job = Json.createObjectBuilder();

    JsonObject headers = MessageTools.getHeaders(exchange);

    long taskId = Long.parseLong(headers.getString("taskId"));
    scheduler.updateTask(taskId, TaskStatus.RUNNING, taskStep, null);

    JsonObject jsonBody = MessageTools.getBody(exchange);

    if (jsonBody != null) {

        String cmisServerId = jsonBody.getString("cmisServerId");
        JsonArray jsonEntities = jsonBody.getJsonArray("entities");

        job.add("cmisServerId", cmisServerId);
        job.add("entities", jsonEntities);

        for (JsonValue jsonValue : jsonEntities) {

            JsonObject jsonObject = (JsonObject) jsonValue;

            String type = jsonObject.getString("type");

            if (type.equals(Collection.class.getName()))
                continue;

            long pofId = jsonObject.getInt("pofId");

            try {

                String collectorStorageFolder = ConfigurationManager.getConfiguration()
                        .getString("collector.storage.folder");

                Path sipPath = Paths.get(collectorStorageFolder + File.separator + pofId);

                Path metadataPath = Paths.get(sipPath.toString(), "metadata");

                Path contentPath = Paths.get(sipPath.toString(), "content");

                Path imageAnalysisPath = Paths.get(metadataPath.toString(), "imageAnalysis.xml");

                String imagePaths = getImagePaths(contentPath, pofId);

                if (imagePaths != null && !imagePaths.isEmpty()) {

                    String response = service.img_request(imagePaths, "all", null);

                    FileUtils.writeStringToFile(imageAnalysisPath.toFile(), response);

                    logger.debug("Image Analysis completed for " + imagePaths);
                }//from  w w  w  . j  a  v a 2 s  .  c  o  m

            } catch (IOException e) {

                e.printStackTrace();
            }

        }

        exchange.getOut().setBody(job.build().toString());
        exchange.getOut().setHeaders(exchange.getIn().getHeaders());

    } else {

        scheduler.updateTask(taskId, TaskStatus.FAILED, taskStep, null);

        job.add("Message", "Task " + taskId + " failed");

        scheduler.sendMessage("activemq:queue:ERROR.QUEUE", exchange.getIn().getHeaders(), job.build());
    }

}

From source file:io.bibleget.BibleGetFrame.java

/**
 *
 * @throws ClassNotFoundException//  w ww. ja v a2  s .  co m
 */
private void prepareDynamicInformation() 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;
            array = versionStr.split("\\|");
            bibleVersions.add(new BibleVersion(s, array[0], array[1],
                    StringUtils.capitalize(new Locale(array[2]).getDisplayLanguage())));
        }
    }

    List<String> preferredVersions = new ArrayList<>();
    String retVal = (String) biblegetDB.getOption("PREFERREDVERSIONS");
    if (null == retVal) {
        //System.out.println("Attempt to retrieve PREFERREDVERSIONS from the Database resulted in null value");
    } else {
        //System.out.println("Retrieved PREFERREDVERSIONS from the Database. Value is:"+retVal);
        String[] favoriteVersions = StringUtils.split(retVal, ',');
        preferredVersions = Arrays.asList(favoriteVersions);
    }
    if (preferredVersions.isEmpty()) {
        preferredVersions.add("NVBSE");
    }
    List<Integer> preferredVersionsIndices = new ArrayList<>();

    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 (next.getClass().getSimpleName().equals("BibleVersion")) {
            BibleVersion thisBibleVersion = (BibleVersion) next;
            if (preferredVersions.contains(thisBibleVersion.getAbbrev())) {
                preferredVersionsIndices.add(idx);
            }
        }
    }
    indices = ArrayUtils
            .toPrimitive(preferredVersionsIndices.toArray(new Integer[preferredVersionsIndices.size()]));
    //System.out.println("value of indices array: "+Arrays.toString(indices));

}

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

/**
 * Gets a List of ElectionHeaders from the Bulletin Board and returns it. Fetched list depends on the given ElectionFilterTyp
 * @param filter//from   ww  w  .  j a v a  2 s.c  om
 * The filter can be set to All, Open or Closed
 * @return returns a list of election headers
 */
public List<ElectionHeader> getElectionHeaders(ElectionFilterTyp filter) {
    List<ElectionHeader> electionHeaderlist = new ArrayList<ElectionHeader>();

    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime actualDateTime = LocalDateTime.now();
    String dateTimeString = actualDateTime.format(format);

    URL url = null;
    //depending on the filter a different request is sent to the bulletin board
    switch (filter) {
    // if the filter is set to ALL, all the electionheaders on the bulletin board are requested
    case ALL: {
        try {
            url = new URL(bulletinBoardUrl + "/elections");
        } catch (MalformedURLException ex) {
            Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
        break;

    // if the filter is set to OPEN only ElectionHeaders where the VotingPeriod is still going are requested from the bulletin board
    case OPEN: {
        try {
            url = new URL(bulletinBoardUrl + "/elections/open?date="
                    + URLEncoder.encode(dateTimeString, "UTF-8").replace("+", "%20"));
        } catch (UnsupportedEncodingException | MalformedURLException ex) {
            System.err.println(ex);
        }
    }
        break;
    // if the filter is set to CLOSED only ElectionHeaders where the VotingPeriod is already over are requested from the bulletin board
    case CLOSED: {
        try {
            url = new URL(bulletinBoardUrl + "/elections/closed?date="
                    + URLEncoder.encode(dateTimeString, "UTF-8").replace("+", "%20"));
        } catch (UnsupportedEncodingException | MalformedURLException ex) {
            System.err.println(ex);
        }
    }
        break;
    }

    try {

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonArray obj = jsonReader.readArray();
        //Recieved Json String is transformed into a list of ElectionHeader objects
        for (JsonObject result : obj.getValuesAs(JsonObject.class)) {

            int id = Integer.parseInt(result.getString("id"));
            String title = result.getString("electionTitle");
            LocalDateTime beginDate = LocalDateTime.parse(result.getString("beginDate"), format);
            LocalDateTime endDate = LocalDateTime.parse(result.getString("endDate"), format);

            ElectionHeader electionHeader = new ElectionHeader(id, title, beginDate, endDate);
            electionHeaderlist.add(electionHeader);
        }
    } catch (IOException x) {
        System.err.println(x);
    }

    return electionHeaderlist;
}

From source file:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java

@Test
public void testDateFormat() throws Exception {
    configure(Collections.emptyMap(), Collections.emptyMap(), false);

    final String dateFormat = "yyyy-MM-dd'T'HH:mm:ssSSSZ";
    final String timezone = "GMT";

    // Change the date format and time zone
    final CompositeOperationBuilder builder = CompositeOperationBuilder.create();
    builder.addStep(Operations.createWriteAttributeOperation(FORMATTER_ADDRESS, "date-format", dateFormat));
    builder.addStep(Operations.createWriteAttributeOperation(FORMATTER_ADDRESS, "zone-id", timezone));
    executeOperation(builder.build());//from   w  w w  .j av a 2s  .co m

    final String msg = "Logging test: JsonFormatterTestCase.testNoExceptions";
    int statusCode = getResponse(msg,
            Collections.singletonMap(LoggingServiceActivator.LOG_EXCEPTION_KEY, "false"));
    Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK);

    final List<String> expectedKeys = createDefaultKeys();

    for (String s : Files.readAllLines(logFile, StandardCharsets.UTF_8)) {
        if (s.trim().isEmpty())
            continue;
        try (JsonReader reader = Json.createReader(new StringReader(s))) {
            final JsonObject json = reader.readObject();

            validateDefault(json, expectedKeys, msg);
            validateStackTrace(json, false, false);

            // Validate the date format is correct. We don't want to validate the specific date, only that it's
            // parsable.
            final String jsonDate = json.getString("timestamp");
            // If the date is not parsable an exception should be thrown
            try {
                DateTimeFormatter.ofPattern(dateFormat, Locale.ROOT).withZone(ZoneId.of(timezone))
                        .parse(jsonDate);
            } catch (Exception e) {
                Assert.fail(String.format("Failed to parse %s with pattern %s and zone %s: %s", jsonDate,
                        dateFormat, timezone, e.getMessage()));
            }
        }
    }
}