Example usage for java.util Collections enumeration

List of usage examples for java.util Collections enumeration

Introduction

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

Prototype

public static <T> Enumeration<T> enumeration(final Collection<T> c) 

Source Link

Document

Returns an enumeration over the specified collection.

Usage

From source file:org.apache.click.servlet.MockRequest.java

/**
 * Return all the accepted locales. This implementation always returns just
 * one.// w w  w. j  a  v a2  s  .c  o m
 *
 * @return The locales
 */
public Enumeration<Locale> getLocales() {
    List<Locale> list = new ArrayList<Locale>(1);
    list.add(getLocale());
    return Collections.enumeration(list);
}

From source file:org.wso2.carbon.identity.oauth.endpoint.token.OAuth2TokenEndpointTest.java

@Test(dataProvider = "testTokenErrorResponseDataProvider", groups = "testWithConnection")
public void testTokenErrorResponse(String errorCode, Object headerObj, int expectedStatus,
        String expectedErrorCode) throws Exception {
    ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj;

    Map<String, String[]> requestParams = new HashMap<>();
    requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[] { GrantType.PASSWORD.toString() });
    requestParams.put(OAuth.OAUTH_USERNAME, new String[] { USERNAME });
    requestParams.put(OAuth.OAUTH_PASSWORD, new String[] { "password" });

    HttpServletRequest request = mockHttpRequest(requestParams, new HashMap<String, Object>());
    when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(AUTHORIZATION_HEADER);
    when(request.getHeaderNames()).thenReturn(Collections.enumeration(new ArrayList<String>() {
        {/*ww w.jav a  2s .c o  m*/
            add(OAuthConstants.HTTP_REQ_HEADER_AUTHZ);
        }
    }));

    spy(EndpointUtil.class);
    doReturn(REALM).when(EndpointUtil.class, "getRealmInfo");
    doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");

    when(oAuth2Service.issueAccessToken(any(OAuth2AccessTokenReqDTO.class)))
            .thenReturn(oAuth2AccessTokenRespDTO);
    when(oAuth2AccessTokenRespDTO.getErrorMsg()).thenReturn("Token Response error");
    when(oAuth2AccessTokenRespDTO.getErrorCode()).thenReturn(errorCode);
    when(oAuth2AccessTokenRespDTO.getResponseHeaders()).thenReturn(responseHeaders);

    mockOAuthServerConfiguration();
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);

    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> grantTypeValidators = new Hashtable<>();
    grantTypeValidators.put(GrantType.PASSWORD.toString(), PasswordValidator.class);

    when(oAuthServerConfiguration.getSupportedGrantTypeValidators()).thenReturn(grantTypeValidators);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");

    Response response;
    try {
        response = oAuth2TokenEndpoint.issueAccessToken(request, new MultivaluedHashMap<String, String>());
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }

    assertNotNull(response, "Token response is null");
    assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
    assertNotNull(response.getEntity(), "Response entity is null");
    assertTrue(response.getEntity().toString().contains(expectedErrorCode), "Expected error code not found");
}

From source file:org.ireland.jnetty.http.HttpServletRequestImpl.java

@Override
// OK/*w w  w.j  a  v a  2 s.  com*/
public Enumeration<String> getAttributeNames() {
    // Take a copy to prevent ConncurrentModificationExceptions if used to
    // remove attributes
    Set<String> names = new HashSet<String>();
    names.addAll(_attributes.keySet());
    return Collections.enumeration(names);
}

From source file:org.xwoot.jxta.JxtaPeer.java

/** {@inheritDoc} **/
@SuppressWarnings("unchecked")
public Enumeration<PeerGroupAdvertisement> getKnownGroups() {

    if (!this.isConnectedToNetwork()) {
        logger.warn("Not conencted to network.");
        // return empty enumeration.
        return Collections.enumeration(new ArrayList<PeerGroupAdvertisement>());
    }//  w  ww . j  a va  2 s  .  c o  m

    Enumeration en = null;
    DiscoveryService disco = rootGroup.getDiscoveryService();

    try {
        en = disco.getLocalAdvertisements(DiscoveryService.GROUP, null, null);
    } catch (Exception e) {
        logger.warn("Failed to get local group advertisements.\n", e);
        return Collections.enumeration(new ArrayList<PeerGroupAdvertisement>());
    }

    // Look for new groups to add to the local repository.
    discoverGroups(null, null);

    return (Enumeration<PeerGroupAdvertisement>) en;
}

From source file:org.globus.security.stores.PEMKeyStore.java

/**
 * Get an enumertion of all of the aliases in this keystore.
 * /*from w w w  . j  a  v  a2 s . com*/
 * @return An enumeration of the aliases in this keystore.
 */
@Override
public Enumeration<String> engineAliases() {

    return Collections.enumeration(this.aliasObjectMap.keySet());
}

From source file:com.netflix.genie.web.controllers.JobRestControllerUnitTests.java

/**
 * Make sure directory forwarding happens when all conditions are met.
 *
 * @throws IOException      on error//  www .j  ava2s .co m
 * @throws ServletException on error
 * @throws GenieException   on error
 */
@Test
public void canHandleForwardJobOutputRequestWithSuccess() throws IOException, ServletException, GenieException {
    this.jobsProperties.getForwarding().setEnabled(true);
    final String jobId = UUID.randomUUID().toString();
    final String forwardedFrom = null;
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    Mockito.doNothing().when(this.genieResourceHttpRequestHandler).handleRequest(request, response);

    final String jobHostName = UUID.randomUUID().toString();
    Mockito.when(this.jobSearchService.getJobHost(jobId)).thenReturn(jobHostName);

    //Mock parts of the http request
    final String http = "http";
    Mockito.when(request.getScheme()).thenReturn(http);
    final int port = 8080;
    Mockito.when(request.getServerPort()).thenReturn(port);
    final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString();
    Mockito.when(request.getRequestURI()).thenReturn(requestURI);

    final Set<String> headerNames = Sets.newHashSet(HttpHeaders.ACCEPT);
    Mockito.when(request.getHeaderNames()).thenReturn(Collections.enumeration(headerNames));
    Mockito.when(request.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaType.APPLICATION_JSON_VALUE);

    final String requestUrl = UUID.randomUUID().toString();
    Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(requestUrl));

    //Mock parts of forward response
    final HttpResponse forwardResponse = Mockito.mock(HttpResponse.class);
    final StatusLine statusLine = Mockito.mock(StatusLine.class);
    Mockito.when(forwardResponse.getStatusLine()).thenReturn(statusLine);
    final int successCode = 200;
    Mockito.when(statusLine.getStatusCode()).thenReturn(successCode);
    final Header contentTypeHeader = Mockito.mock(Header.class);
    Mockito.when(contentTypeHeader.getName()).thenReturn(HttpHeaders.CONTENT_TYPE);
    Mockito.when(contentTypeHeader.getValue()).thenReturn(MediaType.TEXT_PLAIN_VALUE);
    Mockito.when(forwardResponse.getAllHeaders()).thenReturn(new Header[] { contentTypeHeader });

    final String text = UUID.randomUUID().toString() + UUID.randomUUID().toString()
            + UUID.randomUUID().toString();
    final ByteArrayInputStream bis = new ByteArrayInputStream(text.getBytes(UTF_8));
    final HttpEntity entity = Mockito.mock(HttpEntity.class);
    Mockito.when(entity.getContent()).thenReturn(bis);
    Mockito.when(forwardResponse.getEntity()).thenReturn(entity);

    final ByteArrayServletOutputStream bos = new ByteArrayServletOutputStream();
    Mockito.when(response.getOutputStream()).thenReturn(bos);

    final ClientHttpRequestFactory factory = Mockito.mock(ClientHttpRequestFactory.class);
    final ClientHttpRequest clientHttpRequest = Mockito.mock(ClientHttpRequest.class);
    Mockito.when(clientHttpRequest.execute())
            .thenReturn(new MockClientHttpResponse(text.getBytes(UTF_8), HttpStatus.OK));
    Mockito.when(clientHttpRequest.getHeaders()).thenReturn(new HttpHeaders());
    Mockito.when(factory.createRequest(Mockito.any(), Mockito.any())).thenReturn(clientHttpRequest);
    final RestTemplate template = new RestTemplate(factory);
    final Registry registry = Mockito.mock(Registry.class);
    final Counter counter = Mockito.mock(Counter.class);
    Mockito.when(registry.counter(Mockito.anyString())).thenReturn(counter);

    final JobRestController jobController = new JobRestController(Mockito.mock(JobCoordinatorService.class),
            this.jobSearchService, Mockito.mock(AttachmentService.class),
            Mockito.mock(ApplicationResourceAssembler.class), Mockito.mock(ClusterResourceAssembler.class),
            Mockito.mock(CommandResourceAssembler.class), Mockito.mock(JobResourceAssembler.class),
            Mockito.mock(JobRequestResourceAssembler.class), Mockito.mock(JobExecutionResourceAssembler.class),
            Mockito.mock(JobSearchResultResourceAssembler.class), this.hostname, template,
            this.genieResourceHttpRequestHandler, this.jobsProperties, registry);
    jobController.getJobOutput(jobId, forwardedFrom, request, response);

    Assert.assertThat(new String(bos.toByteArray(), UTF_8), Matchers.is(text));
    Mockito.verify(request, Mockito.times(1)).getHeader(HttpHeaders.ACCEPT);
    Mockito.verify(this.jobSearchService, Mockito.times(1)).getJobHost(Mockito.eq(jobId));
    Mockito.verify(response, Mockito.never()).sendError(Mockito.anyInt());
    Mockito.verify(this.genieResourceHttpRequestHandler, Mockito.never()).handleRequest(request, response);
}

From source file:password.pwm.util.Helper.java

public static Properties newSortedProperties() {
    return new Properties() {
        public synchronized Enumeration<Object> keys() {
            return Collections.enumeration(new TreeSet<>(super.keySet()));
        }//from ww  w .  ja v a2  s  . co  m
    };
}

From source file:org.apache.shindig.common.testing.FakeHttpServletRequest.java

public Enumeration<?> getAttributeNames() {
    return Collections.enumeration(attributes.keySet());
}

From source file:org.springframework.ldap.core.DistinguishedName.java

public Enumeration getAll() {
    LinkedList strings = new LinkedList();
    for (Iterator iter = names.iterator(); iter.hasNext();) {
        LdapRdn rdn = (LdapRdn) iter.next();
        strings.add(rdn.getLdapEncoded());
    }//w w w. j a v  a  2s.  c o m

    return Collections.enumeration(strings);
}

From source file:de.ingrid.ibus.comm.registry.Registry.java

private void loadProperties() {
    try {/*  w ww  .j  av a2 s  .c om*/
        FileInputStream fis = new FileInputStream(this.fFile);

        // create a sorted properties file
        this.fActivatedIplugs = new Properties() {
            private static final long serialVersionUID = 6956076060462348684L;

            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(new TreeSet<>(super.keySet()));
            }
        };

        this.fActivatedIplugs.load(fis);
        fis.close();
    } catch (IOException e) {
        if (fLogger.isErrorEnabled()) {
            fLogger.error("Cannot load the activation properties.", e);
        }
    }
}