本文整理汇总了Java中com.fasterxml.jackson.databind.ObjectReader.readValues方法的典型用法代码示例。如果您正苦于以下问题:Java ObjectReader.readValues方法的具体用法?Java ObjectReader.readValues怎么用?Java ObjectReader.readValues使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.fasterxml.jackson.databind.ObjectReader
的用法示例。
在下文中一共展示了ObjectReader.readValues方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: checkCaptcha
import com.fasterxml.jackson.databind.ObjectReader; //导入方法依赖的package包/类
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);
}
}
示例2: readFromCsv
import com.fasterxml.jackson.databind.ObjectReader; //导入方法依赖的package包/类
/**
* 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;
}
示例3: loadState
import com.fasterxml.jackson.databind.ObjectReader; //导入方法依赖的package包/类
/**
* 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);
}
}
示例4: workflowCreate
import com.fasterxml.jackson.databind.ObjectReader; //导入方法依赖的package包/类
private void workflowCreate() throws IOException, ExecutionException, InterruptedException {
final String component = namespace.getString(parser.workflowCreateComponentId.getDest());
final File file = namespace.get(parser.workflowCreateFile.getDest());
final ObjectReader workflowReader = Json.YAML_MAPPER.reader()
.forType(WorkflowConfiguration.class);
final MappingIterator<WorkflowConfiguration> iterator;
if (file == null || file.getName().equals("-")) {
iterator = workflowReader.readValues(System.in);
} else {
iterator = workflowReader.readValues(file);
}
final List<WorkflowConfiguration> configurations = iterator.readAll();
// TODO: validate workflows locally before creating them
final List<CompletionStage<Workflow>> futures = configurations.stream()
.map(configuration -> styxClient.createOrUpdateWorkflow(component, configuration))
.collect(toList());
for (CompletionStage<Workflow> future : futures) {
final Workflow created = future.toCompletableFuture().get();
cliOutput.printMessage("Workflow " + created.workflowId() + " in component "
+ created.componentId() + " created.");
}
}
示例5: call
import com.fasterxml.jackson.databind.ObjectReader; //导入方法依赖的package包/类
@Override
public Void call() {
try {
ObjectMapper objectMapper = new ObjectMapper();
ObjectReader reader = objectMapper.reader(Map.class);
MappingIterator<Map<String, Object>> iterator = reader.readValues(getInputStream());
while (iterator.hasNextValue()) {
Map<String, Object> entry = iterator.nextValue();
// monitor the distribution of countries
if (entry.containsKey("group") && entry.get("group") instanceof Map) {
Map<String, Object> group = (Map<String, Object>) entry.get("group");
if (group.containsKey("group_country")) {
metrics.meter("meetup.country." + group.get("group_country")).mark();
metrics.meter("meetup.country.total").mark();
}
}
// monitor the distribution of the number of guests
if (entry.containsKey("guests") && entry.get("guests") instanceof Long) {
metrics.histogram("meetup.guests").update((Long)entry.get("guests"));
}
// monitor reservation time upfront, 1d, 4d, 1w, 2w, 1m, 2m, -
if (entry.containsKey("event") && entry.get("event") instanceof Map) {
Map<String, Object> event = (Map<String, Object>) entry.get("event");
if (event.get("time") instanceof Long) {
metrics.counter("meetup.reservation.time.total").inc();
metrics.counter("meetup.reservation.time." + getUpfrontReservationTime((Long) event.get("time"))).inc();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
示例6: run
import com.fasterxml.jackson.databind.ObjectReader; //导入方法依赖的package包/类
public void run() throws Exception {
startElasticsearchIfNecessary();
createIndexAndMappingIfNecessary();
// index into the metrics index without date formatting
ElasticsearchReporter reporter = ElasticsearchReporter.forRegistry(registry)
.hosts("localhost:9200")
.indexDateFormat("")
.percolationNotifier(new HttpNotifier())
.percolationFilter(MetricFilter.ALL)
.build();
reporter.start(60, TimeUnit.SECONDS);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
ObjectReader reader = objectMapper.reader(Map.class);
MappingIterator<Map<String, Object>> iterator = reader.readValues(getInputStream());
try {
while (iterator.hasNextValue()) {
Map<String, Object> entry = iterator.nextValue();
if (entry.containsKey("_heartbeat_")) {
heartbeatCounter.inc();
continue;
}
if (entry.containsKey("ll") && entry.containsKey("t")) {
long timestamp = ((Integer) entry.get("t")).longValue();
List<Number> location = (List<Number>) entry.get("ll");
double latitude = location.get(0).doubleValue();
double longitude = location.get(1).doubleValue();
addToBulkRequest(timestamp, latitude, longitude);
entryMeter.mark(1);
}
}
} finally {
executeBulkRequest();
}
}
示例7: readEvents
import com.fasterxml.jackson.databind.ObjectReader; //导入方法依赖的package包/类
@Override
public Events readEvents( InputStream inputStream, boolean skipFirst ) throws IOException
{
Events events = new Events();
ObjectReader reader = CSV_MAPPER.readerFor( CsvEventDataValue.class )
.with( CSV_SCHEMA.withSkipFirstDataRow( skipFirst ) );
MappingIterator<CsvEventDataValue> iterator = reader.readValues( inputStream );
Event event = new Event();
event.setEvent( "not_valid" );
while ( iterator.hasNext() )
{
CsvEventDataValue dataValue = iterator.next();
if ( !event.getEvent().equals( dataValue.getEvent() ) )
{
event = new Event();
event.setEvent( dataValue.getEvent() );
event.setStatus( StringUtils.isEmpty( dataValue.getStatus() )
? EventStatus.ACTIVE : Enum.valueOf( EventStatus.class, dataValue.getStatus() ) );
event.setProgram( dataValue.getProgram() );
event.setProgramStage( dataValue.getProgramStage() );
event.setEnrollment( dataValue.getEnrollment() );
event.setOrgUnit( dataValue.getOrgUnit() );
event.setEventDate( dataValue.getEventDate() );
event.setDueDate( dataValue.getDueDate() );
event.setCompletedDate( dataValue.getCompletedDate() );
event.setCompletedBy( dataValue.getCompletedBy() );
if ( dataValue.getLongitude() != null && dataValue.getLatitude() != null )
{
event.setCoordinate( new Coordinate( dataValue.getLongitude(), dataValue.getLatitude() ) );
}
events.getEvents().add( event );
}
DataValue value = new DataValue( dataValue.getDataElement(), dataValue.getValue() );
value.setStoredBy( dataValue.getStoredBy() );
value.setProvidedElsewhere( dataValue.getProvidedElsewhere() );
event.getDataValues().add( value );
}
return events;
}
示例8: readEvents
import com.fasterxml.jackson.databind.ObjectReader; //导入方法依赖的package包/类
@Override
public Events readEvents( InputStream inputStream, boolean skipFirst ) throws IOException
{
Events events = new Events();
ObjectReader reader = CSV_MAPPER.readerFor( CsvEventDataValue.class )
.with( CSV_SCHEMA.withSkipFirstDataRow( skipFirst ) );
MappingIterator<CsvEventDataValue> iterator = reader.readValues( inputStream );
Event event = new Event();
event.setEvent( "not_valid" );
while ( iterator.hasNext() )
{
CsvEventDataValue dataValue = iterator.next();
if ( !event.getEvent().equals( dataValue.getEvent() ) )
{
event = new Event();
event.setEvent( dataValue.getEvent() );
event.setStatus( StringUtils.isEmpty( dataValue.getStatus() )
? EventStatus.ACTIVE : Enum.valueOf( EventStatus.class, dataValue.getStatus() ) );
event.setProgram( dataValue.getProgram() );
event.setProgramStage( dataValue.getProgramStage() );
event.setEnrollment( dataValue.getEnrollment() );
event.setOrgUnit( dataValue.getOrgUnit() );
event.setEventDate( dataValue.getEventDate() );
event.setDueDate( dataValue.getDueDate() );
if ( dataValue.getLongitude() != null && dataValue.getLatitude() != null )
{
event.setCoordinate( new Coordinate( dataValue.getLongitude(), dataValue.getLatitude() ) );
}
events.getEvents().add( event );
}
DataValue value = new DataValue( dataValue.getDataElement(), dataValue.getValue() );
value.setStoredBy( dataValue.getStoredBy() );
value.setProvidedElsewhere( dataValue.getProvidedElsewhere() );
event.getDataValues().add( value );
}
return events;
}
示例9: testJsonOutput
import com.fasterxml.jackson.databind.ObjectReader; //导入方法依赖的package包/类
@Test
public void testJsonOutput() throws IOException {
String[] args = new String[] { "-a", "json", "-o",
"/path/to/output.json" };
DirectoryManagerFactory
.setDirectoryManagerClass(MockDirectoryManager.class);
ClientConfiguration config = new ClientConfiguration(args);
JsonSerializationAction jsa = (JsonSerializationAction) config
.getActions().get(0);
ItemIdValue subject1 = Datamodel.makeWikidataItemIdValue("Q42");
ItemIdValue subject2 = Datamodel.makeWikidataItemIdValue("Q43");
MonolingualTextValue mtv1 = Datamodel.makeMonolingualTextValue("Test1",
"en");
MonolingualTextValue mtv2 = Datamodel.makeMonolingualTextValue("Test2",
"fr");
ItemDocument id1 = Datamodel.makeItemDocument(subject1,
Arrays.asList(mtv1, mtv2), Arrays.asList(mtv1),
Collections.<MonolingualTextValue> emptyList(),
Collections.<StatementGroup> emptyList(),
Collections.<String, SiteLink> emptyMap());
ItemDocument id2 = Datamodel.makeItemDocument(subject2,
Collections.<MonolingualTextValue> emptyList(),
Arrays.asList(mtv2),
Collections.<MonolingualTextValue> emptyList(),
Collections.<StatementGroup> emptyList(),
Collections.<String, SiteLink> emptyMap());
PropertyDocument pd1 = Datamodel
.makePropertyDocument(
Datamodel.makeWikidataPropertyIdValue("P31"),
Arrays.asList(mtv1),
Collections.<MonolingualTextValue> emptyList(),
Arrays.asList(mtv1),
Datamodel
.makeDatatypeIdValue(DatatypeIdValue.DT_MONOLINGUAL_TEXT));
jsa.open();
jsa.processItemDocument(id1);
jsa.processPropertyDocument(pd1);
jsa.processItemDocument(id2);
jsa.close();
MockDirectoryManager mdm = new MockDirectoryManager(
Paths.get("/path/to/"), false);
ObjectMapper mapper = new ObjectMapper();
ObjectReader documentReader = mapper
.reader(JacksonTermedStatementDocument.class);
MappingIterator<JacksonTermedStatementDocument> documentIterator = documentReader
.readValues(mdm.getInputStreamForFile("output.json",
CompressionType.NONE));
List<EntityDocument> results = new ArrayList<>();
while (documentIterator.hasNextValue()) {
JacksonTermedStatementDocument document = documentIterator
.nextValue();
document.setSiteIri(Datamodel.SITE_WIKIDATA);
results.add(document);
}
documentIterator.close();
assertEquals(3, results.size());
assertEquals(id1, results.get(0));
assertEquals(pd1, results.get(1));
assertEquals(id2, results.get(2));
}
示例10: testJsonGzipOutput
import com.fasterxml.jackson.databind.ObjectReader; //导入方法依赖的package包/类
@Test
public void testJsonGzipOutput() throws IOException {
String[] args = new String[] { "-a", "json", "-o",
"/path/to/output.json", "-z", "gz" };
DirectoryManagerFactory
.setDirectoryManagerClass(MockDirectoryManager.class);
ClientConfiguration config = new ClientConfiguration(args);
JsonSerializationAction jsa = (JsonSerializationAction) config
.getActions().get(0);
ItemIdValue subject1 = Datamodel.makeWikidataItemIdValue("Q42");
MonolingualTextValue mtv1 = Datamodel.makeMonolingualTextValue("Test1",
"en");
MonolingualTextValue mtv2 = Datamodel.makeMonolingualTextValue("Test2",
"fr");
ItemDocument id1 = Datamodel.makeItemDocument(subject1,
Arrays.asList(mtv1, mtv2), Arrays.asList(mtv1),
Collections.<MonolingualTextValue> emptyList(),
Collections.<StatementGroup> emptyList(),
Collections.<String, SiteLink> emptyMap());
jsa.open();
jsa.processItemDocument(id1);
jsa.close();
MockDirectoryManager mdm = new MockDirectoryManager(
Paths.get("/path/to/"), false);
ObjectMapper mapper = new ObjectMapper();
ObjectReader documentReader = mapper
.reader(JacksonTermedStatementDocument.class);
MappingIterator<JacksonTermedStatementDocument> documentIterator = documentReader
.readValues(mdm.getInputStreamForFile("output.json.gz",
CompressionType.GZIP));
List<EntityDocument> results = new ArrayList<>();
while (documentIterator.hasNextValue()) {
JacksonTermedStatementDocument document = documentIterator
.nextValue();
document.setSiteIri(Datamodel.SITE_WIKIDATA);
results.add(document);
}
documentIterator.close();
assertEquals(1, results.size());
assertEquals(id1, results.get(0));
}
示例11: testJsonBz2Output
import com.fasterxml.jackson.databind.ObjectReader; //导入方法依赖的package包/类
@Test
public void testJsonBz2Output() throws IOException {
String[] args = new String[] { "-a", "json", "-o", "output.json", "-z",
"bz2" };
DirectoryManagerFactory
.setDirectoryManagerClass(MockDirectoryManager.class);
ClientConfiguration config = new ClientConfiguration(args);
JsonSerializationAction jsa = (JsonSerializationAction) config
.getActions().get(0);
ItemIdValue subject1 = Datamodel.makeWikidataItemIdValue("Q42");
MonolingualTextValue mtv1 = Datamodel.makeMonolingualTextValue("Test1",
"en");
MonolingualTextValue mtv2 = Datamodel.makeMonolingualTextValue("Test2",
"fr");
ItemDocument id1 = Datamodel.makeItemDocument(subject1,
Arrays.asList(mtv1, mtv2), Arrays.asList(mtv1),
Collections.<MonolingualTextValue> emptyList(),
Collections.<StatementGroup> emptyList(),
Collections.<String, SiteLink> emptyMap());
jsa.open();
jsa.processItemDocument(id1);
jsa.close();
MockDirectoryManager mdm = new MockDirectoryManager(Paths.get("."),
false);
ObjectMapper mapper = new ObjectMapper();
ObjectReader documentReader = mapper
.reader(JacksonTermedStatementDocument.class);
MappingIterator<JacksonTermedStatementDocument> documentIterator = documentReader
.readValues(mdm.getInputStreamForFile("output.json.bz2",
CompressionType.BZ2));
List<EntityDocument> results = new ArrayList<>();
while (documentIterator.hasNextValue()) {
JacksonTermedStatementDocument document = documentIterator
.nextValue();
document.setSiteIri(Datamodel.SITE_WIKIDATA);
results.add(document);
}
documentIterator.close();
assertEquals(1, results.size());
assertEquals(id1, results.get(0));
}
示例12: testSerializer
import com.fasterxml.jackson.databind.ObjectReader; //导入方法依赖的package包/类
@Test
public void testSerializer() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
JsonSerializer serializer = new JsonSerializer(out);
ItemDocument id1 = Datamodel.makeItemDocument(DataObjectFactoryImplTest
.getTestItemIdValue(1), Collections
.singletonList(Datamodel
.makeMonolingualTextValue("Label1", "lang1")),
Collections.<MonolingualTextValue> emptyList(), Collections
.<MonolingualTextValue> emptyList(),
DataObjectFactoryImplTest.getTestStatementGroups(1, 24, 1,
EntityIdValue.ET_ITEM), Collections
.<String, SiteLink> emptyMap(), 1234);
ItemDocument id2 = Datamodel.makeItemDocument(DataObjectFactoryImplTest
.getTestItemIdValue(2), Collections
.<MonolingualTextValue> emptyList(), Collections
.<MonolingualTextValue> emptyList(), Collections
.<MonolingualTextValue> emptyList(), DataObjectFactoryImplTest
.getTestStatementGroups(2, 23, 1, EntityIdValue.ET_ITEM),
Collections.singletonMap(
"enwiki",
Datamodel.makeSiteLink("Title2", "enwiki",
Collections.<String>emptyList())), 0);
PropertyDocument pd1 = Datamodel.makePropertyDocument(
DataObjectFactoryImplTest.getTestPropertyIdValue(1),
Collections.<MonolingualTextValue> emptyList(), Collections
.<MonolingualTextValue> emptyList(), Collections
.singletonList(Datamodel
.makeMonolingualTextValue("Alias1", "lang1")),
Collections.<StatementGroup> emptyList(), Datamodel
.makeDatatypeIdValue(DatatypeIdValue.DT_COMMONS_MEDIA),
3456);
serializer.open();
serializer.processItemDocument(id1);
serializer.processItemDocument(id2);
serializer.processPropertyDocument(pd1);
serializer.close();
ArrayList<EntityDocument> inputDocuments = new ArrayList<>();
inputDocuments.add(id1);
inputDocuments.add(id2);
inputDocuments.add(pd1);
ArrayList<EntityDocument> outputDocuments = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
ObjectReader documentReader = mapper
.reader(JacksonTermedStatementDocument.class);
MappingIterator<JacksonTermedStatementDocument> documentIterator = documentReader
.readValues(out.toString());
while (documentIterator.hasNextValue()) {
JacksonTermedStatementDocument document = documentIterator
.nextValue();
document.setSiteIri("foo:");
outputDocuments.add(document);
}
documentIterator.close();
for (int i = 0; i < outputDocuments.size(); i++) {
assertEquals(inputDocuments.get(i), outputDocuments.get(i));
}
assertEquals(serializer.getEntityDocumentCount(), 3);
}