javax.json.JsonValue Java Examples

The following examples show how to use javax.json.JsonValue. 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: PropertiesReader.java    From boost with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Properties readFrom(Class<Properties> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {

    JsonReader jr = Json.createReader(entityStream);
    JsonObject json = jr.readObject();
    Properties retVal = new Properties();

    json.keySet().forEach(key -> {
        JsonValue value = json.get(key);
        if (!JsonValue.NULL.equals(value)) {
            if (value.getValueType() != JsonValue.ValueType.STRING) {
                throw new IllegalArgumentException(
                        "Non-String JSON prop value found in payload.  Sample data is more than this sample can deal with.  It's not intended to handle any payload.");
            }
            JsonString jstr = (JsonString) value;

            retVal.setProperty(key, jstr.getString());
        }
    });
    return retVal;
}
 
Example #2
Source File: JsonExporter.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private Map<String, JsonValue> exportMetricsForMap(Map<MetricID, Metric> metricMap, Map<String, Metadata> metadataMap) {
    Map<String, JsonValue> result = new HashMap<>();

    // split into groups by metric name
    Map<String, Map<MetricID, Metric>> metricsGroupedByName = metricMap.entrySet().stream()
            .collect(Collectors.groupingBy(
                    entry -> entry.getKey().getName(),
                    Collectors.mapping(e -> e, Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));
    // and then for each group, perform the export
    metricsGroupedByName.entrySet().stream()
            .map(entry -> exportMetricsByName(entry.getValue(), metadataMap.get(entry.getKey())))
            .forEach(map -> {
                map.forEach(result::put);
            });
    return result;
}
 
Example #3
Source File: JsonHelper.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * JsonArrayまたはJsonObjectをCollectionに変換します<br>
 * JsonObjectの場合は単一のオブジェクトだけを格納しているCollectionを返します
 *
 * @param <T> JsonArrayの内容の型
 * @param <R> functionの戻り値の型
 * @param <C> 変換後のCollectionの型
 * @param value 変換するJsonArrayまたはJsonObject
 * @param function JsonValueを受け取って変換するFunction
 * @param supplier Collectionインスタンスを供給するSupplier
 * @return 変換後のCollection
 */
@SuppressWarnings("unchecked")
public static <T extends JsonValue, C extends Collection<R>, R> C toCollection(JsonValue value,
        Function<T, R> function, Supplier<C> supplier) {
    C collection = supplier.get();
    if (value instanceof JsonArray) {
        for (JsonValue val : (JsonArray) value) {
            if (val == null || val == JsonValue.NULL) {
                collection.add(null);
            } else {
                collection.add(function.apply((T) val));
            }
        }
    } else {
        collection.add(function.apply((T) value));
    }
    return collection;
}
 
Example #4
Source File: JsonpRuntime.java    From jmespath-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public List<JsonValue> toList(JsonValue value) {
  ValueType valueType = value.getValueType();
  if (valueType == ARRAY) {
    return new JsonArrayListWrapper((JsonArray) value);
  } else if (valueType == OBJECT) {
    JsonObject obj = (JsonObject) value;
    if (!obj.isEmpty()) {
      List<JsonValue> elements = new ArrayList<>(obj.size());
      for (JsonValue v : obj.values()) {
        elements.add(nodeOrNullNode(v));
      }
      return elements;
    }
  }
  return Collections.emptyList();
}
 
Example #5
Source File: Patch.java    From FHIR with Apache License 2.0 6 votes vote down vote up
private FHIRPatch createPatch(JsonArray array) throws FHIROperationException {
    try {
        FHIRPatch patch = FHIRPatch.patch(array);
        JsonPatch jsonPatch = patch.as(FHIRJsonPatch.class).getJsonPatch();
        for (JsonValue value : jsonPatch.toJsonArray()) {
            // validate path
            String path = value.asJsonObject().getString("path");
            if ("/id".equals(path) ||
                    "/meta/versionId".equals(path) ||
                    "/meta/lastUpdated".equals(path)) {
                throw new IllegalArgumentException("Path: '" + path
                        + "' is not allowed in a patch operation.");
            }
        }
        return patch;
    } catch (Exception e) {
        String msg = "Invalid patch: " + e.getMessage();
        throw new FHIROperationException(msg, e)
                .withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.INVALID));
    }
}
 
Example #6
Source File: SiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
private static void addField(final JsonObjectBuilder builder, final JsonBuilderFactory factory, final String key, final Map<String, Long> values, final Boolean allowNullValues) {

        if (values != null) {

            final JsonObjectBuilder mapBuilder = factory.createObjectBuilder();
            for (final Map.Entry<String, Long> entry : values.entrySet()) {

                if (entry.getKey() == null ) {
                    continue;
                }else if(entry.getValue() == null ){
                    if(allowNullValues)
                        mapBuilder.add(entry.getKey(),JsonValue.NULL);
                }else{
                    mapBuilder.add(entry.getKey(), entry.getValue());
                }
            }

            builder.add(key, mapBuilder);

        }else if(allowNullValues){
            builder.add(key,JsonValue.NULL);
        }
    }
 
Example #7
Source File: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testPortStatusWithNullValues() throws IOException, InitializationException {
    ProcessGroupStatus pgStatus = generateProcessGroupStatus("root", "Awesome", 1, 0);

    final Map<PropertyDescriptor, String> properties = new HashMap<>();
    properties.put(SiteToSiteUtils.BATCH_SIZE, "4");
    properties.put(SiteToSiteStatusReportingTask.COMPONENT_NAME_FILTER_REGEX, "Awesome.*");
    properties.put(SiteToSiteStatusReportingTask.COMPONENT_TYPE_FILTER_REGEX, "(InputPort)");
    properties.put(SiteToSiteStatusReportingTask.ALLOW_NULL_VALUES,"true");
    MockSiteToSiteStatusReportingTask task = initTask(properties, pgStatus);
    task.onTrigger(context);

    final String msg = new String(task.dataSent.get(0), StandardCharsets.UTF_8);
    JsonReader jsonReader = Json.createReader(new ByteArrayInputStream(msg.getBytes()));
    JsonObject object = jsonReader.readArray().getJsonObject(0);
    JsonValue activeThreadCount = object.get("activeThreadCount");
    assertEquals(activeThreadCount, JsonValue.NULL);
}
 
Example #8
Source File: JavaxJsonDeserializer.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "unchecked" )
private <T> T doGuessDeserialize( ModuleDescriptor module, ValueType valueType, JsonValue json )
{
    switch( json.getValueType() )
    {
        case OBJECT:
            JsonObject object = (JsonObject) json;
            String typeInfo = object.getString( settings.getTypeInfoPropertyName(),
                                                valueType.primaryType().getName() );
            StatefulAssociationCompositeDescriptor descriptor = statefulCompositeDescriptorFor( module, typeInfo );
            if( descriptor != null )
            {
                return (T) deserializeStatefulAssociationValue( ( (CompositeDescriptor) descriptor ).module(),
                                                                descriptor.valueType(),
                                                                object );
            }
        default:
            throw new SerializationException( "Don't know how to deserialize " + valueType + " from " + json );
    }
}
 
Example #9
Source File: TwitterStatusListener.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void onStatus(Status status) {		
	task.setSourceOutage(false);
	String json = TwitterObjectFactory.getRawJSON(status);
	JsonObject originalDoc = Json.createReader(new StringReader(json)).readObject();
	for (Predicate<JsonObject> filter : filters) {
		if (!filter.test(originalDoc)) {
			//logger.info(originalDoc.get("text").toString() + ": failed on filter = " + filter.getFilterName());
			return;
		}
	}
	JsonObjectBuilder builder = Json.createObjectBuilder();
	for (Entry<String, JsonValue> entry: originalDoc.entrySet())
		builder.add(entry.getKey(), entry.getValue());
	builder.add("aidr", aidr);
	JsonObject doc = builder.build();
	for (Publisher p : publishers)
		p.publish(channelName, doc);			
}
 
Example #10
Source File: JsonValueResolver.java    From trimou with Apache License 2.0 6 votes vote down vote up
private Object unwrapJsonValueIfNecessary(JsonValue jsonValue) {
    switch (jsonValue.getValueType()) {
    case STRING:
        return ((JsonString) jsonValue).getString();
    case NUMBER:
        return ((JsonNumber) jsonValue).bigDecimalValue();
    case TRUE:
        return Boolean.TRUE;
    case FALSE:
        return Boolean.FALSE;
    case NULL:
        return Placeholder.NULL;
    default:
        return jsonValue;
    }

}
 
Example #11
Source File: ApiParameters.java    From FHIR with Apache License 2.0 6 votes vote down vote up
public static ApiParameters parse(JsonObject jsonObject) {
    ApiParameters.Builder builder =
            ApiParameters.builder();

    JsonValue t = jsonObject.get("request");
    if (t != null) {
        String request = jsonObject.getString("request");
        builder.request(request);
    }

    t = jsonObject.get("request_status");
    if (t != null) {
        int status = jsonObject.getInt("request_status", -100000000);
        if (status != -100000000) {
            builder.status(status);
        }
    }
    return builder.build();
}
 
Example #12
Source File: NetworkConfig.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private Map<String, JsonObject> findCertificateAuthorities() throws NetworkConfigurationException {
    Map<String, JsonObject> ret = new HashMap<>();

    JsonObject jsonCertificateAuthorities = getJsonObject(jsonConfig, "certificateAuthorities");
    if (null != jsonCertificateAuthorities) {

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

            JsonObject jsonCA = getJsonValueAsObject(entry.getValue());
            if (jsonCA == null) {
                throw new NetworkConfigurationException(format("Error loading config. Invalid CA entry: %s", name));
            }
            ret.put(name, jsonCA);
        }
    }

    return ret;

}
 
Example #13
Source File: JsonpRuntime.java    From jmespath-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public JmesPathType typeOf(JsonValue value) {
  switch (value.getValueType()) {
    case ARRAY:
      return JmesPathType.ARRAY;
    case OBJECT:
      return JmesPathType.OBJECT;
    case STRING:
      return JmesPathType.STRING;
    case FALSE:
    case TRUE:
      return JmesPathType.BOOLEAN;
    case NULL:
      return JmesPathType.NULL;
    case NUMBER:
      return JmesPathType.NUMBER;
    default:
      throw new IllegalStateException(String.format("Unknown node type encountered: %s", value.getValueType()));
  }
}
 
Example #14
Source File: QueryParser.java    From ecosys with Apache License 2.0 6 votes vote down vote up
private static JsonObjectBuilder addValue(JsonObjectBuilder obj, String key, Object value) {
  if (value instanceof Integer) {
    obj.add(key, (Integer)value);
  }
  else if (value instanceof String) {
    obj.add(key, (String)value);
  }
  else if (value instanceof Float) {
    obj.add(key, (Float)value);
  }
  else if (value instanceof Double) {
    obj.add(key, (Double)value);
  }
  else if (value instanceof Boolean) {
    obj.add(key, (Boolean)value);
  }
  else if (value instanceof JsonValue) {
    JsonValue val = (JsonValue)value;
    obj.add(key, val);
  }
  return obj;
}
 
Example #15
Source File: JwtClaimsBuilderImpl.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
private static Object convertJsonValue(JsonValue jsonValue) {
    if (jsonValue instanceof JsonString) {
        String jsonString = jsonValue.toString();
        return jsonString.toString().substring(1, jsonString.length() - 1);
    } else if (jsonValue instanceof JsonNumber) {
        JsonNumber jsonNumber = (JsonNumber) jsonValue;
        if (jsonNumber.isIntegral()) {
            return jsonNumber.longValue();
        } else {
            return jsonNumber.doubleValue();
        }
    } else if (jsonValue == JsonValue.TRUE) {
        return true;
    } else if (jsonValue == JsonValue.FALSE) {
        return false;
    } else {
        return null;
    }
}
 
Example #16
Source File: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoteProcessGroupStatusWithNullValues() throws IOException, InitializationException {
    final ProcessGroupStatus pgStatus = generateProcessGroupStatus("root", "Awesome", 1, 0);

    final Map<PropertyDescriptor, String> properties = new HashMap<>();
    properties.put(SiteToSiteUtils.BATCH_SIZE, "4");
    properties.put(SiteToSiteStatusReportingTask.COMPONENT_NAME_FILTER_REGEX, "Awesome.*");
    properties.put(SiteToSiteStatusReportingTask.COMPONENT_TYPE_FILTER_REGEX, "(RemoteProcessGroup)");
    properties.put(SiteToSiteStatusReportingTask.ALLOW_NULL_VALUES,"true");

    MockSiteToSiteStatusReportingTask task = initTask(properties, pgStatus);
    task.onTrigger(context);

    assertEquals(3, task.dataSent.size());
    final String msg = new String(task.dataSent.get(0), StandardCharsets.UTF_8);
    JsonReader jsonReader = Json.createReader(new ByteArrayInputStream(msg.getBytes()));
    JsonObject firstElement = jsonReader.readArray().getJsonObject(0);
    JsonValue targetURI = firstElement.get("targetURI");
    assertEquals(targetURI, JsonValue.NULL);
}
 
Example #17
Source File: JsonUtilsTests.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrapClaimValueCollection() {
    JsonArray expResult = Json.createArrayBuilder()
            .add("a")
            .add("b")
            .add("c")
            .build();
    JsonValue result = JsonUtils.wrapValue(Arrays.asList("a", "b", "c"));

    assertTrue(result instanceof JsonArray);
    JsonArray resultArray = result.asJsonArray();
    assertEquals(expResult.size(), resultArray.size());
    assertEquals(expResult.getString(0), resultArray.getString(0));
    assertEquals(expResult.getString(1), resultArray.getString(1));
    assertEquals(expResult.getString(2), resultArray.getString(2));
}
 
Example #18
Source File: JsonUtil.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new object builder.
 * @param jso the object used to populate the builder
 * @return the builder
 */
public static JsonObjectBuilder newObjectBuilder(JsonObject jso) {
  JsonObjectBuilder jb = Json.createObjectBuilder();
  if (jso != null) {
    for (Entry<String, JsonValue> entry: jso.entrySet()) {
      jb.add(entry.getKey(), entry.getValue());
    }
  }
  return jb;
}
 
Example #19
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 #20
Source File: FHIRUtil.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static JsonObjectBuilder toJsonObjectBuilder(JsonObject jsonObject) {
    JsonObjectBuilder builder = BUILDER_FACTORY.createObjectBuilder();
    // JsonObject is a Map<String, JsonValue>
    for (String key : jsonObject.keySet()) {
        JsonValue value = jsonObject.get(key);
        builder.add(key, value);
    }
    return builder;
}
 
Example #21
Source File: AbstractSiteToSiteReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected void addField(final JsonObjectBuilder builder, final String key, final Boolean value, final boolean allowNullValues) {
    if (value != null) {
        builder.add(key, value);
    }else if(allowNullValues){
        builder.add(key,JsonValue.NULL);
    }
}
 
Example #22
Source File: NetworkConfig.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void createAllOrganizations(Map<String, JsonObject> foundCertificateAuthorities) throws NetworkConfigurationException {

        // Sanity check
        if (organizations != null) {
            throw new NetworkConfigurationException("INTERNAL ERROR: organizations have already been initialized!");
        }

        organizations = new HashMap<>();

        // organizations is a JSON object containing a nested object for each Org
        JsonObject jsonOrganizations = getJsonObject(jsonConfig, "organizations");

        if (jsonOrganizations != null) {

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

                JsonObject jsonOrg = getJsonValueAsObject(entry.getValue());
                if (jsonOrg == null) {
                    throw new NetworkConfigurationException(format("Error loading config. Invalid Organization entry: %s", orgName));
                }

                OrgInfo org = createOrg(orgName, jsonOrg, foundCertificateAuthorities);
                organizations.put(orgName, org);
            }
        }

    }
 
Example #23
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 #24
Source File: JsonObjectReader.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private Object buildValue(Location location, JsonObject value, FieldInfo field) {
    Location fieldLocation = new Location(field.getType(), location.getDescription() + "." + field.getName());
    JsonValue jsonFieldValue = value.get(field.getName());
    if (jsonFieldValue == null) {
        if (field.isNonNull())
            throw new GraphQlClientException("missing " + fieldLocation);
        return null;
    }
    return readJson(fieldLocation, field.getType(), jsonFieldValue);
}
 
Example #25
Source File: Kitap.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private boolean hasSelectedProperty(final JsonObject stream) {
    return ofNullable(stream.getJsonObject("schema"))
            .map(schema -> schema.getJsonObject("properties"))
            .map(properties -> properties
                    .values()
                    .stream()
                    .filter(prop -> prop.getValueType() == JsonValue.ValueType.OBJECT)
                    .anyMatch(prop -> prop.asJsonObject().getBoolean("selected", false)))
            .orElse(false);
}
 
Example #26
Source File: WebHCatJsonParser.java    From hadoop-etl-udfs with MIT License 5 votes vote down vote up
public static List<HCatSerDeParameter> parseSerDeParameters(JsonObject obj) {
    List<HCatSerDeParameter> serDeParameters = new ArrayList<>();
    for (Entry<String, JsonValue> serdeParam : obj.entrySet()) {
        assert(serdeParam.getValue().getValueType() == ValueType.STRING);
        serDeParameters.add(new HCatSerDeParameter(serdeParam.getKey(), ((JsonString)serdeParam.getValue()).getString()));
    }
    return serDeParameters;
}
 
Example #27
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 #28
Source File: JsonUtilsTests.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrapClaimValueNumberDecimal() {
    JsonValue expResult = Json.createValue(1.1d);
    JsonValue result = JsonUtils.wrapValue(1.1d);

    assertEquals(expResult, result);
}
 
Example #29
Source File: InputsHandler.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
public InputFactory asInputFactory() {
    return name -> {
        final BaseIOHandler.IO ref = connections.get(getActualName(name));
        if (ref == null || !ref.hasNext()) {
            return null;
        }

        final Object value = ref.next();
        if (value instanceof Record) {
            return value;
        }
        final Object convertedValue;
        final RecordConverters.MappingMeta mappingMeta = registry.find(value.getClass(), () -> recordBuilderMapper);
        if (mappingMeta.isLinearMapping()) {
            convertedValue = value;
        } else {
            if (value instanceof javax.json.JsonValue) {
                if (JsonValue.NULL == value) { // JsonObject cant take a JsonValue so pass null
                    return null;
                }
                convertedValue = value.toString();
            } else {
                convertedValue = jsonb.toJson(value);
            }
        }

        return converters.toRecord(registry, convertedValue, () -> jsonb, () -> recordBuilderMapper);
    };
}
 
Example #30
Source File: WebSocketMessage.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
public JsonObject getJsonObject(String key){
    if(!object.containsKey(key)){
        return null;
    }

    JsonValue jsonValue = object.get(key);

    if(jsonValue.getValueType().equals(JsonValue.ValueType.OBJECT)){
        return object.getJsonObject(key);
    }

    return null;
}