Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#writeValue()
The following examples show how to use
com.fasterxml.jackson.databind.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: SwaggerService.java From ob1k with Apache License 2.0 | 6 votes |
private Response buildJsonResponse(final Object value) { try { final StringWriter buffer = new StringWriter(); final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.writeValue(buffer, value); return ResponseBuilder.ok() .withContent(buffer.toString()) .addHeader(CONTENT_TYPE, "application/json; charset=UTF-8") .build(); } catch (final IOException e) { return ResponseBuilder.fromStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR). withContent(e.getMessage()).build(); } }
Example 2
Source File: SwaggerGenMojo.java From herd with Apache License 2.0 | 6 votes |
/** * Creates the YAML file in the output location based on the Swagger metadata. * * @param swagger the Swagger metadata. * * @throws MojoExecutionException if any error was encountered while writing the YAML information to the file. */ private void createYamlFile(Swagger swagger) throws MojoExecutionException { String yamlOutputLocation = outputDirectory + "/" + outputFilename; try { getLog().debug("Creating output YAML file \"" + yamlOutputLocation + "\""); ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); objectMapper.setPropertyNamingStrategy(new SwaggerNamingStrategy()); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.writeValue(new File(yamlOutputLocation), swagger); } catch (IOException e) { throw new MojoExecutionException("Error creating output YAML file \"" + yamlOutputLocation + "\". Reason: " + e.getMessage(), e); } }
Example 3
Source File: JSonBindingUtilsTest.java From roboconf-platform with Apache License 2.0 | 6 votes |
@Test public void testApplicationTemplateBinding_4() throws Exception { final String result = "{\"name\":\"my application\",\"displayName\":\"my application\",\"apps\":[]}"; ObjectMapper mapper = JSonBindingUtils.createObjectMapper(); ApplicationTemplate app = new ApplicationTemplate( "my application" ); StringWriter writer = new StringWriter(); mapper.writeValue( writer, app ); String s = writer.toString(); Assert.assertEquals( result, s ); ApplicationTemplate readApp = mapper.readValue( result, ApplicationTemplate.class ); Assert.assertEquals( app, readApp ); Assert.assertEquals( app.getName(), readApp.getName()); Assert.assertEquals( app.getDescription(), readApp.getDescription()); Assert.assertEquals( app.getVersion(), readApp.getVersion()); Assert.assertEquals( app.getExternalExportsPrefix(), readApp.getExternalExportsPrefix()); Assert.assertEquals( app.getTags(), readApp.getTags()); }
Example 4
Source File: JSonBindingUtilsTest.java From roboconf-platform with Apache License 2.0 | 6 votes |
@Test public void testPreferenceBinding_2() throws Exception { final String result = "{\"name\":\"mail.toto\",\"value\":\"smtp.something\",\"category\":\"email\"}"; ObjectMapper mapper = JSonBindingUtils.createObjectMapper(); // Test the serializer Preference pref = new Preference( "mail.toto", "smtp.something", PreferenceKeyCategory.EMAIL ); StringWriter writer = new StringWriter(); mapper.writeValue( writer, pref ); String s = writer.toString(); Assert.assertEquals( result, s ); // Test the deserializer Preference readPref = mapper.readValue( result, Preference.class ); Assert.assertNotNull( readPref ); Assert.assertEquals( "mail.toto", readPref.getName()); Assert.assertEquals( "smtp.something", readPref.getValue()); Assert.assertEquals( PreferenceKeyCategory.EMAIL, readPref.getCategory()); }
Example 5
Source File: JsonBasedAuthenticatorTest.java From timbuctoo with GNU General Public License v3.0 | 6 votes |
@Test public void createLoginIgnoresTheAdditionOfLoginOfAKnownUserName() throws Exception { Login[] logins = new Login[0]; Path emptyLoginsFile = FileHelpers.makeTempFilePath(true); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.writeValue(emptyLoginsFile.toFile(), logins); JsonBasedAuthenticator instance = backedByFile(emptyLoginsFile); String userName = "userName"; instance.createLogin("userPid", userName, "password", "givenName", "surname", "email", "org"); instance.createLogin("userPid2", userName, "password1", "givenName2", "surname2", "email2", "org2"); List<Login> loginList = objectMapper.readValue(emptyLoginsFile.toFile(), new TypeReference<List<Login>>() { }); long count = loginList.stream().filter(login -> Objects.equals(login.getUsername(), userName)).count(); assertThat(count, is(1L)); Files.delete(emptyLoginsFile); }
Example 6
Source File: LogstashAppenderFactoryHelper.java From dropwizard-logstash-encoder with Eclipse Public License 1.0 | 5 votes |
public static Optional<String> getCustomFieldsFromHashMap(HashMap<String, String> map) { StringWriter writer = new StringWriter(); ObjectMapper mapper = new ObjectMapper(); try { mapper.writeValue(writer, map); } catch (IOException e) { System.err.println("unable to parse customFields: " + e.getMessage()); return Optional.empty(); } return Optional.of(writer.toString()); }
Example 7
Source File: GenerateSwaggerJsonForWebSockets.java From roboconf-platform with Apache License 2.0 | 5 votes |
/** * Prepares the JSon object to inject as the new definitions in the swagger.json file. * @return a non-null map (key = operation ID, value = example) * @throws IOException if something went wrong */ public Map<String,String> prepareNewDefinitions() throws IOException { Map<String,String> result = new HashMap<> (); ObjectMapper mapper = JSonBindingUtils.createObjectMapper(); StringWriter writer = new StringWriter(); // Create a model, as complete as possible Application app = UpdateSwaggerJson.newTestApplication(); // Serialize things and generate the examples Instance tomcat = InstanceHelpers.findInstanceByPath( app, "/tomcat-vm/tomcat-server" ); Objects.requireNonNull( tomcat ); WebSocketMessage msg = new WebSocketMessage( tomcat, app, EventType.CHANGED ); writer = new StringWriter(); mapper.writeValue( writer, msg ); result.put( INSTANCE, writer.toString()); msg = new WebSocketMessage( app, EventType.CREATED ); writer = new StringWriter(); mapper.writeValue( writer, msg ); result.put( APPLICATION, writer.toString()); msg = new WebSocketMessage( app.getTemplate(), EventType.DELETED ); writer = new StringWriter(); mapper.writeValue( writer, msg ); result.put( APPLICATION_TEMPLATE, writer.toString()); msg = new WebSocketMessage( "A text message." ); writer = new StringWriter(); mapper.writeValue( writer, msg ); result.put( TEXT, writer.toString()); return result; }
Example 8
Source File: UserDefinedFunctionHandler.java From aws-athena-query-federation with Apache License 2.0 | 5 votes |
protected final void doHandleRequest(BlockAllocator allocator, ObjectMapper objectMapper, UserDefinedFunctionRequest req, OutputStream outputStream) throws Exception { logger.info("doHandleRequest: request[{}]", req); try (UserDefinedFunctionResponse response = processFunction(allocator, req)) { logger.info("doHandleRequest: response[{}]", response); assertNotNull(response); objectMapper.writeValue(outputStream, response); } }
Example 9
Source File: JSonBindingUtilsTest.java From roboconf-platform with Apache License 2.0 | 5 votes |
@Test public void testApplicationTemplateBinding_6() throws Exception { ApplicationTemplate app = new ApplicationTemplate( "my application" ); app.externalExports.put( "k1", "v1" ); app.externalExports.put( "k2", "v2" ); ObjectMapper mapper = JSonBindingUtils.createObjectMapper(); StringWriter writer = new StringWriter(); mapper.writeValue( writer, app ); String s = writer.toString(); Assert.assertEquals( "{\"name\":\"my application\",\"displayName\":\"my application\",\"extVars\":{\"k1\":\"v1\",\"k2\":\"v2\"},\"apps\":[]}", s ); }
Example 10
Source File: ModuleConfigJsonTest.java From pnc with Apache License 2.0 | 5 votes |
@Test public void serializationTest() throws JsonGenerationException, JsonMappingException, IOException { ModuleConfigJson moduleConfigJson = new ModuleConfigJson("pnc-config"); JenkinsBuildDriverModuleConfig jenkinsBuildDriverModuleConfig = new JenkinsBuildDriverModuleConfig( "user", "pass"); IndyRepoDriverModuleConfig indyRepoDriverModuleConfig = new IndyRepoDriverModuleConfig(); indyRepoDriverModuleConfig.setBuildRepositoryAllowSnapshots(true); indyRepoDriverModuleConfig.setDefaultRequestTimeout(100); List<String> ignoredPatternsMaven = new ArrayList<>(2); ignoredPatternsMaven.add(".*/maven-metadata\\.xml$"); ignoredPatternsMaven.add(".*\\.sha1$"); IgnoredPatterns ignoredPatterns = new IgnoredPatterns(); ignoredPatterns.setMaven(ignoredPatternsMaven); IgnoredPathPatterns ignoredPathPatterns = new IgnoredPathPatterns(); ignoredPathPatterns.setPromotion(ignoredPatterns); indyRepoDriverModuleConfig.setIgnoredPathPatterns(ignoredPathPatterns); PNCModuleGroup pncGroup = new PNCModuleGroup(); pncGroup.addConfig(jenkinsBuildDriverModuleConfig); pncGroup.addConfig(indyRepoDriverModuleConfig); moduleConfigJson.addConfig(pncGroup); ObjectMapper mapper = new ObjectMapper(); PncConfigProvider<AuthenticationModuleConfig> pncProvider = new PncConfigProvider<>( AuthenticationModuleConfig.class); pncProvider.registerProvider(mapper); ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream(); mapper.writeValue(byteOutStream, moduleConfigJson); assertEquals(loadConfig("testConfigNoSpaces.json"), byteOutStream.toString()); }
Example 11
Source File: ExportPipelineCommand.java From datacollector with Apache License 2.0 | 5 votes |
@Override public void run() { if(pipelineRev == null) { pipelineRev = "0"; } try { ApiClient apiClient = getApiClient(); StoreApi storeApi = new StoreApi(apiClient); ObjectMapper mapper = apiClient.getJson().getMapper(); PipelineEnvelopeJson pipelineEnvelopeJson = storeApi.exportPipeline( pipelineId, pipelineRev, false, includeLibraryDefinitions, includePlainTextCredentials ); mapper.writeValue(new File(fileName), pipelineEnvelopeJson); System.out.println("Successfully exported pipeline '" + pipelineId + "' to file - " + fileName ); } catch (Exception ex) { if(printStackTrace) { ex.printStackTrace(); } else { System.out.println(ex.getMessage()); } } }
Example 12
Source File: MapBinding.java From qpid-broker-j with Apache License 2.0 | 5 votes |
@Override public void objectToEntry(final Map<String, Object> map, final TupleOutput output) { try { StringWriter writer = new StringWriter(); final ObjectMapper objectMapper = ConfiguredObjectJacksonModule.newObjectMapper(true); objectMapper.writeValue(writer, map); output.writeString(writer.toString()); } catch (IOException e) { throw new StoreException(e); } }
Example 13
Source File: ListNamedColors.java From constellation with Apache License 2.0 | 5 votes |
@Override public void callService(final PluginParameters parameters, final InputStream in, final OutputStream out) throws IOException { final ObjectMapper mapper = new ObjectMapper(); final ObjectNode root = mapper.createObjectNode(); ConstellationColor.NAMED_COLOR_LIST .forEach(cocol -> { root.put(cocol.getName(), cocol.getHtmlColor()); }); mapper.writeValue(out, root); }
Example 14
Source File: SiteToSiteCliMain.java From localization_nifi with Apache License 2.0 | 5 votes |
/** * Prints the usage to System.out * * @param errorMessage optional error message * @param options the options object to print usage for */ public static void printUsage(String errorMessage, Options options) { if (errorMessage != null) { System.out.println(errorMessage); System.out.println(); System.out.println(); } ObjectMapper objectMapper = new ObjectMapper(); objectMapper.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); System.out.println("s2s is a command line tool that can either read a list of DataPackets from stdin to send over site-to-site or write the received DataPackets to stdout"); System.out.println(); System.out.println("The s2s cli input/output format is a JSON list of DataPackets. They can have the following formats:"); try { System.out.println(); objectMapper.writeValue(System.out, Arrays.asList(new DataPacketDto("hello nifi".getBytes(StandardCharsets.UTF_8)).putAttribute("key", "value"))); System.out.println(); System.out.println("Where data is the base64 encoded value of the FlowFile content (always used for received data) or"); System.out.println(); objectMapper.writeValue(System.out, Arrays.asList(new DataPacketDto(new HashMap<>(), new File("EXAMPLE").getAbsolutePath()).putAttribute("key", "value"))); System.out.println(); System.out.println("Where dataFile is a file to read the FlowFile content from"); System.out.println(); System.out.println(); System.out.println("Example usage to send a FlowFile with the contents of \"hey nifi\" to a local unsecured NiFi over http with an input port named input:"); System.out.print("echo '"); DataPacketDto dataPacketDto = new DataPacketDto("hey nifi".getBytes(StandardCharsets.UTF_8)); dataPacketDto.setAttributes(null); objectMapper.writeValue(System.out, Arrays.asList(dataPacketDto)); System.out.println("' | bin/s2s.sh -n input -p http"); System.out.println(); } catch (IOException e) { e.printStackTrace(); } HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setWidth(160); helpFormatter.printHelp("s2s", options); System.out.flush(); }
Example 15
Source File: VisualizerOld.java From pyramid with Apache License 2.0 | 4 votes |
private void storeJson(File jsonFile, Map<?, ?> data) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(jsonFile, data); }
Example 16
Source File: LambdaMARTModelConverter.java From ltr4l with Apache License 2.0 | 4 votes |
@Override public final void write(SolrLTRModel model, Writer writer) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.writeValue(writer, model); }
Example 17
Source File: ReflectJSON.java From constellation with Apache License 2.0 | 4 votes |
@Override public void callService(final PluginParameters parameters, final InputStream in, final OutputStream out) throws IOException { final ObjectMapper mapper = new ObjectMapper(); final JsonNode json = mapper.readTree(in); mapper.writeValue(out, json); }
Example 18
Source File: AbstractRepositoryManagerDriverTest.java From pnc with Apache License 2.0 | 4 votes |
@Before public void setup() throws Exception { MDC.put("dummy", "non"); // workaround for NPE in Indy 1.6.2 client fixture = newServerFixture(); Properties sysprops = System.getProperties(); oldIni = sysprops.getProperty(CONFIG_SYSPROP); url = fixture.getUrl(); File configFile = temp.newFile("pnc-config.json"); ModuleConfigJson moduleConfigJson = new ModuleConfigJson("pnc-config"); IndyRepoDriverModuleConfig mavenRepoDriverModuleConfig = new IndyRepoDriverModuleConfig(); mavenRepoDriverModuleConfig.setIgnoredRepoPatterns(getIgnoredRepoPatterns()); SystemConfig systemConfig = new SystemConfig( "", "", "JAAS", "4", "4", "4", "", "5", null, null, "14", "", "10"); GlobalModuleGroup globalConfig = new GlobalModuleGroup(); globalConfig.setIndyUrl(fixture.getUrl()); PNCModuleGroup pncGroup = new PNCModuleGroup(); pncGroup.addConfig(mavenRepoDriverModuleConfig); pncGroup.addConfig(systemConfig); moduleConfigJson.addConfig(globalConfig); moduleConfigJson.addConfig(pncGroup); ObjectMapper mapper = new ObjectMapper(); PncConfigProvider<IndyRepoDriverModuleConfig> pncProvider = new PncConfigProvider<>( IndyRepoDriverModuleConfig.class); pncProvider.registerProvider(mapper); mapper.writeValue(configFile, moduleConfigJson); sysprops.setProperty(CONFIG_SYSPROP, configFile.getAbsolutePath()); System.setProperties(sysprops); fixture.start(); if (!fixture.isStarted()) { final BootStatus status = fixture.getBootStatus(); throw new IllegalStateException("server fixture failed to boot.", status.getError()); } Properties props = new Properties(); props.setProperty("base.url", url); System.out.println("Using base URL: " + url); Configuration config = new Configuration(); BuildRecordRepositoryMock bcRepository = new BuildRecordRepositoryMock(); driver = new RepositoryManagerDriver(config, bcRepository); }
Example 19
Source File: MarkupHelper.java From updatebot with Apache License 2.0 | 4 votes |
public static void saveYaml(Object data, FileObject fileObject) throws IOException { ObjectMapper mapper = createYamlObjectMapper(); try (Writer writer = fileObject.openWriter()) { mapper.writeValue(writer, data); } }
Example 20
Source File: MappingJackson2MessageConverter.java From spring4-understanding with Apache License 2.0 | 3 votes |
/** * Map the given object to a {@link TextMessage}. * @param object the object to be mapped * @param session current JMS session * @param objectMapper the mapper to use * @return the resulting message * @throws JMSException if thrown by JMS methods * @throws IOException in case of I/O errors * @see Session#createBytesMessage */ protected TextMessage mapToTextMessage(Object object, Session session, ObjectMapper objectMapper) throws JMSException, IOException { StringWriter writer = new StringWriter(); objectMapper.writeValue(writer, object); return session.createTextMessage(writer.toString()); }