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:com.proofpoint.http.client.SmileBodyGenerator.java
public static <T> SmileBodyGenerator<T> smileBodyGenerator(JsonCodec<T> jsonCodec, T instance) { ObjectMapper objectMapper = OBJECT_MAPPER_SUPPLIER.get(); ByteArrayOutputStream out = new ByteArrayOutputStream(); JsonGenerator jsonGenerator;//from w w w . ja va 2 s. c om try { jsonGenerator = new SmileFactory().createGenerator(out); } catch (IOException e) { throw propagate(e); } Type genericType = jsonCodec.getType(); // 04-Mar-2010, tatu: How about type we were given? (if any) JavaType rootType = null; if (genericType != null && instance != null) { // 10-Jan-2011, tatu: as per [JACKSON-456], it's not safe to just force root // type since it prevents polymorphic type serialization. Since we really // just need this for generics, let's only use generic type if it's truly // generic. if (genericType.getClass() != Class.class) { // generic types are other implementations of 'java.lang.reflect.Type' // This is still not exactly right; should root type be further // specialized with 'value.getClass()'? Let's see how well this works before // trying to come up with more complete solution. rootType = objectMapper.getTypeFactory().constructType(genericType); // 26-Feb-2011, tatu: To help with [JACKSON-518], we better recognize cases where // type degenerates back into "Object.class" (as is the case with plain TypeVariable, // for example), and not use that. // if (rootType.getRawClass() == Object.class) { rootType = null; } } } try { if (rootType != null) { objectMapper.writerWithType(rootType).writeValue(jsonGenerator, instance); } else { objectMapper.writeValue(jsonGenerator, instance); } } catch (IOException e) { throw new IllegalArgumentException( String.format("%s could not be converted to SMILE", instance.getClass().getName()), e); } return new SmileBodyGenerator<>(out.toByteArray()); }
From source file:org.apache.taverna.robundle.manifest.Manifest.java
/** * Write as an RO Bundle JSON-LD manifest * /*from w ww. j a v a 2s .co m*/ * @return The path of the written manifest (e.g. ".ro/manifest.json") * @throws IOException */ public Path writeAsJsonLD() throws IOException { Path jsonld = bundle.getFileSystem().getPath(RO, MANIFEST_JSON); createDirectories(jsonld.getParent()); // Files.createFile(jsonld); if (!getManifest().contains(jsonld)) getManifest().add(0, jsonld); ObjectMapper om = new ObjectMapper(); om.addMixInAnnotations(Path.class, PathMixin.class); om.addMixInAnnotations(FileTime.class, FileTimeMixin.class); om.enable(INDENT_OUTPUT); om.disable(WRITE_EMPTY_JSON_ARRAYS); om.disable(FAIL_ON_EMPTY_BEANS); om.disable(WRITE_NULL_MAP_VALUES); om.setSerializationInclusion(Include.NON_NULL); try (Writer w = newBufferedWriter(jsonld, Charset.forName("UTF-8"), WRITE, TRUNCATE_EXISTING, CREATE)) { om.writeValue(w, this); } return jsonld; }
From source file:com.webtide.jetty.load.generator.jenkins.cometd.CometdProjectAction.java
public void doTrend(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { ObjectMapper objectMapper = new ObjectMapper(); List<BuildLoadResults> datas = new ArrayList<>(); for (Run run : builds) { CometdResultBuildAction buildAction = run.getAction(CometdResultBuildAction.class); if (buildAction != null) { if (buildAction.getLoadResults() != null) { BuildLoadResults buildLoadResults = new BuildLoadResults(run.getId(), buildAction.getLoadResults()); datas.add(buildLoadResults); }//from w w w . jav a2 s.c o m } } // order by buildId Collections.sort(datas, Comparator.comparing(BuildLoadResults::getBuildId)); //StringWriter stringWriter = new StringWriter(); rsp.setHeader("Content-Type", "application/json"); objectMapper.writeValue(rsp.getOutputStream(), datas); //rsp.getWriter().write( data ); }
From source file:uk.ac.cam.cl.dtg.isaac.quiz.IsaacSymbolicValidator.java
@Override public QuestionValidationResponse validateQuestionResponse(final Question question, final Choice answer) throws ValidatorUnavailableException { Validate.notNull(question);// w w w .j ava2s .co m Validate.notNull(answer); if (!(question instanceof IsaacSymbolicQuestion)) { throw new IllegalArgumentException( String.format("This validator only works with Isaac Symbolic Questions... (%s is not symbolic)", question.getId())); } if (!(answer instanceof Formula)) { throw new IllegalArgumentException( String.format("Expected Formula for IsaacSymbolicQuestion: %s. Received (%s) ", question.getId(), answer.getClass())); } IsaacSymbolicQuestion symbolicQuestion = (IsaacSymbolicQuestion) question; Formula submittedFormula = (Formula) answer; // These variables store the important features of the response we'll send. Content feedback = null; // The feedback we send the user MatchType responseMatchType = MatchType.NONE; // The match type we found boolean responseCorrect = false; // Whether we're right or wrong // There are several specific responses the user can receive. Each of them will set feedback content, so // use that to decide whether to proceed to the next check in each case. // STEP 0: Do we even have any answers for this question? Always do this check, because we know we // won't have feedback yet. if (null == symbolicQuestion.getChoices() || symbolicQuestion.getChoices().isEmpty()) { log.error("Question does not have any answers. " + question.getId() + " src: " + question.getCanonicalSourceFile()); feedback = new Content("This question does not have any correct answers"); } // STEP 1: Did they provide an answer? if (null == feedback && (null == submittedFormula.getPythonExpression() || submittedFormula.getPythonExpression().isEmpty())) { feedback = new Content("You did not provide an answer"); } // STEP 2: Otherwise, Does their answer match a choice exactly? if (null == feedback) { // For all the choices on this question... for (Choice c : symbolicQuestion.getChoices()) { // ... that are of the Formula type, ... if (!(c instanceof Formula)) { log.error("Isaac Symbolic Validator for questionId: " + symbolicQuestion.getId() + " expected there to be a Formula. Instead it found a Choice."); continue; } Formula formulaChoice = (Formula) c; // ... and that have a python expression ... if (null == formulaChoice.getPythonExpression() || formulaChoice.getPythonExpression().isEmpty()) { log.error("Expected python expression, but none found in choice for question id: " + symbolicQuestion.getId()); continue; } // ... look for an exact string match to the submitted answer. if (formulaChoice.getPythonExpression().equals(submittedFormula.getPythonExpression())) { feedback = (Content) formulaChoice.getExplanation(); responseMatchType = MatchType.EXACT; responseCorrect = formulaChoice.isCorrect(); } } } // STEP 3: Otherwise, use the symbolic checker to analyse their answer if (null == feedback) { // Go through all choices, keeping track of the best match we've seen so far. A symbolic match terminates // this loop immediately. A numeric match may later be replaced with a symbolic match, but otherwise will suffice. Formula closestMatch = null; MatchType closestMatchType = MatchType.NONE; // Sort the choices so that we match incorrect choices last, taking precedence over correct ones. List<Choice> orderedChoices = Lists.newArrayList(symbolicQuestion.getChoices()); Collections.sort(orderedChoices, new Comparator<Choice>() { @Override public int compare(Choice o1, Choice o2) { int o1Val = o1.isCorrect() ? 0 : 1; int o2Val = o2.isCorrect() ? 0 : 1; return o1Val - o2Val; } }); // For all the choices on this question... for (Choice c : orderedChoices) { // ... that are of the Formula type, ... if (!(c instanceof Formula)) { // Don't need to log this - it will have been logged above. continue; } Formula formulaChoice = (Formula) c; // ... and that have a python expression ... if (null == formulaChoice.getPythonExpression() || formulaChoice.getPythonExpression().isEmpty()) { // Don't need to log this - it will have been logged above. continue; } // ... test their answer against this choice with the symbolic checker. // We don't do any sanitisation of user input here, we'll leave that to the python. MatchType matchType = MatchType.NONE; try { // This is ridiculous. All I want to do is pass some JSON to a REST endpoint and get some JSON back. ObjectMapper mapper = new ObjectMapper(); HashMap<String, String> req = Maps.newHashMap(); req.put("target", formulaChoice.getPythonExpression()); req.put("test", submittedFormula.getPythonExpression()); req.put("description", symbolicQuestion.getId()); StringWriter sw = new StringWriter(); JsonGenerator g = new JsonFactory().createGenerator(sw); mapper.writeValue(g, req); g.close(); String requestString = sw.toString(); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://" + hostname + ":" + port + "/check"); httpPost.setEntity(new StringEntity(requestString, "UTF-8")); httpPost.addHeader("Content-Type", "application/json"); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); String responseString = EntityUtils.toString(responseEntity); HashMap<String, Object> response = mapper.readValue(responseString, HashMap.class); if (response.containsKey("error")) { if (response.containsKey("code")) { log.error("Failed to check formula \"" + submittedFormula.getPythonExpression() + "\" against \"" + formulaChoice.getPythonExpression() + "\": " + response.get("error")); } else { // If it doesn't contain a code, it wasn't a fatal error in the checker; probably only a // problem with the submitted answer. log.warn("Problem checking formula \"" + submittedFormula.getPythonExpression() + "\" for (" + symbolicQuestion.getId() + ") with symbolic checker: " + response.get("error")); } } else { if (response.get("equal").equals("true")) { matchType = MatchType.valueOf(((String) response.get("equality_type")).toUpperCase()); } } } catch (IOException e) { log.error( "Failed to check formula with symbolic checker. Is the server running? Not trying again."); throw new ValidatorUnavailableException( "We are having problems marking Symbolic Questions." + " Please try again later!"); } if (matchType == MatchType.EXACT) { closestMatch = formulaChoice; closestMatchType = MatchType.EXACT; break; } else if (matchType.compareTo(closestMatchType) > 0) { if (formulaChoice.getRequiresExactMatch() && formulaChoice.isCorrect()) { closestMatch = formulaChoice; closestMatchType = matchType; } else { if (closestMatch == null || !closestMatch.getRequiresExactMatch()) { closestMatch = formulaChoice; closestMatchType = matchType; } else { // This is not as good a match as the one we already have. } } } } if (null != closestMatch) { // We found a decent match. Of course, it still might be wrong. if (closestMatchType != MatchType.EXACT && closestMatch.getRequiresExactMatch()) { if (closestMatch.isCorrect()) { feedback = new Content( "Your answer is not in the form we expected. Can you rearrange or simplify it?"); responseCorrect = false; responseMatchType = closestMatchType; log.info("User submitted an answer that was close to an exact match, but not exact " + "for question " + symbolicQuestion.getId() + ". Choice: " + closestMatch.getPythonExpression() + ", submitted: " + submittedFormula.getPythonExpression()); } else { // This is weak match to a wrong answer; we can't use the feedback for the choice. } } else { feedback = (Content) closestMatch.getExplanation(); responseCorrect = closestMatch.isCorrect(); responseMatchType = closestMatchType; } if (closestMatchType == MatchType.NUMERIC) { log.info("User submitted an answer that was only numerically equivalent to one of our choices " + "for question " + symbolicQuestion.getId() + ". Choice: " + closestMatch.getPythonExpression() + ", submitted: " + submittedFormula.getPythonExpression()); // TODO: Decide whether we want to add something to the explanation along the lines of "you got it // right, but only numerically. } } } // If we got this far and feedback is still null, they were wrong. There's no useful feedback we can give at this point. return new FormulaValidationResponse(symbolicQuestion.getId(), answer, feedback, responseCorrect, responseMatchType.toString(), new Date()); }
From source file:com.arpnetworking.logback.serialization.BaseSerializationStrategy.java
/** * Write specified key-value pairs into the current block. * * @param keys The <code>List</code> of keys. * @param values The <code>List</code> of values. * @param jsonGenerator <code>JsonGenerator</code> instance. * @param objectMapper <code>ObjectMapper</code> instance. * @throws IOException If writing JSON fails. *//* www .java 2s.co m*/ protected void writeKeyValuePairs(final List<String> keys, final List<Object> values, final JsonGenerator jsonGenerator, final ObjectMapper objectMapper) throws IOException { if (keys != null) { final int contextValuesLength = values == null ? 0 : values.size(); for (int i = 0; i < keys.size(); ++i) { final String key = keys.get(i); if (i >= contextValuesLength) { jsonGenerator.writeObjectField(key, null); } else { final Object value = values.get(i); if (isSimpleType(value)) { jsonGenerator.writeObjectField(key, value); } else { jsonGenerator.writeFieldName(key); objectMapper.writeValue(jsonGenerator, value); } } } } }
From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java
public InputStream wrapJsonEntities(final InputStream entities) throws Exception { final ObjectMapper mapper = new ObjectMapper(); final JsonNode node = mapper.readTree(entities); final ObjectNode res; final JsonNode value = node.get(JSON_VALUE_NAME); if (value.isArray()) { res = mapper.createObjectNode(); res.set("value", value); final JsonNode next = node.get(JSON_NEXTLINK_NAME); if (next != null) { res.set(JSON_NEXTLINK_NAME, next); }/*ww w. j a va 2 s .co m*/ } else { res = (ObjectNode) value; } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); mapper.writeValue(bos, res); final InputStream is = new ByteArrayInputStream(bos.toByteArray()); IOUtils.closeQuietly(bos); return is; }
From source file:org.mitre.secretsharing.server.JoinServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); resp.setContentType("application/json"); try {/*from ww w .j a v a 2s .co m*/ Request jreq = mapper.readValue(req.getParameter("q"), Request.class); if (jreq.parts == null) throw new IllegalArgumentException(); Part[] parts = new Part[jreq.parts.size()]; for (int i = 0; i < parts.length; i++) parts[i] = PartFormats.parse(jreq.parts.get(i)); byte[] secret = parts[0].join(Arrays.copyOfRange(parts, 1, parts.length)); Response jresp = new Response(); jresp.status = "ok"; if (jreq.base64 != null && jreq.base64) jresp.secret = Base64Variants.MIME_NO_LINEFEEDS.encode(secret); else jresp.secret = new String(secret, "UTF-8"); mapper.writeValue(resp.getOutputStream(), jresp); } catch (Throwable t) { t.printStackTrace(); Response jresp = new Response(); jresp.status = "error"; mapper.writeValue(resp.getOutputStream(), jresp); } }
From source file:org.mortbay.jetty.load.generator.jenkins.LoadGeneratorProjectAction.java
public String getAllLatencyInformations() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); List<RunInformations> datas = new ArrayList<>(); for (Run run : this.builds) { LoadGeneratorBuildAction buildAction = run.getAction(LoadGeneratorBuildAction.class); if (buildAction != null) { if (buildAction.getGlobalLatencyTimeInformations() != null) { RunInformations runInformations = new RunInformations(run.getId(), buildAction.getGlobalLatencyTimeInformations(), buildAction.getTransport()); datas.add(runInformations); }//from ww w . j av a 2 s. c o m } } // order by buildId Collections.sort(datas, Comparator.comparing(RunInformations::getBuildId)); StringWriter stringWriter = new StringWriter(); objectMapper.writeValue(stringWriter, datas); return stringWriter.toString(); }
From source file:org.mortbay.jetty.load.generator.jenkins.LoadGeneratorProjectAction.java
public String getAllResponseTimeInformations() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); List<RunInformations> datas = new ArrayList<>(); for (Run run : this.builds) { LoadGeneratorBuildAction buildAction = run.getAction(LoadGeneratorBuildAction.class); if (buildAction != null) { if (buildAction.getGlobalResponseTimeInformations() != null) { RunInformations runInformations = new RunInformations(run.getId(), buildAction.getGlobalResponseTimeInformations(), buildAction.getTransport()); datas.add(runInformations); }/*ww w . j a v a 2s .com*/ } } // order by buildId Collections.sort(datas, Comparator.comparing(RunInformations::getBuildId)); StringWriter stringWriter = new StringWriter(); objectMapper.writeValue(stringWriter, datas); return stringWriter.toString(); }
From source file:org.apache.kylin.tool.CubeMetaExtractor.java
private void engineOverwriteInternal(File f) throws IOException { try {/*from ww w . j ava 2s. co m*/ ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(f); boolean replaced = false; if (engineType != null && rootNode.get("engine_type") != null) { ((ObjectNode) rootNode).put("engine_type", Integer.parseInt(engineType)); replaced = true; } if (storageType != null && rootNode.get("storage_type") != null) { ((ObjectNode) rootNode).put("storage_type", Integer.parseInt(storageType)); replaced = true; } if (replaced) { objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.writeValue(f, rootNode); } } catch (JsonProcessingException ex) { logger.warn("cannot parse file {}", f); } }