/** * This method adds teams of the specified page to the teams array. * * @param arrBuilder specifies the array builder to add the teams into. * @param year specifies the optional year, null for all years. * @param pageNum specifies the page number. * @param verbosity specifies optional verbosity, null for full verbosity. * @param statusOut specifies standard output stream for command status, can be null for quiet mode. * @return true if successful, false if failed. */ private boolean addTeams( JsonArrayBuilder arrBuilder, String year, int pageNum, String verbosity, PrintStream statusOut) { String request = "teams/"; if (year != null) request += year + "/"; request += pageNum; if (verbosity != null) request += "/" + verbosity; JsonStructure data = get(request, statusOut, header); boolean success; if (data != null && data.getValueType() == JsonValue.ValueType.ARRAY && !((JsonArray)data).isEmpty()) { for (JsonValue team: (JsonArray)data) { arrBuilder.add(team); } success = true; } else { success = false; } return success; }
/** * Returns the value of the body as a structure. * * @return The value of the body as a structure. * @throws RemoteException If the body could not be parsed. * @since 2017/12/17 */ public JsonStructure bodyValue() throws RemoteException { Reference<JsonStructure> ref = this._jsonvalue; JsonStructure rv; if (ref == null || null == (rv = ref.get())) try { this._jsonvalue = new WeakReference<>((rv = Json.createReader(new StringReader(this.body)).read())); } catch (JsonException e) { throw new RemoteException("Failed to parse the body.", e); } return rv; }
/** * Returns the value of the body as a structure. * * @return The value of the body as a structure. * @throws RemoteException If the JSON is not valid. * @since 2017/12/17 */ public JsonStructure bodyValue() throws RemoteException { Reference<JsonStructure> ref = this._jsonvalue; JsonStructure rv; if (ref == null || null == (rv = ref.get())) try { this._jsonvalue = new WeakReference<>((rv = Json.createReader(new StringReader(this.body)).read())); } catch (JsonException e) { throw new RemoteException("Failed to parse the body.", e); } return rv; }
/** * Says if status is OK * @return true if status is OK */ public boolean isStatusOk() { if (jsonResult == null || jsonResult.isEmpty()) { return false; } 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 && status.getString().equals("OK")) { return true; } else { return false; } } catch (Exception e) { this.parseException = e; invalidJsonStream = true; return false; } }
public static Object unbox(JsonValue value, Function<JsonStructure, Object> convert) throws JsonException { switch (value.getValueType()) { case ARRAY: case OBJECT: return convert.apply((JsonStructure) value); case FALSE: return Boolean.FALSE; case TRUE: return Boolean.TRUE; case NULL: return null; case NUMBER: JsonNumber number = (JsonNumber) value; return number.isIntegral() ? number.longValue() : number.doubleValue(); case STRING: return ((JsonString) value).getString(); default: throw new JsonException("Unknow value type"); } }
private String formatBody(String contentType, String body) { if (body != null && contentType != null) { if (contentType.startsWith("application/json")) { try { JsonStructure json = Json.createReader(new StringReader(body)).read(); StringWriter w = new StringWriter(); HashMap<String, Object> p = new HashMap<>(); p.put(JsonGenerator.PRETTY_PRINTING, true); Json.createWriterFactory(p).createWriter(w).write(json); return w.toString(); } catch (JsonException ex) { return body; } } else { return body; } } else { return null; } }
@POST @Path("{id}/enable") public JsonStructure enablePlugin(@PathParam("id") String id, @DefaultValue("0") @QueryParam("timeout") int timeout) { WebTarget target = resource().path("plugins").path(id).path("enable").queryParam("timeout", timeout); Response response = postResponse(target); String entity = response.readEntity(String.class); response.close(); JsonStructure structure; if (entity.isEmpty()) { structure = Json.createObjectBuilder().add("message", id + " plugin enabled.").build(); } else { structure = Json.createReader(new StringReader(entity)).read(); } return structure; }
@POST @Path("{id}/disable") public JsonStructure disablePlugin(@PathParam("id") String id) { WebTarget target = resource().path("plugins").path(id).path("disable"); Response response = postResponse(target); String entity = response.readEntity(String.class); response.close(); JsonStructure structure; if (entity.isEmpty()) { structure = Json.createObjectBuilder().add("message", id + " plugin disabled.").build(); } else { structure = Json.createReader(new StringReader(entity)).read(); } return structure; }
@POST @Path("pull") public JsonStructure pullPlugin(@QueryParam("remote") String remote, @QueryParam("name") String name, JsonStructure content) { WebTarget target = resource().path("plugins").path("pull"); if (Objects.nonNull(remote)) target = target.queryParam("remote", remote); if (Objects.nonNull(name)) target = target.queryParam("name", name); Response response = postResponse(target, content); String entity = response.readEntity(String.class); response.close(); JsonStructure result; if (entity.isEmpty()) { result = Json.createObjectBuilder().add("message", "plugin pulled.").build(); } else { result = Json.createReader(new StringReader(entity)).read(); } return result; }
@POST @Path("{id}/push") public JsonStructure pushPlugin(@PathParam("id") String id) { WebTarget target = resource().path("plugins").path(id).path("push"); Response response = postResponse(target); String entity = response.readEntity(String.class); response.close(); JsonStructure result; if (entity.isEmpty()) { result = Json.createObjectBuilder().add("message", id + " plugin pushed.").build(); } else { result = Json.createReader(new StringReader(entity)).read(); } return result; }
@POST @Path("{id}/upgrade") public JsonStructure upgradePlugin(@PathParam("id") String id, @QueryParam("remote") String remote, JsonStructure content) { WebTarget target = resource().path("plugins").path(id).path("upgrade"); if (Objects.nonNull(remote)) target = target.queryParam("remote", remote); Response response = postResponse(target, content); String entity = response.readEntity(String.class); response.close(); JsonStructure result; if (entity.isEmpty()) { result = Json.createObjectBuilder().add("message", id + " plugin upgraded.").build(); } else { result = Json.createReader(new StringReader(entity)).read(); } return result; }
@POST @Path("{id}/set") public JsonStructure settingPlugin(@PathParam("id") String id, JsonStructure content) { WebTarget target = resource().path("plugins").path(id).path("set"); Response response = postResponse(target, content); String entity = response.readEntity(String.class); response.close(); JsonStructure result; if (entity.isEmpty()) { result = Json.createObjectBuilder().add("message", id + " plugin configuration set.").build(); } else { result = Json.createReader(new StringReader(entity)).read(); } return result; }
public static String toString(final JsonStructure json) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final JsonWriter jsonWriter = getPrettyJsonWriterFactory() .createWriter(outputStream, Charset.forName("UTF-8")); jsonWriter.write(json); jsonWriter.close(); String jsonString; try { jsonString = new String(outputStream.toByteArray(), "UTF8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return jsonString; }
@Test public void testBson () throws IOException { BasicConfigurator.configure (); String f = "../tests/data/data1.bson"; File file = new File (f.replace ('/', File.separatorChar)); JsonPathProvider provider = new JsonPathProvider (); Configuration pathConfig = Configuration.defaultConfiguration ().jsonProvider (provider); JsonPath path = JsonPath.compile ("$..A"); JsonProvider p = new CookJsonProvider (); HashMap<String, Object> readConfig = new HashMap<String, Object> (); readConfig.put (CookJsonProvider.FORMAT, CookJsonProvider.FORMAT_BSON); readConfig.put (CookJsonProvider.ROOT_AS_ARRAY, Boolean.TRUE); JsonReaderFactory rf = p.createReaderFactory (readConfig); JsonReader reader = rf.createReader (new FileInputStream (file)); JsonStructure obj = reader.read (); reader.close (); JsonValue value = path.read (obj, pathConfig); Assert.assertEquals ("[1,3,5,7]", provider.toJson (value)); }
/** * Map deserialization. * * {@literal JsonObject}s are deserialized to {@literal Map<String, ?>}. * {@literal JsonArray}s of key/value {@literal JsonObject}s are deserialized to {@literal Map<?, ?>}. */ private Map<?, ?> deserializeMap( ModuleDescriptor module, MapType mapType, JsonStructure json ) { if( json.getValueType() == JsonValue.ValueType.OBJECT ) { JsonObject object = (JsonObject) json; return object.entrySet().stream() .map( entry -> new AbstractMap.SimpleImmutableEntry<>( entry.getKey(), doDeserialize( module, mapType.valueType(), entry.getValue() ) ) ) .collect( toMapWithNullValues( LinkedHashMap::new ) ); } if( json.getValueType() == JsonValue.ValueType.ARRAY ) { JsonArray array = (JsonArray) json; return array.stream() .map( JsonObject.class::cast ) .map( entry -> new AbstractMap.SimpleImmutableEntry<>( doDeserialize( module, mapType.keyType(), entry.get( "key" ) ), doDeserialize( module, mapType.valueType(), entry.get( "value" ) ) ) ) .collect( toMapWithNullValues( LinkedHashMap::new ) ); } throw new SerializationException( "Don't know how to deserialize " + mapType + " from " + json ); }
@Override public void handle(JKQueryHandle qhandle, JsonObject response, Throwable ex) { if (ex != null) { lastError = ex; errCount.incrementAndGet(); out.println("Error: handle=" + qhandle + ", error=" + ex.getMessage()); ex.printStackTrace(out); } else { msgCount.incrementAndGet(); if (json_path == null) { out.println(JKUtils.prettyPrint(response)); } else { JsonValue jsonPath = JKUtils.getJsonValue(json_path, response); if (jsonPath == null) { out.print("\"" + json_path + "\" not found"); } else if (jsonPath instanceof JsonStructure){ out.println(JKUtils.prettyPrint((JsonStructure)jsonPath)); } else { out.format("%s = %s, %s", json_path, jsonPath, jsonPath.getValueType()); } } } }
@Override @NotNull(message = "Hook is never NULL") public Hook create( @NotNull(message = "name can't be NULL") final String name, @NotNull(message = "config can't be NULL") final Map<String, String> config, final boolean active ) throws IOException { final JsonObjectBuilder builder = Json.createObjectBuilder(); for (final Map.Entry<String, String> entr : config.entrySet()) { builder.add(entr.getKey(), entr.getValue()); } final JsonStructure json = Json.createObjectBuilder() .add("name", name) .add("config", builder) .add("active", active) .build(); return this.get( this.request.method(Request.POST) .body().set(json).back() .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) .json().readObject().getInt("id") ); }
@Override @NotNull(message = "release is never NULL") public Release create( @NotNull(message = "tag can't be NULL") final String tag ) throws IOException { final JsonStructure json = Json.createObjectBuilder() .add("tag_name", tag) .build(); return this.get( this.request.method(Request.POST) .body().set(json).back() .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) .json().readObject().getInt("id") ); }
@Override @NotNull(message = "Comment is never NULL") public Comment post(@NotNull(message = "post text can't be NULL") final String text) throws IOException { final JsonStructure json = Json.createObjectBuilder() .add("body", text) .build(); return this.get( this.request.method(Request.POST) .body().set(json).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) // @checkstyle MultipleStringLiterals (1 line) .json().readObject().getInt("id") ); }
@Override @NotNull(message = "Issue is never NULL") public Issue create( @NotNull(message = "title can't be NULL") final String title, @NotNull(message = "body can't be NULL")final String body) throws IOException { final JsonStructure json = Json.createObjectBuilder() .add("title", title) .add("body", body) .build(); return this.get( this.request.method(Request.POST) .body().set(json).back() .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) .json().readObject().getInt("number") ); }
@Override @NotNull(message = "pull is never NULL") public Pull create( @NotNull(message = "pull title is never NULL") final String title, @NotNull(message = "head is never NULL") final String head, @NotNull(message = "base is never NULL") final String base) throws IOException { final JsonStructure json = Json.createObjectBuilder() .add("title", title) .add("head", head) .add("base", base) .build(); return this.get( this.request.method(Request.POST) .body().set(json).back() .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) .json().readObject().getInt("number") ); }
@Override @NotNull(message = "milestone is never NULL") public Milestone create( @NotNull(message = "title can't be NULL") final String title) throws IOException { final JsonStructure json = Json.createObjectBuilder() .add("title", title) .build(); return this.get( this.request.method(Request.POST) .body().set(json).back() .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) .json().readObject().getInt("number") ); }
@Override @NotNull(message = "GistComment is never NULL") public GistComment post( @NotNull(message = "text can't be NULL") final String text ) throws IOException { final JsonStructure json = Json.createObjectBuilder() .add("body", text) .build(); return this.get( this.request.method(Request.POST) .body().set(json).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) // @checkstyle MultipleStringLiterals (1 line) .json().readObject().getInt("id") ); }
@Override @NotNull(message = "Content can't be NULL") public Content readme( @NotNull(message = "branch can't be NULL") final String branch ) throws IOException { final JsonStructure json = Json.createObjectBuilder() .add("ref", branch) .build(); return new RtContent( this.entry, this.owner, this.entry.uri() .path("/repos") .path(this.owner.coordinates().user()) .path(this.owner.coordinates().repo()) .path("/readme") .back() .method(Request.GET) .body().set(json).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class) .json().readObject().getString("path") ); }
@Override @NotNull(message = "Fork can't be NULL") public Fork create( @NotNull(message = "organization can't be NULL") final String organization) throws IOException { final JsonStructure json = Json.createObjectBuilder() .add("organization", organization) .build(); return this.get( this.request.method(Request.POST) .body().set(json).back() .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_ACCEPTED) .as(JsonResponse.class) .json().readObject().getInt(ID) ); }
@Override @NotNull(message = "PullComment is never NULL") public PullComment post( @NotNull(message = "body can't be NULL") final String body, @NotNull(message = "commit can't be NULL") final String commit, @NotNull(message = "path can't be NULL") final String path, final int position ) throws IOException { final JsonStructure json = Json.createObjectBuilder() // @checkstyle MultipleStringLiterals (4 line) .add("body", body) .add("commit_id", commit) .add("path", path) .add("position", position) .build(); return this.get( this.request.method(Request.POST) .body().set(json).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) .json().readObject().getInt("id") ); }
@Override @NotNull(message = "pull comment is never NULL") public PullComment reply( @NotNull(message = "text can't be NULL") final String body, @NotNull(message = "comment can't be NULL") final int comment ) throws IOException { final JsonStructure json = Json.createObjectBuilder() .add("body", body) .add("in_reply_to", comment) .build(); return this.get( this.request.method(Request.POST) .body().set(json).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) .json().readObject().getInt("id") ); }
@Override @NotNull(message = "label is never NULL") public Label create( @NotNull(message = "label name can't be NULL") final String name, @NotNull(message = "label color can't be NULL") final String color) throws IOException { final JsonStructure json = Json.createObjectBuilder() // @checkstyle MultipleStringLiterals (1 line) .add("name", name) .add("color", color) .build(); this.request.method(Request.POST) .body().set(json).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) .json(); return new RtLabel(this.entry, this.owner, name); }
@Override @NotNull(message = "Gist can't be NULL") public Gist create(@NotNull(message = "list of files can't be NULL") final Map<String, String> files, final boolean visible ) throws IOException { JsonObjectBuilder builder = Json.createObjectBuilder(); for (final Map.Entry<String, String> file : files.entrySet()) { builder = builder.add( file.getKey(), Json.createObjectBuilder().add("content", file.getValue()) ); } final JsonStructure json = Json.createObjectBuilder() .add("files", builder) .add("public", visible) .build(); return this.get( this.request.method(Request.POST) .body().set(json).back() .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) .json().readObject().getString("id") ); }
@Override public void add(@NotNull(message = "iterable of labels can't be NULL") final Iterable<String> labels) throws IOException { JsonArrayBuilder builder = Json.createArrayBuilder(); for (final String label : labels) { builder = builder.add(label); } final JsonStructure json = builder.build(); this.request.method(Request.POST) .body().set(json).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class) .json().readArray(); }
@Override public void replace(@NotNull(message = "iterable of labels can't be NULL") final Iterable<String> labels) throws IOException { JsonArrayBuilder builder = Json.createArrayBuilder(); for (final String label : labels) { builder = builder.add(label); } final JsonStructure json = builder.build(); this.request.method(Request.PUT) .body().set(json).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class) .json().readArray(); }
@Test public void test() { final Project project = new Project("project name", "1.0", resources); cut.configure(singletonMap(INLINE_PRETTIFY, "false")); final String actualOutput = new String(cut.render(project)); // TODO to fix test w/ different formattings // assertEquals(expectedOutput, actualOutput); try (final StringReader expectedReader = new StringReader(expectedOutput); final StringReader actualReader = new StringReader(actualOutput) ) { final JsonStructure expected = Json.createReader(expectedReader).read(); final JsonStructure actual = Json.createReader(actualReader).read(); assertEquals(expected, actual); } }
/** * Returns an IData representation of the JSON data in the given input stream. * * @param inputStream The input stream to be decoded. * @param charset The character set to use. * @return An IData representation of the given input stream data. * @throws IOException If there is a problem reading from the stream. */ public IData decode(InputStream inputStream, Charset charset) throws IOException { JsonReader reader = jsonReaderFactory.createReader(inputStream, CharsetHelper.normalize(charset)); JsonStructure structure = reader.read(); reader.close(); Object object = fromJsonValue(structure); IData output = null; if (object instanceof IData) { output = (IData)object; } else if (object instanceof Object[]) { output = IDataFactory.create(); IDataCursor cursor = output.getCursor(); IDataUtil.put(cursor, "recordWithNoID", object); cursor.destroy(); } return output; }
/** * Returns a JSON representation of the given IData object. * * @param input The IData to convert to JSON. * @return The JSON representation of the IData. */ @Override public String encodeToString(IData input) throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter writer = jsonWriterFactory.createWriter(stringWriter); IDataCursor cursor = input.getCursor(); Object[] array = IDataUtil.getObjectArray(cursor, "recordWithNoID"); cursor.destroy(); JsonStructure structure; if (array != null) { structure = toJsonArray(array); } else { structure = toJsonObject(input); } writer.write(structure); writer.close(); return stringWriter.toString().trim(); }
@SuppressWarnings("unchecked") @Override public final <T> T unmarshal(final Object data, final EnhancedMimeType mimeType) { if (data instanceof byte[]) { final Reader reader = new InputStreamReader(new ByteArrayInputStream((byte[]) data), mimeType.getEncoding()); final JsonReader jsonReader = Json.createReader(reader); try { return (T) jsonReader.read(); } finally { jsonReader.close(); } } if (data instanceof JsonStructure) { // Simply return it return (T) data; } throw new IllegalArgumentException("This deserializer only supports input of type '" + JsonStructure.class.getName() + "' and 'byte[]', but was: " + data); }
/** * Convert a POJO into Serialized JSON form. * * @param o the POJO to serialize * @param s the OutputStream to write to.. * @throws IOException when there are problems creating the JSON. */ public static void serializeAsStream(Object o, OutputStream s) throws IOException { try { JsonStructure builtJsonObject = findFieldsToSerialize(o).mainObject; Map<String, Object> config = new HashMap<String, Object>(); config.put(JsonGenerator.PRETTY_PRINTING, true); JsonWriterFactory writerFactory = Json.createWriterFactory(config); JsonWriter streamWriter = writerFactory.createWriter(s); streamWriter.write(builtJsonObject); } catch (IllegalStateException ise) { // the reflective attempt to build the object failed. throw new IOException("Unable to build JSON for Object", ise); } catch (JsonException e) { throw new IOException("Unable to build JSON for Object", e); } }
/** * Creates a JSON model of the object. Object can be an array, a collection, * a map, a json array builder, a json object builder or a POJO. * * @param object * the object. * @return a json model. * @throws RestyMappingException * if there are errors of annotation using. */ public static JsonStructure build(Object object) throws RestyMappingException { Class<?> type = object.getClass(); if (type.isArray()) { return getArray(object).build(); } else if (object instanceof Collection) { return getCollection((Collection) object).build(); } else if (object instanceof Map) { return getMap((Map) object).build(); } else if (object instanceof JsonArrayBuilder) { return ((JsonArrayBuilder) object).build(); } else if (object instanceof JsonObjectBuilder) { return ((JsonObjectBuilder) object).build(); } else { return getObject(object).build(); } }
private File writeStructure(final File targetDir, final String directory, final String fileName, JsonStructure structure) throws IOException { Validate.notNull(fileName); final File dir = new File(targetDir, directory); dir.mkdirs(); final File file = new File(dir, fileName); final FileWriter fileWriter = new FileWriter(file); try { final JsonWriter jsonWriter = provider.createWriterFactory( Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, Boolean.TRUE)).createWriter(fileWriter); jsonWriter.write(structure); } finally { try { fileWriter.close(); } catch (IOException ignored) { } } return file; }
@Override public void writeJsonStructure(Module<NType, NClass> module, JsonStructure structure, String fileName) { try { final JPackage _package = codeModel._package(""); _package.addResourceFile(createTextFile(fileName, structure)); } catch (IOException ioex) { try { errorHandler.error(new SAXParseException(MessageFormat.format( "Could not create the code for the module [{0}].", module.getName()), null, ioex)); } catch (SAXException ignored) { } } }
public static Object unwrapJsonObjects(Object entity) { if (entity instanceof JsonObjectBuilder) { JsonObjectBuilder jsonObjectBuilder = (JsonObjectBuilder) entity; entity = jsonObjectBuilder.build(); } if (entity instanceof JsonStructure) { StringWriter buffer = new StringWriter(); JsonWriter writer = Json.createWriter(buffer); writer.write((JsonStructure) entity); writer.close(); return buffer.toString(); } return entity; }