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:net.shibboleth.idp.attribute.resolver.impl.ad.ScriptedAttributeTest.java

/**
 * Test resolution of an simple script (statically generated data).
 * //w ww .j av  a 2s  . c  om
 * @throws ResolutionException
 * @throws ComponentInitializationException only if the test will fail
 * @throws ScriptException
 * @throws IOException
 */
@Test
public void simple()
        throws ResolutionException, ComponentInitializationException, ScriptException, IOException {

    final IdPAttribute test = new IdPAttribute(TEST_ATTRIBUTE_NAME);

    test.setValues(Collections.singleton(new StringAttributeValue(SIMPLE_VALUE)));

    final ScriptedAttributeDefinition attr = new ScriptedAttributeDefinition();
    Assert.assertNull(attr.getScript());
    attr.setId(TEST_ATTRIBUTE_NAME);
    attr.setScript(new EvaluableScript(SCRIPT_LANGUAGE, getScript("simple.script")));
    attr.initialize();
    Assert.assertNotNull(attr.getScript());

    final IdPAttribute val = attr.resolve(generateContext());
    final Set<IdPAttributeValue<?>> results = val.getValues();

    Assert.assertTrue(test.equals(val), "Scripted result is the same as bases");
    Assert.assertEquals(results.size(), 1, "Scripted result value count");
    Assert.assertEquals(results.iterator().next().getValue(), SIMPLE_VALUE,
            "Scripted result contains known value");
}

From source file:com.hp.autonomy.frontend.configuration.authentication.CommunityAuthenticationProviderTest.java

@SuppressWarnings("unchecked")
@Before//from   ww w. ja  v a 2s .c  o m
public void setUp() {
    when(authentication.getMethod()).thenReturn("");

    // use not type safe syntax as the usual version won't compile
    Mockito.doReturn(authentication).when(authenticationConfig).getAuthentication();

    when(configService.getConfig()).thenReturn(authenticationConfig);

    when(roles.areRolesAuthorized((Set<String>) argThat(Matchers.hasItem(APP_ROLE)), anySet()))
            .thenReturn(true);
    when(roles.areRolesAuthorized((Set<String>) argThat(Matchers.hasItem(DEFAULT_ROLE)), anySet()))
            .thenReturn(true);
    when(roles.areRolesAuthorized((Set<String>) argThat(Matchers.hasItem(BOGUS_ROLE)), anySet()))
            .thenReturn(false);

    when(springAuthentication.getPrincipal()).thenReturn("username");
    when(springAuthentication.getCredentials()).thenReturn("password");

    when(userService.authenticateUser(anyString(), anyString(), anyString())).thenReturn(true);

    when(grantedAuthoritiesMapper.mapAuthorities(anyCollection())).thenAnswer(returnsFirstArg());

    communityAuthenticationProvider = new CommunityAuthenticationProvider(configService, userService, roles,
            loginPrivileges, grantedAuthoritiesMapper);

    communityAuthenticationProviderWithDefaultRoles = new CommunityAuthenticationProvider(configService,
            userService, roles, loginPrivileges, grantedAuthoritiesMapper, Collections.singleton(DEFAULT_ROLE));
}

From source file:am.ik.categolj2.domain.service.user.UserServiceImplTest.java

@Test(expected = BusinessException.class)
@Transactional//from www  .j ava2s  . c o  m
public void testCreate_illeagal_role() {
    User user = new User("testuser2", null, "testuser2@example.com", true, false, "Test", "User", null);
    user.setRoles(Collections.singleton(new Role(100)));
    userService.create(user, "password");
}

From source file:simx.profiler.info.application.MessagesInfoTopComponent.java

public MessagesInfoTopComponent() {
    initComponents();/*  ww  w.jav a  2  s .c  o m*/
    setName(Bundle.CTL_MessagesInfoTopComponent());
    setToolTipText(Bundle.HINT_MessagesInfoTopComponent());

    this.content = new InstanceContent();

    this.associateLookup(new AbstractLookup(this.content));

    this.profilingData = ProfilingData.getLoadedProfilingData();

    this.messagesDataSet = new DefaultPieDataset();

    this.createPieChart(this.messagesDataSet, this.graphicalPanel);

    final ListSelectionModel listSelectionModel = this.messageTypeInformationTable.getSelectionModel();
    listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    listSelectionModel.addListSelectionListener((final ListSelectionEvent e) -> {
        if (messageTypeInformationTable.getSelectedRow() != -1) {
            final List<Map.Entry<MessageType, Integer>> data = new ArrayList<>(
                    communicationData.getCommunicationData().entrySet());
            final MessageType messageType = data.get(messageTypeInformationTable.getSelectedRow()).getKey();
            content.set(Collections.singleton(messageType), null);
        }
    });
}

From source file:com.devicehive.handler.notification.NotificationSearchHandlerTest.java

@Test
public void shouldHandleNotificationInsertAndQueryByDeviceGuidAndNotificationName() throws Exception {
    NotificationSearchRequest searchRequest = new NotificationSearchRequest();
    searchRequest.setGuid(notifications.get(0).getDeviceGuid());
    searchRequest.setNames(Collections.singleton(notifications.get(0).getNotification()));

    Request request = Request.newBuilder().withBody(searchRequest).build();
    CompletableFuture<Response> future = new CompletableFuture<>();
    client.call(request, future::complete);

    Response response = future.get(10, TimeUnit.SECONDS);
    NotificationSearchResponse responseBody = (NotificationSearchResponse) response.getBody();
    assertEquals(1, responseBody.getNotifications().size());
    assertEquals(notifications.get(0), responseBody.getNotifications().get(0));
}

From source file:com.opengamma.financial.analytics.PositionOrTradeScalingFunction.java

@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context,
        final ComputationTarget target, final Map<ValueSpecification, ValueRequirement> inputs) {
    final ValueSpecification input = inputs.keySet().iterator().next();
    final ValueSpecification specification = new ValueSpecification(_requirementName, target.toSpecification(),
            getResultProperties(input));
    return Collections.singleton(specification);
}

From source file:com.google.samples.apps.abelana.AbelanaThings.java

public AbelanaThings(Context ctx, String phint) {
    final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    final HttpTransport httpTransport = new NetHttpTransport();
    Resources r = ctx.getResources();
    byte[] android, server;
    byte[] password = new byte[32];

    android = Base64.decode("vW7CmbQWdPjpdfpBU39URsjHQV50KEKoSfafHdQPSh8",
            Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_WRAP);
    server = Base64.decode(phint, Base64.URL_SAFE);

    int i = 0;/*www . ja v  a 2 s. c  o  m*/
    for (byte b : android) {
        password[i] = (byte) (android[i] ^ server[i]);
        i++;
    }
    byte[] pw = Base64.encode(password, Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_WRAP);
    String pass = new String(pw);

    if (storage == null) {
        try {
            KeyStore keystore = KeyStore.getInstance("PKCS12");
            keystore.load(r.openRawResource(R.raw.abelananew), pass.toCharArray());

            credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
                    .setServiceAccountId(r.getString(R.string.service_account))
                    .setServiceAccountScopes(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL))
                    .setServiceAccountPrivateKey((PrivateKey) keystore.getKey("privatekey", pass.toCharArray()))
                    .build();

            storage = new Storage.Builder(httpTransport, jsonFactory, credential)
                    .setApplicationName(r.getString(R.string.app_name) + "/1.0").build();

        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("loaded");
    }
}

From source file:com.fredhopper.connector.index.provider.FhCategorySource.java

protected Set<ProductModel> findProductFamily(final ProductModel product) {
    if (product instanceof VariantProductModel) {
        // Collect all the variant products and all their super variants, until the final base product is hit
        final Set<ProductModel> products = new HashSet<>();

        ProductModel currentProduct = product;
        while (currentProduct instanceof VariantProductModel) {
            products.add(currentProduct);
            currentProduct = ((VariantProductModel) currentProduct).getBaseProduct();
        }/*from w w w.j  a  v  a 2 s  .  c  o m*/

        products.add(currentProduct);
        return products;
    } else if (product != null) {
        return Collections.singleton(product);
    }
    return Collections.emptySet();
}

From source file:ca.uhn.fhir.rest.server.RestfulServerUtils.java

public static void configureResponseParser(RequestDetails theRequestDetails, IParser parser) {
    // Pretty print
    boolean prettyPrint = RestfulServerUtils.prettyPrintResponse(theRequestDetails.getServer(),
            theRequestDetails);//ww w.j  a  v  a 2 s.  c om

    parser.setPrettyPrint(prettyPrint);
    parser.setServerBaseUrl(theRequestDetails.getFhirServerBase());

    // Summary mode
    Set<SummaryEnum> summaryMode = RestfulServerUtils.determineSummaryMode(theRequestDetails);

    // _elements
    Set<String> elements = ElementsParameter.getElementsValueOrNull(theRequestDetails);
    if (elements != null && summaryMode != null
            && !summaryMode.equals(Collections.singleton(SummaryEnum.FALSE))) {
        throw new InvalidRequestException("Cannot combine the " + Constants.PARAM_SUMMARY + " and "
                + Constants.PARAM_ELEMENTS + " parameters");
    }
    Set<String> elementsAppliesTo = null;
    if (elements != null && isNotBlank(theRequestDetails.getResourceName())) {
        elementsAppliesTo = Collections.singleton(theRequestDetails.getResourceName());
    }

    if (summaryMode != null) {
        if (summaryMode.contains(SummaryEnum.COUNT)) {
            parser.setEncodeElements(Collections.singleton("Bundle.total"));
        } else if (summaryMode.contains(SummaryEnum.TEXT)) {
            parser.setEncodeElements(TEXT_ENCODE_ELEMENTS);
        } else {
            parser.setSuppressNarratives(summaryMode.contains(SummaryEnum.DATA));
            parser.setSummaryMode(summaryMode.contains(SummaryEnum.TRUE));
        }
    }
    if (elements != null && elements.size() > 0) {
        Set<String> newElements = new HashSet<String>();
        for (String next : elements) {
            newElements.add("*." + next);
        }
        parser.setEncodeElements(newElements);
        parser.setEncodeElementsAppliesToResourceTypes(elementsAppliesTo);
    }
}

From source file:com.haulmont.cuba.gui.ScreenHistorySupport.java

public void saveScreenHistory(Window window, WindowManager.OpenMode openMode) {
    Security security = AppBeans.get(Security.NAME);
    if (security.isEntityOpPermitted(ScreenHistoryEntity.class, EntityOp.CREATE) && window.getFrame() != null
            && (window.getFrame() instanceof Window.Editor) && openMode != WindowManager.OpenMode.DIALOG
            && (screenIds == null || screenIds.contains(window.getId()))) {
        String caption = window.getCaption();
        UUID entityId = null;/* w ww.ja va  2s. c om*/
        Frame frame = window.getFrame();
        Entity entity = null;
        if (frame instanceof Window.Editor) {
            entity = ((Window.Editor) frame).getItem();
            if (entity != null) {
                if (PersistenceHelper.isNew(entity)) {
                    return;
                }
                if (StringUtils.isBlank(caption))
                    caption = messages.getTools().getEntityCaption(entity.getMetaClass()) + " "
                            + entity.getInstanceName();
                entityId = (UUID) entity.getId();
            }
        }
        ScreenHistoryEntity screenHistoryEntity = metadata.create(ScreenHistoryEntity.class);
        screenHistoryEntity.setCaption(StringUtils.abbreviate(caption, 255));
        screenHistoryEntity.setUrl(makeLink(window));
        screenHistoryEntity.setEntityId(entityId);
        addAdditionalFields(screenHistoryEntity, entity);

        CommitContext cc = new CommitContext(Collections.singleton(screenHistoryEntity));
        DataService dataService = AppBeans.get(DataService.NAME);
        dataService.commit(cc);
    }
}