Example usage for javax.json JsonObject get

List of usage examples for javax.json JsonObject get

Introduction

In this page you can find the example usage for javax.json JsonObject get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:org.hyperledger.fabric.sdk.NetworkConfig.java

private Channel reconstructChannel(HFClient client, String channelName, JsonObject jsonChannel)
        throws NetworkConfigurationException {

    Channel channel = null;/*from   ww  w.  java2s.c  o m*/

    try {
        channel = client.newChannel(channelName);

        // orderers is an array of orderer name strings
        JsonArray ordererNames = getJsonValueAsArray(jsonChannel.get("orderers"));
        boolean foundOrderer = false;

        //out("Orderer names: " + (ordererNames == null ? "null" : ordererNames.toString()));
        if (ordererNames != null) {
            for (JsonValue jsonVal : ordererNames) {

                String ordererName = getJsonValueAsString(jsonVal);
                Orderer orderer = getOrderer(client, ordererName);
                if (orderer == null) {
                    throw new NetworkConfigurationException(
                            format("Error constructing channel %s. Orderer %s not defined in configuration",
                                    channelName, ordererName));
                }
                channel.addOrderer(orderer);
                foundOrderer = true;
            }
        }

        // peers is an object containing a nested object for each peer
        JsonObject jsonPeers = getJsonObject(jsonChannel, "peers");
        boolean foundPeer = false;

        //out("Peers: " + (peers == null ? "null" : peers.toString()));
        if (jsonPeers != null) {

            for (Entry<String, JsonValue> entry : jsonPeers.entrySet()) {
                String peerName = entry.getKey();

                if (logger.isTraceEnabled()) {
                    logger.trace(format("NetworkConfig.reconstructChannel: Processing peer %s", peerName));
                }

                JsonObject jsonPeer = getJsonValueAsObject(entry.getValue());
                if (jsonPeer == null) {
                    throw new NetworkConfigurationException(format(
                            "Error constructing channel %s. Invalid peer entry: %s", channelName, peerName));
                }

                Peer peer = getPeer(client, peerName);
                if (peer == null) {
                    throw new NetworkConfigurationException(
                            format("Error constructing channel %s. Peer %s not defined in configuration",
                                    channelName, peerName));
                }

                // Set the various roles
                PeerOptions peerOptions = PeerOptions.createPeerOptions();

                for (PeerRole peerRole : PeerRole.values()) {
                    setPeerRole(channelName, peerOptions, jsonPeer, peerRole);
                }

                foundPeer = true;

                // Add the event hub associated with this peer
                EventHub eventHub = getEventHub(client, peerName);
                if (eventHub != null) {
                    channel.addEventHub(eventHub);
                    if (peerOptions.peerRoles == null) { // means no roles were found but there is an event hub so define all roles but eventing.
                        peerOptions.setPeerRoles(EnumSet.of(PeerRole.ENDORSING_PEER, PeerRole.CHAINCODE_QUERY,
                                PeerRole.LEDGER_QUERY));
                    }
                }
                channel.addPeer(peer, peerOptions);

            }

        }

        if (!foundPeer) {
            // peers is a required field
            throw new NetworkConfigurationException(
                    format("Error constructing channel %s. At least one peer must be specified", channelName));
        }

    } catch (InvalidArgumentException e) {
        throw new IllegalArgumentException(e);
    }

    return channel;
}

From source file:nl.nn.adapterframework.align.Json2Xml.java

@Override
public void startParse(JsonValue node) throws SAXException {
    if (node instanceof JsonObject) {
        JsonObject root = (JsonObject) node;
        if (StringUtils.isEmpty(getRootElement())) {
            if (root.isEmpty()) {
                throw new SAXException("no names found");
            }//www. java2 s .  com
            if (root.size() > 1) {
                String namesList = null;
                int i = 0;
                for (String name : root.keySet()) {
                    if (namesList == null) {
                        namesList = name;
                    } else {
                        namesList += "," + name;
                    }
                    if (i++ > 5) {
                        namesList += ", ...";
                        break;
                    }
                }
                throw new SAXException("too many names [" + namesList + "]");
            }
            setRootElement((String) root.keySet().toArray()[0]);
        }
        // determine somewhat heuristically whether the json contains a 'root' node:
        // if the outermost JsonObject contains only one key, that has the name of the root element, 
        // then we'll assume that that is the root element...
        if (root.size() == 1 && getRootElement().equals(root.keySet().toArray()[0])) {
            node = root.get(getRootElement());
        }
    }
    if (node instanceof JsonArray && !insertElementContainerElements && strictSyntax) {
        throw new SAXException(
                MSG_EXPECTED_SINGLE_ELEMENT + " [" + getRootElement() + "] or array element container");
    }
    super.startParse(node);
}

From source file:de.tu_dortmund.ub.data.dswarm.Task.java

@Override
public String call() {

    // init logger
    PropertyConfigurator.configure(config.getProperty("service.log4j-conf"));

    logger.info("[" + config.getProperty("service.name") + "] " + "Starting 'Task' ...");

    // init IDs of the prototype project
    String dataModelID = config.getProperty("prototype.dataModelID");
    String projectID = config.getProperty("prototype.projectID");
    String outputDataModelID = config.getProperty("prototype.outputDataModelID");

    // init process values
    String inputResourceID = null;
    String message = null;//from ww w  .  j  a  v a  2  s  .  c o  m

    try {

        // get the resource id of the current data model >> updateResourceID replaces resourceID
        String updateResourceID = null;
        try {
            updateResourceID = getProjectResourceID(dataModelID);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        logger.info("[" + config.getProperty("service.name") + "] updateResourceID = " + updateResourceID);

        // upload resource and update a InputDataModel
        String inputResourceJson = uploadFileAndUpdateResource(updateResourceID, resource,
                "resource for project '" + resource, config.getProperty("project.name") + "' - case " + cnt);
        JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(inputResourceJson, "UTF-8"));
        inputResourceID = jsonReader.readObject().getString("uuid");
        logger.info("[" + config.getProperty("service.name") + "] inputResourceID = " + inputResourceID);

        if (updateResourceID != null) {

            // update the datamodel (will use it's (update) resource)
            updateDataModel(dataModelID);

            // configuration and processing of the task
            String jsonResponse = executeTask(dataModelID, projectID, outputDataModelID);

            if (jsonResponse != null) {

                if (Boolean.parseBoolean(config.getProperty("results.persistInFolder"))) {

                    if (Boolean.parseBoolean(config.getProperty("results.writeDMPJson"))) {
                        // save DMP results in files
                        FileUtils.writeStringToFile(new File(config.getProperty("results.folder")
                                + File.separatorChar + dataModelID + "." + cnt + ".json"), jsonResponse);
                    }

                    // build rdf graph
                    ValueFactory factory = ValueFactoryImpl.getInstance();

                    Graph graph = new LinkedHashModel();

                    URI graphUri = factory.createURI(config.getProperty("results.rdf.graph"));

                    URI subject = null;
                    URI predicate = null;
                    URI object = null;
                    Literal literal = null;
                    Statement statement = null;

                    JsonReader dmpJsonResult = Json.createReader(IOUtils.toInputStream(jsonResponse, "UTF-8"));
                    JsonArray records = dmpJsonResult.readArray();

                    for (JsonObject record : records.getValuesAs(JsonObject.class)) {

                        subject = factory
                                .createURI(record.getJsonString("__record_id").toString().replaceAll("\"", ""));

                        for (JsonObject triple : record.getJsonArray("__record_data")
                                .getValuesAs(JsonObject.class)) {

                            for (String key : triple.keySet()) {

                                if (key.endsWith("rdf-syntax-ns#type")) {
                                    predicate = RDF.TYPE;
                                    object = factory.createURI(
                                            triple.getJsonString(key).toString().replaceAll("\"", ""));
                                    statement = factory.createStatement(subject, predicate, object, graphUri);
                                    graph.add(statement);
                                } else {

                                    predicate = factory.createURI(key);

                                    switch (triple.get(key).getValueType().toString()) {

                                    case "STRING": {

                                        try {
                                            object = factory.createURI(
                                                    triple.getJsonString(key).toString().replaceAll("\"", ""));
                                            statement = factory.createStatement(subject, predicate, object,
                                                    graphUri);
                                            graph.add(statement);
                                        } catch (Exception e) {
                                            literal = factory.createLiteral(
                                                    triple.getJsonString(key).toString().replaceAll("\"", ""));
                                            statement = factory.createStatement(subject, predicate, literal,
                                                    graphUri);
                                            graph.add(statement);
                                        }
                                        break;
                                    }
                                    case "ARRAY": {

                                        for (JsonString value : triple.getJsonArray(key)
                                                .getValuesAs(JsonString.class)) {

                                            try {
                                                object = factory
                                                        .createURI(value.toString().replaceAll("\"", ""));
                                                statement = factory.createStatement(subject, predicate, object,
                                                        graphUri);
                                                graph.add(statement);
                                            } catch (Exception e) {
                                                literal = factory
                                                        .createLiteral(value.toString().replaceAll("\"", ""));
                                                statement = factory.createStatement(subject, predicate, literal,
                                                        graphUri);
                                                graph.add(statement);
                                            }
                                        }
                                        break;
                                    }
                                    default: {

                                        logger.info("Unhandled ValueType: " + triple.get(key).getValueType());
                                    }
                                    }
                                }
                            }
                        }
                    }

                    if (graph.size() > 0) {
                        // save rdf data as 'results.rdf.format' in 'results.folder'
                        RDFFormat format = null;
                        switch (config.getProperty("results.rdf.format")) {

                        case "xml": {

                            format = RDFFormat.RDFXML;
                            break;
                        }
                        case "nquads": {

                            format = RDFFormat.NQUADS;
                            break;
                        }
                        case "jsonld": {

                            format = RDFFormat.JSONLD;
                            break;
                        }
                        case "ttl": {

                            format = RDFFormat.TURTLE;
                            break;
                        }
                        default: {

                            format = RDFFormat.RDFXML;
                        }
                        }

                        try {
                            FileOutputStream out = new FileOutputStream(
                                    config.getProperty("results.folder") + File.separatorChar + dataModelID
                                            + "." + cnt + ".rdf." + config.getProperty("results.rdf.format"));
                            RDFWriter writer = Rio.createWriter(format, out);

                            writer.startRDF();
                            for (Statement st : graph) {
                                writer.handleStatement(st);
                            }
                            writer.endRDF();

                            out.close();

                        } catch (RDFHandlerException | IOException e) {
                            e.printStackTrace();
                        }

                        message = "'" + resource + "' transformed. results in '"
                                + config.getProperty("results.folder") + File.separatorChar + dataModelID + "."
                                + cnt + ".rdf." + config.getProperty("results.rdf.format") + "'";
                    } else {

                        message = "'" + resource + "' transformed but result is empty.";
                    }
                }
            } else {

                message = "'" + resource + "' not transformed: error in task execution.";
            }
        }
    } catch (Exception e) {

        logger.error("[" + config.getProperty("service.name") + "] Processing resource '" + resource
                + "' failed with a " + e.getClass().getSimpleName());
        e.printStackTrace();
    }

    return message;
}

From source file:org.btc4j.daemon.BtcJsonRpcHttpClient.java

public BtcTransaction jsonTransaction(JsonValue value) throws BtcException {
    JsonObject object = jsonObject(value);
    if (object == null) {
        return null;
    }/* w w w  .j a v a  2  s .c  o  m*/
    BtcTransaction transaction = new BtcTransaction();
    transaction.setTransaction(object.getString(BTCOBJ_TX_TRANSACTION, ""));
    transaction.setAmount(jsonDouble(object, BTCOBJ_TX_AMOUNT));
    transaction.setFee(jsonDouble(object, BTCOBJ_TX_FEE));
    transaction.setConfirmations(jsonLong(object, BTCOBJ_TX_CONFIRMATIONS));
    transaction.setTime(jsonLong(object, BTCOBJ_TX_TIME));
    transaction.setTimeReceived(jsonLong(object, BTCOBJ_TX_TIME_RECEIVED));
    transaction.setBlockHash(object.getString(BTCOBJ_TX_BLOCK_HASH, ""));
    transaction.setBlockIndex(jsonLong(object, BTCOBJ_TX_BLOCK_INDEX));
    transaction.setBlockTime(jsonLong(object, BTCOBJ_TX_BLOCK_TIME));
    List<BtcTransactionDetail> details = new ArrayList<BtcTransactionDetail>();
    JsonValue txDetails = object.get(BTCOBJ_TX_DETAILS);
    if ((txDetails != null) && (txDetails.getValueType() == JsonValue.ValueType.ARRAY)
            && (txDetails instanceof JsonArray)) {
        JsonArray txDetailsArray = (JsonArray) txDetails;
        for (JsonValue txDetail : txDetailsArray.getValuesAs(JsonValue.class)) {
            details.add(jsonTransactionDetail(txDetail));
        }
    } else {
        details.add(jsonTransactionDetail(value));
    }
    transaction.setDetails(details);
    return transaction;
}