Example usage for java.util List clear

List of usage examples for java.util List clear

Introduction

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

Prototype

void clear();

Source Link

Document

Removes all of the elements from this list (optional operation).

Usage

From source file:com.jaeksoft.searchlib.learning.StandardLearner.java

@Override
public void similar(String data, FieldMap sourceFieldMap, int maxRank, double minScore,
        Collection<LearnerResultItem> collector) throws IOException, SearchLibException {
    rwl.r.lock();/*w w w  .j  a va  2  s  .  c  o  m*/
    try {
        checkIndex(sourceFieldMap);
        BooleanQuery booleanQuery = getBooleanQuery(FIELD_SOURCE_DATA, data);
        if (booleanQuery == null || booleanQuery.getClauses() == null || booleanQuery.getClauses().length == 0)
            return;
        AbstractSearchRequest searchRequest = (AbstractSearchRequest) learnerClient
                .getNewRequest(REQUEST_SEARCH);
        int start = 0;
        final int rows = 1000;
        List<String[]> termVectors = new ArrayList<String[]>(rows);
        List<String> stringIndexTerms = new ArrayList<String>(rows);
        for (;;) {
            termVectors.clear();
            stringIndexTerms.clear();
            searchRequest.setStart(start);
            searchRequest.setRows(rows);
            searchRequest.setBoostedComplexQuery(booleanQuery);
            AbstractResultSearch result = (AbstractResultSearch) learnerClient.request(searchRequest);
            if (result.getDocumentCount() == 0)
                break;
            int end = start + result.getDocumentCount();
            int[] docIds = ArrayUtils.subarray(ResultDocument.getDocIds(result.getDocs()), start, end);
            learnerClient.getIndex().putTermVectors(docIds, FIELD_SOURCE_TARGET, termVectors);
            learnerClient.getIndex().getStringIndex(FIELD_SOURCE_NAME).putTerms(docIds, stringIndexTerms);
            int i = -1;
            for (int pos = start; pos < end; pos++) {
                i++;
                String[] terms = termVectors.get(i);
                if (terms == null)
                    continue;
                double docScore = result.getScore(pos);
                if (docScore < minScore)
                    break;
                String name = stringIndexTerms.get(i);
                if (name == null)
                    continue;
                for (String value : terms) {
                    if (value == null)
                        continue;
                    collector.add(new LearnerResultItem(docScore, pos, null, value, 1, null));
                    break;
                }
            }
            searchRequest.reset();
            start += rows;
        }
    } finally {
        rwl.r.unlock();
    }
}

From source file:es.pode.empaquetador.presentacion.archivos.gestor.GestorArchivosControllerImpl.java

/**
 * @see es.pode.empaquetador.presentacion.archivos.gestor.GestorArchivosController#vaciarPortapapeles(org.apache.struts.action.ActionMapping, es.pode.empaquetador.presentacion.archivos.gestor.VaciarPortapapelesForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from  w  w  w . ja v a 2  s  .  c om*/
public final void vaciarPortapapeles(ActionMapping mapping,
        es.pode.empaquetador.presentacion.archivos.gestor.VaciarPortapapelesForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    GestorArchivosSession sesArch = this.getGestorArchivosSession(request);
    List portapapeles = sesArch.getPortapapeles();
    if (portapapeles != null && portapapeles.size() > 0) {
        portapapeles.clear();
        sesArch.setPortapapeles(portapapeles);
        sesArch.setAccion(NORMAL);
        sesArch.setModoPegar(false);
    } else {
        throw new ValidatorException(PORTAL_EMPAQUETADOR_EXCEPTION);
    }
}

From source file:edu.duke.cabig.c3pr.web.ajax.BookRandomizationAjaxFacade.java

private void parseBookRandomization(String bookRandomizations, Epoch tEpoch) throws Exception {

    try {//from w  ww .  j  a v  a  2  s  . co  m
        // we do not create a new instance of bookRandomization, we use the existing instance
        // which was created in StudyDesignTab.java
        // based on the randomizationType selected on the study_details page.
        BookRandomization randomization = null;
        if (tEpoch.getRandomization() instanceof BookRandomization) {
            randomization = (BookRandomization) tEpoch.getRandomization();
        } else {
            return;
        }

        List<BookRandomizationEntry> breList = randomization.getBookRandomizationEntry();
        //clear existing bookEntries
        breList.clear();
        clearStratumGroups(tEpoch);

        StringTokenizer outer = new StringTokenizer(bookRandomizations, "\n");
        String entry;
        String[] entries;
        Arm arm;
        StratumGroup sGroup;
        BookRandomizationEntry bookRandomizationEntry = null;
        while (outer.hasMoreElements()) {
            entry = outer.nextToken();
            if (entry.trim().length() > 0) {
                entries = entry.split(",");
                bookRandomizationEntry = breList.get(breList.size());

                // find the stratum group with this id and set it here even if its null
                sGroup = getStratumGroupByNumber(tEpoch, entries[0].trim());
                bookRandomizationEntry.setStratumGroup(sGroup);
                sGroup.getBookRandomizationEntry().add(bookRandomizationEntry);
                // set the position
                Integer position = null;
                try {
                    position = Integer.valueOf(entries[1].trim());
                } catch (NumberFormatException nfe) {
                    log.debug("Illegal Position Entered.");
                }
                bookRandomizationEntry.setPosition(position);
                // find the arm with this id and set it here even if its null
                // Empty stratum groups with negetive stratum Group Numbers and arms are checked
                // for while generating the table and replaced with the string 
                // "Invalid Entry" so the user can see which entries are incorrect.
                arm = getArmByName(tEpoch, entries[2].trim());
                bookRandomizationEntry.setArm(arm);
            }
        }
    } catch (Exception e) {
        log.error("parseBookRandomizatrion Failed");
        log.error(e.getMessage());
        throw e;
    }
}

From source file:dicky.controlleruser.CartController.java

@RequestMapping(value = "checkout", method = RequestMethod.GET)
public String checkout(HttpSession session, ModelMap modelMap) {
    modelMap.put("title", "Pembelian Barang");
    if (session.getAttribute("username") == null) {
        modelMap.put("message", "Anda harus mengisi terlebih dahulu data belanjaan");
        return "account.myaccount";
    } else {/*from w  w w . j a  va  2s .com*/
        Orders orders = new Orders();
        orders.setAccount(accountService.find(session.getAttribute("username").toString()));
        orders.setTanggal(new Date());
        Orders newOrders = ordersService.create(orders);

        List<Item> cart = (List<Item>) session.getAttribute("cart");
        for (Item item : cart) {
            OrdersDetail ordersDetail = new OrdersDetail();
            ordersDetail.setId(new OrdersDetailId(newOrders.getIdOrders(), item.getProduct().getIdProduct()));
            ordersDetail.setPrice(item.getProduct().getPrice());
            ordersDetail.setQuantity(item.getQuantity());
            ordersDetailService.create(ordersDetail);
        }

        session.removeAttribute("username");
        cart.clear();
        return "cart.thanks";
    }

}

From source file:com.tesora.dve.server.connectionmanager.loaddata.LoadDataBlockExecutor.java

public static void executeInsert(ChannelHandlerContext ctx, SSConnection connMgr, List<List<byte[]>> rows)
        throws Throwable {

    MyLoadDataInfileContext loadDataInfileContext = ctx
            .attr(MyLoadDataInfileContext.LOAD_DATA_INFILE_CONTEXT_KEY).get();
    if (loadDataInfileContext == null) {
        throw new PEException(
                "Cannot process Load Data Infile data block because load data infile context is missing.");
    }//from  www.j  a  v a  2 s  .  c o m

    if (loadDataInfileContext.getCharset() == null) {
        loadDataInfileContext
                .setCharset(KnownVariables.CHARACTER_SET_CLIENT.getSessionValue(connMgr).getJavaCharset());
    }

    List<Object> params = new ArrayList<Object>();
    int targetNumTuples = rows.size();
    int currentTupleCount = 1;

    for (List<byte[]> cols : rows) {

        if (cols.size() == 0)
            continue;

        buildInsertStatement(loadDataInfileContext, cols, params);

        if (optimalTuples(loadDataInfileContext, targetNumTuples, currentTupleCount)) {
            MyPreparedStatement<String> pStmt = loadDataInfileContext.getPreparedStatement(currentTupleCount);
            if (pStmt == null) {
                throw new PEException("A prepared statement with no id found in the connection's context");
            }

            MysqlSyntheticPreparedResultForwarder resultConsumer = new MysqlSyntheticPreparedResultForwarder(
                    ctx);

            ExecutePreparedStatementRequestExecutor.execute(connMgr, pStmt.getStmtId(), params, resultConsumer);

            loadDataInfileContext.incrementRowsAffected(resultConsumer.getNumRowsAffected());
            loadDataInfileContext.incrementInfileWarnings(resultConsumer.getWarnings());

            targetNumTuples -= currentTupleCount;
            params.clear();
            currentTupleCount = 0;
        }
        currentTupleCount++;
    }
}

From source file:io.cloudslang.engine.queue.services.ExecutionQueueServiceTest.java

@Test
public void pollWithoutAckTest() throws Exception {
    Multimap<String, String> groupWorkerMap = ArrayListMultimap.create();
    groupWorkerMap.put("group1", "worker1");
    groupWorkerMap.put("group1", "worker2");
    when(workerNodeService/*from   w ww  .  j  a  va 2 s .  c om*/
            .readGroupWorkersMapActiveAndRunningAndVersion(engineVersionService.getEngineVersionId()))
                    .thenReturn(groupWorkerMap);

    when(versionService.getCurrentVersion(anyString())).thenReturn(0L);

    List<ExecutionMessage> msgInQueue = executionQueueService.pollMessagesWithoutAck(100, 0);
    Assert.assertEquals(0, msgInQueue.size());

    ExecutionMessage message1 = generateMessage("group1", "5");
    message1.setWorkerId("worker1");
    message1.setStatus(ExecStatus.SENT);

    msgInQueue.clear();
    msgInQueue.add(message1);

    executionQueueService.enqueue(msgInQueue);

    //now we set current system version(100) to be mush higher then msg version (0)
    msgInQueue = executionQueueService.pollMessagesWithoutAck(100, 100);
    Assert.assertEquals(1, msgInQueue.size());

}

From source file:com.hypersocket.client.HypersocketClient.java

protected boolean parseLogonJSON(String json, Map<String, String> params, List<Prompt> prompts)
        throws ParseException, IOException {

    JSONParser parser = new JSONParser();
    prompts.clear();

    JSONObject result = (JSONObject) parser.parse(json);
    if (!(Boolean) result.get("success")) {
        JSONObject template = (JSONObject) result.get("formTemplate");
        JSONArray fields = (JSONArray) template.get("inputFields");
        Boolean lastResultSuccessfull = (Boolean) result.get("lastResultSuccessfull");
        @SuppressWarnings("unchecked")
        Iterator<JSONObject> it = (Iterator<JSONObject>) fields.iterator();
        while (it.hasNext()) {
            JSONObject field = it.next();

            PromptType type = PromptType.TEXT;
            try {
                type = PromptType.valueOf(field.get("type").toString().toUpperCase());
            } catch (IllegalArgumentException iae) {
                log.warn("Unknown prompt type, default to text.", iae);
            }/*from  w w w. j a v  a2  s .  c om*/

            switch (type) {
            case HIDDEN: {
                params.put((String) field.get("resourceKey"), (String) field.get("defaultValue"));
                break;
            }
            case SELECT: {
                Prompt p = new Prompt(type, (String) field.get("resourceKey"),
                        (String) field.get("defaultValue"));
                JSONArray options = (JSONArray) field.get("options");
                @SuppressWarnings("unchecked")
                Iterator<JSONObject> it2 = (Iterator<JSONObject>) options.iterator();
                while (it2.hasNext()) {
                    JSONObject o = it2.next();
                    Boolean isResourceKey = (Boolean) o.get("isNameResourceKey");
                    p.addOption(new Option(
                            isResourceKey ? I18N.getResource((String) o.get("name")) : (String) o.get("name"),
                            (String) o.get("value"), (Boolean) o.get("selected")));
                }
                prompts.add(p);
                break;
            }
            default: {
                prompts.add(new Prompt(type, (String) field.get("resourceKey"),
                        (String) field.get("defaultValue")));
                break;
            }
            }

        }

        return lastResultSuccessfull == null ? true : lastResultSuccessfull;
    } else {
        JSONObject session = (JSONObject) result.get("session");
        sessionId = (String) session.get("id");
        principalName = (String) ((JSONObject) session.get("currentPrincipal")).get("principalName");
        return true;
    }
}

From source file:io.cloudslang.engine.queue.services.ExecutionQueueServiceTest.java

@Test
public void pollWithoutAckTestInProgressState() throws Exception {
    Multimap<String, String> groupWorkerMap = ArrayListMultimap.create();
    groupWorkerMap.put("group1", "worker1");
    groupWorkerMap.put("group1", "worker2");
    when(workerNodeService//w  w w.j ava 2s. co  m
            .readGroupWorkersMapActiveAndRunningAndVersion(engineVersionService.getEngineVersionId()))
                    .thenReturn(groupWorkerMap);

    when(versionService.getCurrentVersion(anyString())).thenReturn(0L);

    List<ExecutionMessage> msgInQueue = executionQueueService.pollMessagesWithoutAck(100, 0);
    Assert.assertEquals(0, msgInQueue.size());

    ExecutionMessage message1 = generateMessage("group1", "5");
    message1.setWorkerId("worker1");
    message1.setStatus(ExecStatus.IN_PROGRESS);

    msgInQueue.clear();
    msgInQueue.add(message1);

    executionQueueService.enqueue(msgInQueue);

    //now we set current system version(100) to be mush higher then msg version (0)
    msgInQueue = executionQueueService.pollMessagesWithoutAck(100, 100);
    Assert.assertEquals("since we sent a msg in IN_PROGRESS status, pollMessagesWithoutAck should not find it",
            0, msgInQueue.size());
}

From source file:me.springframework.di.spring.AutowiringAugmentation.java

private void attributeConstructor(final MutableInstance instance, final MutableContext context) {

    final JavaClass cl = builder.getClassByName(instance.getType());
    final List<JavaMethod> matchingConstructors = findMatchingConstructors(cl, instance, context);
    sortConstructors(matchingConstructors);

    final List<MutableConstructorArgument> arguments = new ArrayList<MutableConstructorArgument>();

    constructorsearch: for (final JavaMethod constructor : matchingConstructors) {
        // starting from the best constructor try to match

        arguments.clear();

        int i = 0;
        int numArgs = instance.getConstructorArguments() == null ? 0
                : instance.getConstructorArguments().size();
        parametersearch: for (final JavaParameter parameter : constructor.getParameters()) {
            if (i < numArgs) {
                final MutableConstructorArgument arg = instance.getConstructorArguments().get(i);
                arg.setType(parameter.getType().getValue());
                arg.setPrimitive(parameter.getType().isPrimitive());
                arguments.add(arg);/*from w w  w  .  j  a  v a2 s .  c o  m*/
                i++;
                continue parametersearch;
            }
            // don't do autowiring for constructors with unset primitive types
            if (parameter.getType().isPrimitive()) {
                continue constructorsearch;
            }

            final MutableInstance newInstance;
            // try to find an instance by type
            newInstance = findInstanceByType(context, instance.getName(),
                    "constructor parameter " + parameter.getName(), parameter.getType().getValue());
            // proper bean not found
            if (newInstance == null || !newInstance.isAutowireCandidate()) {
                continue constructorsearch;
            }

            final MutableConstructorArgument arg = new MutableConstructorArgument(instance);
            final MutableInstanceReference ref = new MutableInstanceReference(arg, newInstance.getName());
            ref.setReferencedId(newInstance.getId());
            ref.setId("source_autowire" + counter++);
            arg.setPrimitive(false);
            arg.setSource(ref);
            arg.setType(newInstance.getType());
            arg.setInstance(instance);
            arguments.add(arg);
        }

        break;
    }

    if (arguments.size() > 0) {
        instance.setConstructorArguments(arguments);
    } else {
        throw new RuntimeException("could not autowire constructor in instance " + instance.getName()
                + ", type " + instance.getType());
    }
}

From source file:hoot.services.controllers.osm.OSMTestUtils.java

static Set<Long> createTestWays(long changesetId, Set<Long> nodeIds) throws Exception {
    Long[] nodeIdsArr = nodeIds.toArray(new Long[nodeIds.size()]);
    Map<String, String> tags = new HashMap<>();

    tags.put("key 1", "val 1");
    tags.put("key 2", "val 2");
    List<Long> wayNodeIds = new ArrayList<>();
    wayNodeIds.add(nodeIdsArr[0]);//w  w w  .jav  a 2 s. com
    wayNodeIds.add(nodeIdsArr[1]);
    wayNodeIds.add(nodeIdsArr[4]);
    Set<Long> wayIds = new LinkedHashSet<>();
    wayIds.add(insertNewWay(changesetId, getMapId(), wayNodeIds, tags));
    tags.clear();
    wayNodeIds.clear();

    wayNodeIds.add(nodeIdsArr[2]);
    wayNodeIds.add(nodeIdsArr[1]);
    wayIds.add(insertNewWay(changesetId, getMapId(), wayNodeIds, null));
    wayNodeIds.clear();

    tags.put("key 3", "val 3");
    wayNodeIds.add(nodeIdsArr[0]);
    wayNodeIds.add(nodeIdsArr[1]);
    wayIds.add(insertNewWay(changesetId, getMapId(), wayNodeIds, tags));
    tags.clear();
    wayNodeIds.clear();

    return wayIds;
}