public boolean checkCaptcha(String captcha) { if (isBlank(captcha)) { throw new ErrorCheckCaptcha("error.captcha.required", "Captcha is blank"); } String url = getReCaptcha().getUrl() + "?secret=" + getReCaptcha().getSecretKey() + "&response=" + captcha; log.debug("Check captcha by url {}", url); final ObjectReader reader = new ObjectMapper().readerFor(Map.class); try { final MappingIterator<Map<String, Object>> result = reader.readValues(new URL(url)); Map<String, Object> resultMap = result.nextValue(); log.info("Captacha result map {}", resultMap); Boolean success = (Boolean) resultMap.get("success"); return success; } catch (IOException e) { throw new ErrorCheckCaptcha(e); } }
public Map<String, Object> decode(String base64EncodedKey, String content) { try { byte[] decodedKey = Base64.getDecoder().decode(base64EncodedKey); SecretKey key = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES"); JWEObject jwe = JWEObject.parse(content); jwe.decrypt(new AESDecrypter(key)); ObjectMapper objectMapper = new ObjectMapper(); ObjectReader reader = objectMapper.readerFor(Map.class); return reader.with(DeserializationFeature.USE_LONG_FOR_INTS) .readValue(jwe.getPayload().toString()); } catch (Exception e) { throw new RuntimeException(e); } }
@Override public List<KeyValueConfigEntity> findAll(@Nonnull KeyValueConfigName configName) throws Exception { Objects.requireNonNull(configName); String collectionName = configName.getQualifiedName(); MongoCollection<RawBsonDocument> collection = connector.getDatabase().getCollection(collectionName, RawBsonDocument.class); MongoCursor<RawBsonDocument> it = collection.find().iterator(); if (!it.hasNext()) { return Collections.emptyList(); } RawBsonDocument document = it.next(); ByteArrayInputStream bin = new ByteArrayInputStream(document.getByteBuffer().array()); ObjectMapper objectMapper = MongoConfigObjectMapper.getInstance(); ObjectReader objectReader = objectMapper.readerFor(MongoConfigEntity.class); List<KeyValueConfigEntity> result = ((MongoConfigEntity) objectReader.readValue(bin)).getConfig(); // set groupName on returned config key-value pairs return result.stream().map(input -> input.setConfigName(configName)).collect(Collectors.toList()); }
protected void setMeta(Resource dataBody, Object instance, ResourceInformation resourceInformation) { ResourceField metaField = resourceInformation.getMetaField(); if (dataBody.getMeta() != null && metaField != null) { JsonNode metaNode = dataBody.getMeta(); Class<?> metaClass = metaField.getType(); ObjectReader metaMapper = objectMapper.readerFor(metaClass); try { Object meta = metaMapper.readValue(metaNode); metaField.getAccessor().setValue(instance, meta); } catch (IOException e) { throw new ResponseBodyException("failed to parse links information", e); } } }
@Override public void close() throws IOException { try { final EncryptedDataContainer encrypted = cipher.doFinal(); super.write(encrypted.getContent()); final String tag = CryptoUtils.byteArrayToString(encrypted.getTag()); final ObjectReader reader = session.getClient().getJSON().getContext(null).readerFor(FileKey.class); final FileKey fileKey = reader.readValue(status.getFilekey().array()); fileKey.setTag(tag); final ObjectWriter writer = session.getClient().getJSON().getContext(null).writerFor(FileKey.class); final ByteArrayOutputStream out = new ByteArrayOutputStream(); writer.writeValue(out, fileKey); status.setFilekey(ByteBuffer.wrap(out.toByteArray())); } catch(CryptoSystemException e) { throw new IOException(e); } finally { super.close(); } }
public ParallelRecordReader(CommittableFileLog cfl, int numLinesPerBatch, ObjectReader vReader, ObjectReader eReader) { super(cfl, vReader, eReader); this.numLinesPerBatch = numLinesPerBatch; this.numProcessors = Runtime.getRuntime().availableProcessors() - 1; // one to insert, read is not 100% busy if (numProcessors < 1) { this.numProcessors = 1; } else if (numProcessors > 4) { this.numProcessors = 4; // Don't need more than 4 threads } this.numBatchInQueue = QUEUE_TO_PROCESSOR_RATIO * numProcessors; this.producerService = Executors.newSingleThreadExecutor(); this.deserializerService = Executors.newFixedThreadPool(numProcessors); this.queue = new ArrayBlockingQueue<Batch>(numBatchInQueue); // This keeps filling up the queue producerService.submit(new ProducerTask()); }
/** * Constructs the object based on the content as a List, the JSON can be an array or just a single value without the [] symbols * @param content Reader * @return A collection of the specified type */ public <T> List<T> constructList(Reader content, Class<T> requiredType) { ObjectReader reader = objectMapper.readerFor(TypeFactory.defaultInstance().constructParametricType(List.class, requiredType)); try { List<T> toReturn = reader.readValue(content); if (toReturn == null || toReturn.isEmpty()) { throw new InvalidArgumentException("Could not read content from HTTP request body, the list is empty"); } return toReturn; } catch (IOException error) { throw new InvalidArgumentException("Could not read content from HTTP request body: "+error.getMessage()); } }
/** * Reload. * * @throws HmsException the hms exception */ public void reload() throws HmsException { ObjectMapper objectMapper = new ObjectMapper(); ObjectReader objectReader = objectMapper.readerForUpdating( this ); try { objectReader.readValue( new File( filename ) ); } catch ( IOException e ) { logger.error( "Error reloading HMS inventory configuration file: {}.", filename, e ); throw new HmsException( "Error reloading HMS inventory configuration file: " + filename, e ); } }
protected void setMeta(Resource dataBody, Object instance, ResourceInformation resourceInformation) { ResourceField metaField = resourceInformation.getMetaField(); if (dataBody.getMeta() != null && metaField != null) { JsonNode metaNode = dataBody.getMeta(); Class<?> metaClass = metaField.getType(); ObjectReader metaMapper = objectMapper.readerFor(metaClass); try { Object meta = metaMapper.readValue(metaNode); PropertyUtils.setProperty(instance, metaField.getUnderlyingName(), meta); } catch (IOException e) { throw new ResponseBodyException("failed to parse links information", e); } } }
/** * Retrieves an object by key. * * @param key Item key * @param reader The object reader * @param <T> Generic type of something * @return The object or null. * @since 17.08.20 */ private <T> T get(final String key, final ObjectReader reader) { T object = null; try { final String rawData; try (final Jedis jedis = this.getConnection()) { rawData = jedis.get(key); } if (rawData != null) { object = reader.readValue(rawData.getBytes()); } } catch (final IOException ex) { PlayRedisImpl.LOG.error("Can't get object", ex); } return object; }
/** * Get values from a list. * * @param key The list key * @param reader The object reader * @param offset From where * @param count The number of items to retrieve * @param <T> Generic type of something implementing {@code java.io.Serializable} * @return The values list * @since 17.08.20 */ private <T> List<T> getFromList(final String key, final ObjectReader reader, final int offset, final int count) { final List<T> objects = new ArrayList<>(); try { final List<String> rawData; try (final Jedis jedis = this.getConnection()) { rawData = jedis.lrange(key, offset, count > 0 ? count - 1 : count); } if (rawData != null) { for (final String s : rawData) { objects.add(reader.readValue(s)); } } } catch (IOException | NullPointerException ex) { PlayRedisImpl.LOG.error("Can't get object from list", ex); } return objects; }
@Override public <T> T unmarshall(final Object marshalled, final Class<T> type) throws Exception { checkNotNull(marshalled); checkState(marshalled instanceof Map, "Marshalled data must be a Map; found: %s", marshalled.getClass()); // FIXME: This allows the top-level object to be created, but if any children objects of this are missing // FIXME: ... no-arg CTOR then Jackson will fail to construct them. // FIXME: Is there any way to configure the basic instance creation for Jackson? Object value = instanceCreator.newInstance(type); // performs same basic logic as ObjectMapper.convertValue(Object, Class) helper ObjectReader reader = objectMapper.readerForUpdating(value); TokenBuffer buff = new TokenBuffer(objectMapper, false); objectMapper.writeValue(buff, marshalled); reader.readValue(buff.asParser()); return type.cast(value); }
public ParserGroundTruth(final InputStream is) throws IOException { try(final BufferedReader reader = new BufferedReader( new InputStreamReader(is, "UTF-8"))) { ObjectMapper om = new ObjectMapper(); ObjectReader r = om.reader().forType(new TypeReference<Paper>() {}); papers = new ArrayList<Paper>(); while (true) { final String line = reader.readLine(); if (line == null) break; papers.add(r.readValue(line)); } } log.info("Read " + papers.size() + " papers."); buildLookup(); papers.forEach((Paper p) -> { for (int i = 0; i < p.authors.length; i++) p.authors[i] = invertAroundComma(p.authors[i]); }); }
Context apply(String s, Map<String, String> args, boolean isBatch, Handle dbiHandle, Map<String, String> parameters, NameList names) throws IOException { ObjectReader mapper = new ObjectMapper().readerFor(Object.class); HashMap<String, Object> parsedArgs = new HashMap<>(); for (Map.Entry<String, String> a : args.entrySet()) { try { parsedArgs.put(a.getKey(), mapper.readValue(a.getValue())); } catch (Exception e) { parsedArgs.put(a.getKey(), a.getValue()); } } Handlebars handlebars = new Handlebars().with(EscapingStrategy.NOOP); this.parameters = parameters; StringHelper.register(handlebars); StringHelpers.register(handlebars); FilterHelper.register(handlebars); ConditionalHelper.register(handlebars); new ParameterHelper(parameters, names).registerHelper(handlebars); eh = new EachHelper(parameters, names, isBatch, dbiHandle).registerHelper(handlebars); template = handlebars.compileInline(s); sql = template.apply(parsedArgs); return this; }
private List<ArrayNode> downloadResult(String jobId) { return client.jobResult(jobId, TDResultFormat.JSON, input -> { try { List<String> lines = CharStreams.readLines(new InputStreamReader(input)); ObjectReader reader = objectMapper().readerFor(ArrayNode.class); List<ArrayNode> result = new ArrayList<>(); for (String line : lines) { result.add(reader.readValue(line)); } return result; } catch (IOException e) { throw Throwables.propagate(e); } }); }
@Override public JsonNode getDocumentByIdAndRev(String id, String rev) { String currentRev = getCurrentRevision(id); JsonNode schema = null; // current and needed revisions are the same so return current version of the schema if (currentRev.equals(rev)) { return this.find(id); } else { AttachmentInputStream ais = db.getAttachment(id, rev); try { byte[] data = IOUtils.toByteArray(ais); ObjectReader reader = (new ObjectMapper()).reader(); schema = reader.readTree(new ByteArrayInputStream(data)); ais.close(); } catch (IOException ex) { logger.error(ex); } return schema; } }
/** * Converts the specified {@link AggregatedHttpMessage} to an object of {@code expectedResultType}. */ @Override public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpMessage request, Class<?> expectedResultType) throws Exception { final MediaType contentType = request.headers().contentType(); if (contentType != null && (contentType.is(MediaType.JSON) || contentType.subtype().endsWith("+json"))) { final ObjectReader reader = readers.computeIfAbsent(expectedResultType, mapper::readerFor); if (reader != null) { final String content = request.content().toString( contentType.charset().orElse(StandardCharsets.UTF_8)); try { return reader.readValue(content); } catch (JsonProcessingException e) { throw new IllegalArgumentException("failed to parse a JSON document: " + e, e); } } } return RequestConverterFunction.fallthrough(); }
/** * Load movies from database. */ void loadMoviesFromDatabase(MVMap<UUID, String> movieMap, ObjectMapper objectMapper) { // load movies ObjectReader movieObjectReader = objectMapper.readerFor(Movie.class); for (UUID uuid : new ArrayList<>(movieMap.keyList())) { String json = ""; try { json = movieMap.get(uuid); Movie movie = movieObjectReader.readValue(json); movie.setDbId(uuid); // for performance reasons we add movies directly movieList.add(movie); } catch (Exception e) { LOGGER.warn("problem decoding movie json string: " + e.getMessage()); LOGGER.info("dropping corrupt movie"); movieMap.remove(uuid); } } LOGGER.info("found " + movieList.size() + " movies in database"); }
void loadMovieSetsFromDatabase(MVMap<UUID, String> movieSetMap, ObjectMapper objectMapper) { // load movie sets ObjectReader movieSetObjectReader = objectMapper.readerFor(MovieSet.class); for (UUID uuid : new ArrayList<>(movieSetMap.keyList())) { try { MovieSet movieSet = movieSetObjectReader.readValue(movieSetMap.get(uuid)); movieSet.setDbId(uuid); // for performance reasons we add movies sets directly movieSetList.add(movieSet); } catch (Exception e) { LOGGER.warn("problem decoding movie set json string: " + e.getMessage()); LOGGER.info("dropping corrupt movie set"); movieSetMap.remove(uuid); } } LOGGER.info("found " + movieSetList.size() + " movieSets in database"); }
/** * Load tv shows from database. */ void loadTvShowsFromDatabase(MVMap<UUID, String> tvShowMap, ObjectMapper objectMapper) { // load all TV shows from the database ObjectReader tvShowObjectReader = objectMapper.readerFor(TvShow.class); for (UUID uuid : new ArrayList<>(tvShowMap.keyList())) { try { TvShow tvShow = tvShowObjectReader.readValue(tvShowMap.get(uuid)); tvShow.setDbId(uuid); // for performance reasons we add tv shows directly tvShowList.add(tvShow); } catch (Exception e) { LOGGER.warn("problem decoding TV show json string: " + e.getMessage()); LOGGER.info("dropping corrupt TV show"); tvShowMap.remove(uuid); } } LOGGER.info("found " + tvShowList.size() + " TV shows in database"); }
@Test public void testJsonDeserialization() throws Exception { InputStream is = null; try { is = getClass().getResourceAsStream( "/decisions/examples/Ch11LoanExample.json"); ObjectMapper mapper = new ObjectMapper(); // we'll be reading instances of MyBean ObjectReader reader = mapper.readerFor(DmnModel.class); // and then do other configuration, if any, and read: DmnModel result = reader.readValue(is); assertNotNull(result); } catch (Exception e) { e.printStackTrace(); // fail("unable to find test resource"); } // DmnModel dmnModel = de.getRepositoryService().createModelForTenant( // ch11LoanExample.getDmnModel()); // transformAndAssert(dmnModel, "applicationRiskScoreModel_bkm"); }
public static Submission getSubmissionFromStorage(String fullName, Context c, boolean offline, ObjectReader reader) throws IOException { String gotten = getStringFromFile(fullName, c); if (!gotten.isEmpty()) { if (gotten.startsWith("[") && offline) { return (SubmissionSerializer.withComments(reader.readTree(gotten), CommentSort.CONFIDENCE)); } else if (gotten.startsWith("[")) { JsonNode elem = reader.readTree(gotten); return (new Submission(elem.get(0).get("data").get("children").get(0).get("data"))); } else { return (new Submission(reader.readTree(gotten))); } } return null; }
private Match _findFormat(AccessorForReader paramAccessorForReader) { Object localObject1 = null; Object localObject2 = null; for (ObjectReader localObjectReader : this._readers) { paramAccessorForReader.reset(); MatchStrength localMatchStrength = localObjectReader.getFactory().hasFormat(paramAccessorForReader); if ((localMatchStrength != null) && (localMatchStrength.ordinal() >= this._minimalMatch.ordinal()) && ((localObject1 == null) || (localObject2.ordinal() < localMatchStrength.ordinal()))) { localObject1 = localObjectReader; localObject2 = localMatchStrength; if (localMatchStrength.ordinal() >= this._optimalMatch.ordinal()) break; } } return paramAccessorForReader.createMatcher(localObject1, localObject2); }
/** * Parse response into data model object. * * @param unwrap Unwrap datamodel * @return Response datamodel * @throws IOException */ public T parseResponse() throws IOException { ObjectReader reader = MAPPER.readerFor(datamodel).without(Feature.AUTO_CLOSE_SOURCE); if (datamodel.isAnnotationPresent(JsonRootName.class)) { reader = reader.with(DeserializationFeature.UNWRAP_ROOT_VALUE); } try (final InputStream is = response.getStream()) { final T result = reader.readValue(is); /* * ObjectReader.readValue might not consume the entire inputstream, * we skip everything after the json root element. * This is needed for proper http connection reuse (keep alive). */ is.skip(Long.MAX_VALUE); return result; } }
@Test public void testUnixTimestampDeserialize() throws Exception { UnixTimestampObjectMapperProvider provider = new UnixTimestampObjectMapperProvider(); ObjectMapper mapper = provider.get(); ObjectReader reader = mapper.reader(); StupidPojo pojo = reader .withType(StupidPojo.class) .readValue(String.format("{\"message\" : \"Test message\", \"date\":%s}", timestamp / 1000)); LOGGER.info("{}", pojo); DateTime refDate = new DateTime(date); Interval interval = getInterval(new DateTime(pojo.getDate()), refDate); assertTrue(Math.abs(interval.toDurationMillis()) < ALLOWED_DIFFERENCE); }
@Test public void testRead() throws Exception { final ObjectReader reader = mapper.reader(MixedContentMap.class); final MixedContentMap map = reader.readValue(MixedContentMapTest.class.getResourceAsStream("mixedMapContent.json")); assertThat(map, notNullValue()); assertThat(map.get("string"), is("string value")); assertThat(map.get("numeric"), is("10")); assertThat(map.get("boolean"), is("true")); assertThat(map.get("double"), is("10.1")); assertThat(map.get("null"), nullValue()); assertThat(map.get("empty"), is("")); final String object = map.get("object"); assertThat(object, sameJSONAs("{\"eq\": { \"field\": \"nbCommands\",\"value\": \"13\" }}")); final String array = map.get("array"); assertThat(array, sameJSONAs("[1, 2, 3]")); }
@Test public void applySomePropertiesToAnObject() throws JsonProcessingException, IOException { ExtensionApplication extensionApplication = new ExtensionApplication(); extensionApplication.setAffiliateDetails(new AffiliateDetails()); extensionApplication.setNotesInternal("internalNotes"); String incomingJSON = "{ \"notesInternal\": \"new value\"}"; ObjectMapper objectMapper = new ObjectMapper(); ObjectReader readerForUpdating = objectMapper.readerForUpdating(extensionApplication); JsonNode tree = objectMapper.readTree(incomingJSON); readerForUpdating.readValue(tree); Assert.assertEquals("new value", extensionApplication.getNotesInternal()); }
@Test public void testReadValue() throws Exception { String json_str = "{\"name\" : \"Jackson\"}"; byte[] json_b = json_str.getBytes(UTF_8); ObjectReader reader = mapper.reader(__POJO.class); __POJO pojo = reader.readValue(json_str); pojo = reader.readValue(json_b); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); Method readval1 = ObjectReader.class.getMethod("readValue", String.class); Method readval2 = ObjectReader.class.getMethod("readValue", byte[].class); verifier.verifyTrace(event("JACKSON", readval1, Expectations.annotation("jackson.json.length", json_str.length()))); verifier.verifyTrace(event("JACKSON", readval2, Expectations.annotation("jackson.json.length", json_b.length))); verifier.verifyTraceCount(0); }
/** * Reads a CSV file into a list of the specified type. * @param csv The CSV file. * @param responseClass The type of the returned list's elements. * @param schema A schema representing the CSV file's structure. * @param <T> The type of the returned list's elements. * @return A list of parsed elements. * @throws IOException if parsing failed. */ public static <T> List<T> readFromCsv(String csv, Class<T> responseClass, CsvSchema schema) throws IOException { if (csv == null) { // Protect against NullPointerException csv = ""; } ObjectReader reader = new CsvMapper().reader(responseClass).with(schema); MappingIterator<T> iterator = reader.readValues(csv); ArrayList<T> results = new ArrayList<>(); try { while (iterator.hasNext()) { results.add(iterator.next()); } } catch (RuntimeException e) { // ObjectReader throws (subclasses of) IOException, but MappingIterator wraps them in a RuntimeException. // We unwrap them for consistency. Throwable cause = e.getCause(); if (cause != null && cause instanceof IOException) { throw (IOException) cause; } throw e; } return results; }
@Test public void deserializingADiseaseOccurrenceCollectionGivesCorrectResult() throws Exception { // Arrange GeoJsonDiseaseOccurrenceFeatureCollection occurrences = new GeoJsonDiseaseOccurrenceFeatureCollection( Arrays.asList(defaultDiseaseOccurrence(), defaultDiseaseOccurrence())); AbraidJsonObjectMapper objectMapper = new AbraidJsonObjectMapper(); OutputStream stream = new ByteArrayOutputStream(); objectMapper.writeValue(stream, occurrences); String input = stream.toString(); // Act ObjectReader reader = objectMapper.reader(GeoJsonDiseaseOccurrenceFeatureCollection.class); GeoJsonDiseaseOccurrenceFeatureCollection result = reader.readValue(input); // Assert assertThat(result).isNotNull(); assertThat(result).isEqualTo(occurrences); }
public static <T extends Config> T load(Class<T> configClazz, InputStream configInput, String configPath, InputStream defaultConfigInput) throws IOException, ConfigValidationException { Objects.requireNonNull(configClazz); Objects.requireNonNull(configInput); final ObjectMapper mapper = createObjectMapper(); T defaultConfig; ObjectReader updater = null; if (defaultConfigInput != null) { defaultConfig = mapper.readValue(defaultConfigInput, configClazz); updater = mapper.readerForUpdating(defaultConfig); } T config; if (updater != null) { config = updater.readValue(configInput); } else { config = mapper.readValue(configInput, configClazz); } config.configFolder = Resource.from(configPath).getParent(); //validate(config); return config; }
public static <T extends Config> T load(TypeReference<?> configClazz, InputStream configInput, String configPath, InputStream defaultConfigInput) throws IOException, ConfigValidationException { Objects.requireNonNull(configClazz); Objects.requireNonNull(configInput); final ObjectMapper mapper = createObjectMapper(); T defaultConfig; ObjectReader updater = null; if (defaultConfigInput != null) { defaultConfig = mapper.readValue(defaultConfigInput, configClazz); updater = mapper.readerForUpdating(defaultConfig); } T config; if (updater != null) { config = updater.readValue(configInput); } else { config = mapper.readValue(configInput, configClazz); } config.configFolder = Resource.from(configPath).getParent(); //validate(config); return config; }
public TraceEventIterator( JsonParser json, ObjectReader reader) throws JsonParseException, IOException { this.json = json; this.reader = reader; if (! json.hasCurrentToken()) { json.nextToken(); } if (! json.isExpectedStartArrayToken()) { throw new IllegalArgumentException(String.valueOf(json.getCurrentLocation())); } json.nextToken(); this.header = reader.readValue(json, TraceHeader.class); json.nextToken(); if (! json.isExpectedStartArrayToken()) { throw new IllegalArgumentException(String.valueOf(json.getCurrentLocation())); } json.clearCurrentToken(); }
protected Iterator<Records.Request> getDefaultRequests() { ObjectReader reader = getObjectMapper().reader(); File file = Tracing.getTraceInputFileConfiguration(getRuntimeModule().getConfiguration()); Iterator<TraceEvent> events; if (getRuntimeModule().getConfiguration().getArguments().helpOptionSet()) { events = Iterators.empty(); } else { logger.info("Trace input: {}", file); try { events = TraceEventIterator.forFile(file, reader); } catch (IOException e) { throw Throwables.propagate(e); } } return TraceRequestIterator.requestsOf(TraceRequestIterator.from(events)); }
public <T> Collection<T> getAll(String path, int limit, Class<T> clazz) { try { final JsonNode json = getJson(path + "/_search?size=" + limit); if (json != null) { JsonNode hits = json.get("hits").get("hits"); List<T> all = new ArrayList<T>(hits.size()); ObjectReader reader = JsonUtils.getObjectReader(clazz); for (JsonNode hit : hits) { all.add(reader.<T>readValue(hit.get("_source"))); } return all; } else { return Collections.emptyList(); } } catch (IOException e) { logger.warn(e.getMessage(), e); return Collections.emptyList(); } }
/** * Flushes all {@code key=>value} pairs and replaces them with * the values read from the given {@code snapshotInputStream}. * This implementation expects the {@code InputStream} to contain * a sequence of JSON {@link KeyValue} instances. * * @param lastAppliedIndex log index >= 0 of the last change contained in this snapshot * @param snapshotInputStream {@code InputStream} from which all {@code key=> value} pairs should be read * @throws IOException if valid {@code key=>value} pairs cannot be read from {@code snapshotInputStream}. * Since no internal state is modified until the {@code snapshotInputStream} is completely read and * parsed, {@code LocalStore} can still be used safely after an {@code IOException} is thrown * @throws RuntimeException if the {@code key=>value} pairs in {@code snapshotInputStream} cannot be converted to JSON */ synchronized void loadState(long lastAppliedIndex, InputStream snapshotInputStream) throws IOException { try { // read values from the snapshot into a temporary map Map<String, String> snapshotEntries = Maps.newHashMap(); ObjectMapper mapper = new ObjectMapper(); ObjectReader reader = mapper.reader(KeyValue.class); MappingIterator<KeyValue> it = reader.readValues(snapshotInputStream); while (it.hasNext()) { KeyValue keyValue = it.next(); snapshotEntries.put(keyValue.getKey(), keyValue.getValue()); // values are read into this temporary map! } // update the index // NOTE: AFAIU, we should never get a snapshot which contains fewer entries than we've applied updateLastAppliedIndex(lastAppliedIndex); // replace the old entries map with the new one generated from the snapshot entries = snapshotEntries; } finally { Closeables.close(snapshotInputStream, true); } }
@Override public Object getObject(String string, Type type) { try { JavaType javaType = mapper.getTypeFactory().constructType(type); ObjectReader objectReader = mapper.readerFor(javaType); return objectReader.readValue(string); } catch (Exception e) { e.printStackTrace(); } return null; }
@Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { JavaType javaType = mapper.getTypeFactory().constructType(type); ObjectReader reader = mapper.readerFor(javaType); return new JacksonResponseBodyConverter<>(reader); }