Example usage for com.google.gson JsonElement getAsJsonArray

List of usage examples for com.google.gson JsonElement getAsJsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsJsonArray.

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

From source file:com.qmetry.qaf.automation.gson.GsonObjectDeserializer.java

License:Open Source License

public static Object read(JsonElement in) {

    if (in.isJsonArray()) {
        List<Object> list = new ArrayList<Object>();
        JsonArray arr = in.getAsJsonArray();
        for (JsonElement anArr : arr) {
            list.add(read(anArr));//from w  w w  .j a  v a  2 s  . co  m
        }
        return list;
    } else if (in.isJsonObject()) {
        Map<String, Object> map = new LinkedTreeMap<String, Object>();
        JsonObject obj = in.getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
        for (Map.Entry<String, JsonElement> entry : entitySet) {
            map.put(entry.getKey(), read(entry.getValue()));
        }
        return map;
    } else if (in.isJsonPrimitive()) {
        JsonPrimitive prim = in.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isString()) {
            return prim.getAsString();
        } else if (prim.isNumber()) {
            if (prim.getAsString().contains("."))
                return prim.getAsDouble();
            else {
                return prim.getAsLong();
            }
        }
    }
    return null;
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.patch.QMetryRestWebservice.java

License:Open Source License

/**
 * attach log using run id/*from   w w  w  .  j  a va2s .  c om*/
 * 
 * @param token
 *            - token generate using username and password
 * @param projectID
 * @param releaseID
 * @param cycleID
 * @param testCaseRunId
 * @param filePath
 *            - absolute path of file to be attached
 * @return
 */
public int attachTestLogsUsingRunId(String token, String projectID, String releaseID, String cycleID,
        long testCaseRunId, File filePath) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(baseURL + "/rest/attachments/testLog");

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                FileBody bin = new FileBody(filePath);
                builder.addTextBody("desc", "Attached on " + CurrentDate, ContentType.TEXT_PLAIN);
                builder.addTextBody("type", "TCR", ContentType.TEXT_PLAIN);
                builder.addTextBody("entityId", String.valueOf(testCaseRunId), ContentType.TEXT_PLAIN);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", projectID + ":" + releaseID + ":" + cycleID);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java

License:Open Source License

/**
 * attach log using run id/*from w ww .j  a  v  a 2s.c o m*/
 * 
 * @param token
 *            - token generate using username and password
 * @param scope
 *            : project:release:cycle
 * @param testCaseRunId
 * @param filePath
 *            - absolute path of file to be attached
 * @return
 */
public int attachTestLogsUsingRunId(long testCaseRunId, File filePath) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog");

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                FileBody bin = new FileBody(filePath);
                builder.addTextBody("desc", "Attached on " + CurrentDate,
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("entityId", String.valueOf(testCaseRunId),
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", scope);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java

License:Open Source License

/**
 * attach log using run id/*from   w w w.ja v a 2s. c  om*/
 * 
 * @param token
 *            - token generate using username and password
 * @param scope
 *            : project:release:cycle
 * @param testCaseRunId
 * @param filePath
 *            - absolute path of file to be attached
 * @param serviceUrl
 * @param scope
 * @return
 */
public int attachTestLogsUsingRunID(String serviceUrl, long testCaseRunId, File filePath, String scope) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog");

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                FileBody bin = new FileBody(filePath);
                builder.addTextBody("desc", "Attached on " + CurrentDate,
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("entityId", String.valueOf(testCaseRunId),
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", scope);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry7.QMetryRestWebservice.java

License:Open Source License

public int attachTestLogs(long tcVersionIdASEntityId, File filePath) {
    try {//  w  ww .j  a v  a2  s.  c om
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments");

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                FileBody bin = new FileBody(filePath);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", scope);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpAggregatedMultiIngestionHandler.java

License:Apache License

public static List<AggregatedPayload> createBundleList(String json) {
    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(json);

    if (!element.isJsonArray()) {
        throw new InvalidDataException("Invalid request body");
    }//w w  w.j a  va  2 s.c o  m

    JsonArray jArray = element.getAsJsonArray();

    ArrayList<AggregatedPayload> bundleList = new ArrayList<AggregatedPayload>();

    for (JsonElement obj : jArray) {
        AggregatedPayload bundle = AggregatedPayload.create(obj);
        bundleList.add(bundle);
    }

    return bundleList;
}

From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpMultiRollupsQueryHandler.java

License:Apache License

private List<String> getLocatorsFromJSONBody(String tenantId, String body) {
    JsonElement element = gson.fromJson(body, JsonElement.class);
    JsonArray metrics = element.getAsJsonArray();
    final List<String> locators = new ArrayList<String>();

    Iterator<JsonElement> it = metrics.iterator();
    while (it.hasNext()) {
        JsonElement metricElement = it.next();
        locators.add(metricElement.getAsString());
    }//  w ww .j  av a 2 s . co  m

    return locators;
}

From source file:com.razza.apps.iosched.server.schedule.model.DataExtractor.java

License:Open Source License

public JsonArray extractSessions(JsonDataSources sources) {
    if (videoSessionsById == null) {
        throw new IllegalStateException(
                "You need to extract video sessions before attempting to extract sessions");
    }/*from w ww .  j  av a  2 s .  c  o m*/
    if (categoryToTagMap == null) {
        throw new IllegalStateException("You need to extract tags before attempting to extract sessions");
    }

    JsonArray result = new JsonArray();
    JsonDataSource source = sources.getSource(InputJsonKeys.VendorAPISource.MainTypes.topics.name());
    if (source != null) {
        for (JsonObject origin : source) {
            if (isVideoSession(origin)) {
                // Sessions with the Video tag are processed as video library content
                continue;
            }
            if (isHiddenSession(origin)) {
                // Sessions with a "Hidden from schedule" flag should be ignored
                continue;
            }
            JsonElement title = DataModelHelper.get(origin, InputJsonKeys.VendorAPISource.Topics.title);
            // Since the CMS returns an empty keynote as a session, we need to ignore it
            if (title != null && title.isJsonPrimitive() && "keynote".equalsIgnoreCase(title.getAsString())) {
                continue;
            }
            JsonObject dest = new JsonObject();

            // Some sessions require a special ID, so we replace it here...
            if (title != null && title.isJsonPrimitive()
                    && "after hours".equalsIgnoreCase(title.getAsString())) {
                DataModelHelper.set(new JsonPrimitive("__afterhours__"), dest, OutputJsonKeys.Sessions.id);
            } else {
                DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest,
                        OutputJsonKeys.Sessions.id);
            }
            DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest,
                    OutputJsonKeys.Sessions.url, Converters.SESSION_URL);
            DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.title, dest,
                    OutputJsonKeys.Sessions.title, obfuscate ? Converters.OBFUSCATE : null);
            DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.description, dest,
                    OutputJsonKeys.Sessions.description, obfuscate ? Converters.OBFUSCATE : null);
            DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.start, dest,
                    OutputJsonKeys.Sessions.startTimestamp, Converters.DATETIME);
            DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.finish, dest,
                    OutputJsonKeys.Sessions.endTimestamp, Converters.DATETIME);
            DataModelHelper.set(new JsonPrimitive(isFeatured(origin)), dest,
                    OutputJsonKeys.Sessions.isFeatured);

            JsonElement documents = DataModelHelper.get(origin, InputJsonKeys.VendorAPISource.Topics.documents);
            if (documents != null && documents.isJsonArray() && documents.getAsJsonArray().size() > 0) {
                // Note that the input for SessionPhotoURL is the entity ID. We simply ignore the original
                // photo URL, because that will be processed by an offline cron script, resizing the
                // photos and saving them to a known location with the entity ID as its base name.
                DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest,
                        OutputJsonKeys.Sessions.photoUrl, Converters.SESSION_PHOTO_URL);
            }

            setVideoPropertiesInSession(origin, dest);
            setRelatedContent(origin, dest);

            JsonElement mainTag = null;
            JsonElement hashtag = null;
            JsonElement mainTagColor = null;
            JsonArray categories = origin
                    .getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.categoryids.name());
            JsonArray tags = new JsonArray();
            for (JsonElement category : categories) {
                JsonObject tag = categoryToTagMap.get(category.getAsString());
                if (tag != null) {
                    JsonElement tagName = DataModelHelper.get(tag, OutputJsonKeys.Tags.tag);
                    tags.add(tagName);
                    usedTags.add(tagName.getAsString());

                    if (mainTag == null) {
                        // check if the tag is from a "default" category. For example, if THEME is the default
                        // category, all sessions will have a "mainTag" property set to the first tag of type THEME
                        JsonElement tagCategory = DataModelHelper.get(tag, OutputJsonKeys.Tags.category); // THEME, TYPE or TOPIC
                        if (tagCategory.equals(mainCategory)) {
                            mainTag = tagName;
                            mainTagColor = DataModelHelper.get(tag, OutputJsonKeys.Tags.color);
                        }
                        if (hashtag == null && DataModelHelper.isHashtag(tag)) {
                            hashtag = DataModelHelper.get(tag, OutputJsonKeys.Tags.hashtag);
                            if (hashtag == null || hashtag.getAsString() == null
                                    || hashtag.getAsString().isEmpty()) {
                                // If no hashtag set in the tagsconf file, we will convert the tagname to find one:
                                hashtag = new JsonPrimitive(
                                        DataModelHelper.get(tag, OutputJsonKeys.Tags.name, Converters.TAG_NAME)
                                                .getAsString().toLowerCase());
                            }
                        }
                    }
                }
            }
            DataModelHelper.set(tags, dest, OutputJsonKeys.Sessions.tags);
            if (mainTag != null) {
                DataModelHelper.set(mainTag, dest, OutputJsonKeys.Sessions.mainTag);
            }
            if (mainTagColor != null) {
                DataModelHelper.set(mainTagColor, dest, OutputJsonKeys.Sessions.color);
            }
            if (hashtag != null) {
                DataModelHelper.set(hashtag, dest, OutputJsonKeys.Sessions.hashtag);
            }

            JsonArray speakers = DataModelHelper.getAsArray(origin,
                    InputJsonKeys.VendorAPISource.Topics.speakerids);
            if (speakers != null)
                for (JsonElement speaker : speakers) {
                    String speakerId = speaker.getAsString();
                    usedSpeakers.add(speakerId);
                }
            DataModelHelper.set(speakers, dest, OutputJsonKeys.Sessions.speakers);

            JsonArray sessions = origin.getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.sessions.name());
            if (sessions != null && sessions.size() > 0) {
                String roomId = DataModelHelper
                        .get(sessions.get(0).getAsJsonObject(), InputJsonKeys.VendorAPISource.Sessions.roomid)
                        .getAsString();
                roomId = Config.ROOM_MAPPING.getRoomId(roomId);
                DataModelHelper.set(new JsonPrimitive(roomId), dest, OutputJsonKeys.Sessions.room);

                // captions URL is set based on the session room, so keep it here.
                String captionsURL = Config.ROOM_MAPPING.getCaptions(roomId);
                if (captionsURL != null) {
                    DataModelHelper.set(new JsonPrimitive(captionsURL), dest,
                            OutputJsonKeys.Sessions.captionsUrl);
                }
            }

            if (Config.DEBUG_FIX_DATA) {
                DebugDataExtractorHelper.changeSession(dest, usedTags);
            }
            result.add(dest);
        }
    }
    return result;
}

From source file:com.razza.apps.iosched.server.schedule.model.DataExtractor.java

License:Open Source License

@Deprecated
private void setRelatedVideos(JsonObject origin, JsonObject dest) {
    JsonArray related = DataModelHelper.getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.related);
    if (related == null) {
        return;/*ww w  .  j a v  a  2 s .c  o m*/
    }
    for (JsonElement el : related) {
        if (!el.isJsonObject()) {
            continue;
        }
        JsonObject obj = el.getAsJsonObject();
        if (!obj.has("name") || !obj.has("values")) {
            continue;
        }

        if (InputJsonKeys.VendorAPISource.Topics.RELATED_NAME_VIDEO
                .equals(obj.getAsJsonPrimitive("name").getAsString())) {

            JsonElement values = obj.get("values");
            if (!values.isJsonArray()) {
                continue;
            }

            // As per the data specification, related content is formatted as
            // "video1 title1\nvideo2 title2\n..."
            StringBuilder relatedContentStr = new StringBuilder();
            for (JsonElement value : values.getAsJsonArray()) {
                String relatedSessionId = value.getAsString();
                JsonObject relatedVideo = videoSessionsById.get(relatedSessionId);
                if (relatedVideo != null) {
                    JsonElement vid = DataModelHelper.get(relatedVideo, OutputJsonKeys.VideoLibrary.vid);
                    JsonElement title = DataModelHelper.get(relatedVideo, OutputJsonKeys.VideoLibrary.title);
                    if (vid != null && title != null) {
                        relatedContentStr.append(vid.getAsString()).append(" ").append(title.getAsString())
                                .append("\n");
                    }
                }
            }
            DataModelHelper.set(new JsonPrimitive(relatedContentStr.toString()), dest,
                    OutputJsonKeys.Sessions.relatedContent);
        }
    }
}

From source file:com.razza.apps.iosched.server.schedule.model.DataExtractor.java

License:Open Source License

private void setRelatedContent(JsonObject origin, JsonObject dest) {
    JsonArray related = DataModelHelper.getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.related);
    JsonArray outputArray = new JsonArray();

    if (related == null) {
        return;/* w w w .j ava2  s.  c  o m*/
    }
    for (JsonElement el : related) {
        if (!el.isJsonObject()) {
            continue;
        }
        JsonObject obj = el.getAsJsonObject();
        if (!obj.has("name") || !obj.has("values")) {
            continue;
        }

        if (InputJsonKeys.VendorAPISource.Topics.RELATED_NAME_SESSIONS
                .equals(obj.getAsJsonPrimitive("name").getAsString())) {

            JsonElement values = obj.get("topics");
            if (!values.isJsonArray()) {
                continue;
            }

            // As per the data specification, related content is formatted as
            // "video1 title1\nvideo2 title2\n..."
            for (JsonElement topic : values.getAsJsonArray()) {
                if (!topic.isJsonObject()) {
                    continue;
                }

                JsonObject topicObj = topic.getAsJsonObject();

                String id = DataModelHelper.get(topicObj, InputJsonKeys.VendorAPISource.RelatedTopics.id)
                        .getAsString();
                String title = DataModelHelper.get(topicObj, InputJsonKeys.VendorAPISource.RelatedTopics.title)
                        .getAsString();

                if (id != null && title != null) {
                    JsonObject outputObj = new JsonObject();
                    DataModelHelper.set(new JsonPrimitive(id), outputObj, OutputJsonKeys.RelatedContent.id);
                    DataModelHelper.set(new JsonPrimitive(title), outputObj,
                            OutputJsonKeys.RelatedContent.title);
                    outputArray.add(outputObj);
                }
            }
            DataModelHelper.set(outputArray, dest, OutputJsonKeys.Sessions.relatedContent);
        }
    }
}