Example usage for com.google.gson JsonPrimitive JsonPrimitive

List of usage examples for com.google.gson JsonPrimitive JsonPrimitive

Introduction

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

Prototype

public JsonPrimitive(Character c) 

Source Link

Document

Create a primitive containing a character.

Usage

From source file:com.google.dart.server.generated.types.ExtractMethodFeedback.java

License:Open Source License

public JsonObject toJson() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("offset", offset);
    jsonObject.addProperty("length", length);
    jsonObject.addProperty("returnType", returnType);
    JsonArray jsonArrayNames = new JsonArray();
    for (String elt : names) {
        jsonArrayNames.add(new JsonPrimitive(elt));
    }//from  www  .  j a  v  a  2s. c om
    jsonObject.add("names", jsonArrayNames);
    jsonObject.addProperty("canCreateGetter", canCreateGetter);
    JsonArray jsonArrayParameters = new JsonArray();
    for (RefactoringMethodParameter elt : parameters) {
        jsonArrayParameters.add(elt.toJson());
    }
    jsonObject.add("parameters", jsonArrayParameters);
    JsonArray jsonArrayOffsets = new JsonArray();
    for (int elt : offsets) {
        jsonArrayOffsets.add(new JsonPrimitive(elt));
    }
    jsonObject.add("offsets", jsonArrayOffsets);
    JsonArray jsonArrayLengths = new JsonArray();
    for (int elt : lengths) {
        jsonArrayLengths.add(new JsonPrimitive(elt));
    }
    jsonObject.add("lengths", jsonArrayLengths);
    return jsonObject;
}

From source file:com.google.dart.server.generated.types.NavigationRegion.java

License:Open Source License

public JsonObject toJson() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("offset", offset);
    jsonObject.addProperty("length", length);
    JsonArray jsonArrayTargets = new JsonArray();
    for (int elt : targets) {
        jsonArrayTargets.add(new JsonPrimitive(elt));
    }//  w ww.ja  v a 2 s . c om
    jsonObject.add("targets", jsonArrayTargets);
    return jsonObject;
}

From source file:com.google.dart.server.generated.types.Occurrences.java

License:Open Source License

public JsonObject toJson() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.add("element", element.toJson());
    JsonArray jsonArrayOffsets = new JsonArray();
    for (int elt : offsets) {
        jsonArrayOffsets.add(new JsonPrimitive(elt));
    }/* w ww.  j av a2 s. c  o  m*/
    jsonObject.add("offsets", jsonArrayOffsets);
    jsonObject.addProperty("length", length);
    return jsonObject;
}

From source file:com.google.dart.server.generated.types.TypeHierarchyItem.java

License:Open Source License

public JsonObject toJson() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.add("classElement", classElement.toJson());
    if (displayName != null) {
        jsonObject.addProperty("displayName", displayName);
    }//ww w.  j  av a  2s.  co m
    if (memberElement != null) {
        jsonObject.add("memberElement", memberElement.toJson());
    }
    if (superclass != null) {
        jsonObject.addProperty("superclass", superclass);
    }
    JsonArray jsonArrayInterfaces = new JsonArray();
    for (int elt : interfaces) {
        jsonArrayInterfaces.add(new JsonPrimitive(elt));
    }
    jsonObject.add("interfaces", jsonArrayInterfaces);
    JsonArray jsonArrayMixins = new JsonArray();
    for (int elt : mixins) {
        jsonArrayMixins.add(new JsonPrimitive(elt));
    }
    jsonObject.add("mixins", jsonArrayMixins);
    JsonArray jsonArraySubclasses = new JsonArray();
    for (int elt : subclasses) {
        jsonArraySubclasses.add(new JsonPrimitive(elt));
    }
    jsonObject.add("subclasses", jsonArraySubclasses);
    return jsonObject;
}

From source file:com.google.dart.server.internal.remote.utilities.RequestUtilities.java

License:Open Source License

@VisibleForTesting
public static JsonElement buildJsonElement(Object object) {
    if (object instanceof Boolean) {
        return new JsonPrimitive((Boolean) object);
    } else if (object instanceof Number) {
        return new JsonPrimitive((Number) object);
    } else if (object instanceof String) {
        return new JsonPrimitive((String) object);
    } else if (object instanceof List<?>) {
        List<?> list = (List<?>) object;
        JsonArray jsonArray = new JsonArray();
        for (Object item : list) {
            JsonElement jsonItem = buildJsonElement(item);
            jsonArray.add(jsonItem);/*from   www.j  av a 2  s .  c  o  m*/
        }
        return jsonArray;
    } else if (object instanceof Map<?, ?>) {
        Map<?, ?> map = (Map<?, ?>) object;
        JsonObject jsonObject = new JsonObject();
        for (Entry<?, ?> entry : map.entrySet()) {
            Object key = entry.getKey();
            // prepare string key
            String keyString;
            if (key instanceof String) {
                keyString = (String) key;
            } else {
                throw new IllegalArgumentException("Unable to convert to string: " + getClassName(key));
            }
            // prepare JsonElement value
            Object value = entry.getValue();
            JsonElement valueJson = buildJsonElement(value);
            // put a property into the JSON object
            if (keyString != null && valueJson != null) {
                jsonObject.add(keyString, valueJson);
            }
        }
        return jsonObject;
    } else if (object instanceof AnalysisError) {
        return buildJsonObjectAnalysisError((AnalysisError) object);
    } else if (object instanceof AddContentOverlay) {
        return ((AddContentOverlay) object).toJson();
    } else if (object instanceof ChangeContentOverlay) {
        return ((ChangeContentOverlay) object).toJson();
    } else if (object instanceof RemoveContentOverlay) {
        return ((RemoveContentOverlay) object).toJson();
    } else if (object instanceof AnalysisOptions) {
        return ((AnalysisOptions) object).toJson();
    } else if (object instanceof Location) {
        return buildJsonObjectLocation((Location) object);
    }
    throw new IllegalArgumentException("Unable to convert to JSON: " + object);
}

From source file:com.google.devfestnorte.server.APIUpdater.java

License:Open Source License

public void run(boolean force, OutputStream optionalOutput) throws IOException {

    RemoteFilesEntityFetcherFactory.setBuilder(new FetcherBuilder() {
        String[] filenames;// w  ww  . j av a  2 s.c  om

        @Override
        public FetcherBuilder setSourceFiles(String... filenames) {
            this.filenames = filenames;
            return this;
        }

        @Override
        public EntityFetcher build() {
            return new CloudStorageRemoteFilesEntityFetcher(filenames);
        }
    });

    UpdateRunLogger logger = new UpdateRunLogger();
    CloudFileManager fileManager = new CloudFileManager();

    logger.startTimer();
    JsonDataSources sources = new ExtraInput().fetchAllDataSources();
    logger.stopTimer("fetchExtraAPI");

    logger.startTimer();
    sources.putAll(new VendorStaticInput().fetchAllDataSources());
    logger.stopTimer("fetchVendorStaticAPI");

    logger.startTimer();
    JsonObject newData = new DataExtractor().extractFromDataSources(sources);
    logger.stopTimer("extractOurData");

    logger.startTimer();
    byte[] newHash = CloudFileManager.calulateHash(newData);
    logger.stopTimer("calculateHash");

    // compare current Vendor API log with the one from previous run:
    logger.startTimer();
    if (!force && isUpToDate(newHash, logger)) {
        logger.logNoopRun();
        return;
    }
    logger.stopTimer("compareHash");

    logger.startTimer();
    ManifestData dataProduction = extractManifestData(fileManager.readProductionManifest(), null);
    ManifestData dataStaging = extractManifestData(fileManager.readStagingManifest(), dataProduction);

    logger.stopTimer("readManifest");

    JsonWriter optionalOutputWriter = null;

    logger.startTimer();
    // Upload a new version of the sessions file
    if (optionalOutput != null) {
        // send data to the outputstream
        Writer writer = Channels.newWriter(Channels.newChannel(optionalOutput), "UTF-8");
        optionalOutputWriter = new JsonWriter(writer);
        optionalOutputWriter.setIndent("  ");
        new Gson().toJson(newData, optionalOutputWriter);
        optionalOutputWriter.flush();
    } else {
        // save data to the CloudStorage
        fileManager.createOrUpdate(dataProduction.sessionsFilename, newData, false);
    }
    logger.stopTimer("uploadNewSessionsFile");

    // Check data consistency
    logger.startTimer();
    DataCheck checker = new DataCheck(fileManager);
    CheckResult result = checker.check(sources, newData, dataProduction);
    if (!result.failures.isEmpty()) {
        reportDataCheckFailures(result, optionalOutput);
    }
    logger.stopTimer("runDataCheck");

    if (optionalOutput == null) {
        // Only update manifest and log if saving to persistent storage

        logger.startTimer();

        // Create new manifests
        JsonObject newProductionManifest = new JsonObject();
        newProductionManifest.add("format", new JsonPrimitive(Config.MANIFEST_FORMAT_VERSION));
        newProductionManifest.add("data_files", dataProduction.dataFiles);

        JsonObject newStagingManifest = new JsonObject();
        newStagingManifest.add("format", new JsonPrimitive(Config.MANIFEST_FORMAT_VERSION));
        newStagingManifest.add("data_files", dataStaging.dataFiles);

        // save manifests to the CloudStorage
        fileManager.createOrUpdateProductionManifest(newProductionManifest);
        fileManager.createOrUpdateStagingManifest(newStagingManifest);

        try {
            // notify production GCM server:
            new GCMPing().notifyGCMServer(Config.GCM_PROD, Config.GCM_API_KEY_PROD);
        } catch (Throwable t) {
            Logger.getLogger(APIUpdater.class.getName()).log(Level.SEVERE,
                    "error while pinging production GCM server", t);
        }

        try {
            // notify staging GCM server:
            new GCMPing().notifyGCMServer(Config.GCM_DEV, Config.GCM_API_KEY_DEV);
        } catch (Throwable t) {
            Logger.getLogger(APIUpdater.class.getName()).log(Level.WARNING,
                    "error while pinging staging GCM server", t);
        }

        logger.stopTimer("uploadManifest");

        logger.logUpdateRun(dataProduction.majorVersion, dataProduction.minorVersion,
                dataProduction.sessionsFilename, newHash, newData, force);
    }

}

From source file:com.google.devfestnorte.server.APIUpdater.java

License:Open Source License

private ManifestData extractManifestData(JsonObject currentManifest, ManifestData copyFrom) {
    ManifestData data = new ManifestData();
    data.majorVersion = copyFrom == null ? Config.MANIFEST_VERSION : copyFrom.majorVersion;
    data.minorVersion = copyFrom == null ? 0 : copyFrom.minorVersion;
    data.dataFiles = new JsonArray();

    if (currentManifest != null) {
        try {/*w  w w  .j  a  v  a  2s  . co m*/
            JsonArray files = currentManifest.get("data_files").getAsJsonArray();
            for (JsonElement file : files) {
                String filename = file.getAsString();
                Matcher matcher = Config.SESSIONS_PATTERN.matcher(filename);
                if (matcher.matches()) {
                    // versions numbers are only extracted from the existing session filename if copyFrom is null.
                    if (copyFrom == null) {
                        data.majorVersion = Integer.parseInt(matcher.group(1));
                        data.minorVersion = Integer.parseInt(matcher.group(2));
                    }
                } else {
                    data.dataFiles.add(file);
                }
            }
        } catch (NullPointerException ex) {
            Logger.getLogger(getClass().getName())
                    .warning("Ignoring existing manifest, as it seems " + "to be badly formatted.");
        } catch (NumberFormatException ex) {
            Logger.getLogger(getClass().getName())
                    .warning("Ignoring existing manifest, as it seems " + "to be badly formatted.");
        }
    }

    if (copyFrom == null) {
        // Increment the minor version
        data.minorVersion++;
        data.sessionsFilename = MessageFormat.format(Config.SESSIONS_FORMAT, data.majorVersion,
                data.minorVersion);
    } else {
        data.sessionsFilename = copyFrom.sessionsFilename;
    }

    data.dataFiles.add(new JsonPrimitive(data.sessionsFilename));
    return data;
}

From source file:com.google.gdt.googleapi.core.ApiDirectoryListingJsonCodec.java

License:Open Source License

protected void populateJsonFromApiInfo(ReadableApiInfo src, JsonObject entry, String baseHref) {
    if (null != src.getName()) {
        entry.addProperty("name", src.getName());
    }// w w  w.  java 2 s .co m
    if (null != src.getVersion()) {
        entry.addProperty("version", src.getVersion());
    }
    if (null != src.getDisplayName()) {
        entry.addProperty("title", src.getDisplayName());
    }
    if (null != src.getPublisher()) {
        entry.addProperty("publisher", src.getPublisher());
    }
    String[] labels = src.getLabels();
    if (labels.length > 0) {
        JsonArray jsonLabels = new JsonArray();
        for (String label : labels) {
            jsonLabels.add(new JsonPrimitive(label));
        }
        entry.add("labels", jsonLabels);
    }
    entry.addProperty("ranking", src.getRanking());
    if (null != src.getDescription()) {
        entry.addProperty("description", src.getDescription());
    }
    Set<String> iconLinkRefs = src.getIconLinkKeys();
    if (!iconLinkRefs.isEmpty()) {
        JsonObject iconLinks = new JsonObject();
        for (String ref : iconLinkRefs) {
            URL link = src.getIconLink(ref);
            if (link == null) {
                break;
            }
            String linkStr = renderLink(link, baseHref);
            if (linkStr == null) {
                break;
            }
            iconLinks.addProperty(ref, linkStr);
        }
        entry.add("icons", iconLinks);
    }
    if (null != src.getTosLink()) {
        entry.addProperty("tosLink", src.getTosLink().toExternalForm());
    }
    if (null != src.getReleaseDate()) {
        entry.addProperty("releaseDate", src.getReleaseDate().toString());
    }
    if (null != src.getReleaseNotesLink()) {
        entry.addProperty("releaseNotesLink", src.getReleaseNotesLink().toExternalForm());
    }
    if (null != src.getDiscoveryLink()) {
        entry.addProperty("discoveryLink", src.getDiscoveryLink().toExternalForm());
    }
    if (null != src.getDocumentationLink()) {
        entry.addProperty("documentationLink", src.getDocumentationLink().toExternalForm());
    }
    if (null != src.getDownloadLink()) {
        entry.addProperty("downloadLink", src.getDownloadLink().toExternalForm());
    }
}

From source file:com.google.gerrit.httpd.restapi.ParameterParser.java

License:Apache License

@VisibleForTesting
static JsonObject formToJson(Map<String, String[]> map, Set<String> query) throws BadRequestException {
    JsonObject inputObject = new JsonObject();
    for (Map.Entry<String, String[]> ent : map.entrySet()) {
        String key = ent.getKey();
        String[] values = ent.getValue();

        if (query.contains(key) || values.length == 0) {
            // Disallow processing query parameters as input body fields.
            // Implementations of views should avoid duplicate naming.
            continue;
        }//www  .ja v  a  2  s .c  o m

        JsonObject obj = inputObject;
        int dot = key.indexOf('.');
        if (0 <= dot) {
            String property = key.substring(0, dot);
            JsonElement e = inputObject.get(property);
            if (e == null) {
                obj = new JsonObject();
                inputObject.add(property, obj);
            } else if (e.isJsonObject()) {
                obj = e.getAsJsonObject();
            } else {
                throw new BadRequestException(String.format("key %s conflicts with %s", key, property));
            }
            key = key.substring(dot + 1);
        }

        if (obj.get(key) != null) {
            // This error should never happen. If all form values are handled
            // together in a single pass properties are set only once. Setting
            // again indicates something has gone very wrong.
            throw new BadRequestException("invalid form input, use JSON instead");
        } else if (values.length == 1) {
            obj.addProperty(key, values[0]);
        } else {
            JsonArray list = new JsonArray();
            for (String v : values) {
                list.add(new JsonPrimitive(v));
            }
            obj.add(key, list);
        }
    }
    return inputObject;
}

From source file:com.google.gerrit.httpd.restapi.RestApiServlet.java

License:Apache License

static void replyText(@Nullable HttpServletRequest req, HttpServletResponse res, String text)
        throws IOException {
    if ((req == null || isGetOrHead(req)) && isMaybeHTML(text)) {
        replyJson(req, res, ImmutableMultimap.of("pp", "0"), new JsonPrimitive(text));
    } else {/*w  ww  .  j a  va 2  s.c  om*/
        if (!text.endsWith("\n")) {
            text += "\n";
        }
        replyBinaryResult(req, res, BinaryResult.create(text).setContentType("text/plain"));
    }
}