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.apache.tamaya.etcd.EtcdAccessor.java

/**
 * Recursively read out all key/values from this etcd JSON array.
 *
 * @param result map with key, values and metadata.
 * @param node   the node to parse./* w w w . j  a v a 2s  . co  m*/
 */
private void addNodes(Map<String, String> result, JsonObject node) {
    if (!node.containsKey("dir") || "false".equals(node.get("dir").toString())) {
        final String key = node.getString("key").substring(1);
        result.put(key, node.getString("value"));
        if (node.containsKey("createdIndex")) {
            result.put("_" + key + ".createdIndex", String.valueOf(node.getInt("createdIndex")));
        }
        if (node.containsKey("modifiedIndex")) {
            result.put("_" + key + ".modifiedIndex", String.valueOf(node.getInt("modifiedIndex")));
        }
        if (node.containsKey("expiration")) {
            result.put("_" + key + ".expiration", String.valueOf(node.getString("expiration")));
        }
        if (node.containsKey("ttl")) {
            result.put("_" + key + ".ttl", String.valueOf(node.getInt("ttl")));
        }
        result.put("_" + key + ".source", "[etcd]" + serverURL);
    } else {
        final JsonArray nodes = node.getJsonArray("nodes");
        if (nodes != null) {
            for (int i = 0; i < nodes.size(); i++) {
                addNodes(result, nodes.getJsonObject(i));
            }
        }
    }
}

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

private void importTalkTypeList() {
    this.talkTypeNameToTalkTypeMap = new HashMap<>();
    List<TalkType> talkTypeList = new ArrayList<>();

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

    JsonArray talkTypeArray = rootObject.getJsonArray("proposalTypes");
    for (int i = 0; i < talkTypeArray.size(); i++) {
        JsonObject talkTypeObject = talkTypeArray.getJsonObject(i);
        String talkTypeName = talkTypeObject.getString("id");
        if (talkTypeNameToTalkTypeMap.keySet().contains(talkTypeName)) {
            LOGGER.warn("Duplicate talk type in " + proposalTypeUrl + " at index " + i + ".");
            continue;
        }//  ww  w  .j av  a 2 s  .  c o  m

        TalkType talkType = new TalkType((long) i, talkTypeName);
        talkType.setCompatibleRoomSet(new HashSet<>());
        talkType.setCompatibleTimeslotSet(new HashSet<>());

        talkTypeList.add(talkType);
        talkTypeNameToTalkTypeMap.put(talkTypeName, talkType);
    }

    solution.setTalkTypeList(talkTypeList);
}

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

private void importTalkList() {
    this.talkCodeToTalkMap = new HashMap<>();
    List<Talk> talkList = new ArrayList<>();
    Long talkId = 0L;//from w  w  w  .  j  ava 2 s.c  o m

    String talksPath = getClass().getResource("devoxxBE").toString();
    String[] confFiles = { "BOF", "Conf14Sept2018", "DeepDive", "HandsOnLabs", "Quickies", "ToolsInAction" };
    for (String confType : confFiles) {
        LOGGER.debug("Sending a request to: " + talksPath + "/" + confType + ".json");
        JsonArray talksArray = readJson(talksPath + "/" + confType + ".json", JsonReader::readObject)
                .getJsonObject("approvedTalks").getJsonArray("talks");

        for (int i = 0; i < talksArray.size(); i++) {
            JsonObject talkObject = talksArray.getJsonObject(i);

            String code = talkObject.getString("id");
            String title = talkObject.getString("title").substring(5);
            String talkTypeName = talkObject.getJsonObject("talkType").getString("id");
            Set<String> themeTrackSet = extractThemeTrackSet(talkObject, code, title);
            String language = talkObject.getString("lang");
            int audienceLevel = Integer
                    .parseInt(talkObject.getString("audienceLevel").replaceAll("[^0-9]", ""));
            List<Speaker> speakerList = extractSpeakerList(confType, talkObject, code, title);
            Set<String> contentTagSet = extractContentTagSet(talkObject);
            String state = talkObject.getJsonObject("state").getString("code");

            if (!Arrays.asList(IGNORED_TALK_TYPES).contains(code) && !state.equals("declined")) {
                Talk talk = createTalk(talkId++, code, title, talkTypeName, themeTrackSet, language,
                        speakerList, audienceLevel, contentTagSet);
                talkCodeToTalkMap.put(code, talk);
                talkList.add(talk);
                talkTalkTypeToTotalMap.merge(talkTypeName, 1, Integer::sum);
            }
        }
    }
    solution.setTalkList(talkList);
}

From source file:org.apache.tamaya.etcd.EtcdAccessor.java

/**
 * Ask etcd for a single key, value pair. Hereby the response returned from
 * etcd://from w ww  . ja  va  2  s .com
 * 
 * <pre>
 * {
 * "action": "get",
 * "node": {
 * "createdIndex": 2,
 * "key": "/message",
 * "modifiedIndex": 2,
 * "value": "Hello world"
 * }
 * }
 * </pre>
 * 
 * is mapped to:
 * 
 * <pre>
 *     key=value
 *     _key.source=[etcd]http://127.0.0.1:4001
 *     _key.createdIndex=12
 *     _key.modifiedIndex=34
 *     _key.ttl=300
 *     _key.expiration=...
 * </pre>
 *
 * @param key the requested key
 * @return the mapped result, including meta-entries.
 */
public Map<String, String> get(String key) {
    final Map<String, String> result = new HashMap<>();
    try {
        final HttpGet httpGet = new HttpGet(serverURL + "/v2/keys/" + key);
        httpGet.setConfig(RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(socketTimeout)
                .setConnectionRequestTimeout(timeout).setConnectTimeout(connectTimeout).build());
        try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                final HttpEntity entity = response.getEntity();
                final JsonReader reader = readerFactory
                        .createReader(new StringReader(EntityUtils.toString(entity)));
                final JsonObject o = reader.readObject();
                final JsonObject node = o.getJsonObject("node");
                if (node.containsKey("value")) {
                    result.put(key, node.getString("value"));
                    result.put("_" + key + ".source", "[etcd]" + serverURL);
                }
                if (node.containsKey("createdIndex")) {
                    result.put("_" + key + ".createdIndex", String.valueOf(node.getInt("createdIndex")));
                }
                if (node.containsKey("modifiedIndex")) {
                    result.put("_" + key + ".modifiedIndex", String.valueOf(node.getInt("modifiedIndex")));
                }
                if (node.containsKey("expiration")) {
                    result.put("_" + key + ".expiration", String.valueOf(node.getString("expiration")));
                }
                if (node.containsKey("ttl")) {
                    result.put("_" + key + ".ttl", String.valueOf(node.getInt("ttl")));
                }
                EntityUtils.consume(entity);
            } else {
                result.put("_" + key + ".NOT_FOUND.target", "[etcd]" + serverURL);
            }
        }
    } catch (final Exception e) {
        LOG.log(Level.INFO, "Error reading key '" + key + "' from etcd: " + serverURL, e);
        result.put("_ERROR", "Error reading key '" + key + "' from etcd: " + serverURL + ": " + e.toString());
    }
    return result;
}

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

private void importSpeakerList() {
    this.speakerNameToSpeakerMap = new HashMap<>();
    this.talkUrlSet = new HashSet<>();
    List<Speaker> speakerList = new ArrayList<>();

    String speakersUrl = conferenceBaseUrl + "/speakers";
    LOGGER.debug("Sending a request to: " + speakersUrl);
    JsonArray speakerArray = readJson(speakersUrl, JsonReader::readArray);

    for (int i = 0; i < speakerArray.size(); i++) {
        String speakerUrl = speakerArray.getJsonObject(i).getJsonArray("links").getJsonObject(0)
                .getString("href");
        LOGGER.debug("Sending a request to: " + speakerUrl);
        JsonObject speakerObject = readJson(speakerUrl, JsonReader::readObject);

        String speakerId = speakerObject.getString("uuid");
        String speakerName = speakerObject.getString("firstName") + " " + speakerObject.getString("lastName");

        if (Arrays.asList(IGNORED_SPEAKER_NAMES).contains(speakerName)) {
            continue;
        }//  ww  w .  j  a v  a 2 s  . c o m
        Speaker speaker = new Speaker((long) i);
        speaker.setName(speakerName);
        speaker.withPreferredRoomTagSet(new HashSet<>()).withPreferredTimeslotTagSet(new HashSet<>())
                .withProhibitedRoomTagSet(new HashSet<>()).withProhibitedTimeslotTagSet(new HashSet<>())
                .withRequiredRoomTagSet(new HashSet<>()).withRequiredTimeslotTagSet(new HashSet<>())
                .withUnavailableTimeslotSet(new HashSet<>()).withUndesiredRoomTagSet(new HashSet<>())
                .withUndesiredTimeslotTagSet(new HashSet<>());
        speakerList.add(speaker);
        if (speakerNameToSpeakerMap.keySet().contains(speakerName)) {
            throw new IllegalStateException("Speaker (" + speakerName + ") with id (" + speakerId
                    + ") already exists in the speaker list");
        }
        speakerNameToSpeakerMap.put(speakerName, speaker);

        JsonArray speakerTalksArray = speakerObject.getJsonArray("acceptedTalks");
        for (int j = 0; j < speakerTalksArray.size(); j++) {
            String talkUrl = speakerTalksArray.getJsonObject(j).getJsonArray("links").getJsonObject(0)
                    .getString("href");
            talkUrlSet.add(talkUrl);
        }
    }

    speakerList.sort(Comparator.comparing(Speaker::getName));
    solution.setSpeakerList(speakerList);
}

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

private void importTimeslotList() {
    List<Timeslot> timeslotList = new ArrayList<>();
    Map<Timeslot, List<Room>> timeslotToAvailableRoomsMap = new HashMap<>();
    Map<Pair<LocalDateTime, LocalDateTime>, Timeslot> startAndEndTimeToTimeslotMap = new HashMap<>();

    Long timeSlotId = 0L;/*  w ww  .  j av  a  2  s. c  om*/
    String schedulesUrl = conferenceBaseUrl + "/schedules/";
    LOGGER.debug("Sending a request to: " + schedulesUrl);
    JsonArray daysArray = readJson(schedulesUrl, JsonReader::readObject).getJsonArray("links");
    for (int i = 0; i < daysArray.size(); i++) {
        JsonObject dayObject = daysArray.getJsonObject(i);
        String dayUrl = dayObject.getString("href");

        LOGGER.debug("Sending a request to: " + dayUrl);
        JsonArray daySlotsArray = readJson(dayUrl, JsonReader::readObject).getJsonArray("slots");

        for (int j = 0; j < daySlotsArray.size(); j++) {
            JsonObject timeslotObject = daySlotsArray.getJsonObject(j);

            LocalDateTime startDateTime = LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(timeslotObject.getJsonNumber("fromTimeMillis").longValue()),
                    ZoneId.of(ZONE_ID));
            LocalDateTime endDateTime = LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(timeslotObject.getJsonNumber("toTimeMillis").longValue()),
                    ZoneId.of(ZONE_ID));

            Room room = roomIdToRoomMap.get(timeslotObject.getString("roomId"));
            if (room == null) {
                throw new IllegalStateException("The timeslot (" + timeslotObject.getString("slotId")
                        + ") has a roomId (" + timeslotObject.getString("roomId")
                        + ") that does not exist in the rooms list");
            }

            // Assuming slotId is of format: tia_room6_monday_12_.... take only "tia"
            String talkTypeName = timeslotObject.getString("slotId").split("_")[0];
            TalkType timeslotTalkType = talkTypeNameToTalkTypeMap.get(talkTypeName);
            if (Arrays.asList(IGNORED_TALK_TYPES).contains(talkTypeName)) {
                continue;
            }

            Timeslot timeslot;
            if (startAndEndTimeToTimeslotMap.keySet().contains(Pair.of(startDateTime, endDateTime))) {
                timeslot = startAndEndTimeToTimeslotMap.get(Pair.of(startDateTime, endDateTime));
                timeslotToAvailableRoomsMap.get(timeslot).add(room);
                if (timeslotTalkType != null) {
                    timeslot.getTalkTypeSet().add(timeslotTalkType);
                }
            } else {
                timeslot = new Timeslot(timeSlotId++);
                timeslot.withStartDateTime(startDateTime).withEndDateTime(endDateTime)
                        .withTalkTypeSet(timeslotTalkType == null ? new HashSet<>()
                                : new HashSet<>(Arrays.asList(timeslotTalkType)));
                timeslot.setTagSet(new HashSet<>());

                timeslotList.add(timeslot);
                timeslotToAvailableRoomsMap.put(timeslot, new ArrayList<>(Arrays.asList(room)));
                startAndEndTimeToTimeslotMap.put(Pair.of(startDateTime, endDateTime), timeslot);
            }

            if (!timeslotObject.isNull("talk")) {
                scheduleTalk(timeslotObject, room, timeslot);
            }

            for (TalkType talkType : timeslot.getTalkTypeSet()) {
                talkType.getCompatibleTimeslotSet().add(timeslot);
            }
            timeslotTalkTypeToTotalMap.merge(talkTypeName, 1, Integer::sum);
        }
    }

    for (Room room : solution.getRoomList()) {
        room.setUnavailableTimeslotSet(timeslotList.stream()
                .filter(timeslot -> !timeslotToAvailableRoomsMap.get(timeslot).contains(room))
                .collect(Collectors.toSet()));
    }

    solution.setTimeslotList(timeslotList);
}

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

private List<Speaker> extractSpeakerList(String confType, JsonObject talkObject, String code, String title) {
    List<Speaker> speakerList = new ArrayList<>();

    String mainSpeakerName = talkObject.getString("mainSpeaker");
    if (Arrays.asList(IGNORED_SPEAKER_NAMES).contains(mainSpeakerName)) {
        return speakerList;
    }/*from   ww w . j  a  va  2s  .com*/

    speakerList.add(getSpeakerOrCreateOneIfNull(confType, code, title, mainSpeakerName));
    if (talkObject.containsKey("secondarySpeaker")) {
        String secondarySpeakerName = talkObject.getString("secondarySpeaker");
        speakerList.add(getSpeakerOrCreateOneIfNull(confType, code, title, secondarySpeakerName));
    }

    if (talkObject.containsKey("otherSpeakers")) {
        JsonArray otherSpeakersArray = talkObject.getJsonArray("otherSpeakers");
        for (JsonValue otherSpeakerName : otherSpeakersArray) {
            speakerList.add(getSpeakerOrCreateOneIfNull(confType, code, title,
                    otherSpeakerName.toString().replaceAll("\"", "")));
        }
    }

    return speakerList;
}

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());//from   w ww  .j  a  v a 2s .  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())).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());/*  w ww.  j  a  v 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(), 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"));
}

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

@Test
public void handleExecuteNestedCleanupError() throws Exception {
    UnitTestUtils.mockJobConsoleLogger();
    PowerMockito.mockStatic(DockerUtils.class);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.pullImage(anyString());/*from w w w . j  a  va 2s .  co  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("FAIL1"));
    PowerMockito.doThrow(new DockerException("FAIL2")).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", "FAIL1", responseBody.getString("message"));
}