@Test public void testWriteValueOutputStreamObject() { boolean status = true; String[] stringArray = new String[1]; stringArray[0] = "abc"; new MockUp<ObjectWriter>() { @Mock public void writeValue(OutputStream out, Object value) throws IOException, JsonGenerationException, JsonMappingException { } }; try { StandardObjectWriter.writeValue(outputStream, stringArray); } catch (IOException e) { status = false; } Assert.assertTrue(status); }
@Test public void testNullInComment() throws IOException { final Comment aComment = new Comment(); aComment.setContent(null); ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out, new Writer() { @Override public void writeContents(JsonGenerator generator, ObjectMapper objectMapper) throws JsonGenerationException, JsonMappingException, IOException { FilterProvider fp = new SimpleFilterProvider().addFilter( JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties()); objectMapper.writer(fp).writeValue(generator, aComment); } }); assertEquals("Null values should not be output.", "{\"canEdit\":false,\"canDelete\":false}", out.toString()); }
@Override public Response toResponse(JsonProcessingException exception) { if (exception instanceof JsonGenerationException) { LOG.error("Error generating JSON", exception); return Response.serverError().build(); } if (exception.getMessage().startsWith("No suitable constructor found")) { LOG.error("Unable to deserialize the specific type", exception); return Response.serverError().build(); } LOG.info(exception.getLocalizedMessage()); return Response .status(Response.Status.BAD_REQUEST) .type(MediaType.APPLICATION_JSON_TYPE) .entity(createUnauditedErrorStatus(UUID.randomUUID(), ExceptionType.JSON_PARSING, exception.getOriginalMessage())) .build(); }
@CsapDoc ( notes = { "Summary status of host" } , linkTests = "default" ) @RequestMapping ( { "/status" } ) public ObjectNode status () throws JsonGenerationException, JsonMappingException, IOException { ObjectNode healthJson = jacksonMapper.createObjectNode(); if ( Application.isJvmInManagerMode() ) { healthJson.put( "error", "vmHealth is only enabled on CsAgent urls." ); } else { healthJson = csapApp.statusForAdminOrAgent( ServiceAlertsEnum.ALERT_LEVEL ); } return healthJson; }
@Override public void serialize(SerializablePagedCollection pagedCol, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { if (pagedCol != null) { jgen.writeStartObject(); jgen.writeFieldName("list"); jgen.writeStartObject(); serializePagination(pagedCol, jgen); serializeContext(pagedCol, jgen); jgen.writeObjectField("entries", pagedCol.getCollection()); serializeIncludedSource(pagedCol, jgen); jgen.writeEndObject(); jgen.writeEndObject(); } }
@CsapDoc ( notes = { "refer to /api/appication/service" } , linkTests = { "ServletSample" } , linkPaths = { "/serviceStop/ServletSample_8041" } , linkPostParams = { "userid=someDeveloper,pass=changeMe,cluster=changeMe,clean=clean" } ) @RequestMapping ( "/serviceStop/{serviceName}" ) @Deprecated public JsonNode serviceStop ( @PathVariable ( "serviceName" ) String serviceName_port, @RequestParam ( value = "cluster" , defaultValue = "" ) String cluster, @RequestParam ( value = "clean" , defaultValue = "" ) String clean, @RequestParam ( SpringAuthCachingFilter.USERID ) String userid, @RequestParam ( SpringAuthCachingFilter.PASSWORD ) String inputPass, HttpServletRequest request ) throws JsonGenerationException, JsonMappingException, IOException { logger.debug( "DeprecatedApi - use /api/application/service/kill" ); if ( Application.isJvmInManagerMode() ) { return applicationApi.serviceKill( serviceName_port, stripOffLifecycle(cluster), clean, "keepLogs", userid, inputPass, request ); } else { ArrayList<String> services = new ArrayList<>() ; services.add( serviceName_port ) ; return agentApi.serviceKill( services, clean, null, userid, userid, request ); } }
public void serialize(JsonGenerator jgen, BeakerObjectConverter boc) throws JsonGenerationException, IOException { jgen.writeStartObject(); jgen.writeNumberField("width", w); if (theStyle!=null) jgen.writeStringField("thestyle", theStyle); if (theClass!=null) jgen.writeStringField("theclass", theClass); jgen.writeArrayFieldStart("payload"); for (Object o : payload) { if ( o instanceof dashRow ) { ((dashRow) o).serialize(jgen, boc); } else if (!boc.writeObject(o, jgen, true)) jgen.writeObject(o.toString()); } jgen.writeEndArray(); jgen.writeEndObject(); }
/** * Writes the list of <code>Principal</code>s to the JSONGenerator. * * @param principals * the list of principals to be written. */ private void writePrincipals(List<Principal> principals) throws JsonGenerationException, IOException { if (principals.size() == 1 && principals.get(0).equals(Principal.All)) { writeJsonKeyValue(JsonDocumentFields.PRINCIPAL, Principal.All.getId()); } else { writeJsonObjectStart(JsonDocumentFields.PRINCIPAL); Map<String, List<String>> principalsByScheme = groupPrincipalByScheme(principals); List<String> principalValues; for (Map.Entry<String, List<String>> entry : principalsByScheme.entrySet()) { principalValues = principalsByScheme.get(entry.getKey()); if (principalValues.size() == 1) { writeJsonKeyValue(entry.getKey(), principalValues.get(0)); } else { writeJsonArray(entry.getKey(), principalValues); } } writeJsonObjectEnd(); } }
/** * A callback so a JsonGenerator can be used inline but exception are handled here * @param outStream OutputStream * @param writer The writer interface * @throws IOException */ public void withWriter(OutputStream outStream, Writer writer) throws IOException { try { JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(outStream, encoding); writer.writeContents(generator, objectMapper); } catch (JsonMappingException error) { logger.error("Failed to write Json output",error); } catch (JsonGenerationException generror) { logger.error("Failed to write Json output",generror); } }
/** * Writes the list of conditions to the JSONGenerator. * * @param conditions * the conditions to be written. */ private void writeConditions(List<Condition> conditions) throws JsonGenerationException, IOException { Map<String, ConditionsByKey> conditionsByType = groupConditionsByTypeAndKey(conditions); writeJsonObjectStart(JsonDocumentFields.CONDITION); ConditionsByKey conditionsByKey; for (Map.Entry<String, ConditionsByKey> entry : conditionsByType .entrySet()) { conditionsByKey = conditionsByType.get(entry.getKey()); writeJsonObjectStart(entry.getKey()); for (String key : conditionsByKey.keySet()) { writeJsonArray(key, conditionsByKey.getConditionsByKey(key)); } writeJsonObjectEnd(); } writeJsonObjectEnd(); }
@Test public void testSerializeComment() throws IOException { final Comment aComment = new Comment(); aComment.setContent("<b>There it is</b>"); ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out, new Writer() { @Override public void writeContents(JsonGenerator generator, ObjectMapper objectMapper) throws JsonGenerationException, JsonMappingException, IOException { FilterProvider fp = new SimpleFilterProvider().addFilter( JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties()); objectMapper.writer(fp).writeValue(generator, aComment); } }); assertTrue(out.toString().contains("{\"content\":\"<b>There it is</b>\"")); }
@Override public void writeMetaData(OutputStream out, ResourceWithMetadata resource, Map<String, ResourceWithMetadata> allApiResources) throws IOException { final Object result = processResult(resource,allApiResources); assistant.getJsonHelper().withWriter(out, new Writer() { @Override public void writeContents(JsonGenerator generator, ObjectMapper objectMapper) throws JsonGenerationException, JsonMappingException, IOException { objectMapper.writeValue(generator, result); } }); }
@Test public void logShouldSwallowExceptions() throws JsonProcessingException { SystemFragment frag = SystemFragment.empty(); Mockito.when(analyzerMock.analyzeSystem()).thenReturn(frag); Mockito.when(objectMapperMock.writeValueAsString(frag)).thenThrow(Mockito.mock(JsonGenerationException.class)); logSnitch.log(); Mockito.verify(analyzerMock).analyzeSystem(); Mockito.verify(objectMapperMock).writeValueAsString(frag); }
@Override public void serialize(CategoryEntity value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (null == value) { throw new JsonGenerationException("Could not serialize object to json, input object to serialize is null"); } StringWriter writer = new StringWriter(); mapper.writeValue(writer, value); gen.writeFieldName(writer.toString()); }
@Override public void serialize(JSONOptions value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { if (value.opaque != null) { jgen.writeObject(value.opaque); } else { jgen.writeTree(value.root); } }
@CsapDoc ( notes = "Summary information for application. On Admin nodes, it will include packages, clusters, trending configuration and more." ) @RequestMapping ( "/summary" ) public ObjectNode applicationSummary () throws JsonGenerationException, JsonMappingException, IOException { return application.getCapabilitySummary( true ); }
private void print(MapVector mapVector, int count) throws JsonGenerationException, IOException{ if(PRINT_OUTPUT){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter jsonWriter = new JsonWriter(baos, true, false); FieldReader reader = new SingleMapReaderImpl(mapVector); for(int index = 0; index < count; index++){ reader.setPosition(index); jsonWriter.write(reader); } System.out.println(baos.toString()); } }
@CsapDoc ( notes = { "Uses active in past 60 minutes" } , linkTests = "default" ) @GetMapping ( USERS_URL ) public ArrayNode usersActive () throws JsonGenerationException, JsonMappingException, IOException { return activeUsers.getActive(); }
@CsapDoc ( notes = { KILL_SERVICES_URL + ": api for stoping specified service", "param services: 1 or more service port is required.", "Parameter: clean - optional - omit or leave blank to not delete files" } , linkTests = { "ServletSample" } , linkPaths = { KILL_SERVICES_URL } , linkPostParams = { USERID_PASS_PARAMS + "clean=clean,keepLogs=keepLogs,services=ServletSample_8041,auditUserid=blank" } ) @PostMapping ( KILL_SERVICES_URL ) public ObjectNode serviceKill ( @RequestParam ArrayList<String> services, @RequestParam ( required = false ) String clean, @RequestParam ( required = false ) String keepLogs, @RequestParam ( SpringAuthCachingFilter.USERID ) String apiUserid, @RequestParam ( defaultValue = "" ) String auditUserid, HttpServletRequest request ) throws JsonGenerationException, JsonMappingException, IOException { logger.info( "auditUserid: {}, apiUserid: {}, services: {} clean: {}, keepLogs: {} ", auditUserid, apiUserid, services, clean, keepLogs ); ObjectNode apiResponse = serviceCommands.killRequest( apiUserid, services, clean, keepLogs, auditUserid ); ObjectNode securityResponse = (ObjectNode) request .getAttribute( SpringAuthCachingFilter.SEC_RESPONSE_ATTRIBUTE ); apiResponse.set( "security", securityResponse ); return apiResponse; }
@CsapDoc ( notes = { START_SERVICES_URL + ": api for starting specified service", "parameter: services: 1 or more service port is required.", "optional: deployId - start will only be issued IF deployment id specified is successful. If not specified start will be issued.", "optional: clean - omit or leave blank to not delete files" } , linkTests = { "ServletSample" } , linkPaths = { START_SERVICES_URL } , linkPostParams = { USERID_PASS_PARAMS + "commandArguments=blank,runtime=blank,services=ServletSample_8041,auditUserid=blank,startClean=blank,startNoDeploy=blank,hotDeploy=blank,deployId=blank" } ) @PostMapping ( START_SERVICES_URL ) public ObjectNode serviceStart ( @RequestParam ArrayList<String> services, @RequestParam ( required = false ) String commandArguments, @RequestParam ( required = false ) String runtime, @RequestParam ( required = false ) String hotDeploy, @RequestParam ( required = false ) String startClean, @RequestParam ( required = false ) String noDeploy, String deployId, @RequestParam ( SpringAuthCachingFilter.USERID ) String apiUserid, @RequestParam ( defaultValue = "" ) String auditUserid, HttpServletRequest request ) throws JsonGenerationException, JsonMappingException, IOException { logger.info( "auditUserid: {}, apiUserid:{} , services: {} javaOpts: {}, runtime: {}, hotDeploy: {}, startClean: {}, startNoDeploy: {} ", auditUserid, apiUserid, services, commandArguments, runtime, hotDeploy, startClean, noDeploy ); return serviceCommands.startRequest( apiUserid, services, commandArguments, runtime, hotDeploy, startClean, noDeploy, auditUserid, deployId ); }
@Override public void writeObjectFieldValueSeparator(JsonGenerator jg) throws IOException, JsonGenerationException { /** * Custom object separator (Default is " : ") to make it easier to compare state dumps with other * ethereum client implementations */ jg.writeRaw(": "); }
@Test public void testSerializeMultipleObjects() throws IOException { final Collection<Comment> allComments = new ArrayList<Comment>(); Comment aComment = new Comment(); aComment.setContent("<b>There it is</b>"); allComments.add(aComment); aComment = new Comment(); aComment.setContent("<p>I agree with the author</p>"); allComments.add(aComment); ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out, new Writer() { @Override public void writeContents(JsonGenerator generator, ObjectMapper objectMapper) throws JsonGenerationException, JsonMappingException, IOException { FilterProvider fp = new SimpleFilterProvider().addFilter( JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties()); objectMapper.writer(fp).writeValue(generator, allComments); } }); assertTrue(out.toString().contains("content\":\"<b>There it is</b>")); assertTrue(out.toString().contains("content\":\"<p>I agree with the author</p>")); }
@CsapDoc ( notes = { "Health Check for Http Monitoring via Eman, hyperic, nagios, and others.", "* Agent service only" } , linkTests = "default" ) @RequestMapping ( value = { "/hostStatus", "/vmStatus" } ) @Deprecated public JsonNode hostStatus () throws JsonGenerationException, JsonMappingException, IOException { return agentApi.runtime(); }
@CsapDoc ( notes = { "refer to /api/appication/service" } , linkTests = { "ServletSample" } , linkPaths = { "/serviceDeploy/ServletSample_8041" } , linkPostParams = { USERID_PASS_PARAMS + "performStart=true,mavenId=com.your.group:Servlet3Sample:1.0.3:war,cluster=changeMe" } ) @PostMapping ( "/serviceDeploy/{serviceName}" ) @Deprecated public JsonNode serviceDeploy ( @PathVariable ( "serviceName" ) String serviceName_port, @RequestParam ( "mavenId" ) String mavenId, @RequestParam ( value = "cluster" , defaultValue = "" ) String cluster, @RequestParam ( value = "performStart" , defaultValue = "true" ) boolean performStart, @RequestParam ( SpringAuthCachingFilter.USERID ) String userid, @RequestParam ( SpringAuthCachingFilter.PASSWORD ) String inputPass, HttpServletRequest request ) throws JsonGenerationException, JsonMappingException, IOException { logger.debug( "DeprecatedApi - use /api/application/serviceDeploy" ); return applicationApi.serviceDeploy( serviceName_port, stripOffLifecycle(cluster), mavenId, performStart, userid, inputPass, request ); }
@Override public void serialize(LogicalExpression value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { StringBuilder sb = new StringBuilder(); ExpressionStringBuilder esb = new ExpressionStringBuilder(); value.accept(esb, sb); jgen.writeString(sb.toString()); }
public String writeResponse(final Object respons) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out, new Writer() { @Override public void writeContents(JsonGenerator generator, ObjectMapper objectMapper) throws JsonGenerationException, JsonMappingException, IOException { objectMapper.writeValue(generator, respons); } }); return out.toString(); }
/** * Renders the result of an execution. * * @param res WebScriptResponse * @param toSerialize result of an execution * @throws IOException */ default void renderJsonResponse(final WebScriptResponse res, final Object toSerialize, final JacksonHelper jsonHelper) throws IOException { jsonHelper.withWriter(res.getOutputStream(), new JacksonHelper.Writer() { @Override public void writeContents(JsonGenerator generator, ObjectMapper objectMapper) throws JsonGenerationException, JsonMappingException, IOException { objectMapper.writeValue(generator, toSerialize); } }); }
public static void generateVertexLine(StringWriter sw, ObjectMapper mapper, VertexBean vBean) throws JsonGenerationException, JsonMappingException, IOException { sw.getBuffer().setLength(0); sw.append('V'); // Record type sw.append('='); mapper.writeValue(sw, vBean); sw.append('#'); int hashCode = sw.toString().hashCode(); sw.append(toHex(hashCode)); sw.append('\n'); }
public static void generateEdgeLine(StringWriter sw, ObjectMapper mapper, EdgeBean eBean) throws JsonGenerationException, JsonMappingException, IOException { sw.getBuffer().setLength(0); sw.append('E'); // Record type sw.append('='); mapper.writeValue(sw, eBean); sw.append('#'); int hashCode = sw.toString().hashCode(); sw.append(toHex(hashCode)); sw.append('\n'); }
@Override public void serialize(AbstractEntity value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { if (value != null) jgen.writeNumber(value.getId()); else jgen.writeNull(); }
@Override public String serialize(ISpatialReference value) throws IOException, JsonGenerationException { String json = this.geometryMapper.writeSpatialReference(value); return json; }
@Override public void serialize(T value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { String content = serialize(value); JsonNode node = this.objectMapper.readTree(content); jgen.writeTree(node); }
private void getJSONStringFromMap(JsonGenerator jg, Map map, String pf) throws JsonGenerationException, IOException { jg.writeStartObject(); Iterator iter = (Iterator) map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); // Iterate over Map and write key-value jg.writeFieldName(entry.getKey().toString()); // write Key in a Map writeValue(jg, entry.getValue(), pf); // write value in a Map } jg.writeEndObject(); }
private String getJSONString(JsonGenerator jg, PdxInstance pdxInstance) throws JsonGenerationException, IOException { jg.writeStartObject(); List<String> pdxFields = pdxInstance.getFieldNames(); for (String pf : pdxFields) { Object value = pdxInstance.getField(pf); jg.writeFieldName(pf); writeValue(jg, value, pf); } jg.writeEndObject(); return null; }
private <T> void getJSONStringFromArray1(JsonGenerator jg, T[] array, String pf) throws JsonGenerationException, IOException { jg.writeStartArray(); for (T obj : array) { writeValue(jg, obj, pf); } jg.writeEndArray(); }
private void getJSONStringFromCollection(JsonGenerator jg, Collection<?> coll, String pf) throws JsonGenerationException, IOException { jg.writeStartArray(); for (Object obj : coll) { writeValue(jg, obj, pf); } jg.writeEndArray(); }
public static void getJsonFromPrimitiveBoolArray(JsonGenerator jg, boolean[] array, String pf) throws JsonGenerationException, IOException { jg.writeStartArray(); for (boolean obj : array) { jg.writeBoolean(obj); } jg.writeEndArray(); }