List of usage examples for javax.json Json createObjectBuilder
public static JsonObjectBuilder createObjectBuilder()
From source file:tools.xor.logic.DefaultJson.java
protected void checkDateField() throws JSONException { // create person JsonObjectBuilder jsonBuilder = Json.createObjectBuilder(); jsonBuilder.add("name", "DILIP_DALTON"); jsonBuilder.add("displayName", "Dilip Dalton"); jsonBuilder.add("description", "Software engineer in the bay area"); jsonBuilder.add("userName", "daltond"); // 1/1/15 7:00 PM EST final long CREATED_ON = 1420156800000L; Date createdOn = new Date(CREATED_ON); DateFormat df = new SimpleDateFormat(ImmutableJsonProperty.ISO8601_FORMAT); jsonBuilder.add("createdOn", df.format(createdOn)); Settings settings = new Settings(); settings.setEntityClass(Person.class); Person person = (Person) aggregateService.create(jsonBuilder.build(), settings); assert (person.getId() != null); assert (person.getName().equals("DILIP_DALTON")); assert (person.getCreatedOn().getTime() == CREATED_ON); Object jsonObject = aggregateService.read(person, settings); JsonObject json = (JsonObject) jsonObject; System.out.println("JSON string: " + json.toString()); assert (((JsonString) json.get("name")).getString().equals("DILIP_DALTON")); assert (((JsonString) json.get("createdOn")).getString().equals("2015-01-01T16:00:00.000-0800")); }
From source file:org.takes.facets.auth.social.PsTwitterTest.java
/** * PsTwitter can login./* ww w . j av a 2 s . c o m*/ * @throws IOException If error occurs in the process */ @Test public void logsIn() throws IOException { final int tid = RandomUtils.nextInt(1000); final String name = RandomStringUtils.randomAlphanumeric(10); final String picture = RandomStringUtils.randomAlphanumeric(10); final Pass pass = new PsTwitter( new FakeRequest(200, "HTTP OK", Collections.<Map.Entry<String, String>>emptyList(), String.format("{\"token_type\":\"bearer\",\"access_token\":\"%s\"}", RandomStringUtils.randomAlphanumeric(10)).getBytes()), new FakeRequest(200, "HTTP OK", Collections.<Map.Entry<String, String>>emptyList(), Json.createObjectBuilder().add("id", tid).add("name", name) .add("profile_image_url", picture).build().toString().getBytes()), RandomStringUtils.randomAlphanumeric(10), RandomStringUtils.randomAlphanumeric(10)); final Identity identity = pass.enter(new RqFake("GET", "")).get(); MatcherAssert.assertThat(identity.urn(), CoreMatchers.equalTo(String.format("urn:twitter:%d", tid))); MatcherAssert.assertThat(identity.properties().get("name"), CoreMatchers.equalTo(name)); MatcherAssert.assertThat(identity.properties().get("picture"), CoreMatchers.equalTo(picture)); }
From source file:sample.products.java
private String getResults(String query, String... params) { StringBuilder sb = new StringBuilder(); // return "s"; StringWriter out = new StringWriter(); ResultSet rs;//from w ww . ja v a2 s .c o m int rows = 0; JSONArray products = new JSONArray(); try (Connection cn = connection.getConnection()) { PreparedStatement pstmt = cn.prepareStatement(query); for (int i = 1; i <= params.length; i++) { pstmt.setString(i, params[i - 1]); } rs = pstmt.executeQuery(); if (rs.last()) { rows = rs.getRow(); } System.out.println(rows); rs.beforeFirst(); if (rows > 1) { while (rs.next()) { //sb.append(String.format("%s\t%s\t%s\t%s\n", rs.getInt("productId"), rs.getString("name"), rs.getString("description"), rs.getInt("quantity"))); JsonObject json = Json.createObjectBuilder().add("Product Id", rs.getInt("productId")) .add("Name", rs.getString("name")).add("Description", rs.getString("description")) .add("Quantity", rs.getString("quantity")).build(); products.add(json); } } else { while (rs.next()) { JsonObject json = Json.createObjectBuilder().add("Product Id", rs.getInt("productId")) .add("Name", rs.getString("name")).add("Description", rs.getString("description")) .add("Quantity", rs.getString("quantity")).build(); return json.toString(); } } } catch (SQLException ex) { Logger.getLogger(products.class.getName()).log(Level.SEVERE, null, ex); } return products.toString(); }
From source file:com.pankaj.GenericResource.java
/** * Retrieves representation of an instance of com.pankaj.GenericResource * * @return an instance of java.lang.String * @throws java.lang.ClassNotFoundException * @throws java.sql.SQLException//from w w w. j a v a 2 s.c o m * @throws java.lang.InstantiationException * @throws java.lang.IllegalAccessException */ @GET @Path("/products") @Produces(MediaType.APPLICATION_JSON) public String getAllProducts() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException { Statement smt = conn.createStatement(); ResultSet rs = smt.executeQuery("select * from product"); ResultSetMetaData rsmd = rs.getMetaData(); int col = rsmd.getColumnCount(); while (rs.next()) { product pro = new product(rs.getInt("productid"), rs.getString("name"), rs.getString("description"), rs.getInt("quantity")); products.add(pro); json = Json.createObjectBuilder().add("productID", rs.getInt("productID")) .add("name", rs.getString("name")).add("description", rs.getString("description")) .add("quantity", rs.getInt("quantity")); productarray.add(json); } String res = productarray.build().toString(); return res; }
From source file:eu.forgetit.middleware.component.Contextualizer.java
public void executeTextContextualization(Exchange exchange) { taskStep = "CONTEXTUALIZER_CONTEXTUALIZE_DOCUMENTS"; logger.debug("New message retrieved for " + taskStep); JsonObjectBuilder job = Json.createObjectBuilder(); JsonObject headers = MessageTools.getHeaders(exchange); long taskId = Long.parseLong(headers.getString("taskId")); scheduler.updateTask(taskId, TaskStatus.RUNNING, taskStep, null); JsonObject jsonBody = MessageTools.getBody(exchange); String cmisServerId = null;/* w w w .j av a2 s . c om*/ if (jsonBody != null) { cmisServerId = jsonBody.getString("cmisServerId"); JsonArray jsonEntities = jsonBody.getJsonArray("entities"); job.add("cmisServerId", cmisServerId); job.add("entities", jsonEntities); for (JsonValue jsonValue : jsonEntities) { JsonObject jsonObject = (JsonObject) jsonValue; String type = jsonObject.getString("type"); if (type.equals(Collection.class.getName())) continue; long pofId = jsonObject.getInt("pofId"); try { String collectorStorageFolder = ConfigurationManager.getConfiguration() .getString("collector.storage.folder"); Path sipPath = Paths.get(collectorStorageFolder + File.separator + pofId); Path metadataPath = Paths.get(sipPath.toString(), "metadata"); Path contentPath = Paths.get(sipPath.toString(), "content"); Path contextAnalysisPath = Paths.get(metadataPath.toString(), "worldContext.json"); logger.debug("Looking for text documents in folder: " + contentPath); List<File> documentList = getFilteredDocumentList(contentPath); logger.debug("Document List for Contextualization: " + documentList); if (documentList != null && !documentList.isEmpty()) { File[] documents = documentList.stream().toArray(File[]::new); context = service.contextualize(documents); logger.debug("World Context:\n"); for (String contextEntry : context) { logger.debug(contextEntry); } StringBuilder contextResult = new StringBuilder(); for (int i = 0; i < context.length; i++) { Map<String, String> jsonMap = new HashMap<>(); jsonMap.put("filename", documents[i].getName()); jsonMap.put("context", context[i]); contextResult.append(jsonMap.toString()); } FileUtils.writeStringToFile(contextAnalysisPath.toFile(), contextResult.toString()); logger.debug("Document Contextualization completed for " + documentList); } } catch (IOException | ResourceInstantiationException | ExecutionException e) { e.printStackTrace(); } } exchange.getOut().setBody(job.build().toString()); exchange.getOut().setHeaders(exchange.getIn().getHeaders()); } else { scheduler.updateTask(taskId, TaskStatus.FAILED, taskStep, null); job.add("Message", "Task " + taskId + " failed"); scheduler.sendMessage("activemq:queue:ERROR.QUEUE", exchange.getIn().getHeaders(), job.build()); } }
From source file:assignment5.ProductServlet.java
/** * json format taken from/*from w ww . j a v a 2 s. co m*/ * https://code.google.com/p/json-simple/wiki/EncodingExamples * * @param query * @param params * @return */ private String getResults(String query, String... params) { JsonArrayBuilder productArray = Json.createArrayBuilder(); String numChanges = new String(); try (Connection conn = credentials.getConnection()) { PreparedStatement pstmt = conn.prepareStatement(query); for (int i = 1; i <= params.length; i++) { pstmt.setString(i, params[i - 1]); } ResultSet rs = pstmt.executeQuery(); while (rs.next()) { JsonObjectBuilder jsonobj = Json.createObjectBuilder().add("productID", rs.getInt("productID")) .add("name", rs.getString("name")).add("description", rs.getString("description")) .add("quantity", rs.getInt("quantity")); numChanges = jsonobj.build().toString(); productArray.add(jsonobj); } } catch (SQLException ex) { Logger.getLogger(ProductServlet.class.getName()).log(Level.SEVERE, null, ex); } if (params.length == 0) { numChanges = productArray.build().toString(); } return numChanges; }
From source file:org.openstreetmap.josm.plugins.mapillary.actions.MapillarySubmitCurrentChangesetAction.java
@Override public void actionPerformed(ActionEvent event) { String token = Main.pref.get("mapillary.access-token"); if (token == null || token.trim().isEmpty()) { PluginState.notLoggedInToMapillaryDialog(); return;// ww w . ja v a2 s .co m } PluginState.setSubmittingChangeset(true); MapillaryUtils.updateHelpText(); HttpClientBuilder builder = HttpClientBuilder.create(); HttpPost httpPost = new HttpPost(MapillaryURL.submitChangesetURL().toString()); httpPost.addHeader("content-type", "application/json"); httpPost.addHeader("Authorization", "Bearer " + token); JsonArrayBuilder changes = Json.createArrayBuilder(); MapillaryLocationChangeset locationChangeset = MapillaryLayer.getInstance().getLocationChangeset(); for (MapillaryImage image : locationChangeset) { changes.add(Json.createObjectBuilder().add("image_key", image.getKey()).add("values", Json.createObjectBuilder() .add("from", Json.createObjectBuilder().add("ca", image.getCa()) .add("lat", image.getLatLon().getY()).add("lon", image.getLatLon().getX())) .add("to", Json.createObjectBuilder().add("ca", image.getTempCa()) .add("lat", image.getTempLatLon().getY()) .add("lon", image.getTempLatLon().getX())))); } String json = Json.createObjectBuilder().add("change_type", "location").add("changes", changes) .add("request_comment", "JOSM-created").build().toString(); try (CloseableHttpClient httpClient = builder.build()) { httpPost.setEntity(new StringEntity(json)); CloseableHttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { String key = Json.createReader(response.getEntity().getContent()).readObject().getString("key"); synchronized (MapillaryUtils.class) { Main.map.statusLine.setHelpText( String.format("%s images submitted, Changeset key: %s", locationChangeset.size(), key)); } locationChangeset.cleanChangeset(); } } catch (IOException e) { logger.error("got exception", e); synchronized (MapillaryUtils.class) { Main.map.statusLine.setHelpText("Error submitting Mapillary changeset: " + e.getMessage()); } } finally { PluginState.setSubmittingChangeset(false); } }
From source file:com.product.ProductResource.java
@GET @Path("{id}") @Produces(MediaType.APPLICATION_JSON)/*from www .j a v a 2 s . c o m*/ public String getproduct(@PathParam("id") int id) throws SQLException { if (conn == null) { return "not connected"; } else { String query = "Select * from product where product_id = ?"; PreparedStatement pstmt = conn.prepareStatement(query); pstmt.setInt(1, id); ResultSet rs = pstmt.executeQuery(); String result = ""; JsonArrayBuilder productArr = Json.createArrayBuilder(); while (rs.next()) { JsonObjectBuilder prodMap = Json.createObjectBuilder(); prodMap.add("productID", rs.getInt("product_id")); prodMap.add("name", rs.getString("name")); prodMap.add("description", rs.getString("description")); prodMap.add("quantity", rs.getInt("quantity")); productArr.add(prodMap); } result = productArr.build().toString(); return result; } }
From source file:org.fuin.esc.eshttp.ESHttpMarshallerTest.java
@Test public void testMarshalEventJSON() throws IOException { // PREPARE/*from w w w . j a v a 2 s. com*/ final String expectedJson = IOUtils.toString( this.getClass().getResourceAsStream("/" + this.getClass().getSimpleName() + "_Event.json")); final UUID uuid = UUID.fromString("a07d6a1a-715d-4d8e-98fa-b158e3339303"); final JsonObject myEvent = Json.createObjectBuilder().add("id", uuid.toString()) .add("description", "Whatever...").build(); final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(uuid), MyEvent.TYPE, myEvent); final ESHttpMarshaller testee = new ESHttpMarshaller(); // TEST final String currentJson = testee.marshal(createJsonRegistry(), commonEvent); // TEST assertThatJson(currentJson).isEqualTo(expectedJson); }
From source file:org.piwik.java.tracking.PiwikTracker.java
/** * Send multiple requests in a single HTTP call. More efficient than sending * several individual requests. Specify the AuthToken if parameters that require * an auth token is used.//from w w w. j av a2s . c om * @param requests the requests to send * @param authToken specify if any of the parameters use require AuthToken * @return the response from these requests * @throws IOException thrown if there was a problem with this connection */ public HttpResponse sendBulkRequest(Iterable<PiwikRequest> requests, String authToken) throws IOException { if (authToken != null && authToken.length() != PiwikRequest.AUTH_TOKEN_LENGTH) { throw new IllegalArgumentException( authToken + " is not " + PiwikRequest.AUTH_TOKEN_LENGTH + " characters long."); } JsonObjectBuilder ob = Json.createObjectBuilder(); JsonArrayBuilder ab = Json.createArrayBuilder(); for (PiwikRequest request : requests) { ab.add("?" + request.getQueryString()); } ob.add(REQUESTS, ab); if (authToken != null) { ob.add(AUTH_TOKEN, authToken); } HttpClient client = getHttpClient(); HttpPost post = new HttpPost(uriBuilder.build()); post.setEntity(new StringEntity(ob.build().toString(), ContentType.APPLICATION_JSON)); return client.execute(post); }