Search in sources :

Example 16 with JsonObject

use of javax.json.JsonObject in project mysql_perf_analyzer by yahoo.

the class SNMPSettings method readConfig.

private synchronized boolean readConfig() {
    File cfgFile = new File(this.myperfSnmpConfigPath);
    if (!cfgFile.exists()) {
        logger.info("There is no customized snmp configuration file");
        return true;
    }
    FileInputStream in = null;
    try {
        in = new FileInputStream(cfgFile);
        JsonReader jr = javax.json.Json.createReader(in);
        JsonObject jsonObject = jr.readObject();
        jr.close();
        this.setSiteSetting(readFromJson(jsonObject.getJsonObject("site")));
        JsonArray groups = jsonObject.getJsonArray("group");
        if (groups != null) {
            int len = groups.size();
            for (int i = 0; i < len; i++) {
                JsonObject grp = groups.getJsonObject(i);
                SNMPSetting grpSetting = readFromJson(grp);
                String grpName = grp.getString("dbgroup", null);
                if (grpName != null && grpSetting != null)
                    this.groupSettings.put(grpName, grpSetting);
            }
        }
        JsonArray hosts = jsonObject.getJsonArray("host");
        if (hosts != null) {
            int len = hosts.size();
            for (int i = 0; i < len; i++) {
                JsonObject host = hosts.getJsonObject(i);
                SNMPSetting hostSetting = readFromJson(host);
                String hostName = host.getString("dbhost", null);
                if (hostName != null && hostSetting != null)
                    this.hostSettings.put(hostName, hostSetting);
            }
        }
        return true;
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Failed to read SNMP configuration file " + cfgFile.getAbsolutePath(), ex);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception fex) {
            }
            ;
        }
    }
    return false;
}
Also used : JsonArray(javax.json.JsonArray) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 17 with JsonObject

use of javax.json.JsonObject in project mysql_perf_analyzer by yahoo.

the class AlertDefinition method createFromJson.

public static AlertDefinition createFromJson(java.io.InputStream in) {
    JsonReader jsonReader = null;
    AlertDefinition alert = null;
    try {
        jsonReader = javax.json.Json.createReader(in);
        JsonObject jsonObject = jsonReader.readObject();
        jsonReader.close();
        alert = new AlertDefinition(jsonObject.getString("name"));
        alert.setSource(jsonObject.getString("source"));
        alert.setMetricName(jsonObject.getString("metricName", null));
        alert.setMetricValueType(jsonObject.getString("metricValueType", null));
        alert.setMetricComparison(jsonObject.getString("metricComparison", null));
        try {
            alert.setDefaultThreshold(Float.parseFloat(jsonObject.getString("defaultThreshold", null)));
        } catch (Exception ex) {
        }
        alert.setSqlId(jsonObject.getString("sqlId", null));
        alert.setSqlText(jsonObject.getString("sqlText", null));
        JsonArray params = jsonObject.getJsonArray("params");
        if (params != null) {
            int mlen = params.size();
            for (int i = 0; i < mlen; i++) {
                JsonObject mobj = params.getJsonObject(i);
                alert.addParam(mobj.getString("name"), mobj.getString("defaultValue"));
            }
        }
        return alert;
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Error to parse UDM", ex);
    }
    return null;
}
Also used : JsonArray(javax.json.JsonArray) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) UserDefinedMetricsException(com.yahoo.dba.perf.myperf.common.UserDefinedMetrics.UserDefinedMetricsException)

Example 18 with JsonObject

use of javax.json.JsonObject in project goci by EBISPOT.

the class JsonBuilder method buildJson.

public String buildJson(String pvalue, String efoTrait, String rsId, String pubmedId, int sampleSize, long gwasPanelResolution, String ensemblId) {
    String dbVersion = getDate();
    String gwasDbId = "http://identifiers.org/gwascatalog";
    String jsonSchemaVersion = "1.2.2";
    String soTerm = "http://purl.obolibrary.org/obo/SO_0001627";
    JsonObject target = Json.createObjectBuilder().add("activity", "http://identifiers.org/cttv.activity/predicted_damaging").add("id", Json.createArrayBuilder().add("http://identifiers.org/ensembl/" + ensemblId)).add("target_type", "http://identifiers.org/cttv.target/gene_evidence").build();
    JsonObject variant = Json.createObjectBuilder().add("type", "snp single").add("id", Json.createArrayBuilder().add("http://identifiers.org/dbsnp/" + rsId)).build();
    JsonObject disease = Json.createObjectBuilder().add("id", Json.createArrayBuilder().add(efoTrait)).build();
    JsonObject uniqueAssociationFields = Json.createObjectBuilder().add("sample_size", Integer.toString(sampleSize)).add("gwas_panel_resolution", Long.toString(gwasPanelResolution)).add("pubmed_refs", "http://europepmc.org/abstract/MED/" + pubmedId).add("target", "http://identifiers.org/ensembl/" + ensemblId).add("object", efoTrait).add("variant", "http://identifiers.org/dbsnp/" + rsId).add("study_name", "cttv009_gwas_catalog").add("pvalue", pvalue).build();
    JsonObject litId = Json.createObjectBuilder().add("lit_id", "http://europepmc.org/abstract/MED/" + pubmedId).build();
    JsonArray references = Json.createArrayBuilder().add(litId).build();
    JsonObject literature = Json.createObjectBuilder().add("references", references).build();
    JsonArray litIdArray = Json.createArrayBuilder().add(litId).build();
    JsonObject literatureHigher = Json.createObjectBuilder().add("references", litIdArray).build();
    JsonObject expert = Json.createObjectBuilder().add("status", true).add("statement", "Primary submitter of data").build();
    JsonObject dbXref = Json.createObjectBuilder().add("version", dbVersion).add("id", gwasDbId).build();
    JsonObject database = Json.createObjectBuilder().add("version", dbVersion).add("id", "GWAS Catalog").add("dbxref", dbXref).build();
    JsonObject variant2diseaseProvenanceType = Json.createObjectBuilder().add("literature", literature).add("expert", expert).add("database", database).build();
    JsonObject method = Json.createObjectBuilder().add("description", "pvalue for the snp to disease association.").build();
    JsonObject resourceScore = Json.createObjectBuilder().add("type", "pvalue").add("method", method).add("value", pvalue).build();
    JsonArray evidenceCodes = Json.createArrayBuilder().add("http://identifiers.org/eco/GWAS").add("http://purl.obolibrary.org/obo/ECO_0000205").build();
    JsonObject variant2disease = Json.createObjectBuilder().add("gwas_sample_size", sampleSize).add("unique_experiment_reference", "http://europepmc.org/abstract/MED/" + pubmedId).add("gwas_panel_resolution", gwasPanelResolution).add("provenance_type", variant2diseaseProvenanceType).add("is_associated", true).add("resource_score", resourceScore).add("evidence_codes", evidenceCodes).add("date_asserted", dbVersion).build();
    JsonObject gene2Variantexpert = Json.createObjectBuilder().add("status", true).add("statement", "Primary submitter of data").build();
    JsonObject gene2variantProvenanceType = Json.createObjectBuilder().add("expert", gene2Variantexpert).add("database", database).build();
    JsonArray gene2VariantEvidenceCodes = Json.createArrayBuilder().add("http://purl.obolibrary.org/obo/ECO_0000205").add("http://identifiers.org/eco/cttv_mapping_pipeline").build();
    JsonObject gene2variant = Json.createObjectBuilder().add("provenance_type", gene2variantProvenanceType).add("is_associated", true).add("date_asserted", dbVersion).add("evidence_codes", gene2VariantEvidenceCodes).add("functional_consequence", soTerm).build();
    JsonObject evidence = Json.createObjectBuilder().add("variant2disease", variant2disease).add("gene2variant", gene2variant).build();
    JsonObject json = Json.createObjectBuilder().add("target", target).add("access_level", "public").add("sourceID", "gwascatalog").add("variant", variant).add("disease", disease).add("unique_association_fields", uniqueAssociationFields).add("evidence", evidence).add("validated_against_schema_version", jsonSchemaVersion).add("type", "genetic_association").add("literature", literatureHigher).build();
    String jsonToReturn = json.toString();
    //        Pattern pattern = Pattern.compile(",\"value\":(\".E.\")");
    //        Matcher matcher = pattern.matcher(jsonToReturn);
    //
    //        boolean found = false;
    //        while (matcher.find()) {
    //            System.out.println("I found the text" +
    //                            matcher.group() + " starting at " +
    //                            "index " + matcher.start() + " and ending at index " +  matcher.end() );
    //            found = true;
    //        }
    jsonToReturn = removeQuoteAroundPvalue(jsonToReturn);
    System.out.println("\n" + jsonToReturn);
    return jsonToReturn;
}
Also used : JsonArray(javax.json.JsonArray) JsonObject(javax.json.JsonObject)

Example 19 with JsonObject

use of javax.json.JsonObject in project azure-iot-sdk-java by Azure.

the class IotHubExceptionManager method httpResponseVerification.

/**
     * Verify Http response using response status
     *
     * @param httpResponse Http response object to verify
     * @throws IotHubBadFormatException This exception is thrown if the response status equal 400
     * @throws IotHubUnathorizedException This exception is thrown if the response status equal 401
     * @throws IotHubTooManyDevicesException This exception is thrown if the response status equal 403
     * @throws IotHubNotFoundException This exception is thrown if the response status equal 404
     * @throws IotHubPreconditionFailedException This exception is thrown if the response status equal 412
     * @throws IotHubTooManyRequestsException This exception is thrown if the response status equal 429
     * @throws IotHubInternalServerErrorException This exception is thrown if the response status equal 500
     * @throws IotHubBadGatewayException This exception is thrown if the response status equal 502
     * @throws IotHubServerBusyException This exception is thrown if the response status equal 503
     * @throws IotHubGatewayTimeoutException This exception is thrown if the response status equal 504
     * @throws IotHubException This exception is thrown if the response status none of them above and greater then 300
     */
public static void httpResponseVerification(HttpResponse httpResponse) throws IotHubBadFormatException, IotHubUnathorizedException, IotHubTooManyDevicesException, IotHubPreconditionFailedException, IotHubTooManyRequestsException, IotHubInternalServerErrorException, IotHubServerBusyException, IotHubBadGatewayException, IotHubNotFoundException, IotHubGatewayTimeoutException, IotHubException {
    int responseStatus = httpResponse.getStatus();
    String errorMessage = "";
    try {
        String jsonString = new String(httpResponse.getErrorReason(), StandardCharsets.UTF_8);
        try (JsonReader jsonReader = Json.createReader(new StringReader(jsonString))) {
            JsonObject jsonObject = jsonReader.readObject();
            if ((jsonObject != JsonObject.NULL) && (jsonObject != null)) {
                errorMessage = Tools.getValueFromJsonObject(jsonObject, "ExceptionMessage");
            }
        }
    } catch (Exception e) {
    /* If it cannot parser the errorReason, just log a error without message.*/
    // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_21_013: [If the httpresponse contains a reason message, the function must print this reason in the error message]
    }
    // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_12_001: [The function shall throw IotHubBadFormatException if the Http response status equal 400]
    if (400 == responseStatus) {
        throw new IotHubBadFormatException(errorMessage);
    } else // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_12_002: [The function shall throw IotHubUnathorizedException if the Http response status equal 401]
    if (401 == responseStatus) {
        throw new IotHubUnathorizedException(errorMessage);
    } else // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_12_003: [The function shall throw IotHubTooManyDevicesException if the Http response status equal 403]
    if (403 == responseStatus) {
        throw new IotHubTooManyDevicesException(errorMessage);
    } else // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_12_004: [The function shall throw IotHubNotFoundException if the Http response status equal 404]
    if (404 == responseStatus) {
        throw new IotHubNotFoundException(errorMessage);
    } else // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_12_005: [The function shall throw IotHubPreconditionFailedException if the Http response status equal 412]
    if (412 == responseStatus) {
        throw new IotHubPreconditionFailedException(errorMessage);
    } else // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_12_006: [The function shall throw IotHubTooManyRequestsException if the Http response status equal 429]
    if (429 == responseStatus) {
        throw new IotHubTooManyRequestsException(errorMessage);
    } else // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_12_007: [The function shall throw IotHubInternalServerErrorException if the Http response status equal 500]
    if (500 == responseStatus) {
        throw new IotHubInternalServerErrorException(errorMessage);
    } else // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_21_008: [The function shall throw IotHubBadGatewayException if the Http response status equal 502]
    if (502 == responseStatus) {
        throw new IotHubBadGatewayException(errorMessage);
    } else // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_12_009: [The function shall throw IotHubServerBusyException if the Http response status equal 503]
    if (503 == responseStatus) {
        throw new IotHubServerBusyException(errorMessage);
    } else // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_21_010: [The function shall throw IotHubGatewayTimeoutException if the Http response status equal 504]
    if (504 == responseStatus) {
        throw new IotHubGatewayTimeoutException(errorMessage);
    } else // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_12_011: [The function shall throw IotHubException if the Http response status none of them above and greater than 300 copying the error Http reason to the exception]
    if (responseStatus > 300) {
        if (errorMessage.isEmpty()) {
            throw new IotHubException("Unknown error reason");
        } else {
            throw new IotHubException(errorMessage);
        }
    }
// Codes_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_12_012: [The function shall return without exception if the response status equal or less than 300]
}
Also used : JsonObject(javax.json.JsonObject) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader)

Example 20 with JsonObject

use of javax.json.JsonObject in project azure-iot-sdk-java by Azure.

the class ToolsTest method getValueFromJsonObject_value_null.

// Tests_SRS_SERVICE_SDK_JAVA_TOOLS_12_014: [The function shall return empty string if the JsonValue is null]
@Test
public void getValueFromJsonObject_value_null() {
    // Arrange
    String jsonString = "{\"deviceId\":\"xxx-device\",\"generationId\":null,\"etag\":\"MA==\",\"connectionState\":\"Disconnected\",\"status\":\"disabled\",\"statusReason\":null,\"connectionStateUpdatedTime\":\"0001-01-01T00:00:00\",\"statusUpdatedTime\":\"0001-01-01T00:00:00\",\"lastActivityTime\":\"0001-01-01T00:00:00\",\"cloudToDeviceMessageCount\":0,\"authentication\":{\"symmetricKey\":{\"primaryKey\":\"AAABBBCCC111222333444000\",\"secondaryKey\":\"111222333444555AAABBBCCC\"}}}";
    StringReader stringReader = new StringReader(jsonString);
    JsonReader jsonReader = Json.createReader(stringReader);
    JsonObject jsonObject = jsonReader.readObject();
    String key = "generationId";
    String expResult = "";
    // Act
    String result = Tools.getValueFromJsonObject(jsonObject, key);
    // Assert
    assertEquals(expResult, result);
}
Also used : StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) JsonString(javax.json.JsonString) Test(org.junit.Test)

Aggregations

JsonObject (javax.json.JsonObject)214 Test (org.junit.Test)101 JsonArray (javax.json.JsonArray)58 StringReader (java.io.StringReader)52 Credentials (org.apache.commons.httpclient.Credentials)52 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)52 ArrayList (java.util.ArrayList)51 HashMap (java.util.HashMap)47 NameValuePair (org.apache.commons.httpclient.NameValuePair)43 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)41 JsonString (javax.json.JsonString)31 JsonReader (javax.json.JsonReader)25 HashSet (java.util.HashSet)16 Map (java.util.Map)12 Response (javax.ws.rs.core.Response)12 JsonObjectBuilder (javax.json.JsonObjectBuilder)11 NameValuePairList (org.apache.sling.commons.testing.integration.NameValuePairList)11 StringWriter (java.io.StringWriter)10 JsonException (javax.json.JsonException)10 JsonArrayBuilder (javax.json.JsonArrayBuilder)9