List of usage examples for com.fasterxml.jackson.core JsonFactory JsonFactory
public JsonFactory()
From source file:com.greplin.gec.GecLogbackAppender.java
/** * Writes a formatted exception to the given writer. * * @param message the log message// w ww .j a va2s . co m * @param throwableProxy the exception * @param level the error level * @param out the destination * @throws IOException if there are IO errors in the destination */ private void writeFormattedException(final String message, final IThrowableProxy throwableProxy, final Level level, final Writer out) throws IOException { JsonGenerator generator = new JsonFactory().createJsonGenerator(out); IThrowableProxy rootThrowable = throwableProxy; while (this.passthroughExceptions.contains(rootThrowable.getClassName()) && rootThrowable.getCause() != null) { rootThrowable = rootThrowable.getCause(); } generator.writeStartObject(); generator.writeStringField("project", this.project); generator.writeStringField("environment", this.environment); generator.writeStringField("serverName", this.serverName); // FIXME this was 'throwable' generator.writeStringField("backtrace", getStackTrace(rootThrowable)); generator.writeStringField("message", rootThrowable.getMessage()); generator.writeStringField("logMessage", message); generator.writeStringField("type", rootThrowable.getClassName()); if (level != Level.ERROR) { generator.writeStringField("errorLevel", level.toString()); } writeContext(generator); generator.writeEndObject(); generator.close(); }
From source file:com.baasbox.configuration.PropertiesConfigurationHelper.java
public static String dumpConfigurationSectionAsFlatJson(String section) { Class en = CONFIGURATION_SECTIONS.get(section); try {/*from w w w . ja v a 2s. c o m*/ JsonFactory jfactory = new JsonFactory(); StringWriter sw = new StringWriter(); String enumDescription = ""; JsonGenerator gen = jfactory.createJsonGenerator(sw); gen.writeStartArray(); EnumSet values = EnumSet.allOf(en); for (Object v : values) { String key = (String) (en.getMethod("getKey")).invoke(v); boolean isVisible = (Boolean) (en.getMethod("isVisible")).invoke(v); String valueAsString; if (isVisible) valueAsString = (String) (en.getMethod("getValueAsString")).invoke(v); else valueAsString = "--HIDDEN--"; boolean isEditable = (Boolean) (en.getMethod("isEditable")).invoke(v); boolean isOverridden = (Boolean) (en.getMethod("isOverridden")).invoke(v); String valueDescription = (String) (en.getMethod("getValueDescription")).invoke(v); Class type = (Class) en.getMethod("getType").invoke(v); gen.writeStartObject(); // { gen.writeStringField("key", key); gen.writeStringField("value", valueAsString); gen.writeStringField("description", valueDescription); // ,"description":"description" gen.writeStringField("type", type.getSimpleName()); // ,"type":"type" gen.writeBooleanField("editable", isEditable); gen.writeBooleanField("overridden", isOverridden); gen.writeEndObject(); // } } if (gen.getOutputContext().inArray()) gen.writeEndArray(); // ] gen.close(); return sw.toString(); } catch (Exception e) { BaasBoxLogger.error("Cannot generate a json for " + en.getSimpleName() + " Enum. Is it an Enum that implements the IProperties interface?", e); } return "{}"; }
From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java
@Override public SerializerResult serviceDocument(final ServiceMetadata metadata, final String serviceRoot) throws SerializerException { OutputStream outputStream = null; SerializerException cachedException = null; try {//from w ww.j a va 2s .c o m CircleStreamBuffer buffer = new CircleStreamBuffer(); outputStream = buffer.getOutputStream(); JsonGenerator json = new JsonFactory().createGenerator(outputStream); new ServiceDocumentJsonSerializer(metadata, serviceRoot, isODataMetadataNone) .writeServiceDocument(json); json.close(); outputStream.close(); return SerializerResultImpl.with().content(buffer.getInputStream()).build(); } catch (final IOException e) { cachedException = new SerializerException(IO_EXCEPTION_TEXT, e, SerializerException.MessageKeys.IO_EXCEPTION); throw cachedException; } finally { closeCircleStreamBufferOutput(outputStream, cachedException); } }
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);/*from w w w. java2 s.c om*/ 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:net.floodlightcontroller.configuration.ConfigurationManager.java
/** * Reads a configuration file and calls the corresponding configuration * listeners./*w w w . j a v a 2 s .c o m*/ * * @param file An optional configuration file name. */ private void readJsonFromFile(String fileName) { String configFile = (fileName != null) ? fileName : this.fileName; ObjectMapper mapper = new ObjectMapper(); JsonFactory f = new JsonFactory(); JsonParser jp = null; try { jp = f.createJsonParser(new File(configFile)); JsonNode root = mapper.readTree(jp); // Check if the file is empty. if (root == null) return; Iterator<Entry<String, JsonNode>> iter = root.fields(); // For every configuration sub-node. while (iter.hasNext()) { Entry<String, JsonNode> entry = iter.next(); String fieldName = entry.getKey(); JsonNode child = entry.getValue(); if (configurationListener.containsKey(fieldName)) { configurationListener.get(fieldName).putJsonConfig(child); } else { if (logger.isWarnEnabled()) { logger.warn("No configuration listener found for " + fieldName); } } } } catch (FileNotFoundException e) { if (logger.isWarnEnabled()) { logger.warn("Configuration file {} not found.", configFile); } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.ConsistentHashTest.java
License:asdf
@Test public void itAppliesConsistentHashingForRequestsOutsideCoverageZone() throws Exception { CloseableHttpResponse response = null; try {/*from w ww.java 2 s .co m*/ String requestPath = URLEncoder.encode("/some/path/thing", "UTF-8"); HttpGet httpGet = new HttpGet( "http://localhost:3333/crs/consistenthash/cache/geolocation?ip=8.8.8.8&deliveryServiceId=" + deliveryServiceId + "&requestPath=" + requestPath); response = closeableHttpClient.execute(httpGet); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); ObjectMapper objectMapper = new ObjectMapper(new JsonFactory()); JsonNode cacheNode = objectMapper.readTree(EntityUtils.toString(response.getEntity())); String cacheId = cacheNode.get("id").asText(); assertThat(cacheId, not(equalTo(""))); response.close(); response = closeableHttpClient.execute(httpGet); cacheNode = objectMapper.readTree(EntityUtils.toString(response.getEntity())); assertThat(cacheNode.get("id").asText(), equalTo(cacheId)); response.close(); requestPath = URLEncoder.encode("/another/different/path", "UTF-8"); httpGet = new HttpGet( "http://localhost:3333/crs/consistenthash/cache/geolocation?ip=8.8.8.8&deliveryServiceId=" + deliveryServiceId + "&requestPath=" + requestPath); response = closeableHttpClient.execute(httpGet); cacheNode = objectMapper.readTree(EntityUtils.toString(response.getEntity())); assertThat(cacheNode.get("id").asText(), not(equalTo(cacheId))); assertThat(cacheNode.get("id").asText(), not(equalTo(""))); } finally { if (response != null) response.close(); } }
From source file:org.springframework.social.weibo.api.impl.WeiboErrorHandler.java
private Map<String, String> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException { ObjectMapper mapper = new ObjectMapper(new JsonFactory()); String json = readFully(response.getBody()); System.out.println(json);//from w ww. j av a 2 s . com if (logger.isDebugEnabled()) { logger.debug("Error from Weibo: " + json); } try { return mapper.<Map<String, String>>readValue(json, new TypeReference<Map<String, String>>() { }); } catch (JsonParseException e) { return null; } }
From source file:com.adobe.communities.ugc.migration.importer.GenericUGCImporter.java
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { final ResourceResolver resolver = request.getResourceResolver(); UGCImportHelper.checkUserPrivileges(resolver, rrf); final String path = request.getRequestParameter("path").getString(); final Resource resource = resolver.getResource(path); if (resource == null) { throw new ServletException("Could not find a valid resource for import"); }//w ww . j a va2s.com final String filePath = request.getRequestParameter("filePath").getString(); if (!filePath.startsWith(ImportFileUploadServlet.UPLOAD_DIR)) { throw new ServletException("Path to file resource lies outside migration import path"); } final Resource fileResource = resolver.getResource(filePath); if (fileResource == null) { throw new ServletException("Could not find a valid file resource to read"); } // get the input stream from the file resource Resource file = fileResource.getChild("file"); if (null != file && !(file instanceof NonExistingResource)) { file = file.getChild(JcrConstants.JCR_CONTENT); if (null != file && !(file instanceof NonExistingResource)) { final ValueMap contentVM = file.getValueMap(); InputStream inputStream = (InputStream) contentVM.get(JcrConstants.JCR_DATA); if (inputStream != null) { final JsonParser jsonParser = new JsonFactory().createParser(inputStream); jsonParser.nextToken(); // get the first token importFile(jsonParser, resource, resolver); ImportFileUploadServlet.deleteResource(fileResource); return; } } } throw new ServletException("Unable to read file in provided file resource path"); }
From source file:com.kaloer.yummly.Yummly.java
/** * Searches for recipes matching a given query. * /*from w w w . jav a 2s .c o m*/ * @param query * The query to search for. * @param requirePictures * If true, only recipes with pictures are returned. * @param requiredIngredients * A list of required ingredient names in the recipes. * @param excludedIngredients * A list of excluded ingredient names in the recipes. * @param maxTotalTimeInSeconds * The maximum total preparetion and cooking time in seconds. * @param minFlavors * The minimum flavor levels. * @param maxFlavors * The maximum flavor levels. * @param ingredientFacetField * If true, the result will contain the total count of each * ingredient in the matched recipes. * @param dietFacetField * If true, the result will contain the total count of each * diet in the matched recipes. * @return The result of the search. Be aware that the the returned recipes * are sparse. Use the {@link #getRecipe(String)} method to receive * all available information. * @throws IOException * Thrown if network or parsing errors occur. */ public SearchResult search(String query, boolean requirePictures, ArrayList<String> requiredIngredients, ArrayList<String> excludedIngredients, int maxTotalTimeInSeconds, Flavors minFlavors, Flavors maxFlavors, boolean ingredientFacetField, boolean dietFacetField, ArrayList<NutritionRange> nutritionRanges) throws IOException { // Set parameters. ArrayList<Parameter> params = new ArrayList<Parameter>(); params.add(new Parameter("q", URLEncoder.encode(query, "utf8"))); params.add(new Parameter("requirePictures", requirePictures ? "true" : "false")); if (requiredIngredients != null) { for (String ingredient : requiredIngredients) { params.add(new Parameter(URLEncoder.encode("requiredIngredient[]", "utf8"), URLEncoder.encode(ingredient, "utf8"))); } } if (excludedIngredients != null) { for (String ingredient : excludedIngredients) { params.add(new Parameter(URLEncoder.encode("excludedIngredient[]", "utf8"), URLEncoder.encode(ingredient, "utf8"))); } } if (ingredientFacetField) { params.add(new Parameter(URLEncoder.encode("facetField[]", "utf8"), URLEncoder.encode("ingredient", "utf8"))); } if (dietFacetField) { params.add(new Parameter(URLEncoder.encode("facetField[]", "utf8"), URLEncoder.encode("diet", "utf8"))); } if (maxTotalTimeInSeconds > 0) { params.add(new Parameter("maxTotalTimeInSeconds", Integer.toString(maxTotalTimeInSeconds))); } if (minFlavors != null) { if (minFlavors.getSweet() != null) { params.add(new Parameter("flavor.sweet.min", minFlavors.getSweet().toString())); } if (minFlavors.getBitter() != null) { params.add(new Parameter("flavor.bitter.min", minFlavors.getBitter().toString())); } if (minFlavors.getMeaty() != null) { params.add(new Parameter("flavor.meaty.min", minFlavors.getMeaty().toString())); } if (minFlavors.getPiquant() != null) { params.add(new Parameter("flavor.piquant.min", minFlavors.getPiquant().toString())); } if (minFlavors.getSalty() != null) { params.add(new Parameter("flavor.salty.min", minFlavors.getSalty().toString())); } if (minFlavors.getSour() != null) { params.add(new Parameter("flavor.sour.min", minFlavors.getSour().toString())); } } if (maxFlavors != null) { if (maxFlavors.getSweet() != null) { params.add(new Parameter("flavor.sweet.max", maxFlavors.getSweet().toString())); } if (maxFlavors.getBitter() != null) { params.add(new Parameter("flavor.bitter.max", maxFlavors.getBitter().toString())); } if (maxFlavors.getMeaty() != null) { params.add(new Parameter("flavor.meaty.max", maxFlavors.getMeaty().toString())); } if (maxFlavors.getPiquant() != null) { params.add(new Parameter("flavor.piquant.max", maxFlavors.getPiquant().toString())); } if (maxFlavors.getSalty() != null) { params.add(new Parameter("flavor.salty.max", maxFlavors.getSalty().toString())); } if (maxFlavors.getSour() != null) { params.add(new Parameter("flavor.sour.max", maxFlavors.getSour().toString())); } } if (nutritionRanges != null) { for (NutritionRange range : nutritionRanges) { params.add( new Parameter( URLEncoder.encode( String.format("nutrition.%s.max", range.getNutrition().toString()), "utf8"), range.getMax().toString())); params.add( new Parameter( URLEncoder.encode( String.format("nutrition.%s.min", range.getNutrition().toString()), "utf8"), range.getMin().toString())); } } // Perform search request. InputStream in = performRequest("recipes", params); // Parse json. JsonFactory factory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(factory); SearchResult result = mapper.readValue(in, SearchResult.class); in.close(); return result; }
From source file:org.hawkular.wildfly.agent.itest.util.AbstractITest.java
@BeforeMethod public void before() { JsonFactory f = new JsonFactory(); mapper = new ObjectMapper(f); InventoryJacksonConfig.configure(mapper); this.client = new OkHttpClient(); }