本文整理匯總了Java中com.google.common.collect.Streams類的典型用法代碼示例。如果您正苦於以下問題:Java Streams類的具體用法?Java Streams怎麽用?Java Streams使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Streams類屬於com.google.common.collect包,在下文中一共展示了Streams類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: listRuntimeDependencies
import com.google.common.collect.Streams; //導入依賴的package包/類
protected List<String> listRuntimeDependencies(String collectionName) throws IOException, SolrServerException {
ModifiableSolrParams params = new ModifiableSolrParams().set("file",RUNTIME_LIB_FILE_NAME);
SolrRequest request = new QueryRequest(params);
request.setPath("/admin/file");
request.setResponseParser(new InputStreamResponseParser("json"));
NamedList o = client.request(request, collectionName);
LineIterator it = IOUtils.lineIterator((InputStream) o.get("stream"), "utf-8");
List<String> returnValues = Streams.stream(it).collect(Collectors.toList());
//if file not exists (a little hacky..)
if(returnValues.size() == 1 && returnValues.get(0).startsWith("{\"responseHeader\":{\"status\":404")) {
logger.warn("Release does not yet contain rumtimelib configuration file. Runtimelibs have to be installed manually.");
return Collections.emptyList();
};
return returnValues;
}
示例2: getSemiBlocks
import com.google.common.collect.Streams; //導入依賴的package包/類
public Stream<ISemiBlock> getSemiBlocks(World world, BlockPos pos) {
Stream<ISemiBlock> stream = null;
Chunk chunk = world.getChunkFromBlockCoords(pos);
Map<BlockPos, List<ISemiBlock>> map = semiBlocks.get(chunk);
if (map != null) {
List<ISemiBlock> semiblocks = map.get(pos);
if(semiblocks != null){
stream = semiblocks.stream().filter(semiBlock -> !semiBlock.isInvalid());
}
}
//Semiblocks that _just_ have been added, but not the the chunk maps yet.
Stream<ISemiBlock> addingStream = addingBlocks.stream()
.filter(semiBlock -> semiBlock.getWorld() == world &&
semiBlock.getPos().equals(pos) &&
!semiBlock.isInvalid());
if(stream == null){
return addingStream;
}else{
return Streams.concat(stream, addingStream);
}
}
示例3: compute
import com.google.common.collect.Streams; //導入依賴的package包/類
public void compute(String text, CodeArea parent) {
Matcher matcher = getHighlightingPattern().matcher(text);
while(matcher.find()) {
String styleClass = getStyleClass(matcher);
// For now lets setStyles for base style.
parent.setStyle(matcher.start(), matcher.end(), Collections.singleton(styleClass));
// Then we can grab the style from the document via subView and overlay
for(HighlightStyle style : getChildStyles(styleClass, getText(matcher.start(), matcher.end(), parent))){
StyleSpans spans = parent.getStyleSpans(matcher.start(), matcher.end()).subView(style.start, style.end).overlay(
StyleSpans.singleton(new StyleSpan<>(
Arrays.asList(style.styleClasses),
(style.end - style.start)
)),
(strings, strings2) -> {
Collection<String> coll = Streams.concat(strings.stream(), strings2.stream()).collect(Collectors.toList());
logger.debug(coll.toString());
return coll;
}
);
parent.setStyleSpans(matcher.start(), spans); // Reset styles
}
}
}
示例4: deserialize
import com.google.common.collect.Streams; //導入依賴的package包/類
@Override
public BuckarooConfig deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {
Preconditions.checkNotNull(jsonElement);
Preconditions.checkNotNull(type);
Preconditions.checkNotNull(context);
final JsonObject jsonObject = jsonElement.getAsJsonObject();
final JsonArray cookBooksElement = jsonObject.getAsJsonArray("cookbooks");
final ImmutableList<RemoteCookbook> cookBooks = ImmutableList.copyOf(
Streams.stream(cookBooksElement == null ? ImmutableList.of() : cookBooksElement)
.map(x -> (RemoteCookbook) context.deserialize(x, RemoteCookbook.class))
.collect(Collectors.toList()));
final Optional<URL> analyticsServer = jsonObject.has("analytics") ?
Optional.of(context.deserialize(jsonObject.get("analytics"), URL.class)) :
Optional.empty();
return BuckarooConfig.of(cookBooks, analyticsServer);
}
示例5: selectDependency
import com.google.common.collect.Streams; //導入依賴的package包/類
public static Process<Event, RecipeIdentifier> selectDependency(final RecipeSource source, final PartialDependency dependency) {
if (dependency.organization.isPresent()) {
return Process.of(
Single.just(RecipeIdentifier.of(dependency.source, dependency.organization.get(), dependency.project))
);
}
final ImmutableList<RecipeIdentifier> candidates = Streams.stream(source
.findCandidates(dependency))
.limit(5)
.collect(toImmutableList());
if (candidates.size() == 0) {
return Process.error(
PartialDependencyResolutionException.of(candidates, dependency));
}
if (candidates.size() > 1) {
return Process.error(PartialDependencyResolutionException.of(candidates, dependency));
}
return Process.of(
Observable.just(
Notification.of("Resolved partial dependency " + dependency.encode() + " to " + candidates.get(0).encode())),
Single.just(candidates.get(0)));
}
示例6: testEncode
import com.google.common.collect.Streams; //導入依賴的package包/類
@Test
public void testEncode() throws IOException {
ImageWriter writer = Streams.stream(ImageIO.getImageWritersByFormatName("jpeg"))
.filter(TurboJpegImageWriter.class::isInstance)
.findFirst().get();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.85f);
BufferedImage in = ImageIO.read(ClassLoader.getSystemResource("crop_aligned.jpg"));
ByteArrayOutputStream os = new ByteArrayOutputStream();
try (ImageOutputStream ios = ImageIO.createImageOutputStream(os)) {
writer.setOutput(ios);
writer.write(null, new IIOImage(in, null, null), param);
}
os.flush();
assertThat(os.toByteArray()).isNotEmpty();
}
示例7: testCanReuseWriter
import com.google.common.collect.Streams; //導入依賴的package包/類
@Test
public void testCanReuseWriter() throws IOException {
ImageWriter writer = Streams.stream(ImageIO.getImageWritersByFormatName("jpeg"))
.filter(TurboJpegImageWriter.class::isInstance)
.findFirst().get();
BufferedImage in = ImageIO.read(ClassLoader.getSystemResource("rgb.jpg"));
ByteArrayOutputStream rgb = new ByteArrayOutputStream();
try (ImageOutputStream ios = ImageIO.createImageOutputStream(rgb)) {
writer.setOutput(ios);
writer.write(null, new IIOImage(in, null, null), null);
}
rgb.flush();
in = ImageIO.read(ClassLoader.getSystemResource("crop_aligned.jpg"));
ByteArrayOutputStream bw = new ByteArrayOutputStream();
try (ImageOutputStream ios = ImageIO.createImageOutputStream(bw)) {
writer.setOutput(ios);
writer.write(null, new IIOImage(in, null, null), null);
}
bw.flush();
assertThat(rgb.toByteArray()).isNotEqualTo(bw.toByteArray());
}
示例8: getReader
import com.google.common.collect.Streams; //導入依賴的package包/類
/** Try to obtain a {@link ImageReader} for a given identifier **/
private ImageReader getReader(String identifier) throws ResourceNotFoundException, UnsupportedFormatException, IOException {
if (imageSecurityService != null && !imageSecurityService.isAccessAllowed(identifier)) {
throw new ResourceNotFoundException();
}
Resource res = null;
try {
res = resourceService.get(identifier, ResourcePersistenceType.RESOLVED, MimeType.MIME_IMAGE);
} catch (ResourceIOException e) {
throw new ResourceNotFoundException();
}
ImageInputStream iis = ImageIO.createImageInputStream(resourceService.getInputStream(res));
ImageReader reader = Streams.stream(ImageIO.getImageReaders(iis))
.findFirst()
.orElseThrow(() -> new UnsupportedFormatException());
reader.setInput(iis);
return reader;
}
示例9: processImage
import com.google.common.collect.Streams; //導入依賴的package包/類
@Override
public void processImage(String identifier, ImageApiSelector selector, OutputStream os)
throws InvalidParametersException, UnsupportedOperationException, UnsupportedFormatException, ResourceNotFoundException, IOException {
DecodedImage img;
try {
img = readImage(identifier, selector);
} catch (IllegalArgumentException e) {
throw new InvalidParametersException();
}
BufferedImage outImg = transformImage(img.img, img.targetSize, img.rotation, selector.getRotation().isMirror(), selector.getQuality());
ImageWriter writer = Streams.stream(ImageIO.getImageWriters(new ImageTypeSpecifier(outImg), selector.getFormat().name()))
.findFirst()
.orElseThrow(() -> new UnsupportedFormatException());
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
writer.write(null, new IIOImage(outImg, null, null), null);
writer.dispose();
ios.flush();
}
示例10: getResultSetSchema
import com.google.common.collect.Streams; //導入依賴的package包/類
/**
* Generates ZonedSchema object from given JsonNode.
*
* @param schemaNode JsonNode which contains all the columns, timezone and granularity
*
* @return ResultSetSchema object generated from the JsonNode
*/
private ResultSetSchema getResultSetSchema(JsonNode schemaNode) {
DateTimeZone timezone = generateTimezone(
schemaNode.get(SCHEMA_TIMEZONE).asText(),
DateTimeZone.forID(
SYSTEM_CONFIG.getStringProperty(SYSTEM_CONFIG.getPackageVariableName("timezone"), "UTC")
)
);
//Recreate ResultSetSchema
LinkedHashSet<Column> columns = Stream.concat(
Streams.stream(schemaNode.get(SCHEMA_DIM_COLUMNS))
.map(JsonNode::asText)
.map(this::resolveDimensionName)
.map(DimensionColumn::new),
Streams.stream(() -> schemaNode.get(SCHEMA_METRIC_COLUMNS_TYPE).fields())
.map(entry -> new MetricColumnWithValueType(entry.getKey(), entry.getValue().asText()))
).collect(Collectors.toCollection(LinkedHashSet::new));
return new ResultSetSchema(generateGranularity(schemaNode.get(SCHEMA_GRANULARITY).asText(), timezone), columns);
}
示例11: makeStatusValueList
import com.google.common.collect.Streams; //導入依賴的package包/類
/**
* Creates a string array of status values.
*
* <p>The spec indicates that OK should be listed as "active". We use the "removed" status to
* indicate deleted objects.
*/
private static ImmutableList<String> makeStatusValueList(
ImmutableSet<StatusValue> statusValues, boolean isDeleted) {
Stream<RdapStatus> stream =
statusValues
.stream()
.map(status -> statusToRdapStatusMap.getOrDefault(status, RdapStatus.OBSCURED));
if (isDeleted) {
stream =
Streams.concat(
stream.filter(rdapStatus -> !Objects.equals(rdapStatus, RdapStatus.ACTIVE)),
Stream.of(RdapStatus.REMOVED));
}
return stream
.map(RdapStatus::getDisplayName)
.collect(toImmutableSortedSet(Ordering.natural()))
.asList();
}
示例12: loadAllDiffKeys
import com.google.common.collect.Streams; //導入依賴的package包/類
/**
* Loads all the diff keys, sorted in a transaction-consistent chronological order.
*
* @param lowerCheckpoint exclusive lower bound on keys in this diff, or null if no lower bound
* @param upperCheckpoint inclusive upper bound on keys in this diff
*/
private ImmutableList<Key<CommitLogManifest>> loadAllDiffKeys(
@Nullable final CommitLogCheckpoint lowerCheckpoint,
final CommitLogCheckpoint upperCheckpoint) {
// Fetch the keys (no data) between these checkpoints, and sort by timestamp. This ordering is
// transaction-consistent by virtue of our checkpoint strategy and our customized Ofy; see
// CommitLogCheckpointStrategy for the proof. We break ties by sorting on bucket ID to ensure
// a deterministic order.
return upperCheckpoint
.getBucketTimestamps()
.keySet()
.stream()
.flatMap(
bucketNum ->
Streams.stream(loadDiffKeysFromBucket(lowerCheckpoint, upperCheckpoint, bucketNum)))
.sorted(
comparingLong(Key<CommitLogManifest>::getId)
.thenComparingLong(a -> a.getParent().getId()))
.collect(toImmutableList());
}
示例13: getAllRegistrarNames
import com.google.common.collect.Streams; //導入依賴的package包/類
/**
* Returns the names of all active registrars. Finds registrar accounts with clientIds matching
* the format used for OT&E accounts (regname-1, regname-2, etc.) and returns just the common
* prefixes of those accounts (in this case, regname).
*/
private ImmutableSet<String> getAllRegistrarNames() {
return Streams.stream(Registrar.loadAll())
.map(
registrar -> {
if (!registrar.isLive()) {
return null;
}
String name = registrar.getClientId();
// Look for names of the form "regname-1", "regname-2", etc. and strip the -# suffix.
String replacedName = name.replaceFirst("^(.*)-[1234]$", "$1");
// Check if any replacement happened, and thus whether the name matches the format.
// If it matches, provide the shortened name, and otherwise return null.
return name.equals(replacedName) ? null : replacedName;
})
.filter(Objects::nonNull)
.collect(toImmutableSet());
}
示例14: getOldRegistrar
import com.google.common.collect.Streams; //導入依賴的package包/類
@Nullable
@Override
Registrar getOldRegistrar(final String clientId) {
checkArgument(clientId.length() >= 3, "Client identifier (%s) is too short", clientId);
checkArgument(clientId.length() <= 16, "Client identifier (%s) is too long", clientId);
if (Registrar.Type.REAL.equals(registrarType)) {
checkArgument(
clientId.equals(normalizeClientId(clientId)),
"Client identifier (%s) can only contain lowercase letters, numbers, and hyphens",
clientId);
}
checkState(
!Registrar.loadByClientId(clientId).isPresent(), "Registrar %s already exists", clientId);
List<Registrar> collisions =
Streams.stream(Registrar.loadAll())
.filter(registrar -> normalizeClientId(registrar.getClientId()).equals(clientId))
.collect(toCollection(ArrayList::new));
if (!collisions.isEmpty()) {
throw new IllegalArgumentException(String.format(
"The registrar client identifier %s normalizes identically to existing registrar %s",
clientId,
collisions.get(0).getClientId()));
}
return null;
}
示例15: run
import com.google.common.collect.Streams; //導入依賴的package包/類
@Override
public void run() {
checkArgument( // safety
RegistryEnvironment.get() == RegistryEnvironment.CRASH
|| RegistryEnvironment.get() == RegistryEnvironment.UNITTEST,
"DO NOT RUN ANYWHERE ELSE EXCEPT CRASH OR TESTS.");
// Create a in-memory input, assigning each bucket to its own shard for maximum parallelization,
// with one extra shard for the CommitLogCheckpointRoot.
Input<Key<?>> input =
new InMemoryInput<>(
Lists.partition(
Streams.concat(
Stream.of(CommitLogCheckpointRoot.getKey()),
CommitLogBucket.getAllBucketKeys().stream())
.collect(toImmutableList()),
1));
response.sendJavaScriptRedirect(createJobPath(mrRunner
.setJobName("Delete all commit logs")
.setModuleName("tools")
.runMapreduce(
new KillAllCommitLogsMapper(),
new KillAllEntitiesReducer(),
ImmutableList.of(input))));
}