Java Code Examples for javax.json.JsonObject#get()

The following examples show how to use javax.json.JsonObject#get() . 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: TestSiteToSiteProvenanceReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializedForm() throws IOException, InitializationException {
    final Map<PropertyDescriptor, String> properties = new HashMap<>();
    for (final PropertyDescriptor descriptor : new MockSiteToSiteProvenanceReportingTask().getSupportedPropertyDescriptors()) {
        properties.put(descriptor, descriptor.getDefaultValue());
    }
    properties.put(SiteToSiteUtils.BATCH_SIZE, "1000");

    ProvenanceEventRecord event = createProvenanceEventRecord();

    MockSiteToSiteProvenanceReportingTask task = setup(event, properties);
    task.initialize(initContext);
    task.onScheduled(confContext);
    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 object = jsonReader.readArray().getJsonObject(0);
    JsonValue details = object.get("details");
    JsonObject msgArray = object.getJsonObject("updatedAttributes");
    assertNull(details);
    assertEquals(msgArray.getString("abc"), event.getAttributes().get("abc"));
    assertNull(msgArray.get("emptyVal"));
}
 
Example 2
Source File: ConfigData.java    From FHIR with Apache License 2.0 6 votes vote down vote up
public static ConfigData parse(InputStream in)
        throws FHIRException {
    try (JsonReader jsonReader =
            JSON_READER_FACTORY.createReader(in, StandardCharsets.UTF_8)) {
        JsonObject jsonObject = jsonReader.readObject();
        ConfigData.Builder builder =
                ConfigData.builder();
        
        JsonValue v = jsonObject.get("server_startup_parameters");
        if (v != null) {
            String serverStartupParameters = jsonObject.getString("server_startup_parameters");
            builder.serverStartupParameters(serverStartupParameters);
        }

        return builder.build();
    } catch (Exception e) {
        throw new FHIRException("Problem parsing the ConfigData", e);
    }
}
 
Example 3
Source File: RobotOrdersResource.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@POST
@Path("/new")
@Consumes(MediaType.APPLICATION_JSON)
public Response createNewOrder(@Context HttpServletRequest request, JsonObject jsonEntity) {
	OpenTracingFilter.setKeepOpen(request, true);

	String customerIdStr = jsonEntity.getString(Customer.KEY_CUSTOMER_ID);
	if (customerIdStr == null) {
		return Response.status(Status.BAD_REQUEST)
				.entity(Utils.errorAsJSonString("Request did not specify customer!")).build();
	}
	Long customerId = Long.parseLong(customerIdStr);
	JsonValue jsonValue = jsonEntity.get(RobotOrder.KEY_LINE_ITEMS);
	List<RobotOrderLineItem> lineItems = jsonValue.asJsonArray().stream().map(RobotOrderLineItem::fromJSon)
			.collect(Collectors.toList());
	try {
		RobotOrder newOrder = OrderManager.getInstance().createNewOrder(customerId,
				lineItems.toArray(new RobotOrderLineItem[0]));
		OrderManager.getInstance().dispatchOrder(newOrder);
		return Response.accepted(newOrder.toJSon().build()).build();
	} catch (RejectedExecutionException e) {
		return Response.status(Status.SERVICE_UNAVAILABLE)
				.entity(Utils.errorAsJSonString("Order Service is overworked!")).build();
	}
}
 
Example 4
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 5
Source File: GeoJsonReader.java    From geojson with Apache License 2.0 5 votes vote down vote up
private void parseFeature(final JsonObject feature) {
    JsonValue geometry = feature.get(GEOMETRY);
    if (geometry != null && geometry.getValueType().equals(JsonValue.ValueType.OBJECT)) {
        parseGeometry(feature, geometry.asJsonObject());
    } else {
        JsonValue properties = feature.get(PROPERTIES);
        if(properties != null && properties.getValueType().equals(JsonValue.ValueType.OBJECT)) {
            parseNonGeometryFeature(feature, properties.asJsonObject());
        } else {
            Logging.warn(tr("Relation/non-geometry feature without properties found: {0}", feature));
        }
    }
}
 
Example 6
Source File: MigrationService.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public JsonObject renameManyAssociation( MigrationContext context, JsonObject state, String from, String to )
    throws JsonException
{
    JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
    if( valueState.containsKey( from ) )
    {
        JsonValue jsonValue = valueState.get( from );
        valueState = jsonFactories.cloneBuilderExclude( valueState, from )
                                  .add( to, jsonValue )
                                  .build();
        JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                .add( JSONKeys.VALUE, valueState )
                                                .build();
        context.markAsChanged();
        for( MigrationEvents migrationEvent : migrationEvents )
        {
            migrationEvent.manyAssociationRenamed( state.getString( JSONKeys.IDENTITY ), from, to );
        }
        return migratedState;
    }
    else
    {
        context.addFailure( "Rename many-association " + from + " to " + to );
        return state;
    }
}
 
Example 7
Source File: GeoJsonReader.java    From geojson with Apache License 2.0 5 votes vote down vote up
private void parseNonGeometryFeature(final JsonObject feature, final JsonObject properties) {
    // get relation type
    JsonValue type = properties.get(TYPE);
    if (type == null || properties.getValueType().equals(JsonValue.ValueType.STRING)) {
        Logging.warn(tr("Relation/non-geometry feature without type found: {0}", feature));
        return;
    }

    // create misc. non-geometry feature
    final Relation relation = new Relation();
    relation.put(TYPE, type.toString());
    fillTagsFromFeature(feature, relation);
    getDataSet().addPrimitive(relation);
}
 
Example 8
Source File: CadfCredential.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static CadfCredential parse(JsonObject jsonObject)
        throws FHIRException, IOException {

    CadfCredential.Builder builder =
            CadfCredential.builder();

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

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

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

    if (jsonObject.get("assertions") != null) {
        JsonArray annotations = jsonObject.getJsonArray("assertions");
        for (int i = 0; i < annotations.size(); i++) {
            JsonObject obj = (JsonObject) annotations.get(0);
            CadfMapItem mapItem = CadfMapItem.Parser.parse(obj);
            builder.assertion(mapItem);
        }
    }
    return builder.build();
}
 
Example 9
Source File: ResultAnalyzer.java    From aceql-http with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    * Returns the stack_trace in case of failure
    *
    * @return the stack_trace in case of failure, null if no stack_trace
    */
   public String getStackTrace() {

if (isInvalidJsonStream()) {
    return null;
}

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) {
	return null;
    }

    JsonString stackTrace = (JsonString) object.get("stack_trace");
    if (stackTrace == null) {
	return null;
    } else {
	return stackTrace.getString();
    }
} catch (Exception e) {
    this.parseException = e;
    return null;
}

   }
 
Example 10
Source File: UserDeserializer.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public User deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
	JsonObject jo = parser.getObject();
	String name = jo.get("name").toString().replace("\"", "");
	if (jo.get("extra") != null) {
		name = name + jo.get("extra").toString().replace("\"", "");
	}
	User u = new User(Integer.parseInt(jo.get("id").toString()), name, null);

	return u;
}
 
Example 11
Source File: generateFido2PreauthenticateChallenge.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
private JsonObject generateExtensions(ExtensionsPolicyOptions extOp, JsonObject extensionsInput){
    JsonObjectBuilder extensionJsonBuilder = Json.createObjectBuilder();

    for(Fido2Extension ext: extOp.getExtensions()){
        if(ext instanceof Fido2AuthenticationExtension){
            JsonValue extensionInput = (extensionsInput == null) ? null
                    : extensionsInput.get(ext.getExtensionIdentifier());

            Object extensionChallangeObject = ext.generateChallengeInfo(extensionInput);
            if(extensionChallangeObject != null){
                if(extensionChallangeObject instanceof String){
                    extensionJsonBuilder.add(ext.getExtensionIdentifier(), (String) extensionChallangeObject);
                }
                else if(extensionChallangeObject instanceof JsonObject){
                    extensionJsonBuilder.add(ext.getExtensionIdentifier(), (JsonObject) extensionChallangeObject);
                }
                else if (extensionChallangeObject instanceof JsonValue) {
                    extensionJsonBuilder.add(ext.getExtensionIdentifier(), (JsonValue) extensionChallangeObject);
                }
                else{
                    throw new UnsupportedOperationException("Unimplemented Extension requested");
                }
            }
        }
    }

    return extensionJsonBuilder.build();
}
 
Example 12
Source File: Json2Xml.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<JsonValue> getNodeChildrenByName(JsonValue node, XSElementDeclaration childElementDeclaration) throws SAXException {
	String name=childElementDeclaration.getName();
	if (log.isTraceEnabled()) log.trace("getChildrenByName() childname ["+name+"] isParentOfSingleMultipleOccurringChildElement ["+isParentOfSingleMultipleOccurringChildElement()+"] isMultipleOccuringChildElement ["+isMultipleOccurringChildElement(name)+"] node ["+node+"]");
	try {
		if (!(node instanceof JsonObject)) {
			if (log.isTraceEnabled()) log.trace("getChildrenByName() parent node is not a JsonObject, but a ["+node.getClass().getName()+"]");
			return null;
		} 
		JsonObject o = (JsonObject)node;
		if (!o.containsKey(name)) {
			if (log.isTraceEnabled()) log.trace("getChildrenByName() no children named ["+name+"] node ["+node+"]");
			return null;
		} 
		JsonValue child = o.get(name);
		List<JsonValue> result = new LinkedList<JsonValue>(); 
		if (child instanceof JsonArray) {
			if (log.isTraceEnabled()) log.trace("getChildrenByName() child named ["+name+"] is a JsonArray, current node insertElementContainerElements ["+insertElementContainerElements+"]");
			// if it could be necessary to insert elementContainers, we cannot return them as a list of individual elements now, because then the containing element would be duplicated
			// we also cannot use the isSingleMultipleOccurringChildElement, because it is not valid yet
			if (!isMultipleOccurringChildElement(name)) {
				if (insertElementContainerElements || !strictSyntax) { 
					result.add(child);
					if (log.isTraceEnabled()) log.trace("getChildrenByName() singleMultipleOccurringChildElement ["+name+"] returning array node (insertElementContainerElements=true)");
				} else {
					throw new SAXException(MSG_EXPECTED_SINGLE_ELEMENT+" ["+name+"]");
				}
			} else {
				if (log.isTraceEnabled()) log.trace("getChildrenByName() childname ["+name+"] returning elements of array node (insertElementContainerElements=false or not singleMultipleOccurringChildElement)");
				result.addAll((JsonArray)child);
			}
			return result;
		}
		result.add(child);
		if (log.isTraceEnabled()) log.trace("getChildrenByName() name ["+name+"] returning ["+child+"]");
		return result;
	} catch (JsonException e) {
		throw new SAXException(e);
	}
}
 
Example 13
Source File: CamundaModelApiOrderEventHandler.java    From flowing-retail-old with Apache License 2.0 5 votes vote down vote up
private VariableMap getNewVariables(JsonObject event) {
  VariableMap variables = Variables.createVariables();
  if (event.get("pickId") != null) {
    variables.putValue("pickId", event.getString("pickId"));
  }
  if (event.get("shipmentId") != null) {
    variables.putValue("shipmentId", event.getString("shipmentId"));
  }
  return variables;
}
 
Example 14
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 15
Source File: FIDO2RegistrationBean.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void verifyRequiredFieldsExist(JsonObject jsonObject, String[] requiredFields){
    for(String field: requiredFields){
        JsonValue jsonValue = jsonObject.get(field);
        if(jsonValue == null || jsonValue.toString().isEmpty()){
            skfsLogger.log(skfsConstants.SKFE_LOGGER,Level.FINE, "FIDO-ERR-5011", "Missing " + field);
            throw new SKIllegalArgumentException("Missing " + field);
        }
    }
}
 
Example 16
Source File: generateFido2PreregisterChallenge_v1.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
private JsonObject generateExtensions(ExtensionsPolicyOptions extOp, JsonObject extensionsInput){
    JsonObjectBuilder extensionJsonBuilder = Json.createObjectBuilder();

    for (Fido2Extension ext : extOp.getExtensions()) {
        if (ext instanceof Fido2RegistrationExtension) {
            JsonValue extensionInput = (extensionsInput == null) ? null
                    : extensionsInput.get(ext.getExtensionIdentifier());

            Object extensionChallangeObject = ext.generateChallengeInfo(extensionInput);
            if (extensionChallangeObject != null) {
                if (extensionChallangeObject instanceof String) {
                    extensionJsonBuilder.add(ext.getExtensionIdentifier(), (String) extensionChallangeObject);
                }
                else if (extensionChallangeObject instanceof JsonObject) {
                    extensionJsonBuilder.add(ext.getExtensionIdentifier(), (JsonObject) extensionChallangeObject);
                }
                else if (extensionChallangeObject instanceof JsonValue) {
                    extensionJsonBuilder.add(ext.getExtensionIdentifier(), (JsonValue) extensionChallangeObject);
                }
                else {
                    throw new UnsupportedOperationException("Unimplemented Extension requested");
                }
            }
        }
    }

    return extensionJsonBuilder.build();
}
 
Example 17
Source File: MigrationService.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public JsonObject renameAssociation( MigrationContext context, JsonObject state, String from, String to )
    throws JsonException
{
    JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
    if( valueState.containsKey( from ) )
    {
        JsonValue jsonValue = valueState.get( from );
        valueState = jsonFactories.cloneBuilderExclude( valueState, from )
                                  .add( to, jsonValue )
                                  .build();
        JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                .add( JSONKeys.VALUE, valueState )
                                                .build();
        context.markAsChanged();
        for( MigrationEvents migrationEvent : migrationEvents )
        {
            migrationEvent.associationRenamed( state.getString( JSONKeys.IDENTITY ), from, to );
        }
        return migratedState;
    }
    else
    {
        context.addFailure( "Rename association " + from + " to " + to );
        return state;
    }
}
 
Example 18
Source File: Context.java    From FHIR with Apache License 2.0 4 votes vote down vote up
public static Context parse(InputStream in)
        throws FHIRException {
    try (JsonReader jsonReader =
            JSON_READER_FACTORY.createReader(in, StandardCharsets.UTF_8)) {
        JsonObject jsonObject = jsonReader.readObject();
        Context.Builder builder =
                Context.builder();

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

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

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

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

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

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

        t = jsonObject.get("api_parameters");
        if (t != null) {
            JsonObject apiParameters = jsonObject.getJsonObject("api_parameters");
            ApiParameters p = ApiParameters.Parser.parse(apiParameters);
            builder.apiParameters(p);
        }

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

        t = jsonObject.get("data");
        if (t != null) {
            JsonObject data = jsonObject.getJsonObject("data");
            Data d = Data.Parser.parse(data);
            builder.data(d);
        }

        t = jsonObject.get("batch");
        if (t != null) {
            JsonObject batch = jsonObject.getJsonObject("batch");
            Batch b = Batch.Parser.parse(batch);
            builder.batch(b);
        }

        return builder.build();
    } catch (Exception e) {
        throw new FHIRException("Problem parsing the Context", e);
    }
}
 
Example 19
Source File: ApplicationBuilder.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
/** Configures the application struucture from a JSON document.
 *
 * @param root The JSON document root.
 * @throws AssemblyException if probelms in the Assemblers provided in the JSON document.
 */
protected void configureWithJson( JsonObject root )
    throws AssemblyException
{
    JsonValue optLayers = root.get( "layers" );
    if( optLayers != null && optLayers.getValueType() == JsonValue.ValueType.ARRAY )
    {
        JsonArray layers = (JsonArray) optLayers;
        for( int i = 0; i < layers.size(); i++ )
        {
            JsonObject layerObject = layers.getJsonObject( i );
            String layerName = layerObject.getString( "name" );
            LayerDeclaration layerDeclaration = withLayer( layerName );
            JsonValue optUsing = layerObject.get( "uses" );
            if( optUsing != null && optUsing.getValueType() == JsonValue.ValueType.ARRAY )
            {
                JsonArray using = (JsonArray) optUsing;
                for( int j = 0; j < using.size(); j++ )
                {
                    layerDeclaration.using( using.getString( j ) );
                }
            }
            JsonValue optModules = layerObject.get( "modules" );
            if( optModules != null && optModules.getValueType() == JsonValue.ValueType.ARRAY )
            {
                JsonArray modules = (JsonArray) optModules;
                for( int k = 0; k < modules.size(); k++ )
                {
                    JsonObject moduleObject = modules.getJsonObject( k );
                    String moduleName = moduleObject.getString( "name" );
                    ModuleDeclaration moduleDeclaration = layerDeclaration.withModule( moduleName );
                    JsonValue optAssemblers = moduleObject.get( "assemblers" );
                    if( optAssemblers != null && optAssemblers.getValueType() == JsonValue.ValueType.ARRAY )
                    {
                        JsonArray assemblers = (JsonArray) optAssemblers;
                        for( int m = 0; m < assemblers.size(); m++ )
                        {
                            String string = assemblers.getString( m );
                            moduleDeclaration.withAssembler( string );
                        }
                    }
                }
            }
        }
    }
}
 
Example 20
Source File: ExecutionService.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
private boolean hasOperationName(JsonObject jsonInput) {
    return jsonInput.containsKey(OPERATION_NAME)
            && jsonInput.get(OPERATION_NAME) != null
            && !jsonInput.get(OPERATION_NAME).getValueType().equals(JsonValue.ValueType.NULL);
}