Java Code Examples for javax.json.JsonString

The following examples show how to use javax.json.JsonString. These examples are extracted from open source projects. 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
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 2
Source Project: nifi   Source File: TestSiteToSiteStatusReportingTask.java    License: 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 Project: activemq-artemis   Source File: QueueConfiguration.java    License: 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 Project: smallrye-jwt   Source File: RawClaimTypeProducer.java    License: 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 Project: smallrye-jwt   Source File: JwtClaimsBuilderImpl.java    License: 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 Project: smallrye-jwt   Source File: ClaimInjectionTest.java    License: 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 Project: trimou   Source File: JsonValueResolver.java    License: 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 Project: diirt   Source File: Message.java    License: 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 Project: boost   Source File: PropertiesReader.java    License: 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 Project: tessera   Source File: CrossDomainConfigTest.java    License: 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 11
Source Project: quarkus   Source File: JsonValuejectionEndpoint.java    License: 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 12
Source Project: nifi   Source File: TestSiteToSiteStatusReportingTask.java    License: 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 13
/**
    * 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 14
Source Project: iaf   Source File: Json2Xml.java    License: 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 15
Source Project: attic-polygene-java   Source File: CustomJsonAdapterTest.java    License: 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 16
Source Project: nifi   Source File: TestSiteToSiteStatusReportingTask.java    License: 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 17
Source Project: component-runtime   Source File: RecordConverters.java    License: 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
@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 19
public static MdsPolicyOptions parse(JsonObject mdsJson) {
    if(mdsJson == null){
        return null;
    }

    return new MdsPolicyOptions.MdsPolicyOptionsBuilder(
            new ArrayList<>(mdsJson.getJsonArray(skfsConstants.POLICY_MDS_ENDPOINTS).stream()
                    .map(x -> (JsonObject) x)
                    .map(x -> new MDSEndpointObject(x.getString(skfsConstants.POLICY_MDS_ENDPOINT_URL, null),
                            x.getString(skfsConstants.POLICY_MDS_ENDPOINT_TOKEN, null)))
                    .collect(Collectors.toList())),
            new ArrayList<>(mdsJson.getJsonArray(skfsConstants.POLICY_MDS_CERTIFICATION).stream().map(x -> ((JsonString) x).getString()).collect(Collectors.toList())))
            .build();
}
 
Example 20
Source Project: FHIR   Source File: CodeGenerator.java    License: 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 21
Source Project: FHIR   Source File: PropertyGroup.java    License: 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;
}
 
Example 22
Source Project: diirt   Source File: Message.java    License: 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 Project: FHIR   Source File: PropertyGroup.java    License: 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 Project: FHIR   Source File: JsonSupport.java    License: Apache License 2.0 5 votes vote down vote up
public static Class<?> getResourceType(JsonObject jsonObject) {
    JsonString resourceTypeString = jsonObject.getJsonString("resourceType");
    if (resourceTypeString == null) {
        throw new IllegalArgumentException("Missing required element: 'resourceType'");
    }
    String resourceTypeName = resourceTypeString.getString();
    Class<?> resourceType = ModelSupport.getResourceType(resourceTypeName);
    if (resourceType == null) {
        throw new IllegalArgumentException("Invalid resource type: '" + resourceTypeName + "'");
    }
    return resourceType;
}
 
Example 25
Source Project: mzmine3   Source File: MonaJsonParser.java    License: 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 26
Source Project: smallrye-graphql   Source File: GraphQLVariables.java    License: Apache License 2.0 5 votes vote down vote up
private Object toObject(JsonValue jsonValue) {
    Object ret = null;
    JsonValue.ValueType typ = jsonValue.getValueType();
    if (null != typ)
        switch (typ) {
            case NUMBER:
                ret = ((JsonNumber) jsonValue).bigDecimalValue();
                break;
            case STRING:
                ret = ((JsonString) jsonValue).getString();
                break;
            case FALSE:
                ret = Boolean.FALSE;
                break;
            case TRUE:
                ret = Boolean.TRUE;
                break;
            case ARRAY:
                JsonArray arr = (JsonArray) jsonValue;
                List<Object> vals = new ArrayList<>();
                int sz = arr.size();
                for (int i = 0; i < sz; i++) {
                    JsonValue v = arr.get(i);
                    vals.add(toObject(v));
                }
                ret = vals;
                break;
            case OBJECT:
                ret = toMap((JsonObject) jsonValue);
                break;
            default:
                break;
        }
    return ret;
}
 
Example 27
Source Project: smallrye-jwt   Source File: JsonValueProducerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIssuerInjected() {
    jwtProducer = weld.select(PrincipalProducer.class).get();
    jwtProducer.setJsonWebToken(jwt);
    Mockito.when(jwt.claim(Claims.iss.name())).thenReturn(Optional.of("issuer1"));
    JsonString issuer = selectJsonValue("iss", JsonString.class);

    assertNotNull(issuer);
    assertEquals("issuer1", issuer.getString());
}
 
Example 28
Source Project: cxf   Source File: AsyncMethodTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokesGetOperationWithRegisteredProvidersAsyncCompletionStage() throws Exception {
    wireMockRule.stubFor(get(urlEqualTo("/echo/test2"))
                            .willReturn(aResponse()
                            .withBody("{\"name\": \"test\"}")));

    AsyncClientWithCompletionStage api = RestClientBuilder.newBuilder()
            .register(TestClientRequestFilter.class)
            .register(TestClientResponseFilter.class)
            .register(TestMessageBodyReader.class, 3)
            .register(TestMessageBodyWriter.class)
            .register(TestParamConverterProvider.class)
            .register(TestReaderInterceptor.class)
            .register(TestWriterInterceptor.class)
            .register(JsrJsonpProvider.class)
            .baseUri(getBaseUri())
            .build(AsyncClientWithCompletionStage.class);

    CompletionStage<JsonStructure> cs = api.get();

    // should need <1 second, but 20s timeout in case something goes wrong
    JsonStructure response = cs.toCompletableFuture().get(20, TimeUnit.SECONDS);
    assertThat(response, instanceOf(JsonObject.class));
    
    final JsonObject jsonObject = (JsonObject)response;
    assertThat(jsonObject.get("name"), instanceOf(JsonString.class));
    assertThat(((JsonString)jsonObject.get("name")).getString(), equalTo("test"));

    assertEquals(TestClientResponseFilter.getAndResetValue(), 1);
    assertEquals(TestClientRequestFilter.getAndResetValue(), 1);
    assertEquals(TestReaderInterceptor.getAndResetValue(), 1);
}
 
Example 29
/**
 * When passed <code>["value1","value2"]</code>, is executed once per array
 * element
 * @param string the parsed JsonString for each array element
 */
@ParameterizedTest
@JsonSource("[\"value1\",\"value2\"]")
@DisplayName("provides an array of strings")
void arrayOfStrings(JsonString string) {
    assertThat(string.getString()).startsWith("value");
}
 
Example 30
/**
 * When passed <code>["value1","value2"]</code>, is executed once per array
 * element
 * @param string the parsed JsonString for each array element
 */
@ParameterizedTest
@JsonFileSource(resources = "/array-of-strings.json")
@DisplayName("provides an array of strings")
void arrayOfStrings(JsonString string) {
    assertThat(string.getString()).startsWith("value");
}