Example usage for java.util List indexOf

List of usage examples for java.util List indexOf

Introduction

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

Prototype

int indexOf(Object o);

Source Link

Document

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

Usage

From source file:com.basistech.m2e.code.quality.pmd.MavenPluginConfigurationTranslator.java

private void buildExcludeAndIncludeSourceRoots() throws CoreException {
    final List<File> includeRoots = new ArrayList<File>();
    final List<File> excludeRoots = new ArrayList<File>();

    includeRoots.addAll(this.transformResourceStringsToFiles(this.mavenProject.getCompileSourceRoots()));

    List<String> targetDirectories = new ArrayList<String>();
    targetDirectories.add(this.mavenProject.getBuild().getDirectory());
    excludeRoots.addAll(this.transformResourceStringsToFiles(targetDirectories));

    // Get all the normalized test roots and add them to include or exclude.
    final List<File> testCompileSourceRoots = this
            .transformResourceStringsToFiles(this.mavenProject.getTestCompileSourceRoots());
    if (this.getIncludeTests()) {
        includeRoots.addAll(testCompileSourceRoots);
    } else {//  w w  w.  jav  a2  s.  co  m
        excludeRoots.addAll(testCompileSourceRoots);
    }

    // now we need to filter out any excludeRoots from plugin configurations
    List<File> excludeRootsFromConfig;
    File[] excludeRootsArray = configurator.getParameterValue("excludeRoots", File[].class, session,
            pmdGoalExecution);
    if (excludeRootsArray == null) {
        excludeRootsFromConfig = Collections.emptyList();
    } else {
        excludeRootsFromConfig = Arrays.asList(excludeRootsArray);
    }
    // do the filtering
    List<File> filteredIncludeRoots = new LinkedList<File>();
    for (File f : includeRoots) {
        int idx = excludeRootsFromConfig.indexOf(f);
        /**
         * Be optimistic when adding inclusions; if the specified File does not exist yet, then assume it
         * will at some point and include it.
         */
        if (idx == -1 && (f.isDirectory() || !f.exists())) {
            filteredIncludeRoots.add(f);
        } else {
            // adding in mid-iteration?
            excludeRoots.add(f);
        }
    }
    this.includeSourceRoots.addAll(this.convertFileFoldersToRelativePathStrings(filteredIncludeRoots));
    this.excludeSourceRoots.addAll(this.convertFileFoldersToRelativePathStrings(excludeRoots));
}

From source file:org.gbif.portal.web.controller.dataset.IndexingHistoryController.java

/**
 * Create a time series graphic to display indexing processes.
 * //from w  ww .  j a v  a 2s . c  o m
 * @param dataProvider
 * @param dataResource
 * @param activities
 * @param fileNamePrefix
 * @return
 */
public String timeSeriesTest(DataProviderDTO dataProvider, DataResourceDTO dataResource,
        List<LoggedActivityDTO> loggedActivities, String fileNamePrefix, int minProcessingTimeToRender) {

    List<LoggedActivityDTO> activities = new ArrayList<LoggedActivityDTO>();
    for (LoggedActivityDTO la : loggedActivities) {
        if (la.getDataResourceKey() != null && la.getDataResourceName() != null && la.getEventName() != null)
            activities.add(la);
    }

    //if no activities to render, return
    if (activities.isEmpty())
        return null;

    Map<String, Integer> drActualCount = new HashMap<String, Integer>();
    Map<String, Integer> drCount = new HashMap<String, Integer>();

    //record the actual counts
    for (LoggedActivityDTO laDTO : activities) {
        if (laDTO.getStartDate() != null && laDTO.getEndDate() != null
                && laDTO.getDurationInMillisecs() > minProcessingTimeToRender) {
            if (drActualCount.get(laDTO.getDataResourceName()) == null) {
                drActualCount.put(laDTO.getDataResourceName(), new Integer(4));
                drCount.put(laDTO.getDataResourceName(), new Integer(0));
            } else {
                Integer theCount = drActualCount.get(laDTO.getDataResourceName());
                theCount = new Integer(theCount.intValue() + 4);
                drActualCount.remove(laDTO.getDataResourceName());
                drActualCount.put(laDTO.getDataResourceName(), theCount);
            }
        }
    }

    StringBuffer fileNameBuffer = new StringBuffer(fileNamePrefix);
    if (dataResource != null) {
        fileNameBuffer.append("-resource-");
        fileNameBuffer.append(dataResource.getKey());
    } else if (dataProvider != null) {
        fileNameBuffer.append("-provider-");
        fileNameBuffer.append(dataProvider.getKey());
    }
    fileNameBuffer.append(".png");

    String fileName = fileNameBuffer.toString();
    String filePath = System.getProperty("java.io.tmpdir") + File.separator + fileName;

    File fileToCheck = new File(filePath);
    if (fileToCheck.exists()) {
        return fileName;
    }

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    boolean generateChart = false;

    int count = 1;
    int dataResourceCount = 1;

    Collections.sort(activities, new Comparator<LoggedActivityDTO>() {
        public int compare(LoggedActivityDTO o1, LoggedActivityDTO o2) {
            if (o1 == null || o2 == null || o1.getDataResourceKey() != null || o2.getDataResourceKey() != null)
                return -1;
            return o1.getDataResourceKey().compareTo(o2.getDataResourceKey());
        }
    });

    String currentDataResourceKey = activities.get(0).getDataResourceKey();

    for (LoggedActivityDTO laDTO : activities) {
        if (laDTO.getStartDate() != null && laDTO.getEndDate() != null
                && laDTO.getDurationInMillisecs() > minProcessingTimeToRender) {

            if (currentDataResourceKey != null && !currentDataResourceKey.equals(laDTO.getDataResourceKey())) {
                dataResourceCount++;
                count = count + 1;
                currentDataResourceKey = laDTO.getDataResourceKey();
            }
            TimeSeries s1 = new TimeSeries(laDTO.getDataResourceName(), "Process time period",
                    laDTO.getEventName(), Hour.class);
            s1.add(new Hour(laDTO.getStartDate()), count);
            s1.add(new Hour(laDTO.getEndDate()), count);
            dataset.addSeries(s1);
            generateChart = true;
        }
    }

    if (!generateChart)
        return null;

    // create a pie chart...
    final JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false);

    XYPlot plot = chart.getXYPlot();
    plot.setWeight(10);
    plot.getRangeAxis().setAutoRange(false);
    plot.getRangeAxis().setRange(0, drCount.size() + 1);
    plot.getRangeAxis().setAxisLineVisible(false);
    plot.getRangeAxis().setAxisLinePaint(Color.WHITE);
    plot.setDomainCrosshairValue(1);
    plot.setRangeGridlinesVisible(false);
    plot.getRangeAxis().setVisible(false);
    plot.getRangeAxis().setLabel("datasets");

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setItemLabelsVisible(true);
    MyXYItemLabelGenerator labelGenerator = new MyXYItemLabelGenerator();
    labelGenerator.setDataResourceActualCount(drActualCount);
    labelGenerator.setDataResourceCount(drCount);
    renderer.setItemLabelGenerator(labelGenerator);

    List<TimeSeries> seriesList = dataset.getSeries();
    for (TimeSeries series : seriesList) {
        if (((String) series.getRangeDescription()).startsWith("extraction")) {
            renderer.setSeriesPaint(seriesList.indexOf(series), Color.RED);
        } else {
            renderer.setSeriesPaint(seriesList.indexOf(series), Color.BLUE);
        }
        renderer.setSeriesStroke(seriesList.indexOf(series), new BasicStroke(7f));
    }

    int imageHeight = 30 * dataResourceCount;
    if (imageHeight < 100) {
        imageHeight = 100;
    } else {
        imageHeight = imageHeight + 100;
    }

    final BufferedImage image = new BufferedImage(900, imageHeight, BufferedImage.TYPE_INT_RGB);
    KeypointPNGEncoderAdapter adapter = new KeypointPNGEncoderAdapter();
    adapter.setQuality(1);
    try {
        adapter.encode(image);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    final Graphics2D g2 = image.createGraphics();
    g2.setFont(new Font("Arial", Font.PLAIN, 11));
    final Rectangle2D chartArea = new Rectangle2D.Double(0, 0, 900, imageHeight);

    // draw
    chart.draw(g2, chartArea, null, null);

    //styling
    chart.setPadding(new RectangleInsets(0, 0, 0, 0));
    chart.setBorderVisible(false);
    chart.setBackgroundImageAlpha(0);
    chart.setBackgroundPaint(Color.WHITE);
    chart.setBorderPaint(Color.LIGHT_GRAY);

    try {
        FileOutputStream fOut = new FileOutputStream(filePath);
        ChartUtilities.writeChartAsPNG(fOut, chart, 900, imageHeight);
        return fileName;
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:com.viewer.controller.ViewerController.java

@RequestMapping(value = "/RotatePage", method = RequestMethod.POST, headers = {
        "Content-type=application/json" })
@ResponseBody/*from   w  ww.j av a  2s.com*/
public RotatePageResponse rotatePage(@RequestBody RotatePageParameters parameters, HttpServletRequest request)
        throws Exception {

    String guid = parameters.getPath();
    int pageIndex = parameters.getPageNumber();

    DocumentInfoOptions documentInfoOptions = new DocumentInfoOptions(guid);
    DocumentInfoContainer documentInfoContainer = (DocumentInfoContainer) _imageHandler
            .getDocumentInfo(documentInfoOptions);

    List<PageData> pageList = new ArrayList<PageData>();
    pageList = documentInfoContainer.getPages();
    int pageNumber = pageList.indexOf(pageIndex);

    RotatePageOptions rotatePageOptions = new RotatePageOptions(guid, 1, parameters.getRotationAmount());
    RotatePageContainer rotatePageContainer = _imageHandler.rotatePage(rotatePageOptions);
    int currentPage = rotatePageContainer.getCurrentRotationAngle();
    RotatePageResponse response = new RotatePageResponse();
    response.setResultAngle(currentPage);

    return response;
}

From source file:com.adito.jdbc.JDBCSystemDatabase.java

public void moveAuthenticationSchemeUp(AuthenticationScheme scheme, List<AuthenticationScheme> schemes)
        throws Exception {
    int indexOf = schemes.indexOf(scheme);
    if (indexOf == 0)
        throw new IllegalStateException("Scheme is already set to highest priority");

    int schemeAboveIndex = indexOf - 1;
    AuthenticationScheme schemeAbove = schemes.get(schemeAboveIndex);
    updateAuthenticationSchemePriority(scheme, schemeAbove.getPriorityInt());
    updateAuthenticationSchemePriority(schemeAbove, scheme.getPriorityInt());
}

From source file:com.adito.jdbc.JDBCSystemDatabase.java

public void moveAuthenticationSchemeDown(AuthenticationScheme scheme, List<AuthenticationScheme> schemes)
        throws Exception {
    int indexOf = schemes.indexOf(scheme);
    if (indexOf == schemes.size() - 1)
        throw new IllegalStateException("Scheme is already set to lowest priority");

    int schemeBelowIndex = indexOf + 1;
    AuthenticationScheme schemeBelow = schemes.get(schemeBelowIndex);
    updateAuthenticationSchemePriority(scheme, schemeBelow.getPriorityInt());
    updateAuthenticationSchemePriority(schemeBelow, scheme.getPriorityInt());
}

From source file:info.mikaelsvensson.devtools.sitesearch.SiteSearchPlugin.java

private Collection<WordCount> getWordCount(final String text) {
    List<WordCount> words = new ArrayList<WordCount>();
    StringTokenizer tokenizer = new StringTokenizer(text);
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken().toLowerCase();
        WordCount wordCount = new WordCount(token, 1);
        if (words.contains(wordCount)) {
            words.get(words.indexOf(wordCount)).increaseCount();
        } else {//from   w ww  . ja  v  a2  s. co m
            words.add(wordCount);
        }
    }
    return words;
}

From source file:com.blm.orc.ReaderImpl.java

private List<Integer> getColumnIndicesFromNames(List<String> colNames) {
    // top level struct
    Type type = footer.getTypesList().get(0);
    List<Integer> colIndices = Lists.newArrayList();
    List<String> fieldNames = type.getFieldNamesList();
    int fieldIdx = 0;
    for (String colName : colNames) {
        if (fieldNames.contains(colName)) {
            fieldIdx = fieldNames.indexOf(colName);
        }/*from  w  w w.  j a  va2  s .co  m*/

        // a single field may span multiple columns. find start and end column
        // index for the requested field
        int idxStart = type.getSubtypes(fieldIdx);

        int idxEnd;

        // if the specified is the last field and then end index will be last
        // column index
        if (fieldIdx + 1 > fieldNames.size() - 1) {
            idxEnd = getLastIdx() + 1;
        } else {
            idxEnd = type.getSubtypes(fieldIdx + 1);
        }

        // if start index and end index are same then the field is a primitive
        // field else complex field (like map, list, struct, union)
        if (idxStart == idxEnd) {
            // simple field
            colIndices.add(idxStart);
        } else {
            // complex fields spans multiple columns
            for (int i = idxStart; i < idxEnd; i++) {
                colIndices.add(i);
            }
        }
    }
    return colIndices;
}

From source file:org.commonjava.aprox.core.expire.ScheduleManager.java

public void updateSnapshotVersions(final StoreKey key, final String path) {
    final ArtifactPathInfo pathInfo = ArtifactPathInfo.parse(path);
    if (pathInfo == null) {
        return;/*  w  w  w.j  av  a 2 s.  c o m*/
    }

    final ArtifactStore store;
    try {
        store = dataManager.getArtifactStore(key);
    } catch (final AproxDataException e) {
        logger.error(
                String.format("Failed to update metadata after snapshot deletion. Reason: {}", e.getMessage()),
                e);
        return;
    }

    if (store == null) {
        logger.error(
                "Failed to update metadata after snapshot deletion in: {}. Reason: Cannot find corresponding ArtifactStore",
                key);
        return;
    }

    final Transfer item = fileManager.getStorageReference(store, path);
    if (item.getParent() == null || item.getParent().getParent() == null) {
        return;
    }

    final Transfer metadata = fileManager.getStorageReference(store, item.getParent().getParent().getPath(),
            "maven-metadata.xml");

    if (metadata.exists()) {
        //            logger.info( "[UPDATE VERSIONS] Updating snapshot versions for path: {} in store: {}", path, key.getName() );
        Reader reader = null;
        Writer writer = null;
        try {
            reader = new InputStreamReader(metadata.openInputStream());
            final Metadata md = new MetadataXpp3Reader().read(reader);

            final Versioning versioning = md.getVersioning();
            final List<String> versions = versioning.getVersions();

            final String version = pathInfo.getVersion();
            String replacement = null;

            final int idx = versions.indexOf(version);
            if (idx > -1) {
                if (idx > 0) {
                    replacement = versions.get(idx - 1);
                }

                versions.remove(idx);
            }

            if (version.equals(md.getVersion())) {
                md.setVersion(replacement);
            }

            if (version.equals(versioning.getLatest())) {
                versioning.setLatest(replacement);
            }

            final SnapshotPart si = pathInfo.getSnapshotInfo();
            if (si != null) {
                final SnapshotPart siRepl = SnapshotUtils.extractSnapshotVersionPart(replacement);
                final Snapshot snapshot = versioning.getSnapshot();

                final String siTstamp = SnapshotUtils.generateSnapshotTimestamp(si.getTimestamp());
                if (si.isRemoteSnapshot() && siTstamp.equals(snapshot.getTimestamp())
                        && si.getBuildNumber() == snapshot.getBuildNumber()) {
                    if (siRepl != null) {
                        if (siRepl.isRemoteSnapshot()) {
                            snapshot.setTimestamp(
                                    SnapshotUtils.generateSnapshotTimestamp(siRepl.getTimestamp()));
                            snapshot.setBuildNumber(siRepl.getBuildNumber());
                        } else {
                            snapshot.setLocalCopy(true);
                        }
                    } else {
                        versioning.setSnapshot(null);
                    }
                }
            }

            writer = new OutputStreamWriter(metadata.openOutputStream(TransferOperation.GENERATE, true));
            new MetadataXpp3Writer().write(writer, md);
        } catch (final IOException e) {
            logger.error(
                    "Failed to update metadata after snapshot deletion.\n  Snapshot: {}\n  Metadata: {}\n  Reason: {}",
                    e, item.getFullPath(), metadata, e.getMessage());
        } catch (final XmlPullParserException e) {
            logger.error(
                    "Failed to update metadata after snapshot deletion.\n  Snapshot: {}\n  Metadata: {}\n  Reason: {}",
                    e, item.getFullPath(), metadata, e.getMessage());
        } finally {
            closeQuietly(reader);
            closeQuietly(writer);
        }
    }
}

From source file:com.funambol.server.engine.EngineHelper.java

/**
 * Calculate the intersection between the given lists, returning a new list
 * of <i>SyncItemMapping</i>s each containing the corresponding item couple.
 * Items are matched using the <i>get()</i> method of the <i>List</i> object,
 * therefore the rules for matching items are the ones specified by the
 * <i>List</i> interface.//from   w  w  w  .  j av  a2s  . com
 * BTW, if an item isn't mapped, it is skipped. In this way, two items with
 * the same key are not mapped (now we have the twins for that).
 *
 * @param a the first list - NOT NULL
 * @param b the seconf list - NOT NULL
 *
 * @return the intersection mapping list.
 */
public static List intersect(final List a, final List b) {
    int n = 0;
    SyncItem itemA = null;
    List ret = new ArrayList();
    SyncItemMapping mapping = null;

    Iterator i = a.iterator();
    while (i.hasNext()) {
        itemA = (SyncItem) i.next();
        //
        // If an item isn't mapped, it is skipped.
        // In this way, two items with the same key are not mapped
        // (now we have the twins for that)
        //
        if (((AbstractSyncItem) itemA).getMappedKey() != null) {
            n = b.indexOf(itemA);
            if (n >= 0) {
                mapping = new SyncItemMapping(itemA.getKey());
                mapping.setMapping(itemA, (SyncItem) b.get(n));
                ret.add(mapping);
            }
        }
    }

    return ret;
}

From source file:hydrograph.ui.propertywindow.widgets.dialog.hiveInput.HiveFieldDialogHelper.java

/**
 * //from  ww  w  . jav  a 2 s .c o  m
 * @param keyValues
 * @param keyList
 * @param incomingList2 
 */
private void checkAndAdjustRowsColumns(List<HivePartitionFields> keyValues, List<String> keyList,
        List<InputHivePartitionColumn> incomingList) {
    Set<String> colNames = new HashSet<>();
    for (int i = 0; i < incomingList.size(); i++) {

        colNames = extractColumnNamesFromObject(incomingList.get(i), colNames);

        List<String> notAvailableFields = ListUtils.subtract(keyList, new ArrayList<>(colNames));

        if (null != notAvailableFields && notAvailableFields.size() > 0) {
            for (String fieldName : notAvailableFields) {

                keyValues.get(i).getRowFields().add(keyList.indexOf(fieldName), "");
            }
        }
        colNames.clear();
    }

}