Example usage for java.util LinkedList addFirst

List of usage examples for java.util LinkedList addFirst

Introduction

In this page you can find the example usage for java.util LinkedList addFirst.

Prototype

public void addFirst(E e) 

Source Link

Document

Inserts the specified element at the beginning of this list.

Usage

From source file:net.sourceforge.fenixedu.domain.Person.java

public List<Photograph> getPhotographHistory() {
    final LinkedList<Photograph> history = new LinkedList<Photograph>();
    for (Photograph photo = super.getPersonalPhoto(); photo != null; photo = photo.getPrevious()) {
        history.addFirst(photo);
    }//ww w.  j  a v  a2 s.  c  om
    return history;
}

From source file:org.sakaiproject.content.tool.ListItem.java

/**
 * @return/* w  ww  .j  ava  2s  .com*/
 */
public List<ListItem> getCollectionPath() {
    LinkedList<ListItem> path = new LinkedList<ListItem>();
    if (contentService == null) {
        contentService = (org.sakaiproject.content.api.ContentHostingService) ComponentManager
                .get(org.sakaiproject.content.api.ContentHostingService.class);
    }

    ContentCollection containingCollection = null;
    ContentEntity entity = this.getEntity();
    if (entity == null) {
        try {
            containingCollection = contentService.getCollection(this.containingCollectionId);

        } catch (IdUnusedException e) {
            logger.warn("IdUnusedException " + e);
        } catch (TypeException e) {
            logger.warn("TypeException " + e);
        } catch (PermissionException e) {
            logger.warn("PermissionException " + e);
        }

    } else {
        containingCollection = entity.getContainingCollection();
    }

    ListItem previousItem = null;
    while (containingCollection != null && !contentService.isRootCollection(containingCollection.getId())) {
        if (previousItem != null) {
            path.addFirst(previousItem);
        }
        previousItem = new ListItem(containingCollection);
        containingCollection = containingCollection.getContainingCollection();
    }
    //      if(containingCollection != null)
    //      {
    //         path.addFirst(new ListItem(containingCollection));
    //      }

    return path;
}

From source file:org.sakaiproject.content.tool.FilePickerAction.java

/**
 * @param state// ww  w  .j a v  a2  s . co m
 * @param homeCollectionId
 * @param currentCollectionId
 * @return
 */
public static List getCollectionPath(SessionState state) {
    logger.debug("ResourcesAction.getCollectionPath()");
    org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state
            .getAttribute(STATE_CONTENT_SERVICE);
    // make sure the channedId is set
    String currentCollectionId = (String) state.getAttribute(STATE_COLLECTION_ID);
    String homeCollectionId = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
    String navRoot = (String) state.getAttribute(STATE_NAVIGATION_ROOT);

    LinkedList collectionPath = new LinkedList();

    String previousCollectionId = "";
    List pathitems = new ArrayList();
    while ((currentCollectionId != null) && (!currentCollectionId.equals(navRoot))
            && (!currentCollectionId.equals(previousCollectionId))
            && !(contentService.ROOT_COLLECTIONS.contains(currentCollectionId))
            && (!contentService.isRootCollection(previousCollectionId))) {
        pathitems.add(currentCollectionId);
        previousCollectionId = currentCollectionId;
        currentCollectionId = contentService.getContainingCollectionId(currentCollectionId);
    }

    if (navRoot != null && (pathitems.isEmpty()
            || (!navRoot.equals(previousCollectionId) && !navRoot.equals(currentCollectionId)))) {
        pathitems.add(navRoot);

    }
    if (homeCollectionId != null && (pathitems.isEmpty()
            || (!homeCollectionId.equals(navRoot) && !homeCollectionId.equals(previousCollectionId)
                    && !homeCollectionId.equals(currentCollectionId)))) {
        pathitems.add(homeCollectionId);
    }

    Iterator items = pathitems.iterator();
    while (items.hasNext()) {
        String id = (String) items.next();
        try {
            ResourceProperties props = contentService.getProperties(id);
            String name = props.getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
            String containingCollectionId = contentService.getContainingCollectionId(id);
            if (contentService.COLLECTION_DROPBOX.equals(containingCollectionId)) {
                Reference ref = EntityManager.newReference(contentService.getReference(id));
                Site site = SiteService.getSite(ref.getContext());
                String[] args = { site.getTitle() };
                name = trb.getFormattedMessage("title.dropbox", args);
            } else if (contentService.COLLECTION_SITE.equals(containingCollectionId)) {
                Reference ref = EntityManager.newReference(contentService.getReference(id));
                Site site = SiteService.getSite(ref.getContext());
                String[] args = { site.getTitle() };
                name = trb.getFormattedMessage("title.resources", args);
            }

            ChefPathItem item = new ChefPathItem(id, name);

            boolean canRead = contentService.allowGetCollection(id) || contentService.allowGetResource(id);
            item.setCanRead(canRead);

            if (canRead) {
                String url = contentService.getUrl(id);
                item.setUrl(url);
            }

            item.setLast(collectionPath.isEmpty());
            if (id.equals(homeCollectionId)) {
                item.setRoot(homeCollectionId);
            } else {
                item.setRoot(navRoot);
            }

            try {
                boolean isFolder = props.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION);
                item.setIsFolder(isFolder);
            } catch (EntityPropertyNotDefinedException e1) {
            } catch (EntityPropertyTypeException e1) {
            }

            collectionPath.addFirst(item);

        } catch (PermissionException e) {
        } catch (IdUnusedException e) {
        }
    }
    return collectionPath;
}

From source file:org.mycard.net.network.Connection.java

/***
 * Process requests in queue//  w w  w  . j a  v  a2 s. c  o  m
 * pipelines requests
 */
void processRequests(Request firstRequest) {
    Request req = null;
    boolean empty;
    int error = EventHandler.OK;
    Exception exception = null;

    LinkedList<Request> pipe = new LinkedList<Request>();

    int minPipe = MIN_PIPE, maxPipe = MAX_PIPE;
    int state = SEND;

    while (state != DONE) {
        /** If a request was cancelled, give other cancel requests
           some time to go through so we don't uselessly restart
           connections */
        if (mActive == STATE_CANCEL_REQUESTED) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException x) {
                /** ignore */
            }
            mActive = STATE_NORMAL;
        }

        switch (state) {
        case SEND: {
            if (pipe.size() == maxPipe) {
                state = READ;
                break;
            }
            /** get a request */
            if (firstRequest == null) {
                req = mRequestFeeder.getRequest(mHost);
            } else {
                req = firstRequest;
                firstRequest = null;
            }
            if (req == null) {
                state = DRAIN;
                break;
            }
            req.setConnection(this);

            /** Don't work on cancelled requests. */
            if (req.mCancelled) {
                req.complete();
                break;
            }

            if (mHttpClientConnection == null || !mHttpClientConnection.isOpen()) {
                /** If this call fails, the address is bad or
                   the net is down.  Punt for now.
                        
                   FIXME: blow out entire queue here on
                   connection failure if net up? */

                if (!openHttpConnection(req)) {
                    state = DONE;
                    break;
                }
            }

            /** we have a connection, let the event handler
             * know of any associated certificate,
             * potentially none.
             */
            //req.mEventHandler.certificate(mCertificate);

            try {
                /** FIXME: don't increment failure count if old
                   connection?  There should not be a penalty for
                   attempting to reuse an old connection */
                req.sendRequest(mHttpClientConnection);
            } catch (HttpException e) {
                exception = e;
                error = EventHandler.ERROR;
            } catch (IOException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            } catch (IllegalStateException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            }
            if (exception != null) {
                if (httpFailure(req, error, exception) && !req.mCancelled) {
                    /** retry request if not permanent failure
                       or cancelled */
                    pipe.addLast(req);
                }
                exception = null;
                state = clearPipe(pipe) ? DONE : SEND;
                minPipe = maxPipe = 1;
                break;
            }

            pipe.addLast(req);
            if (!mCanPersist)
                state = READ;
            break;

        }
        case DRAIN:
        case READ: {
            empty = !mRequestFeeder.haveRequest(mHost);
            int pipeSize = pipe.size();
            if (state != DRAIN && pipeSize < minPipe && !empty && mCanPersist) {
                state = SEND;
                break;
            } else if (pipeSize == 0) {
                /** Done if no other work to do */
                state = empty ? DONE : SEND;
                break;
            }

            req = (Request) pipe.removeFirst();

            try {
                req.readResponse(mHttpClientConnection);
            } catch (ParseException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            } catch (IOException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            } catch (IllegalStateException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            }
            if (exception != null) {
                if (httpFailure(req, error, exception) && !req.mCancelled) {
                    /** retry request if not permanent failure
                       or cancelled */
                    req.reset();
                    pipe.addFirst(req);
                }
                exception = null;
                mCanPersist = false;
            }
            if (!mCanPersist) {

                closeConnection();

                mHttpContext.removeAttribute(HTTP_CONNECTION);
                clearPipe(pipe);
                minPipe = maxPipe = 1;
                state = SEND;
            }
            break;
        }
        }
    }
}

From source file:android.net.http.Connection.java

/**
 * Process requests in queue/*  w w  w  .  j  a  va2 s . co  m*/
 * pipelines requests
 */
void processRequests(Request firstRequest) {
    Request req = null;
    boolean empty;
    int error = EventHandler.OK;
    Exception exception = null;

    LinkedList<Request> pipe = new LinkedList<Request>();

    int minPipe = MIN_PIPE, maxPipe = MAX_PIPE;
    int state = SEND;

    while (state != DONE) {
        if (HttpLog.LOGV)
            HttpLog.v(states[state] + " pipe " + pipe.size());

        /* If a request was cancelled, give other cancel requests
           some time to go through so we don't uselessly restart
           connections */
        if (mActive == STATE_CANCEL_REQUESTED) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException x) {
                /* ignore */ }
            mActive = STATE_NORMAL;
        }

        switch (state) {
        case SEND: {
            if (pipe.size() == maxPipe) {
                state = READ;
                break;
            }
            /* get a request */
            if (firstRequest == null) {
                req = mRequestFeeder.getRequest(mHost);
            } else {
                req = firstRequest;
                firstRequest = null;
            }
            if (req == null) {
                state = DRAIN;
                break;
            }
            req.setConnection(this);

            /* Don't work on cancelled requests. */
            if (req.mCancelled) {
                if (HttpLog.LOGV)
                    HttpLog.v("processRequests(): skipping cancelled request " + req);
                req.complete();
                break;
            }

            if (mHttpClientConnection == null || !mHttpClientConnection.isOpen()) {
                /* If this call fails, the address is bad or
                   the net is down.  Punt for now.
                        
                   FIXME: blow out entire queue here on
                   connection failure if net up? */

                if (!openHttpConnection(req)) {
                    state = DONE;
                    break;
                }
            }

            try {
                /* FIXME: don't increment failure count if old
                   connection?  There should not be a penalty for
                   attempting to reuse an old connection */
                req.sendRequest(mHttpClientConnection);
            } catch (HttpException e) {
                exception = e;
                error = EventHandler.ERROR;
            } catch (IOException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            } catch (IllegalStateException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            }
            if (exception != null) {
                if (httpFailure(req, error, exception) && !req.mCancelled) {
                    /* retry request if not permanent failure
                       or cancelled */
                    pipe.addLast(req);
                }
                exception = null;
                state = clearPipe(pipe) ? DONE : SEND;
                minPipe = maxPipe = 1;
                break;
            }

            pipe.addLast(req);
            if (!mCanPersist)
                state = READ;
            break;

        }
        case DRAIN:
        case READ: {
            empty = !mRequestFeeder.haveRequest(mHost);
            int pipeSize = pipe.size();
            if (state != DRAIN && pipeSize < minPipe && !empty && mCanPersist) {
                state = SEND;
                break;
            } else if (pipeSize == 0) {
                /* Done if no other work to do */
                state = empty ? DONE : SEND;
                break;
            }

            req = (Request) pipe.removeFirst();
            if (HttpLog.LOGV)
                HttpLog.v("processRequests() reading " + req);

            try {
                req.readResponse(mHttpClientConnection);
            } catch (ParseException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            } catch (IOException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            } catch (IllegalStateException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            }
            if (exception != null) {
                if (httpFailure(req, error, exception) && !req.mCancelled) {
                    /* retry request if not permanent failure
                       or cancelled */
                    req.reset();
                    pipe.addFirst(req);
                }
                exception = null;
                mCanPersist = false;
            }
            if (!mCanPersist) {
                if (HttpLog.LOGV)
                    HttpLog.v("processRequests(): no persist, closing " + mHost);

                closeConnection();

                mHttpContext.removeAttribute(HTTP_CONNECTION);
                clearPipe(pipe);
                minPipe = maxPipe = 1;
                state = SEND;
            }
            break;
        }
        }
    }
}

From source file:android.net.http.Connection.java

/**
 * Process requests in queue/* w  w  w.j av  a2s.  c o  m*/
 * pipelines requests
 */
void processRequests(Request firstRequest) {
    Request req = null;
    boolean empty;
    int error = EventHandler.OK;
    Exception exception = null;

    LinkedList<Request> pipe = new LinkedList<Request>();

    int minPipe = MIN_PIPE, maxPipe = MAX_PIPE;
    int state = SEND;

    while (state != DONE) {
        if (HttpLog.LOGV)
            HttpLog.v(states[state] + " pipe " + pipe.size());

        /* If a request was cancelled, give other cancel requests
           some time to go through so we don't uselessly restart
           connections */
        if (mActive == STATE_CANCEL_REQUESTED) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException x) {
                /* ignore */ }
            mActive = STATE_NORMAL;
        }

        switch (state) {
        case SEND: {
            if (pipe.size() == maxPipe) {
                state = READ;
                break;
            }
            /* get a request */
            if (firstRequest == null) {
                req = mRequestFeeder.getRequest(mHost);
            } else {
                req = firstRequest;
                firstRequest = null;
            }
            if (req == null) {
                state = DRAIN;
                break;
            }
            req.setConnection(this);

            /* Don't work on cancelled requests. */
            if (req.mCancelled) {
                if (HttpLog.LOGV)
                    HttpLog.v("processRequests(): skipping cancelled request " + req);
                req.complete();
                break;
            }

            if (mHttpClientConnection == null || !mHttpClientConnection.isOpen()) {
                /* If this call fails, the address is bad or
                   the net is down.  Punt for now.
                        
                   FIXME: blow out entire queue here on
                   connection failure if net up? */

                if (!openHttpConnection(req)) {
                    state = DONE;
                    break;
                }
            }

            /* we have a connection, let the event handler
             * know of any associated certificate,
             * potentially none.
             */
            req.mEventHandler.certificate(mCertificate);

            try {
                /* FIXME: don't increment failure count if old
                   connection?  There should not be a penalty for
                   attempting to reuse an old connection */
                req.sendRequest(mHttpClientConnection);
            } catch (HttpException e) {
                exception = e;
                error = EventHandler.ERROR;
            } catch (IOException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            } catch (IllegalStateException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            }
            if (exception != null) {
                if (httpFailure(req, error, exception) && !req.mCancelled) {
                    /* retry request if not permanent failure
                       or cancelled */
                    pipe.addLast(req);
                }
                exception = null;
                state = clearPipe(pipe) ? DONE : SEND;
                minPipe = maxPipe = 1;
                break;
            }

            pipe.addLast(req);
            if (!mCanPersist)
                state = READ;
            break;

        }
        case DRAIN:
        case READ: {
            empty = !mRequestFeeder.haveRequest(mHost);
            int pipeSize = pipe.size();
            if (state != DRAIN && pipeSize < minPipe && !empty && mCanPersist) {
                state = SEND;
                break;
            } else if (pipeSize == 0) {
                /* Done if no other work to do */
                state = empty ? DONE : SEND;
                break;
            }

            req = (Request) pipe.removeFirst();
            if (HttpLog.LOGV)
                HttpLog.v("processRequests() reading " + req);

            try {
                req.readResponse(mHttpClientConnection);
            } catch (ParseException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            } catch (IOException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            } catch (IllegalStateException e) {
                exception = e;
                error = EventHandler.ERROR_IO;
            }
            if (exception != null) {
                if (httpFailure(req, error, exception) && !req.mCancelled) {
                    /* retry request if not permanent failure
                       or cancelled */
                    req.reset();
                    pipe.addFirst(req);
                }
                exception = null;
                mCanPersist = false;
            }
            if (!mCanPersist) {
                if (HttpLog.LOGV)
                    HttpLog.v("processRequests(): no persist, closing " + mHost);

                closeConnection();

                mHttpContext.removeAttribute(HTTP_CONNECTION);
                clearPipe(pipe);
                minPipe = maxPipe = 1;
                state = SEND;
            }
            break;
        }
        }
    }
}

From source file:com.joliciel.talismane.TalismaneImpl.java

public void analyse(TalismaneConfig config) {
    try {/* w  w  w  .jav  a2s .  co m*/
        if (config.needsSentenceDetector()) {
            if (config.getSentenceDetector() == null) {
                throw new TalismaneException("Sentence detector not provided.");
            }
        }
        if (config.needsTokeniser()) {
            if (config.getTokeniser() == null) {
                throw new TalismaneException("Tokeniser not provided.");
            }
        }
        if (config.needsPosTagger()) {
            if (config.getPosTagger() == null) {
                throw new TalismaneException("Pos-tagger not provided.");
            }
        }
        if (config.needsParser()) {
            if (config.getParser() == null) {
                throw new TalismaneException("Parser not provided.");
            }
        }

        if (config.getEndModule().equals(Module.SentenceDetector)) {
            if (this.getSentenceProcessor() == null) {
                throw new TalismaneException(
                        "No sentence processor provided with sentence detector end module, cannot generate output.");
            }
        }
        if (config.getEndModule().equals(Module.Tokeniser)) {
            if (this.getTokenSequenceProcessor() == null) {
                throw new TalismaneException(
                        "No token sequence processor provided with tokeniser end module, cannot generate output.");
            }
        }
        if (config.getEndModule().equals(Module.PosTagger)) {
            if (this.getPosTagSequenceProcessor() == null) {
                throw new TalismaneException(
                        "No postag sequence processor provided with pos-tagger end module, cannot generate output.");
            }
        }
        if (config.getEndModule().equals(Module.Parser)) {
            if (this.getParseConfigurationProcessor() == null) {
                throw new TalismaneException(
                        "No parse configuration processor provided with parser end module, cannot generate output.");
            }
        }

        LinkedList<String> textSegments = new LinkedList<String>();
        LinkedList<Sentence> sentences = new LinkedList<Sentence>();
        TokenSequence tokenSequence = null;
        PosTagSequence posTagSequence = null;

        RollingSentenceProcessor rollingSentenceProcessor = this.getFilterService()
                .getRollingSentenceProcessor(config.getFileName(), config.isProcessByDefault());
        Sentence leftover = null;
        if (config.getStartModule().equals(Module.SentenceDetector)
                || config.getStartModule().equals(Module.Tokeniser)) {
            // prime the sentence detector with two text segments, to ensure everything gets processed
            textSegments.addLast("");
            textSegments.addLast("");
        }

        StringBuilder stringBuilder = new StringBuilder();
        boolean finished = false;
        int sentenceCount = 0;

        String prevProcessedText = "";
        String processedText = "";
        String nextProcessedText = "";
        SentenceHolder prevSentenceHolder = null;

        int endBlockCharacterCount = 0;

        while (!finished) {
            if (config.getStartModule().equals(Module.SentenceDetector)
                    || config.getStartModule().equals(Module.Tokeniser)) {
                // Note SentenceDetector and Tokeniser start modules treated identically,
                // except that for SentenceDetector we apply a probabilistic sentence detector
                // whereas for Tokeniser we assume all sentence breaks are marked by filters

                // read characters from the reader, one at a time
                char c;
                int r = -1;
                try {
                    r = this.getReader().read();
                } catch (IOException e) {
                    LogUtils.logError(LOG, e);
                }

                if (r == -1) {
                    finished = true;
                    c = '\n';
                } else {
                    c = (char) r;
                }

                // Jump out if we have 3 consecutive end-block characters.
                if (c == config.getEndBlockCharacter()) {
                    endBlockCharacterCount++;
                    if (endBlockCharacterCount == 3) {
                        LOG.info("Three consecutive end-block characters. Exiting.");
                        finished = true;
                    }
                } else {
                    endBlockCharacterCount = 0;
                }

                // have sentence detector
                if (finished || (Character.isWhitespace(c) && stringBuilder.length() > config.getBlockSize())
                        || c == config.getEndBlockCharacter()) {
                    if (c == config.getEndBlockCharacter())
                        stringBuilder.append(c);
                    if (stringBuilder.length() > 0) {
                        String textSegment = stringBuilder.toString();
                        stringBuilder = new StringBuilder();

                        textSegments.add(textSegment);
                    } // is the current block > 0 characters?
                    if (c == config.getEndBlockCharacter()) {
                        textSegments.addLast("");
                    }
                } // is there a next block available?

                if (finished) {
                    if (stringBuilder.length() > 0) {
                        textSegments.addLast(stringBuilder.toString());
                        stringBuilder = new StringBuilder();
                    }
                    textSegments.addLast("");
                    textSegments.addLast("");
                    textSegments.addLast("");
                }

                if (c != config.getEndBlockCharacter())
                    stringBuilder.append(c);

                while (textSegments.size() >= 3) {
                    String prevText = textSegments.removeFirst();
                    String text = textSegments.removeFirst();
                    String nextText = textSegments.removeFirst();
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("prevText: " + prevText);
                        LOG.trace("text: " + text);
                        LOG.trace("nextText: " + nextText);
                    }

                    Set<TextMarker> textMarkers = new TreeSet<TextMarker>();
                    for (TextMarkerFilter textMarkerFilter : config.getTextMarkerFilters()) {
                        Set<TextMarker> result = textMarkerFilter.apply(prevText, text, nextText);
                        textMarkers.addAll(result);
                    }

                    // push the text segments back onto the beginning of Deque
                    textSegments.addFirst(nextText);
                    textSegments.addFirst(text);

                    SentenceHolder sentenceHolder = rollingSentenceProcessor.addNextSegment(text, textMarkers);
                    prevProcessedText = processedText;
                    processedText = nextProcessedText;
                    nextProcessedText = sentenceHolder.getText();

                    if (LOG.isTraceEnabled()) {
                        LOG.trace("prevProcessedText: " + prevProcessedText);
                        LOG.trace("processedText: " + processedText);
                        LOG.trace("nextProcessedText: " + nextProcessedText);
                    }

                    boolean reallyFinished = finished && textSegments.size() == 3;

                    if (prevSentenceHolder != null) {
                        if (config.getStartModule().equals(Module.SentenceDetector)) {
                            List<Integer> sentenceBreaks = config.getSentenceDetector()
                                    .detectSentences(prevProcessedText, processedText, nextProcessedText);
                            for (int sentenceBreak : sentenceBreaks) {
                                prevSentenceHolder.addSentenceBoundary(sentenceBreak);
                            }
                        }

                        List<Sentence> theSentences = prevSentenceHolder.getDetectedSentences(leftover);
                        leftover = null;
                        for (Sentence sentence : theSentences) {
                            if (sentence.isComplete() || reallyFinished) {
                                sentences.add(sentence);
                                sentenceCount++;
                            } else {
                                LOG.debug("Setting leftover to: " + sentence.getText());
                                leftover = sentence;
                            }
                        }
                        if (config.getMaxSentenceCount() > 0 && sentenceCount >= config.getMaxSentenceCount()) {
                            finished = true;
                        }
                    }
                    prevSentenceHolder = sentenceHolder;
                } // we have at least 3 text segments (should always be the case once we get started)
            } else if (config.getStartModule().equals(Module.PosTagger)) {
                if (config.getTokenCorpusReader().hasNextTokenSequence()) {
                    tokenSequence = config.getTokenCorpusReader().nextTokenSequence();
                } else {
                    tokenSequence = null;
                    finished = true;
                }
            } else if (config.getStartModule().equals(Module.Parser)) {
                if (config.getPosTagCorpusReader().hasNextPosTagSequence()) {
                    posTagSequence = config.getPosTagCorpusReader().nextPosTagSequence();
                } else {
                    posTagSequence = null;
                    finished = true;
                }
            } // which start module?

            boolean needToProcess = false;
            if (config.getStartModule().equals(Module.SentenceDetector)
                    || config.getStartModule().equals(Module.Tokeniser))
                needToProcess = !sentences.isEmpty();
            else if (config.getStartModule().equals(Module.PosTagger))
                needToProcess = tokenSequence != null;
            else if (config.getStartModule().equals(Module.Parser))
                needToProcess = posTagSequence != null;

            while (needToProcess) {
                Sentence sentence = null;
                if (config.getStartModule().compareTo(Module.Tokeniser) <= 0
                        && config.getEndModule().compareTo(Module.SentenceDetector) >= 0) {
                    sentence = sentences.poll();
                    LOG.debug("Sentence: " + sentence);
                    if (this.getSentenceProcessor() != null)
                        this.getSentenceProcessor().onNextSentence(sentence.getText(), this.getWriter());
                } // need to read next sentence

                List<TokenSequence> tokenSequences = null;
                if (config.needsTokeniser()) {
                    tokenSequences = config.getTokeniser().tokenise(sentence);
                    tokenSequence = tokenSequences.get(0);

                    if (this.getTokenSequenceProcessor() != null) {
                        this.getTokenSequenceProcessor().onNextTokenSequence(tokenSequence, this.getWriter());
                    }
                } // need to tokenise ?

                List<PosTagSequence> posTagSequences = null;
                if (config.needsPosTagger()) {
                    posTagSequence = null;
                    if (tokenSequences == null || !config.isPropagateTokeniserBeam()) {
                        tokenSequences = new ArrayList<TokenSequence>();
                        tokenSequences.add(tokenSequence);
                    }

                    if (config.getPosTagger() instanceof NonDeterministicPosTagger) {
                        NonDeterministicPosTagger nonDeterministicPosTagger = (NonDeterministicPosTagger) config
                                .getPosTagger();
                        posTagSequences = nonDeterministicPosTagger.tagSentence(tokenSequences);
                        posTagSequence = posTagSequences.get(0);
                    } else {
                        posTagSequence = config.getPosTagger().tagSentence(tokenSequence);
                    }

                    if (posTagSequenceProcessor != null) {
                        posTagSequenceProcessor.onNextPosTagSequence(posTagSequence, this.getWriter());
                    }

                    tokenSequence = null;
                } // need to postag

                if (config.needsParser()) {
                    if (posTagSequences == null || !config.isPropagatePosTaggerBeam()) {
                        posTagSequences = new ArrayList<PosTagSequence>();
                        posTagSequences.add(posTagSequence);
                    }

                    ParseConfiguration parseConfiguration = null;
                    List<ParseConfiguration> parseConfigurations = null;
                    try {
                        if (config.getParser() instanceof NonDeterministicParser) {
                            NonDeterministicParser nonDeterministicParser = (NonDeterministicParser) config
                                    .getParser();
                            parseConfigurations = nonDeterministicParser.parseSentence(posTagSequences);
                            parseConfiguration = parseConfigurations.get(0);
                        } else {
                            parseConfiguration = config.getParser().parseSentence(posTagSequence);
                        }

                        if (this.getParseConfigurationProcessor() != null) {
                            this.getParseConfigurationProcessor().onNextParseConfiguration(parseConfiguration,
                                    this.getWriter());
                        }
                    } catch (Exception e) {
                        LOG.error(e);
                        if (stopOnError)
                            throw new RuntimeException(e);
                    }
                    posTagSequence = null;
                } // need to parse

                if (config.getStartModule().equals(Module.SentenceDetector)
                        || config.getStartModule().equals(Module.Tokeniser))
                    needToProcess = !sentences.isEmpty();
                else if (config.getStartModule().equals(Module.PosTagger))
                    needToProcess = tokenSequence != null;
                else if (config.getStartModule().equals(Module.Parser))
                    needToProcess = posTagSequence != null;
            } // next sentence
        } // next character
    } finally {
        if (this.getParseConfigurationProcessor() != null) {
            this.getParseConfigurationProcessor().onCompleteParse();
        }

        try {
            this.getReader().close();
            this.getWriter().flush();
            this.getWriter().close();
        } catch (IOException ioe2) {
            LOG.error(ioe2);
            throw new RuntimeException(ioe2);
        }

    }
}

From source file:tokyo.northside.jrst.JRSTLexer.java

/**
 * read table simple and complexe/*from   w w w .jav a  2s .  c  o m*/
 * 
 * <pre>
 * +------------------------+------------+----------+----------+
 * | Header row, column 1   | Header 2   | Header 3 | Header 4 |
 * | (header rows optional) |            |          |          |
 * +========================+============+==========+==========+
 * | body row 1, column 1   | column 2   | column 3 | column 4 |
 * +------------------------+------------+----------+----------+
 * | body row 2             | Cells may span columns.          |
 * +------------------------+------------+---------------------+
 * </pre>
 * 
 * @return Element
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public Element peekTable() throws IOException {
    beginPeek();

    Element result = null;
    // in.skipBlankLines();
    String line = in.readLine();

    if (line != null) {
        Pattern pTableBegin = Pattern.compile("^\\s*(\\+-+)+\\+\\s*$");
        Matcher matcher = null;

        matcher = pTableBegin.matcher(line);
        if (matcher.matches()) { // complexe table
            result = DocumentHelper.createElement(TABLE);
            result.addAttribute(TABLE_HEADER, FALSE);
            int level = level(line);
            result.addAttribute(LEVEL, String.valueOf(level));
            line = line.trim();
            int tableWidth = line.length();
            result.addAttribute(TABLE_WIDTH, String.valueOf(tableWidth));

            Pattern pCellEnd = Pattern
                    .compile("^\\s{" + level + "}(\\+-+\\+|\\|(?:[^+]+))([^+]+(?:\\+|\\|\\s*$)|-+\\+)*\\s*"); // fin
            // de
            // ligne
            Pattern pCell = Pattern.compile("^\\s{" + level + "}(\\|[^|]+)+\\|\\s*$"); // une ligne
            Pattern pHeader = Pattern.compile("^\\s{" + level + "}(\\+=+)+\\+\\s*$"); // fin du header
            Pattern pEnd = Pattern.compile("^\\s{" + level + "}(\\+-+)+\\+\\s*$"); // fin de table

            // used to know if | is cell separator or not
            String lastSeparationLine = line;
            String lastLine = line;

            Element row = DocumentHelper.createElement(ROW);
            String[] table = in.readUntilBlank();

            boolean done = false;
            for (String l : table) {
                done = false;
                l = l.trim();
                if (l.length() != tableWidth) {
                    // Erreur dans la table, peut-etre lever une exception ?
                    result = null;
                    break;
                }
                matcher = pEnd.matcher(l);
                if (!done && matcher.matches()) {
                    // fin normale de ligne, on peut directement l'assigner
                    lastSeparationLine = l;
                    for (Element cell : (List<Element>) row.elements()) {
                        cell.addAttribute(CELL_END, TRUE);
                    }
                    row.addAttribute(ROW_END_HEADER, FALSE);
                    result.add(row);
                    row = DocumentHelper.createElement(ROW);
                    done = true;
                }
                matcher = pHeader.matcher(l);
                if (!done && matcher.matches()) {
                    // fin de du header, on peut directement l'assigner
                    lastSeparationLine = l;
                    for (Element cell : (List<Element>) row.elements()) {
                        cell.addAttribute(CELL_END, TRUE);
                    }
                    row.addAttribute(ROW_END_HEADER, TRUE);
                    result.add(row);
                    result.addAttribute(TABLE_HEADER, TRUE);
                    row = DocumentHelper.createElement(ROW);
                    done = true;
                }
                matcher = pCell.matcher(l);
                if (!done && matcher.matches()) {
                    // debug
                    row.addAttribute("debug", "pCell");
                    // recuperation des textes des cellules
                    int start = -1;
                    String content = "";
                    matcher = Pattern.compile("([^|]+)\\|").matcher(l);
                    for (int cellNumber = 0; matcher.find(); cellNumber++) {
                        int tmpstart = matcher.start(1);
                        int end = matcher.end(1);
                        String tmpcontent = matcher.group(1);
                        // on a forcement un | ou un + au dessus du +
                        // et forcement un + sur lastSeparationLine
                        // sinon ca veut dire qu'il y avait un | dans la
                        // cell
                        if ((lastLine.charAt(end) == '|' || lastLine.charAt(end) == '+')
                                && lastSeparationLine.charAt(end) == '+') {
                            if ("".equals(content)) {
                                content = tmpcontent;
                            } else {
                                content += tmpcontent;
                            }
                            if (start == -1) {
                                start = tmpstart;
                            }
                            Element cell = null;
                            if (row.nodeCount() <= cellNumber) {
                                cell = row.addElement(CELL);
                                cell.addAttribute(CELL_END, FALSE);
                            } else {
                                cell = (Element) row.node(cellNumber);
                            }
                            cell.addAttribute(CELL_INDEX_START, String.valueOf(start));
                            cell.addAttribute(CELL_INDEX_END, String.valueOf(end));
                            cell.setText(cell.getText() + content + "\n");
                            start = end + 1; // +1 to pass + or | at end
                            // of cell
                            content = "";
                        } else {
                            // start = tmpstart;
                            if (start == -1) {
                                start = tmpstart;
                            }
                            content += tmpcontent + "|";
                            cellNumber--;
                        }
                    }
                    done = true;
                }
                matcher = pCellEnd.matcher(l);
                if (!done && matcher.matches()) {
                    // debug
                    row.addAttribute("debug", "pCellEnd");
                    // fin d'une ligne, on ne peut pas l'assigner
                    // directement
                    // pour chaque continuation de cellule, il faut copier
                    // l'ancienne valeur

                    // mais on commence tout de meme par fermer tout les
                    // cells
                    for (Element cell : (List<Element>) row.elements()) {
                        cell.addAttribute(CELL_END, TRUE);
                    }

                    StringBuffer tmp = new StringBuffer(l);
                    int start = -1;
                    String content = "";
                    matcher = Pattern.compile("([^+|]+|-+)([+|])").matcher(l);
                    for (int cellNumber = 0; matcher.find(); cellNumber++) {
                        int tmpstart = matcher.start(1);
                        int end = matcher.end(1);
                        String tmpcontent = matcher.group(1);
                        String ender = matcher.group(2);
                        if (!tmpcontent.matches("-+")) {
                            // on a forcement un | au dessus du + ou du |
                            // sinon ca veut dire qu'il y avait un + dans la
                            // cell
                            if (lastLine.charAt(end) == '|') {
                                if (start == -1) {
                                    start = tmpstart;
                                }
                                // -1 and +1 to take the + or | at begin and
                                // end
                                String old = lastSeparationLine.substring(start - 1, end + 1);
                                tmp.replace(start - 1, end + 1, old);
                                if ("".equals(content)) {
                                    content = tmpcontent;
                                }
                                Element cell = null;
                                if (row.nodeCount() <= cellNumber) {
                                    cell = row.addElement(CELL);
                                } else {
                                    cell = (Element) row.node(cellNumber);

                                }
                                cell.setText(cell.getText() + content + "\n");
                                // on a ajouter des choses dans la cell,
                                // donc
                                // ce n'est pas la fin
                                cell.addAttribute(CELL_END, FALSE);
                                cell.addAttribute(CELL_INDEX_START, String.valueOf(start));
                                cell.addAttribute(CELL_INDEX_END, String.valueOf(end));
                                start = end + 1; // +1 to pass + or | at
                                // end of cell
                                content = "";
                            } else {
                                // start = tmpstart;
                                content += tmpcontent + ender;
                            }
                        }
                    }
                    lastSeparationLine = tmp.toString();
                    row.addAttribute(ROW_END_HEADER, FALSE);
                    result.add(row);
                    row = DocumentHelper.createElement(ROW);
                    done = true;
                }
                if (!done) {
                    log.warn("Bad table format line " + in.getLineNumber());
                }
                lastLine = l;
            }

            //
            // line += "\n" + joinBlock(table, "\n", false);
            //
            // result.addText(line);
        } else if (line.matches("^\\s*(=+ +)+=+\\s*$")) {
            // Les donnees de la table peuvent depasser de celle-ci
            /*
             * ===== ===== ====== Inputs Output ------------ ------ A B A or
             * B ===== ===== ====== False False Second column of row 1. True
             * False Second column of row 2.
             * 
             * True 2 - Second column of row 3.
             * 
             * - Second item in bullet list (row 3, column 2). ============
             * ======
             */

            result = DocumentHelper.createElement(TABLE);
            line = line.trim();
            Pattern pBordersEquals = Pattern.compile("^\\s*(=+ +)+=+\\s*$"); // Separation
            // =
            Pattern pBordersTiret = Pattern.compile("^\\s*(-+ +)+-+\\s*$"); // Separation
            // -
            Pattern pBorders = Pattern.compile("^\\s*([=-]+ +)+[=-]+\\s*$"); // =
            // ou
            // -
            String[] table = in.readUntilBlank(); // Recuperation de la
            // table

            int tableWidth = line.length();
            int nbSeparations = 0;
            for (String l : table) {
                if (l.length() > tableWidth) {
                    tableWidth = l.length(); // Determination de la
                } // Determination de la
                  // longueur max
                matcher = pBordersEquals.matcher(l);
                if (matcher.matches()) {
                    nbSeparations++;
                }

            }
            // Header if the table contains 3 equals separations
            result.addAttribute(TABLE_HEADER, "" + (nbSeparations == 2));
            int level = level(line);
            result.addAttribute(LEVEL, String.valueOf(level));
            result.addAttribute(TABLE_WIDTH, String.valueOf(tableWidth + 1));
            Element row = DocumentHelper.createElement(ROW);
            // Determination of the columns positions
            List<Integer> columns = new LinkedList<Integer>();
            matcher = Pattern.compile("=+\\s+").matcher(line);
            for (int cellNumber = 0; matcher.find(); cellNumber++) {
                columns.add(matcher.end());
            }
            columns.add(tableWidth);

            // Traitement du tbl
            /*
             * ===== ===== ====== Inputs Output ------------ ------ A B A or
             * B ===== ===== ====== False False Second column of row 1. True
             * False Second column of row 2.
             * 
             * True 2 - Second column of row 3.
             * 
             * - Second item in bullet list (row 3, column 2). ============
             * ====== devient l'equivalent : ===== ===== ====== Inputs
             * Output ------------ ------ A B A or B ===== ===== ======
             * False False Second column of row 1. ----- ----- ------ True
             * False Second column of row 2. ----- ----- ------ True 2 -
             * Second column of row 3. - Second item in bullet list (row 3,
             * column 2). ============ ======
             */
            String lineRef = line.replace('=', '-');
            Matcher matcher2;
            List<String> tableTmp = new LinkedList<String>();

            for (int i = 0; i < table.length - 1; i++) {
                tableTmp.add(table[i]);
                if (!table[i].equals("")) {
                    if (!table[i + 1].substring(0, columns.get(0)).matches("\\s*")) {
                        matcher = pBorders.matcher(table[i]);
                        matcher2 = pBorders.matcher(table[i + 1]);
                        if (!matcher.matches() && !matcher2.matches() && !table[i + 1].equals("")) {
                            tableTmp.add(lineRef);
                        }
                    }
                }
            }
            tableTmp.add(table[table.length - 1]);
            table = new String[tableTmp.size()];
            for (int i = 0; i < tableTmp.size(); i++) {
                table[i] = tableTmp.get(i);
            }

            boolean done = false;
            LinkedList<String> lastLines = new LinkedList<String>();
            int separation = 1;
            for (String l : table) {
                if (l != null) {
                    done = false;
                    matcher = pBordersTiret.matcher(l);
                    matcher2 = pBordersEquals.matcher(l);
                    if (matcher.matches() || matcher2.matches()) { // Intermediate
                        // separation
                        while (!lastLines.isEmpty()) {
                            matcher = Pattern.compile("[-=]+\\s*").matcher(l);
                            String tmpLine = lastLines.getLast();
                            lastLines.removeLast();
                            int cellNumber;
                            for (cellNumber = 0; matcher.find(); cellNumber++) {
                                Element cell = null;
                                if (row.nodeCount() <= cellNumber) {
                                    cell = row.addElement(CELL);
                                } else {
                                    cell = (Element) row.node(cellNumber);
                                }
                                if (matcher.start() < tmpLine.length()) {
                                    if (columns.size() - 1 == cellNumber) {
                                        cell.setText(
                                                tmpLine.substring(matcher.start(), tmpLine.length()) + "\n");
                                    } else {
                                        if (matcher.end() < tmpLine.length()) {
                                            cell.setText(
                                                    tmpLine.substring(matcher.start(), matcher.end()) + "\n");
                                        } else {
                                            cell.setText(tmpLine.substring(matcher.start(), tmpLine.length())
                                                    + "\n");
                                        }
                                    }
                                }

                                if (lastLines.size() == 0) {
                                    row.addAttribute("debug", "pCell");
                                    cell.addAttribute(CELL_END, TRUE);
                                } else {
                                    row.addAttribute("debug", "pCellEnd");
                                    cell.addAttribute(CELL_END, FALSE);
                                }
                                cell.addAttribute(CELL_INDEX_START, String.valueOf(matcher.start() + 1));
                                if (line.length() == matcher.end()) {
                                    cell.addAttribute(CELL_INDEX_END,
                                            String.valueOf(columns.get(columns.size() - 1)));
                                } else {
                                    cell.addAttribute(CELL_INDEX_END, String.valueOf(matcher.end()));
                                }
                            }

                            if (matcher2.matches()) {
                                separation++;
                                row.addAttribute(ROW_END_HEADER, "" + (separation == 2));
                            } else {
                                row.addAttribute(ROW_END_HEADER, FALSE);
                            }

                            result.add(row);
                            row = DocumentHelper.createElement(ROW);
                            done = true;
                        }
                    }
                    if (!done && l.matches("^\\s*(.+ +)+.+\\s*$")) {
                        // Data
                        lastLines.addFirst(l); // Les donnees sont stoquee
                        // dans une file d'attente
                        // lastLines (FIFO)
                        done = true;
                    }
                    if (!done) {
                        log.warn("Bad table format line " + in.getLineNumber());
                    }
                }
            }
        }
    }
    endPeek();

    return result;
}

From source file:com.mirth.connect.plugins.dashboardstatus.DashboardConnectorStatusMonitor.java

public void updateStatus(String connectorId, ConnectorType type, Event event, Socket socket) {
    String stateImage = COLOR_BLACK;
    String stateText = STATE_UNKNOWN;
    boolean updateStatus = true;

    switch (event) {
    case INITIALIZED:
        switch (type) {
        case LISTENER:
            stateImage = COLOR_YELLOW;//from   ww w .  j  a v a2  s.c  om
            stateText = STATE_WAITING;
            break;
        case READER:
            stateImage = COLOR_YELLOW;
            stateText = STATE_IDLE;
            break;
        }
        break;
    case CONNECTED:
        switch (type) {
        case LISTENER:
            if (socket != null) {
                addConnectionToSocketSet(socket, connectorId);
                stateImage = COLOR_GREEN;
                stateText = STATE_CONNECTED + " (" + getSocketSetCount(connectorId) + ")";
            } else {
                stateImage = COLOR_GREEN;
                stateText = STATE_CONNECTED;
            }
            break;
        case READER:
            stateImage = COLOR_GREEN;
            stateText = STATE_POLLING;
            break;
        }
        break;
    case DISCONNECTED:
        switch (type) {
        case LISTENER:
            if (socket != null) {
                removeConnectionInSocketSet(socket, connectorId);
                int connectedSockets = getSocketSetCount(connectorId);
                if (connectedSockets == 0) {
                    stateImage = COLOR_YELLOW;
                    stateText = STATE_WAITING;
                } else {
                    stateImage = COLOR_GREEN;
                    stateText = STATE_CONNECTED + " (" + connectedSockets + ")";
                }
            } else {
                clearSocketSet(connectorId);
                stateImage = COLOR_RED;
                stateText = STATE_DISCONNECTED;
            }
            break;
        case READER:
            stateImage = COLOR_RED;
            stateText = STATE_NOT_POLLING;
            break;
        case WRITER:
            stateImage = COLOR_RED;
            stateText = STATE_DISCONNECTED;
            break;
        case SENDER:
            stateImage = COLOR_RED;
            stateText = STATE_DISCONNECTED;
            break;
        }
        break;
    case BUSY:
        switch (type) {
        case READER:
            stateImage = COLOR_GREEN;
            stateText = STATE_READING;
            break;
        case LISTENER:
            stateImage = COLOR_GREEN;
            stateText = STATE_RECEIVING;
            break;
        case WRITER:
            stateImage = COLOR_YELLOW;
            stateText = STATE_WRITING;
            break;
        case SENDER:
            stateImage = COLOR_YELLOW;
            stateText = STATE_SENDING;
            break;
        }
        break;
    case DONE:
        switch (type) {
        case READER:
            stateImage = COLOR_YELLOW;
            stateText = STATE_IDLE;
            break;
        case LISTENER:
            if (socket != null) {
                stateImage = COLOR_GREEN;
                stateText = STATE_CONNECTED + " (" + getSocketSetCount(connectorId) + ")";
            } else {
                stateImage = COLOR_YELLOW;
                stateText = STATE_WAITING;
            }
            break;
        }
        break;
    case ATTEMPTING:
        switch (type) {
        case WRITER:
            stateImage = COLOR_YELLOW;
            stateText = STATE_ATTEMPTING;
            break;
        case SENDER:
            stateImage = COLOR_YELLOW;
            stateText = STATE_ATTEMPTING;
            break;
        }
        break;
    default:
        updateStatus = false;
        break;
    }

    if (updateStatus) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");

        String channelName = "";
        // this will be overwritten down below. If not, something's wrong.
        String connectorType = type.toString();
        String information = "";

        /*
         * check 'connectorId' - contains destination_1_connector, etc.
         * connectorId consists of id_source_connector for sources, and
         * id_destination_x_connector for destinations. i.e. tokenCount will
         * be 3 for sources and 4 for destinations. Note that READER and
         * LISTENER are sources, and WRITER and SENDER are destinations.
         */
        StringTokenizer tokenizer = new StringTokenizer(connectorId, "_");
        String channelId = tokenizer.nextToken();
        int destinationIndex;
        LinkedList<String[]> channelLog = null;

        Channel channel = ControllerFactory.getFactory().createChannelController()
                .getDeployedChannelById(channelId);

        if (channel != null) {
            channelName = channel.getName();
            // grab the channel's log from the HashMap, if not exist, create
            // one.
            if (connectorInfoLogs.containsKey(channelName)) {
                channelLog = connectorInfoLogs.get(channelName);
            } else {
                channelLog = new LinkedList<String[]>();
            }

            Connector connector = null;

            switch (type) {
            case READER:
                connectorType = "Source: " + channel.getSourceConnector().getTransportName() + "  ("
                        + channel.getSourceConnector().getTransformer().getInboundProtocol().toString() + " -> "
                        + channel.getSourceConnector().getTransformer().getOutboundProtocol().toString() + ")";
                break;
            case LISTENER:
                connectorType = "Source: " + channel.getSourceConnector().getTransportName() + "  ("
                        + channel.getSourceConnector().getTransformer().getInboundProtocol().toString() + " -> "
                        + channel.getSourceConnector().getTransformer().getOutboundProtocol().toString() + ")";
                break;
            case WRITER:
                tokenizer.nextToken();
                // destinationId begins from 1, so subtract by 1 for the
                // arrayIndex.
                destinationIndex = Integer.valueOf(tokenizer.nextToken()) - 1;
                connector = channel.getDestinationConnectors().get(destinationIndex);
                connectorType = "Destination: " + connector.getTransportName() + " - " + connector.getName();

                if (connector.getTransportName().equals(FileWriterProperties.name)) {
                    // Destination - File Writer.
                    switch (event) {
                    case BUSY:
                        information = FileWriterProperties.getInformation(connector.getProperties());
                        break;
                    }
                } else if (connector.getTransportName().equals(DatabaseWriterProperties.name)) {
                    // Destination - Database Writer.
                    information = DatabaseWriterProperties.getInformation(connector.getProperties());
                } else if (connector.getTransportName().equals(JMSWriterProperties.name)) {
                    // Destination - JMS Writer.
                    information = JMSWriterProperties.getInformation(connector.getProperties());
                } else if (connector.getTransportName().equals(DocumentWriterProperties.name)) {
                    // Destination - Document Writer.
                    information = DocumentWriterProperties.getInformation(connector.getProperties());
                }
                break;
            case SENDER:
                tokenizer.nextToken();
                // destinationId begins from 1, so subtract by 1 for the
                // arrayIndex.
                destinationIndex = Integer.valueOf(tokenizer.nextToken()) - 1;
                connector = channel.getDestinationConnectors().get(destinationIndex);
                connectorType = "Destination: " + connector.getTransportName() + " - " + connector.getName();

                if (connector.getTransportName().equals(HttpSenderProperties.name)) {
                    // Destination - HTTP Sender.
                    information = HttpSenderProperties.getInformation(connector.getProperties());
                } else if (connector.getTransportName().equals(ChannelWriterProperties.name)) {
                    // Destination - Channel Writer.
                    Channel targetChannel = ControllerFactory.getFactory().createChannelController()
                            .getDeployedChannelById(
                                    ChannelWriterProperties.getInformation(connector.getProperties()));

                    if (targetChannel == null) {
                        information = "Target Channel: None";
                    } else {
                        information = "Target Channel: " + targetChannel.getName();
                    }
                } else if (connector.getTransportName().equals(SmtpSenderProperties.name)) {
                    // Destination - SMTP Sender.
                    information = SmtpSenderProperties.getInformation(connector.getProperties());
                } else if (connector.getTransportName().equals(TCPSenderProperties.name)) {
                    // Destination - TCP Sender.
                    // The useful info for TCP Sender - host:port will
                    // be taken care of by the socket below.
                } else if (connector.getTransportName().equals(LLPSenderProperties.name)) {
                    // Destination - LLP Sender.
                    // The useful info for LLP Sender - host:port will
                    // be taken care of by the socket below.
                } else if (connector.getTransportName().equals(WebServiceSenderProperties.name)) {
                    // Destination - Web Service Sender.
                    // information = "";
                }
                break;
            }
        }

        if (socket != null) {
            String sendingAddress = socket.getLocalAddress().toString() + ":" + socket.getLocalPort();
            String receivingAddress = socket.getInetAddress().toString() + ":" + socket.getPort();

            // If addresses begin with a slash "/", remove it.
            if (sendingAddress.startsWith("/")) {
                sendingAddress = sendingAddress.substring(1);
            }

            if (receivingAddress.startsWith("/")) {
                receivingAddress = receivingAddress.substring(1);
            }

            information += "Sender: " + sendingAddress + "  Receiver: " + receivingAddress;
        }

        if (channelLog != null) {
            synchronized (this) {
                if (channelLog.size() == MAX_LOG_SIZE) {
                    channelLog.removeLast();
                }
                channelLog.addFirst(new String[] { String.valueOf(logId), channelName,
                        dateFormat.format(timestamp), connectorType, event.toString(), information });

                if (entireConnectorInfoLogs.size() == MAX_LOG_SIZE) {
                    entireConnectorInfoLogs.removeLast();
                }
                entireConnectorInfoLogs.addFirst(new String[] { String.valueOf(logId), channelName,
                        dateFormat.format(timestamp), connectorType, event.toString(), information });

                logId++;

                // put the channel log into the HashMap.
                connectorInfoLogs.put(channelName, channelLog);
            }
        }

        connectorStateMap.put(connectorId, new String[] { stateImage, stateText });
    }
}

From source file:com.crushpaper.Servlet.java

/**
 * Validates a list of entries, in that the IDs must be well formed, the
 * entries must exist and the parents must be placed before the children.
 * Put the validated Entries in the same order as the IDs in the
 * validatedEntriesList parameter. Returns null if there was no error. God,
 * how I long to code in a better language.
 *///  ww  w  .  j  a  v  a  2s . com
private String validateEntriesParentsBeforeChildren(RequestAndResponse requestAndResponse,
        String[] idsToValidate, LinkedList<EntryAndIsFromList> validatedEntriesList)
        throws ServletException, IOException {
    // Iterate in reverse to validate that parents are moved before
    // children.
    final HashSet<String> validatedIdsSet = new HashSet<String>();
    for (int i = idsToValidate.length - 1; i >= 0; --i) {
        final String[] idToValidateArray = idsToValidate[i].split(":");
        final String idToValidate = idToValidateArray[idToValidateArray.length == 1 ? 0 : 1];
        final boolean isFromList = idToValidateArray.length != 1;

        if (!dbLogic.getIdGenerator().isIdWellFormed(idToValidate)) {
            return servletText.errorIdIsInvalidFormat();
        }

        final Entry movedEntry = dbLogic.getEntryById(idToValidate);
        if (movedEntry == null) {
            return servletText.errorEntryCouldNotBeFound();
        }

        if (validatedIdsSet.contains(idToValidate)) {
            return servletText.errorDuplicateEntry();
        }

        // Validate that parents are moved before children.
        validatedIdsSet.add(idToValidate);

        final Entry oldParentOfMovedEntry = dbLogic.getEntryById(movedEntry.getParentId());

        if (oldParentOfMovedEntry != null && validatedIdsSet.contains(oldParentOfMovedEntry.getId())) {
            servletText.errorParentMustBeMovedBeforeChild();
        }

        validatedEntriesList.addFirst(new EntryAndIsFromList(movedEntry, isFromList));
    }

    return null;
}