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:nl.tue.gale.um.data.EntityValue.java

License:Open Source License

@Override
public EntityValue deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    EntityValue ev = new EntityValue();
    JsonObject obj = (JsonObject) json;/*from ww w.ja v a 2s .c o  m*/
    try {
        ev.setUriString(obj.getAsJsonPrimitive("uri").getAsString());
        ev.setValueBytes(Base64.decode(obj.getAsJsonPrimitive("value").getAsString()));
    } catch (Exception e) {
        throw new JsonParseException("unable to deserialize EntityValue: " + json.toString(), e);
    }
    return ev;
}

From source file:org.apache.gobblin.converter.json.JsonStringToJsonIntermediateConverter.java

License:Apache License

/**
 * Parses primitive types//w w w .j a  v  a2 s. c o  m
 * @param schema
 * @param value
 * @return
 * @throws DataConversionException
 */
private JsonElement parsePrimitiveType(JsonSchema schema, JsonElement value) throws DataConversionException {

    if ((schema.isType(NULL) || schema.isNullable()) && value.isJsonNull()) {
        return JsonNull.INSTANCE;
    }

    if ((schema.isType(NULL) && !value.isJsonNull()) || (!schema.isType(NULL) && value.isJsonNull())) {
        throw new DataConversionException(
                "Type mismatch for " + value.toString() + " of type " + schema.getDataTypes().toString());
    }

    if (schema.isType(FIXED)) {
        int expectedSize = schema.getSizeOfFixedData();
        if (value.getAsString().length() == expectedSize) {
            return value;
        } else {
            throw new DataConversionException(
                    "Fixed type value is not same as defined value expected fieldsCount: " + expectedSize);
        }
    } else {
        return value;
    }
}

From source file:org.apache.synapse.mediators.eip.aggregator.AggregateMediator.java

License:Apache License

/**
 * Get the aggregated message from the specified Aggregate instance
 *
 * @param aggregate the Aggregate object that holds collected messages and properties of the
 * aggregation//  ww w. j  ava 2s .c o m
 * @return the aggregated message context
 */
private MessageContext getAggregatedMessage(Aggregate aggregate) {

    MessageContext newCtx = null;
    JsonArray jsonArray = new JsonArray();
    JsonElement result;
    boolean isJSONAggregation = aggregationExpression instanceof SynapseJsonPath ? true : false;

    for (MessageContext synCtx : aggregate.getMessages()) {

        if (newCtx == null) {
            try {
                newCtx = MessageHelper.cloneMessageContextForAggregateMediator(synCtx);
            } catch (AxisFault axisFault) {
                handleException(aggregate, "Error creating a copy of the message", axisFault, synCtx);
            }

            if (log.isDebugEnabled()) {
                log.debug("Generating Aggregated message from : " + newCtx.getEnvelope());
            }
            if (isJSONAggregation) {
                jsonArray.add(EIPUtils.getJSONElement(synCtx, (SynapseJsonPath) aggregationExpression));
            }
        } else {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Merging message : " + synCtx.getEnvelope() + " using XPath : "
                            + aggregationExpression);
                }
                if (isJSONAggregation) {
                    jsonArray.add(EIPUtils.getJSONElement(synCtx, (SynapseJsonPath) aggregationExpression));
                } else {
                    EIPUtils.enrichEnvelope(newCtx.getEnvelope(), synCtx.getEnvelope(), synCtx,
                            (SynapseXPath) aggregationExpression);
                }

                if (log.isDebugEnabled()) {
                    log.debug("Merged result : " + newCtx.getEnvelope());
                }

            } catch (JaxenException e) {
                handleException(aggregate,
                        "Error merging aggregation results using XPath : " + aggregationExpression.toString(),
                        e, synCtx);
            } catch (SynapseException e) {
                handleException(aggregate, "Error evaluating expression: " + aggregationExpression.toString(),
                        e, synCtx);
            }
        }
    }

    // setting json array as the result
    result = jsonArray;

    // Enclose with a parent element if EnclosingElement is defined
    if (enclosingElementPropertyName != null) {

        if (log.isDebugEnabled()) {
            log.debug(
                    "Enclosing the aggregated message with enclosing element: " + enclosingElementPropertyName);
        }

        Object enclosingElementProperty = newCtx.getProperty(enclosingElementPropertyName);

        if (enclosingElementProperty != null) {
            if (enclosingElementProperty instanceof OMElement) {
                OMElement enclosingElement = ((OMElement) enclosingElementProperty).cloneOMElement();
                if (isJSONAggregation) {
                    JsonObject jsonObject = new JsonObject();
                    // Currently using only the root element
                    String key = enclosingElement.getLocalName();
                    jsonObject.add(key, jsonArray);
                    result = jsonObject;
                } else {
                    EIPUtils.encloseWithElement(newCtx.getEnvelope(), enclosingElement);
                }
            } else {
                handleException(aggregate, "Enclosing Element defined in the property: "
                        + enclosingElementPropertyName + " is not an OMElement ", null, newCtx);
            }
        } else {
            handleException(aggregate,
                    "Enclosing Element property: " + enclosingElementPropertyName + " not found ", null,
                    newCtx);
        }
    }

    StatisticDataCollectionHelper.collectAggregatedParents(aggregate.getMessages(), newCtx);
    if (isJSONAggregation) {
        // setting the new JSON payload to the messageContext
        try {
            JsonUtil.getNewJsonPayload(((Axis2MessageContext) newCtx).getAxis2MessageContext(),
                    new ByteArrayInputStream(result.toString().getBytes()), true, true);
        } catch (AxisFault axisFault) {
            log.error("Error occurred while setting the new JSON payload to the msg context", axisFault);
        }
    }
    return newCtx;
}

From source file:org.apache.synapse.mediators.eip.splitter.IterateMediator.java

License:Apache License

/**
 * Splits the message by iterating over the results of the given Path expression
 *
 * @param synCtx - MessageContext to be mediated
 * @return boolean false if need to stop processing of the parent message
 *///from  w  ww.j  a  v a  2s  .  c  o m
public boolean mediate(MessageContext synCtx) {

    if (synCtx.getEnvironment().isDebuggerEnabled()) {
        if (super.divertMediationRoute(synCtx)) {
            return true;
        }
    }

    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Start : Iterate mediator");

        if (synLog.isTraceTraceEnabled()) {
            synLog.traceTrace("Message : " + synCtx.getEnvelope());
        }
    }

    synCtx.setProperty(
            id != null ? EIPConstants.EIP_SHARED_DATA_HOLDER + "." + id : EIPConstants.EIP_SHARED_DATA_HOLDER,
            new SharedDataHolder());

    try {

        // check whether expression contains jsonpath or xpath and process according to it
        if (expression != null && expression instanceof SynapseJsonPath) {

            // SynapseJSONPath implementation reads the JSON stream and execute the JSON path.
            Object resultValue = expression.evaluate(synCtx);

            //Gson parser to parse the string json objects
            JsonParser parser = new JsonParser();

            //Complete json payload read from the synCtx
            Object rootJSON = parser
                    .parse(JsonUtil
                            .jsonPayloadToString(((Axis2MessageContext) synCtx).getAxis2MessageContext()))
                    .toString();

            //delete the iterated json object if the attachPath is different from expression.
            // If both are same, the json object will be replaced eventually, so no need to do it here
            if (!((SynapseJsonPath) expression).getJsonPath().getPath()
                    .equals(((SynapseJsonPath) attachPath).getJsonPath().getPath())) {

                //parse the json into gson to delete the iterated json array
                JsonElement rootJsonElement = parser.parse(rootJSON.toString());

                //Check whether the JSON element expressed by the jsonpath is a valid JsonArray
                //else throw an exception
                if (!(EIPUtils.formatJsonPathResponse(JsonPath.parse(rootJsonElement.toString())
                        .read(((SynapseJsonPath) expression).getJsonPath())) instanceof JsonArray)) {
                    handleException("JSON element expressed by the path "
                            + ((SynapseJsonPath) expression).getJsonPathExpression()
                            + " is not a valid JSON array that can be iterated", synCtx);
                }
                ;

                //replace the expressed jsonElement with an empty array
                rootJSON = JsonPath.parse(rootJsonElement.toString())
                        .set(((SynapseJsonPath) expression).getJsonPath(), new JsonArray()).jsonString();

            }

            if (resultValue instanceof List) {
                List list = (List) resultValue;

                int msgNumber = 0;
                int msgCount = list.size();

                for (Object o : list) {
                    MessageContext iteratedMsgCtx = getIteratedMessage(synCtx, msgNumber++, msgCount, rootJSON,
                            o);
                    ContinuationStackManager.addReliantContinuationState(iteratedMsgCtx, 0,
                            getMediatorPosition());
                    if (target.isAsynchronous()) {
                        target.mediate(iteratedMsgCtx);
                    } else {
                        try {
                            /*
                             * if Iteration is sequential we won't be able to execute correct fault
                             * handler as data are lost with clone message ending execution. So here we
                             * copy fault stack of clone message context to original message context
                             */
                            target.mediate(iteratedMsgCtx);
                        } catch (SynapseException synEx) {
                            copyFaultyIteratedMessage(synCtx, iteratedMsgCtx);
                            throw synEx;
                        } catch (Exception e) {
                            copyFaultyIteratedMessage(synCtx, iteratedMsgCtx);
                            handleException("Exception occurred while executing sequential iteration "
                                    + "in the Iterator Mediator", e, synCtx);
                        }
                    }
                }
            }

        } else {
            // get a copy of the message for the processing, if the continueParent is set to true
            // this original message can go in further mediations and hence we should not change
            // the original message context
            SOAPEnvelope envelope = MessageHelper.cloneSOAPEnvelope(synCtx.getEnvelope());

            // get the iteration elements and iterate through the list,
            // this call will also detach all the iteration elements
            List splitElements = EIPUtils.getDetachedMatchingElements(envelope, synCtx,
                    (SynapseXPath) expression);

            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("Splitting with XPath : " + expression + " resulted in "
                        + splitElements.size() + " elements");
            }

            // if not preservePayload remove all the child elements
            if (!preservePayload && envelope.getBody() != null) {
                for (Iterator itr = envelope.getBody().getChildren(); itr.hasNext();) {
                    ((OMNode) itr.next()).detach();
                }
            }

            int msgCount = splitElements.size();
            int msgNumber = 0;

            // iterate through the list
            for (Object o : splitElements) {

                // for the moment iterator will look for an OMNode as the iteration element
                if (!(o instanceof OMNode)) {
                    handleException(
                            "Error splitting message with XPath : " + expression + " - result not an OMNode",
                            synCtx);
                }

                if (synLog.isTraceOrDebugEnabled()) {
                    synLog.traceOrDebug("Submitting " + (msgNumber + 1) + " of " + msgCount
                            + (target.isAsynchronous() ? " messages for processing in parallel"
                                    : " messages for processing in sequentially"));
                }

                MessageContext iteratedMsgCtx = getIteratedMessage(synCtx, msgNumber++, msgCount, envelope,
                        (OMNode) o);
                ContinuationStackManager.addReliantContinuationState(iteratedMsgCtx, 0, getMediatorPosition());
                if (target.isAsynchronous()) {
                    target.mediate(iteratedMsgCtx);
                } else {
                    try {
                        /*
                         * if Iteration is sequential we won't be able to execute correct fault
                         * handler as data are lost with clone message ending execution. So here we
                         * copy fault stack of clone message context to original message context
                         */
                        target.mediate(iteratedMsgCtx);
                    } catch (SynapseException synEx) {
                        copyFaultyIteratedMessage(synCtx, iteratedMsgCtx);
                        throw synEx;
                    } catch (Exception e) {
                        copyFaultyIteratedMessage(synCtx, iteratedMsgCtx);
                        handleException("Exception occurred while executing sequential iteration "
                                + "in the Iterator Mediator", e, synCtx);
                    }
                }
            }
        }

    } catch (JaxenException e) {
        handleException("Error evaluating split XPath expression : " + expression, e, synCtx);
    } catch (AxisFault af) {
        handleException("Error creating an iterated copy of the message", af, synCtx);
    } catch (SynapseException synEx) {
        throw synEx;
    } catch (Exception e) {
        handleException("Exception occurred while executing the Iterate Mediator", e, synCtx);
    }

    // if the continuation of the parent message is stopped from here set the RESPONSE_WRITTEN
    // property to SKIP to skip the blank http response
    OperationContext opCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext().getOperationContext();
    if (!continueParent && opCtx != null) {
        opCtx.setProperty(Constants.RESPONSE_WRITTEN, "SKIP");
    }

    synLog.traceOrDebug("End : Iterate mediator");

    // whether to continue mediation on the original message
    return continueParent;
}

From source file:org.apache.synapse.mediators.elementary.Target.java

License:Apache License

/**
 * This method will add the sourceNode to location pointed by expression in the jsonString.
 *
 * @param sourceNode JsonElement which needs to be inserted.
 * @param expression Json-path which points the location to be inserted.
 * @param jsonString Target payload as a string.
 * @param parentPath Parent path of expression.
 * @param isSibling to be added as sibling or child.
 * @return formatted string.//from w ww . j  a v a  2  s.  c  o m
 */
private String getNewJSONString(Object sourceNode, String expression, String jsonString, String parentPath,
        boolean isSibling) {
    String newJsonString;
    DocumentContext documentContext = JsonPath.parse(jsonString);
    JsonElement receivingElement = documentContext.read(parentPath);
    JsonElement sourceElement = EIPUtils.tryParseJsonString(jsonParser, sourceNode.toString());
    if (receivingElement.isJsonArray()) {
        receivingElement.getAsJsonArray().add(sourceElement);
    } else {
        log.error("Cannot append since the target element / parent of  target element is not a JSON array: "
                + receivingElement.toString());
    }
    if (isSibling) {
        documentContext.set(parentPath, receivingElement);
    } else {
        documentContext.set(expression, receivingElement);
    }
    newJsonString = documentContext.json().toString();
    return newJsonString;
}

From source file:org.apache.synapse.util.xpath.SynapseJsonPath.java

License:Apache License

/**
 * Replaces first matching item with a given child object.
 * Updated root object will be return back to the caller
 *
 * @param rootObject/*from  w w  w .jav a  2 s. c om*/
 *            Root JSON Object or Array
 * @param newChild
 *            New jsonObject to replace
 * @return Updated Root Object
 */
public Object replace(Object rootObject, Object newChild) {
    if (isWholeBody) {
        rootObject = newChild;

    } else {
        JsonParser parser = new JsonParser();
        JsonElement jsonElement = parser.parse(rootObject.toString());

        Object attachPathObject = null;

        //this try catch block evaluates whether the attachPath is valid and available in the root Object
        try {
            attachPathObject = formatJsonPathResponse(
                    JsonPath.parse(jsonElement.toString()).read(getJsonPath()));

        } catch (PathNotFoundException e) {
            handleException("Unable to get the attach path specified by the expression " + expression, e);
        }

        if (attachPathObject != null) {
            rootObject = JsonPath.parse(jsonElement.toString()).set(expression, newChild).jsonString();

        }

    }
    return rootObject;
}

From source file:org.apache.tika.eval.tokens.AnalyzerDeserializer.java

License:Apache License

private static TokenizerFactory buildTokenizerFactory(JsonElement map, String analyzerName) throws IOException {
    if (!(map instanceof JsonObject)) {
        throw new IllegalArgumentException("Expecting a map with \"factory\" string and "
                + "\"params\" map in tokenizer factory;" + " not: " + map.toString() + " in " + analyzerName);
    }//from   w  w  w. ja v a 2 s  .  c o  m
    JsonElement factoryEl = ((JsonObject) map).get(FACTORY);
    if (factoryEl == null || !factoryEl.isJsonPrimitive()) {
        throw new IllegalArgumentException(
                "Expecting value for factory in char filter factory builder in:" + analyzerName);
    }
    String factoryName = factoryEl.getAsString();
    factoryName = factoryName.startsWith("oala.")
            ? factoryName.replaceFirst("oala.", "org.apache.lucene.analysis.")
            : factoryName;

    JsonElement paramsEl = ((JsonObject) map).get(PARAMS);
    Map<String, String> params = mapify(paramsEl);
    String spiName = "";
    for (String s : TokenizerFactory.availableTokenizers()) {
        Class clazz = TokenizerFactory.lookupClass(s);
        if (clazz.getName().equals(factoryName)) {
            spiName = s;
            break;
        }
    }
    if (spiName.equals("")) {
        throw new IllegalArgumentException(
                "A SPI class of type org.apache.lucene.analysis.util.TokenizerFactory with name" + "'"
                        + factoryName + "' does not exist.");
    }
    try {
        TokenizerFactory tokenizerFactory = TokenizerFactory.forName(spiName, params);
        if (tokenizerFactory instanceof ResourceLoaderAware) {
            ((ResourceLoaderAware) tokenizerFactory)
                    .inform(new ClasspathResourceLoader(AnalyzerDeserializer.class));
        }

        return tokenizerFactory;
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("While working on " + analyzerName, e);
    }
}

From source file:org.apache.tika.eval.tokens.AnalyzerDeserializer.java

License:Apache License

private static CharFilterFactory[] buildCharFilters(JsonElement el, String analyzerName) throws IOException {
    if (el == null || el.isJsonNull()) {
        return null;
    }// w ww  .  j  a v a 2 s. co m
    if (!el.isJsonArray()) {
        throw new IllegalArgumentException(
                "Expecting array for charfilters, but got:" + el.toString() + " for " + analyzerName);
    }
    JsonArray jsonArray = (JsonArray) el;
    List<CharFilterFactory> ret = new LinkedList<CharFilterFactory>();
    for (JsonElement filterMap : jsonArray) {
        if (!(filterMap instanceof JsonObject)) {
            throw new IllegalArgumentException(
                    "Expecting a map with \"factory\" string and \"params\" map in char filter factory;"
                            + " not: " + filterMap.toString() + " in " + analyzerName);
        }
        JsonElement factoryEl = ((JsonObject) filterMap).get(FACTORY);
        if (factoryEl == null || !factoryEl.isJsonPrimitive()) {
            throw new IllegalArgumentException(
                    "Expecting value for factory in char filter factory builder in:" + analyzerName);
        }
        String factoryName = factoryEl.getAsString();
        factoryName = factoryName.replaceAll("oala.", "org.apache.lucene.analysis.");

        JsonElement paramsEl = ((JsonObject) filterMap).get(PARAMS);
        Map<String, String> params = mapify(paramsEl);
        String spiName = "";
        for (String s : CharFilterFactory.availableCharFilters()) {
            Class clazz = CharFilterFactory.lookupClass(s);
            if (clazz.getName().equals(factoryName)) {
                spiName = s;
                break;
            }
        }
        if (spiName.equals("")) {
            throw new IllegalArgumentException(
                    "A SPI class of type org.apache.lucene.analysis.util.CharFilterFactory with name" + "'"
                            + factoryName + "' does not exist.");
        }

        try {
            CharFilterFactory charFilterFactory = CharFilterFactory.forName(spiName, params);
            if (charFilterFactory instanceof ResourceLoaderAware) {
                ((ResourceLoaderAware) charFilterFactory)
                        .inform(new ClasspathResourceLoader(AnalyzerDeserializer.class));
            }
            ret.add(charFilterFactory);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("While trying to load " + analyzerName + ": " + e.getMessage(),
                    e);
        }
    }
    if (ret.size() == 0) {
        return new CharFilterFactory[0];
    }
    return ret.toArray(new CharFilterFactory[ret.size()]);
}

From source file:org.apache.tika.eval.tokens.AnalyzerDeserializer.java

License:Apache License

private static TokenFilterFactory[] buildTokenFilterFactories(JsonElement el, String analyzerName)
        throws IOException {
    if (el == null || el.isJsonNull()) {
        return null;
    }/*from  w  ww.java2s .com*/
    if (!el.isJsonArray()) {
        throw new IllegalArgumentException(
                "Expecting array for tokenfilters, but got:" + el.toString() + " in " + analyzerName);
    }
    JsonArray jsonArray = (JsonArray) el;
    List<TokenFilterFactory> ret = new LinkedList<>();
    for (JsonElement filterMap : jsonArray) {
        if (!(filterMap instanceof JsonObject)) {
            throw new IllegalArgumentException(
                    "Expecting a map with \"factory\" string and \"params\" map in token filter factory;"
                            + " not: " + filterMap.toString() + " in " + analyzerName);
        }
        JsonElement factoryEl = ((JsonObject) filterMap).get(FACTORY);
        if (factoryEl == null || !factoryEl.isJsonPrimitive()) {
            throw new IllegalArgumentException(
                    "Expecting value for factory in token filter factory builder in " + analyzerName);
        }
        String factoryName = factoryEl.getAsString();
        factoryName = factoryName.startsWith("oala.")
                ? factoryName.replaceFirst("oala.", "org.apache.lucene.analysis.")
                : factoryName;

        JsonElement paramsEl = ((JsonObject) filterMap).get(PARAMS);
        Map<String, String> params = mapify(paramsEl);
        String spiName = "";
        for (String s : TokenFilterFactory.availableTokenFilters()) {
            Class clazz = TokenFilterFactory.lookupClass(s);
            if (clazz.getName().equals(factoryName)) {
                spiName = s;
                break;
            }
        }
        if (spiName.equals("")) {
            throw new IllegalArgumentException(
                    "A SPI class of type org.apache.lucene.analysis.util.TokenFilterFactory with name" + "'"
                            + factoryName + "' does not exist.");
        }

        try {
            TokenFilterFactory tokenFilterFactory = TokenFilterFactory.forName(spiName, params);
            if (tokenFilterFactory instanceof ResourceLoaderAware) {
                ((ResourceLoaderAware) tokenFilterFactory)
                        .inform(new ClasspathResourceLoader(AnalyzerDeserializer.class));
            }
            ret.add(tokenFilterFactory);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("While loading " + analyzerName, e);
        }
    }
    if (ret.size() == 0) {
        return new TokenFilterFactory[0];
    }
    return ret.toArray(new TokenFilterFactory[ret.size()]);
}

From source file:org.apache.tika.eval.tokens.AnalyzerDeserializer.java

License:Apache License

private static Map<String, String> mapify(JsonElement paramsEl) {
    if (paramsEl == null || paramsEl.isJsonNull()) {
        return Collections.EMPTY_MAP;
    }//  ww w .  j  av a2 s . c  o  m
    if (!paramsEl.isJsonObject()) {
        throw new IllegalArgumentException("Expecting map, not: " + paramsEl.toString());
    }
    Map<String, String> params = new HashMap<>();
    for (Map.Entry<String, JsonElement> e : ((JsonObject) paramsEl).entrySet()) {
        JsonElement value = e.getValue();
        if (!value.isJsonPrimitive()) {
            throw new IllegalArgumentException(
                    "Expecting parameter to have primitive value: " + value.toString());
        }
        String v = e.getValue().getAsString();
        params.put(e.getKey(), v);
    }
    return params;
}