Example usage for org.apache.commons.lang ArrayUtils reverse

List of usage examples for org.apache.commons.lang ArrayUtils reverse

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils reverse.

Prototype

public static void reverse(boolean[] array) 

Source Link

Document

Reverses the order of the given array.

Usage

From source file:org.apache.usergrid.rest.applications.collection.activities.PagingEntitiesTest.java

@Test //USERGRID-266
public void pageThroughConnectedEntities() {

    CustomCollection activities = context.collection("activities");

    long created = 0;
    int maxSize = 1500;
    long[] verifyCreated = new long[maxSize];
    Map actor = hashMap("displayName", "Erin");
    Map props = new HashMap();

    props.put("actor", actor);
    props.put("verb", "go");

    for (int i = 0; i < maxSize; i++) {

        props.put("ordinal", i);
        JsonNode activity = activities.create(props);
        verifyCreated[i] = activity.findValue("created").getLongValue();
        if (i == 0) {
            created = activity.findValue("created").getLongValue();
        }/*from  w  w  w.  j ava2  s . co  m*/
    }
    ArrayUtils.reverse(verifyCreated);
    String query = "select * where created >= " + created;

    JsonNode node = activities.query(query, "limit", "2"); //activities.query(query,"");
    int index = 0;
    while (node.get("entities").get("created") != null) {
        assertEquals(2, node.get("entities").size());

        if (node.get("cursor") != null) {
            node = activities.query(query, "cursor", node.get("cursor").toString());
        }

        else {
            break;
        }
    }
}

From source file:org.apache.usergrid.rest.applications.queries.OrderByTest.java

/**
 * Ensure that results are returned in the correct descending order, when specified
 * 1. Insert a number of entities and add them to an array
 * 2. Query for the entities in descending order
 * 3. Validate that the order is correct
 *
 * @throws IOException//www  .j  a  v  a2s  .  c o  m
 */
@Test
public void orderByReturnCorrectResults() throws IOException {

    int size = 20;
    Entity[] activities = new Entity[size];

    Entity actor = new Entity();
    actor.put("displayName", "Erin");
    Entity props = new Entity();
    props.put("actor", actor);
    props.put("verb", "go");
    props.put("content", "bragh");
    //1. Insert a number of entities and add them to an array
    for (int i = 0; i < size; i++) {
        props.put("ordinal", i);
        Entity e = this.app().collection("activity").post(props);
        activities[i] = e;
        logger.info(String.valueOf(e.get("uuid").toString()));
        logger.info(String.valueOf(Long.parseLong(activities[0].get("created").toString())));
    }

    refreshIndex();

    ArrayUtils.reverse(activities);
    long lastCreated = Long.parseLong(activities[0].get("created").toString());
    //2. Query for the entities in descending order
    String errorQuery = String.format("select * where created <= %d order by created desc", lastCreated);
    int index = 0;

    QueryParameters params = new QueryParameters().setQuery(errorQuery);
    Collection activitiesResponse = this.app().collection("activities").get(params);
    //3. Validate that the order is correct
    do {
        int returnSize = activitiesResponse.getResponse().getEntityCount();
        //loop through the current page of results
        for (int i = 0; i < returnSize; i++, index++) {
            assertEquals((activities[index]).get("uuid").toString(),
                    activitiesResponse.getResponse().getEntities().get(i).get("uuid").toString());
        }
        //grab the next page of results
        activitiesResponse = this.app().collection("activities").getNextPage(activitiesResponse, params, true);
    } while (activitiesResponse.getCursor() != null);
}

From source file:org.bensteele.jirrigate.Console.java

private void printIrrigationResults(String input) {
    for (Controller c : irrigator.getControllers()) {
        if (input.toLowerCase().contains(c.getName().toLowerCase())) {
            String[] amountString = input.split("results last ");
            int duration = Integer.parseInt(amountString[1]);
            IrrigationResult[] results = (IrrigationResult[]) c.getIrrigationResults().toArray();
            ArrayUtils.reverse(results);
            for (int i = 0; i < duration; i++) {
                // Don't let the array go out of bounds.
                if (i == results.length) {
                    break;
                }//from ww  w  .  j a va 2 s.  co m
                System.out.println("\n" + results[i]);
            }
        }
    }
}

From source file:org.carrot2.clustering.synthetic.ByUrlClusteringAlgorithm.java

/**
 * For each documents builds an array of parts of their corresponding URLs.
 *//*from  ww w . ja v  a2 s  .c o m*/
final String[][] buildUrlParts(final Document[] documents) {
    final String[][] urlParts = new String[documents.length][];
    for (int i = 0; i < documents.length; i++) {
        final String url = documents[i].getField(Document.CONTENT_URL);
        if (url == null) {
            continue;
        }

        int colonSlashSlashIndex = url.indexOf("://");
        if (colonSlashSlashIndex < 0) {
            colonSlashSlashIndex = 0;
        } else if (colonSlashSlashIndex + 3 >= url.length()) {
            continue;
        } else {
            colonSlashSlashIndex += 3;
        }

        int slashIndex = url.indexOf('/', colonSlashSlashIndex + 3);
        if (slashIndex < 0) {
            slashIndex = url.length();
        }

        final String urlMainPart = url.substring(colonSlashSlashIndex, slashIndex).toLowerCase();

        final String[] splitUrl = urlMainPart.split("\\.");
        ArrayUtils.reverse(splitUrl);
        urlParts[i] = splitUrl;
    }

    return urlParts;
}

From source file:org.cesecore.certificates.util.DnComponents.java

/**
 * Returns the reversed dnObjects./*from  www. ja  v  a 2s  .  c om*/
 * Protected to allow testing
 */
protected static String[] getDnObjectsReverse() {
    // Create and reverse the order if it has not been initialized already
    if (dNObjectsReverse == null) {
        // this cast is not needed in java 5, but is needed for java 1.4
        dNObjectsReverse = (String[]) dNObjectsForward.clone();
        ArrayUtils.reverse(dNObjectsReverse);
    }
    return dNObjectsReverse;
}

From source file:org.eclipse.dataset.slicer.SliceNDGenerator.java

private static int[] getDimensionSortingArray(final int rank, final int[] incrementOrder) {
    final int[] full = new int[rank];
    int[] rev = incrementOrder.clone();
    ArrayUtils.reverse(rev);

    for (int i = rank - 1, j = 0; i > 0; i--) {
        if (!ArrayUtils.contains(incrementOrder, i)) {
            full[j++] = i;/*  ww  w  .j  a v a 2 s . c o m*/
        }
    }

    for (int i = rank - incrementOrder.length; i < rank; i++) {
        full[i] = rev[incrementOrder.length + i - rank];
    }

    return full;
}

From source file:org.eclipse.wb.internal.core.databinding.ui.EditSelection.java

/**
 * @return the path for given object in elements tree.
 *///from   w w  w .j a v a2s .  co m
private static int[] objectToPath(ITreeContentProvider provider, Object[] input, Object object) {
    if (object == null) {
        return ArrayUtils.EMPTY_INT_ARRAY;
    }
    ArrayIntList pathList = new ArrayIntList();
    while (true) {
        Object parent = provider.getParent(object);
        if (parent == null) {
            pathList.add(ArrayUtils.indexOf(input, object));
            break;
        }
        pathList.add(ArrayUtils.indexOf(provider.getChildren(parent), object));
        object = parent;
    }
    int[] path = pathList.toArray();
    ArrayUtils.reverse(path);
    return path;
}

From source file:org.eclipse.wb.internal.core.editor.ObjectPathHelper.java

/**
 * @return the path for given object in components tree.
 *//*from  w ww . ja v  a2  s .c  o  m*/
private int[] getObjectPath(Object object) {
    ArrayIntList path = new ArrayIntList();
    while (true) {
        Object parent = m_componentsProvider.getParent(object);
        if (parent == null) {
            break;
        }
        // add index
        int index = ArrayUtils.indexOf(m_componentsProvider.getChildren(parent), object);
        path.add(index);
        // go to parent
        object = parent;
    }
    // convert to array
    int[] finalPath = path.toArray();
    ArrayUtils.reverse(finalPath);
    return finalPath;
}

From source file:org.ejbca.ui.web.pub.CertDistServlet.java

private void handleCaChainCommands(AuthenticationToken administrator, String issuerdn, int caid, String format,
        HttpServletResponse res) throws IOException, NoSuchFieldException {
    try {/*from  w w w  . j av  a  2s  .  co  m*/
        Certificate[] chain = getCertificateChain(administrator, caid, issuerdn);
        // Reverse the chain to get proper ordering for chain file
        // (top-level CA first, requested CA last).
        ArrayUtils.reverse(chain);

        // Construct the filename based on requested CA. Fail-back to
        // name "ca-chain.EXT".
        String filename = RequestHelper.getFileNameFromCertNoEnding(chain[chain.length - 1], "ca") + "-chain."
                + format.toLowerCase();

        byte[] outbytes = new byte[0];
        // Encode and send back
        if ((format == null) || StringUtils.equalsIgnoreCase(format, "pem")) {
            outbytes = CertTools.getPemFromCertificateChain(Arrays.asList(chain));
        } else {
            // Create a JKS truststore with the CA certificates in
            final KeyStore store = KeyStore.getInstance("JKS");
            store.load(null, null);
            for (int i = 0; i < chain.length; i++) {
                String cadn = CertTools.getSubjectDN(chain[i]);
                String alias = CertTools.getPartFromDN(cadn, "CN");
                if (alias == null) {
                    alias = CertTools.getPartFromDN(cadn, "O");
                }
                if (alias == null) {
                    alias = "cacert" + i;
                }
                alias = StringUtils.replaceChars(alias, ' ', '_');
                alias = StringUtils.substring(alias, 0, 15);
                store.setCertificateEntry(alias, chain[i]);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                store.store(out, "changeit".toCharArray());
                out.close();
                outbytes = out.toByteArray();
            }
        }
        // We must remove cache headers for IE
        ServletUtils.removeCacheHeaders(res);
        res.setHeader("Content-disposition",
                "attachment; filename=\"" + StringTools.stripFilename(filename) + "\"");
        res.setContentType("application/octet-stream");
        res.setContentLength(outbytes.length);
        res.getOutputStream().write(outbytes);
        log.debug("Sent CA certificate chain to client, len=" + outbytes.length + ".");
    } catch (CertificateEncodingException e) {
        log.debug("Error getting CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting CA certificate chain.");
    } catch (KeyStoreException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (NoSuchAlgorithmException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (CertificateException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (EJBException e) {
        log.debug("CA does not exist: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND,
                "CA does not exist: " + HTMLTools.htmlescape(e.getMessage()));
    } catch (AuthorizationDeniedException e) {
        log.debug("Authotization denied: ", e);
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Authorization denied: " + HTMLTools.htmlescape(e.getMessage()));
    }
}

From source file:org.eurekastreams.server.service.actions.strategies.activity.IterpolationListColliderTest.java

/**
 * Test collision collding 100 sorted items with 10 unsorted items..
 * //from   w  w  w.  j  ava 2  s. co m
 * @throws FileNotFoundException
 *             if the file is not found.
 */
@Test
public final void testCollision100x10() throws FileNotFoundException {
    final Long[] sorted = fileToList(ITEMS_100_SORTED_FILE, ONE_HUNDRED);

    // Method that generates array does it the ascending, switch to descending.
    ArrayUtils.reverse(sorted);

    // Contains some known items in the list.
    final Long[] unsorted = { 508L, 25L, 251L, 413L, 500L, 795L, 1L, 990L, 2L };

    collideTest(sorted, unsorted, ONE_HUNDRED);
}