Java Code Examples for org.codehaus.jackson.map.ObjectMapper#writeValue()
The following examples show how to use
org.codehaus.jackson.map.ObjectMapper#writeValue() .
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: CustomAuthExceptionEntryPoint.java From spring-security with Apache License 2.0 | 6 votes |
/** * token错误时进入到这里 * * @param request * @param response * @param authException * @throws ServletException */ @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws ServletException { Map<String, Object> map = new HashMap<>(); map.put("code", 401); map.put("msg", "非法访问资源,访问此资源需要完全身份验证"); map.put("path", request.getServletPath()); map.put("timestamp", System.currentTimeMillis()); response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); try { ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(response.getOutputStream(), map); } catch (Exception e) { throw new ServletException(); } }
Example 2
Source File: ServerUtils.java From pentaho-cpython-plugin with Apache License 2.0 | 6 votes |
/** * Send a shutdown command to the micro server * * @param outputStream the output stream to write the command to * @throws KettleException if a problem occurs */ protected static void sendServerShutdown( OutputStream outputStream ) throws KettleException { Map<String, Object> command = new HashMap<String, Object>(); command.put( "command", "shutdown" ); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue( bos, command ); byte[] bytes = bos.toByteArray(); // write the command writeDelimitedToOutputStream( bytes, outputStream ); } catch ( IOException ex ) { throw new KettleException( ex ); } }
Example 3
Source File: JacksonPayloadSerializer.java From helix with Apache License 2.0 | 6 votes |
@Override public <T> byte[] serialize(final T data) { if (data == null) { return null; } ObjectMapper mapper = new ObjectMapper(); SerializationConfig serializationConfig = mapper.getSerializationConfig(); serializationConfig.set(SerializationConfig.Feature.INDENT_OUTPUT, true); serializationConfig.set(SerializationConfig.Feature.AUTO_DETECT_FIELDS, true); serializationConfig.set(SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true); StringWriter sw = new StringWriter(); try { mapper.writeValue(sw, data); } catch (Exception e) { logger.error("Exception during payload data serialization.", e); throw new ZkClientException(e); } return sw.toString().getBytes(); }
Example 4
Source File: ServerUtils.java From pentaho-cpython-plugin with Apache License 2.0 | 6 votes |
/** * Prints out a json command for debugging purposes * * @param command the command to print out * @param log optional log */ protected static void outputCommandDebug( Map<String, Object> command, LogChannelInterface log ) throws KettleException { ObjectMapper mapper = new ObjectMapper(); StringWriter sw = new StringWriter(); try { mapper.writeValue( sw, command ); String serialized = sw.toString(); if ( log != null ) { log.logDebug( "Sending command:\n" + serialized ); } else { System.err.println( "Sending command: " ); System.err.println( serialized ); } } catch ( IOException ex ) { throw new KettleException( ex ); } }
Example 5
Source File: TestZNRecordSerializeWriteSizeLimit.java From helix with Apache License 2.0 | 6 votes |
private byte[] serialize(Object data) { ObjectMapper mapper = new ObjectMapper(); SerializationConfig serializationConfig = mapper.getSerializationConfig(); serializationConfig.set(SerializationConfig.Feature.INDENT_OUTPUT, true); serializationConfig.set(SerializationConfig.Feature.AUTO_DETECT_FIELDS, true); serializationConfig.set(SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] serializedBytes = new byte[0]; try { mapper.writeValue(baos, data); serializedBytes = baos.toByteArray(); } catch (IOException e) { Assert.fail("Can not serialize data.", e); } return serializedBytes; }
Example 6
Source File: WriteJsonServletHandler.java From uflo with Apache License 2.0 | 6 votes |
protected void writeObjectToJson(HttpServletResponse resp,Object obj) throws ServletException, IOException{ resp.setHeader("Access-Control-Allow-Origin", "*"); resp.setContentType("text/json"); resp.setCharacterEncoding("UTF-8"); ObjectMapper mapper=new ObjectMapper(); mapper.setSerializationInclusion(Inclusion.NON_NULL); mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); OutputStream out = resp.getOutputStream(); try { mapper.writeValue(out, obj); } finally { out.flush(); out.close(); } }
Example 7
Source File: AvroJson.java From brooklin with BSD 2-Clause "Simplified" License | 6 votes |
/** * Convert the HashMap {@code _info} into an AvroSchema * This involves using the Avro Parser which will ensure the entire * schema is properly formatted * * If the Schema is not formatted properly, this function will throw an * error */ public Schema toSchema() throws SchemaGenerationException { try { ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = new JsonFactory(); StringWriter writer = new StringWriter(); JsonGenerator jgen = factory.createJsonGenerator(writer); jgen.useDefaultPrettyPrinter(); mapper.writeValue(jgen, _info); String schema = writer.getBuffer().toString(); return Schema.parse(schema); } catch (IOException e) { throw new SchemaGenerationException("Failed to generate Schema from AvroJson", e); } }
Example 8
Source File: OlatJerseyTestCase.java From olat with Apache License 2.0 | 5 votes |
protected String stringuified(final Object obj) { try { final ObjectMapper mapper = new ObjectMapper(jsonFactory); final StringWriter w = new StringWriter(); mapper.writeValue(w, obj); return w.toString(); } catch (final Exception e) { e.printStackTrace(); return null; } }
Example 9
Source File: CascadeResult.java From secure-data-service with Apache License 2.0 | 5 votes |
private String objectToJSON(Object ob) { ObjectMapper mapper = new ObjectMapper(); StringWriter writer = new StringWriter(); try { mapper.writeValue(writer, ob); } catch (Exception e) { return "{\"error\": \"JSON conversion error\""; } return writer.getBuffer().toString(); }
Example 10
Source File: EPLUtilities.java From jetstream-esper with GNU General Public License v2.0 | 5 votes |
/** * transformToJsonString - This method converts from incoming object to JSON string. Need/use of this method is, in * EPL we need to use pass Objects through window. But EPL allows primitives type alone. For that we 'll convert * Obejct to JsonString and pass it to the stream. * * @param obj * @return */ public static String transformToJsonString(Object obj) throws Exception { if (obj != null) { ObjectMapper mapper = new ObjectMapper(); Writer writer = new StringWriter(); mapper.writeValue(writer, obj); return writer.toString(); } return null; }
Example 11
Source File: WriteJsonServletAction.java From ureport with Apache License 2.0 | 5 votes |
protected void writeObjectToJson(HttpServletResponse resp,Object obj) throws ServletException, IOException{ resp.setContentType("text/json"); resp.setCharacterEncoding("UTF-8"); ObjectMapper mapper=new ObjectMapper(); mapper.setSerializationInclusion(Inclusion.NON_NULL); mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); OutputStream out = resp.getOutputStream(); try { mapper.writeValue(out, obj); } finally { out.flush(); out.close(); } }
Example 12
Source File: TestHelixAdminScenariosRest.java From helix with Apache License 2.0 | 5 votes |
public static String ObjectToJson(Object object) throws JsonGenerationException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); SerializationConfig serializationConfig = mapper.getSerializationConfig(); serializationConfig.set(SerializationConfig.Feature.INDENT_OUTPUT, true); StringWriter sw = new StringWriter(); mapper.writeValue(sw, object); return sw.toString(); }
Example 13
Source File: TestShuffledIdealState.java From helix with Apache License 2.0 | 4 votes |
@Test() public void testInvocation() throws Exception { int partitions = 6, replicas = 2; String dbName = "espressoDB1"; List<String> instanceNames = new ArrayList<String>(); instanceNames.add("localhost_1231"); instanceNames.add("localhost_1232"); instanceNames.add("localhost_1233"); instanceNames.add("localhost_1234"); ZNRecord result = IdealStateCalculatorByShuffling .calculateIdealState(instanceNames, partitions, replicas, dbName); IdealCalculatorByConsistentHashing.printIdealStateStats(result, "MASTER"); IdealCalculatorByConsistentHashing.printIdealStateStats(result, "SLAVE"); ZNRecord result2 = IdealStateCalculatorByRush .calculateIdealState(instanceNames, 1, partitions, replicas, dbName); ZNRecord result3 = IdealCalculatorByConsistentHashing .calculateIdealState(instanceNames, partitions, replicas, dbName, new IdealCalculatorByConsistentHashing.FnvHash()); IdealCalculatorByConsistentHashing.printIdealStateStats(result3, "MASTER"); IdealCalculatorByConsistentHashing.printIdealStateStats(result3, "SLAVE"); IdealCalculatorByConsistentHashing.printIdealStateStats(result3, ""); IdealCalculatorByConsistentHashing.printNodeOfflineOverhead(result3); // System.out.println(result); ObjectMapper mapper = new ObjectMapper(); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); StringWriter sw = new StringWriter(); mapper.writeValue(sw, result); // System.out.println(sw.toString()); ZNRecord zn = mapper.readValue(new StringReader(sw.toString()), ZNRecord.class); System.out.println(result.toString()); System.out.println(zn.toString()); AssertJUnit.assertTrue(zn.toString().equalsIgnoreCase(result.toString())); System.out.println(); sw = new StringWriter(); mapper.writeValue(sw, result2); ZNRecord zn2 = mapper.readValue(new StringReader(sw.toString()), ZNRecord.class); System.out.println(result2.toString()); System.out.println(zn2.toString()); AssertJUnit.assertTrue(zn2.toString().equalsIgnoreCase(result2.toString())); sw = new StringWriter(); mapper.writeValue(sw, result3); System.out.println(); ZNRecord zn3 = mapper.readValue(new StringReader(sw.toString()), ZNRecord.class); System.out.println(result3.toString()); System.out.println(zn3.toString()); AssertJUnit.assertTrue(zn3.toString().equalsIgnoreCase(result3.toString())); System.out.println(); }
Example 14
Source File: ServerUtils.java From pentaho-cpython-plugin with Apache License 2.0 | 4 votes |
/** * Execute a script on the server * * @param script the script to execute * @param outputStream the output stream to write data to the server * @param inputStream the input stream to read responses from * @param log optional log to write to * @return a two element list that contains the sys out and sys error from the * script execution * @throws KettleException if a problem occurs */ @SuppressWarnings( "unchecked" ) protected static List<String> executeUserScript( String script, OutputStream outputStream, InputStream inputStream, LogChannelInterface log ) throws KettleException { if ( !script.endsWith( "\n" ) ) { script += "\n"; } List<String> outAndErr = new ArrayList<String>(); ObjectMapper mapper = new ObjectMapper(); boolean debug = log == null || log.isDebug(); Map<String, Object> command = new HashMap<String, Object>(); command.put( "command", "execute_script" ); command.put( "script", script ); command.put( "debug", debug ); if ( inputStream != null && outputStream != null ) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); mapper.writeValue( bos, command ); byte[] bytes = bos.toByteArray(); if ( debug ) { outputCommandDebug( command, log ); } writeDelimitedToOutputStream( bytes, outputStream ); // get the result of execution bytes = readDelimitedFromInputStream( inputStream ); Map<String, Object> ack = mapper.readValue( bytes, Map.class ); if ( !ack.get( RESPONSE_KEY ).toString().equals( OK_KEY ) ) { // fatal error throw new KettleException( ack.get( ERROR_MESSAGE_KEY ).toString() ); } // get the script out and err outAndErr.add( ack.get( SCRIPT_OUT_KEY ).toString() ); outAndErr.add( ack.get( SCRIPT_ERROR_KEY ).toString() ); if ( debug ) { if ( log != null ) { log.logDebug( BaseMessages.getString( PKG, "ServerUtils.Message.ScriptOutput" ) + "\n" + outAndErr.get( 0 ) ); log.logDebug( BaseMessages.getString( PKG, "ServerUtils.Message.ScriptError" ) + "\n" + outAndErr.get( 1 ) ); } else { System.err.println( "Script output:\n" + outAndErr.get( 0 ) ); System.err.println( "\nScript error:\n" + outAndErr.get( 1 ) ); } } if ( outAndErr.get( 1 ).contains( "Warning:" ) ) { // clear warnings - we really just want to know if there // are major errors outAndErr.set( 1, "" ); } } catch ( IOException ex ) { throw new KettleException( ex ); } } else if ( debug ) { outputCommandDebug( command, log ); } return outAndErr; }
Example 15
Source File: ServerUtils.java From pentaho-cpython-plugin with Apache License 2.0 | 4 votes |
/** * Send rows to python to be converted to a pandas data frame * * @param log the log channel to use * @param inputStream the input stream to read a response from * @param outputStream the output stream to talk to the server on * @throws KettleException if a problem occurs */ protected static void sendRowsToPandasDataFrame( LogChannelInterface log, RowMetaInterface meta, List<Object[]> rows, String frameName, OutputStream outputStream, InputStream inputStream ) throws KettleException { ObjectMapper mapper = new ObjectMapper(); boolean debug = log == null || log.isDebug(); Map<String, Object> metaData = createMetadataMessage( frameName, meta ); Map<String, Object> command = new HashMap<String, Object>(); command.put( COMMAND_KEY, ACCEPT_ROWS_COMMAND ); command.put( NUM_ROWS_KEY, rows.size() ); command.put( ROW_META_KEY, metaData ); command.put( DEBUG_KEY, debug ); boolean needsBase64 = (boolean) metaData.get( BASE64_ENCODING_KEY ); command.put( BASE64_ENCODING_KEY, needsBase64 ); metaData.remove( BASE64_ENCODING_KEY ); if ( inputStream != null && outputStream != null ) { try { List<Object> rowsInfo = rowsToCSVNew( meta, rows ); // unfortunately we'll incur the base 64 transcoding overhead even if it // is only the header row that needs it. if ( !needsBase64 ) { command.put( BASE64_ENCODING_KEY, (boolean) rowsInfo.get( 1 ) ); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); mapper.writeValue( bos, command ); byte[] bytes = bos.toByteArray(); if ( debug ) { outputCommandDebug( command, log ); } // write the command writeDelimitedToOutputStream( bytes, outputStream ); // now write the CSV data if ( rows.size() > 0 ) { if ( log != null && debug ) { log.logDebug( "Sending CSV data..." ); } writeDelimitedToOutputStream( (byte[]) rowsInfo.get( 0 ), outputStream ); /* // bos = new ByteArrayOutputStream(); // BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( bos ) ); StringBuilder csv = rowsToCSV( meta, rows ); Charset utf8 = Charset.forName( "UTF-8" ); ByteBuffer bb = utf8.newEncoder().onUnmappableCharacter( CodingErrorAction.IGNORE ) .onMalformedInput( CodingErrorAction.IGNORE ).encode( CharBuffer.wrap( csv.toString() ) ); // byte[] ptext = csv.toString().getBytes( Charset.forName( "UTF-8" ) ); System.out.println( csv.toString() ); System.out.println( "-----------------" ); // bw.write( csv.toString() ); // bw.flush(); // bw.close(); // bytes = bos.toByteArray(); // writeDelimitedToOutputStream( bytes, outputStream ); writeDelimitedToOutputStream( bb.array(), outputStream ); */ } String serverAck = receiveServerAck( inputStream ); if ( serverAck != null ) { throw new KettleException( BaseMessages.getString( PKG, "ServerUtils.Error.TransferOfRowsFailed" ) + serverAck ); } } catch ( IOException ex ) { throw new KettleException( ex ); } } else if ( debug ) { outputCommandDebug( command, log ); } }
Example 16
Source File: TestJsonSerde.java From hraven with Apache License 2.0 | 4 votes |
@Test public void testJobSerializationContextCounterFilters() throws Exception { // load a sample flow final short numJobs = 1; GenerateFlowTestData flowDataGen = new GenerateFlowTestData(); Table historyTable = hbaseConnection.getTable(TableName.valueOf(Constants.HISTORY_TABLE)); flowDataGen.loadFlow("c1@local", "buser", "testJobSerializationContextCounterFilters", 1234, "a", numJobs, 10, idService, historyTable); historyTable.close(); JobHistoryService service = new JobHistoryService(UTIL.getConfiguration(), hbaseConnection); Flow actualFlow = service.getFlow("c1@local", "buser", "testJobSerializationContextCounterFilters", 1234, false); assertNotNull(actualFlow); assertTrue(actualFlow.getJobCount() == numJobs); JobDetails actualJob = actualFlow.getJobs().get(0); // test serialization matching specific property keys // serialize job into json List<String> includeFields = Lists.newArrayList("megabyteMillis", "jobId", "jobKey", "status"); List<String> includeCounters = Lists.newArrayList("FileSystemCounters.HDFS_BYTES_READ", "FileSystemCounters.HDFS_BYTES_WRITTEN"); Predicate<String> includeFilter = new SerializationContext.FieldNameFilter(includeFields); Predicate<String> includeCounterPredicate = new SerializationContext.FieldNameFilter(includeCounters); SerializationContext serializationContext = new SerializationContext(SerializationContext.DetailLevel.EVERYTHING, null, null, includeFilter, null, includeCounterPredicate); RestResource.serializationContext.set( serializationContext); ObjectMapper om = ObjectMapperProvider.createCustomMapper(); om.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); om.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); om.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); ByteArrayOutputStream f = new ByteArrayOutputStream(); om.writeValue(f, actualJob); ByteArrayInputStream is = new ByteArrayInputStream(f.toByteArray()); JobDetails deserJob = (JobDetails) JSONUtil.readJson(is, new TypeReference<JobDetails>() { }); // check the values match assertEquals(actualJob.getJobId(), deserJob.getJobId()); assertEquals(actualJob.getJobKey(), deserJob.getJobKey()); assertEquals(actualJob.getStatus(), deserJob.getStatus()); assertEquals(actualJob.getMegabyteMillis(), deserJob.getMegabyteMillis()); // check all FileSystem counters are here assertEquals(Sets.newHashSet("FileSystemCounters"), deserJob.getCounters().getGroups()); assertEquals(actualJob.getCounters().getGroup("FileSystemCounters"), deserJob.getCounters().getGroup("FileSystemCounters")); }
Example 17
Source File: ContentImporter.java From fuchsia with Apache License 2.0 | 3 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<LinkerNode> rootList = new ArrayList<LinkerNode>(); ObjectMapper mapper = new ObjectMapper(); for (Factory factory : content.getFuchsiaFactories(IMPORTER_SERVICE_INTERFACE, IMPORTER_SERVICE_PROPERTIES)) { rootList.add(new LinkerNode(factory.getName())); } /* try { ServiceReference[] references=context.getServiceReferences(Factory.class.getName(),null); if(references!=null) { for (ServiceReference sr : references) { for(String key:sr.getPropertyKeys()){ System.out.println(key+"----->" + sr.getProperty(key)); } System.out.println("######################################"); Factory fact=(Factory) context.getService(sr); } } } catch (InvalidSyntaxException e) { e.printStackTrace(); } */ //rootList.add(new ImportationLinkerNode("jander fact")); mapper.writeValue(resp.getWriter(), rootList); }
Example 18
Source File: UnionsWithNullJacksonOneTest.java From raml-java-tools with Apache License 2.0 | 3 votes |
@Test public void withString() throws IOException { NilUnionTypeJ1Impl nilUnionType = new NilUnionTypeJ1Impl("somevalue"); ObjectMapper mapper = new ObjectMapper(); StringWriter out = new StringWriter(); mapper.writeValue(out, nilUnionType); NilUnionTypeJ1 b = mapper.readValue(new StringReader(out.toString()), NilUnionTypeJ1.class); assertEquals("somevalue", b.getString()); }
Example 19
Source File: InsertImporter.java From fuchsia with Apache License 2.0 | 3 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ObjectMapper mapper = new ObjectMapper(); try { Collection<ServiceReference<Factory>> services = context.getServiceReferences(Factory.class, String.format("(factory.name=%s)", req.getParameter("importerCombo"))); if (services.size() == 1) { ServiceReference factorySR = (ServiceReference) services.iterator().next(); Factory factory = (Factory) context.getService(factorySR); Dictionary<String, Object> hs = new Hashtable<String, Object>(); String filter = getValue(req.getParameter("importerTarget")); FuchsiaUtils.getFilter(filter); hs.put(ImporterService.TARGET_FILTER_PROPERTY, filter); String instanceName = req.getParameter("importerInstanceName"); if (instanceName != null && instanceName.trim().length() != 0) { hs.put(Factory.INSTANCE_NAME_PROPERTY, instanceName); } ComponentInstance ci = factory.createComponentInstance(hs); mapper.writeValue(resp.getWriter(), new ViewMessage("success", "Importer created successfully.")); } } catch (Exception e) { LOG.info("Error while preparing response", e); mapper.writeValue(resp.getWriter(), new ViewMessage("error", e.getMessage())); } }
Example 20
Source File: InsertExporter.java From fuchsia with Apache License 2.0 | 3 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ObjectMapper mapper = new ObjectMapper(); try { Collection<ServiceReference<Factory>> services = context.getServiceReferences(Factory.class, String.format("(factory.name=%s)", req.getParameter("exporterCombo"))); if (services.size() == 1) { ServiceReference factorySR = (ServiceReference) services.iterator().next(); Factory factory = (Factory) context.getService(factorySR); Dictionary<String, Object> hs = new Hashtable<String, Object>(); String filter = getValue(req.getParameter("exporterTarget")); FuchsiaUtils.getFilter(filter); hs.put(ImporterService.TARGET_FILTER_PROPERTY, filter); String instanceName = req.getParameter("exporterInstanceName"); if (instanceName != null && instanceName.trim().length() != 0) { hs.put(Factory.INSTANCE_NAME_PROPERTY, instanceName); } ComponentInstance ci = factory.createComponentInstance(hs); mapper.writeValue(resp.getWriter(), new ViewMessage("success", "Exporter created successfully.")); } } catch (Exception e) { LOG.info("Error while preparing response", e); mapper.writeValue(resp.getWriter(), new ViewMessage("error", e.getMessage())); } }