Example usage for com.google.gson JsonElement toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:com.citrus.sdk.CitrusClient.java

License:Apache License

/**
 * Get the payment bill for the transaction.
 *
 * @param amount   - Transaction amount//from  www.  j  a  v  a 2  s. co  m
 * @param callback
 */
public synchronized void getBill(String billUrl, Amount amount, final Callback<PaymentBill> callback) {
    // Get the bill from the merchant server.

    new GetJSONBill(billUrl, amount, new retrofit.Callback<JsonElement>() {
        @Override
        public void success(JsonElement jsonElement, Response response) {
            Logger.d("GETBILL RESPONSE **" + jsonElement.toString());
            PaymentBill paymentBill = PaymentBill.fromJSON(jsonElement.toString());
            if (paymentBill != null) {
                callback.success(paymentBill);
            } else {
                sendError(callback,
                        new CitrusError(ResponseMessages.ERROR_MESSAGE_INVALID_BILL, Status.FAILED));
            }
        }

        @Override
        public void failure(RetrofitError error) {
            sendError(callback, error);

        }
    }).getJSONBill();

}

From source file:com.citrus.sdk.CitrusClient.java

License:Apache License

public synchronized void getCashoutInfo(final Callback<CashoutInfo> callback) {
    oauthToken.getPrepaidToken(new Callback<AccessToken>() {
        @Override/*w w  w.  j a  v a  2 s. c om*/
        public void success(AccessToken accessToken) {
            retrofitClient.getCashoutInfo(accessToken.getHeaderAccessToken(),
                    new retrofit.Callback<JsonElement>() {
                        @Override
                        public void success(JsonElement jsonElement, Response response) {
                            CashoutInfo cashoutInfo = CashoutInfo.fromJSON(jsonElement.toString());

                            sendResponse(callback, cashoutInfo);
                        }

                        @Override
                        public void failure(RetrofitError error) {
                            sendError(callback, error);
                        }
                    });
        }

        @Override
        public void error(CitrusError error) {
            sendError(callback, error);
        }
    });

}

From source file:com.cloud.stack.CloudStackClient.java

License:Apache License

public JsonAccessor execute(CloudStackCommand cmd, String apiKey, String secretKey) throws Exception {
    JsonParser parser = new JsonParser();
    URL url = new URL(_serviceUrl + cmd.signCommand(apiKey, secretKey));

    if (logger.isDebugEnabled())
        logger.debug("Cloud API call + [" + url.toString() + "]");

    URLConnection connect = url.openConnection();

    int statusCode;
    statusCode = ((HttpURLConnection) connect).getResponseCode();
    if (statusCode >= 400) {
        logger.error("Cloud API call + [" + url.toString() + "] failed with status code: " + statusCode);
        String errorMessage = ((HttpURLConnection) connect).getResponseMessage();
        if (errorMessage == null) {
            errorMessage = connect.getHeaderField("X-Description");
        }// w ww.  j  a  v  a  2s . c om

        if (errorMessage == null) {
            errorMessage = "CloudStack API call HTTP response error, HTTP status code: " + statusCode;
        }

        throw new IOException(errorMessage);
    }

    InputStream inputStream = connect.getInputStream();
    JsonElement jsonElement = parser.parse(new InputStreamReader(inputStream));
    if (jsonElement == null) {
        logger.error(
                "Cloud API call + [" + url.toString() + "] failed: unable to parse expected JSON response");

        throw new IOException("CloudStack API call error : invalid JSON response");
    }

    if (logger.isDebugEnabled())
        logger.debug("Cloud API call + [" + url.toString() + "] returned: " + jsonElement.toString());
    return new JsonAccessor(jsonElement);
}

From source file:com.collaide.fileuploader.requests.notifications.RepoItemsNotificationRequest.java

public void notificationWithListener(int userId, long timestamp, RepoItemListener[] listeners) {
    for (JsonElement notificationElement : getJsonNotifications(userId, timestamp)) {
        try {/*from   w w w . ja v a  2s.co m*/
            Class notification = getClassFromString(
                    notificationElement.getAsJsonObject().get("type").getAsString());
            for (RepoItemListener listener : listeners) {
                new CallListenerMethodThread(notification, listener, notificationElement.toString()).start();
            }
        } catch (ClassNotFoundException ex) {
            logger.error("Notification cannot be found: " + ex);
        }
    }
}

From source file:com.collaide.fileuploader.requests.notifications.RepoItemsNotificationRequest.java

/**
 * <br/>//  www.ja va2  s.c o m
 * get the notifications between the time passed in params and now
 *
 * @param userId
 * @param timestamp
 * @return
 */
public NotificationsMap getNotifications(int userId, long timestamp) {
    NotificationsMap notificationsMap = new NotificationsMap();
    for (JsonElement notificationElement : getJsonNotifications(userId, timestamp)) {
        try {
            Class notification = getClassFromString(
                    notificationElement.getAsJsonObject().get("type").getAsString());
            logger.debug("json: " + notificationElement.toString());
            notificationsMap.addNotification(Model.getJson(notification, notificationElement.toString()));
        } catch (ClassNotFoundException ex) {
            logger.error("Notification cannot be found: " + ex);
            return null;
        }
    }
    return notificationsMap;
}

From source file:com.compose.nifi.processors.ComposeBatchPutMongo.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;//  www.  ja va 2  s. co m
    }

    final Charset charset = Charset.forName(context.getProperty(CHARACTER_SET).getValue());
    final String collectionName = context.getProperty(COLLECTION_NAME).getValue();
    final WriteConcern writeConcern = mongoWrapper.getWriteConcern(context);

    final MongoCollection<Document> collection = mongoWrapper.getDatabase(context).getCollection(collectionName)
            .withWriteConcern(writeConcern);

    try {
        // Read the contents of the FlowFile into a byte array
        final byte[] content = new byte[(int) flowFile.getSize()];
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(final InputStream in) throws IOException {
                StreamUtils.fillBuffer(in, content, true);
            }
        });

        //Hack away :)
        ArrayList<Document> docs = new ArrayList<>();
        JsonParser parser = new JsonParser();
        JsonArray array = parser.parse(new String(content, charset)).getAsJsonArray();
        for (JsonElement element : array) {
            //Terrible. surely a better way. learn more.
            Document doc = Document.parse(element.toString());
            docs.add(doc);
        }

        collection.insertMany(docs);

        session.getProvenanceReporter().send(flowFile, mongoWrapper.getURI(context));
        session.transfer(flowFile, REL_SUCCESS);
    } catch (Exception e) {
        getLogger().error("Failed to insert {} into MongoDB due to {}", new Object[] { flowFile, e }, e);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}

From source file:com.continuuity.weave.internal.json.JsonUtils.java

License:Apache License

/**
 * Returns a String representation of the given property.
 *//* w ww .  j a va 2 s .c o m*/
public static String getAsString(JsonObject json, String property) {
    JsonElement jsonElement = json.get(property);
    if (jsonElement.isJsonNull()) {
        return null;
    }
    if (jsonElement.isJsonPrimitive()) {
        return jsonElement.getAsString();
    }
    return jsonElement.toString();
}

From source file:com.couchbase.plugin.basement.api.Client.java

License:Open Source License

private void addJsonElement(String key, JsonElement value, HashMap<String, Object> map) {

    if (value.isJsonArray()) {
        JsonArray jsonArray = value.getAsJsonArray();

        ArrayList listAsValue = new ArrayList<HashMap<String, Object>>();

        HashMap<String, Object> listElementMap = new HashMap<String, Object>();

        Iterator<JsonElement> jsonArrayIterator = jsonArray.iterator();
        while (jsonArrayIterator.hasNext()) {
            JsonElement jsonElement = jsonArrayIterator.next();

            listAsValue.add(parse(jsonElement.toString()));

        }/*from   w  w w  .  j a v a2 s.c om*/

        map.put(key, listAsValue);

    } else if (value.isJsonPrimitive()) {
        // check the type using JsonPrimitive
        // TODO: check all types
        JsonPrimitive jsonPrimitive = value.getAsJsonPrimitive();
        if (jsonPrimitive.isNumber()) {
            map.put(key, jsonPrimitive.getAsInt());
        } else {
            map.put(key, jsonPrimitive.getAsString());
        }
    } else {
        map.put(key, parse(value.toString()));
    }

}

From source file:com.crypticbit.diff.demo.swing.contacts.JsonJTreeNode.java

License:Apache License

/**
 * @param fieldName/*from  w w w  . j a  v a  2 s.com*/
 *            - name of field if applicable or null
 * @param index
 *            - index of element in the array or -1 if not part of an array
 * @param jsonElement
 *            - element to represent
 */
public JsonJTreeNode(String fieldName, int index, JsonElement jsonElement) {
    this.index = index;
    this.fieldName = fieldName;
    if (jsonElement.isJsonArray()) {
        this.dataType = DataType.ARRAY;
        this.value = jsonElement.toString();
        populateChildren(jsonElement);
    } else if (jsonElement.isJsonObject()) {
        this.dataType = DataType.OBJECT;
        this.value = jsonElement.toString();
        populateChildren(jsonElement);
    } else if (jsonElement.isJsonPrimitive()) {
        this.dataType = DataType.VALUE;
        this.value = jsonElement.toString();
    } else if (jsonElement.isJsonNull()) {
        this.dataType = DataType.VALUE;
        this.value = jsonElement.toString();
    } else {
        throw new IllegalArgumentException("jsonElement is an unknown element type.");
    }

}

From source file:com.crypticbit.diff.demo.swing.contacts.JsonJTreeNode.java

License:Apache License

@SuppressWarnings("unchecked")
private void buildJsonString(StringBuilder sb) {
    if (!(this.fieldName == null || this.fieldName.length() == 0)) {
        sb.append("\"" + this.fieldName + "\":");
    }/*ww w  .  j  ava  2 s . co  m*/
    Enumeration children;
    switch (dataType) {
    case ARRAY:
        sb.append("[");
        children = this.children();
        while (children.hasMoreElements()) {
            JsonJTreeNode child = (JsonJTreeNode) children.nextElement();
            child.buildJsonString(sb);
            if (children.hasMoreElements()) {
                sb.append(",");
            }
        }
        sb.append("]");
        break;
    case OBJECT:
        sb.append("{");
        children = this.children();
        while (children.hasMoreElements()) {
            JsonJTreeNode child = (JsonJTreeNode) children.nextElement();
            child.buildJsonString(sb);
            if (children.hasMoreElements()) {
                sb.append(",");
            }
        }
        sb.append("}");
        break;
    default: {
        // Use the JSON parser to parse the value for safety
        JsonElement elt = new JsonParser().parse(this.value);
        sb.append(elt.toString());
    }
    }
}