List of usage examples for com.fasterxml.jackson.databind ObjectMapper writerWithDefaultPrettyPrinter
public ObjectWriter writerWithDefaultPrettyPrinter()
From source file:org.opencb.opencga.app.cli.analysis.VariantCommandExecutor.java
private void query() throws Exception { AnalysisCliOptionsParser.QueryVariantCommandOptions cliOptions = variantCommandOptions.queryVariantCommandOptions; Map<Long, String> studyIds = getStudyIds(sessionId); Query query = VariantQueryCommandUtils.parseQuery(cliOptions, studyIds); QueryOptions queryOptions = VariantQueryCommandUtils.parseQueryOptions(cliOptions); VariantFetcher variantFetcher = new VariantFetcher(catalogManager, storageManagerFactory); if (cliOptions.count) { QueryResult<Long> result = variantFetcher.count(query, sessionId); System.out.println("Num. results\t" + result.getResult().get(0)); } else if (StringUtils.isNotEmpty(cliOptions.groupBy)) { ObjectMapper objectMapper = new ObjectMapper(); QueryResult groupBy = variantFetcher.groupBy(query, queryOptions, cliOptions.groupBy, sessionId); System.out//from w w w.j a v a 2 s . c o m .println("rank = " + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(groupBy)); } else if (StringUtils.isNotEmpty(cliOptions.rank)) { ObjectMapper objectMapper = new ObjectMapper(); QueryResult rank = variantFetcher.rank(query, queryOptions, cliOptions.rank, sessionId); System.out.println("rank = " + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rank)); } else { final String outputFormat; if (StringUtils.isNotEmpty(cliOptions.outputFormat)) { outputFormat = cliOptions.outputFormat.toLowerCase(); } else { outputFormat = "vcf"; } try (OutputStream outputStream = VariantQueryCommandUtils.getOutputStream(cliOptions); VariantDBIterator iterator = variantFetcher.iterator(query, queryOptions, sessionId)) { StudyConfiguration studyConfiguration; final DataWriter<Variant> exporter; switch (VariantQueryCommandUtils.VariantOutputFormat.safeValueOf(outputFormat)) { case VCF: // StudyConfigurationManager studyConfigurationManager = variantDBAdaptor.getStudyConfigurationManager(); // Map<Long, List<Sample>> samplesMetadata = variantFetcher.getSamplesMetadata(studyId, query, queryOptions, sessionId); // QueryResult<StudyConfiguration> studyConfigurationResult = studyConfigurationManager.getStudyConfiguration( // query.getAsStringList(RETURNED_STUDIES.key()).get(0), null); studyConfiguration = variantFetcher.getStudyConfiguration( query.getAsIntegerList(RETURNED_STUDIES.key()).get(0), null, sessionId); if (studyConfiguration != null) { // Samples to be returned if (query.containsKey(RETURNED_SAMPLES.key())) { queryOptions.put(RETURNED_SAMPLES.key(), query.get(RETURNED_SAMPLES.key())); } // options.add("includeAnnotations", queryVariantsCommandOptions.includeAnnotations); if (cliOptions.annotations != null) { queryOptions.add("annotations", cliOptions.annotations); } // VariantVcfExporter.htsExport(iterator, studyConfiguration, outputStream, queryOptions); long studyId = variantFetcher.getMainStudyId(query); VariantSourceDBAdaptor sourceDBAdaptor = variantFetcher.getSourceDBAdaptor((int) studyId, sessionId); exporter = new VariantVcfExporter(studyConfiguration, sourceDBAdaptor, outputStream, queryOptions); } else { throw new IllegalArgumentException( "No study found named " + query.getAsStringList(RETURNED_STUDIES.key()).get(0)); } break; case JSON: // we know that it is JSON, otherwise we have not reached this point exporter = batch -> { batch.forEach(variant -> { try { outputStream.write(variant.toJson().getBytes()); outputStream.write('\n'); } catch (IOException e) { throw new UncheckedIOException(e); } }); return true; }; break; case AVRO: String codecName = ""; if (VariantQueryCommandUtils.VariantOutputFormat.isGzip(outputFormat)) { codecName = "gzip"; } if (outputFormat.endsWith("snappy")) { codecName = "snappy"; } exporter = new VariantAvroWriter(VariantAvro.getClassSchema(), codecName, outputStream); break; case STATS: studyConfiguration = variantFetcher.getStudyConfiguration( query.getAsIntegerList(RETURNED_STUDIES.key()).get(0), null, sessionId); List<String> cohorts = new ArrayList<>(studyConfiguration.getCohortIds().keySet()); cohorts.sort(String::compareTo); exporter = new VariantStatsTsvExporter(outputStream, studyConfiguration.getStudyName(), cohorts); break; case CELLBASE: exporter = new VariantStatsPopulationFrequencyExporter(outputStream); break; default: throw new ParameterException("Unknown output format " + outputFormat); } ParallelTaskRunner.Task<Variant, Variant> progressTask; ExecutorService executor; if (VariantQueryCommandUtils.isStandardOutput(cliOptions)) { progressTask = batch -> batch; executor = null; } else { executor = Executors.newSingleThreadExecutor(); Future<Long> future = executor.submit(() -> { Long count = variantFetcher.count(query, sessionId).first(); count = Math.min(queryOptions.getLong(QueryOptions.LIMIT, Long.MAX_VALUE), count - queryOptions.getLong(QueryOptions.SKIP, 0)); return count; }); executor.shutdown(); ProgressLogger progressLogger = new ProgressLogger("Export variants", future, 200); progressTask = batch -> { progressLogger.increment(batch.size()); return batch; }; } ParallelTaskRunner.Config config = ParallelTaskRunner.Config.builder().setNumTasks(1) .setBatchSize(10).setAbortOnFail(true).build(); ParallelTaskRunner<Variant, Variant> ptr = new ParallelTaskRunner<>(batchSize -> { List<Variant> variants = new ArrayList<>(batchSize); while (iterator.hasNext() && variants.size() < batchSize) { variants.add(iterator.next()); } return variants; }, progressTask, exporter, config); ptr.run(); if (executor != null) { executor.shutdownNow(); } logger.info( "Time fetching data: " + iterator.getTimeFetching(TimeUnit.MILLISECONDS) / 1000.0 + "s"); logger.info("Time converting data: " + iterator.getTimeConverting(TimeUnit.MILLISECONDS) / 1000.0 + "s"); } } }
From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java
private boolean verify(Message message, MsgCheck check) { String sVal = ""; if (check.getField().equals(MESSAGECONTENTFIELD)) { try {/*from ww w. ja va2 s .co m*/ if (message instanceof TextMessage) { sVal = ((TextMessage) message).getText(); } else if (message instanceof MapMessage) { MapMessage mm = (MapMessage) message; ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.createObjectNode(); @SuppressWarnings("unchecked") Enumeration<String> e = mm.getMapNames(); while (e.hasMoreElements()) { String field = e.nextElement(); root.set(field, mapper.convertValue(mm.getObject(field), JsonNode.class)); } sVal = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root); } else if (message instanceof BytesMessage) { BytesMessage bm = (BytesMessage) message; bm.reset(); byte[] bytes = new byte[(int) bm.getBodyLength()]; if (bm.readBytes(bytes) == bm.getBodyLength()) { sVal = new String(bytes); } } } catch (JMSException e) { return false; } catch (JsonProcessingException e) { return false; } } else { Enumeration<String> propNames = null; try { propNames = message.getPropertyNames(); while (propNames.hasMoreElements()) { String propertyName = propNames.nextElement(); if (propertyName.equals(check.getField())) { if (message.getObjectProperty(propertyName) != null) { sVal = message.getObjectProperty(propertyName).toString(); break; } } } } catch (JMSException e) { return false; } } String eVal = ""; if (check.getExpectedValue() != null) { eVal = check.getExpectedValue(); } if (Pattern.compile(eVal).matcher(sVal).find()) { return true; } return false; }
From source file:org.opencb.opencga.storage.app.cli.client.VariantCommandExecutor.java
private void query() throws Exception { CliOptionsParser.QueryVariantsCommandOptions queryVariantsCommandOptions = variantCommandOptions.queryVariantsCommandOptions; storageConfiguration.getVariant().getOptions().putAll(queryVariantsCommandOptions.commonOptions.params); VariantDBAdaptor variantDBAdaptor = variantStorageManager.getDBAdaptor(queryVariantsCommandOptions.dbName); List<String> studyNames = variantDBAdaptor.getStudyConfigurationManager().getStudyNames(new QueryOptions()); Query query = VariantQueryCommandUtils.parseQuery(queryVariantsCommandOptions, studyNames); QueryOptions options = VariantQueryCommandUtils.parseQueryOptions(queryVariantsCommandOptions); OutputStream outputStream = VariantQueryCommandUtils.getOutputStream(queryVariantsCommandOptions); if (queryVariantsCommandOptions.count) { QueryResult<Long> result = variantDBAdaptor.count(query); System.out.println("Num. results\t" + result.getResult().get(0)); return;// www .j av a 2s . c o m } String outputFormat = "vcf"; if (StringUtils.isNotEmpty(queryVariantsCommandOptions.outputFormat)) { if (queryVariantsCommandOptions.outputFormat.equals("json") || queryVariantsCommandOptions.outputFormat.equals("json.gz")) { outputFormat = "json"; } } ObjectMapper objectMapper = new ObjectMapper(); if (StringUtils.isNotEmpty(queryVariantsCommandOptions.rank)) { executeRank(query, variantDBAdaptor, queryVariantsCommandOptions); } else { if (StringUtils.isNotEmpty(queryVariantsCommandOptions.groupBy)) { QueryResult groupBy = variantDBAdaptor.groupBy(query, queryVariantsCommandOptions.groupBy, options); System.out.println( "groupBy = " + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(groupBy)); } else { VariantDBIterator iterator = variantDBAdaptor.iterator(query, options); if (outputFormat.equalsIgnoreCase("vcf")) { StudyConfigurationManager studyConfigurationManager = variantDBAdaptor .getStudyConfigurationManager(); QueryResult<StudyConfiguration> studyConfigurationResult = studyConfigurationManager .getStudyConfiguration(query.getAsStringList(RETURNED_STUDIES.key()).get(0), null); if (studyConfigurationResult.getResult().size() >= 1) { // Samples to be returned if (query.containsKey(RETURNED_SAMPLES.key())) { options.put(RETURNED_SAMPLES.key(), query.get(RETURNED_SAMPLES.key())); } // options.add("includeAnnotations", queryVariantsCommandOptions.includeAnnotations); if (queryVariantsCommandOptions.annotations != null) { options.add("annotations", queryVariantsCommandOptions.annotations); } VariantVcfExporter.htsExport(iterator, studyConfigurationResult.first(), variantDBAdaptor.getVariantSourceDBAdaptor(), outputStream, options); } else { logger.warn("no study found named " + query.getAsStringList(RETURNED_STUDIES.key()).get(0)); } // printVcfResult(iterator, studyConfigurationManager, printWriter); } else { // we know that it is JSON, otherwise we have not reached this point printJsonResult(iterator, outputStream); } iterator.close(); } } outputStream.close(); }
From source file:com.phoenixnap.oss.ramlapisync.parser.SpringMvcResourceParser.java
@Override protected Pair<String, RamlMimeType> extractRequestBody(Method method, Map<String, String> parameterComments, String comment, List<ApiParameterMetadata> apiParameters) { RamlMimeType mimeType = RamlModelFactoryOfFactories.createRamlModelFactory().createRamlMimeType(); String type;//from w w w . j a v a 2 s. c o m //Handle empty body if (apiParameters != null && apiParameters.size() == 0) { // do nothing here return null; } else if (apiParameters != null && apiParameters.size() == 1 && String.class.equals(apiParameters.get(0).getType()) // Handle Plain Text parameters && apiParameters.get(0).isAnnotationPresent(RequestBody.class)) { ApiParameterMetadata apiParameterMetadata = apiParameters.get(0); type = "text/plain"; if (StringUtils.hasText(apiParameterMetadata.getExample())) { mimeType.setExample(apiParameterMetadata.getExample()); } ObjectMapper m = new ObjectMapper(); SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); try { m.acceptJsonFormatVisitor(m.constructType(String.class), visitor); JsonSchema jsonSchema = visitor.finalSchema(); String description = parameterComments.get(apiParameterMetadata.getJavaName()); if (description == null) { description = apiParameterMetadata.getName(); } jsonSchema.setDescription(description); jsonSchema.setRequired(!apiParameterMetadata.isNullable()); mimeType.setSchema(m.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema)); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return new Pair<>(type, mimeType); } else if (apiParameters != null && (apiParameters.size() > 1 || (!apiParameters.get(0).isAnnotationPresent(RequestBody.class) && String.class.equals(apiParameters.get(0).getType())))) { type = "application/x-www-form-urlencoded"; for (ApiParameterMetadata param : apiParameters) { RamlFormParameter formParameter = RamlModelFactoryOfFactories.createRamlModelFactory() .createRamlFormParameter(); formParameter.setDisplayName(param.getName()); formParameter.setExample(param.getExample()); RamlParamType simpleType = SchemaHelper.mapSimpleType(param.getType()); formParameter.setType(simpleType == null ? RamlParamType.STRING : simpleType); String description = parameterComments.get(param.getJavaName()); if (description == null) { description = param.getName(); } formParameter.setDescription(description); formParameter.setRequired(!param.isNullable()); Map<String, List<RamlFormParameter>> paramMap; if (mimeType.getFormParameters() == null) { paramMap = new TreeMap<>(); mimeType.setFormParameters(paramMap); } else { paramMap = mimeType.getFormParameters(); } mimeType.addFormParameters(param.getName(), Collections.singletonList(formParameter)); } return new Pair<>(type, mimeType); } else { return super.extractRequestBody(method, parameterComments, comment, apiParameters); } }
From source file:com.jkoolcloud.tnt4j.streams.custom.kafka.interceptors.reporters.metrics.MetricsReporter.java
protected void reportMetrics(Map<String, TopicMetrics> mRegistry) { String metricsCorrelator = tracker.newUUID(); try {// ww w . j a v a 2 s . com if (InterceptionsManager.getInstance().isProducerIntercepted()) { TrackingActivity metricsJMX = collectKafkaProducerMetricsJMX(tracker); metricsJMX.setCorrelator(metricsCorrelator); prepareAndSend(metricsJMX); } if (InterceptionsManager.getInstance().isConsumerIntercepted()) { TrackingActivity metricsJMX = collectKafkaConsumerMetricsJMX(tracker); metricsJMX.setCorrelator(metricsCorrelator); prepareAndSend(metricsJMX); } TrackingActivity metricsJMX = collectJVMMetricsJMX(tracker); metricsJMX.setCorrelator(metricsCorrelator); prepareAndSend(metricsJMX); } catch (UnsupportedOperationException exc) { LOGGER.log(OpLevel.WARNING, StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME), "MetricsReporter.clients.jmx.unsupported", Utils.getExceptionMessages(exc)); } catch (Exception exc) { Utils.logThrowable(LOGGER, OpLevel.WARNING, StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME), "MetricsReporter.clients.jmx.fail", exc); } try { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, false)); mapper.registerModule(new MetricsRegistryModule()); for (Map.Entry<String, TopicMetrics> metrics : mRegistry.entrySet()) { TopicMetrics topicMetrics = metrics.getValue(); topicMetrics.correlator = metricsCorrelator; String msg = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(topicMetrics); topicMetrics.reset(); tracker.log(OpLevel.INFO, msg); } } catch (JsonProcessingException exc) { Utils.logThrowable(LOGGER, OpLevel.ERROR, StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME), "MetricsReporter.report.metrics.fail", exc); } }
From source file:com.linecorp.armeria.server.grpc.GrpcDocServiceTest.java
@Test public void testOk() throws Exception { List<ServiceEntry> entries = ImmutableList.of( new ServiceEntry(TEST_SERVICE_DESCRIPTOR, ImmutableList.of(new EndpointInfo("*", "/test/armeria.grpc.testing.TestService/", "", GrpcSerializationFormats.PROTO.mediaType(), ImmutableSet.of(GrpcSerializationFormats.PROTO.mediaType(), GrpcSerializationFormats.JSON.mediaType(), GrpcSerializationFormats.PROTO_WEB.mediaType(), GrpcSerializationFormats.JSON_WEB.mediaType(), MediaType.PROTOBUF.withParameter("protocol", "gRPC"), MediaType.JSON_UTF_8.withParameter("protocol", "gRPC"))))), new ServiceEntry(RECONNECT_SERVICE_DESCRIPTOR, ImmutableList.of(new EndpointInfo("*", "/armeria.grpc.testing.ReconnectService/", "", GrpcSerializationFormats.PROTO, ImmutableSet.of(GrpcSerializationFormats.PROTO, GrpcSerializationFormats.PROTO_WEB))))); final ObjectMapper mapper = new ObjectMapper(); final JsonNode expectedJson = mapper.valueToTree(new GrpcDocServicePlugin().generate(entries)); // The specification generated by GrpcDocServicePlugin does not include the examples specified // when building a DocService, so we add them manually here. addExamples(expectedJson);// w w w.jav a 2 s . c o m try (CloseableHttpClient hc = HttpClients.createMinimal()) { final HttpGet req = new HttpGet(specificationUri()); try (CloseableHttpResponse res = hc.execute(req)) { assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK"); final JsonNode actualJson = mapper.readTree(EntityUtils.toString(res.getEntity())); // The specification generated by ThriftDocServicePlugin does not include the docstrings // because it's injected by the DocService, so we remove them here for easier comparison. removeDocStrings(actualJson); // Convert to the prettified strings for human-readable comparison. final ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter(); final String actualJsonString = writer.writeValueAsString(actualJson); final String expectedJsonString = writer.writeValueAsString(expectedJson); assertThat(actualJsonString).isEqualTo(expectedJsonString); } } }
From source file:org.opencb.opencga.storage.app.cli.client.VariantCommandExecutor.java
private void executeRank(Query query, VariantDBAdaptor variantDBAdaptor, CliOptionsParser.QueryVariantsCommandOptions queryVariantsCommandOptions) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); String field = queryVariantsCommandOptions.rank; boolean asc = false; if (queryVariantsCommandOptions.rank.contains(":")) { // eg. gene:-1 String[] arr = queryVariantsCommandOptions.rank.split(":"); field = arr[0];/*from w w w. j a v a2 s .com*/ if (arr[1].endsWith("-1")) { asc = true; } } int limit = 10; if (queryVariantsCommandOptions.limit > 0) { limit = queryVariantsCommandOptions.limit; } QueryResult rank = variantDBAdaptor.rank(query, field, limit, asc); System.out.println("rank = " + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rank)); }
From source file:org.wrml.runtime.format.text.html.WrmldocFormatter.java
@Override public void writeModel(final OutputStream out, final Model model, final ModelWriteOptions writeOptions) throws ModelWritingException, UnsupportedOperationException { final Context context = getContext(); final SchemaLoader schemaLoader = context.getSchemaLoader(); final URI schemaUri = model.getSchemaUri(); final String dotMin = (_IsSourceCodeMinified) ? ".min" : ""; final String titleSlotName = SchemaDesignFormatter.getTitleSlotName(schemaUri, schemaLoader); String documentTitle = "Untitled"; String documentIcon = _Docroot + "img/model.png"; if (StringUtils.isNotBlank(titleSlotName)) { documentTitle = String.valueOf(model.getSlotValue(titleSlotName)); }//from ww w .ja v a 2 s.c o m // TODO: Replace this ObjectMapper-based implementation with the construction of a WRML model that represents // the wrmldoc "shell" data structure final ObjectMapper objectMapper = new ObjectMapper(); try { final String modelValue; final String schemaValue; String linkRelationValue = EMPTY_OBJECT; if (model instanceof Schema) { modelValue = EMPTY_OBJECT; final Schema schema = (Schema) model; final ObjectNode schemaNode = SchemaDesignFormatter.createSchemaDesignObjectNode(objectMapper, schema); schemaValue = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(schemaNode); documentIcon = _Docroot + "img/schema.png"; } else if (model instanceof Api) { modelValue = EMPTY_OBJECT; schemaValue = EMPTY_OBJECT; documentIcon = _Docroot + "img/api.png"; } else if (model instanceof LinkRelation) { modelValue = model.toString(); final ObjectNode linkRelationNode = buildLinkRelationNode(objectMapper, (LinkRelation) model); linkRelationValue = objectMapper.writerWithDefaultPrettyPrinter() .writeValueAsString(linkRelationNode); schemaValue = EMPTY_OBJECT; documentIcon = _Docroot + "img/linkRelation.png"; } else if (model instanceof ErrorReport) { modelValue = model.toString(); schemaValue = EMPTY_OBJECT; if (model instanceof ApiNotFoundErrorReport) { documentIcon = _Docroot + "img/apiNotFound.png"; } else if (model instanceof ResourceNotFoundErrorReport) { documentIcon = _Docroot + "img/resourceNotFound.png"; } else if (model instanceof DocumentNotFoundErrorReport) { documentIcon = _Docroot + "img/documentNotFound.png"; } } else { modelValue = model.toString(); final Keys schemaKeys = context.getApiLoader().buildDocumentKeys(schemaUri, schemaLoader.getSchemaSchemaUri()); final Schema schema = context.getModel(schemaKeys, schemaLoader.getSchemaDimensions()); final ObjectNode schemaNode = SchemaDesignFormatter.createSchemaDesignObjectNode(objectMapper, schema); schemaValue = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(schemaNode); } final ObjectNode apiNode = buildApiNode(objectMapper, model); final String apiValue = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(apiNode); final MessageFormat pageTemplate = getTemplate(SHELL_PAGE_TEMPLATE_RESOURCE); final String renderedPage = renderPage(pageTemplate, _Docroot, dotMin, documentTitle, documentIcon, schemaUri.toString(), modelValue, schemaValue, apiValue, linkRelationValue); IOUtils.write(renderedPage, out); } catch (IOException e) { throw new ModelWritingException(e.getMessage(), e, this); } }
From source file:eu.seaclouds.platform.planner.core.Planner.java
private String generateMMOutput(Map<String, HashSet<String>> mmResult, Map<String, Pair<NodeTemplate, String>> offerings) throws Exception { ObjectMapper mapper = new ObjectMapper(); ArrayList<Map<String, ArrayList<Map<String, Object>>>> singleRes = new ArrayList<>(); Yaml yml = new Yaml(); for (String moduleName : mmResult.keySet()) { ArrayList<Map<String, Object>> suitableList = new ArrayList<>(); //create suitable lists for (String id : mmResult.get(moduleName)) { String off = offerings.get(id).second; Map<String, Object> innerMap = new HashMap<>(); Map<String, Map<String, Object>> tosca = (Map<String, Map<String, Object>>) yml.load(off); Object o = tosca.get("topology_template").get("node_templates"); String od = yml.dump(o); innerMap.put(id, od);//from w ww . j a va2 s. c o m suitableList.add(innerMap); } HashMap<String, ArrayList<Map<String, Object>>> finalRes = new HashMap<>(); finalRes.put(moduleName, suitableList); singleRes.add(finalRes); } return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(singleRes); }
From source file:org.opencb.opencga.storage.app.cli.client.executors.VariantCommandExecutor.java
private void executeRank(Query query, VariantDBAdaptor variantDBAdaptor, StorageVariantCommandOptions.VariantQueryCommandOptions variantQueryCommandOptions) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); String field = variantQueryCommandOptions.rank; boolean asc = false; if (variantQueryCommandOptions.rank.contains(":")) { // eg. gene:-1 String[] arr = variantQueryCommandOptions.rank.split(":"); field = arr[0];//from w w w. ja v a2 s .c o m if (arr[1].endsWith("-1")) { asc = true; } } int limit = 10; if (variantQueryCommandOptions.commonQueryOptions.limit > 0) { limit = variantQueryCommandOptions.commonQueryOptions.limit; } QueryResult rank = variantDBAdaptor.rank(query, field, limit, asc); System.out.println("rank = " + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rank)); }