Java Code Examples for com.google.common.collect.Collections2#transform()

The following examples show how to use com.google.common.collect.Collections2#transform() . 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: BlazeCommandNameTest.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Test
public void userCommandNamesShouldBecomeKnown() {
  Collection<String> knownCommandStrings =
      Collections2.transform(
          BlazeCommandName.knownCommands(),
          new Function<BlazeCommandName, String>() {
            @Nullable
            @Override
            public String apply(BlazeCommandName input) {
              return input.toString();
            }
          });
  assertThat(knownCommandStrings).doesNotContain("user-command");
  BlazeCommandName userCommand = BlazeCommandName.fromString("user-command");
  assertThat(BlazeCommandName.knownCommands()).contains(userCommand);
}
 
Example 2
Source File: TypeProtobufEncoder.java    From tajo with Apache License 2.0 6 votes vote down vote up
@Override
public void visitRecord(Record record) {
  super.visitRecord(record);

  Collection<QualifiedIdentifierProto> field_names =
      Collections2.transform(record.fields(), new Function<Field, QualifiedIdentifierProto>() {
    @Override
    public QualifiedIdentifierProto apply(@Nullable Field field) {
      return field.name().getProto();
    }
  });

  builder
      .addElements(TypeElement.newBuilder()
          .setChildNum(record.size())
          .addAllFieldNames(field_names)
          .setKind(RECORD));
}
 
Example 3
Source File: SchemaRegistryModule.java    From registry with Apache License 2.0 6 votes vote down vote up
private Collection<? extends SchemaProvider> getSchemaProviders() {
    Collection<Map<String, Object>> schemaProviders = (Collection<Map<String, Object>>) config.get(SCHEMA_PROVIDERS);
    if (schemaProviders == null || schemaProviders.isEmpty()) {
        throw new IllegalArgumentException("No [" + SCHEMA_PROVIDERS + "] property is configured in schema registry configuration file.");
    }

    return Collections2.transform(schemaProviders, new Function<Map<String, Object>, SchemaProvider>() {
        @Nullable
        @Override
        public SchemaProvider apply(@Nullable Map<String, Object> schemaProviderConfig) {
            String className = (String) schemaProviderConfig.get("providerClass");
            if (className == null || className.isEmpty()) {
                throw new IllegalArgumentException("Schema provider class name must be non empty, Invalid provider class name [" + className + "]");
            }
            try {
                SchemaProvider schemaProvider = (SchemaProvider) Class.forName(className, true, Thread.currentThread().getContextClassLoader()).newInstance();
                schemaProvider.init(schemaProviderConfig);
                return schemaProvider;
            } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                LOG.error("Error encountered while loading SchemaProvider [{}] ", className, e);
                throw new IllegalArgumentException(e);
            }
        }
    });
}
 
Example 4
Source File: CheckProjectInfo.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
public Collection<String> getMetamodelImports() {
  return Collections2.transform(grammarHelper.getMetamodelPackages(), new Function<String, String>() {
    public String apply(final String importPackageName) {
      return importPackageName + ".*";
    }
  });
}
 
Example 5
Source File: VertexGroupCommitStartedEvent.java    From tez with Apache License 2.0 5 votes vote down vote up
public void fromProto(VertexGroupCommitStartedProto proto) {
  this.dagID = TezDAGID.fromString(proto.getDagId());
  this.vertexGroupName = proto.getVertexGroupName();
  this.vertexIds = Collections2.transform(proto.getVertexIdsList(), new Function<String, TezVertexID>() {
    @Override
    public TezVertexID apply(String input) {
      return TezVertexID.fromString(input);
    }
  });
}
 
Example 6
Source File: AbstractTemplateProcessor.java    From ameba with MIT License 5 votes vote down vote up
private Collection<String> getTemplatePaths(String name, String basePath) {
    String lowerName = name.toLowerCase();
    final String templatePath = basePath.endsWith("/") ? basePath + name.substring(1) : basePath + name;

    // Check whether the given name ends with supported suffix.
    for (final String extension : supportedExtensions) {
        if (lowerName.endsWith(extension)) {
            return Collections.singleton(templatePath);
        }
    }

    return Collections2.transform(this.supportedExtensions, input -> templatePath + input);
}
 
Example 7
Source File: DatadogExpansionFilteredReporterFactory.java    From emodb with Apache License 2.0 5 votes vote down vote up
private Collection<DatadogReporter.Expansion> asExpansions(Collection<String> strings) {
    return Collections2.transform(strings, new Function<String, DatadogReporter.Expansion>() {
        @Override
        public DatadogReporter.Expansion apply(String string) {
            for (DatadogReporter.Expansion expansion : DatadogReporter.Expansion.values()) {
                if (expansion.toString().equals(string)) {
                    return expansion;
                }
            }
            throw new IllegalArgumentException("Unknown expansion: " + string);
        }
    });
}
 
Example 8
Source File: ContentHandlerTestBase.java    From vespa with Apache License 2.0 5 votes vote down vote up
private String generateResultArray(String... files) {
    Collection<String> output = Collections2.transform(Arrays.asList(files), input -> "\"" + baseUrl + input + "\"");
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    sb.append(Joiner.on(",").join(output));
    sb.append("]");
    return sb.toString();
}
 
Example 9
Source File: TestLinkedMetadataManager.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTablespaces() throws Exception {
  Collection<String> names = Collections2.transform(catalog.getAllTablespaces(),
      new Function<CatalogProtos.TablespaceProto, String>() {
    @Override
    public String apply(@Nullable CatalogProtos.TablespaceProto input) {
      return input.getSpaceName();
    }
  });

  assertEquals(Sets.newHashSet("space1", "space2", "default"), Sets.newHashSet(names));
}
 
Example 10
Source File: AbstractTask.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Collection<ContextAwareTaskAction> transformToContextAwareTaskActions(Collection<Object> c) {
    return Collections2.transform(c, new Function<Object, ContextAwareTaskAction>() {
        public ContextAwareTaskAction apply(@Nullable Object input) {
            return wrap((Action<? super Task>) input);
        }
    });
}
 
Example 11
Source File: QueueScanWorkflow.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public void releaseCompleteScanRanges(Collection<ScanRangeComplete> completions) {
    if (completions.isEmpty()) {
        return;
    }

    Collection<String> messageIds = Collections2.transform(completions, new Function<ScanRangeComplete, String>() {
        @Override
        public String apply(ScanRangeComplete completion) {
            return ((QueueScanRangeComplete) completion).getMessageId();
        }
    });

    _queueService.acknowledge(_completeScanRangeQueue, messageIds);
}
 
Example 12
Source File: ParserToSalTest.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private static Collection<byte[]> fixMessages(final Collection<byte[]> bgpMessages) {
    return Collections2.transform(bgpMessages, input -> {
        final byte[] ret = new byte[input.length + 1];
        // ff
        ret[0] = -1;
        System.arraycopy(input, 0, ret, 1, input.length);
        return ret;
    });
}
 
Example 13
Source File: ObservationViewActivity.java    From mage-android with Apache License 2.0 5 votes vote down vote up
private void onFavoritesClick(Collection<ObservationFavorite> favorites) {
	Collection<String> userIds = Collections2.transform(favorites, favorite -> favorite.getUserId());

	Intent intent = new Intent(this, PeopleActivity.class);
	intent.putStringArrayListExtra(PeopleActivity.USER_REMOTE_IDS, new ArrayList<>(userIds));
	startActivity(intent);
}
 
Example 14
Source File: ReceiverClusterManager.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Promote a segment from realtime part into historical part.
 */
void promoteNewSegment(CubingJob cubingJob, CubeInstance cubeInstance, CubeSegment cubeSegment) throws IOException {
    logger.debug("Try transfer segment's {} state to ready.", cubeSegment.getName());
    long sourceCount = cubingJob.findSourceRecordCount();
    long sourceSizeBytes = cubingJob.findSourceSizeBytes();
    long cubeSizeBytes = cubingJob.findCubeSizeBytes();
    Map<Integer, String> sourceCheckpoint = getCoordinator().getStreamMetadataStore()
            .getSourceCheckpoint(cubeInstance.getName(), cubeSegment.getName());

    ISourcePositionHandler positionOperator = StreamingSourceFactory.getStreamingSource(cubeInstance)
            .getSourcePositionHandler();
    Collection<ISourcePosition> sourcePositions = Collections2.transform(sourceCheckpoint.values(),
            new Function<String, ISourcePosition>() {
                @Nullable
                @Override
                public ISourcePosition apply(@Nullable String input) {
                    return positionOperator.parsePosition(input);
                }
            });
    ISourcePosition sourcePosition = positionOperator.mergePositions(sourcePositions,
            ISourcePositionHandler.MergeStrategy.KEEP_SMALL);
    cubeSegment.setLastBuildJobID(cubingJob.getId());
    cubeSegment.setLastBuildTime(System.currentTimeMillis());
    cubeSegment.setSizeKB(cubeSizeBytes / 1024);
    cubeSegment.setInputRecords(sourceCount);
    cubeSegment.setInputRecordsSize(sourceSizeBytes);
    cubeSegment.setStreamSourceCheckpoint(positionOperator.serializePosition(sourcePosition));
    getCoordinator().getCubeManager().promoteNewlyBuiltSegments(cubeInstance, cubeSegment);
}
 
Example 15
Source File: Coordinator.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private void promoteNewSegment(CubingJob cubingJob, CubeInstance cubeInstance, CubeSegment cubeSegment)
        throws IOException {
    long sourceCount = cubingJob.findSourceRecordCount();
    long sourceSizeBytes = cubingJob.findSourceSizeBytes();
    long cubeSizeBytes = cubingJob.findCubeSizeBytes();
    Map<Integer, String> sourceCheckpoint = streamMetadataStore.getSourceCheckpoint(cubeInstance.getName(),
            cubeSegment.getName());

    ISourcePositionHandler positionOperator = StreamingSourceFactory.getStreamingSource(cubeInstance)
            .getSourcePositionHandler();
    Collection<ISourcePosition> sourcePositions = Collections2.transform(sourceCheckpoint.values(),
            new Function<String, ISourcePosition>() {
                @Nullable
                @Override
                public ISourcePosition apply(@Nullable String input) {
                    return positionOperator.parsePosition(input);
                }
            });
    ISourcePosition sourcePosition = positionOperator.mergePositions(sourcePositions, MergeStrategy.KEEP_SMALL);
    cubeSegment.setLastBuildJobID(cubingJob.getId());
    cubeSegment.setLastBuildTime(System.currentTimeMillis());
    cubeSegment.setSizeKB(cubeSizeBytes / 1024);
    cubeSegment.setInputRecords(sourceCount);
    cubeSegment.setInputRecordsSize(sourceSizeBytes);
    cubeSegment.setStreamSourceCheckpoint(positionOperator.serializePosition(sourcePosition));
    getCubeManager().promoteNewlyBuiltSegments(cubeInstance, cubeSegment);
}
 
Example 16
Source File: BlockedIpInterceptor.java    From mamute with Apache License 2.0 5 votes vote down vote up
@Override
public void intercept(InterceptorStack interceptorStack, ControllerMethod controllerMethod, Object o) throws InterceptionException {
	List<BlockedIp> ips = blockedIps.list();
	Collection<IpMatcher> matchers = Collections2.transform(ips, extractIp);
	boolean isBlocked = matches(matchers);
	if (isBlocked) {
		result.use(http()).sendError(503);
		return;
	}
	interceptorStack.next(controllerMethod, o);
}
 
Example 17
Source File: KeyValuesFinderFactory.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Override
public List<KeyValue> getKeyValues() {
    Collection<KeyValue> kvs = Collections2.transform(map.entrySet(), new Function<Map.Entry<String, String>, KeyValue>() {
        @Override
        public KeyValue apply(Map.Entry<String, String> input) {
            return new ConcreteKeyValue(input);
        }
    });
    return ImmutableList.copyOf(kvs);
}
 
Example 18
Source File: SchedulerDriverService.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
public void acceptOffers(
    Protos.OfferID offerId,
    Collection<Protos.Offer.Operation> operations,
    Protos.Filters filter) {
  ensureRunning();

  OfferID convertedOfferId = ProtosConversion.convert(offerId);
  Collection<Operation> convertedOperations =
      Collections2.transform(operations, ProtosConversion::convert);
  Filters convertedFilter = ProtosConversion.convert(filter);

  Futures.getUnchecked(driverFuture)
      .acceptOffers(ImmutableList.of(convertedOfferId), convertedOperations, convertedFilter);
}
 
Example 19
Source File: QueueScanWorkflow.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public void renewScanRangeTasks(Collection<ScanRangeTask> tasks, Duration ttl) {
    if (tasks.isEmpty()) {
        return;
    }

    Collection<String> messageIds = Collections2.transform(tasks, new Function<ScanRangeTask, String>() {
        @Override
        public String apply(ScanRangeTask task) {
            return ((QueueScanRangeTask) task).getMessageId();
        }
    });

    _queueService.renew(_pendingScanRangeQueue, messageIds, ttl);
}
 
Example 20
Source File: ScopedRoleDialog.java    From core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public Widget asWidget() {
    TextBoxItem name = new TextBoxItem("name", "Name", true);
    ComboBoxItem baseRole = new ComboBoxItem("baseRole", "Base Role");
    baseRole.setDefaultToFirstOption(true);
    Collection<String> roleNames = Collections2.transform(StandardRole.values(), StandardRole::getId);
    baseRole.setValueMap(roleNames);

    ComboBoxItem type = new ComboBoxItem("type", "Type");
    type.setDefaultToFirstOption(true);
    type.setValueMap(new String[]{"Host", "Server Group"});

    ListItem scope = new ListItem("scope", "Scope");
    scope.setRequired(true);
    CheckBoxItem includeAll = new CheckBoxItem("includeAll", "Include All");

    Form<RoleBean> form = new Form<>(RoleBean.class);
    if (scoped) {
        form.setFields(name, baseRole, type, scope, includeAll);
    } else {
        form.setFields(name, includeAll);
    }
    if (this.existingRole != null) {
        name.setEnabled(false);
        type.setEnabled(false);
        form.edit(modelToBean(existingRole));
    }

    form.addFormValidator((formItems, outcome) -> {
        if (existingRole == null && duplicateNameAndType(beanToModel(form.getUpdatedEntity()))) {
            outcome.addError("name");
            name.setErrMessage("Role already exists");
            name.setErroneous(true);
        }
    });

    VerticalPanel layout = new VerticalPanel();
    layout.setStyleName("window-content");
    layout.add(new HelpPanel().asWidget());
    layout.add(form.asWidget());

    DialogueOptions options = new DialogueOptions(
            event -> {
                FormValidation validation = form.validate();
                if (!validation.hasErrors()) {
                    if (existingRole == null) {
                        circuit.dispatch(new AddScopedRole(beanToModel(form.getUpdatedEntity())));
                    } else if (existingRole.isScoped()) {
                        circuit.dispatch(new ModifyScopedRole(beanToModel(form.getUpdatedEntity())));
                    } else {
                        circuit.dispatch(new ModifyStandardRole(beanToModel(form.getUpdatedEntity())));
                    }
                    presenter.closeWindow();
                }
            },
            event -> presenter.closeWindow()
    );

    return new WindowContentBuilder(layout, options).build();
}