javax.json.JsonObjectBuilder Java Examples
The following examples show how to use
javax.json.JsonObjectBuilder.
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: RevocationRequest.java From fabric-sdk-java with Apache License 2.0 | 7 votes |
private JsonObject toJsonObject() { JsonObjectBuilder factory = Json.createObjectBuilder(); if (enrollmentID != null) { // revoke all enrollments of this user, serial and aki are ignored in this case factory.add("id", enrollmentID); } else { // revoke one particular enrollment factory.add("serial", serial); factory.add("aki", aki); } if (null != reason) { factory.add("reason", reason); } if (caName != null) { factory.add(HFCAClient.FABRIC_CA_REQPROP, caName); } if (genCRL != null) { factory.add("gencrl", genCRL); } return factory.build(); }
Example #2
Source File: SmallRyeHealthReporter.java From smallrye-health with Apache License 2.0 | 6 votes |
private JsonObject jsonObject(HealthCheckResponse response) { JsonObjectBuilder builder = jsonProvider.createObjectBuilder(); builder.add("name", response.getName()); builder.add("status", response.getState().toString()); response.getData().ifPresent(d -> { JsonObjectBuilder data = jsonProvider.createObjectBuilder(); for (Map.Entry<String, Object> entry : d.entrySet()) { Object value = entry.getValue(); if (value instanceof String) { data.add(entry.getKey(), (String) value); } else if (value instanceof Long) { data.add(entry.getKey(), (Long) value); } else if (value instanceof Boolean) { data.add(entry.getKey(), (Boolean) value); } } builder.add("data", data.build()); }); return builder.build(); }
Example #3
Source File: ConfigurationLoader.java From openwebbeans-meecrowave with Apache License 2.0 | 6 votes |
private JsonObject doMerge(final JsonBuilderFactory jsonFactory, final JsonObject template, final JsonObject currentRoute) { if (currentRoute == null) { return template; } if (template == null) { return currentRoute; } return Stream.concat(template.keySet().stream(), currentRoute.keySet().stream()) .distinct() .collect(Collector.of(jsonFactory::createObjectBuilder, (builder, key) -> { final JsonValue templateValue = template.get(key); final JsonValue value = ofNullable(currentRoute.get(key)).orElse(templateValue); switch (value.getValueType()) { case NULL: break; case OBJECT: builder.add(key, templateValue != null ? doMerge(jsonFactory, templateValue.asJsonObject(), value.asJsonObject()) : value); break; default: // primitives + array, get or replace logic since it is "values" builder.add(key, value); break; } }, JsonObjectBuilder::addAll, JsonObjectBuilder::build)); }
Example #4
Source File: Message.java From sample-room-java with Apache License 2.0 | 6 votes |
/** * Create an event targeted at a specific player (still use broadcast to send to * all connections) * * @return constructed message */ public static Message createSpecificEvent(String userid, String messageForUser) { // player,<userId>,{ // "type": "event", // "content": { // "<userId>": "specific to player" // }, // "bookmark": "String representing last message seen" // } JsonObjectBuilder payload = Json.createObjectBuilder(); payload.add(TYPE, EVENT); JsonObjectBuilder content = Json.createObjectBuilder(); content.add(userid, messageForUser); payload.add(CONTENT, content.build()); payload.add(BOOKMARK, PREFIX + bookmark.incrementAndGet()); return new Message(Target.player, userid, payload.build().toString()); }
Example #5
Source File: AdminResource.java From eplmp with Eclipse Public License 1.0 | 6 votes |
@GET @Path("products-stats") @ApiOperation(value = "Get products stats", response = String.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful retrieval of products statistics"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 403, message = "Forbidden"), @ApiResponse(code = 500, message = "Internal server error") }) @Produces(MediaType.APPLICATION_JSON) public JsonObject getProductsStats() throws EntityNotFoundException, UserNotActiveException, WorkspaceNotEnabledException { JsonObjectBuilder productsStats = Json.createObjectBuilder(); Workspace[] allWorkspaces = userManager.getAdministratedWorkspaces(); for (Workspace workspace : allWorkspaces) { int productsCount = productService.getConfigurationItems(workspace.getId()).size(); productsStats.add(workspace.getId(), productsCount); } return productsStats.build(); }
Example #6
Source File: Config.java From rapid with MIT License | 6 votes |
@DELETE @Path("{id}") public Response deleteConfig(@PathParam("id") String configId) { WebTarget target = resource().path(CONFIGS).path(configId); Response response = deleteResponse(target); String entity = response.readEntity(String.class); if (entity.isEmpty()) { JsonObjectBuilder jsonObject = Json.createObjectBuilder(); jsonObject.add("id", configId); jsonObject.add("message", "the config is deleted."); return Response.ok(jsonObject.build()).build(); } try (JsonReader json = Json.createReader(new StringReader(entity))) { return Response.status(response.getStatus()).entity(json.read()).build(); } }
Example #7
Source File: FilteredUriBuilder.java From docker-java-api with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Adds a JSON encoded `filters` parameter. * @param filters Filters. */ private void addFilters(final Map<String, Iterable<String>> filters) { if (filters != null && !filters.isEmpty()) { final JsonObjectBuilder json = Json.createObjectBuilder(); filters.forEach( (name, values) -> { final JsonArrayBuilder array = Json.createArrayBuilder(); values.forEach(array::add); json.add(name, array); } ); this.origin.addParameter("filters", json.build().toString()); } }
Example #8
Source File: APIConnectAdapter.java From FHIR with Apache License 2.0 | 6 votes |
private static JsonObjectBuilder buildExecuteInvoke() { JsonObjectBuilder headerControl = factory.createObjectBuilder() .add("type", "blacklist") .add("values", factory.createArrayBuilder()); JsonObjectBuilder paramControl = factory.createObjectBuilder() .add("type", "whitelist") .add("values", factory.createArrayBuilder()); return factory.createObjectBuilder() .add("version", "2.0.0") .add("title", "invoke") .add("header-control", headerControl) .add("parameter-control",paramControl) .add("timeout", 60) .add("verb", "keep") .add("cache-response", "protocol") .add("cache-ttl", 900) .add("stop-on-error", factory.createArrayBuilder()) .add("target-url", "$(target-url)$(api.operation.path)$(request.search)"); }
Example #9
Source File: MocoServerConfigWriter.java From tcases with MIT License | 6 votes |
/** * Returns the JSON object that represents the expected header parameters for the given request case. */ private Optional<JsonObject> expectedHeaders( RequestCase requestCase) { JsonObjectBuilder headers = Json.createObjectBuilder(); toStream( requestCase.getParams()) .filter( param -> param.getLocation() == HEADER) .forEach( param -> TestWriterUtils.getHeaderParameterValue( param).ifPresent( value -> headers.add( param.getName(), value))); Optional.ofNullable( requestCase.getBody()) .flatMap( body -> Optional.ofNullable( body.getMediaType())) .ifPresent( mediaType -> { JsonObjectBuilder contentType = Json.createObjectBuilder(); contentType.add( "contain", mediaType); headers.add( "Content-Type", contentType.build()); }); return Optional.of( headers.build()).filter( json -> !json.isEmpty()); }
Example #10
Source File: FruitResource.java From quarkus with Apache License 2.0 | 6 votes |
@Override public Response toResponse(Exception exception) { LOG.error("Failed to handle request", exception); int code = 500; if (exception instanceof WebApplicationException) { code = ((WebApplicationException) exception).getResponse().getStatus(); } JsonObjectBuilder entityBuilder = Json.createObjectBuilder() .add("exceptionType", exception.getClass().getName()) .add("code", code); if (exception.getMessage() != null) { entityBuilder.add("error", exception.getMessage()); } return Response.status(code) .type(MediaType.APPLICATION_JSON) .entity(entityBuilder.build()) .build(); }
Example #11
Source File: TestAzureLogAnalyticsProvenanceReportingTask.java From nifi with Apache License 2.0 | 6 votes |
@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 #12
Source File: BundleTest.java From FHIR with Apache License 2.0 | 6 votes |
@Test(groups = { "batch" }) public void testInvalidResource() throws Exception { WebTarget target = getWebTarget(); JsonObjectBuilder bundleObject = TestUtil.getEmptyBundleJsonObjectBuilder(); JsonObject PatientJsonObject = TestUtil.readJsonObject("InvalidPatient.json"); JsonObject requestJsonObject = TestUtil.getRequestJsonObject("POST", "Patient"); JsonObjectBuilder resourceObject = Json.createBuilderFactory(null).createObjectBuilder(); resourceObject.add( "resource", PatientJsonObject).add("request", requestJsonObject); bundleObject.add("Entry", Json.createBuilderFactory(null).createArrayBuilder().add(resourceObject)); Entity<JsonObject> entity = Entity.entity(bundleObject.build(), FHIRMediaType.APPLICATION_FHIR_JSON); Response response = target.request().post(entity, Response.class); assertTrue(response.getStatus() >= 400); }
Example #13
Source File: AbstractEmbeddedDBAccess.java From jcypher with Apache License 2.0 | 6 votes |
private void init(Node node) { JsonObjectBuilder nd = Json.createObjectBuilder(); nd.add("id", String.valueOf(node.getId())); JsonArrayBuilder labels = Json.createArrayBuilder(); Iterator<Label> lblIter = node.getLabels().iterator(); boolean hasLabels = false; while (lblIter.hasNext()) { hasLabels = true; Label lab = lblIter.next(); labels.add(lab.name()); } if (hasLabels) nd.add("labels", labels); JsonObjectBuilder props = Json.createObjectBuilder(); Iterator<String> pit = node.getPropertyKeys().iterator(); while (pit.hasNext()) { String pKey = pit.next(); Object pval = node.getProperty(pKey); writeLiteral(pKey, pval, props); } nd.add("properties", props); this.nodeObject = nd; }
Example #14
Source File: NotificationUtil.java From dependency-track with Apache License 2.0 | 6 votes |
public static JsonObject toJson(final Project project) { final JsonObjectBuilder projectBuilder = Json.createObjectBuilder(); projectBuilder.add("uuid", project.getUuid().toString()); JsonUtil.add(projectBuilder, "name", project.getName()); JsonUtil.add(projectBuilder, "version", project.getVersion()); JsonUtil.add(projectBuilder, "description", project.getDescription()); JsonUtil.add(projectBuilder, "purl", project.getPurl()); if (project.getTags() != null && project.getTags().size() > 0) { final StringBuilder sb = new StringBuilder(); for (final Tag tag: project.getTags()) { sb.append(tag.getName()).append(","); } String tags = sb.toString(); if (tags.endsWith(",")) { tags = tags.substring(0, tags.length()-1); } JsonUtil.add(projectBuilder, "tags", tags); } return projectBuilder.build(); }
Example #15
Source File: ConnectionView.java From activemq-artemis with Apache License 2.0 | 6 votes |
@Override public JsonObjectBuilder toJson(RemotingConnection connection) { List<ServerSession> sessions = server.getSessions(connection.getID().toString()); Set<String> users = new TreeSet<>(); String jmsSessionClientID = null; for (ServerSession session : sessions) { String username = session.getUsername() == null ? "" : session.getUsername(); users.add(username); //for the special case for JMS if (session.getMetaData(ClientSession.JMS_SESSION_IDENTIFIER_PROPERTY) != null) { jmsSessionClientID = session.getMetaData("jms-client-id"); } } return JsonLoader.createObjectBuilder().add("connectionID", toString(connection.getID())) .add("remoteAddress", toString(connection.getRemoteAddress())) .add("users", StringUtil.joinStringList(users, ",")) .add("creationTime", new Date(connection.getCreationTime()).toString()) .add("implementation", toString(connection.getClass().getSimpleName())) .add("protocol", toString(connection.getProtocolName())) .add("clientID", toString(connection.getClientID() != null ? connection.getClientID() : jmsSessionClientID)) .add("localAddress", toString(connection.getTransportLocalAddress())) .add("sessionCount", sessions.size()); }
Example #16
Source File: RTCMediaStreamTrackStats.java From KITE with Apache License 2.0 | 6 votes |
@Override public JsonObjectBuilder getJsonObjectBuilder() { return Json.createObjectBuilder() .add("trackIdentifier", this.trackIdentifier) .add("remoteSource", this.remoteSource) .add("ended", this.ended) .add("detached", this.detached) .add("frameWidth", this.frameWidth) .add("frameHeight", this.frameHeight) .add("framesPerSecond", this.framesPerSecond) .add("framesSent", this.framesSent) .add("framesReceived", this.framesReceived) .add("frameHeight", this.frameHeight) .add("framesDecoded", this.framesDecoded) .add("framesDropped", this.framesDropped) .add("framesCorrupted", this.framesCorrupted) .add("audioLevel", this.audioLevel) .add("timestamp", this.timestamp); }
Example #17
Source File: JSONEntityState.java From attic-polygene-java with Apache License 2.0 | 6 votes |
private boolean stateCloneWithProperty( String stateName, JsonValue value ) { JsonObject valueState = state.getJsonObject( JSONKeys.VALUE ); if( Objects.equals( valueState.get( stateName ), value ) ) { return false; } JsonObjectBuilder valueBuilder = jsonFactories.cloneBuilderExclude( valueState, stateName ); if( value == null ) { valueBuilder.addNull( stateName ); } else { valueBuilder.add( stateName, value ); } state = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE ) .add( JSONKeys.VALUE, valueBuilder.build() ) .build(); return true; }
Example #18
Source File: SystemInputJson.java From tcases with MIT License | 6 votes |
/** * Returns the JSON object that represents the given variable definition. */ private static JsonStructure toJson( IVarDef varDef) { JsonObjectBuilder builder = Json.createObjectBuilder(); addAnnotations( builder, varDef); ConditionJson.toJson( varDef).ifPresent( json -> builder.add( WHEN_KEY, json)); if( varDef.getValues() != null) { JsonObjectBuilder valuesBuilder = Json.createObjectBuilder(); toStream( varDef.getValues()).forEach( value -> valuesBuilder.add( String.valueOf( value.getName()), toJson( value))); builder.add( VALUES_KEY, valuesBuilder.build()); } else if( varDef.getMembers() != null) { JsonObjectBuilder membersBuilder = Json.createObjectBuilder(); toStream( varDef.getMembers()).forEach( member -> membersBuilder.add( member.getName(), toJson( member))); builder.add( MEMBERS_KEY, membersBuilder.build()); } return builder.build(); }
Example #19
Source File: CoreMainResource.java From camel-quarkus with Apache License 2.0 | 6 votes |
@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 #20
Source File: ConcatProcessor.java From component-runtime with Apache License 2.0 | 6 votes |
@ElementListener public void cat(@Input("str1") final JsonObject str1, @Input("str2") final JsonObject str2, @Output final OutputEmitter<JsonObject> concat) { if (str1 == null && str2 == null) { return; } final JsonObjectBuilder builder = factory.createObjectBuilder(); if (str1 != null) { str1.keySet().forEach(k -> builder.add(k, str1.get(k))); } if (str2 != null) { str2.keySet().forEach(k -> builder.add(k, str2.get(k))); } concat.emit(builder.build()); }
Example #21
Source File: MetricBuilder.java From nifi with Apache License 2.0 | 5 votes |
public JsonObject build(final boolean allowNullValues) { JsonObjectBuilder metricValueBuilder = this.metricValue == null && allowNullValues? factory.createObjectBuilder() .add(String.valueOf(timestamp), JsonValue.NULL): factory.createObjectBuilder() .add(String.valueOf(timestamp), this.metricValue); return factory.createObjectBuilder() .add(MetricFields.METRIC_NAME, metricName) .add(MetricFields.APP_ID, applicationId) .add(MetricFields.INSTANCE_ID, instanceId) .add(MetricFields.HOSTNAME, hostname) .add(MetricFields.TIMESTAMP, timestamp) .add(MetricFields.START_TIME, timestamp) .add(MetricFields.METRICS, metricValueBuilder) .build(); }
Example #22
Source File: CollaborativeWebSocketModuleImpl.java From eplmp with Eclipse Public License 1.0 | 5 votes |
private void onCollaborativeInviteMessage(String sender, Session session, WebSocketMessage webSocketMessage) { String invitedUser = webSocketMessage.getString("remoteUser"); JsonObject broadcastMessage = webSocketMessage.getJsonObject("broadcastMessage"); String context = broadcastMessage.getString("context"); String url = broadcastMessage.getString("url"); CollaborativeRoom room = CollaborativeRoom.getByKeyName(webSocketMessage.getString("key")); if (webSocketSessionsManager.isAllowedToReachUser(sender, invitedUser)) { if (room.getMasterName().equals(sender) && room.findUserSession(invitedUser) == null) { // the master sent the invitation // the user is not already in the room if (!room.getPendingUsers().contains(invitedUser)) { // the user is not yet in the pending list, add him. room.addPendingUser(invitedUser); } String invite = "/invite " + url + "/room/" + room.getKey(); JsonObjectBuilder b = Json.createObjectBuilder() .add("type", CHAT_MESSAGE) .add("remoteUser", sender) .add("sender", sender) .add("message", invite) .add("context", context); WebSocketMessage message = new WebSocketMessage(b.build()); webSocketSessionsManager.broadcast(invitedUser, message); broadcastNewContext(room); } } }
Example #23
Source File: Attachment.java From maven-confluence-plugin with Apache License 2.0 | 5 votes |
public JsonObject toJsonObject() { final JsonObjectBuilder extensions = Json.createObjectBuilder() .add( "mediaType", contentType) .add( "comment", comment ) ; return Json.createObjectBuilder() .add( "title", getFileName() ) //.add( "when", ISO8601Local.format(created)) .add( "extensions", extensions ) .build(); }
Example #24
Source File: TestClass2.java From jaxrs-analyzer with Apache License 2.0 | 5 votes |
@javax.ws.rs.GET public JsonObject method() { final JsonObjectBuilder objectBuilder = Json.createObjectBuilder(); objectBuilder.add("key", "value"); if ("".equals("")) objectBuilder.add("another", "value"); else objectBuilder.add("key", "test"); return objectBuilder.build(); }
Example #25
Source File: ExecutionService.java From smallrye-graphql with Apache License 2.0 | 5 votes |
private JsonObjectBuilder addErrorsToResponse(JsonObjectBuilder returnObjectBuilder, ExecutionResult executionResult) { List<GraphQLError> errors = executionResult.getErrors(); if (errors != null) { JsonArray jsonArray = errorsService.toJsonErrors(errors); if (!jsonArray.isEmpty()) { returnObjectBuilder = returnObjectBuilder.add(ERRORS, jsonArray); } return returnObjectBuilder; } else { return returnObjectBuilder; } }
Example #26
Source File: Portfolio.java From trader with Apache License 2.0 | 5 votes |
public void addStock(Stock newStock) { if (newStock != null) { String symbol = newStock.getSymbol(); if (symbol != null) { JsonObjectBuilder stocksBuilder = Json.createObjectBuilder(); if (stocks != null) { //JsonObject is immutable, so copy current "stocks" into new builder Iterator<String> iter = stocks.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); JsonObject obj = stocks.getJsonObject(key); stocksBuilder.add(key, obj); } } //can only add a JSON-P object to a JSON-P object; can't add a JSON-B object. So converting... JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add("symbol", symbol); builder.add("shares", newStock.getShares()); builder.add("commission", newStock.getCommission()); builder.add("price", newStock.getPrice()); builder.add("total", newStock.getTotal()); builder.add("date", newStock.getDate()); JsonObject stock = builder.build(); stocksBuilder.add(symbol, stock); //might be replacing an item; caller needs to do any merge (like updatePortfolio does) stocks = stocksBuilder.build(); } } }
Example #27
Source File: SiteToSiteProvenanceReportingTask.java From localization_nifi with Apache License 2.0 | 5 votes |
private static void addField(final JsonObjectBuilder builder, final JsonBuilderFactory factory, final String key, final Collection<String> values) { if (values == null) { return; } builder.add(key, createJsonArray(factory, values)); }
Example #28
Source File: JsonFormatter.java From structlog4j with MIT License | 5 votes |
@Override public final String end(Logger log, JsonObjectBuilder bld) { StringWriter stWriter = new StringWriter(); try (JsonWriter jsonWriter = Json.createWriter(stWriter)) { jsonWriter.writeObject(bld.build()); } return stWriter.toString(); }
Example #29
Source File: SmallRyeHealthReporter.java From smallrye-health with Apache License 2.0 | 5 votes |
private SmallRyeHealth createSmallRyeHealth(JsonArrayBuilder results, HealthCheckResponse.State status) { JsonObjectBuilder builder = jsonProvider.createObjectBuilder(); JsonArray checkResults = results.build(); builder.add("status", checkResults.isEmpty() ? emptyChecksOutcome : status.toString()); builder.add("checks", checkResults); return new SmallRyeHealth(builder.build()); }
Example #30
Source File: NotificationFallbackHandler.java From sample-acmegifts with Eclipse Public License 1.0 | 5 votes |
@Override public OccasionResponse handle(ExecutionContext context) { Object[] connectParameters = context.getParameters(); String message = (String) connectParameters[0]; Orchestrator orchestrator = (Orchestrator) connectParameters[1]; String jwtTokenString = (String) connectParameters[2]; String notification11ServiceUrl = (String) connectParameters[3]; String twitterRecepientHandle = (String) connectParameters[4]; JsonObjectBuilder content = Json.createObjectBuilder(); content.add(JSON_KEY_TWITTER_HANDLE, twitterRecepientHandle); content.add(JSON_KEY_TWITTER_NOTIF_MODE, JSON_KEY_TWITTER_NOTIF_MODE_POST_MENTION); content.add(JSON_KEY_MESSAGE, message); JsonObjectBuilder notification = Json.createObjectBuilder(); notification.add(JSON_KEY_NOTIFICATION, content.build()); String payload = notification.build().toString(); Response notificationResponse = null; try { notificationResponse = orchestrator.makeConnection("POST", notification11ServiceUrl, payload, jwtTokenString); } catch (IOException e) { e.printStackTrace(); } OccasionResponse occasionResponse = new OccasionResponse(notificationResponse, OccasionResponse.NOTIFICATION_TYPE_TWEET, null); return occasionResponse; }