Java Code Examples for javax.json.JsonValue#asJsonObject()

The following examples show how to use javax.json.JsonValue#asJsonObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImportPartitionMapper.java    From FHIR with Apache License 2.0 6 votes vote down vote up
private List<FhirDataSource> getFhirDataSources(JsonArray dataSourceArray, BulkImportDataSourceStorageType type)
        throws Exception {
    List<FhirDataSource> fhirDataSources = new ArrayList<>();
    for (JsonValue jsonValue : dataSourceArray) {
        JsonObject dataSourceInfo = jsonValue.asJsonObject();
        String dsTypeInfo = dataSourceInfo.getString(Constants.IMPORT_INPUT_RESOURCE_TYPE);
        String dsDataLocationInfo = dataSourceInfo.getString(Constants.IMPORT_INPUT_RESOURCE_URL);

        switch (type) {
        case HTTPS:
        case FILE:
            fhirDataSources.add(new FhirDataSource(dsTypeInfo, dsDataLocationInfo));
            break;
        case AWSS3:
        case IBMCOS:
            fhirDataSources.addAll(getFhirDataSourcesForObjectStore(dsTypeInfo, dsDataLocationInfo));
            break;
        default:
            break;
        }
    }

    return fhirDataSources;
}
 
Example 2
Source File: JsonUtilsTests.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrapClaimValueMap() {
    JsonObject expResult = Json.createObjectBuilder()
            .add("a", "a")
            .add("b", "b")
            .add("c", "c")
            .build();

    Map<String, String> value = new HashMap<>();
    value.put("a", "a");
    value.put("b", "b");
    value.put("c", "c");
    JsonValue result = JsonUtils.wrapValue(value);

    assertTrue(result instanceof JsonObject);
    JsonObject resultObject = result.asJsonObject();
    assertEquals(expResult, resultObject);
}
 
Example 3
Source File: JsonIndexedRecord.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Object toObject(final JsonValue jsonValue, final Schema schema) {
    if (jsonValue == null) {
        return null;
    }
    switch (jsonValue.getValueType()) {
    case TRUE:
        return true;
    case FALSE:
        return false;
    case NUMBER:
        return JsonNumber.class.cast(jsonValue).numberValue();
    case STRING:
        return JsonString.class.cast(jsonValue).getString();
    case ARRAY:
        return jsonValue
                .asJsonArray()
                .stream()
                .map(it -> toObject(jsonValue, schema.getElementType()))
                .collect(toList());
    case OBJECT:
        return new JsonIndexedRecord(jsonValue.asJsonObject(), schema);
    case NULL:
    default:
        return null;
    }
}
 
Example 4
Source File: JsonUtilsTests.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrapClaimValueMapWithNull() {
    JsonObject expResult = Json.createObjectBuilder()
            .build();

    Map<String, String> value = new HashMap<>();
    value.put("a", null);
    JsonValue result = JsonUtils.wrapValue(value);

    assertTrue(result instanceof JsonObject);
    JsonObject resultObject = result.asJsonObject();
    assertEquals(expResult, resultObject);
}
 
Example 5
Source File: GenerateExtensionsJsonMojo.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public OverrideInfo getOverrideInfo(File overridesFile) throws MojoExecutionException {
    // Read the overrides file for the extensions (if it exists)
    HashMap extOverrides = new HashMap<>();
    JsonObject theRest = null;
    if (overridesFile.isFile()) {
        info("Found overrides file %s", overridesFile);
        try (JsonReader jsonReader = Json.createReader(new FileInputStream(overridesFile))) {
            JsonObject overridesObject = jsonReader.readObject();
            JsonArray extOverrideObjects = overridesObject.getJsonArray("extensions");
            if (extOverrideObjects != null) {
                // Put the extension overrides into a map keyed to their GAV
                for (JsonValue val : extOverrideObjects) {
                    JsonObject extOverrideObject = val.asJsonObject();
                    String key = extensionId(extOverrideObject);
                    extOverrides.put(key, extOverrideObject);
                }
            }

            theRest = overridesObject;
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to read " + overridesFile, e);
        }
        return new OverrideInfo(extOverrides, theRest);

    } else {
        throw new MojoExecutionException(overridesFile + " not found.");
    }
}
 
Example 6
Source File: Generator.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private static boolean areEqualsIgnoringOrder(final JsonValue oldValue, final JsonValue newValue) {
    if (!oldValue.getValueType().equals(newValue.getValueType())) {
        return false;
    }
    switch (oldValue.getValueType()) {
    case STRING:
        return JsonString.class.cast(oldValue).getString().equals(JsonString.class.cast(newValue).getString());
    case NUMBER:
        return JsonNumber.class.cast(oldValue).doubleValue() == JsonNumber.class.cast(newValue).doubleValue();
    case OBJECT:
        final JsonObject oldObject = oldValue.asJsonObject();
        final JsonObject newObject = newValue.asJsonObject();
        if (!oldObject.keySet().equals(newObject.keySet())) {
            return false;
        }
        return oldObject
                .keySet()
                .stream()
                .map(key -> areEqualsIgnoringOrder(oldObject.get(key), newObject.get(key)))
                .reduce(true, (a, b) -> a && b);
    case ARRAY:
        final JsonArray oldArray = oldValue.asJsonArray();
        final JsonArray newArray = newValue.asJsonArray();
        if (oldArray.size() != newArray.size()) {
            return false;
        }
        if (oldArray.isEmpty()) {
            return true;
        }
        for (final JsonValue oldItem : oldArray) {
            if (newArray.stream().noneMatch(newitem -> areEqualsIgnoringOrder(oldItem, newitem))) {
                return false;
            }
        }
        return true;
    default:
        // value type check was enough
        return true;
    }
}
 
Example 7
Source File: FeatureServiceImpl.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private FeatureBundle[] getBundles(JsonObject json) {
    JsonArray ja = json.getJsonArray("bundles");
    if (ja == null)
        return new FeatureBundle[] {};

    List<FeatureBundle> bundles = new ArrayList<>();

    for (JsonValue val : ja) {
        if (val.getValueType() == JsonValue.ValueType.OBJECT) {
            JsonObject jo = val.asJsonObject();
            String bid = jo.getString("id");
            FeatureBundleBuilder builder = builderFactory.newBundleBuilder(ID.fromMavenID(bid));

            for (Map.Entry<String, JsonValue> entry : jo.entrySet()) {
                if (entry.getKey().equals("id"))
                    continue;

                JsonValue value = entry.getValue();

                Object v;
                switch (value.getValueType()) {
                case NUMBER:
                    v = ((JsonNumber) value).longValueExact();
                    break;
                case STRING:
                    v = ((JsonString) value).getString();
                    break;
                default:
                    v = value.toString();
                }
                builder.addMetadata(entry.getKey(), v);
            }
            bundles.add(builder.build());
        }
    }

    return bundles.toArray(new FeatureBundle[0]);
}
 
Example 8
Source File: ChaincodeCollectionConfiguration.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
Collection.CollectionConfigPackage parse(JsonArray jsonConfig) throws ChaincodeCollectionConfigurationException {

        Collection.CollectionConfigPackage.Builder colcofbuilder = Collection.CollectionConfigPackage.newBuilder();
        for (int i = jsonConfig.size() - 1; i > -1; --i) {

            Collection.StaticCollectionConfig.Builder ssc = Collection.StaticCollectionConfig.newBuilder();

            JsonValue j = jsonConfig.get(i);
            if (j.getValueType() != JsonValue.ValueType.OBJECT) {
                throw new ChaincodeCollectionConfigurationException(format("Expected StaticCollectionConfig to be Object type but got: %s", j.getValueType().name()));
            }

            JsonObject jsonObject = j.asJsonObject();
            JsonObject scf = getJsonObject(jsonObject, "StaticCollectionConfig"); // oneof .. may have different values in the future
            ssc.setName(getJsonString(scf, "name"))
                    .setBlockToLive(getJsonLong(scf, "blockToLive"))
                    .setMaximumPeerCount(getJsonInt(scf, "maximumPeerCount"))
                    .setMemberOrgsPolicy(Collection.CollectionPolicyConfig.newBuilder()
                            .setSignaturePolicy(parseSignaturePolicyEnvelope(scf)).build())
                    .setRequiredPeerCount(getJsonInt(scf, "requiredPeerCount"));

            colcofbuilder.addConfig(Collection.CollectionConfig.newBuilder().setStaticCollectionConfig(ssc).build());

        }
        return colcofbuilder.build();

    }
 
Example 9
Source File: ChaincodeCollectionConfiguration.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private static JsonObject getJsonObject(JsonObject obj, String prop) throws ChaincodeCollectionConfigurationException {
    JsonValue ret = obj.get(prop);
    if (ret == null) {
        throw new ChaincodeCollectionConfigurationException(format("property %s missing", prop));
    }
    if (ret.getValueType() != JsonValue.ValueType.OBJECT) {
        throw new ChaincodeCollectionConfigurationException(format("property %s wrong type expected object got %s", prop, ret.getValueType().name()));
    }

    return ret.asJsonObject();

}
 
Example 10
Source File: NetworkConfig.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private static JsonObject getJsonObject(JsonObject object, String propName) {
    JsonObject obj = null;
    JsonValue val = object.get(propName);
    if (val != null && val.getValueType() == ValueType.OBJECT) {
        obj = val.asJsonObject();
    }
    return obj;
}
 
Example 11
Source File: SystemTestJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the FunctionTestDef represented by the given JSON value.
 */
private static FunctionTestDef asFunctionTestDef( String functionName, JsonValue json)
  {
  FunctionTestDef functionTestDef;

  try
    {
    functionTestDef = new FunctionTestDef( validIdentifier( functionName));

    JsonArray testCases;
    if( json.getValueType() == ARRAY)
      {
      // For compatibility, accept documents conforming to schema version <= 3.0.1
      testCases = json.asJsonArray();
      }
    else
      {
      JsonObject functionObject = json.asJsonObject();
      testCases = functionObject.getJsonArray( TEST_CASES_KEY);
      
      // Get annotations for this function.
      Optional.ofNullable( functionObject.getJsonObject( HAS_KEY))
        .ifPresent( has -> has.keySet().stream().forEach( key -> functionTestDef.setAnnotation( key, has.getString( key))));
      }

    // Get function test cases.
    testCases
      .getValuesAs( JsonObject.class)
      .stream()
      .forEach( testCase -> functionTestDef.addTestCase( asTestCase( testCase)));
    }
  catch( SystemTestException e)
    {
    throw new SystemTestException( String.format( "Error defining function=%s", functionName), e);
    }
  
  return functionTestDef;
  }
 
Example 12
Source File: JobExecutionResponse.java    From FHIR with Apache License 2.0 4 votes vote down vote up
public static JobExecutionResponse parse(InputStream in) throws FHIROperationException {
    try (JsonReader jsonReader =
            JSON_READER_FACTORY.createReader(in, StandardCharsets.UTF_8)) {
        JsonObject jsonObject = jsonReader.readObject();
        JobExecutionResponse.Builder builder = JobExecutionResponse.builder();

        if (jsonObject.containsKey("jobName")) {
            String jobName = jsonObject.getString("jobName");
            builder.jobName(jobName);
        }

        if (jsonObject.containsKey("instanceId")) {
            Integer instanceId = jsonObject.getInt("instanceId");
            builder.instanceId(instanceId);
        }

        if (jsonObject.containsKey("appName")) {
            String appName = jsonObject.getString("appName");
            builder.appName(appName);
        }

        if (jsonObject.containsKey("batchStatus")) {
            String batchStatus = jsonObject.getString("batchStatus");
            builder.batchStatus(batchStatus);
        }

        if (jsonObject.containsKey("exitStatus")) {
            String exitStatus = jsonObject.getString("exitStatus");
            builder.exitStatus(exitStatus);
        }

        if (jsonObject.containsKey("jobXMLName")) {
            String jobXMLName = jsonObject.getString("jobXMLName");
            builder.jobXMLName(jobXMLName);
        }

        if (jsonObject.containsKey("instanceName")) {
            String instanceName = jsonObject.getString("instanceName");
            builder.instanceName(instanceName);
        }

        if (jsonObject.containsKey("lastUpdatedTime")) {
            String lastUpdatedTime = jsonObject.getString("lastUpdatedTime");
            builder.lastUpdatedTime(lastUpdatedTime);
        }

        if (jsonObject.containsKey("_links")) {
            JsonArray arr = jsonObject.getJsonArray("_links");
            ListIterator<JsonValue> iter = arr.listIterator();
            while (iter.hasNext()) {
                JsonValue v = iter.next();
                JsonObject vObj = v.asJsonObject();

                if (vObj.containsKey("rel") && vObj.containsKey("href")) {
                    String rel = vObj.getString("rel");
                    String href = vObj.getString("href");
                    builder.link(rel, href);
                }
            }
        }

        if (jsonObject.containsKey("submitter")) {
            String submitter = jsonObject.getString("submitter");
            builder.submitter(submitter);
        }

        if (jsonObject.containsKey("instanceState")) {
            String instanceState = jsonObject.getString("instanceState");
            builder.instanceState(instanceState);
        }

        if (jsonObject.containsKey("jobParameters")) {
            JsonObject obj = jsonObject.getJsonObject("jobParameters");
            JobParameter.Parser.parse(builder, obj);
        }
        return builder.build();
    } catch (Exception e) {
        throw new FHIROperationException("Problem parsing the Bulk Export Job's response from the server", e);
    }
}
 
Example 13
Source File: JobInstanceResponse.java    From FHIR with Apache License 2.0 4 votes vote down vote up
public static JobInstanceResponse parse(InputStream in) throws FHIROperationException {
    try (JsonReader jsonReader = JSON_READER_FACTORY.createReader(in, StandardCharsets.UTF_8)) {
        JsonObject jsonObject = jsonReader.readObject();
        JobInstanceResponse.Builder builder = JobInstanceResponse.builder();

        if (jsonObject.containsKey("jobName")) {
            String jobName = jsonObject.getString("jobName");
            builder.jobName(jobName);
        }

        if (jsonObject.containsKey("instanceId")) {
            Integer instanceId = jsonObject.getInt("instanceId");
            builder.instanceId(instanceId);
        }

        if (jsonObject.containsKey("appName")) {
            String appName = jsonObject.getString("appName");
            builder.appName(appName);
        }

        if (jsonObject.containsKey("batchStatus")) {
            String batchStatus = jsonObject.getString("batchStatus");
            builder.batchStatus(batchStatus);
        }

        if (jsonObject.containsKey("jobXMLName")) {
            String jobXMLName = jsonObject.getString("jobXMLName");
            builder.jobXMLName(jobXMLName);
        }

        if (jsonObject.containsKey("instanceName")) {
            String instanceName = jsonObject.getString("instanceName");
            builder.instanceName(instanceName);
        }

        if (jsonObject.containsKey("instanceState")) {
            String instanceState = jsonObject.getString("instanceState");
            builder.instanceState(instanceState);
        }

        if (jsonObject.containsKey("submitter")) {
            String submitter = jsonObject.getString("submitter");
            builder.submitter(submitter);
        }

        if (jsonObject.containsKey("lastUpdatedTime")) {
            String lastUpdatedTime = jsonObject.getString("lastUpdatedTime");
            builder.lastUpdatedTime(lastUpdatedTime);
        }

        int jobExecutionId = 0;
        if (jsonObject.containsKey("_links")) {
            JsonArray arr = jsonObject.getJsonArray("_links");
            ListIterator<JsonValue> iter = arr.listIterator();
            while (iter.hasNext()) {
                JsonValue v = iter.next();
                JsonObject vObj = v.asJsonObject();

                if (vObj.containsKey("rel") && vObj.containsKey("href")) {
                    String rel = vObj.getString("rel");
                    String href = vObj.getString("href");
                    builder.link(rel, href);
                    if (rel.equalsIgnoreCase("job execution")) {
                        // e.g, https://localhost:9443/ibm/api/batch/jobinstances/9/jobexecutions/2
                        // Get the job execution id of the job instance at the end of the url, because the same job instance can be
                        // started, stopped and then restarted multipe times, so need to find the last job execution id and use it
                        // as the current job execution id.
                        int tmpJobExecutionId =
                                Integer.parseInt(href.substring(href.indexOf("jobexecutions") + 14));
                        jobExecutionId =
                                jobExecutionId < tmpJobExecutionId ? tmpJobExecutionId : jobExecutionId;
                    }
                }
            }
        }
        builder.executionId(jobExecutionId);

        return builder.build();
    } catch (Exception e) {
        throw new FHIROperationException("Problem parsing the Bulk Export Job's response from the server", e);
    }
}
 
Example 14
Source File: NetworkConfig.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
private static JsonObject getJsonValueAsObject(JsonValue value) {
    return (value != null && value.getValueType() == ValueType.OBJECT) ? value.asJsonObject() : null;
}