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.samples.apps.iosched.server.schedule.model.validator.TwitterURLConverter.java

License:Open Source License

/**
 * Takes a user inputted twitter profile as a JsonPrimitive and returns a properly
 * formatted/cleaned URL to that twitter profile.
 *///from   ww  w. j a v a2  s  .c  o m
@Override
public JsonPrimitive convert(JsonPrimitive value) {
    if (value == null) {
        return null;
    }
    String str = value.getAsString();
    if (str.isEmpty()) {
        return value;
    }

    // If they didn't enter it as a URL, format it as one.
    for (Pattern p : twitterRecognizedPatterns) {
        Matcher m = p.matcher(str);
        if (m.find()) {
            return new JsonPrimitive(twitterFormat.format(new String[] { m.group(0) }));
        }
    }

    // If URL starts with http/https:
    if (acceptableUrlPattern.matcher(str).matches()) {
        return value;
    }

    // Otherwise, just add https://:
    str = "https://" + str;
    return new JsonPrimitive(str);
}

From source file:com.google.samples.apps.iosched.server.schedule.server.APIUpdater.java

License:Open Source License

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

    RemoteFilesEntityFetcherFactory.setBuilder(new RemoteFilesEntityFetcherFactory.FetcherBuilder() {
        String[] filenames;//w  w  w.j ava2 s .c  om

        @Override
        public RemoteFilesEntityFetcherFactory.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(obfuscate).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_URL, Config.GCM_API_KEY);
        } catch (Throwable t) {
            Logger.getLogger(APIUpdater.class.getName()).log(Level.SEVERE, "Error while pinging GCM server", t);
        }

        logger.stopTimer("uploadManifest");

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

}

From source file:com.google.samples.apps.iosched.sync.userdata.util.UserActionHelper.java

License:Open Source License

public static String serializeUserActions(List<UserAction> actions) {
    JsonArray array = new JsonArray();
    for (UserAction action : actions) {
        JsonObject obj = new JsonObject();
        obj.add("type", new JsonPrimitive(action.type.name()));
        obj.add("id", new JsonPrimitive(action.sessionId));
        array.add(obj);/*from  www . j  a va 2s .co m*/
    }
    return array.toString();
}

From source file:com.google.samples.apps.iosched.sync.userdata.util.UserDataHelper.java

License:Open Source License

static public String toSessionsString(Set<String> sessionIds) {
    JsonArray array = new JsonArray();
    for (String sessionId : sessionIds) {
        array.add(new JsonPrimitive(sessionId));
    }//w ww.ja v a 2s. c  o  m
    JsonObject obj = new JsonObject();
    obj.add(JSON_STARRED_SESSIONS_KEY, array);
    return obj.toString();
}

From source file:com.google.shipshape.util.rpc.Connection.java

License:Open Source License

private Protocol.Request createRequest(Protocol.Version version, String method, Object params) {
    Preconditions.checkArgument(version != null, "version must be non-null");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(method), "method must be non-empty");
    Protocol.Request request = new Protocol.Request();
    request.version = version;/*  w w w  .  ja  v a 2s. c  o  m*/
    request.method = method;
    if (params != null) {
        request.params = gson.toJsonTree(params).getAsJsonObject();
    }
    request.id = new JsonPrimitive(id.incrementAndGet());
    return request;
}

From source file:com.google.u2f.server.messages.RegisteredKey.java

License:Open Source License

private JsonArray getTransportsAsJsonArray() {
    JsonArray transportsArray = new JsonArray();
    for (Transports transport : this.transports) {
        transportsArray.add(new JsonPrimitive(transport.toString()));
    }/*  w w w.  j  a  va 2 s  . c om*/
    return transportsArray;
}

From source file:com.google.walkaround.proto.gson.RobotSearchDigestGsonImpl.java

License:Apache License

/**
 * Static implementation-independent GSON serializer. Call this from
 * {@link #toGson} to avoid subclassing issues with inner message types.
 *///from ww  w . jav  a  2  s  .  c  o  m
public static JsonElement toGsonHelper(RobotSearchDigest message, RawStringData raw, Gson gson) {
    JsonObject json = new JsonObject();
    json.add("1", new JsonPrimitive(message.getWaveId()));
    {
        JsonArray array = new JsonArray();
        for (int i = 0; i < message.getParticipantSize(); i++) {
            array.add(new JsonPrimitive(message.getParticipant(i)));
        }
        json.add("2", array);
    }
    json.add("3", new JsonPrimitive(message.getTitle()));
    json.add("4", new JsonPrimitive(message.getSnippet()));
    json.add("5", GsonUtil.toJson(message.getLastModifiedMillis()));
    json.add("6", new JsonPrimitive(message.getBlipCount()));
    json.add("7", new JsonPrimitive(message.getUnreadBlipCount()));
    return json;
}

From source file:com.google.walkaround.wave.server.rpc.ContactsHandler.java

License:Open Source License

/**
 * Prints a contact feed as JSON into a servlet response.
 *//*w  w  w .  j a v a 2s  . c o m*/
private void printJson(ContactFeed results, String encodedAddress, HttpServletResponse resp)
        throws IOException {
    // Since the fetch API is index based, this handler must return exactly one
    // result per contact entry. If a contact has 0 email addresses, then an
    // empty contact is returned, since without the email address, the
    // information is useless. If a contact has >1 email addresses, a contact
    // object based on just the first one is returned, due to the
    // exactly-one-result-per-feed-entry constraint.
    JsonArray res = new JsonArray();
    for (ContactEntry e : results.getEntries()) {
        JsonObject contact = new JsonObject();
        List<Email> emails = e.getEmailAddresses();
        if (!emails.isEmpty()) {
            contact.add("a", new JsonPrimitive(emails.get(0).getAddress()));
            contact.add("n", new JsonPrimitive(e.getTitle().getPlainText()));
            contact.add("p", new JsonPrimitive(shortPhotoUrl(encodedAddress, e.getContactPhotoLink())));
        }
        res.add(contact);
    }
    resp.getWriter().print(SharedConstants.XSSI_PREFIX + "(" + res.toString() + ")");
}

From source file:com.google.wave.api.impl.ElementGsonAdaptor.java

License:Apache License

@Override
public JsonElement serialize(Element src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty(TYPE_TAG, src.getType().toString());
    JsonObject properties = new JsonObject();
    if (src.isAttachment()) {
        Attachment attachment = (Attachment) src;
        if (attachment.hasData()) {
            byte[] encodedData = Base64.encodeBase64(attachment.getData());
            try {
                properties.add(Attachment.DATA, new JsonPrimitive(new String(encodedData, "UTF-8")));
            } catch (UnsupportedEncodingException e) {
                // this shouldn't happen, so let it slide.
            }/* w w  w.j  av a 2 s .c  o m*/
        }
    }
    for (Entry<String, String> entry : src.getProperties().entrySet()) {
        // Note: Gson's JsonObject and MapTypeAdapter don't escape the key
        // automatically, so we have to manually escape it here by calling
        // JsonSerializationContext.serialize(). Also, unfortunately, calling
        // JsonPrimitive.toString() wraps the text inside double quotes, that we
        // need to strip out.
        String quotedKey = context.serialize(entry.getKey()).toString();
        String key = quotedKey.substring(1, quotedKey.length() - 1);

        JsonElement value = context.serialize(entry.getValue());
        properties.add(key, value);
    }

    jsonObject.add(PROPERTIES_TAG, properties);
    return jsonObject;
}

From source file:com.googlesource.gerrit.plugins.github.wizard.PullRequestListController.java

License:Apache License

@Override
public void doAction(IdentifiedUser user, GitHubLogin hubLogin, HttpServletRequest req,
        HttpServletResponse resp, ControllerErrors errors) throws ServletException, IOException {
    PrintWriter out = resp.getWriter();

    SimpleDateFormat dateFmt = new SimpleDateFormat(DATE_FMT);
    String organisation = req.getParameter("organisation");
    String repository = req.getParameter("repository");
    Map<String, List<GHPullRequest>> pullRequests = getPullRequests(hubLogin, organisation, repository);

    JsonArray reposPullRequests = new JsonArray();
    for (Entry<String, List<GHPullRequest>> repoEntry : pullRequests.entrySet()) {
        JsonObject repoPullRequests = new JsonObject();

        repoPullRequests.add("repository", new JsonPrimitive(repoEntry.getKey()));

        if (repoEntry.getValue() != null) {
            JsonArray prArray = new JsonArray();
            for (GHPullRequest pr : repoEntry.getValue()) {
                JsonObject prObj = new JsonObject();
                prObj.add("id", new JsonPrimitive(pr.getNumber()));
                prObj.add("title", new JsonPrimitive(pr.getTitle()));
                prObj.add("body", new JsonPrimitive(pr.getBody()));
                prObj.add("author", new JsonPrimitive(pr.getUser() == null ? "" : pr.getUser().getLogin()));
                prObj.add("status", new JsonPrimitive(pr.getState().name()));
                prObj.add("date", new JsonPrimitive(dateFmt.format(pr.getUpdatedAt())));

                prArray.add(prObj);//from   www . j  ava  2 s.  co m
            }
            repoPullRequests.add("pullrequests", prArray);
        }

        reposPullRequests.add(repoPullRequests);
    }
    out.println(reposPullRequests.toString());
}