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:com.nuodb.migrator.cli.parse.parser.ParserImpl.java

/**
 * Parse the withConnection.arguments according to the specified options and properties.
 *
 * @param arguments to parse.//  ww w  . ja  v a 2  s.  c om
 * @param option    sets the option to parse against.
 * @return the option setValue object.
 */
public OptionSet parse(String[] arguments, Option option) throws OptionException {
    if (logger.isTraceEnabled()) {
        logger.trace(format("Parsing options %s", join(asList(arguments), " ")));
    }
    List<String> list = Lists.newArrayList(arguments);

    CommandLine commandLine = new CommandLineImpl(option, list);
    // pick up any defaults from the meta
    option.defaults(commandLine);
    // withConnection the options as far as possible
    ListIterator<String> iterator = list.listIterator();
    Object previous = null;
    while (option.canProcess(commandLine, iterator)) {
        // peek at the next item and backtrack
        String current = iterator.next();
        iterator.previous();
        // if we have just tried to process this instance
        if (current == previous) {
            // abort
            break;
        }
        previous = current;
        option.preProcess(commandLine, iterator);
        option.process(commandLine, iterator);
    }
    if (iterator.hasNext()) {
        throw new OptionException(format("Unexpected argument %s", iterator.next()), option);
    }
    option.postProcess(commandLine);
    return commandLine;
}

From source file:org.apereo.portal.rendering.xslt.XSLTComponent.java

@Override
public PipelineEventReader<XMLEventReader, XMLEvent> getEventReader(HttpServletRequest request,
        HttpServletResponse response) {//from  w  ww  . j a  v a2s .  c  om
    final PipelineEventReader<XMLEventReader, XMLEvent> pipelineEventReader = this.wrappedComponent
            .getEventReader(request, response);

    final Transformer transformer = this.transformerSource.getTransformer(request, response);

    //Setup a URIResolver based on the current resource loader
    transformer.setURIResolver(this.uriResolver);

    //Configure the Transformer via injected class
    if (this.xsltParameterSource != null) {
        final Map<String, Object> transformerParameters = this.xsltParameterSource.getParameters(request,
                response);
        if (transformerParameters != null) {
            this.logger.debug("{} - Setting Transformer Parameters: ", this.beanName, transformerParameters);
            for (final Map.Entry<String, Object> transformerParametersEntry : transformerParameters
                    .entrySet()) {
                final String name = transformerParametersEntry.getKey();
                final Object value = transformerParametersEntry.getValue();
                if (value != null) {
                    transformer.setParameter(name, value);
                }
            }
        }

        final Properties outputProperties = this.xsltParameterSource.getOutputProperties(request, response);
        if (outputProperties != null) {
            this.logger.debug("{} - Setting Transformer Output Properties: ", this.beanName, outputProperties);
            transformer.setOutputProperties(outputProperties);
        }
    }

    //The event reader from the previous component in the pipeline
    final XMLEventReader eventReader = pipelineEventReader.getEventReader();

    //Wrap the event reader in a stream reader to avoid a JDK bug
    final XMLStreamReader streamReader;
    try {
        streamReader = new FixedXMLEventStreamReader(eventReader);
    } catch (XMLStreamException e) {
        throw new RuntimeException("Failed to create XMLStreamReader from XMLEventReader", e);
    }
    final Source xmlReaderSource = new StAXSource(streamReader);

    //Setup logging for the transform
    transformer.setErrorListener(this.errorListener);

    //Transform to a SAX ContentHandler to avoid JDK bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6775588
    final XMLEventBufferWriter eventWriterBuffer = new XMLEventBufferWriter();
    final ContentHandler contentHandler = StaxUtils.createLexicalContentHandler(eventWriterBuffer);
    contentHandler.setDocumentLocator(new LocatorImpl());

    final SAXResult outputTarget = new SAXResult(contentHandler);
    try {
        this.logger.debug("{} - Begining XML Transformation", this.beanName);
        transformer.transform(xmlReaderSource, outputTarget);
        this.logger.debug("{} - XML Transformation complete", this.beanName);
    } catch (TransformerException e) {
        throw new RuntimeException("Failed to transform document", e);
    }

    final String mediaType = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE);

    final List<XMLEvent> eventBuffer = eventWriterBuffer.getEventBuffer();
    final XMLEventReader outputEventReader = new XMLEventBufferReader(eventBuffer.listIterator());

    final Map<String, String> outputProperties = pipelineEventReader.getOutputProperties();
    final PipelineEventReaderImpl<XMLEventReader, XMLEvent> pipelineEventReaderImpl = new PipelineEventReaderImpl<XMLEventReader, XMLEvent>(
            outputEventReader, outputProperties);
    pipelineEventReaderImpl.setOutputProperty(OutputKeys.MEDIA_TYPE, mediaType);
    return pipelineEventReaderImpl;
}

From source file:edu.harvard.mcz.imagecapture.TemplatePickerDialog.java

protected boolean setupForImage(ICImage image) throws UnreadableFileException {
    boolean result = false;
    imageToTemplate = image;/* ww w.j av  a 2  s  .co  m*/

    StringBuffer heading = new StringBuffer();
    heading.append("Current Template:");
    heading.append(" ").append(image.getTemplateId());

    StringBuffer filename = new StringBuffer();
    filename.append(image.getPath()).append(File.pathSeparator).append(image.getFilename());
    this.lblFileName.setText(filename.toString());
    lblTemplate.setText(heading.toString());
    comboBoxTemplatePicker.addItem(image.getTemplateId());
    File imageFile = new File(
            ImageCaptureProperties.assemblePathWithBase(image.getPath(), image.getFilename()));

    BufferedImage bufImage = null;
    int imageWidth = 0;
    try {
        bufImage = ImageIO.read(imageFile);
        imageWidth = bufImage.getWidth();
    } catch (IOException e) {
        throw new UnreadableFileException("IOException trying to read " + imageFile.getName());
    }

    if (imageFile.exists()) {
        List<PositionTemplate> templates = PositionTemplate.getTemplates();
        ListIterator<PositionTemplate> i = templates.listIterator();
        while (i.hasNext()) {
            PositionTemplate template = i.next();
            if (!template.getTemplateId().equals(PositionTemplate.TEMPLATE_NO_COMPONENT_PARTS)) {
                int templateWidth = -1;
                try {
                    templateWidth = (int) template.getImageSize().getWidth();
                } catch (NullPointerException e) {
                    log.debug(e.getMessage());
                }
                if (imageWidth == templateWidth) {
                    comboBoxTemplatePicker.addItem(template.getTemplateId());
                }
            }
        }
    }

    return result;
}

From source file:com.fstx.stdlib.authen.users.old.GroupMembershipDAOTest.java

public void testGetMemberAndNonMemberList() throws Exception {
    Collection listUsers = UserDAO.factory.build().find(selectAll);

    GroupMembershipDAO dao = GroupMembershipDAO.factory.build();
    List listMembers = dao.find(GroupMembershipDAO.SELECT_BY_GROUP_USER_MEMBERS, "" + group.getId());
    log.info("Members: " + listMembers);

    Collection nonMembers = UserDAO.factory.build().find(selectAll);
    Iterator i = listMembers.listIterator();

    while (i.hasNext()) {
        Object o = i.next();/*  ww  w  .j  ava2 s . c o m*/
        nonMembers.remove(o);
    }

    log.info("nonMemb: " + nonMembers);

    assertTrue(nonMembers.size() == listUsers.size() - listMembers.size());
}

From source file:org.alfresco.repo.admin.patch.impl.RenameSiteAuthorityDisplayName.java

/**
 * Rename display names of authorities of sites.
 * /*w ww  .j a va2s .  co m*/
 * @param siteInfos
 *            list of sites
 */
private void renameDispayNames(final List<SiteInfo> siteInfos) {
    final String tenantDomain = tenantAdminService.getCurrentUserDomain();

    final Iterator<SiteInfo> pathItr = siteInfos.listIterator();

    BatchProcessWorkProvider<SiteInfo> siteWorkProvider = new BatchProcessWorkProvider<SiteInfo>() {

        @Override
        public int getTotalEstimatedWorkSize() {
            return siteInfos.size();
        }

        @Override
        public Collection<SiteInfo> getNextWork() {
            int batchCount = 0;

            List<SiteInfo> nodes = new ArrayList<SiteInfo>(BATCH_SIZE);
            while (pathItr.hasNext() && batchCount++ != BATCH_SIZE) {
                nodes.add(pathItr.next());
            }
            return nodes;
        }
    };

    // prepare the batch processor and worker object
    BatchProcessor<SiteInfo> siteBatchProcessor = new BatchProcessor<SiteInfo>("RenameSiteAuthorityDisplayName",
            this.transactionHelper, siteWorkProvider, BATCH_THREADS, BATCH_SIZE, this.applicationEventPublisher,
            progress_logger, BATCH_SIZE * 10);

    BatchProcessWorker<SiteInfo> worker = new BatchProcessWorker<SiteInfo>() {

        @Override
        public String getIdentifier(SiteInfo entry) {
            return entry.getShortName();
        }

        @Override
        public void beforeProcess() throws Throwable {
            // Disable rules
            ruleService.disableRules();
            // Authentication
            String systemUser = AuthenticationUtil.getSystemUserName();
            systemUser = tenantAdminService.getDomainUser(systemUser, tenantDomain);
            AuthenticationUtil.setRunAsUser(systemUser);
        }

        @Override
        public void afterProcess() throws Throwable {
            // Enable rules
            ruleService.enableRules();
            // Clear authentication
            AuthenticationUtil.clearCurrentSecurityContext();
        }

        @Override
        public void process(SiteInfo siteInfo) throws Throwable {
            // Set all the permissions of site
            Set<AccessPermission> sitePermissions = permissionService
                    .getAllSetPermissions(siteInfo.getNodeRef());
            for (AccessPermission sitePermission : sitePermissions) {
                // Use only GROUP authority
                if (sitePermission.getAuthorityType() == AuthorityType.GROUP) {
                    String authorityName = sitePermission.getAuthority();
                    String currDisplayName = authorityService.getAuthorityDisplayName(authorityName);
                    String necessaryName = ((SiteServiceImpl) siteService)
                            .getSiteRoleGroup(siteInfo.getShortName(), sitePermission.getPermission(), false);
                    String alternativeName = ((SiteServiceImpl) siteService)
                            .getSiteRoleGroup(siteInfo.getShortName(), sitePermission.getPermission(), true);
                    // check for correct displayName
                    if ((!necessaryName.equalsIgnoreCase(currDisplayName))
                            || (!alternativeName.equalsIgnoreCase(currDisplayName))) {
                        // fix incorrect display name
                        authorityService.setAuthorityDisplayName(authorityName, necessaryName);
                    }
                }
            }
        }
    };

    siteBatchProcessor.process(worker, true);
}

From source file:org.apereo.portal.redirect.PortletRedirectionController.java

protected String getUrlString(IRedirectionUrl url, HttpServletRequest request, List<String> extraPath) {

    if (url instanceof ExternalRedirectionUrl) {
        ExternalRedirectionUrl externalUrl = (ExternalRedirectionUrl) url;
        StringBuffer urlStr = new StringBuffer();
        urlStr.append(externalUrl.getUrl());

        try {//w  w w.ja v a 2  s .co m

            // add any additional parameters
            String separator = "?";
            for (Map.Entry<String, String[]> param : externalUrl.getAdditionalParameters().entrySet()) {
                for (String value : param.getValue()) {
                    urlStr.append(separator);
                    urlStr.append(param.getKey());
                    urlStr.append("=");
                    urlStr.append(URLEncoder.encode(value, "UTF-8"));
                    separator = "&";
                }
            }

            // add any dynamic parameters
            for (Map.Entry<String, String> param : externalUrl.getDynamicParameters().entrySet()) {
                String[] values = request.getParameterValues(param.getKey());
                if (values != null) {
                    for (String value : values) {
                        urlStr.append(separator);
                        urlStr.append(param.getValue());
                        urlStr.append("=");
                        urlStr.append(URLEncoder.encode(value, "UTF-8"));
                        separator = "&";
                    }
                }
            }

            if (!extraPath.isEmpty()) {

                List<String> paramNames = externalUrl.getPathParameters();

                ListIterator<String> itt = paramNames.listIterator();
                while (itt.hasNext() && !extraPath.isEmpty()) {
                    String param = itt.next();
                    String value;
                    if (itt.hasNext()) {
                        value = extraPath.remove(0);
                    } else {
                        value = StringUtils.join(extraPath, "/");
                    }
                    urlStr.append(separator);
                    urlStr.append(param);
                    urlStr.append("=");
                    urlStr.append(URLEncoder.encode(value, "UTF-8"));
                    separator = "&";
                }
            }

            return urlStr.toString();

        } catch (UnsupportedEncodingException ex) {
            log.error("Unable to encode URL parameter for external service redirect", ex);
            return null;
        }

    }

    else {

        PortletRedirectionUrl portletUrl = (PortletRedirectionUrl) url;

        // create the base URL for the portlet
        final IPortletWindow portletWindow = this.portletWindowRegistry
                .getOrCreateDefaultPortletWindowByFname(request, portletUrl.getFname());
        final IPortalUrlBuilder portalUrlBuilder = this.portalUrlProvider.getPortalUrlBuilderByPortletWindow(
                request, portletWindow.getPortletWindowId(), portletUrl.getType());
        final IPortletUrlBuilder portletUrlBuilder = portalUrlBuilder.getTargetedPortletUrlBuilder();
        portletUrlBuilder.setPortletMode(portletUrl.getMode());
        portletUrlBuilder.setWindowState(WindowState.MAXIMIZED);

        // for each of the defined additional parameters, add a matching
        // parameter to the portlet URL
        for (Map.Entry<String, String[]> param : portletUrl.getAdditionalParameters().entrySet()) {
            portletUrlBuilder.addParameter(param.getKey(), param.getValue());
        }

        // for each of the defined dynamic parameters, add a parameter if
        // the value submitted to this service was non-null
        for (Map.Entry<String, String> param : portletUrl.getDynamicParameters().entrySet()) {
            String[] values = request.getParameterValues(param.getKey());
            if (values != null) {
                portletUrlBuilder.addParameter(param.getValue(), values);
            }
        }

        if (!extraPath.isEmpty()) {
            List<String> paramNames = portletUrl.getPathParameters();

            ListIterator<String> itt = paramNames.listIterator();
            while (itt.hasNext() && !extraPath.isEmpty()) {

                String param = itt.next();
                String value;
                if (itt.hasNext()) {
                    value = extraPath.remove(0);
                } else {
                    value = StringUtils.join(extraPath, "/");
                }

                if (StringUtils.isEmpty(value)) {
                    break;
                } else
                    portletUrlBuilder.addParameter(param, value);
            }
        }

        return portalUrlBuilder.getUrlString();
    }
}

From source file:de.micromata.genome.util.event.SimpleEventClassRegistry.java

/**
 * Removes the listener.//from  www  . j  ava 2s  .com
 *
 * @param event the event
 * @param listener the listener
 */
protected void removeListener(Class<? extends MgcEvent> event, Class<? extends MgcEventListener<?>> listener) {
    Map<Class<? extends MgcEvent>, List<Reference<Class<? extends MgcEventListener<?>>>>> nmp = new ReferenceMap<>(
            ReferenceMap.ReferenceStrength.WEAK, ReferenceMap.ReferenceStrength.HARD);
    nmp.putAll(listenerMap);
    List<Reference<Class<? extends MgcEventListener<?>>>> list = nmp.get(event);
    if (list == null) {
        return;
    }
    for (ListIterator<Reference<Class<? extends MgcEventListener<?>>>> lit = list.listIterator(); lit
            .hasNext();) {
        Reference<Class<? extends MgcEventListener<?>>> ref = lit.next();
        Class<? extends MgcEventListener<?>> cls = ref.get();
        if (cls == listener) {
            lit.remove();
        }
    }
    listenerMap = nmp;

}

From source file:edu.cornell.mannlib.vitro.webapp.dao.jena.PropertyGroupDaoJena.java

public int removeUnpopulatedGroups(List<PropertyGroup> groups) {
    if (groups == null || groups.size() == 0)
        return 0;
    int removedGroupsCount = 0;
    ListIterator<PropertyGroup> it = groups.listIterator();
    while (it.hasNext()) {
        PropertyGroup group = it.next();
        List properties = group.getPropertyList();
        if (properties == null || properties.size() < 1) {
            removedGroupsCount++;/*from  ww  w  .  j a  va 2s .  c o m*/
            it.remove();
        }
    }
    return removedGroupsCount;
}

From source file:com.google.gwt.emultest.java.util.ListTestBase.java

public void testListIteratorHasNextHasPreviousAndIndexes() {
    List l = makeEmptyList();
    ListIterator i = l.listIterator();
    assertFalse(i.hasNext());//from w  w w  . j a  va 2  s .co  m
    assertFalse(i.hasPrevious());
    i.add(new Integer(1));
    assertEquals(1, i.nextIndex());
    assertEquals(0, i.previousIndex());
    i = l.listIterator();
    assertEquals(0, i.nextIndex());
    assertEquals(-1, i.previousIndex());
    assertTrue(i.hasNext());
    assertFalse(i.hasPrevious());
    i.next();
    assertEquals(1, i.nextIndex());
    assertEquals(0, i.previousIndex());
    assertFalse(i.hasNext());
    assertTrue(i.hasPrevious());
}

From source file:com.google.gwt.emultest.java.util.ListTestBase.java

public void testListIteratorAddInSeveralPositions() {
    List l = makeEmptyList();
    ListIterator i = l.listIterator();
    l.add(new Integer(0));
    for (int n = 2; n < 5; n += 2) {
        l.add(new Integer(n));
    }//from   ww w .jav  a 2s .c om
    i = l.listIterator();
    i.next();
    i.add(new Integer(1));
    i.next();
    i.next();
    i.previous();
    i.add(new Integer(3));
    i.next();
    i.add(new Integer(5));
    i.add(new Integer(6));
    for (int n = 0; n < 6; n++) {
        assertEquals(new Integer(n), l.get(n));
    }
}