Java Code Examples for org.apache.commons.collections4.IterableUtils

The following examples show how to use org.apache.commons.collections4.IterableUtils. These examples are extracted from open source projects. 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
@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 2
Source Project: openemm   Source File: CssUtils.java    License: 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 3
Source Project: ghidra   Source File: FcgProvider.java    License: 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 4
Source Project: archiva   Source File: DefaultProxyConnectorAdmin.java    License: 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 5
Source Project: incubator-wikift   Source File: ArticleServiceImpl.java    License: 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 6
Source Project: cuba   Source File: JmxConnectionHelper.java    License: 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 7
Source Project: herd   Source File: AttributeDaoHelperTest.java    License: 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 8
@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 9
@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 10
Source Project: proctor   Source File: ProctorController.java    License: 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 11
Source Project: archiva   Source File: FileTypes.java    License: 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 12
Source Project: ghidra   Source File: DefaultVisualGraph.java    License: 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 13
Source Project: archiva   Source File: RepositoryScannerInstance.java    License: 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 14
Source Project: WiFiAnalyzer   Source File: SeriesCacheTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testRemoveExpectNoneLeft() {
    // setup
    List<WiFiDetail> expected = withData();
    // execute
    List<BaseSeries<DataPoint>> actual = fixture.remove(expected);
    // validate
    assertEquals(expected.size(), actual.size());
    IterableUtils.forEach(expected, new ContainsFalseClosure());
}
 
Example 15
Source Project: WiFiAnalyzer   Source File: DataManagerTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testAdjustDataAppendsData() {
    // setup
    Set<WiFiDetail> wiFiDetails = Collections.emptySet();
    List<WiFiDetail> difference = makeWiFiDetails();
    int xValue = fixture.getXValue();
    Integer scanCount = fixture.getScanCount();
    DataPoint dataPoint = new DataPoint(xValue, GraphConstants.MIN_Y + GraphConstants.MIN_Y_OFFSET);
    when(graphViewWrapper.differenceSeries(wiFiDetails)).thenReturn(difference);
    // execute
    fixture.adjustData(graphViewWrapper, wiFiDetails);
    // validate
    IterableUtils.forEach(difference, new WiFiDetailClosure(dataPoint, scanCount));
    verify(timeGraphCache).clear();
}
 
Example 16
Source Project: ghidra   Source File: FcgProvider.java    License: 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 17
Source Project: ghidra   Source File: FcgProvider.java    License: Apache License 2.0 5 votes vote down vote up
private Iterable<Function> getCallingFunctions(Function f) {

		FunctionEdgeCache edgeCache = graphData.getFunctionEdgeCache();

		// all functions should be registered when the vertices are created
		SystemUtilities.assertTrue(edgeCache.isTracked(f), "Function not tracked in cache");

		Set<FunctionEdge> edges = edgeCache.get(f);
		Iterable<FunctionEdge> filtered =
			IterableUtils.filteredIterable(edges, e -> isCalledFunction(f, e));
		Iterable<Function> functions =
			IterableUtils.transformedIterable(filtered, e -> e.getStart());
		return functions;
	}
 
Example 18
Source Project: ghidra   Source File: FcgProvider.java    License: Apache License 2.0 5 votes vote down vote up
private Iterable<Function> getCallerFunctions(Function f) {

		FunctionEdgeCache edgeCache = graphData.getFunctionEdgeCache();

		// all functions should be registered when the vertices are created
		SystemUtilities.assertTrue(edgeCache.isTracked(f), "Function not tracked in cache");

		Set<FunctionEdge> edges = edgeCache.get(f);
		Iterable<FunctionEdge> filtered =
			IterableUtils.filteredIterable(edges, e -> isCallingFunction(f, e));
		Iterable<Function> functions = IterableUtils.transformedIterable(filtered, e -> e.getEnd());
		return functions;
	}
 
Example 19
Source Project: multiapps   Source File: PropertiesResolver.java    License: Apache License 2.0 5 votes vote down vote up
private Object resolveKeyInIterable(String key, Collection<?> listOfProperties, String longKey) {
    if (StringUtils.isNumeric(key)) {
        try {
            return IterableUtils.get(listOfProperties, Integer.parseInt(key));
        } catch (IndexOutOfBoundsException e) { // Intentionally ignored
        }
    }

    throw new ContentException(Messages.UNABLE_TO_RESOLVE, getPrefixedName(prefix, longKey));
}
 
Example 20
Source Project: gocd   Source File: DefaultPluginRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GoPluginBundleDescriptor getBundleDescriptor(String bundleSymbolicName) {
    final GoPluginDescriptor descriptor = IterableUtils.find(idToDescriptorMap.values(),
            pluginDescriptor -> pluginDescriptor.bundleDescriptor().bundleSymbolicName().equals(bundleSymbolicName));

    if (descriptor == null) {
        return null;
    }
    return descriptor.bundleDescriptor();
}
 
Example 21
Source Project: gocd   Source File: DefaultPluginJarLocationMonitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void removePluginJarChangeListener(final PluginJarChangeListener listener) {
    WeakReference<PluginJarChangeListener> referenceOfListenerToBeRemoved = IterableUtils.find(pluginJarChangeListeners, listenerWeakReference -> {
        PluginJarChangeListener registeredListener = listenerWeakReference.get();
        return registeredListener != null && registeredListener == listener;
    });
    pluginJarChangeListeners.remove(referenceOfListenerToBeRemoved);
    removeClearedWeakReferences();
}
 
Example 22
Source Project: cuba   Source File: SendingMessageBrowser.java    License: Apache License 2.0 5 votes vote down vote up
protected void selectAttachmentDialog(SendingMessage message) {
    openLookup("sys$SendingMessage.attachments", items -> {
        if (items.size() == 1) {
            exportFile((SendingAttachment) IterableUtils.get(items, 0));
        }
    }, OpenType.DIALOG, ParamsMap.of("message", message));
}
 
Example 23
Source Project: alf.io   Source File: EventManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void validatePaymentProxies(List<PaymentProxy> paymentProxies, int organizationId) {
    var conflicts = paymentManager.validateSelection(paymentProxies, organizationId);
    if(!conflicts.isEmpty()) {
        var firstConflict = IterableUtils.get(conflicts, 0);
        throw new IllegalStateException("Conflicting providers found: "+firstConflict.getValue());
    }
}
 
Example 24
@Test
public void testChannelsAustraliaCanada() {
    SortedSet<Integer> exclude = new TreeSet<>(Arrays.asList(120, 124, 128));
    int expectedSize = CHANNELS_SET1.size() + CHANNELS_SET2.size() + CHANNELS_SET3.size() - exclude.size();
    List<String> countries = Arrays.asList("AU", "CA");
    IterableUtils.forEach(countries, new ChannelCanadaClosure(expectedSize, exclude));
}
 
Example 25
Source Project: tcases   Source File: TestCase.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the index of the binding for the given variable.
 */
private int findBinding( final String name)
  {
  return
    IterableUtils.indexOf(
      varBindings_,
      binding -> Objects.equals( binding.getVar(), name));
  }
 
Example 26
Source Project: herd   Source File: UploadDownloadHelperServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets a unique storage from the given business object data. The given business object data must have one and only one storage unit with a storage,
 * otherwise this method throws an exception.
 *
 * @param businessObjectDataEntity the business object data entity
 *
 * @return the unique storage entity
 */
private StorageEntity getUniqueStorage(BusinessObjectDataEntity businessObjectDataEntity)
{
    Collection<StorageUnitEntity> targetStorageUnits = businessObjectDataEntity.getStorageUnits();
    Assert.notEmpty(targetStorageUnits, "No storage units found for business object data ID \"" + businessObjectDataEntity.getId() + "\".");
    Assert.isTrue(targetStorageUnits.size() == 1,
        "More than 1 storage units found for business object data ID \"" + businessObjectDataEntity.getId() + "\".");
    return IterableUtils.get(targetStorageUnits, 0).getStorage();
}
 
Example 27
Source Project: javaccPlugin   Source File: JjdocProgramInvoker.java    License: 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;
}
 
Example 28
@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 Project: herd   Source File: UploadDownloadServiceTest.java    License: 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 30
Source Project: herd   Source File: UploadDownloadServiceTest.java    License: 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());
    }
}