javax.json.JsonString Java Examples

The following examples show how to use javax.json.JsonString. 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: JsonpRuntime.java    From jmespath-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public boolean isTruthy(JsonValue value) {
  switch (value.getValueType()) {
    case FALSE:
    case NULL:
      return false;
    case NUMBER:
    case TRUE:
      return true;
    case ARRAY:
      return ((JsonArray) value).size() > 0;
    case OBJECT:
      return ((JsonObject) value).size() > 0;
    case STRING:
      return ((JsonString) value).getString().length() > 0;
    default:
      throw new IllegalStateException(String.format("Unknown node type encountered: %s", value.getValueType()));
  }
}
 
Example #2
Source File: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testComponentNameFilter_nested() throws IOException, InitializationException {
    final ProcessGroupStatus pgStatus = generateProcessGroupStatus("root", "Awesome", 2, 0);

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

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

    assertEquals(10, task.dataSent.size());  // 3 + (3 * 3) + (3 * 3 * 3) = 39, or 10 batches of 4
    final String msg = new String(task.dataSent.get(0), StandardCharsets.UTF_8);
    JsonReader jsonReader = Json.createReader(new ByteArrayInputStream(msg.getBytes()));
    JsonString componentId = jsonReader.readArray().getJsonObject(0).getJsonString("componentId");
    assertEquals("root.1.1.processor.1", componentId.getString());
}
 
Example #3
Source File: QueueConfiguration.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns a {@code QueueConfiguration} created from the JSON-formatted input {@code String}. The input
 * should be a simple object of key/value pairs. Valid keys are referenced in {@link #set(String, String)}.
 *
 * @param jsonString
 * @return the {@code QueueConfiguration} created from the JSON-formatted input {@code String}
 */
public static QueueConfiguration fromJSON(String jsonString) {
   JsonObject json = JsonLoader.createReader(new StringReader(jsonString)).readObject();

   // name is the only required value
   if (!json.keySet().contains(NAME)) {
      return null;
   }
   QueueConfiguration result = new QueueConfiguration(json.getString(NAME));

   for (Map.Entry<String, JsonValue> entry : json.entrySet()) {
      result.set(entry.getKey(), entry.getValue().getValueType() == JsonValue.ValueType.STRING ? ((JsonString)entry.getValue()).getString() : entry.getValue().toString());
   }

   return result;
}
 
Example #4
Source File: RawClaimTypeProducer.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Produces
@Claim("")
String getClaimAsString(InjectionPoint ip) {
    CDILogging.log.getClaimAsString(ip);
    if (currentToken == null) {
        return null;
    }

    String name = getName(ip);
    Optional<Object> optValue = currentToken.claim(name);
    String returnValue = null;
    if (optValue.isPresent()) {
        Object value = optValue.get();
        if (value instanceof JsonString) {
            JsonString jsonValue = (JsonString) value;
            returnValue = jsonValue.getString();
        } else {
            returnValue = value.toString();
        }
    }
    return returnValue;
}
 
Example #5
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 #6
Source File: ClaimInjectionTest.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Test
public void injectSet() {
    MatcherAssert.assertThat(claimsBean.getSetClaim(), hasItems("value0", "value1", "value2"));
    MatcherAssert.assertThat(claimsBean.getSetClaimValue().getValue(), hasItems("value0", "value1", "value2"));
    MatcherAssert.assertThat(claimsBean.getSetOptional().get(), hasItems("value0", "value1", "value2"));
    MatcherAssert.assertThat(claimsBean.getSetClaimValueOptional().getValue().get(),
            hasItems("value0", "value1", "value2"));

    MatcherAssert.assertThat(claimsBean.getSetJson().getValuesAs(JsonString::getString),
            hasItems("value0", "value1", "value2"));
    MatcherAssert.assertThat(claimsBean.getSetOptionalJson().get().getValuesAs(JsonString::getString),
            hasItems("value0", "value1", "value2"));
    MatcherAssert.assertThat(claimsBean.getSetClaimValueJson().getValue().getValuesAs(JsonString::getString),
            hasItems("value0", "value1", "value2"));
    MatcherAssert.assertThat(claimsBean.getSetClaimValueOptionalJson().getValue().get().getValuesAs(JsonString::getString),
            hasItems("value0", "value1", "value2"));

    MatcherAssert.assertThat(claimBeanInstance.getSetClaim().get(),
            hasItems("value0", "value1", "value2"));
    MatcherAssert.assertThat(claimBeanInstance.getSetOptional().get().get(),
            hasItems("value0", "value1", "value2"));
    MatcherAssert.assertThat(claimBeanInstance.getSetJson().get().getValuesAs(JsonString::getString),
            hasItems("value0", "value1", "value2"));
    MatcherAssert.assertThat(claimBeanInstance.getSetOptionalJson().get().get().getValuesAs(JsonString::getString),
            hasItems("value0", "value1", "value2"));
}
 
Example #7
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 #8
Source File: Message.java    From diirt with MIT License 6 votes vote down vote up
/**
 * Converts the given JSON value to either a vtype, a Java time or a
 * ListNumber.
 *
 * @param msgValue the JSON value
 * @return the converted type
 */
public static Object readValueFromJson(JsonValue msgValue) {
    if (msgValue instanceof JsonObject) {
        return VTypeToJson.toVType((JsonObject) msgValue);
    } else if (msgValue instanceof JsonNumber) {
        return ((JsonNumber) msgValue).doubleValue();
    } else if (msgValue instanceof JsonString){
        return ((JsonString) msgValue).getString();
    } else if (msgValue instanceof JsonArray){
        JsonArray array = (JsonArray) msgValue;
        if (isNumericArray(array)) {
            return toListDouble(array);
        } else if (isStringArray(array)) {
            return toListString(array);
        } else {
            return null;
        }
    } else {
        return null;
    }
}
 
Example #9
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 #10
Source File: JsonValuejectionEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/verifyInjectedAudience")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("Tester")
public JsonObject verifyInjectedAudience(@QueryParam("aud") String audience) {
    boolean pass = false;
    String msg;
    // aud
    List<JsonString> audValue = aud.getValuesAs(JsonString.class);
    if (audValue == null || audValue.size() == 0) {
        msg = Claims.aud.name() + "value is null or empty, FAIL";
    } else if (audValue.get(0).getString().equals(audience)) {
        msg = Claims.aud.name() + " PASS";
        pass = true;
    } else {
        msg = String.format("%s: %s != %s", Claims.aud.name(), audValue, audience);
    }
    JsonObject result = Json.createObjectBuilder()
            .add("pass", pass)
            .add("msg", msg)
            .build();
    return result;
}
 
Example #11
Source File: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testPortStatus() 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,"false");

    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);
    JsonString runStatus = object.getJsonString("runStatus");
    assertEquals(RunStatus.Stopped.name(), runStatus.getString());
    boolean isTransmitting = object.getBoolean("transmitting");
    assertFalse(isTransmitting);
    JsonNumber inputBytes = object.getJsonNumber("inputBytes");
    assertEquals(5, inputBytes.intValue());
    assertNull(object.get("activeThreadCount"));
}
 
Example #12
Source File: ResultAnalyzer.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    * Says if status is OK
    *
    * @return true if status is OK
    */
   public boolean isStatusOk() {

if (jsonResult == null || jsonResult.isEmpty()) {
    return false;
}

try {
    JsonReader reader = Json.createReader(new StringReader(jsonResult));
    JsonStructure jsonst = reader.read();

    JsonObject object = (JsonObject) jsonst;
    JsonString status = (JsonString) object.get("status");

    if (status != null && status.getString().equals("OK")) {
	return true;
    } else {
	return false;
    }
} catch (Exception e) {
    this.parseException = e;
    invalidJsonStream = true;
    return false;
}

   }
 
Example #13
Source File: Json2Xml.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
public String getNodeText(XSElementDeclaration elementDeclaration, JsonValue node) {
	String result;
	if (node instanceof JsonString) {
		result=((JsonString)node).getString();
	} else if (node instanceof JsonStructure) { // this happens when override key is present without a value
		result=null; 
	} else { 
		result=node.toString();
	}
	if ("{}".equals(result)) {
		result="";
	}
	if (log.isTraceEnabled()) log.trace("getText() node ["+ToStringBuilder.reflectionToString(node)+"] = ["+result+"]");
	return result;
}
 
Example #14
Source File: CustomJsonAdapterTest.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@Test
public void customJsonAdapterForDirectObject()
{
    CustomValue customValueObject = new CustomValue( "custom-value-state" );
    JsonValue serialized = serialization.toJson( customValueObject );
    assertThat( serialized.getValueType(), is( JsonValue.ValueType.STRING ) );
    JsonString jsonString = (JsonString) serialized;
    assertThat( jsonString.getString(), equalTo( "custom-value-state" ) );

    CustomStructure customStructureObject = new CustomStructure( "foo", LocalDate.of( 2017, 1, 1 ) );
    serialized = serialization.toJson( customStructureObject );
    assertThat( serialized.getValueType(), is( JsonValue.ValueType.OBJECT ) );
    JsonObject jsonObject = (JsonObject) serialized;
    assertThat( jsonObject.getString( "foo" ), equalTo( "foo" ) );
    assertThat( jsonObject.getString( "bar" ), equalTo( "2017-01-01" ) );
}
 
Example #15
Source File: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoteProcessGroupStatus() 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)");

    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);
    JsonNumber activeThreadCount = firstElement.getJsonNumber("activeThreadCount");
    assertEquals(1L, activeThreadCount.longValue());
    JsonString transmissionStatus = firstElement.getJsonString("transmissionStatus");
    assertEquals("Transmitting", transmissionStatus.getString());
}
 
Example #16
Source File: CrossDomainConfigTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void marshal() {
    CrossDomainConfig config = new CrossDomainConfig();
    config.setAllowedMethods(Arrays.asList("GET", "OPTIONS"));
    config.setAllowedOrigins(Arrays.asList("a", "b"));
    config.setAllowedHeaders(Arrays.asList("A", "B"));
    config.setAllowCredentials(Boolean.TRUE);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JaxbUtil.marshal(config, out);

    JsonObject result = Json.createReader(new ByteArrayInputStream(out.toByteArray())).readObject();

    assertThat(result.getJsonArray("allowedMethods").getValuesAs(JsonString.class)).containsExactlyInAnyOrder(Json.createValue("GET"), Json.createValue("OPTIONS"));
    assertThat(result.getJsonArray("allowedOrigins").getValuesAs(JsonString.class)).containsExactlyInAnyOrder(Json.createValue("a"), Json.createValue("b"));
    assertThat(result.getJsonArray("allowedHeaders").getValuesAs(JsonString.class)).containsExactlyInAnyOrder(Json.createValue("A"), Json.createValue("B"));
    assertThat(result.get("allowCredentials")).isEqualTo(JsonValue.TRUE);
}
 
Example #17
Source File: RecordConverters.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Object mapJson(final RecordBuilderFactory factory, final JsonValue it) {
    if (JsonObject.class.isInstance(it)) {
        return json2Record(factory, JsonObject.class.cast(it));
    }
    if (JsonArray.class.isInstance(it)) {
        return JsonArray.class.cast(it).stream().map(i -> mapJson(factory, i)).collect(toList());
    }
    if (JsonString.class.isInstance(it)) {
        return JsonString.class.cast(it).getString();
    }
    if (JsonNumber.class.isInstance(it)) {
        return JsonNumber.class.cast(it).numberValue();
    }
    if (JsonValue.FALSE.equals(it)) {
        return false;
    }
    if (JsonValue.TRUE.equals(it)) {
        return true;
    }
    if (JsonValue.NULL.equals(it)) {
        return null;
    }
    return it;
}
 
Example #18
Source File: CryptographyPolicyOptions.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static CryptographyPolicyOptions parse(JsonObject cryptoJson) {
    CryptographyPolicyOptionsBuilder cryptoPolicyBuilder =
            new CryptographyPolicyOptions.CryptographyPolicyOptionsBuilder(
            new ArrayList<>(cryptoJson.getJsonArray(skfsConstants.POLICY_CRYPTO_ATTESTATION_FORMATS).stream().map(x -> ((JsonString) x).getString()).collect(Collectors.toList())),
            new ArrayList<>(cryptoJson.getJsonArray(skfsConstants.POLICY_CRYPTO_ATTESTATION_TYPES).stream().map(x -> ((JsonString) x).getString()).collect(Collectors.toList())));
    if(cryptoJson.getJsonArray(skfsConstants.POLICY_CRYPTO_ALLOWED_EC_SIGNATURES) != null){
        cryptoPolicyBuilder.setAllowedECSignatures(new ArrayList<>(cryptoJson.getJsonArray(skfsConstants.POLICY_CRYPTO_ALLOWED_EC_SIGNATURES).stream().map(x -> ((JsonString) x).getString()).collect(Collectors.toList())));
    }
    if(cryptoJson.getJsonArray(skfsConstants.POLICY_CRYPTO_ALLOWED_RSA_SIGNATURES) != null){
        cryptoPolicyBuilder.setAllowedRSASignatures(new ArrayList<>(cryptoJson.getJsonArray(skfsConstants.POLICY_CRYPTO_ALLOWED_RSA_SIGNATURES).stream().map(x -> ((JsonString) x).getString()).collect(Collectors.toList())));
    }
    if(cryptoJson.getJsonArray(skfsConstants.POLICY_CRYPTO_ELLIPTIC_CURVES) != null){
        cryptoPolicyBuilder.setSupportedEllipticCurves(new ArrayList<>(cryptoJson.getJsonArray(skfsConstants.POLICY_CRYPTO_ELLIPTIC_CURVES).stream().map(x -> ((JsonString) x).getString()).collect(Collectors.toList())));
    }
    return cryptoPolicyBuilder.build();
}
 
Example #19
Source File: OAuth2Test.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
private void validateJwt(final ClientAccessToken token) {
    final JwtParser parser = new JwtParser();
    final KidMapper kidMapper = new KidMapper();
    final DateValidator dateValidator = new DateValidator();
    final SignatureValidator signatureValidator = new SignatureValidator();
    final GeronimoJwtAuthConfig config = (value, def) -> {
        switch (value) {
            case "issuer.default":
                return "myissuer";
            case "jwt.header.kid.default":
                return "defaultkid";
            case "public-key.default":
                return Base64.getEncoder().encodeToString(PUBLIC_KEY.getEncoded());
            default:
                return def;
        }
    };
    setField(kidMapper, "config", config);
    setField(dateValidator, "config", config);
    setField(parser, "config", config);
    setField(signatureValidator, "config", config);
    setField(parser, "kidMapper", kidMapper);
    setField(parser, "dateValidator", dateValidator);
    setField(parser, "signatureValidator", signatureValidator);
    Stream.of(dateValidator, signatureValidator, kidMapper, parser).forEach(this::init);
    final JsonWebToken jsonWebToken = parser.parse(token.getTokenKey());
    assertNotNull(jsonWebToken);
    assertEquals("myissuer", jsonWebToken.getIssuer());
    assertEquals("test", JsonString.class.cast(jsonWebToken.getClaim("username")).getString());
}
 
Example #20
Source File: ProjectJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the reference base URI represented by the given JSON string.
 */
private static URI asRefBase( JsonString uri)
  {
  try
    {
    return
      uri == null
      ? null
      : new URI( uri.getChars().toString());
    }
  catch( Exception e)
    {
    throw new ProjectException( String.format( "Error defining reference base=%s", uri), e);
    }
  }
 
Example #21
Source File: CodeGenerator.java    From FHIR with Apache License 2.0 5 votes vote down vote up
private List<String> getReferenceTypes(JsonObject elementDefinition) {
    List<String> referenceTypes = new ArrayList<>();
    for (JsonValue type : elementDefinition.getOrDefault("type", JsonArray.EMPTY_JSON_ARRAY).asJsonArray()) {
        for (JsonValue targetProfile : type.asJsonObject().getOrDefault("targetProfile", JsonArray.EMPTY_JSON_ARRAY).asJsonArray()) {
            String url = ((JsonString) targetProfile).getString();
            if (url.startsWith("http://hl7.org/fhir/StructureDefinition/")) {
                String referenceType = url.substring("http://hl7.org/fhir/StructureDefinition/".length());
                if (!"Resource".equals(referenceType)) {
                    referenceTypes.add(referenceType);
                }
            }
        }
    }
    return referenceTypes;
}
 
Example #22
Source File: Message.java    From diirt with MIT License 5 votes vote down vote up
/**
 * Un-marshals a string, or returns the default value if it's not able to.
 *
 * @param jObject the JSON object
 * @param name the attribute name where the string is stored
 * @param defaultValue the value to use if no attribute is found
 * @return the message string
 * @throws MessageDecodeException if the field is of the wrong type
 */
static String stringOptional(JsonObject jObject, String name, String defaultValue) throws MessageDecodeException {
    try {
        JsonString jsonString = jObject.getJsonString(name);
        if (jsonString == null) {
            return defaultValue;
        } else {
            return jsonString.getString();
        }
    } catch (ClassCastException  e) {
        throw MessageDecodeException.wrongAttributeType(jObject, name, "string");
    }
}
 
Example #23
Source File: PropertyGroup.java    From FHIR with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the specified JsonValue into the appropriate java.lang.* type.
 * @param jsonValue the JsonValue instance to be converted
 * @return an instance of Boolean, Integer, String, PropertyGroup, or List<Object>
 * @throws Exception 
 */
public static Object convertJsonValue(JsonValue jsonValue) throws Exception {
    Object result = null;
    switch (jsonValue.getValueType()) {
    case ARRAY:
        Object[] objArray = convertJsonArray((JsonArray)jsonValue);
        result = Arrays.asList(objArray);
        break;
    case OBJECT:
        result = new PropertyGroup((JsonObject) jsonValue);
        break;
    case STRING:
        result = FHIRUtilities.decode(((JsonString) jsonValue).getString());
        break;
    case NUMBER:
        JsonNumber jsonNumber = (JsonNumber) jsonValue;
        if (jsonNumber.isIntegral()) {
            result = Integer.valueOf(jsonNumber.intValue());
        } else {
            result = Double.valueOf(jsonNumber.doubleValue());
        }
        break;
    case TRUE:
        result = Boolean.TRUE;
        break;
    case FALSE:
        result = Boolean.FALSE;
        break;
    default:
        throw new IllegalStateException("Unexpected JSON value type: " + jsonValue.getValueType().name());
    }
    return result;
}
 
Example #24
Source File: MonaJsonParser.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * read from META_DATA array
 * 
 * @param main
 * @param id
 * @return String or Number or null
 */
private Object readMetaData(JsonObject main, String id) {
  JsonValue j = main.getJsonArray(META_DATA).stream().map(v -> v.asJsonObject())
      .filter(v -> v.getString("name").equals(id)).map(v -> v.get("value")).findFirst()
      .orElse(null);

  if (j != null) {
    if (j.getValueType().equals(ValueType.STRING))
      return ((JsonString) j).getString();
    if (j.getValueType().equals(ValueType.NUMBER))
      return ((JsonNumber) j).numberValue();
  }
  return null;
}
 
Example #25
Source File: JsonParser.java    From jeddict with Apache License 2.0 5 votes vote down vote up
private BeanClass generateClass(EntityMappings entityMappings, String className, JsonObject jsonObject) {
    reporter.accept(getMessage(DocWizardDescriptor.class, "MSG_Progress_Class_Parsing", className));

    BeanClass beanClass = createBeanClass(entityMappings, className);
    jsonObject.forEach((key, value) -> {
        Attribute baseAttribute;
        if (value instanceof JsonString) {
            baseAttribute = createBeanAttribute(beanClass, STRING, key);
        } else if (value instanceof JsonNumber) {
            baseAttribute = createBeanAttribute(beanClass, getJsonNumberType((JsonNumber) value), key);
        } else if (value instanceof JsonArray) {
            JsonArray jsonArray = (JsonArray) value;
            if (!jsonArray.isEmpty()) {
                JsonValue arrayElement = jsonArray.get(0);
                if (arrayElement instanceof JsonString) {
                    baseAttribute = createBeanCollection(beanClass, STRING, key);
                } else if (arrayElement instanceof JsonNumber) {
                    baseAttribute = createBeanCollection(beanClass, getJsonNumberType((JsonNumber) arrayElement), key);
                } else if (arrayElement instanceof JsonObject) {
                    baseAttribute = createOneToManyAssociation(beanClass, generateClass(entityMappings, key, (JsonObject) arrayElement), key);
                } else {
                    baseAttribute = createBeanCollection(beanClass, STRING, key);
                }
            } else {
                baseAttribute = createBeanCollection(beanClass, STRING, key);
            }
        } else if (value instanceof JsonObject) {
            baseAttribute = createOneToOneAssociation(beanClass, generateClass(entityMappings, key, (JsonObject) value), key);
        } else if (value instanceof JsonValue) {
            if (((JsonValue) value).getValueType() == TRUE || ((JsonValue) value).getValueType() == FALSE) {
                baseAttribute = createBeanAttribute(beanClass, BOOLEAN, key);
            } else {
                baseAttribute = createBeanAttribute(beanClass, STRING, key);
            }
        } else {
            baseAttribute = createBeanAttribute(beanClass, STRING, key);
        }
    });
    return beanClass;
}
 
Example #26
Source File: JsonProcessingValueConverter.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Override
public String convert(Object value) {
    if (value instanceof JsonString) {
        return ((JsonString) value).getString();
    } else if (JsonValue.NULL.equals(value)) {
        return Strings.EMPTY;
    }
    return null;
}
 
Example #27
Source File: JsonMergePatchExampleTest.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Test
public void givenPatch_sourceValueChanges() throws Exception {
    JsonMergePatchExample jsonMergePatchExample = new JsonMergePatchExample();
    JsonValue result = jsonMergePatchExample.changeValue();

    assertThat(((JsonString) result).getString()).isEqualToIgnoringCase("{\"colour\":\"red\"}");
}
 
Example #28
Source File: JsonMergeDiffExampleTest.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Test
public void givenSourceAndTarget_shouldCreateMergePatch() {
    JsonMergeDiffExample jsonMergeDiffExample = new JsonMergeDiffExample();
    JsonMergePatch mergePatch = jsonMergeDiffExample.createMergePatch();
    JsonString jsonString = (JsonString) mergePatch.toJsonValue();

    assertThat(jsonString.getString()).isEqualToIgnoringCase("{\"colour\":\"red\"}");
}
 
Example #29
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 #30
Source File: PropertyGroup.java    From FHIR with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the specified String property.  If not found, then
 * 'defaultValue' is returned instead.
 * If the value is encoded, then it will be decoded.
 * 
 * @param propertyName the name of the property to retrieve
 * @throws Exception 
 */
public String getStringProperty(String propertyName, String defaultValue) throws Exception {
    String result = defaultValue;
    JsonValue jsonValue = getJsonValue(propertyName);
    if (jsonValue != null) {
        if (jsonValue instanceof JsonString) {
            result = FHIRUtilities.decode(((JsonString) jsonValue).getString());
        } else {
            throw new IllegalArgumentException("Property '" + propertyName + "' must be of type String");
        }
    }
    return result;
}