Example usage for com.google.gson JsonElement getAsString

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

Introduction

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

Prototype

public String getAsString() 

Source Link

Document

convenience method to get this element as a string value.

Usage

From source file:com.ibm.mqlight.api.impl.endpoint.BluemixEndpointService.java

License:Apache License

protected void doHttpLookup(final String httpUri, final EndpointPromise future) {
    final String methodName = "doHttpLookup";
    logger.entry(this, methodName, httpUri, future);

    synchronized (this) {
        if (executor == null) {
            executor = new ThreadPoolExecutor(THREAD_POOL_CORE_THREADS, THREAD_POOL_MAX_THREADS,
                    THREAD_POOL_KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
                    new BluemixThreadFactory());
        }//from www  . j av  a  2s . c  om
    }

    executor.execute(new Runnable() {
        public void run() {
            final String methodName = "run";
            logger.entry(this, methodName);

            try {
                String serviceJson = hitUri(httpUri);

                JsonParser parser = new JsonParser();
                JsonObject root = parser.parse(serviceJson).getAsJsonObject();
                JsonArray services = root.get("service").getAsJsonArray();
                Endpoint endpoint = null;
                synchronized (this) {
                    state.endpoints = new LinkedList<>();
                    for (JsonElement serviceElement : services) {
                        String uri = serviceElement.getAsString();
                        state.endpoints.add(new EndpointImpl(uri, state.user, state.password));
                    }

                    if (state.endpoints.isEmpty()) {
                        state.endpoints = null;
                        state.nextEndpointIndex = 0;
                    } else {
                        endpoint = state.endpoints.get(0);
                        state.nextEndpointIndex = 1;
                    }
                }

                if (endpoint == null) {
                    doRetry(future);
                } else {
                    future.setSuccess(endpoint);
                }
            } catch (IOException ioException) {
                logger.data(this, methodName, "will retry due to java.io.IOException exception",
                        ioException.getLocalizedMessage());
                // Retry later...
                doRetry(future);
            } catch (JsonParseException parseException) {
                final ClientException exception = new ClientException(
                        "Could not parse the JSON returned by the IBM MQ Light Bluemix lookup service.  See linked exception for more information",
                        parseException);
                logger.data(this, methodName, exception);
                future.setFailure(exception);
            } catch (IllegalArgumentException iae) {
                final ClientException exception = new ClientException(
                        "Endpoint information returned by IBM MQ Light Bluemix lookup service was not valid.  See linked exception for more information",
                        iae);
                logger.data(this, methodName, exception);
                future.setFailure(exception);
            }

            logger.exit(this, methodName);
        }
    });

    logger.exit(this, methodName);
}

From source file:com.ibm.streamsx.rest.StreamingAnalyticsConnectionV2.java

License:Open Source License

/**
 * Cancels a job that has been submitted to IBM Streaming Analytics service
 *
 * @param instanceId//from w w w .  j a  va2s.  c  om
 *            string indicating the instance id of the job
 * @param jobId
 *            string indicating the job id to be canceled
 * @return boolean indicating
 *         <ul>
 *         <li>true - if job is cancelled</li>
 *         <li>false - if the job still exists</li>
 *         </ul>
 * @throws IOException
 */
@Override
boolean cancelJob(Instance instance, String jobId) throws IOException {
    if (null == jobsUrl) {
        String restUrl = jstring(credentials, "v2_rest_url");
        JsonObject response = StreamsRestUtils.getGsonResponse(executor, getAuthorization(), restUrl);
        JsonElement element = response.get("jobs");
        if (null != element) {
            jobsUrl = element.getAsString();
        } else {
            throw new RESTException("Unable to get jobs URL");
        }
    }

    return delete(jobsUrl + "/" + jobId);
}

From source file:com.ibm.streamsx.rest.StreamsRestUtils.java

License:Open Source License

/**
 * Get a member that is expected to exist and be non-null.
 * @param json The JSON object/* w  w w .j av a  2 s.com*/
 * @param member The member name in the object.
 * @return The string value of the member.
 * @throws IllegalStateException if the member does not exist or is null.
 */
static String getRequiredMember(JsonObject json, String member) throws IllegalStateException {
    JsonElement element = json.get(member);
    if (null == element || element.isJsonNull()) {
        throw new IllegalStateException("JSON missing required member " + member);
    }
    return element.getAsString();
}

From source file:com.ibm.streamsx.topology.generator.spl.GraphUtilities.java

License:Open Source License

static void removeOperators(Collection<JsonObject> operators, JsonObject graph) {
    for (JsonObject iso : operators) {

        // Get parents and children of operator
        Set<JsonObject> operatorParents = getUpstream(iso, graph);
        Set<JsonObject> operatorChildren = getDownstream(iso, graph);

        JsonArray operatorOutputs = array(iso, "outputs");

        // Get the output name of the operator
        String operatorOutName = "";
        if (operatorOutputs != null) {
            JsonObject operatorFirstOutput = operatorOutputs.get(0).getAsJsonObject();
            if (operatorFirstOutput != null) {
                operatorOutName = jstring(operatorFirstOutput, "name");
            }/* w  w w. j  a va 2 s. co m*/
        }

        // Also get input names
        List<String> operatorInNames = new ArrayList<>();
        inputs(iso, input -> operatorInNames.add(jstring(input, "name")));

        // Respectively, the names of the child and parent input and
        // output ports connected to the operator.
        List<String> childInputPortNames = new ArrayList<>();
        List<String> parentOutputPortNames = new ArrayList<>();

        // References to the list of connections for the parent and child
        // output and input ports that are connected to the $isolate$
        // operator.
        List<JsonArray> childConnections = new ArrayList<>();
        List<JsonArray> parentConnections = new ArrayList<>();

        // Get names of children's input ports that are connected to the
        // operator;
        for (JsonObject child : operatorChildren) {
            JsonArray inputs = child.get("inputs").getAsJsonArray();
            for (JsonElement inputObj : inputs) {
                JsonObject input = inputObj.getAsJsonObject();
                JsonArray connections = input.get("connections").getAsJsonArray();
                for (JsonElement connectionObj : connections) {
                    String connection = connectionObj.getAsString();
                    if (connection.equals(operatorOutName)) {
                        childInputPortNames.add(jstring(input, "name"));
                        childConnections.add(connections);
                        connections.remove(connectionObj);
                        break;
                    }
                }
            }
        }

        // Get names of parent's output ports that are connected to the
        // $Isolate$ operator;
        for (JsonObject parent : operatorParents) {
            JsonArray outputs = parent.get("outputs").getAsJsonArray();
            for (JsonElement outputObj : outputs) {
                JsonObject output = outputObj.getAsJsonObject();
                JsonArray connections = output.get("connections").getAsJsonArray();
                for (JsonElement connectionObj : connections) {
                    String connection = connectionObj.getAsString();
                    if (operatorInNames.contains(connection)) {
                        parentOutputPortNames.add(jstring(output, "name"));
                        parentConnections.add(connections);
                        connections.remove(connectionObj);
                        break;
                    }
                }
            }
        }

        // Connect child to parents
        for (JsonArray childConnection : childConnections) {
            for (String name : parentOutputPortNames)
                childConnection.add(new JsonPrimitive(name));
        }

        // Connect parent to children
        for (JsonArray parentConnection : parentConnections) {
            for (String name : childInputPortNames)
                parentConnection.add(new JsonPrimitive(name));
        }
        JsonArray ops = graph.get("operators").getAsJsonArray();
        ops.remove(iso);
    }
}

From source file:com.ibm.streamsx.topology.generator.spl.GraphUtilities.java

License:Open Source License

static void insertOperatorBetweenPorts(JsonObject input, JsonObject output, JsonObject op) {
    String oportName = jstring(output, "name");
    String iportName = jstring(input, "name");

    JsonObject opInput = op.get("inputs").getAsJsonArray().get(0).getAsJsonObject();
    JsonObject opOutput = op.get("outputs").getAsJsonArray().get(0).getAsJsonObject();

    String opIportName = jstring(opInput, "name");
    String opOportName = jstring(opOutput, "name");

    // Attach op in inputs and outputs
    JsonArray opInputConns = opInput.get("connections").getAsJsonArray();
    JsonArray opOutputConns = opOutput.get("connections").getAsJsonArray();
    boolean add = true;
    for (JsonElement conn : opInputConns)
        if (conn.getAsString().equals(oportName)) {
            add = false;//from   w ww.j a v a  2s. c  o m
            break;
        }
    if (add)
        opInputConns.add(new JsonPrimitive(oportName));

    add = true;
    for (JsonElement conn : opOutputConns)
        if (conn.getAsString().equals(iportName)) {
            add = false;
            break;
        }
    opOutputConns.add(new JsonPrimitive(iportName));

    JsonArray outputConns = output.get("connections").getAsJsonArray();
    JsonArray inputConns = input.get("connections").getAsJsonArray();

    for (int i = 0; i < outputConns.size(); i++) {
        if (outputConns.get(i).getAsString().equals(iportName))
            outputConns.set(i, new JsonPrimitive(opIportName));
    }

    for (int i = 0; i < inputConns.size(); i++) {
        if (inputConns.get(i).getAsString().equals(oportName))
            inputConns.set(i, new JsonPrimitive(opOportName));
    }
}

From source file:com.ibm.streamsx.topology.generator.spl.OperatorGenerator.java

License:Open Source License

private void parallelAnnotation(JsonObject op, StringBuilder sb) {
    boolean parallel = jboolean(op, "parallelOperator");

    if (parallel) {
        boolean partitioned = jboolean(op, "partitioned");
        JsonObject parallelInfo = op.get("parallelInfo").getAsJsonObject();

        sb.append("@parallel(width=");
        JsonElement width = parallelInfo.get(OpProperties.WIDTH);
        if (width.isJsonPrimitive()) {
            sb.append(width.getAsString());
        } else {//from  w w w.  j a  va  2  s .  co m
            splValueSupportingSubmission(width.getAsJsonObject(), sb);
        }

        if (partitioned) {
            sb.append(", partitionBy=[");
            JsonArray partitionedPorts = array(parallelInfo, "partitionedPorts");
            for (int i = 0; i < partitionedPorts.size(); i++) {
                JsonObject partitionedPort = partitionedPorts.get(i).getAsJsonObject();

                if (i > 0)
                    sb.append(", ");

                sb.append("{port=");
                sb.append(getSPLCompatibleName(GsonUtilities.jstring(partitionedPort, "name")));
                sb.append(", attributes=[");
                JsonArray partitionKeys = partitionedPort.get("partitionedKeys").getAsJsonArray();
                for (int j = 0; j < partitionKeys.size(); j++) {
                    if (j != 0)
                        sb.append(", ");
                    sb.append(partitionKeys.get(j).getAsString());
                }
                sb.append("]}");
            }

            sb.append("]");
        }

        JsonArray broadcastPorts = parallelInfo.get("broadcastPorts").getAsJsonArray();
        if (broadcastPorts.size() > 0) {
            sb.append(", broadcast=[");
            for (int i = 0; i < broadcastPorts.size(); i++) {
                if (i != 0)
                    sb.append(", ");
                sb.append(getSPLCompatibleName(broadcastPorts.get(i).getAsString()));
            }
            sb.append("]");

        }

        sb.append(")");
        sb.append("\n");
    }
}

From source file:com.ibm.streamsx.topology.generator.spl.OperatorGenerator.java

License:Open Source License

private void splValueSupportingSubmission(JsonObject value, StringBuilder sb) {

    JsonElement type = value.get("type");
    if (value.has("type") && TYPE_SUBMISSION_PARAMETER.equals(type.getAsString())) {
        value = stvHelper.getSPLExpression(value);
    }//from   ww w .j  a v a  2 s . c om

    SPLGenerator.value(sb, value);
}

From source file:com.ibm.streamsx.topology.generator.spl.OperatorGenerator.java

License:Open Source License

/**
 * Gets or creates a host pool at the graphConfig level corresponding to the
 * unique set of tags.//from   w  w w. j a  va2s . com
 */
private static String getHostPoolName(JsonObject graphConfig, Set<String> uniqueResourceTags) {
    JsonArray hostPools = array(graphConfig, "__spl_hostPools");
    if (hostPools == null) {
        graphConfig.add("__spl_hostPools", hostPools = new JsonArray());
    }

    // Look for a host pool matching this one
    for (JsonElement hpe : hostPools) {
        JsonObject hostPoolDef = hpe.getAsJsonObject();
        JsonArray rta = hostPoolDef.get("resourceTags").getAsJsonArray();
        Set<String> poolResourceTags = new HashSet<>();
        for (JsonElement tage : rta)
            poolResourceTags.add(tage.getAsString());
        if (uniqueResourceTags.equals(poolResourceTags)) {
            return jstring(hostPoolDef, "name");
        }
    }

    JsonObject hostPoolDef = new JsonObject();
    String hostPool;
    hostPoolDef.addProperty("name", hostPool = "__jaaHostPool" + hostPools.size());
    JsonArray rta = new JsonArray();
    for (String tag : uniqueResourceTags)
        rta.add(new JsonPrimitive(tag));
    hostPoolDef.add("resourceTags", rta);
    hostPools.add(hostPoolDef);
    return hostPool;
}

From source file:com.ibm.streamsx.topology.generator.spl.SPLGenerator.java

License:Open Source License

/**
 * When we create a composite, operators need to create connections with the composite's output port.
 * @param graph//  w w  w  .  j a  v a2 s . c  o m
 * @param startsEndsAndOperators
 * @param opDefinition
 */
private void fixCompositeOutputNaming(JsonObject graph, List<List<JsonObject>> startsEndsAndOperators,
        JsonObject opDefinition, JsonObject opInvocation) {
    // We iterate like this because we need the index into the operatorDefinition's inputNames list.
    for (int[] i = { 0 }; i[0] < startsEndsAndOperators.get(1).size(); i[0]++) {
        JsonObject end = startsEndsAndOperators.get(1).get(i[0]);

        // Region markers like $Parallel$ only have one input and output
        String inputPortName = GsonUtilities
                .jstring(end.get("inputs").getAsJsonArray().get(0).getAsJsonObject(), "name");

        for (JsonObject parent : getUpstream(end, graph)) {
            String endType = jstring(array(end, "outputs").get(0).getAsJsonObject(), "type");
            array(opInvocation, "outputs").get(i[0]).getAsJsonObject().addProperty("type", endType);

            GraphUtilities.outputs(parent, output -> {
                JsonArray conns = array(output, "connections");
                for (JsonElement conn : conns) {
                    String sconn = conn.getAsString();
                    if (sconn.equals(inputPortName)) {
                        output.addProperty("name",
                                GsonUtilities.array(opDefinition, "outputNames").get(i[0]).getAsString());
                    }
                }
            });
        }

    }
}

From source file:com.ibm.streamsx.topology.generator.spl.SPLGenerator.java

License:Open Source License

void generateComposite(JsonObject graphConfig, JsonObject graph, StringBuilder compBuilder) throws IOException {
    boolean isPublic = jboolean(graph, "public");
    String kind = jstring(graph, KIND);
    kind = getSPLCompatibleName(kind);/*from  w  ww  . j  a v a  2s.c o  m*/
    if (isPublic)
        compBuilder.append("public ");

    compBuilder.append("composite ");

    compBuilder.append(kind);
    if (jboolean(graph, "generated")) {
        JsonArray inputNames = array(graph, "inputNames");
        JsonArray outputNames = array(graph, "outputNames");
        compBuilder.append("(");
        if (inputNames != null && inputNames.size() > 0) {
            compBuilder.append("input ");
            boolean first = true;
            for (JsonElement inputName : inputNames) {
                if (!first)
                    compBuilder.append(",");
                String strInputName = getSPLCompatibleName(inputName.getAsString());
                compBuilder.append(strInputName);
                first = false;
            }

        }

        if (outputNames != null && outputNames.size() > 0) {
            if (inputNames != null && inputNames.size() > 0)
                compBuilder.append(";");
            compBuilder.append("output ");
            boolean first = true;
            for (JsonElement outputName : outputNames) {
                if (!first)
                    compBuilder.append(",");
                String strOutputName = getSPLCompatibleName(outputName.getAsString());
                compBuilder.append(strOutputName);
                first = false;
            }

        }

        compBuilder.append(")");

    }
    compBuilder.append("\n{\n");

    generateCompParams(graph, compBuilder);

    compBuilder.append("graph\n");
    operators(graphConfig, graph, compBuilder);

    generateCompConfig(graph, graphConfig, compBuilder);

    compBuilder.append("}\n");
}