Example usage for java.util List set

List of usage examples for java.util List set

Introduction

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

Prototype

E set(int index, E element);

Source Link

Document

Replaces the element at the specified position in this list with the specified element (optional operation).

Usage

From source file:com.xiaomi.linden.core.search.MultiLindenCoreImpl.java

@Override
public LindenResult search(final LindenSearchRequest request) throws IOException {
    final List<LindenResult> resultList = new ArrayList<>();
    final List<Future<BoxedUnit>> futures = new ArrayList<>();

    List<String> indexNames;
    // Only INDEX_NAME division type supports specified index name request
    if (multiIndexStrategy instanceof TimeLimitMultiIndexStrategy
            || multiIndexStrategy instanceof DocNumLimitMultiIndexStrategy) {
        indexNames = new ArrayList<>(lindenCoreMap.keySet());
    } else {/*from  w w w. j a v a2s  .  co m*/
        if (request.getIndexNames() == null
                || (request.getIndexNamesSize() == 1 && request.getIndexNames().get(0).equals(LINDEN))) {
            indexNames = new ArrayList<>(lindenCoreMap.keySet());
        } else {
            indexNames = request.getIndexNames();
            for (int i = 0; i < indexNames.size(); ++i) {
                indexNames.set(i, MultiIndexStrategy.MULTI_INDEX_PREFIX_NAME + indexNames.get(i));
            }
        }
    }

    for (final String indexName : indexNames) {
        final LindenCore core = lindenCoreMap.get(indexName);
        if (core != null) {
            futures.add(Future.value(core.search(request))
                    .transformedBy(new FutureTransformer<LindenResult, BoxedUnit>() {
                        @Override
                        public BoxedUnit map(LindenResult lindenResult) {
                            synchronized (resultList) {
                                resultList.add(lindenResult);
                            }
                            return BoxedUnit.UNIT;
                        }

                        @Override
                        public BoxedUnit handle(Throwable t) {
                            LOGGER.info("Index {} search error: {}", indexName,
                                    Throwables.getStackTraceAsString(t));
                            return BoxedUnit.UNIT;
                        }
                    }));
        } else {
            LOGGER.error("Index {} doesn't exist.", indexName);
        }
    }
    Future<List<BoxedUnit>> collected = Future.collect(futures);
    try {
        collected.apply(Duration.apply(DEFAULT_SEARCH_TIMEOUT, TimeUnit.MILLISECONDS));
    } catch (Exception e) {
        LOGGER.error("Multi-index search error: {}", Throwables.getStackTraceAsString(e));
    }
    return ResultMerger.merge(request, resultList);
}

From source file:me.doshou.admin.maintain.staticresource.web.controller.StaticResourceVersionController.java

private StaticResource switchStaticResourceContent(String rootRealPath, String versionedResourceRealPath,
        String fileName, String content, boolean isMin) throws IOException {

    StaticResource resource = extractResource(fileName, content);
    String filePath = resource.getUrl();
    filePath = filePath.replace("${ctx}", rootRealPath);

    if (isMin) {/*from  www. j  av a2s.co  m*/
        File file = new File(YuiCompressorUtils.getCompressFileName(filePath));
        if (!file.exists()) {
            throw new RuntimeException("" + resource.getUrl());
        }
    } else {
        File file = new File(YuiCompressorUtils.getNoneCompressFileName(filePath));
        if (!file.exists()) {
            throw new RuntimeException("?" + resource.getUrl());
        }
    }

    content = StringEscapeUtils.unescapeXml(content);

    File file = new File(versionedResourceRealPath + fileName);

    List<String> contents = FileUtils.readLines(file);

    for (int i = 0, l = contents.size(); i < l; i++) {
        String fileContent = contents.get(i);
        if (content.equals(fileContent)) {
            Matcher matcher = scriptPattern.matcher(content);
            if (!matcher.matches()) {
                matcher = linkPattern.matcher(content);
            }
            String newUrl = isMin ? YuiCompressorUtils.getCompressFileName(resource.getUrl())
                    : YuiCompressorUtils.getNoneCompressFileName(resource.getUrl());

            content = matcher.replaceAll("$1" + Matcher.quoteReplacement(newUrl) + "$3$4$5");
            contents.set(i, content);

            resource.setContent(content);
            resource.setUrl(newUrl);

            break;
        }
    }
    FileUtils.writeLines(file, contents);

    return resource;
}

From source file:de.dfki.km.perspecting.obie.model.Document.java

public void removeUnresolvedSubjects(int[] subjects) {

    TIntHashSet _subjects = new TIntHashSet(subjects);

    for (int tokenIndex : data.getIntegerKeys(TokenSequence.SUBJECT)) {
        List<SemanticEntity> values = data.get(TokenSequence.SUBJECT, tokenIndex);
        Set<Integer> indexes = new HashSet<Integer>();
        int i = 0;
        for (SemanticEntity value : values) {

            int subject = value.getSubjectIndex();

            if (_subjects.contains(subject)) {
                indexes.add(i);/*w  w w .j av  a2  s .  co m*/
            }
            i++;
        }

        for (int j : indexes) {
            log.fine("removed entity: " + values.get(j));
            values.set(j, null);
        }

        while (values.remove(null))
            ;

    }

}

From source file:hudson.plugins.plot.PlotReport.java

public List<List<String>> getTable(int i) {
    List<List<String>> tableData = new ArrayList<List<String>>();

    Plot plot = getPlot(i);/*  w w w  .  j a va 2s  . c o  m*/

    // load existing csv file
    File plotFile = new File(project.getRootDir(), plot.getCsvFileName());
    if (!plotFile.exists()) {
        return tableData;
    }
    CSVReader reader = null;
    try {
        reader = new CSVReader(new FileReader(plotFile));
        // throw away 2 header lines
        reader.readNext();
        reader.readNext();
        // array containing header titles
        List<String> header = new ArrayList<String>();
        header.add(Messages.Plot_Build() + " #");
        tableData.add(header);
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            String buildNumber = nextLine[2];
            if (!plot.reportBuild(Integer.parseInt(buildNumber))) {
                continue;
            }
            String seriesLabel = nextLine[1];
            // index of the column where the value should be located
            int index = header.lastIndexOf(seriesLabel);
            if (index <= 0) {
                // add header label
                index = header.size();
                header.add(seriesLabel);
            }
            List<String> tableRow = null;
            for (int j = 1; j < tableData.size(); j++) {
                List<String> r = tableData.get(j);
                if (StringUtils.equals(r.get(0), buildNumber)) {
                    // found table row corresponding to the build number
                    tableRow = r;
                    break;
                }
            }
            // table row corresponding to the build number not found
            if (tableRow == null) {
                // create table row with build number at first column
                tableRow = new ArrayList<String>();
                tableRow.add(buildNumber);
                tableData.add(tableRow);
            }
            // set value at index column
            String value = nextLine[0];
            if (index < tableRow.size()) {
                tableRow.set(index, value);
            } else {
                for (int j = tableRow.size(); j < index; j++) {
                    tableRow.add(StringUtils.EMPTY);
                }
                tableRow.add(value);
            }
        }
        int lastColumn = tableData.get(0).size();
        for (List<String> tableRow : tableData) {
            for (int j = tableRow.size(); j < lastColumn; j++) {
                tableRow.add(StringUtils.EMPTY);
            }
        }
    } catch (IOException ioe) {
        LOGGER.log(Level.SEVERE, "Exception reading csv file", ioe);
        // ignore
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ignore) {
                // ignore
            }
        }
    }
    return tableData;
}

From source file:com.example.phonetic.KoelnerPhonetik.java

private List<String> getVariations(String str) {
    int position = 0;
    List<String> variations = new ArrayList<>();
    variations.add("");
    while (position < str.length()) {
        int i = 0;
        int substPos = -1;
        while (substPos < position && i < getPatterns().length) {
            Matcher m = variationsPatterns[i].matcher(str);
            while (substPos < position && m.find()) {
                substPos = m.start();/*from   www  . j  av a2  s  .c om*/
            }
            i++;
        }
        if (substPos >= position) {
            i--;
            List<String> varNew = new ArrayList<>();
            String prevPart = str.substring(position, substPos);
            for (int ii = 0; ii < variations.size(); ii++) {
                String tmp = variations.get(ii);
                varNew.add(tmp.concat(prevPart + getReplacements()[i]));
                variations.set(ii, variations.get(ii) + prevPart + getPatterns()[i]);
            }
            variations.addAll(varNew);
            position = substPos + getPatterns()[i].length();
        } else {
            for (int ii = 0; ii < variations.size(); ii++) {
                variations.set(ii, variations.get(ii) + str.substring(position, str.length()));
            }
            position = str.length();
        }
    }
    return variations;
}

From source file:com.alvermont.terraj.stargen.dole.DoleAccrete.java

/**
 * Let's see who 'p' will run into, if anyone.
 *
 * @param star The star for the solar system
 * @param p The planet being considered//from w  ww . j  av  a 2 s  .c  o m
 */
void checkCoalesence(Primary star, DolePlanetRecord p) {
    boolean merged = true;

    while (merged) {
        merged = false;

        final List<Planet> planets = star.getPlanets();

        int index = planets.indexOf(p);

        if (index < 0) {
            throw new AssertionError("Did not find the planet in the list");
        }

        int pindex = index - 1;

        while (pindex >= 0) {
            final DolePlanetRecord p1 = (DolePlanetRecord) planets.get(pindex);

            if (p1.getRMax() >= p.getRMin()) {
                planets.set(pindex, mergePlanets(p1, p));

                planets.remove(pindex + 1);

                --pindex;

                merged = true;
            } else {
                pindex = -1;
            }
        }

        if (merged) {
            // then this could have changed
            index = planets.indexOf(p);
        }

        pindex = index + 1;

        while (pindex < planets.size()) {
            final DolePlanetRecord p1 = (DolePlanetRecord) planets.get(pindex);

            if (p1.getRMin() <= p.getRMax()) {
                planets.set(pindex, mergePlanets(p1, p));
                planets.remove(pindex - 1);

                ++pindex;

                merged = true;
            } else {
                pindex = Integer.MAX_VALUE;
            }
        }

        if (merged) {
            evolvePlanet(star, p);
        }
    }
}

From source file:edu.uci.ics.jung.graph.OrderedKAryTree.java

/**
 * Adds the specified {@code child} vertex and edge {@code e} to the graph
 * with the specified parent vertex {@code parent}.  If {@code index} is 
 * greater than or equal to 0, then the child is placed at position
 * {@code index}; if it is less than 0, the child is placed at the lowest
 * available position; if it is greater than or equal to the order of this
 * tree, an exception is thrown.//from   w  ww  .  j  ava2 s  .co m
 * 
 * @see edu.uci.ics.jung.graph.Graph#addEdge(java.lang.Object, java.lang.Object, java.lang.Object)
 */
public boolean addEdge(E e, V parent, V child, int index) {
    if (e == null || child == null || parent == null)
        throw new IllegalArgumentException("Inputs may not be null");
    if (!containsVertex(parent))
        throw new IllegalArgumentException("Tree must already " + "include parent: " + parent);
    if (containsVertex(child))
        throw new IllegalArgumentException("Tree must not already " + "include child: " + child);
    if (parent.equals(child))
        throw new IllegalArgumentException("Input vertices must be distinct");
    if (index < 0 || index >= order)
        throw new IllegalArgumentException("'index' must be in [0, [order-1]]");

    Pair<V> endpoints = new Pair<V>(parent, child);
    if (containsEdge(e))
        if (!endpoints.equals(edge_vpairs.get(e)))
            throw new IllegalArgumentException(
                    "Tree already includes edge" + e + " with different endpoints " + edge_vpairs.get(e));
        else
            return false;

    VertexData parent_data = vertex_data.get(parent);
    List<E> outedges = parent_data.child_edges;

    if (outedges == null)
        outedges = new ArrayList<E>(this.order);

    boolean edge_placed = false;
    if (index >= 0)
        if (outedges.get(index) != null)
            throw new IllegalArgumentException(
                    "Parent " + parent + " already has a child at index " + index + " in this tree");
        else
            outedges.set(index, e);
    for (int i = 0; i < order; i++) {
        if (outedges.get(i) == null) {
            outedges.set(i, e);
            edge_placed = true;
            break;
        }
    }
    if (!edge_placed)
        throw new IllegalArgumentException(
                "Parent " + parent + " already" + " has " + order + " children in this tree");

    // initialize VertexData for child; leave child's child_edges null for now
    VertexData child_data = new VertexData(e, parent_data.depth + 1);
    vertex_data.put(child, child_data);

    height = child_data.depth > height ? child_data.depth : height;
    edge_vpairs.put(e, endpoints);

    return true;
}

From source file:com.couchbase.lite.DatabaseAttachmentTest.java

/**
 * - (void) test13_GarbageCollectAttachments
 */// w  ww  .ja  va  2  s .c  o m
public void test13_GarbageCollectAttachments() throws CouchbaseLiteException {
    List<RevisionInternal> revs = new ArrayList<RevisionInternal>();
    for (int i = 0; i < 100; i++)
        revs.add(this.putDocWithAttachment(String.format(Locale.ENGLISH, "doc-%d", i),
                String.format(Locale.ENGLISH, "Attachment #%d", i), false));
    for (int i = 0; i < 40; i++) {
        revs.set(i,
                database.updateAttachment("attach", null, null,
                        AttachmentInternal.AttachmentEncoding.AttachmentEncodingNone, revs.get(i).getDocID(),
                        revs.get(i).getRevID(), null));
    }
    database.compact();
    assertEquals(60, database.getAttachmentStore().count());
}

From source file:com.caricah.iotracah.core.worker.DumbWorker.java

private Set<String> getMatchingSubscriptions(String partition, String topic) {

    Set<String> topicFilterKeys = new HashSet<>();

    ListIterator<String> pathIterator = Arrays.asList(topic.split(Constant.PATH_SEPARATOR)).listIterator();

    List<String> growingTitles = new ArrayList<>();

    while (pathIterator.hasNext()) {

        String name = pathIterator.next();

        List<String> slWildCardList = new ArrayList<>(growingTitles);

        if (pathIterator.hasNext()) {
            //We deal with wildcard.
            slWildCardList.add(Constant.SINGLE_LEVEL_WILDCARD);
            topicFilterKeys.add(quickCheckIdKey(partition, slWildCardList));

        } else {//from ww w .j ava  2  s  . c o  m
            //we deal with full topic
            slWildCardList.add(name);
        }

        List<String> reverseSlWildCardList = new ArrayList<>(slWildCardList);

        growingTitles.add(name);

        int sizeOfTopic = slWildCardList.size();
        if (sizeOfTopic > 1) {
            sizeOfTopic -= 1;

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

                if (i >= 0) {
                    slWildCardList.set(i, Constant.MULTI_LEVEL_WILDCARD);
                    reverseSlWildCardList.set(sizeOfTopic - i, Constant.MULTI_LEVEL_WILDCARD);

                    topicFilterKeys.add(quickCheckIdKey(partition, slWildCardList));
                    topicFilterKeys.add(quickCheckIdKey(partition, reverseSlWildCardList));

                }
            }
        }

    }

    topicFilterKeys.add(quickCheckIdKey(partition, growingTitles));

    return topicFilterKeys;

}

From source file:com.strategicgains.docussandra.controller.IndexControllerTest.java

/**
 * Tests that the POST /{databases}/{setTable}/indexes/ endpoint properly
 * creates a index, setting errors to the index status table and that the
 * GET/{database}/{setTable}/index_status/{status_id} endpoint is working.
 *//*from   ww  w .  j ava  2 s. co  m*/
@Test
public void createBadDataThenPostIndexAndCheckStatusTest() throws InterruptedException, Exception {
    String restAssuredBasePath = RestAssured.basePath;
    Database testDb = Fixtures.createTestPlayersDatabase();
    Table testTable = Fixtures.createTestPlayersTable();
    List<Document> docs = Fixtures.getBulkDocuments("./src/test/resources/players-short.json", testTable);
    //botch a doc
    Document badDoc = docs.get(0);
    //the year field is now text
    badDoc.object(
            "{\"SOURCE\":\"kffl\",\"LINK\":\"http://www.kffl.com/gnews.php?id=796662-eagles-michael-vick-showed-quick-release\",\"CREATEDON\":\"July, 07 2012 00:00:00\",\"ROOKIEYEAR\":\"TWO THOUSAND AND ONE\",\"NAMEFIRST\":\"Michael\",\"POSITION\":\"QB\",\"NAMEFULL\":\"Michael Vick\",\"TEAM\":\"PHI\",\"TITLE\":\"Michael Vick showed quick release\",\"NAMELAST\":\"Vick\"}");
    docs.set(0, badDoc);
    try {
        //data insert          
        f.insertDatabase(testDb);
        f.insertTable(testTable);
        f.insertDocuments(docs);//put in a ton of data directly into the db
        Index rookieyear = Fixtures.createTestPlayersIndexRookieYear();

        String indexString = Fixtures.generateIndexCreationStringWithFields(rookieyear);
        RestAssured.basePath = "/" + rookieyear.getDatabaseName() + "/" + rookieyear.getTableName()
                + "/indexes";
        //act -- create index
        ResponseOptions response = given().body(indexString).expect().statusCode(201)
                .body("index.name", equalTo(rookieyear.getName())).body("index.fields", notNullValue())
                .body("index.createdAt", notNullValue()).body("index.updatedAt", notNullValue())
                .body("index.active", equalTo(false))//should not yet be active
                .body("id", notNullValue()).body("dateStarted", notNullValue())
                .body("statusLastUpdatedAt", notNullValue()).body("eta", notNullValue())
                .body("precentComplete", notNullValue()).body("totalRecords", equalTo(3308))
                .body("recordsCompleted", equalTo(0)).when().post("/" + rookieyear.getName()).andReturn();

        //start a timer
        StopWatch sw = new StopWatch();
        sw.start();

        //check the status endpoint to make sure it got created
        //get the uuid from the response
        String uuidString = response.getBody().jsonPath().get("id");
        RestAssured.basePath = "/" + rookieyear.getDatabaseName() + "/" + rookieyear.getTableName()
                + "/index_status/";
        ResponseOptions res = expect().statusCode(200).body("id", equalTo(uuidString))
                .body("dateStarted", notNullValue()).body("statusLastUpdatedAt", notNullValue())
                .body("eta", notNullValue()).body("precentComplete", notNullValue())
                .body("index", notNullValue()).body("index.active", notNullValue())
                .body("index.active", equalTo(false))//should not yet be active
                .body("recordsCompleted", notNullValue()).when().get(uuidString).andReturn();
        LOGGER.debug("Status Response: " + res.getBody().prettyPrint());

        boolean active = false;
        while (!active) {
            //poll the status until it is active to make sure an index did in fact get created
            res = expect().statusCode(200).body("id", equalTo(uuidString)).body("dateStarted", notNullValue())
                    .body("statusLastUpdatedAt", notNullValue()).body("eta", notNullValue())
                    .body("precentComplete", notNullValue()).body("index", notNullValue())
                    .body("index.active", notNullValue()).body("recordsCompleted", notNullValue()).when()
                    .get(uuidString).andReturn();
            LOGGER.debug("Status Response: " + res.getBody().prettyPrint());
            active = res.getBody().jsonPath().get("index.active");
            if (active) {
                sw.stop();
                break;
            }
            LOGGER.debug("Waiting for index to go active for: " + sw.getTime());
            if (sw.getTime() >= 60000) {
                fail("Index took too long to create: " + sw.getTime());
            }
            Thread.sleep(2000);
        }
        LOGGER.info("It took: " + (sw.getTime() / 1000) + " seconds to create the index.");

        //once it is active, lets check and make sure we have an error in the status table for our bad doc -- side note: there are tons more errors than our intentional one in this dataset
        res = expect().statusCode(200).body("id", equalTo(uuidString)).body("dateStarted", notNullValue())
                .body("statusLastUpdatedAt", notNullValue()).body("eta", notNullValue())
                .body("precentComplete", notNullValue()).body("index", notNullValue())
                .body("index.active", notNullValue()).body("recordsCompleted", notNullValue()).when()
                .get(uuidString).andReturn();
        LOGGER.debug("Status Response: " + res.getBody().prettyPrint());
        Assert.assertTrue(res.getBody().prettyPrint().contains("error"));
        Assert.assertTrue(
                res.getBody().prettyPrint().contains("796662-eagles-michael-vick-showed-quick-release"));

    } finally {
        RestAssured.basePath = restAssuredBasePath;
        //clean up
        DocumentRepositoryImpl docrepo = new DocumentRepositoryImpl(f.getSession());
        for (Document d : docs) {
            try {
                docrepo.delete(d);
            } catch (Exception e) {
                ;//eh -- the doc probably never got created
            }
        }
    }
}