Example usage for java.util List lastIndexOf

List of usage examples for java.util List lastIndexOf

Introduction

In this page you can find the example usage for java.util List lastIndexOf.

Prototype

int lastIndexOf(Object o);

Source Link

Document

Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

Usage

From source file:MainClass.java

public static void main(String[] a) {
    List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
    System.out.println(list.lastIndexOf("A"));
}

From source file:opendap.metacat.NCMLWriter.java

public static void main(String[] args) {
    // There has to be a better way...
    likelyServerNames.add("opendap");
    likelyServerNames.add("hyrax");
    likelyServerNames.add("dap");
    likelyServerNames.add("data");

    CommandLineParser parser = new PosixParser();

    Options options = new Options();

    options.addOption("v", "verbose", false, "Write info to stdout");
    options.addOption("V", "very-verbose", false, "Write NCML to stdout");
    options.addOption("h", "help", false, "Usage information");

    options.addOption("n", "groups-name", true, "URLGroups name prefix");
    options.addOption("o", "output", false, "Write NCML files using the groupName name and a counter.");
    // options.addOption("d", "dir", true, "Write NCML files to this directory.");

    try {/*from   ww w .  j  a  v a2  s  .co  m*/
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("NCMLWriter [options] --groups-name <name prefix>", options);
            return;
        }

        boolean verbose = line.hasOption("verbose");
        boolean veryVerbose = line.hasOption("very-verbose");
        PrintStream ps = System.out;

        // Extract options
        String groupsName = line.getOptionValue("groups-name");
        if (groupsName == null || groupsName.isEmpty())
            throw new Exception("The calssifier must have a URLGroups file name.");
        if (verbose)
            ps.println("Groups file: " + groupsName);

        boolean output = line.hasOption("output");

        // Build objects
        DDXRetriever ddxRetriever = new DDXRetriever(true, groupsName);

        multifileNCMLBuilder = new NCMLBuilder(groupsName, "many_ddx2ncml-1.0.xsl");

        if (verbose)
            ps.println("(" + infoLogSdf.format(new Date()) + ") Reading groups");

        URLGroups groups = new URLGroups();
        groups.restoreState(groupsName);

        factBase = new HashMap<URLGroup, URLGroupFacts>();

        if (verbose)
            ps.println("(" + infoLogSdf.format(new Date()) + ") Begining analysis of groups");

        // initialize the fact base.
        Integer count = 0;
        for (URLGroup group : groups) {
            String ddxURL = group.getURLs().get(0).getTheURL();
            factBase.put(group, new URLGroupFacts(ddxURL, ddxRetriever.getDDXDoc(ddxURL)));
            count++;
        }

        // Look at each group and decide if it can be aggregated.
        /*
        for (URLGroup group: groups) {
                   
        }
        */

        if (verbose)
            ps.println("(" + infoLogSdf.format(new Date()) + ") " + count.toString() + " groups.");

        // Find multifile groups
        count = 0;
        for (URLGroup group : groups) {
            if (group.getURLs().size() > 1) {
                factBase.get(group).setIsMultiFile(true);
                count++;
            }
        }

        if (verbose)
            ps.println("(" + infoLogSdf.format(new Date()) + ") " + count.toString() + " multifile groups.");

        // Find multifile groups with a date equivalence
        count = 0;
        for (URLGroup group : groups) {
            if (factBase.get(group).getIsMultiFile() && group.getDateEquivalence() != null) {
                factBase.get(group).setIsTimeSeries(true);

                SortedValues sortedDates = group.getDateEquivalence().getSortedValues();

                DateString first = sortedDates.get(0);
                DateString last = sortedDates.get(sortedDates.size() - 1);

                factBase.get(group).setFirstDate(iso_8601_sdf.format(first.getDate()));
                factBase.get(group).setLastDate(iso_8601_sdf.format(last.getDate()));

                count++;
            }
        }

        if (verbose)
            ps.println("(" + infoLogSdf.format(new Date()) + ") " + count.toString()
                    + " multifile groups with date equivalence classes.");

        // For groups that have multiple files, find various pathnames
        for (URLGroup group : groups) {
            String DDXURL = factBase.get(group).getFirstDDXURL();
            int serverNameEndPosition = findServerNameEnd(DDXURL);
            log.debug("serverNameEndPosition: " + serverNameEndPosition);

            int serverRootPosition = findServerRootPosition(group, serverNameEndPosition);
            log.debug("serverRootPosition: " + serverRootPosition);

            factBase.get(group).setServerRootPosition(serverRootPosition);

            int dataRootPosition = findDataRootPosition(group, serverNameEndPosition);
            log.debug("dataRootPosition: " + dataRootPosition);

            log.debug("DDX (length: " + DDXURL.length() + "): " + DDXURL);
            int len = DDXURL.length();
            // The monkey shines here guard against the case where a single
            // file dataset's dataRootPosition is past the en of the URL.
            String dataRoot = DDXURL.substring(serverRootPosition,
                    (dataRootPosition > len) ? len : dataRootPosition);
            log.debug("DDX: " + DDXURL + "; dataset scan: " + dataRoot);

            factBase.get(group).setDatasetRoot(dataRoot);
        }

        // Check for things that are unique, like dataRoot - for each group
        // is its value of dataRoot Unique?

        // Put all the dataRoot paths in a list
        List<String> dataRootList = new ArrayList<String>();
        ;
        for (URLGroup group : groups) {
            dataRootList.add(factBase.get(group).getDatasetRoot());
        }

        // ... now test to see if the first and last occurrence are the same
        for (URLGroup group : groups) {
            String dr = factBase.get(group).getDatasetRoot();
            if (dataRootList.indexOf(dr) == dataRootList.lastIndexOf(dr))
                factBase.get(group).setIsDatasetRootUnique(true);
            else
                factBase.get(group).setIsDatasetRootUnique(false);
        }

        // now build some NCML
        if (verbose)
            ps.println("(" + infoLogSdf.format(new Date()) + ") Building NCML");

        Integer output_counter = 0;
        for (URLGroup group : groups) {
            String ncmlDoc = null;

            if (factBase.get(group).getIsTimeSeries()) {
                if (verbose)
                    ps.println("(" + infoLogSdf.format(new Date()) + ") Start building NCML");

                ncmlDoc = buildExplicitNCMLForTimeSeries(group);

                if (verbose)
                    ps.println("(" + infoLogSdf.format(new Date()) + ") End building NCML");

                if (veryVerbose)
                    ps.println("(" + infoLogSdf.format(new Date()) + ") NCML: " + ncmlDoc);
            }

            if (output && ncmlDoc != null && !ncmlDoc.isEmpty()) {
                output_counter++;
                FileWriter fw;
                String dr = factBase.get(group).getDatasetRoot();
                dr = dr.replace('/', '_');
                if (dr.charAt(dr.length() - 1) == '_')
                    dr = dr.substring(0, dr.length() - 1);
                if (factBase.get(group).getIsDatasetRootUnique())
                    fw = new FileWriter(dr + ".ncml");
                else
                    fw = new FileWriter(dr + "_" + output_counter.toString() + ".ncml");

                fw.write(ncmlDoc);
                fw.close();
            }

            // delete document just written 
            // ncmlDoc = null;
        }
    } catch (Exception e) {
        System.err.println("Error: " + e.getLocalizedMessage());
        e.printStackTrace();
        return;
    }
}

From source file:Main.java

/**
 * Removes all occurrences of <code>e</code> from <code>c</code>.
 * /*from  w w w.  j a va2s .  c  o m*/
 * @param c the <code>Collection</code>
 * @param e the element to remove
 */
public static <T> void removeAll(Collection<?> c, Object e) {
    if (c instanceof List) {
        List<?> list = (List<?>) c;

        int index = -1;
        do {
            index = list.lastIndexOf(e);
            if (index != -1)
                list.remove(index);
        } while (index != -1);

    } else if (c instanceof Set) {
        c.remove(e);
    } else {
        while (c.remove(e))
            ;
    }
}

From source file:org.eclipse.jdt.ls.core.internal.managers.InvisibleProjectImporter.java

private static String inferPackageNameFromPath(IPath javaFile, IPath workspaceRoot) {
    IPath parentPath = javaFile.removeTrailingSeparator().removeLastSegments(1);
    List<String> segments = Arrays.asList(parentPath.segments());
    int index = segments.lastIndexOf(JDTUtils.SRC);
    if (index > -1) {
        return String.join(JDTUtils.PERIOD, segments.subList(index + 1, segments.size()));
    }/*from   w  w w. j  a  v a2s.c o m*/

    IPath relativePath = parentPath.makeRelativeTo(workspaceRoot);
    return String.join(JDTUtils.PERIOD, relativePath.segments());
}

From source file:org.jbpm.graph.exe.ExecutionContext.java

public static void popCurrentContext(ExecutionContext executionContext) {
    List stack = getContextStack();
    int index = stack.lastIndexOf(executionContext);
    if (index == -1) {
        log.warn(executionContext + " was not found in thread-local stack;"
                + " do not access ExecutionContext instances from multiple threads");
    } else {/*from  w w w.ja va  2  s.c  o m*/
        if (index < stack.size() - 1) {
            log.warn(executionContext + " was not popped in reverse push order;"
                    + " make sure you pop every context you push");
        }
        // remove execution context from stack, no matter what
        stack.remove(index);
    }
}

From source file:org.hyperic.hq.ui.util.DashboardUtils.java

public static boolean addEntityToPreferences(String key, ConfigResponse userConfig, AppdefEntityID newId,
        int max) {
    List existing = preferencesAsEntityIds(key, userConfig);

    int lastIdx = existing.lastIndexOf(newId);
    if (existing.size() > 0 && lastIdx == (existing.size() - 1)) {
        return false; // Already the last one
    }//from  ww w.  j  a  va 2 s. com

    // Now add the new one
    existing.add(newId);

    if (lastIdx > -1) {
        for (Iterator it = existing.iterator(); it.hasNext();) {
            AppdefEntityID entityID = (AppdefEntityID) it.next();
            if (entityID.equals(newId)) {
                it.remove();
                break;
            }
        }
    } else {
        if (max < Integer.MAX_VALUE && existing.size() > max)
            existing.remove(0);
    }

    userConfig.setValue(key, StringUtil.listToString(existing, Constants.DASHBOARD_DELIMITER));

    return true;
}

From source file:net.gsantner.opoc.preference.SharedPreferencesPropertyBackend.java

public static void limitListTo(final List<?> list, int maxSize, boolean removeDuplicates) {
    Object o;/*  w  w w .  j a v  a2  s . co m*/
    int pos;

    for (int i = 0; removeDuplicates && i < list.size(); i++) {
        o = list.get(i);
        while ((pos = list.lastIndexOf(o)) != i && pos >= 0) {
            list.remove(pos);
        }
    }
    while ((pos = list.size()) > maxSize && pos > 0) {
        list.remove(list.size() - 1);
    }
}

From source file:fr.inria.atlanmod.neoemf.data.berkeleydb.store.DirectWriteBerkeleyDBListsStore.java

@Override
public int lastIndexOf(InternalEObject object, EStructuralFeature feature, Object value) {
    int returnValue;
    PersistentEObject persistentEObject = PersistentEObject.from(object);
    List<Object> list = manyValueFrom(getFromMap(persistentEObject, feature));
    if (isNull(list)) {
        returnValue = NO_INDEX;//  ww  w  .  j  av  a 2s . co m
    } else if (feature instanceof EAttribute) {
        returnValue = list.lastIndexOf(serializeToProperty((EAttribute) feature, value));
    } else {
        PersistentEObject childEObject = PersistentEObject.from(value);
        returnValue = list.lastIndexOf(childEObject.id());
    }
    return returnValue;
}

From source file:ListSet.java

/**
 * Construct a <tt>ListSet</tt>.
 * //from  w  ww .j  a  v a2s. c  o  m
 * @param list
 *          The <tt>List</tt> which will be used for element storage.
 * 
 * @throws IllegalArgumentException
 *           List is <tt>null</tt> or contains duplicate entries.
 */
public ListSet(final List list) {
    if (list == null)
        throw new RuntimeException("list");

    // make sure there are no duplicates
    int size = list.size();
    for (int i = 0; i < size; i++) {
        Object obj = list.get(i);
        if (list.indexOf(obj) != list.lastIndexOf(obj)) {
            throw new IllegalArgumentException("list contains duplicate entries");
        }
    }

    this.list = list;
}

From source file:com.celements.cells.RenderingEngine.java

void internal_renderSubCells(TreeNode parentNode) {
    EntityReference parentRef = getParentReference(parentNode);
    if (renderStrategy.isRenderSubCells(parentRef)) {
        List<TreeNode> children = getTreeNodeService().getSubNodesForParent(parentRef,
                renderStrategy.getMenuPart(parentNode));
        LOGGER.debug("internal_renderSubCells: for parent [" + parentRef + "] render [" + children.size()
                + "] children [" + children + "].");
        if (children.size() > 0) {
            renderStrategy.startRenderChildren(parentRef);
            boolean isFirstItem = true;
            for (TreeNode node : children) {
                boolean isLastItem = (children.lastIndexOf(node) == (children.size() - 1));
                internal_renderCell(node, isFirstItem, isLastItem);
                isFirstItem = false;//w w  w.  ja va  2s.  co  m
            }
            renderStrategy.endRenderChildren(parentRef);
        } else if (renderStrategy.isRenderCell(parentNode)) {
            renderStrategy.renderEmptyChildren(parentNode);
        }
    }
}