com.fasterxml.jackson.core.JsonFactory Java Examples

The following examples show how to use com.fasterxml.jackson.core.JsonFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JCalRawWriter.java    From biweekly with BSD 2-Clause "Simplified" License 7 votes vote down vote up
private void init() throws IOException {
	JsonFactory factory = new JsonFactory();
	factory.configure(Feature.AUTO_CLOSE_TARGET, false);
	generator = factory.createGenerator(writer);

	if (prettyPrint) {
		if (prettyPrinter == null) {
			prettyPrinter = new JCalPrettyPrinter();
		}
		generator.setPrettyPrinter(prettyPrinter);
	}

	if (wrapInArray) {
		generator.writeStartArray();
	}
}
 
Example #2
Source File: StreamingModel.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
private void processDownload(Long topicId) throws UserException, ServerException, PublicInterfaceNotFoundException, IfcModelInterfaceException, IOException {
	InputStream inputStream = bimServerClient.getDownloadData(topicId);
	if (inputStream == null) {
		throw new IfcModelInterfaceException("No InputStream to read from for topicId " + topicId);
	}
	InputStream downloadData = new org.bimserver.utils.CountingInputStream(inputStream) {
	};
	try {
		JsonFactory jsonFactory = new JsonFactory();
		JsonParser jp = jsonFactory.createParser(downloadData);
		// TODO implement
	} catch (Exception e) {
		throw new IfcModelInterfaceException(e);
	} finally {
		if (downloadData != null) {
			downloadData.close();
		}
	}
}
 
Example #3
Source File: ContractDeserializerTest.java    From bonita-ui-designer with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void deserialize_a_serialized_contract_json_document_into_a_contract_object() throws Exception {
    Contract aSimpleContract = aSimpleContract();
    byte[] serializedContract = new ObjectMapper().writeValueAsBytes(aSimpleContract);
    ContractDeserializer contractDeserializer = new ContractDeserializer();

    Contract contract = contractDeserializer.deserialize(new JsonFactory(new ObjectMapper()).createParser(serializedContract), null);

    assertThat(contract.getInput()).extracting("name", "type").containsExactly(
            tuple("name", String.class.getName()),
            tuple("isValid", Boolean.class.getName()),
            tuple("ticket", NodeContractInput.class.getName()));
    assertThat(find(contract.getInput(), instanceOf(NodeContractInput.class)).getInput()).extracting("name", "type").containsExactly(
            tuple("title", String.class.getName()),
            tuple("creationDate", Date.class.getName()),
            tuple("creationLocalDate", LocalDate.class.getName()),
            tuple("creationLocalDateTime", LocalDateTime.class.getName()),
            tuple("creationOffsetDateTime", OffsetDateTime.class.getName()),
            tuple("updateTime", Long.class.getName()));
}
 
Example #4
Source File: ObjectMapperIT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructor() throws Exception {
    ObjectMapper mapper1 = new ObjectMapper();
    ObjectMapper mapper2 = new ObjectMapper(new JsonFactory());

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    Constructor<?> omConstructor = ObjectMapper.class.getConstructor(JsonFactory.class, DefaultSerializerProvider.class, DefaultDeserializationContext.class);
    Constructor<?> omConstructor1 = ObjectMapper.class.getConstructor();
    Constructor<?> omConstructor2 = ObjectMapper.class.getConstructor(JsonFactory.class);
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor));
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor1));
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor));
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor2));

    verifier.verifyTraceCount(0);
}
 
Example #5
Source File: JsonParserUtilsTest.java    From proctor with Apache License 2.0 6 votes vote down vote up
private static void verifyTestObjectMap(final String testObjectMapAsJsonString) throws IOException {
    final Map<String, TestObject> expected = OBJECT_MAPPER.readValue(
            testObjectMapAsJsonString,
            new TypeReference<Map<String, TestObject>>() {
            }
    );

    final JsonFactory jsonFactory = new JsonFactory();
    final JsonParser jsonParser = jsonFactory.createParser(testObjectMapAsJsonString);

    jsonParser.nextToken();

    final Map<String, TestObject> actual = new HashMap<>();
    JsonParserUtils.consumeJson(
            jsonParser,
            (key, parser) -> {
                final TestObject testObject = OBJECT_MAPPER.readValue(parser, TestObject.class);

                actual.put(key, testObject);
            }
    );

    assertThat(actual).isEqualTo(expected);
}
 
Example #6
Source File: DeserializeTest.java    From ig-json-parser with MIT License 6 votes vote down vote up
@Test
public void valueExtractTest() throws IOException, JSONException {
  final int encodedValue = 25;
  final int deserializedValue = 40;

  StringWriter stringWriter = new StringWriter();
  JSONWriter writer = new JSONWriter(stringWriter);

  writer.object().key(FormatterUUT.VALUE_FORMATTER_FIELD_NAME).value(encodedValue).endObject();

  String inputString = stringWriter.toString();
  JsonParser jp = new JsonFactory().createParser(inputString);
  jp.nextToken();
  FormatterUUT uut = FormatterUUT__JsonHelper.parseFromJson(jp);

  assertSame(deserializedValue, uut.getValueFormatter());
}
 
Example #7
Source File: ResultsLog.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Override
public void open() throws IOException {
    synchronized ( isOpen ) {
        if ( isOpen.compareAndSet( false, true ) ) {
            resultCount.set( 0 );

            // write the json header for recording the chop results
            JsonFactory factory = new JsonFactory();
            jgen = factory.createGenerator(  new File( resultsFile.get() ), JsonEncoding.UTF8 );

            if ( prettyPrint.get() ) {
                jgen.useDefaultPrettyPrinter();
            }

            jgen.setCodec( new ObjectMapper() );

            setupJsonStream();

            thread = new Thread( this, "ResultLog Writer" );
            thread.start();
        }
    }
}
 
Example #8
Source File: HistoDbClientImpl.java    From ipst with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public List<HistoDbAttributeId> listAttributes() throws IOException {
    List<HistoDbAttributeId> attrs = new ArrayList<>();
    try (InputStream is = httpClient.getHttpRequest(new HistoDbUrl(config, "metadata.json", ImmutableMap.of("colRange", "*")))) {
        JsonFactory jfactory = new JsonFactory();
        try (JsonParser jParser = jfactory.createParser(is)) {
            while (jParser.nextToken() != null) {
                String fieldname = jParser.getCurrentName();
                if ("name".equals(fieldname)) {
                    jParser.nextToken();
                    attrs.add(HistoDbAttributeIdParser.parse(jParser.getText()));
                }
            }
        }
    }
    return attrs;
}
 
Example #9
Source File: BlockTest.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
/**
 * Temporary 'HACK' - this assertion will fail if the overhead associated with serializing blocks exceeds
 * the hard coded expectation. This is only meaningful for inline blocks which will exceed Lambda's response size.
 * If this assertion fails we need to revisit the default settings in our serialization layer. The serialization
 * layer is currently being refactored and eventually this assertion will not be needed.
 *
 * @param serializedBlock The bytes of the block to serialize.
 * @note https://github.com/awslabs/aws-athena-query-federation/issues/121
 */
private void assertSerializationOverhead(ByteArrayOutputStream serializedBlock)
{
    try {
        ByteArrayOutputStream jout = new ByteArrayOutputStream();
        JsonFactory factory = new JsonFactory();
        JsonGenerator jsonGenerator = factory.createJsonGenerator(jout);
        jsonGenerator.writeBinaryField("field", serializedBlock.toByteArray());
        jsonGenerator.close();
        double overhead = 1 - (((double) serializedBlock.size()) / ((double) jout.size()));
        logger.info("assertSerializationOverhead: {} vs {} = {}", serializedBlock.size(), jout.size(), overhead);
        assertTrue(0.35D > overhead);
    }
    catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #10
Source File: AuditActionGraphCommand.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Dump basic information about the action graph to the given stream in a simple JSON format.
 *
 * <p>The passed in stream is not closed after this operation.
 */
private static void dumpAsJson(
    ActionGraph graph,
    ActionGraphBuilder actionGraphBuilder,
    boolean includeRuntimeDeps,
    NodeView nodeView,
    OutputStream out)
    throws IOException {
  try (JsonGenerator json =
      new JsonFactory()
          .createGenerator(out)
          .configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false)) {
    json.writeStartArray();
    for (BuildRule node : graph.getNodes()) {
      writeJsonObjectForBuildRule(json, node, actionGraphBuilder, includeRuntimeDeps, nodeView);
    }
    json.writeEndArray();
  }
}
 
Example #11
Source File: CharsToNameCanonicalizer.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Internal constructor used when creating child instances.
 */
private CharsToNameCanonicalizer(CharsToNameCanonicalizer parent, int flags,
        String[] symbols, Bucket[] buckets, int size, int hashSeed, int longestColl) {
    _parent = parent;

    _flags = flags;
    _canonicalize = JsonFactory.Feature.CANONICALIZE_FIELD_NAMES.enabledIn(flags);

    _symbols = symbols;
    _buckets = buckets;
    _size = size;
    _hashSeed = hashSeed;
    // Hard-coded fill factor, 75%
    int arrayLen = (symbols.length);
    _sizeThreshold = _thresholdSize(arrayLen);
    _indexMask =  (arrayLen - 1);
    _longestCollisionList = longestColl;

    // Need to make copies of arrays, if/when adding new entries
    _dirty = false;
}
 
Example #12
Source File: UVaultSet.java    From ure with MIT License 6 votes vote down vote up
public void persist(String absoluteFilepath) {
    File file = new File(absoluteFilepath);
    try (
            FileOutputStream stream = new FileOutputStream(file);
            //GZIPOutputStream gzip = new GZIPOutputStream(stream)
    ) {
        JsonFactory jfactory = new JsonFactory();
        JsonGenerator jGenerator = jfactory
                .createGenerator(stream, JsonEncoding.UTF8);
        jGenerator.setCodec(new ObjectMapper());
        jGenerator.writeObject(this);
        jGenerator.close();
    } catch (IOException e) {
        throw new RuntimeException("Couldn't persist object " + toString(), e);
    }
}
 
Example #13
Source File: MetricStore.java    From incubator-nemo with Apache License 2.0 6 votes vote down vote up
/**
 * Dumps JSON-serialized string of all stored metric.
 *
 * @return dumped JSON string of all metric.
 * @throws IOException when failed to write file.
 */
public synchronized String dumpAllMetricToJson() throws IOException {
  final ObjectMapper objectMapper = new ObjectMapper();
  final JsonFactory jsonFactory = new JsonFactory();
  final ByteArrayOutputStream stream = new ByteArrayOutputStream();

  try (JsonGenerator jsonGenerator = jsonFactory.createGenerator(stream, JsonEncoding.UTF8)) {
    jsonGenerator.setCodec(objectMapper);

    jsonGenerator.writeStartObject();
    for (final Map.Entry<Class<? extends Metric>, Map<String, Object>> metricMapEntry : metricMap.entrySet()) {
      jsonGenerator.writeFieldName(metricMapEntry.getKey().getSimpleName());
      jsonGenerator.writeStartObject();
      for (final Map.Entry<String, Object> idToMetricEntry : metricMapEntry.getValue().entrySet()) {
        generatePreprocessedJsonFromMetricEntry(idToMetricEntry, jsonGenerator, objectMapper);
      }
      jsonGenerator.writeEndObject();
    }
    jsonGenerator.writeEndObject();
  }

  return stream.toString();
}
 
Example #14
Source File: MessageList.java    From event-streams-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Build message list dependent on the format Event Streams requires. The
 * message list is in the form: [{ "value": base_64_string }, ...]
 *
 * @return {String} String representation of a JSON object.
 * @throws IOException
 */
public String build() throws IOException {
    final JsonFactory jsonFactory = new JsonFactory();
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final JsonGenerator jsonGenerator = jsonFactory.createGenerator(outputStream);

    jsonGenerator.writeStartArray();
    for (int i = 0; i < this.messages.size(); i++) {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeFieldName("value");
        jsonGenerator.writeObject(this.messages.get(i));
        jsonGenerator.writeEndObject();
    }
    jsonGenerator.writeEndArray();

    jsonGenerator.close();
    outputStream.close();

    return new String(outputStream.toByteArray());
}
 
Example #15
Source File: ProfileWrapper.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
public String getFragmentsJSON() throws IOException {
  final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  final JsonGenerator jsonGenerator = new JsonFactory().createGenerator(outputStream);

  jsonGenerator.writeStartObject();

  for (FragmentWrapper fragmentWrapper : getFragmentProfiles()) {
    fragmentWrapper.addFragment(jsonGenerator);
  }

  jsonGenerator.writeEndObject();

  jsonGenerator.flush();
  return outputStream.toString();
}
 
Example #16
Source File: Configuration.java    From Canova with Apache License 2.0 6 votes vote down vote up
/**
 *  Writes out all the parameters and their properties (final and resource) to
 *  the given {@link Writer}
 *  The format of the output would be
 *  { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
 *  key2.isFinal,key2.resource}... ] }
 *  It does not output the parameters of the configuration object which is
 *  loaded from an input stream.
 * @param out the Writer to write to
 * @throws IOException
 */
public static void dumpConfiguration(Configuration conf,
                                     Writer out) throws IOException {
    Configuration config = new Configuration(conf,true);
    config.reloadConfiguration();
    JsonFactory dumpFactory = new JsonFactory();
    JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
    dumpGenerator.writeStartObject();
    dumpGenerator.writeFieldName("properties");
    dumpGenerator.writeStartArray();
    dumpGenerator.flush();
    for (Map.Entry<Object,Object> item: config.getProps().entrySet()) {
        dumpGenerator.writeStartObject();
        dumpGenerator.writeStringField("key", (String) item.getKey());
        dumpGenerator.writeStringField("value",
                config.get((String) item.getKey()));
        dumpGenerator.writeBooleanField("isFinal",
                config.finalParameters.contains(item.getKey()));
        dumpGenerator.writeStringField("resource",
                config.updatingResource.get(item.getKey()));
        dumpGenerator.writeEndObject();
    }
    dumpGenerator.writeEndArray();
    dumpGenerator.writeEndObject();
    dumpGenerator.flush();
}
 
Example #17
Source File: DeserializeTest.java    From ig-json-parser with MIT License 6 votes vote down vote up
@Test
public void fieldAssignmentTest() throws IOException, JSONException {
  final int encodedValue = 25;
  final int deserializedValue = -encodedValue;

  StringWriter stringWriter = new StringWriter();
  JSONWriter writer = new JSONWriter(stringWriter);

  writer.object().key(FormatterUUT.FIELD_ASSIGNMENT_FIELD_NAME).value(encodedValue).endObject();

  String inputString = stringWriter.toString();
  JsonParser jp = new JsonFactory().createParser(inputString);
  jp.nextToken();
  FormatterUUT uut = FormatterUUT__JsonHelper.parseFromJson(jp);

  assertSame(deserializedValue, uut.getFieldAssignmentFormatter());
}
 
Example #18
Source File: TestJsonParser.java    From geometry-api-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeometryToJSONOldID() throws Exception {// CR
	Polygon geom = new Polygon();
	geom.startPath(new Point(-113, 34));
	geom.lineTo(new Point(-105, 34));
	geom.lineTo(new Point(-108, 40));
	String outputPolygon = GeometryEngine.geometryToJson(SpatialReference.create(3857), geom);// Test
																								// WKID
																								// ==
																								// -1
	String correctPolygon = "{\"rings\":[[[-113,34],[-105,34],[-108,40],[-113,34]]],\"spatialReference\":{\"wkid\":102100,\"latestWkid\":3857}}";
	assertTrue(outputPolygon.equals(correctPolygon));
	JsonFactory jf = new JsonFactory();
	JsonParser jp = jf.createJsonParser(outputPolygon);
	jp.nextToken();
	MapGeometry mg = GeometryEngine.jsonToGeometry(jp);
	@SuppressWarnings("unused")
	int srId = mg.getSpatialReference().getID();
	@SuppressWarnings("unused")
	int srOldId = mg.getSpatialReference().getOldID();
	Assert.assertTrue(mg.getSpatialReference().getID() == 3857);
	Assert.assertTrue(mg.getSpatialReference().getLatestID() == 3857);
	Assert.assertTrue(mg.getSpatialReference().getOldID() == 102100);
}
 
Example #19
Source File: PreviewConfiguration.java    From data-prep with Apache License 2.0 6 votes vote down vote up
private List<Long> parseIndexes(final String indexes) {
    if (indexes == null) {
        return null;
    }
    if (indexes.isEmpty()) {
        throw new TDPException(CommonErrorCodes.UNABLE_TO_PARSE_ACTIONS,
                new IllegalArgumentException("Source should not be empty"));
    }
    try {
        final ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        final JsonNode json = mapper.readTree(indexes);

        final List<Long> result = new ArrayList<>(json.size());
        for (JsonNode index : json) {
            result.add(index.longValue());
        }
        return result;
    } catch (IOException e) {
        throw new TDPException(CommonErrorCodes.UNABLE_TO_PARSE_ACTIONS, e);
    }
}
 
Example #20
Source File: ClientRPCStoreTest.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Test 
public void testDefaultRequestToJSON() throws JsonParseException, IOException, NoSuchMethodException, SecurityException
{
	mockClientConfigHandler.addListener((ClientConfigUpdateListener) EasyMock.anyObject());
	EasyMock.expectLastCall().once();
	replay(mockClientConfigHandler);
	final String client = "test";
	ClientRpcStore store = new ClientRpcStore(mockClientConfigHandler);
	DefaultCustomPredictRequest customRequest =  DefaultCustomPredictRequest.newBuilder().addValues(1.0f).build();

	Any anyMsg = Any.pack(customRequest);
	ClassificationRequestMeta meta = ClassificationRequestMeta.newBuilder().setPuid("1234").build();
	ClassificationRequest request = ClassificationRequest.newBuilder().setMeta(meta).setData(anyMsg).build();
	System.out.println(request);
	JsonNode json = store.getJSONForRequest(client, request);
	Assert.assertNotNull(json);
	System.out.println(json);
	ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser parser = factory.createParser(json.toString());
    JsonNode actualObj = mapper.readTree(parser);
    ClassificationRequest req = store.getPredictRequestFromJson(client, actualObj);
    Assert.assertNotNull(req);
    System.out.println(req);
}
 
Example #21
Source File: CatalogManagerImpl.java    From logging-log4j-audit with Apache License 2.0 6 votes vote down vote up
private Map<String, Map<String, CatalogInfo>> initializeData(CatalogReader catalogReader) throws Exception {
    JsonFactory factory = new JsonFactory();
    factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
    ObjectMapper mapper = new ObjectMapper(factory);

    String catalog = catalogReader.readCatalog();
    catalogData = mapper.readValue(catalog, CatalogData.class);

    if (catalogData.getAttributes() != null) {
        for (Attribute attr : catalogData.getAttributes()) {
            if (attr.isRequestContext()) {
                requestContextAttributes.put(attr.getName(), attr);
            }
            Map<String, Attribute> attrMap = attributeMap.computeIfAbsent(attr.getCatalogId(), k -> new HashMap<>());
            attrMap.put(attr.getName(), attr);
        }
    }

    Map<String, Map<String, CatalogInfo>> map = new HashMap<>();
    map.put(DEFAULT_CATALOG, new HashMap<>());
    for (Event event : catalogData.getEvents()) {
        addEntry(map, event);
    }
    return map;
}
 
Example #22
Source File: DumpReportTask.java    From extract with MIT License 6 votes vote down vote up
/**
 * Dump the report as JSON to the given output stream.
 *
 * @param reportMap the report to dump
 * @param output the stream to dump to
 * @param match only dump matching results
 */
private void dump(final ReportMap reportMap, final OutputStream output, final ExtractionStatus match) throws
		IOException {
	final ObjectMapper mapper = new ObjectMapper();
	final SimpleModule module = new SimpleModule();

	module.addSerializer(ReportMap.class, new ReportSerializer(monitor, match));
	mapper.registerModule(module);

	try (final JsonGenerator jsonGenerator = new JsonFactory().setCodec(mapper).createGenerator(output,
			JsonEncoding.UTF8)) {
		jsonGenerator.useDefaultPrettyPrinter();
		jsonGenerator.writeObject(reportMap);
		jsonGenerator.writeRaw('\n');
	}
}
 
Example #23
Source File: LoadReportTask.java    From extract with MIT License 5 votes vote down vote up
/**
 * Load dump JSON from the given stream into a report.
 *
 * @param reportMap the report to load into
 * @param input the input stream to load from
 */
private void load(final DocumentFactory factory, final ReportMap reportMap, final InputStream input) throws IOException {
	final ObjectMapper mapper = new ObjectMapper();
	final SimpleModule module = new SimpleModule();

	module.addDeserializer(ReportMap.class, new ReportDeserializer(factory, reportMap));
	mapper.registerModule(module);

	try (final JsonParser jsonParser = new JsonFactory().setCodec(mapper).createParser(input)) {
		jsonParser.readValueAs(ReportMap.class);
	}
}
 
Example #24
Source File: GlyphedModal.java    From ure with MIT License 5 votes vote down vote up
void writeJson(ArrayList<Icon> icons, String filename) {
    log.info("writing " + filename);
    File file = new File(commander.config.getResourcePath() + "icons/" + filename);
    try (FileOutputStream stream = new FileOutputStream(file);) {
        JsonFactory jfactory = new JsonFactory();
        JsonGenerator jGenerator = jfactory.createGenerator(stream, JsonEncoding.UTF8);
        jGenerator.setCodec(objectMapper);
        jGenerator.writeObject(icons);
        jGenerator.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #25
Source File: ImportUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void importUsersFromStream(KeycloakSession session, String realmName, ObjectMapper mapper, InputStream is) throws IOException {
    RealmProvider model = session.realms();
    JsonFactory factory = mapper.getJsonFactory();
    JsonParser parser = factory.createJsonParser(is);
    try {
        parser.nextToken();

        while (parser.nextToken() == JsonToken.FIELD_NAME) {
            if ("realm".equals(parser.getText())) {
                parser.nextToken();
                String currRealmName = parser.getText();
                if (!currRealmName.equals(realmName)) {
                    throw new IllegalStateException("Trying to import users into invalid realm. Realm name: " + realmName + ", Expected realm name: " + currRealmName);
                }
            } else if ("users".equals(parser.getText())) {
                parser.nextToken();

                if (parser.getCurrentToken() == JsonToken.START_ARRAY) {
                    parser.nextToken();
                }

                // TODO: support for more transactions per single users file (if needed)
                List<UserRepresentation> userReps = new ArrayList<UserRepresentation>();
                while (parser.getCurrentToken() == JsonToken.START_OBJECT) {
                    UserRepresentation user = parser.readValueAs(UserRepresentation.class);
                    userReps.add(user);
                    parser.nextToken();
                }

                importUsers(session, model, realmName, userReps);

                if (parser.getCurrentToken() == JsonToken.END_ARRAY) {
                    parser.nextToken();
                }
            }
        }
    } finally {
        parser.close();
    }
}
 
Example #26
Source File: JsonUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createMapper( JsonFactory factory )
{
    ObjectMapper mapper = new ObjectMapper( factory );

    mapper.setVisibility( PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY );

    return mapper;
}
 
Example #27
Source File: CborAvailabilityChecker.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean calculateCborAvailable() {
    try {
        // used to determine availability of jackson-core at runtime
        new JsonFactory();
        // used to determine availability of jackson-databind-cbor at runtime
        new CBORFactory();
    } catch (final NoClassDefFoundError e) {
        return false;
    }
    return true;
}
 
Example #28
Source File: DefaultServiceRegistryService.java    From knox with Apache License 2.0 5 votes vote down vote up
private Map<String, Map<String,RegEntry>> getMapFromJsonString(String json) {
  Registry map = null;
  JsonFactory factory = new JsonFactory();
  ObjectMapper mapper = new ObjectMapper(factory);
  TypeReference<Registry> typeRef
        = new TypeReference<Registry>() {};
  try {
    map = mapper.readValue(json, typeRef);
  } catch (IOException e) {
    LOG.failedToGetMapFromJsonString( json, e );
  }
  return map;
}
 
Example #29
Source File: ConfigJsServlet.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String ct = "application/javascript; charset=" + StandardCharsets.UTF_8;
    response.setContentType(ct);
    JsonFactory f = new JsonFactory();
    try (JsonGenerator g = f.createGenerator(response.getOutputStream(), JsonEncoding.UTF8)) {
        response.getOutputStream().write("var ApicurioRegistryConfig = ".getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        g.setCodec(mapper);
        g.useDefaultPrettyPrinter();

        ConfigJs config = new ConfigJs();
        config.mode = "prod";

        config.artifacts.url = this.generateApiUrl(request);
        
        config.ui.url = this.generateUiUrl(request);
        config.ui.contextPath = "/ui";
        
        config.features.readOnly = this.isFeatureReadOnly();
        
        g.writeObject(config);

        g.flush();
        response.getOutputStream().write(";".getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
 
Example #30
Source File: DruidQuery.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Nullable
private String planAsGroupBy(List<DimensionSpec> groupByKeyDims, DruidJsonFilter jsonFilter,
    List<VirtualColumn> virtualColumnList, List<JsonAggregation> aggregations,
    List<JsonExpressionPostAgg> postAggregations, JsonLimit limit, DruidJsonFilter havingFilter) {
  final StringWriter sw = new StringWriter();
  final JsonFactory factory = new JsonFactory();
  try {
    final JsonGenerator generator = factory.createGenerator(sw);

    generator.writeStartObject();
    generator.writeStringField("queryType", "groupBy");
    generator.writeStringField("dataSource", druidTable.dataSource);
    writeField(generator, "granularity", Granularities.all());
    writeField(generator, "dimensions", groupByKeyDims);
    writeFieldIf(generator, "virtualColumns",
        virtualColumnList.size() > 0 ? virtualColumnList : null);
    writeFieldIf(generator, "limitSpec", limit);
    writeFieldIf(generator, "filter", jsonFilter);
    writeField(generator, "aggregations", aggregations);
    writeFieldIf(generator, "postAggregations",
        postAggregations.size() > 0 ? postAggregations : null);
    writeField(generator, "intervals", intervals);
    writeFieldIf(generator, "having",
        havingFilter == null ? null : new DruidJsonFilter.JsonDimHavingFilter(havingFilter));
    generator.writeEndObject();
    generator.close();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  return sw.toString();
}