Example usage for java.util Collections singleton

List of usage examples for java.util Collections singleton

Introduction

In this page you can find the example usage for java.util Collections singleton.

Prototype

public static <T> Set<T> singleton(T o) 

Source Link

Document

Returns an immutable set containing only the specified object.

Usage

From source file:org.commonjava.indy.ftest.core.content.GroupHttpHeadersFromSameRepoWhenNotInPathMaskTest.java

@Before
public void setupStores() throws Exception {
    String changelog = "test setup";
    repoX = new RemoteRepository(REPO_X, server.formatUrl(REPO_X));
    repoX.setPathMaskPatterns(Collections.singleton(PATH));
    repoX = client.stores().create(repoX, changelog, RemoteRepository.class);

    repoY = client.stores().create(new RemoteRepository(REPO_Y, server.formatUrl(REPO_Y)), changelog,
            RemoteRepository.class);

    content2 = CONTENT_2.getBytes("UTF-8");

    server.expect(server.formatUrl(REPO_X, PATH), 200, CONTENT_1);

    server.expect(server.formatUrl(REPO_Y, PATH), 200, new ByteArrayInputStream(content2));

    groupA = client.stores().create(new Group(GROUP_A, repoX.getKey(), repoY.getKey()), changelog, Group.class);

}

From source file:org.eclipse.sw360.datahandler.couchdb.AttachmentStreamConnectorTest.java

@Test
public void testTryingToDownloadIfNotAvailable() throws Exception {
    String id = "11";
    String filename = "filename";
    AttachmentContent attachment = mock(AttachmentContent.class);
    when(attachment.isOnlyRemote()).thenReturn(true);
    when(attachment.getId()).thenReturn(id);
    when(attachment.getFilename()).thenReturn(filename);

    InputStream downloadUrlStream = mock(InputStream.class);
    InputStream returnedStream = mock(InputStream.class);

    AttachmentContent rereadAttachment = mock(AttachmentContent.class);
    when(rereadAttachment.getId()).thenReturn(id);
    when(rereadAttachment.getFilename()).thenReturn(filename);

    attachmentStreamConnector = spy(attachmentStreamConnector);
    doReturn(returnedStream).when(attachmentStreamConnector).readAttachmentStream(rereadAttachment);
    doNothing().when(attachmentStreamConnector).uploadAttachmentPart(attachment, 1, downloadUrlStream);

    when(attachmentContentDownloader.download(eq(attachment), Matchers.any(Duration.class)))
            .thenReturn(downloadUrlStream);

    when(connector.get(AttachmentContent.class, id)).thenReturn(rereadAttachment);
    doReturn(rereadAttachment).when(rereadAttachment).setOnlyRemote(anyBoolean());

    assertThat(attachmentStreamConnector.getAttachmentStream(attachment, dummyUser,
            new Project().setVisbility(Visibility.ME_AND_MODERATORS).setCreatedBy(dummyUser.getEmail())
                    .setAttachments(Collections.singleton(new Attachment().setAttachmentContentId(id)))),
            sameInstance(returnedStream));

    verify(attachmentContentDownloader).download(eq(attachment), Matchers.any(Duration.class));
    verify(attachmentStreamConnector).uploadAttachment(attachment, downloadUrlStream);
    verify(attachmentStreamConnector).readAttachmentStream(rereadAttachment);

    verify(rereadAttachment).setOnlyRemote(false);
    verify(connector).update(rereadAttachment);
}

From source file:com.github.lindenb.jvarkit.tools.biostar.Biostar130456.java

@Override
public Collection<Throwable> call() throws Exception {
    final List<String> args = getInputFiles();

    if (super.filepattern == null || !filepattern.contains(SAMPLE_TAG)) {
        return wrapException("File pattern is missing " + SAMPLE_TAG);
    }//from   w  w w. j  a v a2  s.c om

    VcfIterator in = null;
    try {
        if (args.isEmpty()) {
            LOG.info("Reading from <stdin>");
            in = VCFUtils.createVcfIteratorFromInputStream(stdin());
        } else if (args.size() == 1) {
            String filename = args.get(0);
            LOG.info("Reading from " + filename);
            in = VCFUtils.createVcfIterator(filename);
        } else {
            return wrapException(getMessageBundle("illegal.number.of.arguments"));
        }
        VCFHeader header = in.getHeader();
        Set<String> samples = new HashSet<String>(header.getSampleNamesInOrder());
        Map<String, VariantContextWriter> sample2writer = new HashMap<String, VariantContextWriter>(
                samples.size());

        if (samples.isEmpty()) {
            return wrapException("VCF doesn't contain any sample");
        }
        LOG.info("N sample:" + samples.size());
        for (String sample : samples) {

            VCFHeader h2 = new VCFHeader(header.getMetaDataInInputOrder(), Collections.singleton(sample));
            h2.addMetaDataLine(new VCFHeaderLine(getClass().getSimpleName() + "CmdLine",
                    String.valueOf(getProgramCommandLine())));
            h2.addMetaDataLine(
                    new VCFHeaderLine(getClass().getSimpleName() + "Version", String.valueOf(getVersion())));
            h2.addMetaDataLine(new VCFHeaderLine(getClass().getSimpleName() + "HtsJdkVersion",
                    HtsjdkVersion.getVersion()));
            h2.addMetaDataLine(
                    new VCFHeaderLine(getClass().getSimpleName() + "HtsJdkHome", HtsjdkVersion.getHome()));
            String sampleFile = filepattern.replaceAll(SAMPLE_TAG, sample);
            stdout().println(sampleFile);
            File fout = new File(sampleFile);
            if (fout.getParentFile() != null)
                fout.getParentFile().mkdirs();
            VariantContextWriter w = VCFUtils.createVariantContextWriter(fout);
            w.writeHeader(h2);
            sample2writer.put(sample, w);
        }
        SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(
                header.getSequenceDictionary());
        while (in.hasNext()) {
            VariantContext ctx = progress.watch(in.next());
            for (String sample : samples) {
                Genotype g = ctx.getGenotype(sample);
                if (g == null)
                    continue;
                if (remove_uncalled && (!g.isAvailable() || !g.isCalled() || g.isNoCall())) {
                    continue;
                }
                if (remove_homref && g.isHomRef())
                    continue;
                VariantContextWriter w = sample2writer.get(sample);
                VariantContextBuilder vcb = new VariantContextBuilder(ctx);
                GenotypeBuilder gb = new GenotypeBuilder(g);
                vcb.genotypes(Collections.singletonList(gb.make()));
                VariantContext ctx2 = vcb.make();
                w.add(ctx2);
            }
        }
        for (String sample : samples) {
            LOG.info("Closing for sample " + sample);
            VariantContextWriter w = sample2writer.get(sample);
            w.close();
        }
        progress.finish();
        return Collections.emptyList();
    } catch (Exception e) {
        return wrapException(e);
    } finally {
        CloserUtil.close(in);
    }
}

From source file:gov.nih.nci.caarray.plugins.genepix.GalArrayDesignServiceTest.java

@Test
public void testValidateDesign_Genepix() {
    CaArrayFile designFile = getGenepixCaArrayFile(GenepixArrayDesignFiles.DEMO_GAL);
    ValidationResult result = this.arrayDesignService.validateDesign(Collections.singleton(designFile));
    assertTrue(result.toString(), result.isValid());
    designFile = getGenepixCaArrayFile(GenepixArrayDesignFiles.TWO_K_GAL);
    result = this.arrayDesignService.validateDesign(Collections.singleton(designFile));
    assertTrue(result.toString(), result.isValid());
    designFile = getGenepixCaArrayFile(GenepixArrayDesignFiles.MEEBO);
    result = this.arrayDesignService.validateDesign(Collections.singleton(designFile));
    assertTrue(result.toString(), result.isValid());
}

From source file:org.commonjava.indy.diags.ftest.DownloadDiagBundleTest.java

@Override
protected Collection<IndyClientModule> getAdditionalClientModules() {
    return Collections.singleton(module);
}

From source file:podd.server.authn.impl.PoddUserDetailsServiceImplUnitTest.java

@Test
public void testExistingUser() {
    final UserDetails details = dsService.loadUserByUsername(user.getUserName());
    assertEquals(user.getUserName(), details.getUsername());
    assertEquals(user.getPasswordHash(), details.getPassword());
    final GrantedAuthority[] authorities = details.getAuthorities();
    GrantedAuthority authority = new GrantedAuthorityImpl(user.getRepositoryRole().getName());
    PoddWebappTestUtil.checkMembers(Collections.singleton(authority), authorities);
}

From source file:com.parse.ParseRelation.java

/**
 * Adds an object to this relation./* w w  w . j  a  va  2s  .c om*/
 * 
 * @param object
 *          The object to add to this relation.
 */
public void add(T object) {
    synchronized (mutex) {
        ParseRelationOperation<T> operation = new ParseRelationOperation<>(Collections.singleton(object), null);
        targetClass = operation.getTargetClass();
        getParent().performOperation(key, operation);

        knownObjects.add(object);
    }
}

From source file:com.devicehive.resource.impl.DeviceNotificationResourceImpl.java

/**
 * {@inheritDoc}/*from   w w w  . ja v  a2  s  .  co m*/
 */
@Override
public void query(String guid, String startTs, String endTs, String notification, String sortField,
        String sortOrderSt, Integer take, Integer skip, @Suspended final AsyncResponse asyncResponse) {
    logger.debug("Device notification query requested for device {}", guid);

    final Date timestampSt = TimestampQueryParamParser.parse(startTs);
    final Date timestampEnd = TimestampQueryParamParser.parse(endTs);

    DeviceVO byGuidWithPermissionsCheck = deviceService.getDeviceWithNetworkAndDeviceClass(guid);
    if (byGuidWithPermissionsCheck == null) {
        ErrorResponse errorCode = new ErrorResponse(NOT_FOUND.getStatusCode(),
                String.format(Messages.DEVICE_NOT_FOUND, guid));
        Response response = ResponseFactory.response(NOT_FOUND, errorCode);
        asyncResponse.resume(response);
    } else {
        Set<String> notificationNames = StringUtils.isNoneEmpty(notification)
                ? Collections.singleton(notification)
                : Collections.emptySet();
        notificationService.find(Collections.singleton(guid), notificationNames, timestampSt, timestampEnd)
                .thenApply(notifications -> {
                    final Comparator<DeviceNotification> comparator = CommandResponseFilterAndSort
                            .buildDeviceNotificationComparator(sortField);
                    final Boolean reverse = sortOrderSt == null ? null : "desc".equalsIgnoreCase(sortOrderSt);

                    final List<DeviceNotification> sortedDeviceNotifications = CommandResponseFilterAndSort
                            .orderAndLimit(notifications, comparator, reverse, skip, take);
                    return ResponseFactory.response(OK, sortedDeviceNotifications,
                            JsonPolicyDef.Policy.NOTIFICATION_TO_CLIENT);
                }).thenAccept(asyncResponse::resume);
    }
}

From source file:hudson.plugins.depgraph_view.model.graph.CycleFinderColorTest.java

private DependencyGraph generateGraph(AbstractProject<?, ?> from) {
    return new GraphCalculator(getDependencyGraphEdgeProviders())
            .generateGraph(Collections.singleton(node(from)));
}

From source file:ddf.catalog.validation.impl.validator.SizeValidator.java

/**
 * {@inheritDoc}/*w  ww .  j  a v a  2 s.com*/
 * <p>
 * Validates only the values of {@code attribute} that are {@link CharSequence}s,
 * {@link Collection}s, {@link Map}s, or arrays.
 */
@Override
public Optional<AttributeValidationReport> validate(final Attribute attribute) {
    Preconditions.checkArgument(attribute != null, "The attribute cannot be null.");

    final String name = attribute.getName();
    for (final Serializable value : attribute.getValues()) {
        int size;
        if (value instanceof CharSequence) {
            size = ((CharSequence) value).length();
        } else if (value instanceof Collection) {
            size = ((Collection) value).size();
        } else if (value instanceof Map) {
            size = ((Map) value).size();
        } else if (value != null && value.getClass().isArray()) {
            size = Array.getLength(value);
        } else {
            continue;
        }

        if (!checkSize(size)) {
            final String violationMessage = String.format("%s size must be between %d and %d", name, min, max);
            final AttributeValidationReportImpl report = new AttributeValidationReportImpl();
            report.addViolation(
                    new ValidationViolationImpl(Collections.singleton(name), violationMessage, Severity.ERROR));
            return Optional.of(report);
        }
    }

    return Optional.empty();
}