Example usage for java.util ListIterator previous

List of usage examples for java.util ListIterator previous

Introduction

In this page you can find the example usage for java.util ListIterator previous.

Prototype

E previous();

Source Link

Document

Returns the previous element in the list and moves the cursor position backwards.

Usage

From source file:Heuristics.TermLevelHeuristics.java

public boolean isQuestionMarkAtEndOfStatus(String status) {
    List<String> terms = new ArrayList();
    Collections.addAll(terms, status.split(" "));
    StringBuilder sb = new StringBuilder();
    boolean cleanEnd = false;
    ListIterator<String> termsIterator = terms.listIterator(terms.size());
    while (termsIterator.hasPrevious() & !cleanEnd) {
        String string = termsIterator.previous();
        if (!cleanEnd && (string.contains("/") || string.startsWith("#") || string.startsWith("@")
                || string.equals("\\|") || string.equals("") || string.contains("via")
                || string.equals("..."))) {
            continue;
        } else {//from www  .  jav  a  2s . c  o  m
            cleanEnd = true;
        }
        sb.insert(0, string);
    }
    status = sb.toString().trim();
    if (status.length() == 0) {
        return false;
    } else {
        return ("?".equals(String.valueOf(status.charAt(status.length() - 1)))) ? true : false;
    }
}

From source file:org.apache.stratos.autoscaler.service.util.IaasContext.java

/**
 * This will return the node id of the node which is belong to the
 * requesting domain, sub domain and which is the most recently created. If it cannot find a
 * matching node id, this will return <code>null</code>.
 * @param domain service domain./*from  w  w w  .j a  va2 s.  c  o  m*/
 * @param subDomain service sub domain. 
 * @return the node Id of the node
 */
public String getLastMatchingNode(String domain, String subDomain) {

    InstanceContext ctx = getInstanceContext(domain, subDomain);

    if (ctx == null) {
        return null;
    }

    // iterate in reverse order
    ListIterator<String> iter = new ArrayList<String>(ctx.getNodeIdToIpMap().keySet())
            .listIterator(ctx.getNodeIdToIpMap().size());

    if (iter.hasPrevious()) {
        return iter.previous();
    }

    return null;
}

From source file:org.apache.cayenne.unit.di.server.SchemaBuilder.java

private void dropSchema(DataNode node, DataMap map) throws Exception {

    List<DbEntity> list = dbEntitiesInInsertOrder(node, map);

    try (Connection conn = dataSourceFactory.getSharedDataSource().getConnection();) {

        DatabaseMetaData md = conn.getMetaData();
        List<String> allTables = new ArrayList<String>();

        try (ResultSet tables = md.getTables(null, null, "%", null)) {
            while (tables.next()) {
                // 'toUpperCase' is needed since most databases
                // are case insensitive, and some will convert names to
                // lower
                // case
                // (PostgreSQL)
                String name = tables.getString("TABLE_NAME");
                if (name != null)
                    allTables.add(name.toUpperCase());
            }/*w w  w.j a va2  s .  c o  m*/
        }

        unitDbAdapter.willDropTables(conn, map, allTables);

        // drop all tables in the map
        try (Statement stmt = conn.createStatement();) {

            ListIterator<DbEntity> it = list.listIterator(list.size());
            while (it.hasPrevious()) {
                DbEntity ent = it.previous();
                if (!allTables.contains(ent.getName().toUpperCase())) {
                    continue;
                }

                for (String dropSql : node.getAdapter().dropTableStatements(ent)) {
                    try {
                        logger.info(dropSql);
                        stmt.execute(dropSql);
                    } catch (SQLException sqe) {
                        logger.warn("Can't drop table " + ent.getName() + ", ignoring...", sqe);
                    }
                }
            }
        }

        unitDbAdapter.droppedTables(conn, map);
    }
}

From source file:com.berinchik.sip.FlexibleCommunicationServlet.java

@Override
protected void doRegister(SipServletRequest request) throws ServletException, IOException {

    logger.trace("Got REGISTER:\n" + request);
    normaliseRegisterRequest(request);//w w w .j a  v  a2s.c o m
    logger.trace("normalisation performed");
    logMessageInfo(request);

    Registrar registrar = CommonUtils.getRegistrarHelper(request);

    URI toURI = request.getTo().getURI();

    ListIterator<Address> contacts = request.getAddressHeaders(CommonUtils.SC_CONTACT_HEADER);

    Address firstContact = null;
    if (contacts.hasNext()) {
        firstContact = contacts.next();
        contacts.previous();
        logger.trace("contact: " + firstContact);
    }

    SipServletResponse resp = null;

    try {
        logger.info("trying to register");
        if (registrar == null) {
            logger.error("registrar not initialised!!!");
            throw new RuntimeException("Registrar is not initialised");
        }

        if (!registrar.isPrimary(toURI.toString())) {
            logger.debug("Primary user " + toURI + " not found during registration");
            resp = request.createResponse(SC_NOT_FOUND, "No such user");
        } else if (firstContact == null) {
            logger.debug("No contact headers during registration to " + toURI + "\nReturning all bindings");

            resp = registrar.createRegisterSuccessResponse(request);
        } else if (firstContact.isWildcard()) {
            logger.debug("First contact is Wildcard");
            if (request.getExpires() == 0) {
                logger.debug("Contact = *, Expire = 0: complete de registration");
                registrar.deregisterUser(toURI.toString());
                resp = request.createResponse(SC_OK, "Ok");
                resp.removeHeader(CommonUtils.SC_EXPIRES_HEADER);
            } else {
                logger.debug("Contact = *, Expire != 0: request could not be understood");
                resp = request.createResponse(SC_BAD_REQUEST, "Bad request");
            }
        } else if (request.getExpires() == 0) {
            logger.info("Request is recognized as de registration" + "\ncontact - " + firstContact + "\nuser - "
                    + toURI);
            registrar.deregisterUser(toURI.toString(), firstContact.getURI().toString());
            resp = request.createResponse(SC_OK, "Ok");
            resp.removeHeader(CommonUtils.SC_EXPIRES_HEADER);
        } else {
            logger.debug("Request is recognized as registration request");
            while (contacts.hasNext()) {

                Address nextContact = contacts.next();

                logger.trace("Trying to register contact " + nextContact.getURI() + " to user " + toURI);

                int expires = CommonUtils.getExpires(nextContact, request);

                registrar.registerUser(toURI.toString(), nextContact.getURI().toString(), expires);
            }

            resp = registrar.createRegisterSuccessResponse(request);
        }
    } catch (SQLException e) {
        logger.error("SQL Exception durin registration", e);
        resp = request.createResponse(SC_SERVER_INTERNAL_ERROR, "Server internal error");
    } catch (RuntimeException e) {
        logger.error("Runtime exception", e);
        resp = request.createResponse(SC_SERVER_INTERNAL_ERROR, "Server internal error");
    }

    logger.trace("Sending response: \n" + resp);

    resp.send();
}

From source file:org.cipango.callflow.JmxMessageLog.java

public void setMaxMessages(int maxMessages) {
    if (maxMessages <= 0)
        throw new IllegalArgumentException("Max message must be greater than 0");
    synchronized (this) {
        if (isRunning() && maxMessages != _maxMessages) {
            MessageInfo[] messages = new MessageInfo[maxMessages];
            ListIterator<MessageInfo> it = iterate(false);
            int index = maxMessages;
            while (it.hasPrevious()) {
                messages[--index] = it.previous();
                if (index == 0)
                    break;
            }/* w  w  w. j  a  va2  s  .  c  o  m*/
            _cursor = 0;
            _messages = messages;
        }
        _maxMessages = maxMessages;
    }
}

From source file:com.tesora.dve.distribution.DistributionRange.java

public MappingSolution mapKeyToGeneration(IKeyValue key) throws PEException {
    StorageGroupGeneration groupGen = storageGroup.getLastGen();

    setComparatorClass(key);//from   www  .j  a  va 2 s .co  m
    ListIterator<GenerationKeyRange> i = rangeGenerations.listIterator(rangeGenerations.size());
    while (i.hasPrevious()) {
        //TODO: this traverses from youngest to oldest, but returns oldest match or lastGen(), which can be confusing.  -sgossard
        GenerationKeyRange genKeyRange = i.previous();
        if (genKeyRange.isInRange(key))
            groupGen = genKeyRange.getStorageGroupGeneration();
        else
            break;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Mapping key " + key.toString() + " to generation " + groupGen.getVersion()
                + " using range " + this + " which has " + rangeGenerations.size()
                + " generations and is rep'd by object " + System.identityHashCode(this));
    }

    return getMappingInGeneration(key, groupGen);
}

From source file:brut.androlib.src.SmaliBuilder.java

private void buildFile(String fileName, DexBuilder dexBuilder) throws AndrolibException, IOException {
    File inFile = new File(mSmaliDir, fileName);
    InputStream inStream = new FileInputStream(inFile);

    if (fileName.endsWith(".smali")) {
        try {//from   w w w.j  a  v  a  2s. c  om
            if (!SmaliMod.assembleSmaliFile(inFile, dexBuilder, false, false)) {
                throw new AndrolibException("Could not smali file: " + fileName);
            }
        } catch (IOException | RecognitionException ex) {
            throw new AndrolibException(ex);
        }
        return;
    }
    if (!fileName.endsWith(".java")) {
        LOGGER.warning("Unknown file type, ignoring: " + inFile);
        return;
    }

    StringBuilder out = new StringBuilder();
    List<String> lines = IOUtils.readLines(inStream);

    if (!mDebug) {
        final String[] linesArray = lines.toArray(new String[0]);
        for (int i = 1; i < linesArray.length - 1; i++) {
            out.append(linesArray[i].split("//", 2)[1]).append('\n');
        }
    } else {
        lines.remove(lines.size() - 1);
        ListIterator<String> it = lines.listIterator(1);

        out.append(".source \"").append(inFile.getName()).append("\"\n");
        while (it.hasNext()) {
            String line = it.next().split("//", 2)[1].trim();
            if (line.isEmpty() || line.charAt(0) == '#' || line.startsWith(".source")) {
                continue;
            }
            if (line.startsWith(".method ")) {
                it.previous();
                DebugInjector.inject(it, out);
                continue;
            }

            out.append(line).append('\n');
        }
    }

    try {
        if (!SmaliMod.assembleSmaliFile(out.toString(), dexBuilder, false, false, inFile)) {
            throw new AndrolibException("Could not smali file: " + fileName);
        }
    } catch (IOException | RecognitionException ex) {
        throw new AndrolibException(ex);
    }
}

From source file:org.xchain.impl.CommandList.java

public boolean execute(JXPathContext context) throws Exception {
    // Verify our parameters
    if (context == null) {
        throw new IllegalArgumentException();
    }/*from  w  w  w . ja  va  2 s  .  co m*/

    // Execute the commands in this list until one returns true
    // or throws an exception
    boolean saveResult = false;
    Exception saveException = null;
    ListIterator<Command> iterator = listIterator();
    while (iterator.hasNext()) {
        try {
            saveResult = iterator.next().execute(context);
            if (saveResult) {
                break;
            }
        } catch (Exception e) {
            saveException = e;
            break;
        }
    }

    boolean handled = false;
    boolean result = false;
    while (iterator.hasPrevious()) {
        Object previous = iterator.previous();
        if (previous instanceof Filter) {
            try {
                result = ((Filter) previous).postProcess(context, saveException);
                if (result) {
                    handled = true;
                }
            } catch (Exception e) {
                // Silently ignore
            }
        }
    }

    // Return the exception or result state from the last execute()
    if ((saveException != null) && !handled) {
        throw saveException;
    } else {
        return (saveResult);
    }
}

From source file:org.flowable.cmmn.converter.ConversionHelper.java

public void addExitCriteriaToCurrentElement(Criterion exitCriterion) {
    addExitCriterion(exitCriterion);//w ww.ja  v a  2 s  .com

    ListIterator<CmmnElement> iterator = currentCmmnElements.listIterator(currentCmmnElements.size());
    HasExitCriteria hasExitCriteria = null;
    while (hasExitCriteria == null && iterator.hasPrevious()) {
        CmmnElement cmmnElement = iterator.previous();
        if (cmmnElement instanceof HasExitCriteria) {
            hasExitCriteria = (HasExitCriteria) cmmnElement;
        }
    }

    if (hasExitCriteria == null) {
        hasExitCriteria = getCurrentCase().getPlanModel();
    }

    if (StringUtils.isEmpty(exitCriterion.getId())) {
        // An id is expected by the evaluation algorithm, so setting an internal one if there isn't one
        exitCriterion.setId("exitCriterion_" + (hasExitCriteria.getExitCriteria().size() + 1));
    }

    exitCriterion.setAttachedToRefId(hasExitCriteria.getId());
    hasExitCriteria.getExitCriteria().add(exitCriterion);
}

From source file:therian.operator.add.AddToListIterator.java

@Override
@SuppressWarnings("unchecked")
public boolean perform(TherianContext context, Add<?, ? extends ListIterator<?>> add) {
    @SuppressWarnings("rawtypes")
    final ListIterator listIterator = add.getTargetPosition().getValue();

    int mark = 0;
    while (listIterator.hasNext()) {
        listIterator.next();//from  w  w  w  .j  a v a  2  s . c  o m
        mark++;
    }
    try {
        listIterator.add(add.getSourcePosition().getValue());
        add.setResult(true);
        return true;
    } catch (UnsupportedOperationException e) {
        return false;
    } finally {
        for (; mark >= 0; mark--) {
            listIterator.previous();
        }
    }
}