org.apache.commons.collections4.IterableUtils Java Examples

The following examples show how to use org.apache.commons.collections4.IterableUtils. 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: FileTypes.java    From archiva with Apache License 2.0 6 votes vote down vote up
/**
 * Get the list of patterns for a specified filetype.
 * You will always get a list.  In this order.
 * <ul>
 * <li>The Configured List</li>
 * <li>The Default List</li>
 * <li>A single item list of <code>&quot;**&#47;*&quot;</code></li>
 * </ul>
 *
 * @param id the id to lookup.
 * @return the list of patterns.
 */
public List<String> getFileTypePatterns( String id )
{
    Configuration config = archivaConfiguration.getConfiguration();
    Predicate selectedFiletype = new FiletypeSelectionPredicate( id );
    RepositoryScanningConfiguration repositoryScanningConfiguration = config.getRepositoryScanning();
    if ( repositoryScanningConfiguration != null )
    {
        FileType filetype =
            IterableUtils.find( config.getRepositoryScanning().getFileTypes(), selectedFiletype );

        if ( ( filetype != null ) && CollectionUtils.isNotEmpty( filetype.getPatterns() ) )
        {
            return filetype.getPatterns();
        }
    }
    List<String> defaultPatterns = defaultTypeMap.get( id );

    if ( CollectionUtils.isEmpty( defaultPatterns ) )
    {
        return Collections.singletonList( "**/*" );
    }

    return defaultPatterns;
}
 
Example #2
Source File: PipelineTriggerServiceIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldScheduleAPipelineWithTheProvidedEncryptedEnvironmentVariable() throws CryptoException {
    pipelineConfig.addEnvironmentVariable(new EnvironmentVariableConfig(new GoCipher(), "SECURE_VAR1", "SECURE_VAL", true));
    String digest = entityHashingService.hashForEntity(pipelineConfigService.getPipelineConfig(pipelineConfig.name().toString()), group);
    pipelineConfigService.updatePipelineConfig(admin, pipelineConfig, group, digest, new HttpLocalizedOperationResult());
    CaseInsensitiveString pipelineNameCaseInsensitive = new CaseInsensitiveString(this.pipelineName);
    assertThat(triggerMonitor.isAlreadyTriggered(pipelineNameCaseInsensitive), is(false));
    PipelineScheduleOptions pipelineScheduleOptions = new PipelineScheduleOptions();
    String overriddenEncryptedValue = new GoCipher().encrypt("overridden_value");
    pipelineScheduleOptions.getAllEnvironmentVariables().add(new EnvironmentVariableConfig(new GoCipher(), "SECURE_VAR1", overriddenEncryptedValue));

    pipelineTriggerService.schedule(this.pipelineName, pipelineScheduleOptions, admin, this.result);

    assertThat(this.result.isSuccess(), is(true));
    materialUpdateStatusNotifier.onMessage(new MaterialUpdateSuccessfulMessage(svnMaterial, 1));

    BuildCause buildCause = pipelineScheduleQueue.toBeScheduled().get(pipelineNameCaseInsensitive);
    assertNotNull(buildCause);
    EnvironmentVariable secureVariable = IterableUtils.find(buildCause.getVariables(), variable -> variable.getName().equals("SECURE_VAR1"));
    assertThat(secureVariable.getValue(), is("overridden_value"));
    assertThat(secureVariable.isSecure(), is(true));
}
 
Example #3
Source File: CssUtils.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private static boolean stripMediaType(CSSRuleAdapter rule, String useType) {
    if (rule.hasMediaQueries()) {
        List<CSSMediaQuery> queries = rule.getAllMediaQueries().stream()
                .map(q -> stripMediaType(q, useType))
                .filter(q -> !isAlwaysNegative(q))
                .collect(Collectors.toList());

        if (queries.isEmpty()) {
            return true;
        } else {
            rule.removeAllMediaQueries();

            if (IterableUtils.matchesAny(queries, CssUtils::isAlwaysPositive)) {
                rule.addMediaQuery(new CSSMediaQuery("all"));
            } else {
                queries.forEach(rule::addMediaQuery);
            }
        }
    }

    return false;
}
 
Example #4
Source File: FcgProvider.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Iterable<FcgVertex> getVerticesAtOrGreaterThan(FcgLevel level) {
	List<Iterable<FcgVertex>> result = new ArrayList<>();
	FunctionCallGraph graph = graphData.getGraph();
	FcgLevel greatestLevel = graph.getLargestLevel(level.getDirection());
	FcgLevel currentLevel = level;
	while (currentLevel.getRow() <= greatestLevel.getRow()) {
		Iterable<FcgVertex> vertices = getVerticesByLevel(currentLevel);
		result.add(vertices);
		currentLevel = currentLevel.child();
	}

	// hand out from greatest to least so that we can close the extremities first 
	Collections.reverse(result);

	@SuppressWarnings("unchecked")
	Iterable<FcgVertex>[] array = result.toArray(new Iterable[result.size()]);
	return IterableUtils.chainedIterable(array);
}
 
Example #5
Source File: DefaultProxyConnectorAdmin.java    From archiva with Apache License 2.0 6 votes vote down vote up
private ProxyConnectorConfiguration findProxyConnector( String sourceId, String targetId,
                                                        Configuration configuration )
{
    if ( StringUtils.isBlank( sourceId ) )
    {
        return null;
    }

    if ( StringUtils.isBlank( targetId ) )
    {
        return null;
    }

    ProxyConnectorSelectionPredicate selectedProxy = new ProxyConnectorSelectionPredicate( sourceId, targetId );
    return IterableUtils.find( configuration.getProxyConnectors(), selectedProxy );
}
 
Example #6
Source File: ArticleServiceImpl.java    From incubator-wikift with Apache License 2.0 6 votes vote down vote up
@Override
public CommonResult getAllArticleBySpace(String code, Pageable pageable) {
    // 校验传递参数
    CommonResult validate = ValidateUtils.validateEmpty(code, MessageEnums.PARAMS_NOT_NULL);
    if (validate.getCode() > 0) {
        return validate;
    }
    // 校验数据是否存在
    SpaceEntity space = this.spaceService.getSpaceInfoByCode(code);
    validate = ValidateUtils.validateEmpty(space, MessageEnums.SPACE_NOT_FOUND);
    if (validate.getCode() > 0) {
        return validate;
    }
    // 获取所有数据集合, 封装树形数据
    List<ArticleEntity> entities = IterableUtils.toList(this.repository.findAllBySpace(space));
    return CommonResult.success(this.getChildren(-1L, entities));
}
 
Example #7
Source File: JmxConnectionHelper.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected static ObjectName getObjectName(final MBeanServerConnection connection, final String remoteContext,
                                          final Class objectClass) throws IOException {
    Set<ObjectName> names = connection.queryNames(null, null);
    return IterableUtils.find(names, o -> {
        if (!Objects.equals(remoteContext, o.getDomain())) {
            return false;
        }

        MBeanInfo info;
        try {
            info = connection.getMBeanInfo(o);
        } catch (Exception e) {
            throw new JmxControlException(e);
        }
        return Objects.equals(objectClass.getName(), info.getClassName());
    });
}
 
Example #8
Source File: AttributeDaoHelperTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateBusinessObjectDataAttributesAttributeValueUpdated()
{
    // Create a business object data attribute entity.
    BusinessObjectDataAttributeEntity businessObjectDataAttributeEntity = new BusinessObjectDataAttributeEntity();
    businessObjectDataAttributeEntity.setName(ATTRIBUTE_NAME);
    businessObjectDataAttributeEntity.setValue(ATTRIBUTE_VALUE);

    // Create a business object data entity that contains one attribute entity.
    BusinessObjectDataEntity businessObjectDataEntity = new BusinessObjectDataEntity();
    List<BusinessObjectDataAttributeEntity> businessObjectDataAttributeEntities = new ArrayList<>();
    businessObjectDataEntity.setAttributes(businessObjectDataAttributeEntities);
    businessObjectDataAttributeEntities.add(businessObjectDataAttributeEntity);

    // Call the method under test.
    attributeDaoHelper.updateBusinessObjectDataAttributes(businessObjectDataEntity, Arrays.asList(new Attribute(ATTRIBUTE_NAME, ATTRIBUTE_VALUE_2)));

    // Verify the external calls.
    verifyNoMoreInteractionsHelper();

    // Validate the results.
    assertEquals(1, CollectionUtils.size(businessObjectDataEntity.getAttributes()));
    BusinessObjectDataAttributeEntity result = IterableUtils.get(businessObjectDataEntity.getAttributes(), 0);
    assertEquals(ATTRIBUTE_NAME, result.getName());
    assertEquals(ATTRIBUTE_VALUE_2, result.getValue());
}
 
Example #9
Source File: ChannelGraphNavigationTest.java    From WiFiAnalyzer with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testUpdateWithGHZ5AndUS() {
    // setup
    int colorSelected = ContextCompat.getColor(mainActivity, R.color.selected);
    int colorNotSelected = ContextCompat.getColor(mainActivity, R.color.background);
    Pair<WiFiChannel, WiFiChannel> selectedKey = WiFiBand.GHZ5.getWiFiChannels().getWiFiChannelPairs().get(0);
    when(configuration.getWiFiChannelPair()).thenReturn(selectedKey);
    when(settings.getCountryCode()).thenReturn(Locale.US.getCountry());
    when(settings.getWiFiBand()).thenReturn(WiFiBand.GHZ5);
    when(settings.getSortBy()).thenReturn(SortBy.CHANNEL);
    // execute
    fixture.update(WiFiData.EMPTY);
    // validate
    verify(layout).setVisibility(View.VISIBLE);
    IterableUtils.forEach(views.keySet(), new PairUpdateClosure(selectedKey, colorSelected, colorNotSelected));
    IterableUtils.forEach(ChannelGraphNavigation.ids.values(), new IntegerUpdateClosure());
    verify(settings).getCountryCode();
    verify(settings, times(2)).getWiFiBand();
    verify(settings).getSortBy();
    verify(configuration).getWiFiChannelPair();
}
 
Example #10
Source File: DefaultArchivaAdministrationService.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Override
public List<AdminRepositoryConsumer> getKnownContentAdminRepositoryConsumers()
    throws ArchivaRestServiceException
{
    try
    {
        AddAdminRepoConsumerClosure addAdminRepoConsumer =
            new AddAdminRepoConsumerClosure( archivaAdministration.getKnownContentConsumers() );
        IterableUtils.forEach( repoConsumerUtil.getAvailableKnownConsumers(), addAdminRepoConsumer );
        List<AdminRepositoryConsumer> knownContentConsumers = addAdminRepoConsumer.getList();
        knownContentConsumers.sort( AdminRepositoryConsumerComparator.getInstance( ) );
        return knownContentConsumers;
    }
    catch ( RepositoryAdminException e )
    {
        throw new ArchivaRestServiceException( e.getMessage(), e );
    }
}
 
Example #11
Source File: ProctorController.java    From proctor with Apache License 2.0 6 votes vote down vote up
private static CompatibleSpecificationResult fromTests(
        final Environment environment,
        final AppVersion version,
        final TestMatrixArtifact artifact,
        final Map<String, Collection<TestSpecification>> requiredTests,
        final Set<String> dynamicTests,
        final BiFunction<String, ProctorLoadResult, String> errorMessageFunction
) {
    final String matrixSource = environment.getName() + " r" + artifact.getAudit().getVersion();
    final Map<String, TestSpecification> specMap = Maps.transformValues(
            requiredTests,
            // choosing arbitrary specification when it contains more than one.
            // This is because of limitation of verify method.
            // FIXME: This will give false negative if not all of them is incompatible
            IterableUtils::first
    );
    final ProctorLoadResult plr = ProctorUtils.verify(
            artifact, matrixSource, specMap, dynamicTests
    );
    final boolean compatible = !plr.hasInvalidTests();
    final String error = (compatible ? "" : errorMessageFunction.apply(matrixSource, plr));
    return new CompatibleSpecificationResult(version, compatible, error, dynamicTests);
}
 
Example #12
Source File: DefaultPluginRegistry.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public String pluginIDFor(String bundleSymbolicName, String extensionClassCannonicalName) {
    final GoPluginBundleDescriptor bundleDescriptor = getBundleDescriptor(bundleSymbolicName);

    final GoPluginDescriptor firstPluginDescriptor = bundleDescriptor.descriptors().get(0);
    if (firstPluginDescriptor.extensionClasses().isEmpty()) {
        return firstPluginDescriptor.id();
    }

    final GoPluginDescriptor descriptorWithExtension = IterableUtils.find(bundleDescriptor.descriptors(),
            pluginDescriptor -> pluginDescriptor.extensionClasses().contains(extensionClassCannonicalName));

    return descriptorWithExtension == null ? null : descriptorWithExtension.id();
}
 
Example #13
Source File: TimeGraphCacheTest.java    From WiFiAnalyzer with GNU General Public License v3.0 5 votes vote down vote up
private List<WiFiDetail> withWiFiDetails() {
    List<WiFiDetail> results = new ArrayList<>();
    for (int i = 0; i < 4; i++) {
        WiFiDetail wiFiDetail = withWiFiDetail("SSID" + i);
        results.add(wiFiDetail);
    }
    IterableUtils.forEach(results, new AddClosure());
    for (int i = 0; i < GraphConstants.MAX_NOTSEEN_COUNT; i++) {
        fixture.add(results.get(0));
    }
    return results;
}
 
Example #14
Source File: ChannelGraphNavigation.java    From WiFiAnalyzer with GNU General Public License v3.0 5 votes vote down vote up
private void updateButtons(@NonNull WiFiData wiFiData, Collection<Pair<WiFiChannel, WiFiChannel>> visible) {
    if (visible.size() > 1) {
        MainContext mainContext = MainContext.INSTANCE;
        Configuration configuration = mainContext.getConfiguration();
        Settings settings = mainContext.getSettings();
        Predicate<WiFiDetail> predicate = FilterPredicate.makeOtherPredicate(settings);
        Pair<WiFiChannel, WiFiChannel> selectedWiFiChannelPair = configuration.getWiFiChannelPair();
        List<WiFiDetail> wiFiDetails = wiFiData.getWiFiDetails(predicate, settings.getSortBy());
        IterableUtils.forEach(ids.keySet(), new ButtonClosure(visible, selectedWiFiChannelPair, wiFiDetails));
    }
}
 
Example #15
Source File: ChannelGraphNavigation.java    From WiFiAnalyzer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(Pair<WiFiChannel, WiFiChannel> input) {
    Button button = view.findViewById(ids.get(input));
    if (visible.contains(input)) {
        button.setVisibility(View.VISIBLE);
        setSelected(button, input.equals(selectedWiFiChannelPair));
        setActivity(button, input, IterableUtils.matchesAny(wiFiDetails, new InRangePredicate(input)));
    } else {
        button.setVisibility(View.GONE);
        setSelected(button, false);
    }
}
 
Example #16
Source File: WiFiChannels.java    From WiFiAnalyzer with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
public WiFiChannel getWiFiChannelByFrequency(int frequency) {
    Pair<WiFiChannel, WiFiChannel> found = null;
    if (isInRange(frequency)) {
        found = IterableUtils.find(wiFiChannelPairs, new FrequencyPredicate(frequency));
    }
    return found == null ? WiFiChannel.UNKNOWN : getWiFiChannel(frequency, found);
}
 
Example #17
Source File: RepositoryScannerInstance.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    final Path relativeFile = basePath.relativize( file );
    if (excludeMatcher.stream().noneMatch(m -> m.matches(relativeFile)) && includeMatcher.stream().allMatch(m -> m.matches(relativeFile))) {
        log.debug( "Walk Step: {}, {}", file );

        stats.increaseFileCount();

        // consume files regardless - the predicate will check the timestamp
        Path repoPath = PathUtil.getPathFromUri( repository.getLocation() );
        BaseFile basefile = new BaseFile( repoPath.toString(), file.toFile() );

        // Timestamp finished points to the last successful scan, not this current one.
        if ( Files.getLastModifiedTime(file).toMillis() >= changesSince )
        {
            stats.increaseNewFileCount();
        }

        consumerProcessFile.setBasefile( basefile );
        consumerWantsFile.setBasefile( basefile );

        Closure<RepositoryContentConsumer> processIfWanted = IfClosure.ifClosure( consumerWantsFile, consumerProcessFile );
        IterableUtils.forEach( this.knownConsumers, processIfWanted );

        if ( consumerWantsFile.getWantedFileCount() <= 0 )
        {
            // Nothing known processed this file.  It is invalid!
            IterableUtils.forEach( this.invalidConsumers, consumerProcessFile );
        }

    }
    return FileVisitResult.CONTINUE;
}
 
Example #18
Source File: StrengthAdapterTest.java    From WiFiAnalyzer with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testRemovingAllWillNotRemoveLast() {
    // setup
    Set<Strength> values = EnumUtils.values(Strength.class);
    // execute
    IterableUtils.forEach(values, new ToggleClosure());
    // validate
    IterableUtils.forEachButLast(values, new RemovedClosure());
    assertTrue(fixture.contains(IterableUtils.get(values, values.size() - 1)));
}
 
Example #19
Source File: Cache.java    From WiFiAnalyzer with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
private List<ScanResult> combineCache() {
    List<ScanResult> scanResults = new ArrayList<>();
    IterableUtils.forEach(cachedScanResults, new CacheClosure(scanResults));
    Collections.sort(scanResults, new ScanResultComparator());
    return scanResults;
}
 
Example #20
Source File: WiFiChannelsGHZ5.java    From WiFiAnalyzer with GNU General Public License v3.0 5 votes vote down vote up
@Override
@NonNull
public Pair<WiFiChannel, WiFiChannel> getWiFiChannelPairFirst(String countryCode) {
    Pair<WiFiChannel, WiFiChannel> found = null;
    if (StringUtils.isNotBlank(countryCode)) {
        found = IterableUtils.find(getWiFiChannelPairs(), new WiFiChannelPredicate(countryCode));
    }
    return found == null ? SET1 : found;
}
 
Example #21
Source File: DefaultVisualGraph.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all edges shared between the two given vertices
 * 
 * @param start the start vertex
 * @param end the end vertex
 * @return the edges
 */
public Iterable<E> getEdges(V start, V end) {

	Collection<E> outs = nonNull(getOutEdges(start));
	Collection<E> ins = nonNull(getInEdges(end));
	Set<E> unique = new HashSet<>();
	unique.addAll(outs);
	unique.addAll(ins);

	Iterable<E> filtered = IterableUtils.filteredIterable(unique, e -> {
		return e.getStart().equals(start) && e.getEnd().equals(end);
	});
	return filtered;
}
 
Example #22
Source File: VerifyAllEqualListElements.java    From tutorials with MIT License 5 votes vote down vote up
public boolean verifyAllEqualUsingApacheCommon(List<String> list) {
    return IterableUtils.matchesAll(list, new org.apache.commons.collections4.Predicate<String>() {
        public boolean evaluate(String s) {
            return s.equals(list.get(0));
        }
    });
}
 
Example #23
Source File: UserNamespaceAuthorizationHelperTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildNamespaceAuthorizationsAssertWildcardQueryExecuted()
{
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    String userId = "userId";
    applicationUser.setUserId(userId);

    when(configurationHelper.getBooleanProperty(any())).thenReturn(true);

    List<UserNamespaceAuthorizationEntity> wildcardEntities = new ArrayList<>();
    UserNamespaceAuthorizationEntity wildcardEntity = new UserNamespaceAuthorizationEntity();
    wildcardEntity.setUserId("wildcardEntityUserId");
    NamespaceEntity namespaceEntity = new NamespaceEntity();
    namespaceEntity.setCode("namespace");
    wildcardEntity.setNamespace(namespaceEntity);
    wildcardEntities.add(wildcardEntity);
    when(userNamespaceAuthorizationDao.getUserNamespaceAuthorizationsByUserIdStartsWith(any())).thenReturn(wildcardEntities);

    when(wildcardHelper.matches(any(), any())).thenReturn(true);

    userNamespaceAuthorizationHelper.buildNamespaceAuthorizations(applicationUser);

    assertEquals(1, applicationUser.getNamespaceAuthorizations().size());
    NamespaceAuthorization namespaceAuthorization = IterableUtils.get(applicationUser.getNamespaceAuthorizations(), 0);
    assertEquals(namespaceEntity.getCode(), namespaceAuthorization.getNamespace());

    verify(userNamespaceAuthorizationDao).getUserNamespaceAuthorizationsByUserId(eq(userId));
    verify(userNamespaceAuthorizationDao).getUserNamespaceAuthorizationsByUserIdStartsWith(eq(WildcardHelper.WILDCARD_TOKEN));
    verify(wildcardHelper).matches(eq(userId.toUpperCase()), eq(wildcardEntity.getUserId().toUpperCase()));
    verifyNoMoreInteractions(userNamespaceAuthorizationDao, wildcardHelper);
}
 
Example #24
Source File: UserNamespaceAuthorizationHelperTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildNamespaceAuthorizationsAssertAuthLookupByUserId()
{
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    String userId = "userId";
    applicationUser.setUserId(userId);

    when(configurationHelper.getBooleanProperty(any())).thenReturn(true);

    List<UserNamespaceAuthorizationEntity> userNamespaceAuthorizationEntities = new ArrayList<>();
    UserNamespaceAuthorizationEntity userNamespaceAuthorizationEntity = new UserNamespaceAuthorizationEntity();
    userNamespaceAuthorizationEntity.setUserId("userNamespaceAuthorizationEntityUserId");
    NamespaceEntity namespaceEntity = new NamespaceEntity();
    namespaceEntity.setCode("namespace");
    userNamespaceAuthorizationEntity.setNamespace(namespaceEntity);
    userNamespaceAuthorizationEntities.add(userNamespaceAuthorizationEntity);
    when(userNamespaceAuthorizationDao.getUserNamespaceAuthorizationsByUserId(any())).thenReturn(userNamespaceAuthorizationEntities);

    userNamespaceAuthorizationHelper.buildNamespaceAuthorizations(applicationUser);

    assertEquals(1, applicationUser.getNamespaceAuthorizations().size());
    NamespaceAuthorization namespaceAuthorization = IterableUtils.get(applicationUser.getNamespaceAuthorizations(), 0);
    assertEquals(namespaceEntity.getCode(), namespaceAuthorization.getNamespace());

    verify(userNamespaceAuthorizationDao).getUserNamespaceAuthorizationsByUserId(eq(userId));
    verify(userNamespaceAuthorizationDao).getUserNamespaceAuthorizationsByUserIdStartsWith(eq(WildcardHelper.WILDCARD_TOKEN));
    verifyNoMoreInteractions(userNamespaceAuthorizationDao, wildcardHelper);
}
 
Example #25
Source File: RepositoryScannerInstance.java    From archiva with Apache License 2.0 5 votes vote down vote up
public RepositoryScannerInstance( ManagedRepository repository,
                                  List<KnownRepositoryContentConsumer> knownConsumerList,
                                  List<InvalidRepositoryContentConsumer> invalidConsumerList )
{
    this.repository = repository;
    this.knownConsumers = knownConsumerList;
    this.invalidConsumers = invalidConsumerList;

    addFileNameIncludePattern("**/*");

    consumerTimings = new HashMap<>();
    consumerCounts = new HashMap<>();

    this.consumerProcessFile = new ConsumerProcessFileClosure();
    consumerProcessFile.setExecuteOnEntireRepo( true );
    consumerProcessFile.setConsumerTimings( consumerTimings );
    consumerProcessFile.setConsumerCounts( consumerCounts );

    this.consumerWantsFile = new ConsumerWantsFilePredicate( repository );

    stats = new RepositoryScanStatistics();
    stats.setRepositoryId( repository.getId() );

    Closure<RepositoryContentConsumer> triggerBeginScan =
        new TriggerBeginScanClosure( repository, new Date( System.currentTimeMillis() ), true );

    IterableUtils.forEach( knownConsumerList, triggerBeginScan );
    IterableUtils.forEach( invalidConsumerList, triggerBeginScan );

    if ( SystemUtils.IS_OS_WINDOWS )
    {
        consumerWantsFile.setCaseSensitive( false );
    }
}
 
Example #26
Source File: UploadDownloadServiceTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitiateDownloadSingleMultipleStorageFilesExist()
{
    // Create the upload data.
    UploadSingleInitiationResponse uploadSingleInitiationResponse =
        uploadDownloadServiceTestHelper.createUploadedFileData(BusinessObjectDataStatusEntity.VALID);

    // Get the target business object data entity.
    BusinessObjectDataEntity targetBusinessObjectDataEntity = businessObjectDataDao
        .getBusinessObjectDataByAltKey(businessObjectDataHelper.getBusinessObjectDataKey(uploadSingleInitiationResponse.getTargetBusinessObjectData()));

    // Get the target bushiness object data storage unit.
    StorageUnitEntity targetStorageUnitEntity = IterableUtils.get(targetBusinessObjectDataEntity.getStorageUnits(), 0);

    // Add a second storage file to the target business object data storage unit.
    storageFileDaoTestHelper.createStorageFileEntity(targetStorageUnitEntity, FILE_NAME_2, FILE_SIZE_1_KB, ROW_COUNT_1000);

    // Try to initiate a single file download when business object data has more than one storage file.
    try
    {
        // Initiate the download against the uploaded data (i.e. the target business object data).
        initiateDownload(uploadSingleInitiationResponse.getTargetBusinessObjectData());
        fail("Suppose to throw an IllegalArgumentException when business object has more than one storage file.");
    }
    catch (IllegalArgumentException e)
    {
        BusinessObjectData businessObjectData = uploadSingleInitiationResponse.getTargetBusinessObjectData();
        assertEquals(String.format("Found 2 registered storage files when expecting one in \"%s\" storage for the business object data {%s}.",
            targetStorageUnitEntity.getStorage().getName(), businessObjectDataServiceTestHelper
                .getExpectedBusinessObjectDataKeyAsString(businessObjectDataHelper.getBusinessObjectDataKey(businessObjectData))), e.getMessage());
    }
}
 
Example #27
Source File: UploadDownloadServiceTest.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that the target business object data that is created is using the target storage name that is specified in the request.
 */
@Test
public void testInitiateUploadSingleAssertUseTargetStorageInRequest()
{
    // Create database entities required for testing.
    uploadDownloadServiceTestHelper.createDatabaseEntitiesForUploadDownloadTesting();
    StorageEntity storageEntity = storageDaoTestHelper.createStorageEntity(STORAGE_NAME_3);
    storageEntity.getAttributes().add(storageDaoTestHelper
        .createStorageAttributeEntity(storageEntity, configurationHelper.getProperty(ConfigurationValue.S3_ATTRIBUTE_NAME_BUCKET_NAME), "testBucketName"));
    storageEntity.getAttributes().add(storageDaoTestHelper
        .createStorageAttributeEntity(storageEntity, configurationHelper.getProperty(ConfigurationValue.S3_ATTRIBUTE_NAME_KEY_PREFIX_VELOCITY_TEMPLATE),
            "$environment/$namespace/$businessObjectDataPartitionValue"));
    storageEntity.getAttributes().add(storageDaoTestHelper
        .createStorageAttributeEntity(storageEntity, configurationHelper.getProperty(ConfigurationValue.S3_ATTRIBUTE_NAME_KMS_KEY_ID),
            "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012"));

    // Initiate a file upload.
    UploadSingleInitiationRequest uploadSingleInitiationRequest = uploadDownloadServiceTestHelper.createUploadSingleInitiationRequest();
    uploadSingleInitiationRequest.setTargetStorageName(STORAGE_NAME_3);

    UploadSingleInitiationResponse resultUploadSingleInitiationResponse = uploadDownloadService.initiateUploadSingle(uploadSingleInitiationRequest);

    // Validate the returned object.
    uploadDownloadServiceTestHelper
        .validateUploadSingleInitiationResponse(NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, NAMESPACE, BDEF_NAME_2,
            FORMAT_USAGE_CODE_2, FORMAT_FILE_TYPE_CODE_2, FORMAT_VERSION_2, businessObjectDefinitionServiceTestHelper.getNewAttributes(), FILE_NAME,
            FILE_SIZE_1_KB, STORAGE_NAME_3, resultUploadSingleInitiationResponse);

    BusinessObjectDataEntity targetBusinessObjectDataEntity = businessObjectDataDao.getBusinessObjectDataByAltKey(
        new BusinessObjectDataKey(NAMESPACE, BDEF_NAME_2, FORMAT_USAGE_CODE_2, FORMAT_FILE_TYPE_CODE_2, FORMAT_VERSION_2,
            resultUploadSingleInitiationResponse.getTargetBusinessObjectData().getPartitionValue(), null, 0));

    assertNotNull(targetBusinessObjectDataEntity);
    assertNotNull(targetBusinessObjectDataEntity.getStorageUnits());
    assertEquals(1, targetBusinessObjectDataEntity.getStorageUnits().size());
    StorageUnitEntity storageUnit = IterableUtils.get(targetBusinessObjectDataEntity.getStorageUnits(), 0);
    assertNotNull(storageUnit);
    assertNotNull(storageUnit.getStorage());
    assertEquals(STORAGE_NAME_3, storageUnit.getStorage().getName());
}
 
Example #28
Source File: ChannelGraphNavigationTest.java    From WiFiAnalyzer with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() {
    mainActivity = RobolectricUtil.INSTANCE.getActivity();

    scanner = MainContextHelper.INSTANCE.getScannerService();
    settings = MainContextHelper.INSTANCE.getSettings();
    configuration = MainContextHelper.INSTANCE.getConfiguration();

    layout = mock(View.class);
    views = new HashMap<>();
    IterableUtils.forEach(ChannelGraphNavigation.ids.keySet(), new PairSetUpClosure());

    fixture = new ChannelGraphNavigation(layout, mainActivity);
}
 
Example #29
Source File: FcgProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void expand(Iterable<FcgVertex> sources, FcgLevel sourceLevel, FcgDirection direction) {

		// remove any non-expandable vertices
		sources = IterableUtils.filteredIterable(sources, v -> v.canExpand());
		if (IterableUtils.isEmpty(sources)) {
			return;
		}

		FcgLevel expandingLevel = sourceLevel.child(direction);

		Set<FcgEdge> newEdges = getModelEdges(sources, expandingLevel, edgeNotInGraphFilter);

		// Need all vertices from the source level, as well as their edges.  
		// This is used to correctly layout the vertices we are adding.  This way, if we 
		// later add the sibling vertices, they will be in the correct spot, without clipping.
		Iterable<FcgVertex> sourceSiblings = getVerticesByLevel(sourceLevel);
		Set<FcgEdge> parentLevelEdges = getModelEdges(sourceSiblings, expandingLevel, unfiltered);

		Set<FcgVertex> newVertices = toVertices(newEdges, direction, vertexInGraphFilter.negate());
		boolean isIncoming = direction == IN;
		FcgExpandingVertexCollection collection =
			new FcgExpandingVertexCollection(sources, sourceLevel, expandingLevel, newVertices,
				newEdges, parentLevelEdges, isIncoming, view.getPrimaryGraphViewer());

		doExpand(collection);

		markExpanded(sources, direction, true);
	}
 
Example #30
Source File: JjdocProgramInvoker.java    From javaccPlugin with MIT License 5 votes vote down vote up
private String getJjdocOutputFileExtension(ProgramArguments arguments) {
    String outputFileExtension = ".html";
    if (IterableUtils.matchesAny(Arrays.asList(arguments.toArray()), outputTextPredicate())) {
        outputFileExtension = ".txt";
    }
    return outputFileExtension;
}