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:com.opengamma.financial.analytics.UnitPositionOrTradeScalingFunction.java

@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context,
        final ComputationTarget target, final ValueRequirement desiredValue) {
    final Security security = target.getPositionOrTrade().getSecurity();
    final ValueProperties constraints = desiredValue.getConstraints().withoutAny(ValuePropertyNames.FUNCTION);
    final ValueRequirement requirement = new ValueRequirement(_requirementName, ComputationTargetType.SECURITY,
            security.getUniqueId(), constraints);
    return Collections.singleton(requirement);
}

From source file:de.hybris.platform.task.impl.DefaultTaskServiceIntegrationTest.java

@Test
public void testIgnoreFailedTasks() throws Exception {
    try {// ww w  .j  a  v  a2s.  c  o  m
        assertEquals(testTaskRunner, Registry.getApplicationContext().getBean("testTaskRunner"));
        assertTrue("task engine is not running", taskService.getEngine().isRunning());
        final TaskModel failedTask = modelService.create(TaskModel.class);
        failedTask.setRunnerBean("testTaskRunner");

        final TaskConditionModel condition = modelService.create(TaskConditionModel.class);
        condition.setUniqueID("MyEvent");
        failedTask.setConditions(Collections.singleton(condition));

        taskService.getEngine().stop();
        taskService.scheduleTask(failedTask);
        modelService.refresh(failedTask);
        taskService.getEngine().start();
        ((DefaultTaskService) taskService)
                .setTaskDao(new AdjustTaskToFailedDAO(failedTask.getPk(), jaloSession.getTenant())
        //adjust task in lock section
        {
                    @Override
                    protected void adjustMatchingPK(final PK taskToAdjust) {
                        final TaskModel model = modelService.get(taskToAdjust);
                        final Task failedTaskItem = modelService.getSource(model);
                        failedTaskItem.setProperty(Task.FAILED, Boolean.TRUE);
                        modelService.refresh(model);
                    }
                });
        taskService.triggerEvent("MyEvent");

        Thread.sleep((long) (1000 * timeFactor));

        assureTaskRunnerNotCalledForTask(failedTask);
        modelService.refresh(failedTask);
        assertTrue("Failed task should remove its conditions ",
                CollectionUtils.isEmpty(failedTask.getConditions()));
    } finally {
        if (!taskService.getEngine().isRunning()) {
            taskService.getEngine().start();
        }
    }
}

From source file:net.pterodactylus.sone.web.ajax.GetStatusAjaxPage.java

/**
 * {@inheritDoc}//w  w w .ja  v a2  s.  c  o m
 */
@Override
protected JsonReturnObject createJsonObject(FreenetRequest request) {
    final Sone currentSone = getCurrentSone(request.getToadletContext(), false);
    /* load Sones. always return the status of the current Sone. */
    Set<Sone> sones = new HashSet<Sone>(
            Collections.singleton(getCurrentSone(request.getToadletContext(), false)));
    String loadSoneIds = request.getHttpRequest().getParam("soneIds");
    if (loadSoneIds.length() > 0) {
        String[] soneIds = loadSoneIds.split(",");
        for (String soneId : soneIds) {
            /* just add it, we skip null further down. */
            sones.add(webInterface.getCore().getSone(soneId).orNull());
        }
    }
    ArrayNode jsonSones = new ArrayNode(instance);
    for (Sone sone : sones) {
        if (sone == null) {
            continue;
        }
        jsonSones.add(createJsonSone(sone));
    }
    /* load notifications. */
    List<Notification> notifications = ListNotificationFilters
            .filterNotifications(webInterface.getNotifications().getNotifications(), currentSone);
    Collections.sort(notifications, Notification.CREATED_TIME_SORTER);
    /* load new posts. */
    Collection<Post> newPosts = webInterface.getNewPosts();
    if (currentSone != null) {
        newPosts = Collections2.filter(newPosts, new Predicate<Post>() {

            @Override
            public boolean apply(Post post) {
                return ListNotificationFilters.isPostVisible(currentSone, post);
            }

        });
    }
    ArrayNode jsonPosts = new ArrayNode(instance);
    for (Post post : newPosts) {
        ObjectNode jsonPost = new ObjectNode(instance);
        jsonPost.put("id", post.getId());
        jsonPost.put("sone", post.getSone().getId());
        jsonPost.put("recipient", post.getRecipientId().orNull());
        jsonPost.put("time", post.getTime());
        jsonPosts.add(jsonPost);
    }
    /* load new replies. */
    Collection<PostReply> newReplies = webInterface.getNewReplies();
    if (currentSone != null) {
        newReplies = Collections2.filter(newReplies, new Predicate<PostReply>() {

            @Override
            public boolean apply(PostReply reply) {
                return ListNotificationFilters.isReplyVisible(currentSone, reply);
            }

        });
    }
    /* remove replies to unknown posts. */
    newReplies = Collections2.filter(newReplies, PostReply.HAS_POST_FILTER);
    ArrayNode jsonReplies = new ArrayNode(instance);
    for (PostReply reply : newReplies) {
        ObjectNode jsonReply = new ObjectNode(instance);
        jsonReply.put("id", reply.getId());
        jsonReply.put("sone", reply.getSone().getId());
        jsonReply.put("post", reply.getPostId());
        jsonReply.put("postSone", reply.getPost().get().getSone().getId());
        jsonReplies.add(jsonReply);
    }
    return createSuccessJsonObject().put("loggedIn", currentSone != null)
            .put("options", createJsonOptions(currentSone)).put("sones", jsonSones)
            .put("notificationHash", notifications.hashCode()).put("newPosts", jsonPosts)
            .put("newReplies", jsonReplies);
}

From source file:com.opengamma.financial.analytics.model.equity.indexoption.EquityIndexVanillaBarrierOptionDefaultPropertiesFunction.java

@Override
protected Set<String> getDefaultValue(FunctionCompilationContext context, ComputationTarget target,
        ValueRequirement desiredValue, String propertyName) {
    if (ValuePropertyNames.BINARY_OVERHEDGE.equals(propertyName)) {
        return Collections.singleton(_barrierOverhedge);
    } else if (ValuePropertyNames.BINARY_SMOOTHING_FULLWIDTH.equals(propertyName)) {
        return Collections.singleton(_callSpreadFullWidth);
    }//from w  ww.  jav  a 2s  .c o  m
    return null;
}

From source file:edu.emory.bmi.aiw.i2b2export.output.PatientDataRowOutputFormatter.java

@Override
protected Collection<Observation> matchingObservations(I2b2ConceptEntity i2b2Concept) throws SQLException {
    switch (StringUtils.upperCase(i2b2Concept.getTableName())) {
    case "CONCEPT_DIMENSION":
        List<Observation> obxs = this.keyToObx.get(i2b2Concept.getI2b2Key());
        if (obxs != null) {
            return Collections.unmodifiableCollection(obxs);
        } else {// ww  w  .  j av  a 2 s . c  o  m
            return Collections.emptyList();
        }
    case "PATIENT_DIMENSION":
        if (compareDimensionColumnValue(i2b2Concept, patient)) {
            Observation.Builder b = new Observation.Builder(null).tval(getParam(patient, i2b2Concept));
            Collection<Observation> o = Collections.singleton(b.build());
            return o;
        } else {
            return Collections.emptyList();
        }
    default:
        return Collections.emptyList();
    }
}

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

/**
 * {@inheritDoc}/*from   www.ja va 2 s .  c o  m*/
 * <p>
 * Validates only the values of {@code attribute} that are {@link CharSequence}s.
 */
@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()) {
        if (value instanceof CharSequence && !(pattern.matcher((CharSequence) value)).matches()) {
            final AttributeValidationReportImpl report = new AttributeValidationReportImpl();
            report.addViolation(new ValidationViolationImpl(Collections.singleton(name),
                    name + " does not follow the pattern " + pattern.pattern(), Severity.ERROR));
            return Optional.of(report);
        }
    }

    return Optional.empty();
}

From source file:Main.java

public static PKIXCertPathValidatorResult validateCertificate(X509Certificate entity,
        X509Certificate intermediate, X509Certificate CA) throws Exception {
    /*  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
      ks.load(null, null);//from  w  w  w.  j  a  va2  s.  c om
      String alias = "validationCA";
      ks.setCertificateEntry(alias, CA);
            
     */
    /*  KeyStore intermediatesStore = KeyStore.getInstance(KeyStore.getDefaultType());
    intermediatesStore.load(null, null);
    String alias_intermediate = "validationIntermediate";
    intermediatesStore.setCertificateEntry(alias_intermediate, intermediate);*//*
                                                                                        
                                                                                        
                                                                                X509CertSelector target = new X509CertSelector();
                                                                                target.setCertificate(entity);
                                                                                PKIXBuilderParameters params = new PKIXBuilderParameters(ks, target);
                                                                                ArrayList<X509Certificate> chain = new ArrayList<>();
                                                                                chain.add(intermediate);
                                                                                chain.add(intermediate);
                                                                                CertStoreParameters intermediates = new CollectionCertStoreParameters(chain);
                                                                                params.addCertStore(CertStore.getInstance("Collection", intermediates));
                                                                                CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
                                                                                 *//*
                                                                                    * If build() returns successfully, the certificate is valid. More details
                                                                                    * about the valid path can be obtained through the PKIXBuilderResult.
                                                                                    * If no valid path can be found, a CertPathBuilderException is thrown.
                                                                                    *//*
                                                                                          PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult)builder.build(params);
                                                                                          return result;*/

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    CertPath certPath = certificateFactory
            .generateCertPath(Arrays.asList(new X509Certificate[] { entity, intermediate }));

    TrustAnchor trustAnchor = new TrustAnchor(CA, null);

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");

    PKIXParameters pkixParams = new PKIXParameters(Collections.singleton(trustAnchor));
    pkixParams.setRevocationEnabled(true);

    return (PKIXCertPathValidatorResult) cpv.validate(certPath, pkixParams);
}

From source file:org.glassmaker.spring.oauth.OAuth2Util.java

/**
 * Creates and returns a new {@link AuthorizationCodeFlow} for this app.
 *//*from   w w w  .  j  a  v  a  2 s  . c  o m*/
public AuthorizationCodeFlow newAuthorizationCodeFlow() throws IOException {

    return new GoogleAuthorizationCodeFlow.Builder(new NetHttpTransport(), new JacksonFactory(), clientId,
            clientSecret, Collections.singleton(scope)).setAccessType(accessType)
                    .setCredentialDataStore(getInMemoryDatastore()).build();
}

From source file:org.openmrs.module.distrotools.metadata.handler.impl.PrivilegeDeployHandler.java

/**
 * @see org.openmrs.module.distrotools.metadata.handler.ObjectDeployHandler#overwrite(org.openmrs.OpenmrsObject, org.openmrs.OpenmrsObject)
 *//*from  ww  w  .  j a va2 s  . c  o  m*/
@Override
public void overwrite(Privilege incoming, Privilege existing) {
    // Do per-field copy of incoming to existing, excluding UUID
    ObjectUtils.overwrite(incoming, existing, Collections.singleton("uuid"));
}

From source file:com.netflix.spinnaker.halyard.core.registry.v1.WriteableProfileRegistry.java

private GoogleCredential loadCredential(HttpTransport transport, JsonFactory factory, String jsonPath)
        throws IOException {
    GoogleCredential credential;//from w w  w. j  a v a2 s .c om
    if (!jsonPath.isEmpty()) {
        FileInputStream stream = new FileInputStream(jsonPath);
        credential = GoogleCredential.fromStream(stream, transport, factory)
                .createScoped(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL));
        log.info("Loaded credentials from " + jsonPath);
    } else {
        log.info("Using default application credentials.");
        credential = GoogleCredential.getApplicationDefault();
    }
    return credential;
}