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:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java

@Test
public void testKeyOverrides() throws Exception {
    final Map<String, String> keyOverrides = new HashMap<>();
    keyOverrides.put("timestamp", "dateTime");
    keyOverrides.put("sequence", "seq");
    final Map<String, String> metaData = new LinkedHashMap<>();
    metaData.put("test-key-1", "test-value-1");
    metaData.put("key-no-value", null);
    // Configure the subsystem
    configure(keyOverrides, metaData, true);

    final String msg = "Logging test: JsonFormatterTestCase.defaultLoggingTest";
    final Map<String, String> params = new LinkedHashMap<>();
    // Indicate we need an exception logged
    params.put(LoggingServiceActivator.LOG_EXCEPTION_KEY, "true");
    // Add an NDC value
    params.put(LoggingServiceActivator.NDC_KEY, "test.ndc.value");
    // Add some map entries for MDC values
    params.put("mdcKey1", "mdcValue1");
    params.put("mdcKey2", "mdcValue2");

    final List<String> expectedKeys = createDefaultKeys();
    expectedKeys.remove("timestamp");
    expectedKeys.remove("sequence");
    expectedKeys.addAll(keyOverrides.values());
    expectedKeys.addAll(metaData.keySet());
    expectedKeys.add("exception");
    expectedKeys.add("stackTrace");
    expectedKeys.add("sourceFileName");
    expectedKeys.add("sourceMethodName");
    expectedKeys.add("sourceClassName");
    expectedKeys.add("sourceLineNumber");
    expectedKeys.add("sourceModuleVersion");
    expectedKeys.add("sourceModuleName");

    final int statusCode = getResponse(msg, params);
    Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK);

    // Validate each line
    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);

            // Timestamp should have been renamed to dateTime
            Assert.assertNull("Found timestamp entry in " + s, json.get("timestamp"));

            // Sequence should have been renamed to seq
            Assert.assertNull("Found sequence entry in " + s, json.get("sequence"));

            // Validate MDC
            final JsonObject mdcObject = json.getJsonObject("mdc");
            Assert.assertEquals("mdcValue1", mdcObject.getString("mdcKey1"));
            Assert.assertEquals("mdcValue2", mdcObject.getString("mdcKey2"));

            // Validate the meta-data
            Assert.assertEquals("test-value-1", json.getString("test-key-1"));
            Assert.assertEquals("Expected a null type but got " + json.get("key-no-value"),
                    JsonValue.ValueType.NULL, json.get("key-no-value").getValueType());

            validateStackTrace(json, true, true);
        }/*from   ww w .j  av  a 2 s.c o m*/
    }
}

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

public void videoClustering(Exchange exchange) {

    System.out.println("New message retrieved");

    logger.debug("New message retrieved");

    JsonObject jsonBody = MessageTools.getBody(exchange);

    JsonObjectBuilder job = Json.createObjectBuilder();

    for (Entry<String, JsonValue> entry : jsonBody.entrySet()) {
        job.add(entry.getKey(), entry.getValue());
    }//from   www.ja  v a2s.c  o m

    if (jsonBody != null) {

        String videoXMLPath = jsonBody.getString("video_xmls");
        System.out.println("Retrieved Video XMLs Path: " + videoXMLPath);

        //String method = jsonBody.getString("method");
        //System.out.println("Retrieved VAM: "+method);

        // ONE video per call

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

            System.out.println("Executing Video Clustering Method: ");

            String response_temp = service.video_clustering_request(videoXMLPath);

            System.out.println("Clustering method result:\n" + response_temp);
            // callid is returned at the response 
            String callid;
            String[] callid_tmp = response_temp.split("::");
            callid = callid_tmp[1].trim();
            String response = service.video_clustering_result(callid);

            logger.debug("Video Clustering result:\n" + response);

            job.add("result", response);

        } else {

            System.out.println("Unable to process video xmls, wrong request");
            job.add("result", "Unable to process video, wrong request");

        }

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

    }

}

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

@Test
public void testWithFilter() throws Exception {
    // Create a TCP server and start it
    try (JsonLogServer server = JsonLogServer.createTcpServer(PORT)) {
        server.start(DFT_TIMEOUT);

        final ModelNode address = addSocketHandler("test-log-server", "INFO", "TCP");
        executeOperation(Operations.createWriteAttributeOperation(address, "filter-spec",
                "substituteAll(\"\\\\s\", \"_\")"));
        // We should end up with only 3 messages that should have the spaces removed and replaced with an underscore
        final List<JsonObject> foundMessages = executeRequest("test message",
                Collections.singletonMap(LoggingServiceActivator.LOG_LEVELS_KEY, "INFO,WARN,ERROR"), server, 3);
        // Process the JSON messages
        for (JsonObject foundMessage : foundMessages) {
            final String msg = foundMessage.getString("message");
            Assert.assertEquals(String.format("Expected test_message but found %s for level %s.", msg,
                    foundMessage.getString("level")), "test_message", msg);
        }/*from w  w  w.j  a  v  a 2  s.co  m*/
    }
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.i2b2transmart.I2B2TranSMARTResourceImplementation.java

public List<Entity> searchObservationOnly(String searchTerm, String strategy, SecureSession session,
        String onlObs) {//from w  w w.j  a v  a  2 s  . com
    List<Entity> entities = new ArrayList<Entity>();

    try {
        URI uri = new URI(this.transmartURL.split("://")[0], this.transmartURL.split("://")[1].split("/")[0],
                "/" + this.transmartURL.split("://")[1].split("/")[1] + "/textSearch/findPaths",
                "oblyObs=" + onlObs + "&term=" + searchTerm, null);

        HttpClient client = createClient(session);
        HttpGet get = new HttpGet(uri);
        HttpResponse response = client.execute(get);
        JsonReader reader = Json.createReader(response.getEntity().getContent());
        JsonArray arrayResults = reader.readArray();

        for (JsonValue val : arrayResults) {
            JsonObject returnObject = (JsonObject) val;

            Entity returnedEntity = new Entity();
            returnedEntity
                    .setPui("/" + this.resourceName + converti2b2Path(returnObject.getString("conceptPath")));

            if (!returnObject.isNull("text")) {
                returnedEntity.getAttributes().put("text", returnObject.getString("text"));
            }
            entities.add(returnedEntity);
        }

    } catch (URISyntaxException | JsonException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return entities;
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAIdentity.java

/**
 * read retrieves a specific identity/*from  w w  w  .jav a  2s . com*/
 *
 * @param registrar The identity of the registrar (i.e. who is performing the registration).
 * @return statusCode The HTTP status code in the response
 * @throws IdentityException    if retrieving an identity fails.
 * @throws InvalidArgumentException Invalid (null) argument specified
 */

public int read(User registrar) throws IdentityException, InvalidArgumentException {
    if (registrar == null) {
        throw new InvalidArgumentException("Registrar should be a valid member");
    }

    String readIdURL = "";
    try {
        readIdURL = HFCA_IDENTITY + "/" + enrollmentID;
        logger.debug(format("identity  url: %s, registrar: %s", readIdURL, registrar.getName()));

        JsonObject result = client.httpGet(readIdURL, registrar);

        statusCode = result.getInt("statusCode");
        if (statusCode < 400) {
            type = result.getString("type");
            maxEnrollments = result.getInt("max_enrollments");
            affiliation = result.getString("affiliation");

            JsonArray attributes = result.getJsonArray("attrs");
            Collection<Attribute> attrs = new ArrayList<Attribute>();
            if (attributes != null && !attributes.isEmpty()) {
                for (int i = 0; i < attributes.size(); i++) {
                    JsonObject attribute = attributes.getJsonObject(i);
                    Attribute attr = new Attribute(attribute.getString("name"), attribute.getString("value"),
                            attribute.getBoolean("ecert", false));
                    attrs.add(attr);
                }
            }
            this.attrs = attrs;

            logger.debug(format("identity  url: %s, registrar: %s done.", readIdURL, registrar));
        }
        this.deleted = false;
        return statusCode;
    } catch (HTTPException e) {
        String msg = format("[Code: %d] - Error while getting user '%s' from url '%s': %s", e.getStatusCode(),
                getEnrollmentId(), readIdURL, e.getMessage());
        IdentityException identityException = new IdentityException(msg, e);
        logger.error(msg);
        throw identityException;
    } catch (Exception e) {
        String msg = format("Error while getting user '%s' from url '%s': %s", enrollmentID, readIdURL,
                e.getMessage());
        IdentityException identityException = new IdentityException(msg, e);
        logger.error(msg);
        throw identityException;
    }

}

From source file:org.hyperledger.fabric_ca.sdk.HFCAAffiliation.java

HFCAAffiliationResp getResponse(JsonObject result) {
    if (result.containsKey("name")) {
        this.name = result.getString("name");
    }/*from  w  w w. j  ava  2  s.co  m*/
    return new HFCAAffiliationResp(result);
}

From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java

private String getConferenceName() {
    LOGGER.debug("Sending a request to: " + conferenceBaseUrl);
    JsonObject conferenceObject = readJson(conferenceBaseUrl, JsonReader::readObject);
    return conferenceObject.getString("eventCode");
}

From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java

private void importRoomList() {
    this.roomIdToRoomMap = new HashMap<>();
    List<Room> roomList = new ArrayList<>();

    String roomsUrl = conferenceBaseUrl + "/rooms/";
    LOGGER.debug("Sending a request to: " + roomsUrl);
    JsonObject rootObject = readJson(roomsUrl, JsonReader::readObject);

    JsonArray roomArray = rootObject.getJsonArray("rooms");
    for (int i = 0; i < roomArray.size(); i++) {
        JsonObject roomObject = roomArray.getJsonObject(i);
        String id = roomObject.getString("id");
        int capacity = roomObject.getInt("capacity");

        if (!Arrays.asList(IGNORED_ROOM_IDS).contains(id)) {
            Room room = new Room((long) i);
            room.setName(id);//w ww.  j  ava2  s  .com
            room.setCapacity(capacity);
            room.setTalkTypeSet(getTalkTypeSetForCapacity(capacity));
            for (TalkType talkType : room.getTalkTypeSet()) {
                talkType.getCompatibleRoomSet().add(room);
            }
            room.setTagSet(new HashSet<>());
            room.setUnavailableTimeslotSet(new HashSet<>());
            roomList.add(room);
            roomIdToRoomMap.put(id, room);
        }
    }

    roomList.sort(Comparator.comparing(Room::getName));
    solution.setRoomList(roomList);
}

From source file:ufrj.pedroeusebio.biblioteca_pdf.Controller.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String json = "";
    if (br != null) {
        json = br.readLine();/*from w w  w .  j  a va2s.c  o m*/
    }
    JsonReader reader = Json.createReader(new StringReader(json));
    JsonObject JSONObject = reader.readObject();
    reader.close();

    JsonObject innerObj;
    RespostaDTO dto = new RespostaDTO();
    BibliotecaDAO Biblioteca = new BibliotecaDAO();
    ArrayList<JSONArray> answer = new ArrayList<>();
    Biblioteca.setStrQuery("");
    String Query = "";
    try {
        if (!JSONObject.getString("patrimonio").isEmpty()) {
            System.out.println("entrei !!");
            dto.setPatrimonio(JSONObject.getString("patrimonio"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE patrimonio='" + dto.getPatrimonio()
                        + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("patrimonio", dto.getPatrimonio(), null, "dadoscatalogo");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("titulo").isEmpty()) {
            innerObj = JSONObject.getJsonObject("titulo");
            dto.setTitulo(innerObj.getString("texto"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE titulo='" + dto.getTitulo() + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("titulo", dto.getTitulo(), innerObj.getString("mode"),
                        "dadoscatalogo");
            }
            ;
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("autoria").isEmpty()) {
            innerObj = JSONObject.getJsonObject("autoria");
            dto.setAutoria(innerObj.getString("texto"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE autoria='" + dto.getAutoria()
                        + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("autoria", dto.getAutoria(), innerObj.getString("mode"),
                        "dadoscatalogo");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("veiculo").isEmpty()) {
            innerObj = JSONObject.getJsonObject("veiculo");
            dto.setVeiculo(innerObj.getString("texto"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE veiculo='" + dto.getVeiculo()
                        + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("veiculo", dto.getAutoria(), innerObj.getString("mode"),
                        "dadoscatalogo");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("datapublicacao").isEmpty()) {
            innerObj = JSONObject.getJsonObject("datapublicacao");
            dto.setData(innerObj.getString("texto"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE data_publicacao='" + dto.getData()
                        + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("datapublicacao", dto.getData(), innerObj.getString("mode"),
                        "dadoscatalogo");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("palchave").isEmpty()) {
            innerObj = JSONObject.getJsonObject("palchave");
            String[] parts = innerObj.getString("texto").replaceAll("\\s", "").split(";");
            for (int i = 0; i < parts.length; i++) {
                if (Biblioteca.getStrQuery().isEmpty()) {
                    Query += "SELECT patrimonio FROM public.palavras_chave WHERE palchave='" + parts[i] + "' ";
                    Biblioteca.setStrQuery(Query);
                } else if (!Biblioteca.getStrQuery().isEmpty()) {
                    Query += Biblioteca.QueryGenatator("palchave", parts[i], innerObj.getString("mode"),
                            "palavras_chave");
                }
            }
        }
    } catch (Exception e) {
    }
    try {
        if (JSONObject.getJsonObject("palchave").isEmpty()
                && JSONObject.getJsonObject("datapublicacao").isEmpty()
                && JSONObject.getJsonObject("veiculo").isEmpty()
                && JSONObject.getJsonObject("autoria").isEmpty() && JSONObject.getJsonObject("titulo").isEmpty()
                && JSONObject.getJsonObject("patrimonio").isEmpty()) {
            Query = "SELECT patrimonio FROM public.dadoscatalogo;";

        }
    } catch (Exception e) {

    }

    answer.addAll(Biblioteca.ExecuteQuery(Query));

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.print(answer);
    out.flush();

}

From source file:org.hyperledger.fabric_ca.sdk.HFCAAffiliation.java

private void generateResponse(JsonObject result) {
    if (result.containsKey("name")) {
        this.name = result.getString("name");
    }/*from w  ww. j a  v a  2s  .  com*/
    if (result.containsKey("affiliations")) {
        JsonArray affiliations = result.getJsonArray("affiliations");
        if (affiliations != null && !affiliations.isEmpty()) {
            for (int i = 0; i < affiliations.size(); i++) {
                JsonObject aff = affiliations.getJsonObject(i);
                this.childHFCAAffiliations.add(new HFCAAffiliation(aff));
            }
        }
    }
    if (result.containsKey("identities")) {
        JsonArray ids = result.getJsonArray("identities");
        if (ids != null && !ids.isEmpty()) {
            for (int i = 0; i < ids.size(); i++) {
                JsonObject id = ids.getJsonObject(i);
                HFCAIdentity hfcaID = new HFCAIdentity(id);
                this.identities.add(hfcaID);
            }
        }
    }
}