Example usage for java.util List listIterator

List of usage examples for java.util List listIterator

Introduction

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

Prototype

ListIterator<E> listIterator();

Source Link

Document

Returns a list iterator over the elements in this list (in proper sequence).

Usage

From source file:de.tudarmstadt.ukp.dkpro.core.api.io.ResourceCollectionReaderBase.java

@Override
public void initialize(UimaContext aContext) throws ResourceInitializationException {
    super.initialize(aContext);
    // if an ExternalResourceLocator providing a custom ResourcePatternResolver
    // has been specified, use it, by default use PathMatchingResourcePatternresolver

    // If there are no patterns, then look for a pattern in the location itself.
    // If the source location contains a wildcard, split it up into a base and a pattern
    if (patterns == null) {
        int asterisk = sourceLocation.indexOf('*');
        if (asterisk != -1) {
            patterns = new String[] { INCLUDE_PREFIX + sourceLocation.substring(asterisk) };
            sourceLocation = sourceLocation.substring(0, asterisk);
        }// w  w w. ja v a2  s  . c  om
    }

    // Parse the patterns and inject them into the FileSet
    List<String> includes = new ArrayList<String>();
    List<String> excludes = new ArrayList<String>();
    if (patterns != null) {
        for (String pattern : patterns) {
            if (pattern.startsWith(INCLUDE_PREFIX)) {
                includes.add(pattern.substring(INCLUDE_PREFIX.length()));
            } else if (pattern.startsWith(EXCLUDE_PREFIX)) {
                excludes.add(pattern.substring(EXCLUDE_PREFIX.length()));
            } else if (pattern.matches("^\\[.\\].*")) {
                throw new ResourceInitializationException(new IllegalArgumentException(
                        "Patterns have to start with " + INCLUDE_PREFIX + " or " + EXCLUDE_PREFIX + "."));
            } else {
                includes.add(pattern);
            }
        }
    }

    // These should be the same as documented here: http://ant.apache.org/manual/dirtasks.html
    if (useDefaultExcludes) {
        excludes.add("**/*~");
        excludes.add("**/#*#");
        excludes.add("**/.#*");
        excludes.add("**/%*%");
        excludes.add("**/._*");
        excludes.add("**/CVS");
        excludes.add("**/CVS/**");
        excludes.add("**/.cvsignore");
        excludes.add("**/SCCS");
        excludes.add("**/SCCS/**");
        excludes.add("**/vssver.scc");
        excludes.add("**/.svn");
        excludes.add("**/.svn/**");
        excludes.add("**/.DS_Store");
        excludes.add("**/.git");
        excludes.add("**/.git/**");
        excludes.add("**/.gitattributes");
        excludes.add("**/.gitignore");
        excludes.add("**/.gitmodules");
        excludes.add("**/.hg");
        excludes.add("**/.hg/**");
        excludes.add("**/.hgignore");
        excludes.add("**/.hgsub");
        excludes.add("**/.hgsubstate");
        excludes.add("**/.hgtags");
        excludes.add("**/.bzr");
        excludes.add("**/.bzr/**");
        excludes.add("**/.bzrignore");
    }

    try {
        if (sourceLocation == null) {
            ListIterator<String> i = includes.listIterator();
            while (i.hasNext()) {
                i.set(locationToUrl(i.next()));
            }
            i = excludes.listIterator();
            while (i.hasNext()) {
                i.set(locationToUrl(i.next()));
            }
        } else {
            sourceLocation = locationToUrl(sourceLocation);
        }

        resources = scan(sourceLocation, includes, excludes);

        // Get the iterator that will be used to actually traverse the FileSet.
        resourceIterator = resources.iterator();

        getLogger().info("Found [" + resources.size() + "] resources to be read");
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
}

From source file:org.apache.fop.layoutmgr.inline.InlineLayoutManager.java

/**
 * Generate and add areas to parent area.
 * Set size of each area. This should only create and return one
 * inline area for any inline parent area.
 *
 * @param parentIter Iterator over Position information returned
 * by this LayoutManager.//from   w ww . j  a  va  2  s  . c  om
 * @param context layout context.
 */
@Override
public void addAreas(PositionIterator parentIter, LayoutContext context) {

    addId();

    setChildContext(new LayoutContext(context)); // Store current value

    // "Unwrap" the NonLeafPositions stored in parentIter and put
    // them in a new list.  Set lastLM to be the LayoutManager
    // which created the last Position: if the LAST_AREA flag is
    // set in the layout context, it must be also set in the
    // layout context given to lastLM, but must be cleared in the
    // layout context given to the other LMs.
    List<Position> positionList = new LinkedList<Position>();
    Position pos;
    LayoutManager lastLM = null; // last child LM in this iterator
    Position lastPos = null;
    while (parentIter.hasNext()) {
        pos = parentIter.next();
        if (pos != null && pos.getPosition() != null) {
            if (isFirst(pos)) {
                /*
                 * If this element is a descendant of a table-header/footer,
                 * its content may be repeated over pages, so the generation
                 * of its areas may be restarted.
                 */
                areaCreated = false;
            }
            positionList.add(pos.getPosition());
            lastLM = pos.getPosition().getLM();
            lastPos = pos;
        }
    }

    // If this LM has fence, make a new leading space specifier.
    if (hasLeadingFence(areaCreated)) {
        getContext().setLeadingSpace(new SpaceSpecifier(false));
        getContext().setFlags(LayoutContext.RESOLVE_LEADING_SPACE, true);
    } else {
        getContext().setFlags(LayoutContext.RESOLVE_LEADING_SPACE, false);
    }

    if (getSpaceStart() != null) {
        context.getLeadingSpace().addSpace(new SpaceVal(getSpaceStart(), this));
    }

    addMarkersToPage(true, !areaCreated, lastPos == null || isLast(lastPos));

    InlineArea parent = createArea(lastLM == null || lastLM instanceof InlineLevelLayoutManager);
    parent.setBPD(alignmentContext.getHeight());
    if (parent instanceof InlineParent) {
        parent.setBlockProgressionOffset(alignmentContext.getOffset());
    } else if (parent instanceof InlineBlockParent) {
        // All inline elements are positioned by the renderers relative to
        // the before edge of their content rectangle
        if (borderProps != null) {
            parent.setBlockProgressionOffset(
                    borderProps.getPaddingBefore(false, this) + borderProps.getBorderBeforeWidth(false));
        }
    }
    setCurrentArea(parent);

    PositionIterator childPosIter = new PositionIterator(positionList.listIterator());

    LayoutManager prevLM = null;
    LayoutManager childLM;
    while ((childLM = childPosIter.getNextChildLM()) != null) {
        getContext().setFlags(LayoutContext.LAST_AREA, context.isLastArea() && childLM == lastLM);
        childLM.addAreas(childPosIter, getContext());
        getContext().setLeadingSpace(getContext().getTrailingSpace());
        getContext().setFlags(LayoutContext.RESOLVE_LEADING_SPACE, true);
        prevLM = childLM;
    }

    /* If this LM has a trailing fence, resolve trailing space
     * specs from descendants.  Otherwise, propagate any trailing
     * space specs to the parent LM via the layout context.  If
     * the last child LM called returns LAST_AREA in the layout
     * context and it is the last child LM for this LM, then this
     * must be the last area for the current LM too.
     */
    boolean isLast = (getContext().isLastArea() && prevLM == lastChildLM);

    if (hasTrailingFence(isLast)) {
        addSpace(getCurrentArea(), getContext().getTrailingSpace().resolve(false),
                getContext().getSpaceAdjust());
        context.setTrailingSpace(new SpaceSpecifier(false));
    } else {
        // Propagate trailing space-spec sequence to parent LM in context.
        context.setTrailingSpace(getContext().getTrailingSpace());
    }
    // Add own trailing space to parent context (or set on area?)
    if (context.getTrailingSpace() != null && getSpaceEnd() != null) {
        context.getTrailingSpace().addSpace(new SpaceVal(getSpaceEnd(), this));
    }

    // Not sure if lastPos can legally be null or if that masks a different problem.
    // But it seems to fix bug 38053.
    setTraits(areaCreated, lastPos == null || !isLast(lastPos));
    parentLayoutManager.addChildArea(getCurrentArea());

    addMarkersToPage(false, !areaCreated, lastPos == null || isLast(lastPos));

    context.setFlags(LayoutContext.LAST_AREA, isLast);
    areaCreated = true;
    checkEndOfLayout(lastPos);
}

From source file:org.apache.fop.layoutmgr.BlockContainerLayoutManager.java

/** {@inheritDoc} */
@Override//from w  w w  .j  av a  2  s. co m
public void addAreas(PositionIterator parentIter, LayoutContext layoutContext) {
    getParentArea(null);

    // if this will create the first block area in a page
    // and display-align is bottom or center, add space before
    if (layoutContext.getSpaceBefore() > 0) {
        addBlockSpacing(0.0, MinOptMax.getInstance(layoutContext.getSpaceBefore()));
    }

    LayoutManager childLM;
    LayoutManager lastLM = null;
    LayoutContext lc = new LayoutContext(0);
    lc.setSpaceAdjust(layoutContext.getSpaceAdjust());
    // set space after in the LayoutContext for children
    if (layoutContext.getSpaceAfter() > 0) {
        lc.setSpaceAfter(layoutContext.getSpaceAfter());
    }
    BlockContainerPosition bcpos = null;
    PositionIterator childPosIter;

    // "unwrap" the NonLeafPositions stored in parentIter
    // and put them in a new list;
    List<Position> positionList = new LinkedList<Position>();
    Position pos;
    Position firstPos = null;
    Position lastPos = null;
    while (parentIter.hasNext()) {
        pos = parentIter.next();
        if (pos.getIndex() >= 0) {
            if (firstPos == null) {
                firstPos = pos;
            }
            lastPos = pos;
        }
        Position innerPosition = pos;
        if (pos instanceof NonLeafPosition) {
            innerPosition = pos.getPosition();
        }
        if (pos instanceof BlockContainerPosition) {
            if (bcpos != null) {
                throw new IllegalStateException("Only one BlockContainerPosition allowed");
            }
            bcpos = (BlockContainerPosition) pos;
            //Add child areas inside the reference area
            //bcpos.getBreaker().addContainedAreas();
        } else if (innerPosition == null) {
            //ignore (probably a Position for a simple penalty between blocks)
        } else if (innerPosition.getLM() == this && !(innerPosition instanceof MappingPosition)) {
            // pos was created by this BlockLM and was inside a penalty
            // allowing or forbidding a page break
            // nothing to do
        } else {
            // innerPosition was created by another LM
            positionList.add(innerPosition);
            lastLM = innerPosition.getLM();
        }
    }

    addId();

    addMarkersToPage(true, isFirst(firstPos), isLast(lastPos));

    if (bcpos == null) {
        // the Positions in positionList were inside the elements
        // created by the LineLM
        childPosIter = new PositionIterator(positionList.listIterator());

        while ((childLM = childPosIter.getNextChildLM()) != null) {
            // set last area flag
            lc.setFlags(LayoutContext.LAST_AREA, (layoutContext.isLastArea() && childLM == lastLM));
            lc.setStackLimitBP(layoutContext.getStackLimitBP());
            // Add the line areas to Area
            childLM.addAreas(childPosIter, lc);
        }
    } else {
        //Add child areas inside the reference area
        bcpos.getBreaker().addContainedAreas();
    }

    addMarkersToPage(false, isFirst(firstPos), isLast(lastPos));

    TraitSetter.addSpaceBeforeAfter(viewportBlockArea, layoutContext.getSpaceAdjust(), effSpaceBefore,
            effSpaceAfter);
    flush();

    viewportBlockArea = null;
    referenceArea = null;
    resetSpaces();

    notifyEndOfLayout();
}

From source file:com.rr.wabshs.ui.surveys.surveyController.java

/**
 * The '/startSurvey' GET request will build out the survey and display the first page of the survey.
 *
 * @param i The encrypted client id//from   w w  w.  jav a 2 s  . co  m
 * @param v The encrypted decryption key
 * @param s The id of the selected survey
 *
 * @param session
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/startSurvey", method = RequestMethod.POST)
public ModelAndView startSurvey(@RequestParam(value = "s", required = false) String s,
        @RequestParam(value = "i", required = false) String i,
        @RequestParam(value = "v", required = false) String v,
        @RequestParam(value = "selectedEntities", required = false) List<Integer> selectedEntities,
        HttpSession session) throws Exception {

    ModelAndView mav = new ModelAndView();
    mav.setViewName("/takeSurvey");
    mav.addObject("surveys", surveys);

    //Set the survey answer array to get ready to hold data
    if (session.getAttribute("questionAnswers") != null) {
        session.removeAttribute("questionAnswers");
    }
    session.setAttribute("questionAnswers", new ArrayList<surveyQuestionAnswers>());

    if (session.getAttribute("selectedProgramProfiles") != null) {
        session.removeAttribute("selectedProgramProfiles");
    }
    session.setAttribute("selectedProgramProfiles", new ArrayList<surveyProgramProfiles>());

    if (session.getAttribute("secondTierEntities") != null) {
        session.removeAttribute("secondTierEntities");
    }
    session.setAttribute("secondTierEntities", new ArrayList<secondTierEntities>());

    if (session.getAttribute("seenPages") != null) {
        session.removeAttribute("seenPages");
    }
    session.setAttribute("seenPages", new ArrayList<Integer>());

    if (session.getAttribute("selectedExtras") != null) {
        session.removeAttribute("selectedExtras");
    }
    session.setAttribute("selectedExtras", new ArrayList<surveyExtraInformation>());

    int clientId = 0;
    int surveyId = 0;

    /* Get the submitted surveys for the selected survey type */
    if (!"".equals(i) && i != null && !"".equals(v) && v != null) {
        /* Decrypt the url */
        decryptObject decrypt = new decryptObject();

        Object obj = decrypt.decryptObject(i, v);

        String[] result = obj.toString().split((","));

        surveyId = Integer.parseInt(result[0].substring(4));

    } else {
        surveyId = Integer.parseInt(s);
    }

    if (surveyId > 0) {

        surveys surveyDetails = surveyManager.getSurveyDetails(surveyId);
        mav.addObject("surveyTag", surveyDetails.getSurveyTag());

        /* Make sure the survey is part of this program and active */
        if (surveyDetails.getProgramId() != programId || surveyDetails.getStatus() == false) {

            /* Redirect back to the survey list page */
        } /* Set up the survey */ else {
            survey survey = new survey();
            survey.setClientId(clientId);
            survey.setSurveyId(surveyId);
            survey.setSurveyTitle(surveyDetails.getTitle());
            survey.setPrevButton(surveyDetails.getPrevButtonText());
            survey.setNextButton(surveyDetails.getNextButtonText());
            survey.setSaveButton(surveyDetails.getDoneButtonText());
            survey.setSubmittedSurveyId(0);

            encryptObject encrypt = new encryptObject();
            Map<String, String> map;

            map = new HashMap<String, String>();
            map.put("id", Integer.toString(surveyId));
            map.put("topSecret", topSecret);

            String[] encrypted = encrypt.encryptObject(map);

            survey.setEncryptedId(encrypted[0]);
            survey.setEncryptedSecret(encrypted[1]);

            mav.addObject("surveyURL", "?i=" + encrypted[0] + "&v=" + encrypted[1]);

            /* Get the pages */
            List<SurveyPages> surveyPages = surveyManager.getSurveyPages(surveyId, false, 0, 0, 0, 0);
            SurveyPages currentPage = surveyManager.getSurveyPage(surveyId, true, 1, clientId, 0, 0, 0, 0, 0);
            survey.setPageTitle(currentPage.getPageTitle());
            survey.setSurveyPageQuestions(currentPage.getSurveyQuestions());
            survey.setTotalPages(surveyPages.size());
            survey.setPageId(currentPage.getId());
            survey.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId());

            mav.addObject("survey", survey);
            mav.addObject("surveyPages", surveyPages);

            if (surveyDetails.isAssociateToProgram()) {
                mav.addObject("showPrograms", true);
            } else {
                mav.addObject("showPrograms", false);
            }
        }
    } else {
        /* Redirect back to the survey list page */

    }

    User userDetails = (User) session.getAttribute("userDetails");

    /* Get a list of available tier 3 for the selected tier 2's */
    if (selectedEntities != null && !selectedEntities.isEmpty() && !"".equals(selectedEntities)) {

        encryptObject encrypt = new encryptObject();
        Map<String, String> map;

        List<secondTierEntities> tier2EntityList = (List<secondTierEntities>) session
                .getAttribute("secondTierEntities");

        for (Integer entity : selectedEntities) {

            List<thirdTierEntities> tier3EntityList = new ArrayList<thirdTierEntities>();

            secondTierEntities secondTierEntity = new secondTierEntities();
            secondTierEntity.setId(entity);

            programHierarchyDetails secondTierEntityDetails = hierarchymanager
                    .getProgramHierarchyItemDetails(entity);
            secondTierEntity.setName(secondTierEntityDetails.getName());

            Integer userId = 0;
            if (userDetails.getRoleId() == 3) {
                userId = userDetails.getId();
            }

            List tier3Entities = hierarchymanager.getActiveProgramOrgHierarchyItems(programId, 3, entity,
                    userId);

            if (!tier3Entities.isEmpty() && tier3Entities.size() > 0) {

                for (ListIterator iter = tier3Entities.listIterator(); iter.hasNext();) {

                    Object[] row = (Object[]) iter.next();

                    thirdTierEntities thirdTierEntity = new thirdTierEntities();
                    thirdTierEntity.setId(Integer.parseInt(row[0].toString()));
                    thirdTierEntity.setName(row[1].toString());

                    //Encrypt the use id to pass in the url
                    map = new HashMap<String, String>();
                    map.put("id", Integer.toString(Integer.parseInt(row[0].toString())));
                    map.put("topSecret", topSecret);

                    String[] encrypted = encrypt.encryptObject(map);

                    thirdTierEntity.setEncryptedId(encrypted[0]);
                    thirdTierEntity.setEncryptedSecret(encrypted[1]);

                    tier3EntityList.add(thirdTierEntity);

                }

                secondTierEntity.setTier3EntityList(tier3EntityList);

            }

            tier2EntityList.add(secondTierEntity);

        }

        mav.addObject("seltier2EntityList", tier2EntityList);

    }

    mav.addObject("selSurvey", surveyId);
    mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", ""));
    mav.addObject("currentPage", 1);
    mav.addObject("currPageNum", 1);

    mav.addObject("qNum", 0);
    mav.addObject("disabled", false);

    return mav;
}

From source file:com.rr.wabshs.ui.surveys.surveyController.java

/**
 * The '/editSurvey' GET request will build out the survey and display the first page of the survey.
 *
 * @param i The encrypted survey id/*ww  w  . j  a va2  s  .c o m*/
 * @param v The encrypted decryption key
 *
 * @param session
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "/editSurvey", "/viewSurvey" }, method = RequestMethod.GET)
public ModelAndView editSurvey(@RequestParam String i, @RequestParam String v, HttpSession session,
        HttpServletRequest request, @RequestParam(value = "sessionId", required = false) Integer sessionId)
        throws Exception {

    ModelAndView mav = new ModelAndView();
    mav.setViewName("/takeSurvey");
    mav.addObject("surveys", surveys);

    //Set the survey answer array to get ready to hold data
    if (session.getAttribute("questionAnswers") != null) {
        session.removeAttribute("questionAnswers");
    }
    session.setAttribute("questionAnswers", new ArrayList<surveyQuestionAnswers>());

    if (session.getAttribute("selectedProgramProfiles") != null) {
        session.removeAttribute("selectedProgramProfiles");
    }
    session.setAttribute("selectedProgramProfiles", new ArrayList<surveyProgramProfiles>());

    if (session.getAttribute("secondTierEntities") != null) {
        session.removeAttribute("secondTierEntities");
    }
    session.setAttribute("secondTierEntities", new ArrayList<secondTierEntities>());

    if (session.getAttribute("seenPages") != null) {
        session.removeAttribute("seenPages");
    }
    session.setAttribute("seenPages", new ArrayList<Integer>());

    if (session.getAttribute("selectedExtras") != null) {
        session.removeAttribute("selectedExtras");
    }
    session.setAttribute("selectedExtras", new ArrayList<surveyExtraInformation>());

    int clientId = 0;

    /* Decrypt the url */
    decryptObject decrypt = new decryptObject();

    Object obj = decrypt.decryptObject(i, v);

    String[] result = obj.toString().split((","));

    int submittedSurveyId = Integer.parseInt(result[0].substring(4));

    /* Get the survey details */
    submittedSurveys submittedSurveyDetails = surveyManager.getSubmittedSurvey(submittedSurveyId);

    surveys surveyDetails = surveyManager.getSurveyDetails(submittedSurveyDetails.getSurveyId());
    mav.addObject("surveyTag", surveyDetails.getSurveyTag());
    if (surveyDetails.isAssociateToProgram()) {
        mav.addObject("showPrograms", true);
    } else {
        mav.addObject("showPrograms", false);
    }

    User userDetails = (User) session.getAttribute("userDetails");

    survey survey = new survey();
    survey.setClientId(clientId);
    survey.setSurveyId(submittedSurveyDetails.getSurveyId());
    survey.setSurveyTitle(surveyDetails.getTitle());
    survey.setPrevButton(surveyDetails.getPrevButtonText());
    survey.setNextButton(surveyDetails.getNextButtonText());
    survey.setSaveButton(surveyDetails.getDoneButtonText());
    survey.setSubmittedSurveyId(submittedSurveyId);
    survey.setEntityIds(surveyManager.getSubmittedSurveyEntities(submittedSurveyId, userDetails));

    encryptObject encrypt = new encryptObject();
    Map<String, String> map;

    //Encrypt the use id to pass in the url
    map = new HashMap<String, String>();
    map.put("id", Integer.toString(submittedSurveyDetails.getSurveyId()));
    map.put("topSecret", topSecret);

    String[] encrypted = encrypt.encryptObject(map);

    survey.setEncryptedId(encrypted[0]);
    survey.setEncryptedSecret(encrypted[1]);

    mav.addObject("surveyURL", "?i=" + encrypted[0] + "&v=" + encrypted[1]);

    /* Get the pages */
    List<SurveyPages> surveyPages = surveyManager.getSurveyPages(submittedSurveyDetails.getSurveyId(), false, 0,
            0, 0, 0);
    SurveyPages currentPage = surveyManager.getSurveyPage(submittedSurveyDetails.getSurveyId(), true, 1,
            clientId, 0, 0, submittedSurveyId, 0, 0);
    survey.setPageTitle(currentPage.getPageTitle());
    survey.setSurveyPageQuestions(currentPage.getSurveyQuestions());
    survey.setTotalPages(surveyPages.size());
    survey.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId());
    survey.setPageId(currentPage.getId());

    /* Need to update any date functions */
    if (survey.getSurveyPageQuestions() != null && survey.getSurveyPageQuestions().size() > 0) {
        for (SurveyQuestions question : survey.getSurveyPageQuestions()) {
            if (question.getAnswerTypeId() == 6) {
                if (question.getQuestionValue().length() > 0
                        && !question.getQuestionValue().contains("^^^^^")) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat df2 = new SimpleDateFormat("M/dd/yy");
                    SimpleDateFormat df3 = new SimpleDateFormat("M/dd/yyyy");
                    SimpleDateFormat df4 = new SimpleDateFormat("M/d/yy");
                    SimpleDateFormat df5 = new SimpleDateFormat("M/d/yyyy");
                    SimpleDateFormat df6 = new SimpleDateFormat("MM/d/yyyy");
                    SimpleDateFormat df7 = new SimpleDateFormat("MM/d/yy");
                    SimpleDateFormat df8 = new SimpleDateFormat("MM/dd/yyyy");
                    SimpleDateFormat df9 = new SimpleDateFormat("MM/dd/yy");

                    Date formattedDate;
                    try {
                        formattedDate = df.parse(question.getQuestionValue());
                    } catch (Exception ex) {
                        try {
                            formattedDate = df2.parse(question.getQuestionValue());
                        } catch (Exception ex2) {
                            try {
                                formattedDate = df3.parse(question.getQuestionValue());
                            } catch (Exception ex3) {
                                try {
                                    formattedDate = df4.parse(question.getQuestionValue());
                                } catch (Exception ex4) {
                                    try {
                                        formattedDate = df5.parse(question.getQuestionValue());
                                    } catch (Exception ex5) {
                                        try {
                                            formattedDate = df6.parse(question.getQuestionValue());
                                        } catch (Exception ex6) {
                                            try {
                                                formattedDate = df7.parse(question.getQuestionValue());
                                            } catch (Exception ex7) {
                                                try {
                                                    formattedDate = df8.parse(question.getQuestionValue());
                                                } catch (Exception ex8) {
                                                    formattedDate = df9.parse(question.getQuestionValue());
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (question.getDateFormatType() == 2) { //dd/mm/yyyy
                        df.applyPattern("dd/MM/yyyy");
                    } else { //mm/dd/yyyy
                        df.applyPattern("MM/dd/yyyy");
                    }
                    String formattedDateasString = df.format(formattedDate);
                    question.setQuestionValue(formattedDateasString);
                }
            }
        }
    }

    if (sessionId != null && sessionId > 0) {
        survey.setSessionId(sessionId);
    }

    mav.addObject("survey", survey);
    mav.addObject("surveyPages", surveyPages);

    List<Integer> selectedEntities = surveyManager.getSurveyEntities(submittedSurveyId);

    /* Get a list of available schools for the selected districts */
    if (selectedEntities != null && !selectedEntities.isEmpty() && !"".equals(selectedEntities)) {

        List<secondTierEntities> tier2EntityList = (List<secondTierEntities>) session
                .getAttribute("secondTierEntities");

        for (Integer entityId : selectedEntities) {

            List<thirdTierEntities> tier3EntityList = new ArrayList<thirdTierEntities>();

            secondTierEntities secondTierEntity = new secondTierEntities();
            secondTierEntity.setId(entityId);

            programHierarchyDetails secondTierEntityDetails = hierarchymanager
                    .getProgramHierarchyItemDetails(entityId);
            secondTierEntity.setName(secondTierEntityDetails.getName());

            Integer userId = 0;
            if (userDetails.getRoleId() == 3) {
                userId = userDetails.getId();
            }

            List tier3Entities = hierarchymanager.getProgramOrgHierarchyItems(programId, 3, entityId, userId);

            if (!tier3Entities.isEmpty() && tier3Entities.size() > 0) {

                for (ListIterator iter = tier3Entities.listIterator(); iter.hasNext();) {

                    Object[] row = (Object[]) iter.next();

                    thirdTierEntities thirdTierEntity = new thirdTierEntities();
                    thirdTierEntity.setId(Integer.parseInt(row[0].toString()));
                    thirdTierEntity.setName(row[1].toString());

                    //Encrypt the use id to pass in the url
                    map = new HashMap<String, String>();
                    map.put("id", Integer.toString(Integer.parseInt(row[0].toString())));
                    map.put("topSecret", topSecret);

                    String[] encrypted2 = encrypt.encryptObject(map);

                    thirdTierEntity.setEncryptedId(encrypted2[0]);
                    thirdTierEntity.setEncryptedSecret(encrypted2[1]);

                    tier3EntityList.add(thirdTierEntity);

                }

                secondTierEntity.setTier3EntityList(tier3EntityList);

            }

            tier2EntityList.add(secondTierEntity);

        }

        mav.addObject("seltier2EntityList", tier2EntityList);

    }

    mav.addObject("selSurvey", submittedSurveyDetails.getSurveyId());
    mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", ""));

    mav.addObject("qNum", 0);
    mav.addObject("currPageNum", 1);

    boolean disabled = false;
    if ("/surveys/viewSurvey".equals(request.getServletPath())) {
        disabled = true;
    }

    mav.addObject("disabled", disabled);

    return mav;
}

From source file:javazoom.jlgui.player.amp.Player.java

/**
 * DnD : Drop implementation./*w ww.java2 s.  co m*/
 * Adds all dropped files to the playlist.
 */
public void drop(DropTargetDropEvent e) {
    // Check DataFlavor
    DataFlavor[] dfs = e.getCurrentDataFlavors();
    DataFlavor tdf = null;
    for (int i = 0; i < dfs.length; i++) {
        if (DataFlavor.javaFileListFlavor.equals(dfs[i])) {
            tdf = dfs[i];
            break;
        }
    }
    // Is file list ?
    if (tdf != null) {
        // Accept COPY DnD only.
        if ((e.getSourceActions() & DnDConstants.ACTION_COPY) != 0) {
            e.acceptDrop(DnDConstants.ACTION_COPY);
        } else
            return;
        try {
            Transferable t = e.getTransferable();
            Object data = t.getTransferData(tdf);
            // How many files ?
            if (data instanceof java.util.List) {
                java.util.List al = (java.util.List) data;
                // Read the first File.
                if (al.size() > 0) {
                    File file = null;
                    // Stops the player if needed.
                    if ((playerState == PLAY) || (playerState == PAUSE)) {
                        theSoundPlayer.stop();
                        playerState = STOP;
                    }
                    // Clean the playlist.
                    playlist.removeAllItems();
                    // Add all dropped files to playlist.
                    ListIterator li = al.listIterator();
                    while (li.hasNext()) {
                        file = (File) li.next();
                        PlaylistItem pli = null;
                        if (file != null) {

                            pli = new PlaylistItem(file.getName(), file.getAbsolutePath(), -1, true);
                            if (pli != null)
                                playlist.appendItem(pli);
                        }
                    }
                    // Start the playlist from the top.
                    playlist.nextCursor();
                    fileList.initPlayList();
                    this.setCurrentSong(playlist.getCursor());
                }
            } else {
                log.info("Unknown dropped objects");
            }
        } catch (IOException ioe) {
            log.info("Drop error", ioe);
            e.dropComplete(false);
            return;
        } catch (UnsupportedFlavorException ufe) {
            log.info("Drop error", ufe);
            e.dropComplete(false);
            return;
        } catch (Exception ex) {
            log.info("Drop error", ex);
            e.dropComplete(false);
            return;
        }
        e.dropComplete(true);
    }
}

From source file:net.sf.jasperreports.engine.export.HtmlExporter.java

protected void writeLayers(List<Table> layers, TableVisitor tableVisitor, TableCell cell) throws IOException {
    startCell(cell);//from   w  w w . j  a  v  a2s  .  co m

    StringBuilder styleBuffer = new StringBuilder();
    appendElementCellGenericStyle(cell, styleBuffer);
    appendBackcolorStyle(cell, styleBuffer);
    appendBorderStyle(cell.getBox(), styleBuffer);
    writeStyle(styleBuffer);

    finishStartCell();

    // layers need to always specify backcolors
    setBackcolor(null);
    writer.write("<div style=\"width: 100%; height: 100%; position: relative;\">\n");

    for (ListIterator<Table> it = layers.listIterator(); it.hasNext();) {
        Table table = it.next();

        StringBuilder layerStyleBuffer = new StringBuilder();
        if (it.hasNext()) {
            layerStyleBuffer.append("position: absolute; overflow: hidden; ");
        } else {
            layerStyleBuffer.append("position: relative; ");
        }
        layerStyleBuffer.append("width: 100%; height: 100%; ");

        if (it.previousIndex() > 0) {
            layerStyleBuffer.append("pointer-events: none; ");
        }

        writer.write("<div style=\"");
        writer.write(layerStyleBuffer.toString());
        writer.write("\">\n");

        ++pointerEventsNoneStack;
        exportTable(tableVisitor, table, false, false);
        --pointerEventsNoneStack;

        writer.write("</div>\n");
    }

    writer.write("</div>\n");
    restoreBackcolor();

    endCell();
}

From source file:org.broadleafcommerce.core.web.processor.OnePageCheckoutProcessor.java

/**
 * This method is responsible of populating the variables necessary to draw the checkout page.
 * This logic is highly dependent on your layout. If your layout does not follow the same flow
 * as the HeatClinic demo, you will need to override with your own custom layout implementation
 *
 * @param localVars//from  w w  w  .  j  ava 2  s .co m
 */
protected void populateSectionViewStates(Map<String, Object> localVars) {
    boolean orderInfoPopulated = hasPopulatedOrderInfo(CartState.getCart());
    boolean billingPopulated = hasPopulatedBillingAddress(CartState.getCart());
    boolean shippingPopulated = hasPopulatedShippingAddress(CartState.getCart());

    localVars.put("orderInfoPopulated", orderInfoPopulated);
    localVars.put("billingPopulated", billingPopulated);
    localVars.put("shippingPopulated", shippingPopulated);

    //Logic to show/hide sections based on state of the order
    // show all sections including header unless specifically hidden
    // (e.g. hide shipping if no shippable items in order or hide billing section if the order payment doesn't need
    // an address i.e. PayPal Express)
    boolean showBillingInfoSection = true;
    boolean showShippingInfoSection = true;
    boolean showAllPaymentMethods = true;

    int numShippableFulfillmentGroups = calculateNumShippableFulfillmentGroups();
    if (numShippableFulfillmentGroups == 0) {
        showShippingInfoSection = false;
    }

    boolean orderContainsThirdPartyPayment = false;
    boolean orderContainsUnconfirmedCreditCard = false;
    OrderPayment unconfirmedCC = null;
    if (CartState.getCart().getPayments() != null) {
        for (OrderPayment payment : CartState.getCart().getPayments()) {
            if (payment.isActive() && PaymentType.THIRD_PARTY_ACCOUNT.equals(payment.getType())) {
                orderContainsThirdPartyPayment = true;
            }
            if (payment.isActive() && (PaymentType.CREDIT_CARD.equals(payment.getType())
                    && !PaymentGatewayType.TEMPORARY.equals(payment.getGatewayType()))) {
                orderContainsUnconfirmedCreditCard = true;
                unconfirmedCC = payment;
            }
        }
    }

    //Toggle the Payment Info Section based on what payments were applied to the order
    //(e.g. Third Party Account (i.e. PayPal Express) or Gift Cards/Customer Credit)
    Money orderTotalAfterAppliedPayments = CartState.getCart().getTotalAfterAppliedPayments();
    if (orderContainsThirdPartyPayment || orderContainsUnconfirmedCreditCard) {
        showBillingInfoSection = false;
        showAllPaymentMethods = false;
    } else if (orderTotalAfterAppliedPayments != null && orderTotalAfterAppliedPayments.isZero()) {
        //If all the applied payments (e.g. gift cards) cover the entire amount
        //we don't need to show all payment method options.
        showAllPaymentMethods = false;
    }

    localVars.put("showBillingInfoSection", showBillingInfoSection);
    localVars.put("showAllPaymentMethods", showAllPaymentMethods);
    localVars.put("orderContainsThirdPartyPayment", orderContainsThirdPartyPayment);
    localVars.put("orderContainsUnconfirmedCreditCard", orderContainsUnconfirmedCreditCard);
    localVars.put("unconfirmedCC", unconfirmedCC);

    //The Sections are all initialized to INACTIVE view
    List<CheckoutSectionDTO> drawnSections = new LinkedList<CheckoutSectionDTO>();
    CheckoutSectionDTO orderInfoSection = new CheckoutSectionDTO(CheckoutSectionViewType.ORDER_INFO,
            orderInfoPopulated);
    CheckoutSectionDTO billingInfoSection = new CheckoutSectionDTO(CheckoutSectionViewType.BILLING_INFO,
            billingPopulated);
    CheckoutSectionDTO shippingInfoSection = new CheckoutSectionDTO(CheckoutSectionViewType.SHIPPING_INFO,
            shippingPopulated);
    CheckoutSectionDTO paymentInfoSection = new CheckoutSectionDTO(CheckoutSectionViewType.PAYMENT_INFO, false);

    String orderInfoHelpMessage = (String) localVars.get("orderInfoHelpMessage");
    String billingInfoHelpMessage = (String) localVars.get("billingInfoHelpMessage");
    String shippingInfoHelpMessage = (String) localVars.get("shippingInfoHelpMessage");

    //Add the Order Info Section
    drawnSections.add(orderInfoSection);

    //Add the Billing Section
    if (showBillingInfoSection) {
        billingInfoSection.setHelpMessage(orderInfoHelpMessage);
        drawnSections.add(billingInfoSection);
    }

    //Add the Shipping Section
    if (showShippingInfoSection) {

        if (showBillingInfoSection) {
            shippingInfoSection.setHelpMessage(billingInfoHelpMessage);
        } else {
            shippingInfoSection.setHelpMessage(orderInfoHelpMessage);
        }

        drawnSections.add(shippingInfoSection);
    }

    //Add the Payment Section
    if (showShippingInfoSection) {
        paymentInfoSection.setHelpMessage(shippingInfoHelpMessage);
    } else if (showBillingInfoSection) {
        paymentInfoSection.setHelpMessage(billingInfoHelpMessage);
    } else {
        paymentInfoSection.setHelpMessage(orderInfoHelpMessage);
    }

    drawnSections.add(paymentInfoSection);

    //Logic to toggle state between form view, saved view, and inactive view
    //This is dependent on the layout of your checkout form. Override this if layout is different.

    //initialize first view to always be a FORM view
    CheckoutSectionDTO firstSection = drawnSections.get(0);
    firstSection.setState(CheckoutSectionStateType.FORM);
    //iterate through all the drawn sections and set their state based on the state of the other sections.

    for (ListIterator<CheckoutSectionDTO> itr = drawnSections.listIterator(); itr.hasNext();) {
        CheckoutSectionDTO previousSection = null;
        if (itr.hasPrevious()) {
            previousSection = drawnSections.get(itr.previousIndex());
        }
        CheckoutSectionDTO section = itr.next();

        //if the previous section is populated, set this section to a Form View
        if (previousSection != null && previousSection.isPopulated()) {
            section.setState(CheckoutSectionStateType.FORM);
        }
        //If this sections is populated then set this section to the Saved View
        if (section.isPopulated()) {
            section.setState(CheckoutSectionStateType.SAVED);
        }

        //Custom Logic to handle a state where there may have been an error on the Payment Gateway
        //and the customer is booted back to the checkout page and will have to re-enter their billing address
        //and payment information as there may have been an error on either. Since, to handle all gateways with the same layout
        //we are breaking the Billing Address Form from the Payment Info Form, to serve a better UX, we will have hide the payment info as
        //the customer will need to re-enter their billing address to try again.
        //{@see DefaultPaymentGatewayCheckoutService where payments are invalidated on an unsuccessful transaction}
        if (CheckoutSectionViewType.PAYMENT_INFO.equals(section.getView())) {
            if (showBillingInfoSection && !billingPopulated) {
                section.setState(CheckoutSectionStateType.INACTIVE);
                section.setHelpMessage(billingInfoHelpMessage);
            }
        }

        //Finally, if the edit button is explicitly clicked, set the section to Form View
        BroadleafRequestContext blcContext = BroadleafRequestContext.getBroadleafRequestContext();
        HttpServletRequest request = blcContext.getRequest();
        boolean editOrderInfo = BooleanUtils.toBoolean(request.getParameter("edit-order-info"));
        boolean editBillingInfo = BooleanUtils.toBoolean(request.getParameter("edit-billing"));
        boolean editShippingInfo = BooleanUtils.toBoolean(request.getParameter("edit-shipping"));

        if (CheckoutSectionViewType.ORDER_INFO.equals(section.getView()) && editOrderInfo) {
            section.setState(CheckoutSectionStateType.FORM);
        } else if (CheckoutSectionViewType.BILLING_INFO.equals(section.getView()) && editBillingInfo) {
            section.setState(CheckoutSectionStateType.FORM);
        } else if (CheckoutSectionViewType.SHIPPING_INFO.equals(section.getView()) && editShippingInfo) {
            section.setState(CheckoutSectionStateType.FORM);
        }
    }

    localVars.put("checkoutSectionDTOs", drawnSections);

}

From source file:org.apache.fop.layoutmgr.inline.LineLayoutManager.java

/**
 * Phase 1 of Knuth algorithm: Collect all inline Knuth elements before determining line breaks.
 * @param context the LayoutContext// w ww.j  a  v  a2 s. c  o m
 */
private void collectInlineKnuthElements(LayoutContext context) {
    LayoutContext inlineLC = new LayoutContext(context);

    // convert all the text in a sequence of paragraphs made
    // of KnuthBox, KnuthGlue and KnuthPenalty objects
    boolean previousIsBox = false;

    StringBuffer trace = new StringBuffer("LineLM:");

    Paragraph lastPar = null;

    InlineLevelLayoutManager curLM;
    while ((curLM = (InlineLevelLayoutManager) getChildLM()) != null) {
        List inlineElements = curLM.getNextKnuthElements(inlineLC, effectiveAlignment);
        if (inlineElements == null || inlineElements.size() == 0) {
            /* curLM.getNextKnuthElements() returned null or an empty list;
             * this can happen if there is nothing more to layout,
             * so just iterate once more to see if there are other children */
            continue;
        }

        if (lastPar != null) {
            KnuthSequence firstSeq = (KnuthSequence) inlineElements.get(0);

            // finish last paragraph before a new block sequence
            if (!firstSeq.isInlineSequence()) {
                lastPar.endParagraph();
                ElementListObserver.observe(lastPar, "line", null);
                lastPar = null;
                if (log.isTraceEnabled()) {
                    trace.append(" ]");
                }
                previousIsBox = false;
            }

            // does the first element of the first paragraph add to an existing word?
            if (lastPar != null) {
                KnuthElement thisElement;
                thisElement = (KnuthElement) firstSeq.get(0);
                if (thisElement.isBox() && !thisElement.isAuxiliary() && previousIsBox) {
                    lastPar.addALetterSpace();
                }
            }
        }

        // loop over the KnuthSequences (and single KnuthElements) in returnedList
        ListIterator iter = inlineElements.listIterator();
        while (iter.hasNext()) {
            KnuthSequence sequence = (KnuthSequence) iter.next();
            // the sequence contains inline Knuth elements
            if (sequence.isInlineSequence()) {
                // look at the last element
                ListElement lastElement = sequence.getLast();
                assert lastElement != null;
                previousIsBox = lastElement.isBox() && !((KnuthElement) lastElement).isAuxiliary()
                        && ((KnuthElement) lastElement).getWidth() != 0;

                // if last paragraph is open, add the new elements to the paragraph
                // else this is the last paragraph
                if (lastPar == null) {
                    lastPar = new Paragraph(this, textAlignment, textAlignmentLast, textIndent.getValue(this),
                            lastLineEndIndent.getValue(this));
                    lastPar.startSequence();
                    if (log.isTraceEnabled()) {
                        trace.append(" [");
                    }
                } else {
                    if (log.isTraceEnabled()) {
                        trace.append(" +");
                    }
                }
                lastPar.addAll(sequence);
                if (log.isTraceEnabled()) {
                    trace.append(" I");
                }

                // finish last paragraph if it was closed with a linefeed
                if (lastElement.isPenalty()
                        && ((KnuthPenalty) lastElement).getPenalty() == -KnuthPenalty.INFINITE) {
                    // a penalty item whose value is -inf
                    // represents a preserved linefeed,
                    // which forces a line break
                    lastPar.removeLast();
                    if (!lastPar.containsBox()) {
                        //only a forced linefeed on this line
                        //-> compensate with an auxiliary glue
                        lastPar.add(new KnuthGlue(ipd, 0, ipd, null, true));
                    }
                    lastPar.endParagraph();
                    ElementListObserver.observe(lastPar, "line", null);
                    lastPar = null;
                    if (log.isTraceEnabled()) {
                        trace.append(" ]");
                    }
                    previousIsBox = false;
                }
            } else { // the sequence is a block sequence
                // the positions will be wrapped with this LM in postProcessLineBreaks
                knuthParagraphs.add(sequence);
                if (log.isTraceEnabled()) {
                    trace.append(" B");
                }
            }
        } // end of loop over returnedList
    }

    if (lastPar != null) {
        lastPar.endParagraph();
        ElementListObserver.observe(lastPar, "line", fobj.getId());
        if (log.isTraceEnabled()) {
            trace.append(" ]");
        }
    }
    log.trace(trace);
}

From source file:org.apache.lens.cube.metadata.CubeMetastoreClient.java

/**
 * @param factOrDimTable/*  ww  w.  j av a  2s.c  o  m*/
 * @param storageName
 * @param updatePeriod
 * @param storagePartitionDescs
 * @param type
 * @return
 * @throws HiveException
 * @throws LensException
 */
private List<Partition> addPartitions(String factOrDimTable, String storageName, UpdatePeriod updatePeriod,
        List<StoragePartitionDesc> storagePartitionDescs, CubeTableType type)
        throws HiveException, LensException {
    String storageTableName = getStorageTableName(factOrDimTable, storageName, updatePeriod);
    if (type == CubeTableType.DIM_TABLE) {
        // Adding partition in dimension table.
        Map<Map<String, String>, LatestInfo> latestInfos = Maps.newHashMap();
        for (Map.Entry<Map<String, String>, List<StoragePartitionDesc>> entry : groupByNonTimePartitions(
                storagePartitionDescs).entrySet()) {
            latestInfos.put(entry.getKey(), getDimTableLatestInfo(storageTableName, entry.getKey(),
                    getTimePartSpecs(entry.getValue()), updatePeriod));
        }
        List<Partition> partsAdded = getStorage(storageName).addPartitions(getClient(), factOrDimTable,
                updatePeriod, storagePartitionDescs, latestInfos, storageTableName);
        ListIterator<Partition> iter = partsAdded.listIterator();
        while (iter.hasNext()) {
            if (iter.next().getSpec().values().contains(StorageConstants.LATEST_PARTITION_VALUE)) {
                iter.remove();
            }
        }
        latestLookupCache.add(storageTableName);
        return partsAdded;
    } else if (type == CubeTableType.FACT) {
        List<Partition> partsAdded = new ArrayList<>();
        // first update in memory, then add to hive table's partitions. delete is reverse.
        partitionTimelineCache.updateForAddition(factOrDimTable, storageName, updatePeriod,
                getTimePartSpecs(storagePartitionDescs,
                        getStorageTableStartDate(storageTableName, factOrDimTable),
                        getStorageTableEndDate(storageTableName, factOrDimTable)));
        // Adding partition in fact table.
        if (storagePartitionDescs.size() > 0) {
            partsAdded = getStorage(storageName).addPartitions(getClient(), factOrDimTable, updatePeriod,
                    storagePartitionDescs, null, storageTableName);
        }
        // update hive table
        alterTablePartitionCache((Storage.getPrefix(storageName) + factOrDimTable).toLowerCase(), updatePeriod,
                storageTableName);
        return partsAdded;
    } else {
        throw new LensException("Can't add partitions to anything other than fact or dimtable");
    }
}