Example usage for org.apache.commons.collections IteratorUtils toArray

List of usage examples for org.apache.commons.collections IteratorUtils toArray

Introduction

In this page you can find the example usage for org.apache.commons.collections IteratorUtils toArray.

Prototype

public static Object[] toArray(Iterator iterator) 

Source Link

Document

Gets an array based on an iterator.

Usage

From source file:com.example.ManualSpnegoNegotiateServlet.java

/**
 * Use of Kerberos is wrapped in an HTTP auth-scheme of "Negotiate" [RFC 4559].
 *
 * The auth-params exchanged use data formats defined for use with the GSS-API [RFC 2743]. In particular, they follow the formats set for the SPNEGO [RFC 4178] and
 * Kerberos [RFC 4121] mechanisms for GSSAPI. The "Negotiate" auth-scheme calls for the use of SPNEGO GSSAPI tokens that the specific mechanism type specifies.
 *
 * The current implementation of this protocol is limited to the use of SPNEGO with the Kerberos protocol.
 *
 * @param request//w  w w.  java 2 s .c o m
 * @param response
 * @throws ServletException
 *
 * @return true upon successful authentication, false otherwise
 */
protected boolean attemptNegotiation(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, UnsupportedEncodingException, IOException {
    log.debug("Attempting negotiation.");

    String header = request.getHeader("Authorization");

    /**
     * Guard clause to check for Negotiate header.
     *
     * If the server receives a request for an access-protected object, and if an acceptable Authorization header has not been sent, the server responds with a "401
     * Unauthorized" status code, and a "WWW-Authenticate:" header as per the framework described in [RFC 2616]. The initial WWW-Authenticate header will not carry
     * any gssapi-data.
     */
    if (header == null || header.length() < 10 || !header.startsWith("Negotiate ")) {
        response.setHeader("WWW-Authenticate", "Negotiate");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        log.debug("Proper authorization header not found, returning challenge.");
        return false;
    }

    /**
     * A client may initiate a connection to the server with an "Authorization" header containing the initial token for the server. This form will bypass the initial
     * 401 error from the server when the client knows that the server will accept the Negotiate HTTP authentication type.
     */
    log.debug("Authorization header found, continuing negotiation.");

    /**
     * The data following the word Negotiate is the GSS-API data to process.
     */
    byte gssapiData[] = Base64.decode(header.substring(10));

    log.debug("GSS API data: " + Arrays.toString(gssapiData));

    /**
     * Guard clause to check for the unsupported NTLM authentication mechanism.
     */
    if (isNtlmMechanism(gssapiData)) {
        log.warn("Got request for unsupported NTLM mechanism, aborting negotiation.");
        return false;
    }

    /**
     * The server attempts to establish a security context. Establishment may result in tokens that the server must return to the client. Tokens are BASE-64 encoded
     * GSS-API data.
     */
    GSSContext gssContext = null;
    LoginContext loginContext = null;
    String outToken = null;

    try {
        final String domainUsername = "Zeus";
        final String domainUserPassword = "Z3usP@55";
        final CallbackHandler handler = SpnegoProvider.getUsernamePasswordHandler(domainUsername,
                domainUserPassword);

        loginContext = new LoginContext("spnego-server", handler);
        loginContext.login();
        Subject subject = loginContext.getSubject();

        Oid spnegoOid = new Oid("1.3.6.1.5.5.2"); // for spnego answers
        Oid kerbv5Oid = new Oid("1.2.840.113554.1.2.2"); // for chromium (they send a kerbv5 token instead of spnego)
        final Oid[] oids = new Oid[] { spnegoOid, kerbv5Oid };

        final GSSManager manager = GSSManager.getInstance();
        final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {
            public GSSCredential run() throws GSSException {
                return manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, oids,
                        GSSCredential.ACCEPT_ONLY);
            }
        };

        GSSCredential serverCreds = Subject.doAs(subject, action);

        log.debug("Mechs: " + Arrays.toString(serverCreds.getMechs()));

        gssContext = manager.createContext(serverCreds);

        log.debug("Context created. " + gssContext);

        byte tokenBytes[] = gssContext.acceptSecContext(gssapiData, 0, gssapiData.length);
        outToken = Base64.encode(tokenBytes);
    } catch (PrivilegedActionException ex) {
        log.error("", ex);
    } catch (LoginException ex) {
        log.error("", ex);
    } catch (GSSException gsse) {
        gsse.printStackTrace();
        log.error("GSSException:       " + gsse.getMessage());
        log.error("GSSException major: " + gsse.getMajorString());
        log.error("GSSException minor: " + gsse.getMinorString());
        throw new ServletException(gsse);
    }

    /**
     * If the context is established, we can attempt to retrieve the name of the "context initiator." In the case of the Kerberos mechanism, the context initiator is
     * the Kerberos principal of the client. Additionally, the client may be delegating credentials.
     */
    if (gssContext != null && gssContext.isEstablished()) {
        log.debug("Context established, attempting Kerberos principal retrieval.");

        try {
            Subject subject = new Subject();
            GSSName clientGSSName = gssContext.getSrcName();
            KerberosPrincipal clientPrincipal = new KerberosPrincipal(clientGSSName.toString());
            subject.getPrincipals().add(clientPrincipal);
            log.info("Got client Kerberos principal: " + clientGSSName);
            response.getWriter().println("Hello, " + clientPrincipal);

            /**
             * Retrieve LogonInfo (for example, GroupSIDs) from the PAC Authorization Data
             * from a Kerberos Ticket that was issued by Active Directory.
             */
            byte[] kerberosTokenData = gssapiData;
            try {
                SpnegoToken token = SpnegoToken.parse(gssapiData);
                kerberosTokenData = token.getMechanismToken();
            } catch (DecodingException dex) {
                // Chromium bug: sends a Kerberos response instead of an spnego response with a Kerberos mechanism
            } catch (Exception ex) {
                log.error("", ex);
            }

            try {
                Object[] keyObjs = IteratorUtils
                        .toArray(loginContext.getSubject().getPrivateCredentials(KerberosKey.class).iterator());
                KerberosKey[] keys = new KerberosKey[keyObjs.length];
                System.arraycopy(keyObjs, 0, keys, 0, keyObjs.length);

                KerberosToken token = new KerberosToken(kerberosTokenData, keys);
                log.info("Authorizations: ");
                for (KerberosAuthData authData : token.getTicket().getEncData().getUserAuthorizations()) {
                    if (authData instanceof KerberosPacAuthData) {
                        PacSid[] groupSIDs = ((KerberosPacAuthData) authData).getPac().getLogonInfo()
                                .getGroupSids();
                        log.info("GroupSids: " + Arrays.toString(groupSIDs));
                        response.getWriter().println("Found group SIDs: " + Arrays.toString(groupSIDs));
                    } else {
                        log.info("AuthData without PAC: " + authData.toString());
                    }
                }
            } catch (Exception ex) {
                log.error("", ex);
            }

            if (gssContext.getCredDelegState()) {
                GSSCredential delegateCredential = gssContext.getDelegCred();
                GSSName delegateGSSName = delegateCredential.getName();
                Principal delegatePrincipal = new KerberosPrincipal(delegateGSSName.toString());
                subject.getPrincipals().add(delegatePrincipal);
                subject.getPrivateCredentials().add(delegateCredential);
                log.info("Got delegated Kerberos principal: " + delegateGSSName);
            }

            /**
             * A status code 200 status response can also carry a "WWW-Authenticate" response header containing the final leg of an authentication. In this case, the
             * gssapi-data will be present.
             */
            if (outToken != null && outToken.length() > 0) {
                response.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
                response.setStatus(HttpServletResponse.SC_OK);
                log.debug("Returning final authentication data to client to complete context.");
                log.debug("Negotiation completed.");
                return true;
            }
        } catch (GSSException gsse) {
            log.error("GSSException:       " + gsse.getMessage());
            log.error("GSSException major: " + gsse.getMajorString());
            log.error("GSSException minor: " + gsse.getMinorString());

            response.addHeader("Client-Warning", gsse.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } else {
        /**
         * Any returned code other than a success 2xx code represents an authentication error. If a 401 containing a "WWW-Authenticate" header with "Negotiate" and
         * gssapi-data is returned from the server, it is a continuation of the authentication request.
         */
        if (outToken != null && outToken.length() > 0) {
            response.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.debug("Additional authentication processing required, returning token.");
            return false;
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("Kerberos negotiation failed.");
        }
    }

    log.debug("Negotiation completed.");

    return true;
}

From source file:org.amanzi.awe.statistics.ui.table.StatisticsTableProvider.java

@Override
public Object[] getElements(final Object inputElement) {
    if ((filter.getPeriod() != null) && (inputElement instanceof IStatisticsModel)) {
        IStatisticsModel statisticsModel = (IStatisticsModel) inputElement;
        try {//from w  ww.j av  a  2 s  . c  o  m
            return IteratorUtils
                    .toArray(statisticsModel.getStatisticsRowsInTimeRange(filter.getPeriod().getId(),
                            filter.getStartTime(), filter.getEndTime()).iterator());
        } catch (ModelException e) {
            LOGGER.error("Error on getting Statistics Table content", e);
        }
    }
    return ArrayUtils.EMPTY_OBJECT_ARRAY;
}

From source file:org.amanzi.awe.ui.tree.provider.AWETreeContentProvider.java

private <T extends ITreeItem> Object[] toObject(final Iterator<T> itemIterator) {
    return IteratorUtils.toArray(itemIterator);
}

From source file:org.apache.metron.dataloads.bulk.ElasticsearchDataPruner.java

@Override
public Long prune() throws IOException {

    try {// ww w .ja v a2 s  .co  m

        configuration.update();

    } catch (Exception e) {

        LOG.error("Unable to update configs", e);

    }

    String dateString = configuration.getGlobalConfig().get("es.date.format").toString();

    if (null != dateString) {
        dateFormat = new SimpleDateFormat(dateString);
    }

    ImmutableOpenMap<String, IndexMetaData> allIndices = indexClient.admin().cluster().prepareState().get()
            .getState().getMetaData().getIndices();
    Iterable indicesForDeletion = getFilteredIndices(allIndices);
    Object[] indexArray = IteratorUtils.toArray(indicesForDeletion.iterator());

    if (indexArray.length > 0) {
        String[] indexStringArray = new String[indexArray.length];
        System.arraycopy(indexArray, 0, indexStringArray, 0, indexArray.length);
        deleteIndex(indexClient.admin(), indexStringArray);
    }

    return (long) indexArray.length;

}

From source file:org.apache.metron.dataloads.bulk.ElasticsearchDataPruner.java

protected Iterable<String> getFilteredIndices(ImmutableOpenMap<String, IndexMetaData> indices) {

    String[] returnedIndices = new String[indices.size()];
    Iterator it = indices.keysIt();
    System.arraycopy(IteratorUtils.toArray(it), 0, returnedIndices, 0, returnedIndices.length);
    Iterable<String> matches = Iterables.filter(Arrays.asList(returnedIndices), filterWithRegex);

    return matches;

}

From source file:org.apache.metron.dataloads.bulk.ElasticsearchDataPrunerTest.java

@Test
public void testFilter() throws Exception {

    ObjectObjectHashMap<String, IndexMetaData> indexNames = new ObjectObjectHashMap();
    SimpleDateFormat dateChecker = new SimpleDateFormat("yyyyMMdd");
    int numDays = 5;
    String[] expectedIndices = new String[24];
    Date indexDate = new Date();

    indexDate.setTime(testDate.getTime() - TimeUnit.DAYS.toMillis(numDays));

    for (int i = 0, j = 0; i < numDays * 24; i++) {

        String indexName = "sensor_index_" + dateFormat.format(indexDate);
        //Delete 20160330
        if (dateChecker.format(indexDate).equals("20160330")) {
            expectedIndices[j++] = indexName;
        }/*from   w w w  .j  a v a  2  s.c o  m*/

        indexNames.put(indexName, null);
        indexDate.setTime(indexDate.getTime() + TimeUnit.HOURS.toMillis(1));

    }

    ImmutableOpenMap<String, IndexMetaData> testIndices = ImmutableOpenMap.copyOf(indexNames);

    ElasticsearchDataPruner pruner = new ElasticsearchDataPruner(testDate, 1, configuration, indexClient,
            "sensor_index_");
    pruner.indexClient = indexClient;

    Iterable<String> filteredIndices = pruner.getFilteredIndices(testIndices);

    Object[] indexArray = IteratorUtils.toArray(filteredIndices.iterator());
    Arrays.sort(indexArray);
    Arrays.sort(expectedIndices);

    assertArrayEquals(expectedIndices, indexArray);

}

From source file:org.apache.predictionio.examples.java.recommendations.tutorial3.Evaluator.java

@Override
public String evaluateAll(Iterable<Tuple2<Object, Double>> input) {
    return Arrays.toString(IteratorUtils.toArray(input.iterator()));
}

From source file:org.apache.sling.scripting.javascript.wrapper.ScriptableResource.java

public NativeArray jsFunction_getChildren() {
    return new NativeArray(IteratorUtils.toArray(resource.listChildren()));
}

From source file:org.apache.solr.search.xjoin.simple.TestSimpleXJoinResultsFactory.java

@Test(expected = PathNotFoundException.class)
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testNoJoinIdsAtPath() throws IOException {
    NamedList args = new NamedList();
    args.add(SimpleXJoinResultsFactory.INIT_PARAM_TYPE, SimpleXJoinResultsFactory.Type.JSON.toString());
    args.add(SimpleXJoinResultsFactory.INIT_PARAM_ROOT_URL, getClass().getResource("results.json").toString());

    NamedList globalPaths = new NamedList();
    args.add(SimpleXJoinResultsFactory.INIT_PARAM_GLOBAL_FIELD_PATHS, globalPaths);
    globalPaths.add("total", "$.count");

    args.add(SimpleXJoinResultsFactory.INIT_PARAM_JOIN_ID_PATH, "$.no.ids.at.this.path");

    SimpleXJoinResultsFactory factory = new SimpleXJoinResultsFactory();
    factory.init(args);//from  w ww.  ja v  a2s.  c  o  m

    SolrParams params = new ModifiableSolrParams();
    XJoinResults<String> results = factory.getResults(params);

    assertEquals(0, IteratorUtils.toArray(results.getJoinIds().iterator()).length);
}

From source file:org.metaabm.impl.SContextImpl.java

public EList<EObject> getAllAgents() {
    Object[] all = IteratorUtils.toArray(allAgentsTree());
    return new EcoreEList.UnmodifiableEList.FastCompare<EObject>(this,
            MetaABMPackage.Literals.IVALUE__ACCESSORS, all.length, all);
}