List of usage examples for com.fasterxml.jackson.databind ObjectMapper writerWithDefaultPrettyPrinter
public ObjectWriter writerWithDefaultPrettyPrinter()
From source file:webServices.RestServiceImpl.java
@GET @Path("/requestMaps") @Produces({ MediaType.APPLICATION_JSON }) public Response requestMaps(@QueryParam("title") String title, @QueryParam("creator") String creator, @QueryParam("license") String license, @QueryParam("theme") String theme, @QueryParam("extent") String extent) throws EndpointCommunicationException, JsonProcessingException { String mapURL = HTTP + servlet.getServerName() + ":" + servlet.getServerPort() + context.getContextPath() + "?mapid="; Vector<MyMap> mapResults = new Vector<MyMap>(); //Reset to default registry values endpointStore = new MapEndpointStore(); //Construct query String query = "PREFIX strdf: <http://strdf.di.uoa.gr/ontology#> " + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> " + "SELECT ?mapId ?title ?creator ?license ?theme ?description ?geom WHERE { " + "?mapId <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <" + MapVocabulary.MAP + "> . " + "?mapId <" + MapVocabulary.HASTITLE + "> ?title . " + "?mapId <" + MapVocabulary.HASCREATOR + "> ?creator . " + "?mapId <" + MapVocabulary.HASLICENSE + "> ?license . " + "?mapId <" + MapVocabulary.HASTHEME + "> ?theme . " + "?mapId <" + MapVocabulary.HASDESCRIPTION + "> ?description . " + "?mapId <" + MapVocabulary.HASGEOMETRY + "> ?geom . "; if (title != null) { query = query.concat("FILTER regex(?title, \"" + title + "\", \"i\") . "); }//ww w . java 2 s . co m if (creator != null) { query = query.concat("FILTER regex(?creator, \"" + creator + "\", \"i\") . "); } if (license != null) { query = query.concat("FILTER regex(?license, \"" + license + "\", \"i\") . "); } if (theme != null) { query = query.concat("FILTER regex(?theme, \"" + theme + "\", \"i\") . "); } if (extent != null) { String wkt = extentToWKT(extent); System.out.println(wkt); query = query.concat("FILTER (strdf:mbbIntersects(?geom, \"" + wkt + "\"^^<http://www.opengis.net/ont/geosparql#wktLiteral>)) . "); } query = query.concat("}"); //Pose query Vector<String> results = endpointStore.searchForMaps(query); //Parse results for (int i = 0; i < results.size(); i = i + 7) { Vector<Distribution> ds = new Vector<Distribution>(); ds.add(new Distribution("Distribution", "Sextant", mapURL.concat(results.get(i).substring(results.get(i).lastIndexOf("/") + 1)))); MyMap tempMap = new MyMap( mapURL.concat( results.get(i).substring(results.get(i).lastIndexOf("/") + 1, results.get(i).length())), results.get(i + 1), results.get(i + 2), results.get(i + 3), results.get(i + 4), results.get(i + 5), new Extent("Location", results.get(i + 6) .substring(results.get(i + 6).indexOf("POLYGON"), results.get(i + 6).length())), ds); mapResults.add(tempMap); } ObjectMapper mapper = new ObjectMapper(); String output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Maps(mapResults, HTTP + servlet.getServerName() + ":" + servlet.getServerPort() + context.getContextPath())); output = output.replaceAll("\"context\"", "\"@context\""); output = output.replaceAll("\"type\"", "\"@type\""); output = output.replaceAll("\"id\"", "\"@id\""); return Response.ok().entity(output).header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Methods", "GET").build(); }
From source file:webServices.RestServiceImpl.java
@GET @Path("/findTwittsRest") @Produces({ MediaType.TEXT_PLAIN })/*from w w w . j ava2 s .c o m*/ public String twitterSearchRest(@QueryParam("keys") String searchKeys, @QueryParam("sinceId") long sinceId, @QueryParam("maxId") long maxId, @QueryParam("update") boolean update, @QueryParam("location") String location) { final Vector<String> results = new Vector<String>(); String output = ""; long higherStatusId = Long.MIN_VALUE; long lowerStatusId = Long.MAX_VALUE; Query searchQuery = new Query(searchKeys); searchQuery.setCount(50); searchQuery.setResultType(Query.ResultType.recent); if (sinceId != 0) { if (update) { searchQuery.setSinceId(sinceId); } higherStatusId = sinceId; } if (maxId != 0) { if (!update) { searchQuery.setMaxId(maxId); } lowerStatusId = maxId; } if (location != null) { double lat = Double.parseDouble(location.substring(0, location.indexOf(","))); double lon = Double.parseDouble(location.substring(location.indexOf(",") + 1, location.length())); searchQuery.setGeoCode(new GeoLocation(lat, lon), 10, Query.KILOMETERS); } try { QueryResult qResult = twitter.search(searchQuery); for (Status status : qResult.getTweets()) { //System.out.println(Long.toString(status.getId())+" *** "+Long.toString(status.getUser().getId())+" *** "+status.isRetweet()+" *** "+status.isRetweeted()); higherStatusId = Math.max(status.getId(), higherStatusId); lowerStatusId = Math.min(status.getId(), lowerStatusId); if (!status.isRetweet()) { if (status.getGeoLocation() != null) { System.out.println(Long.toString(status.getId()) + "@" + Double.toString(status.getGeoLocation().getLatitude()) + "," + Double.toString(status.getGeoLocation().getLongitude())); results.add(Long.toString(status.getId()) + "@" + Double.toString(status.getGeoLocation().getLatitude()) + "," + Double.toString(status.getGeoLocation().getLongitude())); } else { results.add(Long.toString(status.getId()) + "@null"); } } } } catch (TwitterException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } TwitterResults resultsObj = new TwitterResults(results.toString(), higherStatusId, lowerStatusId); ObjectMapper mapper = new ObjectMapper(); try { output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultsObj); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return output; }
From source file:org.sakaiproject.lti13.LTI13Servlet.java
protected SakaiAccessToken getSakaiAccessToken(Key publicKey, HttpServletRequest request, HttpServletResponse response) {/*www .j a va 2 s.c o m*/ String authorization = request.getHeader("authorization"); if (authorization == null || !authorization.startsWith("Bearer")) { log.error("Invalid authorization {}", authorization); LTI13Util.return400(response, "invalid_authorization"); return null; } // https://stackoverflow.com/questions/7899525/how-to-split-a-string-by-space/7899558 String[] parts = authorization.split("\\s+"); if (parts.length != 2 || parts[1].length() < 1) { log.error("Bad authorization {}", authorization); LTI13Util.return400(response, "invalid_authorization"); return null; } String jws = parts[1]; Claims claims; try { claims = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(jws).getBody(); } catch (ExpiredJwtException | MalformedJwtException | UnsupportedJwtException | io.jsonwebtoken.security.SignatureException | IllegalArgumentException e) { log.error("Signature error {}\n{}", e.getMessage(), jws); LTI13Util.return400(response, "signature_error"); return null; } // Reconstruct the SakaiAccessToken // https://www.baeldung.com/jackson-deserialization SakaiAccessToken sat; try { ObjectMapper mapper = new ObjectMapper(); String jsonResult = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(claims); // System.out.println("jsonResult=" + jsonResult); sat = new ObjectMapper().readValue(jsonResult, SakaiAccessToken.class); } catch (IOException ex) { log.error("PARSE ERROR {}\n{}", ex.getMessage(), claims.toString()); LTI13Util.return400(response, "token_parse_failure", ex.getMessage()); return null; } // Validity check the access token if (sat.tool_id != null && sat.scope != null && sat.expires != null) { // All good } else { log.error("SakaiAccessToken missing required data {}", sat); LTI13Util.return400(response, "Missing required data in access_token"); return null; } return sat; }
From source file:org.wso2.developerstudio.datamapper.diagram.tree.generator.SchemaTransformer.java
/** * Updates schema file// w ww . jav a2s. c o m */ @Override public void updateSchemaFile(String content, File file) { try { // check of content is null to prevent object mapper throwing // exceptions due to empty content if (content != null && !content.isEmpty()) { ObjectMapper mapper = new ObjectMapper(); Object json = mapper.readValue(content, Object.class); FileUtils.writeStringToFile(file, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json)); } else { FileUtils.writeStringToFile(file, ""); } } catch (IOException e) { log.error(ERROR_WRITING_SCHEMA_FILE + file.getName(), e); return; } }
From source file:org.opencb.opencga.app.cli.main.OpenCGAMainOld.java
private StringBuilder createOutput(OptionsParser.CommonOptions commonOptions, List list, StringBuilder sb) throws JsonProcessingException { if (sb == null) { sb = new StringBuilder(); }/* w w w. j a v a 2 s .c o m*/ String idSeparator = null; switch (commonOptions.outputFormat) { case IDS: idSeparator = idSeparator == null ? "\n" : idSeparator; case ID_CSV: idSeparator = idSeparator == null ? "," : idSeparator; case ID_LIST: idSeparator = idSeparator == null ? "," : idSeparator; { if (!list.isEmpty()) { try { Iterator iterator = list.iterator(); Object next = iterator.next(); if (next instanceof QueryResult) { createOutput(commonOptions, (QueryResult) next, sb); } else { sb.append(getId(next)); } while (iterator.hasNext()) { next = iterator.next(); if (next instanceof QueryResult) { sb.append(idSeparator); createOutput(commonOptions, (QueryResult) next, sb); } else { sb.append(idSeparator).append(getId(next)); } } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } break; } case NAME_ID_MAP: { if (!list.isEmpty()) { try { Iterator iterator = list.iterator(); Object object = iterator.next(); if (object instanceof QueryResult) { createOutput(commonOptions, (QueryResult) object, sb); } else { sb.append(getName(object)).append(":").append(getId(object)); } while (iterator.hasNext()) { object = iterator.next(); if (object instanceof QueryResult) { sb.append(","); createOutput(commonOptions, (QueryResult) object, sb); } else { sb.append(",").append(getName(object)).append(":").append(getId(object)); } } } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) { e.printStackTrace(); } } break; } case RAW: if (list != null) { for (Object o : list) { sb.append(String.valueOf(o)); } } break; default: logger.warn("Unsupported output format \"{}\" for that query", commonOptions.outputFormat); case PRETTY_JSON: case PLAIN_JSON: JsonFactory factory = new JsonFactory(); ObjectMapper objectMapper = new ObjectMapper(factory); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); ObjectWriter objectWriter = commonOptions.outputFormat == OptionsParser.OutputFormat.PRETTY_JSON ? objectMapper.writerWithDefaultPrettyPrinter() : objectMapper.writer(); if (list != null && !list.isEmpty()) { Iterator iterator = list.iterator(); sb.append(objectWriter.writeValueAsString(iterator.next())); while (iterator.hasNext()) { sb.append("\n").append(objectWriter.writeValueAsString(iterator.next())); } } break; } return sb; }
From source file:org.apache.drill.exec.store.parquet.Metadata.java
private void writeFile(ParquetTableMetadataDirs parquetTableMetadataDirs, Path p) throws IOException { JsonFactory jsonFactory = new JsonFactory(); jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false); jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false); ObjectMapper mapper = new ObjectMapper(jsonFactory); SimpleModule module = new SimpleModule(); mapper.registerModule(module);/*from w ww.j av a 2 s .c o m*/ FSDataOutputStream os = fs.create(p); mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadataDirs); os.flush(); os.close(); }
From source file:org.apache.drill.exec.store.parquet.Metadata.java
/** * Serialize parquet metadata to json and write to a file * * @param parquetTableMetadata/*from w w w . jav a 2s.c o m*/ * @param p * @throws IOException */ private void writeFile(ParquetTableMetadata_v3 parquetTableMetadata, Path p) throws IOException { JsonFactory jsonFactory = new JsonFactory(); jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false); jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false); ObjectMapper mapper = new ObjectMapper(jsonFactory); SimpleModule module = new SimpleModule(); module.addSerializer(ColumnMetadata_v3.class, new ColumnMetadata_v3.Serializer()); mapper.registerModule(module); FSDataOutputStream os = fs.create(p); mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadata); os.flush(); os.close(); }
From source file:org.onehippo.forge.content.pojo.model.CsvConvertToContentNodesTest.java
@Test public void testReadCsvAndConvertToContentNodes() throws Exception { InputStream input = null;//from ww w . j a v a 2 s .com InputStreamReader reader = null; try { // 1. Open a reader from a CSV file. input = NEWS_CSV_URL.openStream(); reader = new InputStreamReader(input, "UTF-8"); // 2. Create CSV parser to parse the CSV data with column headers. CSVParser parser = CSVFormat.DEFAULT.withHeader("Title", "Introduction", "Date", "Content") .withSkipHeaderRecord().parse(reader); CSVRecord record; // 3. StringCodec to generate a JCR node name from the title column, // and ObjectMapper instance to log a ContentNode to JSON. final StringCodec codec = new StringCodecFactory.UriEncoding(); final ObjectMapper objectMapper = new ObjectMapper(); String name; String title; String introduction; String date; String content; String translationId; String translationLocale = "en"; String targetDocumentLocation; // 4. Iterate each data record and create a ContentNode for a news article with setting properties and child nodes. for (Iterator<CSVRecord> it = parser.iterator(); it.hasNext();) { record = it.next(); // 4.1. Read each column from a CSV record. title = record.get("Title"); name = codec.encode(title); introduction = record.get("Introduction"); date = record.get("Date"); content = record.get("Content"); // 4.2. Create a ContentNode for a news article and set primitive property values. ContentNode newsNode = new ContentNode(name, "ns1:newsdocument"); newsNode.setProperty("ns1:title", title); newsNode.setProperty("ns1:introduction", introduction); newsNode.setProperty("ns1:date", ContentPropertyType.DATE, date); // 4.3. Create/add a child hippostd:html content node and set the content. ContentNode htmlNode = new ContentNode("ns1:content", HippoStdNodeType.NT_HTML); newsNode.addNode(htmlNode); htmlNode.setProperty(HippoStdNodeType.HIPPOSTD_CONTENT, content); // 4.4. In Hippo CMS, the internal translation UUID and locale string are important in most cases. // So, let's generate a translation UUID and use 'en' for simplicity for now. translationId = UUID.randomUUID().toString(); newsNode.setProperty(HippoTranslationNodeType.ID, translationId); newsNode.setProperty(HippoTranslationNodeType.LOCALE, translationLocale); // 4.5. (Optional) Set kind of meta property for localized document name which is displayed in folder view later. // This meta property is not used by Hippo CMS, but can be read/used by a higher level content importing application // to set a localized (translated) name of the document (e.g, using Hippo TranslationWorkflow). newsNode.setProperty("jcr:localizedName", title); // 4.6. (Optional) Determine the target document location where this content should be generated and // store it in a meta property, jcr:path. // This meta property cannot be used in JCR repository in importing process, but can be read/used by a higher level // content importing application to create a document using Hippo DocumentWorkflow for instance. targetDocumentLocation = "/content/documents/ns1/news/" + name; newsNode.setProperty("jcr:path", targetDocumentLocation); // 4.7. (Optional) Log the JSON-ized string of the news ContentNode instance. StringWriter stringWriter = new StringWriter(256); objectMapper.writerWithDefaultPrettyPrinter().writeValue(stringWriter, newsNode); log.debug("newsNode: \n{}\n", stringWriter.toString()); } } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(input); } }
From source file:ch.rasc.extclassgenerator.ModelGenerator.java
public static String generateJavascript(ModelBean model, OutputConfig outputConfig) { if (!outputConfig.isDebug()) { JsCacheKey key = new JsCacheKey(model, outputConfig); SoftReference<String> jsReference = jsCache.get(key); if (jsReference != null && jsReference.get() != null) { return jsReference.get(); }//from ww w . jav a 2 s . c om } ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false); if (!outputConfig.isSurroundApiWithQuotes()) { if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5) { mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithoutApiQuotesExtJs5Mixin.class); } else { mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithoutApiQuotesMixin.class); } mapper.addMixInAnnotations(ApiObject.class, ApiObjectMixin.class); } else { if (outputConfig.getOutputFormat() != OutputFormat.EXTJS5) { mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithApiQuotesMixin.class); } } Map<String, Object> modelObject = new LinkedHashMap<String, Object>(); modelObject.put("extend", model.getExtend()); if (!model.getAssociations().isEmpty()) { Set<String> usesClasses = new HashSet<String>(); for (AbstractAssociation association : model.getAssociations()) { usesClasses.add(association.getModel()); } usesClasses.remove(model.getName()); if (!usesClasses.isEmpty()) { modelObject.put("uses", usesClasses); } } Map<String, Object> configObject = new LinkedHashMap<String, Object>(); ProxyObject proxyObject = new ProxyObject(model, outputConfig); Map<String, ModelFieldBean> fields = model.getFields(); Set<String> requires = new HashSet<String>(); if (!model.getValidations().isEmpty() && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) { requires = addValidatorsToField(fields, model.getValidations()); } if (proxyObject.hasContent() && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) { requires.add("Ext.data.proxy.Direct"); } if (StringUtils.hasText(model.getIdentifier()) && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) { if ("sequential".equals(model.getIdentifier())) { requires.add("Ext.data.identifier.Sequential"); } else if ("uuid".equals(model.getIdentifier())) { requires.add("Ext.data.identifier.Uuid"); } else if ("negative".equals(model.getIdentifier())) { requires.add("Ext.data.identifier.Negative"); } } if (requires != null && !requires.isEmpty()) { configObject.put("requires", requires); } if (StringUtils.hasText(model.getIdentifier())) { if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5 || outputConfig.getOutputFormat() == OutputFormat.TOUCH2) { configObject.put("identifier", model.getIdentifier()); } else { configObject.put("idgen", model.getIdentifier()); } } if (StringUtils.hasText(model.getIdProperty()) && !model.getIdProperty().equals("id")) { configObject.put("idProperty", model.getIdProperty()); } if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5 && StringUtils.hasText(model.getVersionProperty())) { configObject.put("versionProperty", model.getVersionProperty()); } if (StringUtils.hasText(model.getClientIdProperty())) { if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5 || outputConfig.getOutputFormat() == OutputFormat.EXTJS4) { configObject.put("clientIdProperty", model.getClientIdProperty()); } else if (outputConfig.getOutputFormat() == OutputFormat.TOUCH2 && !"clientId".equals(model.getClientIdProperty())) { configObject.put("clientIdProperty", model.getClientIdProperty()); } } for (ModelFieldBean field : fields.values()) { field.updateTypes(outputConfig); } List<Object> fieldConfigObjects = new ArrayList<Object>(); for (ModelFieldBean field : fields.values()) { if (field.hasOnlyName(outputConfig)) { fieldConfigObjects.add(field.getName()); } else { fieldConfigObjects.add(field); } } configObject.put("fields", fieldConfigObjects); if (!model.getAssociations().isEmpty()) { configObject.put("associations", model.getAssociations()); } if (!model.getValidations().isEmpty() && !(outputConfig.getOutputFormat() == OutputFormat.EXTJS5)) { configObject.put("validations", model.getValidations()); } if (proxyObject.hasContent()) { configObject.put("proxy", proxyObject); } if (outputConfig.getOutputFormat() == OutputFormat.EXTJS4 || outputConfig.getOutputFormat() == OutputFormat.EXTJS5) { modelObject.putAll(configObject); } else { modelObject.put("config", configObject); } StringBuilder sb = new StringBuilder(); sb.append("Ext.define(\"").append(model.getName()).append("\","); if (outputConfig.isDebug()) { sb.append("\n"); } String configObjectString; Class<?> jsonView = JsonViews.ExtJS4.class; if (outputConfig.getOutputFormat() == OutputFormat.TOUCH2) { jsonView = JsonViews.Touch2.class; } else if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5) { jsonView = JsonViews.ExtJS5.class; } try { if (outputConfig.isDebug()) { configObjectString = mapper.writerWithDefaultPrettyPrinter().withView(jsonView) .writeValueAsString(modelObject); } else { configObjectString = mapper.writerWithView(jsonView).writeValueAsString(modelObject); } } catch (JsonGenerationException e) { throw new RuntimeException(e); } catch (JsonMappingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } sb.append(configObjectString); sb.append(");"); String result = sb.toString(); if (outputConfig.isUseSingleQuotes()) { result = result.replace('"', '\''); } if (!outputConfig.isDebug()) { jsCache.put(new JsCacheKey(model, outputConfig), new SoftReference<String>(result)); } return result; }