Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

In this page you can find the example usage for org.json JSONObject JSONObject.

Prototype

public JSONObject() 

Source Link

Document

Construct an empty JSONObject.

Usage

From source file:com.cdd.bao.importer.KeywordMapping.java

public JSONObject createAssay(JSONObject keydata, Schema schema, Map<Schema.Assignment, SchemaTree> treeCache)
        throws JSONException, IOException {
    String uniqueID = null;//from   w  w w  .j  a  v  a 2s.  c  om
    List<String> linesTitle = new ArrayList<>(), linesBlock = new ArrayList<>();
    List<String> linesSkipped = new ArrayList<>(), linesProcessed = new ArrayList<>();
    Set<String> gotAnnot = new HashSet<>(), gotLiteral = new HashSet<>();
    JSONArray jsonAnnot = new JSONArray();
    final String SEP = "::";

    // assertions: these always supply a term
    for (Assertion asrt : assertions) {
        JSONObject obj = new JSONObject();
        obj.put("propURI", ModelSchema.expandPrefix(asrt.propURI));
        obj.put("groupNest", new JSONArray(expandPrefixes(asrt.groupNest)));
        obj.put("valueURI", ModelSchema.expandPrefix(asrt.valueURI));
        jsonAnnot.put(obj);

        String hash = asrt.propURI + SEP + asrt.valueURI + SEP
                + (asrt.groupNest == null ? "" : String.join(SEP, asrt.groupNest));
        gotAnnot.add(hash);
    }

    // go through the columns one at a time
    for (String key : keydata.keySet()) {
        String data = keydata.getString(key);

        Identifier id = findIdentifier(key);
        if (id != null) {
            if (uniqueID == null)
                uniqueID = id.prefix + data;
            continue;
        }

        TextBlock tblk = findTextBlock(key);
        if (tblk != null) {
            if (Util.isBlank(tblk.title))
                linesTitle.add(data);
            else
                linesBlock.add(tblk.title + ": " + data);
        }

        Value val = findValue(key, data);
        if (val != null) {
            if (Util.isBlank(val.valueURI)) {
                linesSkipped.add(key + ": " + data);
            } else {
                String hash = val.propURI + SEP + val.valueURI + SEP
                        + (val.groupNest == null ? "" : String.join(SEP, val.groupNest));
                if (gotAnnot.contains(hash))
                    continue;

                JSONObject obj = new JSONObject();
                obj.put("propURI", ModelSchema.expandPrefix(val.propURI));
                obj.put("groupNest", new JSONArray(expandPrefixes(val.groupNest)));
                obj.put("valueURI", ModelSchema.expandPrefix(val.valueURI));
                jsonAnnot.put(obj);
                gotAnnot.add(hash);
                linesProcessed.add(key + ": " + data);
            }
            continue;
        }

        Literal lit = findLiteral(key, data);
        if (lit != null) {
            String hash = lit.propURI + SEP + (lit.groupNest == null ? "" : String.join(SEP, lit.groupNest))
                    + SEP + data;
            if (gotLiteral.contains(hash))
                continue;

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(lit.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(lit.groupNest)));
            obj.put("valueLabel", data);
            jsonAnnot.put(obj);
            gotLiteral.add(hash);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        Reference ref = findReference(key, data);
        if (ref != null) {
            Pattern ptn = Pattern.compile(ref.valueRegex);
            Matcher m = ptn.matcher(data);
            if (!m.matches() || m.groupCount() < 1)
                throw new IOException(
                        "Pattern /" + ref.valueRegex + "/ did not match '" + data + "' to produce a group.");

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(ref.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(ref.groupNest)));
            obj.put("valueLabel", ref.prefix + m.group(1));
            jsonAnnot.put(obj);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        // probably shouldn't get this far, but just in case
        linesSkipped.add(key + ": " + data);
    }

    // annotation collapsing: sometimes there's a branch sequence that should exclude parent nodes
    for (int n = 0; n < jsonAnnot.length(); n++) {
        JSONObject obj = jsonAnnot.getJSONObject(n);
        String propURI = obj.getString("propURI"), valueURI = obj.optString("valueURI");
        if (valueURI == null)
            continue;
        String[] groupNest = obj.getJSONArray("groupNest").toStringArray();
        Schema.Assignment[] assnList = schema.findAssignmentByProperty(ModelSchema.expandPrefix(propURI),
                groupNest);
        if (assnList.length == 0)
            continue;
        SchemaTree tree = treeCache.get(assnList[0]);
        if (tree == null)
            continue;

        Set<String> exclusion = new HashSet<>();
        for (SchemaTree.Node node = tree.getNode(valueURI); node != null; node = node.parent)
            exclusion.add(node.uri);
        if (exclusion.size() == 0)
            continue;

        for (int i = jsonAnnot.length() - 1; i >= 0; i--)
            if (i != n) {
                obj = jsonAnnot.getJSONObject(i);
                if (!obj.has("valueURI"))
                    continue;
                if (!propURI.equals(obj.getString("propURI")))
                    continue;
                if (!Objects.deepEquals(groupNest, obj.getJSONArray("groupNest").toStringArray()))
                    continue;
                if (!exclusion.contains(obj.getString("valueURI")))
                    continue;
                jsonAnnot.remove(i);
            }
    }

    /*String text = "";
    if (linesBlock.size() > 0) text += String.join("\n", linesBlock) + "\n\n";
    if (linesSkipped.size() > 0) text += "SKIPPED:\n" + String.join("\n", linesSkipped) + "\n\n";
    text += "PROCESSED:\n" + String.join("\n", linesProcessed);*/

    List<String> sections = new ArrayList<>();
    if (linesTitle.size() > 0)
        sections.add(String.join(" / ", linesTitle));
    if (linesBlock.size() > 0)
        sections.add(String.join("\n", linesBlock));
    sections.add("#### IMPORTED ####");
    if (linesSkipped.size() > 0)
        sections.add("SKIPPED:\n" + String.join("\n", linesSkipped));
    if (linesProcessed.size() > 0)
        sections.add("PROCESSED:\n" + String.join("\n", linesProcessed));
    String text = String.join("\n\n", sections);

    JSONObject assay = new JSONObject();
    assay.put("uniqueID", uniqueID);
    assay.put("text", text);
    assay.put("schemaURI", schema.getSchemaPrefix());
    assay.put("annotations", jsonAnnot);
    return assay;
}

From source file:actuatorapp.ActuatorApp.java

public ActuatorApp() throws IOException, JSONException {
    //Takes a sting with a relay name "RELAYLO1-10FAD.relay1"
    //Actuator a = new Actuator("RELAYLO1-12854.relay1");    
    //Starts the virtualhub that is needed to connect to the actuators
    Process process = new ProcessBuilder("src\\actuatorapp\\VirtualHub.exe").start();
    //{"yocto_addr":"10FAD","payload":{"value":true},"type":"control"}

    api = new Socket("10.42.72.25", 8082);
    OutputStreamWriter osw = new OutputStreamWriter(api.getOutputStream(), StandardCharsets.UTF_8);
    InputStreamReader isr = new InputStreamReader(api.getInputStream(), StandardCharsets.UTF_8);

    //Sends JSON authentication to CommandAPI
    JSONObject secret = new JSONObject();
    secret.put("type", "authenticate");
    secret.put("secret", "testpass");
    osw.write(secret.toString() + "\r\n");
    osw.flush();/*from  ww w .  j av  a 2 s  . c o  m*/
    System.out.println("sent");

    //Waits and recieves JSON authentication response
    BufferedReader br = new BufferedReader(isr);
    JSONObject response = new JSONObject(br.readLine());
    System.out.println(response.toString());
    if (!response.getBoolean("success")) {
        System.err.println("Invalid API secret");
        System.exit(1);
    }

    try {
        while (true) {
            //JSON object will contain message from the server
            JSONObject type = getCommand(br);
            //Forward the command to be processed (will find out which actuators to turn on/off)
            commandFromApi(type);
        }
    } catch (Exception e) {
        System.out.println("Error listening to api");
    }

}

From source file:actuatorapp.ActuatorApp.java

public JSONObject getCommand(BufferedReader br) {
    JSONObject type = new JSONObject();
    try {/*from  w w  w . j  a  v a 2s  . co m*/
        System.out.println("Waiting for command...");
        //Waits for a message to be sent and reads that message as a string
        String message = br.readLine();
        System.out.println(message);
        //Converts the message into a JSONObject
        type = new JSONObject(message);
        return type;
    } catch (Exception e) {
        System.err.println("Error listening to api: " + e);
    }
    return type;
}

From source file:com.liferay.mobile.android.v62.announcementsentry.AnnouncementsEntryService.java

public JSONObject addEntry(long plid, long classNameId, long classPK, String title, String content, String url,
        String type, int displayDateMonth, int displayDateDay, int displayDateYear, int displayDateHour,
        int displayDateMinute, int expirationDateMonth, int expirationDateDay, int expirationDateYear,
        int expirationDateHour, int expirationDateMinute, int priority, boolean alert) throws Exception {
    JSONObject _command = new JSONObject();

    try {//from  w  w  w  .j  av  a2 s.co  m
        JSONObject _params = new JSONObject();

        _params.put("plid", plid);
        _params.put("classNameId", classNameId);
        _params.put("classPK", classPK);
        _params.put("title", checkNull(title));
        _params.put("content", checkNull(content));
        _params.put("url", checkNull(url));
        _params.put("type", checkNull(type));
        _params.put("displayDateMonth", displayDateMonth);
        _params.put("displayDateDay", displayDateDay);
        _params.put("displayDateYear", displayDateYear);
        _params.put("displayDateHour", displayDateHour);
        _params.put("displayDateMinute", displayDateMinute);
        _params.put("expirationDateMonth", expirationDateMonth);
        _params.put("expirationDateDay", expirationDateDay);
        _params.put("expirationDateYear", expirationDateYear);
        _params.put("expirationDateHour", expirationDateHour);
        _params.put("expirationDateMinute", expirationDateMinute);
        _params.put("priority", priority);
        _params.put("alert", alert);

        _command.put("/announcementsentry/add-entry", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}

From source file:com.amossys.hooker.common.InterceptEvent.java

/**
 * @return//  ww  w. j  ava  2 s  .com
 */
public String toJson() {
    JSONObject object = new JSONObject();

    try {
        //      object.put("IdEvent", this.getIdEvent().toString());

        object.put("Timestamp", this.getTimestamp());
        object.put("RelativeTimestamp", this.getRelativeTimestamp());
        object.put("HookerName", this.getHookerName());
        object.put("IntrusiveLevel", this.getIntrusiveLevel());
        object.put("InstanceID", this.getInstanceID());
        object.put("PackageName", this.getPackageName());

        object.put("ClassName", this.getClassName());
        object.put("MethodName", this.getMethodName());

        JSONArray parameters = new JSONArray();
        if (this.getParameters() != null) {
            for (Entry<String, String> parameter : this.getParameters()) {
                JSONObject jsonParameter = new JSONObject();
                jsonParameter.put("ParameterType", parameter.getKey());
                jsonParameter.put("ParameterValue", parameter.getValue());
                parameters.put(jsonParameter);
            }
        }
        object.put("Parameters", parameters);

        JSONObject returns = new JSONObject();
        if (this.getReturns() != null) {
            returns.put("ReturnType", this.getReturns().getKey());
            returns.put("ReturnValue", this.getReturns().getValue());
        }
        object.put("Return", returns);

        JSONArray data = new JSONArray();
        if (this.getData() != null) {
            for (String dataName : this.getData().keySet()) {
                if (dataName != null && this.getData().get(dataName) != null) {
                    JSONObject dataP = new JSONObject();
                    dataP.put("DataName", dataName);
                    dataP.put("DataValue", this.getData().get(dataName));
                }
            }
        }
        object.put("Data", data);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return object.toString();
}

From source file:com.apress.progwt.server.web.controllers.GearsLocalServerManifestController.java

private String createManifest() throws JSONException {

    String gwtROOT = hostConfigurer.resolvePlaceholder("HOST.gears.localserver.dir");
    String localServerURL = hostConfigurer.resolvePlaceholder("HOST.gears.localserver.url");

    File contextF = new File(gwtROOT);

    JSONObject json = new JSONObject();
    json.put("betaManifestVersion", Integer.parseInt(getProperty("gears.betaManifestVersion")));
    json.put("version", "0.0.1." + RandomUtils.rand(0, 2048));
    json.put("entries", getEntries(contextF, localServerURL));

    return json.toString();
}

From source file:com.apress.progwt.server.web.controllers.GearsLocalServerManifestController.java

/**
 * //from   www .  j a  v a2  s  .  co m
 * @param dir
 * @param localServerURL
 * @param dirString
 * @param fileArray
 * @return
 * @throws JSONException
 */
private JSONArray getEntries(File dir, String localServerURL, String dirString, JSONArray fileArray)
        throws JSONException {

    log.info("context: |" + dir + "|" + dirString);

    for (File f : dir.listFiles()) {

        if (shouldSkip(f.getName())) {
            continue;
        }

        // descend into directory
        if (f.isDirectory()) {
            log.info("found dir " + f);
            getEntries(f, localServerURL, f.getName() + "/", fileArray);
            continue;
        }

        JSONObject oo = new JSONObject();
        oo.put("url", localServerURL + dirString + f.getName());
        fileArray.put(oo);
    }
    return fileArray;
}

From source file:org.jboss.aerogear.unifiedpush.admin.ui.utils.InstallationUtils.java

public static Response registerInstallation(String contextPath, String variantID, String secret,
        Installation installation) {/*  w w  w.j av  a  2s.c  o m*/

    Response response = null;
    try {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceToken", installation.getDeviceToken());
        jsonObject.put("deviceType", installation.getDeviceType());
        jsonObject.put("operatingSystem", installation.getOperatingSystem());
        jsonObject.put("osVersion", installation.getOsVersion());
        jsonObject.put("alias", installation.getAlias());
        jsonObject.put("simplePushEndpoint", installation.getSimplePushEndpoint());

        response = RestAssured.given().contentType("application/json").auth().basic(variantID, secret)
                .header("Accept", "application/json").body(jsonObject.toString())
                .post(contextPath + "rest/registry/device");
    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;
}

From source file:io.openkit.okcloud.OKCloudAsyncRequest.java

private void postWithCompletionHandler(String relativeURL, final CompletionHandler h) {
    JSONObject requestParamsJSON = new JSONObject();
    try {//from w  ww  .j  a va 2s . c  o m
        requestParamsJSON.put("app_key", OpenKit.getOKAppID());
        for (Map.Entry<String, String> entry : params.entrySet()) {
            requestParamsJSON.put(entry.getKey(), entry.getValue());
        }
    } catch (JSONException e) {
        h.complete(null, new OKCloudException("Could not add post params to json object"));
        return;
    }

    OKHTTPClient.postJSON(relativeURL, requestParamsJSON, new AsyncHttpResponseHandler() {
        @Override
        public void onStart() {
            OKLog.v("POST started.");
        }

        @Override
        public void onSuccess(String response) {
            OKLog.v("POST succeeded, got response: %s", response);
            h.complete(response, null);
        }

        @Override
        public void onFailure(Throwable e, String response) {
            String errMessage = e.getMessage();
            OKLog.v("POST failed, %s", errMessage);
            h.complete(null, new OKCloudException(errMessage));
        }

        @Override
        public void onFinish() {
            OKLog.v("POST finished.");
        }
    });
}

From source file:com.atinternet.tracker.CustomObject.java

/**
 * Constructor
 *
 * @param tracker Tracker
 */
CustomObject(Tracker tracker) {
    super(tracker);
    value = new JSONObject().toString();
}