Java Code Examples for javax.json.JsonObjectBuilder#build()

The following examples show how to use javax.json.JsonObjectBuilder#build() . 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: CollaborativeWebSocketModuleImpl.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
private void onCollaborativeWithdrawInvitationMessage(String sender, Session session, WebSocketMessage webSocketMessage) {

        CollaborativeRoom room = CollaborativeRoom.getByKeyName(webSocketMessage.getString("key"));
        JsonObject broadcastMessage = webSocketMessage.getJsonObject("broadcastMessage");
        String context = broadcastMessage.getString("context");
        String pendingUser = webSocketMessage.getString("remoteUser");

        if (room.getMasterName().equals(sender)) {
            // the master sent the invitation
            room.removePendingUser(pendingUser);
            // Send chat message
            JsonObjectBuilder b = Json.createObjectBuilder()
                    .add("type", CHAT_MESSAGE)
                    .add("remoteUser", sender)
                    .add("sender", sender)
                    .add("message", "/withdrawInvitation")
                    .add("context", context);
            WebSocketMessage message = new WebSocketMessage(b.build());
            webSocketSessionsManager.broadcast(pendingUser, message);

            broadcastNewContext(room);
        }


    }
 
Example 2
Source File: AdminResource.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@GET
@Path("documents-stats")
@ApiOperation(value = "Get documents stats",
        response = String.class)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful retrieval of documents statistics"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getDocumentsStats()
        throws EntityNotFoundException, AccessRightException, UserNotActiveException, WorkspaceNotEnabledException {

    JsonObjectBuilder docStats = Json.createObjectBuilder();

    Workspace[] allWorkspaces = userManager.getAdministratedWorkspaces();

    for (Workspace workspace : allWorkspaces) {
        int documentsCount = documentService.getDocumentsInWorkspaceCount(workspace.getId());
        docStats.add(workspace.getId(), documentsCount);
    }

    return docStats.build();

}
 
Example 3
Source File: NotificationUtil.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
public static JsonObject toJson(final Vulnerability vulnerability) {
    final JsonObjectBuilder vulnerabilityBuilder = Json.createObjectBuilder();
    vulnerabilityBuilder.add("uuid", vulnerability.getUuid().toString());
    JsonUtil.add(vulnerabilityBuilder, "vulnId", vulnerability.getVulnId());
    JsonUtil.add(vulnerabilityBuilder, "source", vulnerability.getSource());
    JsonUtil.add(vulnerabilityBuilder, "title", vulnerability.getTitle());
    JsonUtil.add(vulnerabilityBuilder, "subtitle", vulnerability.getSubTitle());
    JsonUtil.add(vulnerabilityBuilder, "description", vulnerability.getDescription());
    JsonUtil.add(vulnerabilityBuilder, "recommendation", vulnerability.getRecommendation());
    JsonUtil.add(vulnerabilityBuilder, "cvssv2", vulnerability.getCvssV2BaseScore());
    JsonUtil.add(vulnerabilityBuilder, "cvssv3", vulnerability.getCvssV3BaseScore());
    JsonUtil.add(vulnerabilityBuilder, "severity",  vulnerability.getSeverity());
    if (vulnerability.getCwe() != null) {
        final JsonObject cweNode = Json.createObjectBuilder()
                .add("cweId", vulnerability.getCwe().getCweId())
                .add("name", vulnerability.getCwe().getName())
                .build();
        vulnerabilityBuilder.add("cwe", cweNode);
    }
    return vulnerabilityBuilder.build();
}
 
Example 4
Source File: ActivatorDetailDescriptor.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
public JsonObject toJson()
{
    JsonObjectBuilder builder = Json.createObjectBuilder();
    if( service() != null )
    {
        builder.add( "service", service().toString() );
    }
    if( importedService() != null )
    {
        builder.add( "importedService", importedService().toString() );
    }
    if( module() != null )
    {
        builder.add( "module", module().toString() );
    }
    if( layer() != null )
    {
        builder.add( "layer", layer().toString() );
    }
    if( application() != null )
    {
        builder.add( "application", application().toString() );
    }
    return builder.build();
}
 
Example 5
Source File: TestAzureLogAnalyticsProvenanceReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddField1() throws IOException, InterruptedException, InitializationException {

    final Map<String, Object> config = Collections.emptyMap();
    final JsonBuilderFactory factory = Json.createBuilderFactory(config);
    final JsonObjectBuilder builder = factory.createObjectBuilder();
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, "TestKeyString", "StringValue", true);
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, "TestKeyInteger", 2674440, true);
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, "TestKeyLong", 1289904147324L, true);
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, "TestKeyBoolean", true, true);
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, "TestKeyNotSupportedObject", 1.25, true);
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, "TestKeyNull", null, true);
    javax.json.JsonObject actualJson = builder.build();
    String expectedjsonString = "{" +
                                    "\"TestKeyString\": \"StringValue\"," +
                                    "\"TestKeyInteger\": 2674440," +
                                    "\"TestKeyLong\": 1289904147324," +
                                    "\"TestKeyBoolean\": true," +
                                    "\"TestKeyNotSupportedObject\": \"1.25\"," +
                                    "\"TestKeyNull\": null" +
                                "}";
    JsonObject expectedJson = new Gson().fromJson(expectedjsonString, JsonObject.class);
    assertEquals(expectedJson.toString(), actualJson.toString());
}
 
Example 6
Source File: SystemTestJson.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the JSON object that represents the given variable binding.
 */
private static JsonStructure toJson( VarBinding binding)
  {
  JsonObjectBuilder builder = Json.createObjectBuilder();

  addAnnotations( builder, binding);
  
  if( binding.isValueNA())
    {
    builder.add( NA_KEY, true);
    }
  else
    {
    if( !binding.isValueValid())
      {
      builder.add( FAILURE_KEY, true);
      }
    builder.add( VALUE_KEY, String.valueOf( binding.getValue()));
    }

  return builder.build();
  }
 
Example 7
Source File: GeneratorSetJson.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the JSON object that represents the given generator.
 */
private static JsonStructure toJson( ITestCaseGenerator generator)
  {
  JsonObjectBuilder builder = Json.createObjectBuilder();

  if( generator.getClass().equals( TupleGenerator.class))
    {
    TupleGenerator tupleGenerator = (TupleGenerator) generator;
    builder.add( TUPLES_KEY, tupleGenerator.getDefaultTupleSize());
    Optional.ofNullable( tupleGenerator.getRandomSeed()).ifPresent( seed -> builder.add( SEED_KEY, seed));
    
    JsonArrayBuilder combinersBuilder = Json.createArrayBuilder();
    tupleGenerator.getCombiners().stream().forEach( combiner -> combinersBuilder.add( toJson( combiner)));
    JsonArray combiners = combinersBuilder.build();
    if( !combiners.isEmpty())
      {
      builder.add( COMBINERS_KEY, combiners);
      }
    }

  return builder.build();
  }
 
Example 8
Source File: IdemixCredRequest.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
public JsonObject toJsonObject() {
    JsonObjectBuilder factory = Json.createObjectBuilder();
    if (nym != null) {
        JsonObjectBuilder factory2 = Json.createObjectBuilder();
        factory2.add("x", Base64.getEncoder().encodeToString(IdemixUtils.bigToBytes(nym.getX())));
        factory2.add("y", Base64.getEncoder().encodeToString(IdemixUtils.bigToBytes(nym.getY())));
        factory.add("nym", factory2.build());
    }

    if (issuerNonce != null) {
        String b64encoded = Base64.getEncoder().encodeToString(IdemixUtils.bigToBytes(issuerNonce));
        factory.add("issuer_nonce", b64encoded);
    }

    if (proofC != null) {
        factory.add("proof_c", Base64.getEncoder().encodeToString(IdemixUtils.bigToBytes(proofC)));
    }

    if (proofS != null) {
        factory.add("proof_s", Base64.getEncoder().encodeToString(IdemixUtils.bigToBytes(proofS)));
    }

    return factory.build();
}
 
Example 9
Source File: CoreMainResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Path("/context/reactive-executor")
@GET
@Produces(MediaType.TEXT_PLAIN)
public JsonObject reactiveExecutor() {
    ReactiveExecutor executor = main.getCamelContext().adapt(ExtendedCamelContext.class).getReactiveExecutor();

    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add("class", executor.getClass().getName());

    if (executor instanceof VertXReactiveExecutor) {
        builder.add("configured", ((VertXReactiveExecutor) executor).getVertx() != null);

    }

    return builder.build();
}
 
Example 10
Source File: SystemTestJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Add any annotatations from the given Annotated object to the given JsonObjectBuilder.
 */
private static JsonObjectBuilder addAnnotations( JsonObjectBuilder builder, IAnnotated annotated)
  {
  JsonObjectBuilder annotations = Json.createObjectBuilder();
  toStream( annotated.getAnnotations()).forEach( name -> annotations.add( name, annotated.getAnnotation( name)));
  JsonObject json = annotations.build();

  if( !json.isEmpty())
    {
    builder.add( HAS_KEY, json);
    }

  return builder;
  }
 
Example 11
Source File: CommunicationManager.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * getThingDescriptions - Return all pages of the thing descriptions of IoT object(s).
 * 
 * @param sourceObjectId 
 * 
 * @return The list of thing descriptions 
 */
public Representation getThingDescriptions(String sourceObjectId) {
	
	if (sourceObjectId == null || sourceObjectId.isEmpty()) {
		logger.warning("Method parameter sourceObjectId can't be null nor empty.");
		
		return null;
	}
	
	JsonObjectBuilder mainObjectBuilder = Json.createObjectBuilder();
	JsonArrayBuilder mainArrayBuilder = Json.createArrayBuilder();
	
	Representation r = null;
	int i = 0;
	
	do {
		
		r = getThingDescriptions(sourceObjectId, i++);
		
		if (r == null) {
			break;
		}
		
		JsonArray tds = parseThingDescriptionsFromRepresentation(r);
		tds.forEach(item -> {
			mainArrayBuilder.add(item);
		});
	}
	while (true);
	
	mainObjectBuilder.add(ATTR_TDS, mainArrayBuilder);
	JsonObject json = mainObjectBuilder.build();
	
	return new JsonRepresentation(json.toString());
}
 
Example 12
Source File: StatusWebSocketModuleImpl.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
private WebSocketMessage createMessage(String type, String remoteUser, boolean onlineStatus){

        JsonObjectBuilder b = Json.createObjectBuilder()
                .add("type",type)
                .add("remoteUser", remoteUser)
                .add("status",onlineStatus ? USER_STATUS_ONLINE:USER_STATUS_OFFLINE);

        return new WebSocketMessage(b.build());
    }
 
Example 13
Source File: Merged.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Ctor.
 * @param objects JsonObjects to combine.
 */
Merged(final JsonObject... objects) {
    super(() -> {
        final JsonObjectBuilder combined = Json.createObjectBuilder();
        for(final JsonObject json : objects) {
            json.forEach(combined::add);
        }
        return combined.build();
    });
}
 
Example 14
Source File: ExecutionErrorsService.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private JsonObject toJsonError(GraphQLError error) {
    String json = JSONB.toJson(error.toSpecification());
    try (StringReader sr = new StringReader(json); JsonReader reader = jsonReaderFactory.createReader(sr)) {

        JsonObject jsonErrors = reader.readObject();

        JsonObjectBuilder resultBuilder = jsonBuilderFactory.createObjectBuilder(jsonErrors);

        getOptionalExtensions(error).ifPresent(jsonObject -> resultBuilder.add(EXTENSIONS, jsonObject));
        return resultBuilder.build();
    }
}
 
Example 15
Source File: JavaxJsonCollectionSerializationTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Test
public void dontKnowHowToDeserializeMapWithMixedKeys()
{
    JsonObjectBuilder fooKeyBuilder = jsonFactories.builderFactory().createObjectBuilder();
    fooKeyBuilder.add( "foo", "foo" );
    fooKeyBuilder.add( "_type", SomeValue.class.getName() );
    JsonObject fooKey = fooKeyBuilder.build();

    JsonObjectBuilder fooEntryBuilder = jsonFactories.builderFactory().createObjectBuilder();
    fooEntryBuilder.add( "key", fooKey );
    fooEntryBuilder.add( "value", "bar" );
    JsonObject fooEntry = fooEntryBuilder.build();

    JsonObjectBuilder bazEntryBuilder = jsonFactories.builderFactory().createObjectBuilder();
    bazEntryBuilder.add( "key", "baz" );
    bazEntryBuilder.add( "value", "bazar" );
    JsonObject bazEntry = bazEntryBuilder.build();

    JsonArrayBuilder arrayBuilder = jsonFactories.builderFactory().createArrayBuilder();
    arrayBuilder.add( fooEntry );
    arrayBuilder.add( bazEntry );
    JsonArray jsonArray = arrayBuilder.build();

    MapType mapType = MapType.of( ValueType.OBJECT, ValueType.STRING );
    try
    {
        jsonSerialization.fromJson( module, mapType, jsonArray );
        fail( "Should have failed deserialization" );
    }
    catch( SerializationException ex )
    {
        assertThat( ex.getMessage(),
                    equalTo( "Don't know how to deserialize java.lang.Object from \"baz\"" ) );
    }
}
 
Example 16
Source File: GeneratorSetJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the JSON object that represents the given once tuple.
 */
private static JsonStructure toJson( TupleRef tuple)
  {
  JsonObjectBuilder builder = Json.createObjectBuilder();

  toStream( tuple.getVarBindings()).forEach( binding -> builder.add( binding.getVar(), String.valueOf( binding.getValue())));
  
  return builder.build();
  }
 
Example 17
Source File: JsonMarshaller.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
private JsonObject marshal(Event event) {
    JsonObjectBuilder json = Json.createObjectBuilder();
    addTimestamp(event, json);
    for (String key : event.getPropertyNames()) {
        Object value = event.getProperty(key);
        key = replaceDotsByUnderscores ? key.replace('.','_') : key;
        marshalAttribute(json, key, value);
    }
    return json.build();
}
 
Example 18
Source File: CdiExecutionTest.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
private JsonObject toJsonObject(String graphQL) {
    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add("query", graphQL);
    return builder.build();
}
 
Example 19
Source File: JSONManyAssociationStateTest.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Test
public void givenJSONManyAssociationStateWhenChangingReferencesExpectCorrectBehavior()
{
    // Fake JSONManyAssociationState
    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add( JSONKeys.VALUE, Json.createObjectBuilder().build() );
    JsonObject state = builder.build();
    JSONEntityState entityState = new JSONEntityState( module,
                                                       serialization,
                                                       jsonFactories,
                                                       "0",
                                                       SystemTime.now(),
                                                       EntityReference.parseEntityReference( "123" ),
                                                       EntityStatus.NEW,
                                                       null,
                                                       state );
    JSONManyAssociationState jsonState = new JSONManyAssociationState( jsonFactories, entityState, "under-test" );

    assertThat( jsonState.contains( EntityReference.parseEntityReference( "NOT_PRESENT" ) ), is( false ) );

    jsonState.add( 0, EntityReference.parseEntityReference( "0" ) );
    jsonState.add( 1, EntityReference.parseEntityReference( "1" ) );
    jsonState.add( 2, EntityReference.parseEntityReference( "2" ) );

    assertThat( jsonState.contains( EntityReference.parseEntityReference( "1" ) ), is( true ) );

    assertThat( jsonState.get( 0 ).identity().toString(), equalTo( "0" ) );
    assertThat( jsonState.get( 1 ).identity().toString(), equalTo( "1" ) );
    assertThat( jsonState.get( 2 ).identity().toString(), equalTo( "2" ) );

    assertThat( jsonState.count(), equalTo( 3 ) );

    jsonState.remove( EntityReference.parseEntityReference( "1" ) );

    assertThat( jsonState.count(), equalTo( 2 ) );
    assertThat( jsonState.contains( EntityReference.parseEntityReference( "1" ) ), is( false ) );
    assertThat( jsonState.get( 0 ).identity().toString(), equalTo( "0" ) );
    assertThat( jsonState.get( 1 ).identity().toString(), equalTo( "2" ) );

    jsonState.add( 2, EntityReference.parseEntityReference( "1" ) );

    assertThat( jsonState.count(), equalTo( 3 ) );

    jsonState.add( 0, EntityReference.parseEntityReference( "A" ) );
    jsonState.add( 0, EntityReference.parseEntityReference( "B" ) );
    jsonState.add( 0, EntityReference.parseEntityReference( "C" ) );

    assertThat( jsonState.count(), equalTo( 6 ) );

    assertThat( jsonState.get( 0 ).identity().toString(), equalTo( "C" ) );
    assertThat( jsonState.get( 1 ).identity().toString(), equalTo( "B" ) );
    assertThat( jsonState.get( 2 ).identity().toString(), equalTo( "A" ) );

    assertThat( jsonState.contains( EntityReference.parseEntityReference( "C" ) ), is( true ) );
    assertThat( jsonState.contains( EntityReference.parseEntityReference( "B" ) ), is( true ) );
    assertThat( jsonState.contains( EntityReference.parseEntityReference( "A" ) ), is( true ) );
    assertThat( jsonState.contains( EntityReference.parseEntityReference( "0" ) ), is( true ) );
    assertThat( jsonState.contains( EntityReference.parseEntityReference( "2" ) ), is( true ) );
    assertThat( jsonState.contains( EntityReference.parseEntityReference( "1" ) ), is( true ) );

    List<String> refList = new ArrayList<>();
    for( EntityReference ref : jsonState )
    {
        refList.add( ref.identity().toString() );
    }
    assertThat( refList.isEmpty(), is( false ) );
    assertArrayEquals( new String[]
                           {
                               "C", "B", "A", "0", "2", "1"
                           }, refList.toArray() );
}
 
Example 20
Source File: FHIROpenApiGenerator.java    From FHIR with Apache License 2.0 4 votes vote down vote up
private static void generatePaths(Class<?> modelClass, JsonObjectBuilder paths, Filter filter) throws Exception {
    JsonObjectBuilder path = factory.createObjectBuilder();
    // FHIR create operation
    if (filter.acceptOperation(modelClass, "create")) {
        generateCreatePathItem(modelClass, path);
    }
    // FHIR search operation
    if (filter.acceptOperation(modelClass, "search")) {
        generateSearchPathItem(modelClass, path);
    }
    JsonObject pathObject = path.build();
    if (!pathObject.isEmpty()) {
        paths.add("/" + modelClass.getSimpleName(), pathObject);
    }

    path = factory.createObjectBuilder();
    // FHIR vread operation
    if (filter.acceptOperation(modelClass, "vread")) {
        generateVreadPathItem(modelClass, path);
    }
    pathObject = path.build();
    if (!pathObject.isEmpty()) {
        paths.add("/" + modelClass.getSimpleName() + "/{id}/_history/{vid}", pathObject);
    }

    path = factory.createObjectBuilder();
    // FHIR read operation
    if (filter.acceptOperation(modelClass, "read")) {
        generateReadPathItem(modelClass, path);
    }
    // FHIR update operation
    if (filter.acceptOperation(modelClass, "update")) {
        generateUpdatePathItem(modelClass, path);
    }
    // FHIR delete operation
    if (filter.acceptOperation(modelClass, "delete") && includeDeleteOperation) {
        generateDeletePathItem(modelClass, path);
    }
    pathObject = path.build();
    if (!pathObject.isEmpty()) {
        paths.add("/" + modelClass.getSimpleName() + "/{id}", pathObject);
    }

    // FHIR history operation
    path = factory.createObjectBuilder();
    if (filter.acceptOperation(modelClass, "history")) {
        generateHistoryPathItem(modelClass, path);
    }
    pathObject = path.build();
    if (!pathObject.isEmpty()) {
        paths.add("/" + modelClass.getSimpleName() + "/{id}/_history", pathObject);
    }

    // TODO: add patch
}