Java Code Examples for javax.json.Json#createObjectBuilder()

The following examples show how to use javax.json.Json#createObjectBuilder() . 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: ReportMerger.java    From KITE with Apache License 2.0 6 votes vote down vote up
private static void updateResultFile(String pathToResultFile, String pathToOtherResultFile)
    throws IOException {
  JsonObject result = readJsonFile(pathToResultFile);
  JsonObject otherResult = readJsonFile(pathToOtherResultFile);
  JsonObjectBuilder builder = Json.createObjectBuilder();
  for (String key: result.keySet()) {
    switch (key) {
      case "steps":
      case "statusDetails":
      case "attachments":
      case "name":
      case "status":
      case "stage": {
        builder.add(key, otherResult.get(key));
        break;
      }
      default: {
        builder.add(key, result.get(key));
        break;
      }
    }
  }

  FileUtils.forceDelete(new File(pathToResultFile));
  printJsonTofile(builder.build().toString(), pathToResultFile);
}
 
Example 2
Source File: NotificationUtil.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
public static JsonObject toJson(final AnalysisDecisionChange vo) {
    final JsonObjectBuilder builder = Json.createObjectBuilder();
    if (vo.getComponent() != null) {
        builder.add("component", toJson(vo.getComponent()));
    }
    if (vo.getVulnerability() != null) {
        builder.add("vulnerability", toJson(vo.getVulnerability()));
    }
    if (vo.getAnalysis() != null) {
        builder.add("analysis", toJson(vo.getAnalysis()));
    }
    if (vo.getAffectedProjects() != null && vo.getAffectedProjects().size() > 0) {
        final JsonArrayBuilder projectsBuilder = Json.createArrayBuilder();
        for (final Project project: vo.getAffectedProjects()) {
            projectsBuilder.add(toJson(project));
        }
        builder.add("affectedProjects", projectsBuilder.build());
    }
    return builder.build();
}
 
Example 3
Source File: AdminResource.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@GET
@Path("users-stats")
@ApiOperation(value = "Get users stats",
        response = String.class)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful retrieval of user statistics"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getUsersStats()
        throws EntityNotFoundException, AccessRightException, UserNotActiveException, WorkspaceNotEnabledException {

    JsonObjectBuilder userStats = Json.createObjectBuilder();

    Workspace[] allWorkspaces = userManager.getAdministratedWorkspaces();

    for (Workspace workspace : allWorkspaces) {
        int userCount = userManager.getUsers(workspace.getId()).length;
        userStats.add(workspace.getId(), userCount);
    }

    return userStats.build();

}
 
Example 4
Source File: BulkProcessor.java    From maximorestclient with Apache License 2.0 6 votes vote down vote up
private void addMeta(JsonObjectBuilder objb, String method, String uri, String... properties){
	JsonObjectBuilder objBuilder = Json.createObjectBuilder();
	String propStr = this.propertiesBuilder(properties);
	if(propStr != null){
		objBuilder.add("properties", propStr);
	}
	if(method != null && !method.isEmpty()){
		objBuilder.add("method", method);
	}
	if(uri != null && !uri.isEmpty()){
		objBuilder.add("uri", uri);
	}
	JsonObject objMeta = objBuilder.build();
	if(!objMeta.isEmpty()){
		objb.add("_meta", objMeta);
	}
	this.bulkArray.add(objb.build());
}
 
Example 5
Source File: RealizedOrder.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public JsonObjectBuilder toJSon() {
	JsonObjectBuilder builder = Json.createObjectBuilder();
	builder.add(KEY_CUSTOMER, customer.toJSon());
	builder.add(KEY_ORDER, order.toJSon());
	builder.add(KEY_ROBOTS, serializeRobotsToJSon());
	if (error != null) {
		builder.add(Utils.KEY_ERROR, Utils.errorAsJSon(error));
	}
	return builder;
}
 
Example 6
Source File: XmlTypeToJsonSchemaConverter.java    From iaf with Apache License 2.0 5 votes vote down vote up
public void handleTerm(JsonObjectBuilder builder, XSTerm term, XSObjectList attributeUses, boolean multiOccurring, boolean forProperties) {
	if (term instanceof XSModelGroup) {
		handleModelGroup(builder, (XSModelGroup)term, attributeUses, forProperties);
		return;
	} 
	if (term instanceof XSElementDeclaration) {
		XSElementDeclaration elementDeclaration = (XSElementDeclaration)term;
		if (elementDeclaration.getScope()==XSConstants.SCOPE_GLOBAL) {
			JsonObject typeDefininition = Json.createObjectBuilder().add("$ref", "#/definitions/"+elementDeclaration.getName()).build();
			if (multiOccurring) {
				JsonObjectBuilder arrayBuilder = Json.createObjectBuilder();
				arrayBuilder.add("type", "array");
				arrayBuilder.add("items", typeDefininition);

				builder.add(elementDeclaration.getName(), arrayBuilder.build());
			} else {
				builder.add(elementDeclaration.getName(), typeDefininition);
			}
		} else {
			handleElementDeclaration(builder, elementDeclaration, multiOccurring, true);
		}
		return;
	}
	if (term instanceof XSWildcard) {
		handleWildcard((XSWildcard)term);
		return;
	} 
	throw new IllegalStateException("handleTerm unknown Term type ["+term.getClass().getName()+"]");
}
 
Example 7
Source File: ReportMerger.java    From KITE with Apache License 2.0 5 votes vote down vote up
private static void fixWrongStatus(String pathToReportFolder) throws IOException {
  File reportFolder = new File(pathToReportFolder);
  File[] subFiles = reportFolder.listFiles();
  for (int index = 0; index < subFiles.length; index++) {
    if (subFiles[index].getName().contains("result.json")) {
      JsonObject result = readJsonFile(subFiles[index].getAbsolutePath());
      JsonObject statusDetail = result.getJsonObject("statusDetails");
      String message = statusDetail.getString("message");
      boolean issue = message.equalsIgnoreCase("The test has passed successfully!")
          && !result.getString("status").equals("PASSED");
      if (issue) {
        JsonArray steps = result.getJsonArray("steps");
        for (int i = 0; i < steps.size(); i++) {
          JsonObject step = (JsonObject)steps.get(i);
          if (!step.getString("status").equals("PASSED")){
            statusDetail = step.getJsonObject("statusDetails");
            break;
          }
        }
        JsonObjectBuilder builder = Json.createObjectBuilder();
        for (String key: result.keySet()) {
          if (!key.equals("statusDetails")) {
            builder.add(key, result.get(key));
          } else {
            builder.add(key, statusDetail);
          }
        }
        FileUtils.forceDelete(new File(subFiles[index].getAbsolutePath()));
        printJsonTofile(builder.build().toString(), subFiles[index].getAbsolutePath());
      }
    }
  }
}
 
Example 8
Source File: MocoServerConfigWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the JSON object that represents the expected text request body for the given request case.
 */
private Optional<JsonValue> expectedTextBody( RequestCase requestCase)
  {
  JsonObjectBuilder textBody = Json.createObjectBuilder();

  Optional.ofNullable( requestCase.getBody())
    .filter( body -> body.getValue() != null)
    .filter( body -> body.getMediaType().startsWith( "text/"))
    .map( body -> DataValueText.toText( body.getValue()))
    .ifPresent( text -> textBody.add( "body", text));

  return Optional.ofNullable( textBody.build().get( "body"));
  }
 
Example 9
Source File: InjectedFieldDetailDescriptor.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public JsonObjectBuilder toJson()
{
    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add( "name", descriptor().field().getName() );
    builder.add( "type", descriptor().field().getType().getName() );
    return builder;
}
 
Example 10
Source File: EntityBuilder.java    From jaxrs-hypermedia with Apache License 2.0 5 votes vote down vote up
public JsonObject buildOrderTeaser(Order order, URI self) {
    final JsonObjectBuilder builder = Json.createObjectBuilder();

    builder.add("date", order.getDate().toString());
    builder.add("price", order.getPrice());
    builder.add("status", order.getStatus().name());
    builder.add("_links", Json.createObjectBuilder().add("self", self.toString()));

    return builder.build();
}
 
Example 11
Source File: SystemInputJson.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 12
Source File: MocoServerConfigWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the JSON object that represents the expected JSON request body for the given request case.
 */
private Optional<JsonObject> expectedJsonBody( RequestCase requestCase)
  {
  JsonObjectBuilder jsonBody = Json.createObjectBuilder();

  Optional.ofNullable( requestCase.getBody())
    .filter( body -> "application/json".equals( body.getMediaType()))
    .map( body -> DataValueJsonPath.expected( body.getValue()))
    .orElse( emptyList())
    .stream().forEach( entry -> jsonBody.add( entry.getKey(), entry.getValue()));

  return Optional.of( jsonBody.build()).filter( json -> !json.isEmpty());
  }
 
Example 13
Source File: SystemInputJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the JSON object that represents the function variables of the given type.
 */
private static JsonStructure toJson( FunctionInputDef functionInput, String varType)
  {
  JsonObjectBuilder builder = Json.createObjectBuilder();
  toStream( functionInput.getVarDefs())
    .filter( varDef -> varDef.getType().equals( varType))
    .sorted()
    .forEach( varDef -> builder.add( varDef.getName(), toJson( varDef)));

  return builder.build();
  }
 
Example 14
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 15
Source File: EmptyStatObject.java    From KITE with Apache License 2.0 4 votes vote down vote up
@Override
public JsonObjectBuilder getJsonObjectBuilder() {
  return Json.createObjectBuilder();
}
 
Example 16
Source File: FactoryResource.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@POST
@Path("/buildrobot")
@Produces(MediaType.APPLICATION_JSON)
public Response buildRobot(
	@Context HttpServletRequest request, @FormParam(RobotType.KEY_ROBOT_TYPE) String robotTypeId,
	@FormParam(Robot.KEY_COLOR) String color) {
	OpenTracingFilter.setKeepOpen(request, true);

	JsonObjectBuilder createObjectBuilder = Json.createObjectBuilder();

	if (robotTypeId == null) {
		return Response.status(Status.BAD_REQUEST)
				.entity(Utils.errorAsJSonString(RobotType.KEY_ROBOT_TYPE + " must not be null!")).build();
	}

	RobotType robotType = DataAccess.getRobotTypeById(robotTypeId);
	if (robotType == null) {
		return Response.status(Status.BAD_REQUEST)
				.entity(Utils.errorAsJSonString(RobotType.KEY_ROBOT_TYPE + ":" + robotTypeId + " is unknown!"))
				.build();
	}

	if (color == null) {
		return Response.status(Status.BAD_REQUEST)
				.entity(Utils.errorAsJSonString(Robot.KEY_COLOR + " must not be null!")).build();
	}

	Color paint = Color.fromString(color);
	if (paint == null) {
		return Response.status(Status.BAD_REQUEST).entity(Utils.errorAsJSonString(color + " is not a valid color!"))
				.build();
	}

	try {
		long serialNumber = Factory.getInstance().startBuildingRobot(robotTypeId, paint);
		createObjectBuilder.add(Robot.KEY_SERIAL_NUMBER, String.valueOf(serialNumber));
		return Response.accepted(createObjectBuilder.build()).build();
	} catch (RejectedExecutionException e) {
		return Response.status(Status.SERVICE_UNAVAILABLE)
				.entity(Utils.errorAsJSonString("Factory has too much work!")).build();
	}
}
 
Example 17
Source File: NeighbourhoodManagerConnector.java    From vicinity-gateway-api with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Retrieves the thing descriptions of list IoT objects from the Neighborhood Manager. 
 * 
 * @param Representation of the incoming JSON. List of OIDs
 * @return Thing descriptions of objects specified in payload.
 */
public synchronized Representation getThingDescription(String objectId){
	
	String endpointUrl = SERVER_PROTOCOL + neighbourhoodManagerServer + ":" + port + API_PATH + TD_SERVICE;
	
	ClientResource clientResource = createRequest(endpointUrl);
	
	JsonObjectBuilder mainObjectBuilder = Json.createObjectBuilder();
	JsonArrayBuilder mainArrayBuilder = Json.createArrayBuilder();
		
	mainArrayBuilder.add(
		Json.createObjectBuilder().add("oid", objectId)
	);
	
	mainObjectBuilder.add("objects", mainArrayBuilder);
	
	JsonObject payload = mainObjectBuilder.build();
	
	Representation responseRepresentation = clientResource.post(new JsonRepresentation(payload.toString()), MediaType.APPLICATION_JSON);
	
	return responseRepresentation;
	
}
 
Example 18
Source File: RequestCaseJson.java    From tcases with MIT License 4 votes vote down vote up
public void visit( ObjectValue data)
{
JsonObjectBuilder builder = Json.createObjectBuilder();
data.getValue().keySet().stream().forEach( key -> builder.add( key, RequestCaseJson.toJson( data.getValue().get( key))));
json_ = builder.build();
}
 
Example 19
Source File: DataValueJsonValue.java    From tcases with MIT License 4 votes vote down vote up
public void visit( ObjectValue data)
{
JsonObjectBuilder builder = Json.createObjectBuilder();
data.getValue().keySet().stream().forEach( key -> builder.add( key, DataValueJsonValue.toJson( data.getValue().get( key))));
json_ = builder.build();
}
 
Example 20
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() );
}