List of usage examples for com.fasterxml.jackson.databind ObjectMapper writer
public ObjectWriter writer()
From source file:org.geppetto.frontend.controllers.ConnectionHandler.java
/** * Adds watch lists with variables to be watched * //from w w w . java2 s . com * @param requestID * @param jsonLists * @throws GeppettoExecutionException * @throws GeppettoInitializationException */ public void setWatchedVariables(String requestID, List<String> variables, long experimentID, long projectId, boolean watch) throws GeppettoExecutionException, GeppettoInitializationException { IGeppettoProject geppettoProject = retrieveGeppettoProject(projectId); IExperiment experiment = retrieveExperiment(experimentID, geppettoProject); if (geppettoProject.isVolatile()) { info(requestID, Resources.VOLATILE_PROJECT.toString()); return; } else { try { geppettoManager.setWatchedVariables(variables, experiment, geppettoProject, watch); } catch (GeppettoExecutionException | GeppettoAccessException e) { error(e, "Error setting watched variables"); } // serialize watch-lists ObjectMapper mapper = new ObjectMapper(); String serializedLists; try { serializedLists = mapper.writer().writeValueAsString(variables); // send to the client the watch lists were added websocketConnection.sendMessage(requestID, OutboundMessages.WATCHED_VARIABLES_SET, serializedLists); } catch (JsonProcessingException e) { error(e, "There was an error serializing the watched lists"); } } }
From source file:org.opencb.cellbase.app.cli.DownloadCommandExecutor.java
private void writeVersionDataFile(Map versionData, Path outputFilePath) { try {//from w w w . ja v a2s .c o m OutputStream os = Files.newOutputStream(outputFilePath); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); ObjectMapper jsonObjectMapper = new ObjectMapper(); ObjectWriter jsonObjectWriter = jsonObjectMapper.writer(); bw.write(jsonObjectWriter.writeValueAsString(versionData) + "\n"); bw.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.opencb.cellbase.app.cli.VariantAnnotationCommandExecutor.java
private boolean runAnnotation() throws Exception { // Build indexes for custom files and/or population frequencies file getIndexes();/*from ww w . ja v a 2s . com*/ if (variantAnnotationCommandOptions.variant != null && !variantAnnotationCommandOptions.variant.isEmpty()) { List<Variant> variants = Variant.parseVariants(variantAnnotationCommandOptions.variant); if (local) { DBAdaptorFactory dbAdaptorFactory = new MongoDBAdaptorFactory(configuration); VariantAnnotationCalculator variantAnnotationCalculator = new VariantAnnotationCalculator( this.species, this.assembly, dbAdaptorFactory); List<QueryResult<VariantAnnotation>> annotationByVariantList = variantAnnotationCalculator .getAnnotationByVariantList(variants, queryOptions); ObjectMapper jsonObjectMapper = new ObjectMapper(); jsonObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); jsonObjectMapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true); ObjectWriter objectWriter = jsonObjectMapper.writer(); Path outPath = Paths.get(variantAnnotationCommandOptions.output); FileUtils.checkDirectory(outPath.getParent()); BufferedWriter bufferedWriter = FileUtils.newBufferedWriter(outPath); for (QueryResult queryResult : annotationByVariantList) { bufferedWriter.write(objectWriter.writeValueAsString(queryResult.getResult())); bufferedWriter.newLine(); } bufferedWriter.close(); } return true; } // If a variant file is provided then we annotate it. Lines in the input file can be computationally // expensive to parse, i.e.: multisample vcf with thousands of samples. A specific task is created to enable // parallel parsing of these lines if (input != null) { DataReader dataReader = new StringDataReader(input); List<ParallelTaskRunner.TaskWithException<String, Variant, Exception>> variantAnnotatorTaskList = getStringTaskList(); DataWriter dataWriter = getDataWriter(output.toString()); ParallelTaskRunner.Config config = new ParallelTaskRunner.Config(numThreads, batchSize, QUEUE_CAPACITY, false); ParallelTaskRunner<String, Variant> runner = new ParallelTaskRunner<>(dataReader, variantAnnotatorTaskList, dataWriter, config); runner.run(); // For internal use only - will only be run when -Dpopulation-frequencies is activated writeRemainingPopFrequencies(); } else { // This will annotate the CellBase Variation collection if (cellBaseAnnotation) { // TODO: enable this query in the parseQuery method within VariantMongoDBAdaptor // Query query = new Query("$match", // new Document("annotation.consequenceTypes", new Document("$exists", 0))); // Query query = new Query(); QueryOptions options = new QueryOptions("include", "chromosome,start,reference,alternate,type"); List<ParallelTaskRunner.TaskWithException<Variant, Variant, Exception>> variantAnnotatorTaskList = getVariantTaskList(); ParallelTaskRunner.Config config = new ParallelTaskRunner.Config(numThreads, batchSize, QUEUE_CAPACITY, false); for (String chromosome : chromosomeList) { logger.info("Annotating chromosome {}", chromosome); Query query = new Query("chromosome", chromosome); DataReader dataReader = new VariationDataReader(dbAdaptorFactory.getVariationDBAdaptor(species), query, options); DataWriter dataWriter = getDataWriter( output.toString() + "/" + VARIATION_ANNOTATION_FILE_PREFIX + chromosome + ".json.gz"); ParallelTaskRunner<Variant, Variant> runner = new ParallelTaskRunner<Variant, Variant>( dataReader, variantAnnotatorTaskList, dataWriter, config); runner.run(); } } } if (customFiles != null || populationFrequenciesFile != null) { closeIndexes(); } logger.info("Variant annotation finished."); return false; }
From source file:org.opencb.cellbase.app.cli.VariantAnnotationCommandExecutor.java
private void indexPopulationFrequencies(RocksDB db) { ObjectMapper jsonObjectMapper = new ObjectMapper(); jsonObjectMapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true); ObjectWriter jsonObjectWriter = jsonObjectMapper.writer(); try {/* w w w .j a v a 2s . co m*/ DataReader<Variant> dataReader = new JsonVariantReader(populationFrequenciesFile.toString()); dataReader.open(); dataReader.pre(); int lineCounter = 0; List<Variant> variant = dataReader.read(); while (variant != null) { db.put(VariantAnnotationUtils.buildVariantId(variant.get(0).getChromosome(), variant.get(0).getStart(), variant.get(0).getReference(), variant.get(0).getAlternate()) .getBytes(), jsonObjectWriter.writeValueAsBytes(variant.get(0).getImpl())); lineCounter++; if (lineCounter % 100000 == 0) { logger.info("{} lines indexed", lineCounter); } variant = dataReader.read(); } dataReader.post(); dataReader.close(); } catch (IOException | RocksDBException e) { e.printStackTrace(); } }
From source file:org.opencb.cellbase.app.cli.VariantAnnotationCommandExecutor.java
private void indexCustomVcfFile(int customFileNumber, RocksDB db) { ObjectMapper jsonObjectMapper = new ObjectMapper(); ObjectWriter jsonObjectWriter = jsonObjectMapper.writer(); try {/*from w w w. j a va2 s .co m*/ VCFFileReader vcfFileReader = new VCFFileReader(customFiles.get(customFileNumber).toFile(), false); Iterator<VariantContext> iterator = vcfFileReader.iterator(); VariantContextToVariantConverter converter = new VariantContextToVariantConverter("", "", vcfFileReader.getFileHeader().getSampleNamesInOrder()); VariantNormalizer normalizer = new VariantNormalizer(true, false, true); int lineCounter = 0; while (iterator.hasNext()) { VariantContext variantContext = iterator.next(); // Reference positions will not be indexed if (variantContext.getAlternateAlleles().size() > 0) { List<Variant> variantList = normalizer .normalize(converter.apply(Collections.singletonList(variantContext)), true); for (Variant variant : variantList) { db.put((variant.getChromosome() + "_" + variant.getStart() + "_" + variant.getReference() + "_" + variant.getAlternate()).getBytes(), jsonObjectWriter.writeValueAsBytes(parseInfoAttributes(variant, customFileNumber))); } } lineCounter++; if (lineCounter % 100000 == 0) { logger.info("{} lines indexed", lineCounter); } } vcfFileReader.close(); } catch (IOException | RocksDBException | NonStandardCompliantSampleField e) { e.printStackTrace(); System.exit(1); } }
From source file:org.opencb.cellbase.lib.impl.GeneMongoDBAdaptor.java
@Override public QueryResult<Gene> get(Query query, QueryOptions options) { Bson bson = parseQuery(query);//w ww . j a va 2 s .co m options = addPrivateExcludeOptions(options); if (postDBFilteringParametersEnabled(query)) { QueryResult<Document> nativeQueryResult = postDBFiltering(query, mongoDBCollection.find(bson, options)); QueryResult<Gene> queryResult = new QueryResult<Gene>(nativeQueryResult.getId(), nativeQueryResult.getDbTime(), nativeQueryResult.getNumResults(), nativeQueryResult.getNumTotalResults(), nativeQueryResult.getWarningMsg(), nativeQueryResult.getErrorMsg(), null); ObjectMapper jsonObjectMapper = new ObjectMapper(); jsonObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); jsonObjectMapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true); ObjectWriter objectWriter = jsonObjectMapper.writer(); queryResult.setResult(nativeQueryResult.getResult().stream().map(document -> { try { return this.objectMapper.readValue(objectWriter.writeValueAsString(document), Gene.class); } catch (IOException e) { e.printStackTrace(); return null; } }).collect(Collectors.toList())); return queryResult; } else { return mongoDBCollection.find(bson, null, Gene.class, options); } }
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(); }//from w ww . ja 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.opentestsystem.delivery.logging.EventLoggerBase.java
public EventLoggerBase(final ObjectMapper objectMapper) { this.writer = objectMapper.writer(); extraFields.put(BaseEventData.HTTP_REQUEST_UUID.name(), UUID.randomUUID()); }
From source file:org.ownchan.server.persistence.typehandler.auto.PersistableJsonDataTypeHandler.java
public PersistableJsonDataTypeHandler() { ObjectMapper objectMapper = new ObjectMapper(); this.reader = objectMapper.reader(); this.writer = objectMapper.writer(); }
From source file:piecework.ui.InlinePageModelSerializer.java
public InlinePageModelSerializer(UserInterfaceSettings settings, Object t, Class<?> type, Entity user, ObjectMapper objectMapper) { this.settings = settings; this.t = t;/* www .j av a 2 s. c o m*/ this.type = type; PageContext pageContext = new PageContext.Builder().applicationTitle(settings.getApplicationTitle()) .assetsUrl(settings.getAssetsUrl()).user(user).build(); String pageContextAsJson; String modelAsJson; boolean isExplanation; try { pageContextAsJson = objectMapper.writer().writeValueAsString(pageContext); modelAsJson = objectMapper.writer().writeValueAsString(t); isExplanation = type != null && type.equals(Explanation.class); } catch (Exception e) { LOG.error("Unable to construct json", e); pageContextAsJson = ""; modelAsJson = ""; isExplanation = false; } this.pageContextAsJson = pageContextAsJson; this.modelAsJson = modelAsJson; this.isExplanation = isExplanation; }