List of usage examples for com.fasterxml.jackson.databind ObjectMapper writeValue
public void writeValue(Writer w, Object value) throws IOException, JsonGenerationException, JsonMappingException
From source file:de.stadtrallye.rallyesoft.model.Server.java
public void save() throws IOException { ObjectMapper mapper = Serialization.getJsonInstance(); mapper.writeValue(Storage.getServerConfigOutputStream(), this); }
From source file:it.bz.tis.integreen.carsharingbzit.api.ApiClient.java
public <T> T callWebService(ServiceRequest request, Class<T> clazz) throws IOException { request.request.technicalUser.username = this.user; request.request.technicalUser.password = this.password; ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE) .setVisibility(PropertyAccessor.IS_GETTER, Visibility.PUBLIC_ONLY) .setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY) .setVisibility(PropertyAccessor.SETTER, Visibility.PUBLIC_ONLY); mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); mapper.writeValue(sw, request); String requestJson = sw.getBuffer().toString(); logger.debug("callWebService(): jsonRequest:" + requestJson); URL url = new URL(this.endpoint); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true);/* ww w. ja v a 2s. c o m*/ OutputStream out = conn.getOutputStream(); out.write(requestJson.getBytes("UTF-8")); out.flush(); int responseCode = conn.getResponseCode(); InputStream input = conn.getInputStream(); ByteArrayOutputStream data = new ByteArrayOutputStream(); int len; byte[] buf = new byte[50000]; while ((len = input.read(buf)) > 0) { data.write(buf, 0, len); } conn.disconnect(); String jsonResponse = new String(data.toByteArray(), "UTF-8"); if (responseCode != 200) { throw new IOException(jsonResponse); } logger.debug("callWebService(): jsonResponse:" + jsonResponse); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); T response = mapper.readValue(new StringReader(jsonResponse), clazz); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); sw = new StringWriter(); mapper.writeValue(sw, response); logger.debug( "callWebService(): parsed response into " + response.getClass().getName() + ":" + sw.toString()); return response; }
From source file:org.finra.dm.tools.common.databridge.AbstractDataBridgeTest.java
/** * Serializes provided manifest instance as JSON output, written to a file in the specified directory. * * @param baseDir the local parent directory path, relative to which the manifest file should be created * @param manifest the manifest instance to serialize * * @return the resulting file//from ww w .ja v a 2s . c om */ protected File createManifestFile(String baseDir, Object manifest) throws IOException { // Create result file object Path resultFilePath = Paths.get(baseDir, String.format("manifest-%d.json", getNextUniqueIndex())); File resultFile = new File(resultFilePath.toString()); // Convert Java object to JSON format ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(resultFile, manifest); return resultFile; }
From source file:org.dawnsci.commandserver.core.process.ProgressableProcess.java
/** * /*from ww w . j a va2 s . co m*/ * @param dir * @param fileName * @throws Exception */ protected void writeProjectBean(final File dir, final String fileName) throws Exception { final File beanFile = new File(dir, fileName); ObjectMapper mapper = new ObjectMapper(); beanFile.getParentFile().mkdirs(); if (!beanFile.exists()) beanFile.createNewFile(); final FileOutputStream stream = new FileOutputStream(beanFile); try { mapper.writeValue(stream, bean); } finally { stream.close(); } }
From source file:it.uniroma2.sag.kelp.linearization.nystrom.NystromMethod.java
/** * Save a Nystrom-based projection function in a file. If the .gz suffix is * used a compressed file is obtained/*from w w w . j a v a 2s .c o m*/ * * @param outputFilePath * the output file path * @throws FileNotFoundException * @throws IOException */ public void save(String outputFilePath) throws FileNotFoundException, IOException { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); OutputStreamWriter out = new OutputStreamWriter(FileUtils.createOutputStream(outputFilePath), "utf8"); mapper.writeValue(out, this); out.close(); }
From source file:com.ikanow.aleph2.data_model.utils.TestCrudUtils.java
/** Create a DB object from a bean template * @param bean_template/*from w w w.java 2 s. co m*/ * @return * @throws IOException * @throws JsonMappingException * @throws JsonGenerationException */ public static DBObject convertBeanTemplate(BeanTemplate<Object> bean_template, ObjectMapper object_mapper) { try { final BsonObjectGenerator generator = new BsonObjectGenerator(); object_mapper.writeValue(generator, bean_template.get()); return generator.getDBObject(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java
public InputStream addJsonInlinecount(final InputStream src, final int count, final Accept accept) throws Exception { final ObjectMapper mapper = new ObjectMapper(); final JsonNode srcNode = mapper.readTree(src); ((ObjectNode) srcNode).put(ODATA_COUNT_NAME, count); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); mapper.writeValue(bos, srcNode); final InputStream res = new ByteArrayInputStream(bos.toByteArray()); IOUtils.closeQuietly(bos);//from w ww . ja v a 2 s.c o m return res; }
From source file:servlets.Signin.java
/** * Processing POST requests on /signup// www . jav a2 s . co m * * @param request servlet request in JSON * @param response servlet response inJSON * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // JSON ? ? StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { jb.append(line); } } catch (IOException ex) { } String sourceJson = jb.toString(); ObjectMapper mapper = new ObjectMapper(); InsertUserTemplate userToAdd = mapper.readValue(sourceJson, InsertUserTemplate.class); // JSON ? int status = UserActions.loginUser(userToAdd, request.getSession().getId()); try (PrintWriter out = response.getWriter()) { if (status == 200) { InsertedUserTemplate userTempl = new InsertedUserTemplate(status, request.getSession().getId()); mapper.writeValue(out, userTempl); } else { response.setStatus(status); ErrorTemplate error = new ErrorTemplate(status); mapper.writeValue(out, error); } } catch (Exception e) { //do somthing } }
From source file:fll.web.api.SubjectiveScoresServlet.java
@SuppressFBWarnings(value = { "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING" }, justification = "columns and category are dynamic") @Override/* w ww .j ava 2 s. c o m*/ protected final void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { final ServletContext application = getServletContext(); final DataSource datasource = ApplicationAttributes.getDataSource(application); Connection connection = null; PreparedStatement prep = null; ResultSet rs = null; try { connection = datasource.getConnection(); final int currentTournament = Queries.getCurrentTournament(connection); // category->judge->teamNumber->score final Map<String, Map<String, Map<Integer, SubjectiveScore>>> allScores = new HashMap<String, Map<String, Map<Integer, SubjectiveScore>>>(); final ChallengeDescription challengeDescription = ApplicationAttributes .getChallengeDescription(application); for (final ScoreCategory sc : challengeDescription.getSubjectiveCategories()) { // judge->teamNumber->score final Map<String, Map<Integer, SubjectiveScore>> categoryScores = new HashMap<String, Map<Integer, SubjectiveScore>>(); prep = connection.prepareStatement("SELECT * FROM " + sc.getName() + " WHERE Tournament = ?"); prep.setInt(1, currentTournament); rs = prep.executeQuery(); while (rs.next()) { final SubjectiveScore score = new SubjectiveScore(); score.setScoreOnServer(true); final String judge = rs.getString("Judge"); final Map<Integer, SubjectiveScore> judgeScores; if (categoryScores.containsKey(judge)) { judgeScores = categoryScores.get(judge); } else { judgeScores = new HashMap<Integer, SubjectiveScore>(); categoryScores.put(judge, judgeScores); } score.setTeamNumber(rs.getInt("TeamNumber")); score.setJudge(judge); score.setNoShow(rs.getBoolean("NoShow")); score.setNote(rs.getString("note")); final Map<String, Double> standardSubScores = new HashMap<String, Double>(); final Map<String, String> enumSubScores = new HashMap<String, String>(); for (final AbstractGoal goal : sc.getGoals()) { if (goal.isEnumerated()) { final String value = rs.getString(goal.getName()); enumSubScores.put(goal.getName(), value); } else { final double value = rs.getDouble(goal.getName()); standardSubScores.put(goal.getName(), value); } } score.setStandardSubScores(standardSubScores); score.setEnumSubScores(enumSubScores); judgeScores.put(score.getTeamNumber(), score); } allScores.put(sc.getName(), categoryScores); SQLFunctions.close(rs); rs = null; SQLFunctions.close(prep); prep = null; } final ObjectMapper jsonMapper = new ObjectMapper(); response.reset(); response.setContentType("application/json"); final PrintWriter writer = response.getWriter(); jsonMapper.writeValue(writer, allScores); } catch (final SQLException e) { throw new RuntimeException(e); } finally { SQLFunctions.close(rs); SQLFunctions.close(prep); SQLFunctions.close(connection); } }
From source file:com.github.braully.graph.DatabaseFacade.java
public static synchronized void saveResult(UndirectedSparseGraphTO graph, IGraphOperation graphOperation, Map<String, Object> result, List<String> consoleOut) { if (result != null && graph != null && graphOperation != null) { try {/*from w ww.j a v a 2s.com*/ List<RecordResultGraph> results = null; ObjectMapper mapper = new ObjectMapper(); try { results = mapper.readValue(new File(DATABASE_URL), List.class); } catch (Exception e) { } if (results == null) { results = new ArrayList<RecordResultGraph>(); } RecordResultGraph record = new RecordResultGraph(); String fileGraph = saveGraph(graph); String fileConsole = saveConsole(consoleOut, fileGraph); record.status = "ok"; record.graph = fileGraph; record.name = graph.getName(); record.edges = "" + graph.getEdgeCount(); record.vertices = "" + graph.getVertexCount(); record.operation = graphOperation.getName(); record.type = graphOperation.getTypeProblem(); record.date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()); record.results = resultMapToString(result); record.id = "" + results.size(); record.console = fileConsole; results.add(record); mapper.writeValue(new File(DATABASE_URL), results); removeBatchDiretoryIfExists(graph); } catch (Exception e) { e.printStackTrace(); } } }