Example usage for org.apache.commons.collections IteratorUtils getIterator

List of usage examples for org.apache.commons.collections IteratorUtils getIterator

Introduction

In this page you can find the example usage for org.apache.commons.collections IteratorUtils getIterator.

Prototype

public static Iterator getIterator(Object obj) 

Source Link

Document

Gets a suitable Iterator for the given object.

Usage

From source file:com.redhat.rhn.manager.task.TaskScheduler.java

/**
 * This method inserts/updates tasks by the channels in an errata. This method
 * corresponds to ChannelEditor.pm -> schedule_errata_cache_update method in the
 * perl codebase.//from  w w  w .  j a  v  a2s  .  c om
 */
public void updateByChannels() {
    //Get the channels for this errata
    Set channels = errata.getChannels();

    //Loop through the channels and either insert or update a task
    Iterator itr = IteratorUtils.getIterator(channels);
    while (itr.hasNext()) {
        Channel channel = (Channel) itr.next();

        //Look to see if task already exists...
        Task task = TaskFactory.lookup(org, CHANNELNAME, channel.getId());
        if (task == null) { //if not, create a new task
            task = TaskFactory.createTask(org, CHANNELNAME, channel.getId());
        } else { //if so, update the earliest column
            task.setEarliest(new Date(System.currentTimeMillis() + DELAY));
        }
        //save the task
        TaskFactory.save(task);
    }
}

From source file:com.redhat.rhn.frontend.action.errata.ErrataDetailsSetupAction.java

/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
        HttpServletResponse response) {//from   www .  ja  v a  2  s  .  co m

    RequestContext requestContext = new RequestContext(request);

    Long eid = requestContext.getRequiredParam("eid");

    User user = requestContext.getCurrentUser();
    Errata errata = ErrataManager.lookupErrata(eid, user);
    String ovalFile = findOvalFile(errata.getId());
    DataResult channels = ErrataManager.affectedChannels(user, eid);
    DataResult fixed = ErrataManager.bugsFixed(eid);
    DataResult cve = ErrataManager.errataCVEs(eid);
    DataResult keywords = ErrataManager.keywords(eid);

    //create the display for keywords
    //example: "/var/tmp, current, directory, expect"
    String keywordsDisplay = null;
    if (keywords != null) {
        keywordsDisplay = StringUtil.join(LocalizationService.getInstance().getMessage("list delimiter"),
                IteratorUtils.getIterator(CollectionUtils.collect(keywords, new Transformer() {
                    public Object transform(Object o) {
                        return o.toString();
                    }
                })));
    }

    request.setAttribute("errata", errata);
    request.setAttribute("issued", LocalizationService.getInstance().formatShortDate(errata.getIssueDate()));
    request.setAttribute("updated", LocalizationService.getInstance().formatShortDate(errata.getUpdateDate()));
    request.setAttribute("topic", StringUtil.htmlifyText(errata.getTopic()));
    request.setAttribute("description", StringUtil.htmlifyText(errata.getDescription()));
    request.setAttribute("solution", StringUtil.htmlifyText(errata.getSolution()));
    request.setAttribute("notes", StringUtil.htmlifyText(errata.getNotes()));
    request.setAttribute("references", StringUtil.htmlifyText(errata.getRefersTo()));
    request.setAttribute("channels", channels);
    request.setAttribute("fixed", fixed);
    request.setAttribute("cve", cve);
    request.setAttribute("keywords", keywordsDisplay);
    request.setAttribute("ovalFile", ovalFile);
    request.setAttribute("errataFrom", errata.getErrataFrom());

    return getStrutsDelegate().forwardParams(mapping.findForward(RhnHelper.DEFAULT_FORWARD),
            request.getParameterMap());
}

From source file:com.redhat.rhn.frontend.action.errata.EditAction.java

/**
 * This method acts as the default if the dispatch parameter is not in the map
 * It also represents the SetupAction//ww w . ja v a  2 s.c  o m
 * @param mapping ActionMapping
 * @param formIn ActionForm
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @return ActionForward, the forward for the jsp
 */
public ActionForward unspecified(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
        HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);
    Errata errata = requestContext.lookupErratum();

    DynaActionForm form = (DynaActionForm) formIn;

    String keywordDisplay = StringUtil.join(LocalizationService.getInstance().getMessage("list delimiter"),
            IteratorUtils.getIterator(CollectionUtils.collect(errata.getKeywords(), new Transformer() {
                public Object transform(Object o) {
                    return o.toString();
                }
            })));

    //pre-populate form with current values
    form.set("synopsis", errata.getSynopsis());
    form.set("advisoryName", errata.getAdvisoryName());
    form.set("advisoryRelease", errata.getAdvisoryRel().toString());
    form.set("advisoryType", errata.getAdvisoryType());
    form.set("advisoryTypeLabels", ErrataManager.advisoryTypeLabels());
    form.set("product", errata.getProduct());
    form.set("errataFrom", errata.getErrataFrom());
    form.set("topic", errata.getTopic());
    form.set("description", errata.getDescription());
    form.set("solution", errata.getSolution());
    form.set("refersTo", errata.getRefersTo());
    form.set("notes", errata.getNotes());
    form.set("keywords", keywordDisplay);

    return setupPage(request, mapping, errata);
}

From source file:info.magnolia.cms.beans.config.Template.java

private Map nodeDataCollectionToStringMap(Collection collection) {
    Map map = new HashMap();
    Iterator it = IteratorUtils.getIterator(collection);
    while (it.hasNext()) {
        NodeData data = (NodeData) it.next();
        map.put(data.getName(), data.getString());
    }/*  w  w w . j  a v a2s. c om*/
    return map;
}

From source file:com.adobe.acs.commons.synth.children.ChildrenAsPropertyResource.java

/**
 * {@inheritDoc}/*from   ww  w .j  a v a 2s .  c o  m*/
 **/
@Override
public final Iterator<Resource> listChildren() {
    return IteratorUtils.getIterator(this.orderedCache);
}

From source file:com.redhat.rhn.domain.errata.AbstractErrata.java

/**
 * {@inheritDoc}//from   www  .  j  a  va  2s . c  om
 */
public void clearChannels() {
    if (this.getChannels() != null) {
        this.getChannels().clear();
    }
    Iterator<ErrataFile> i = IteratorUtils.getIterator(this.getFiles());
    while (i.hasNext()) {
        PublishedErrataFile pf = (PublishedErrataFile) i.next();
        pf.getChannels().clear();
    }
}

From source file:com.redhat.rhn.domain.errata.ErrataFactory.java

/**
 * Helper method to copy the details for.
 * @param copy The object to copy into./*from  ww  w  .  j  a v  a  2  s.  c  om*/
 * @param original The object to copy from.
 * @param clone  set to true if this is a cloned errata, and thus
 *      things like org or advisory name shouldn't be set
 */
private static void copyDetails(Errata copy, Errata original, boolean clone) {

    //Set the easy things first ;)

    if (!clone) {
        copy.setAdvisory(original.getAdvisory());
        copy.setAdvisoryName(original.getAdvisoryName());
        copy.setOrg(original.getOrg());
    }

    copy.setAdvisoryType(original.getAdvisoryType());
    copy.setProduct(original.getProduct());
    copy.setErrataFrom(original.getErrataFrom());
    copy.setDescription(original.getDescription());
    copy.setSynopsis(original.getSynopsis());
    copy.setTopic(original.getTopic());
    copy.setSolution(original.getSolution());
    copy.setIssueDate(original.getIssueDate());
    copy.setUpdateDate(original.getUpdateDate());
    copy.setNotes(original.getNotes());
    copy.setRefersTo(original.getRefersTo());
    copy.setAdvisoryRel(original.getAdvisoryRel());
    copy.setLocallyModified(original.getLocallyModified());
    copy.setLastModified(original.getLastModified());

    /*
     * Copy the packages
     * packages aren't published or unpublished exactly... that is determined
     * by the status of the errata...
     */
    copy.setPackages(new HashSet(original.getPackages()));

    /*
     * Copy the keywords
     * if we use the string version of addKeyword, we don't have to worry about
     * whether or not the keyword is published.
     */
    Iterator keysItr = IteratorUtils.getIterator(original.getKeywords());
    while (keysItr.hasNext()) {
        Keyword k = (Keyword) keysItr.next();
        copy.addKeyword(k.getKeyword());
    }

    /*
     * Copy the bugs. If copy is published, then the bugs should be published as well.
     * If not, then we want unpublished bugs.
     */
    Iterator bugsItr = IteratorUtils.getIterator(original.getBugs());
    while (bugsItr.hasNext()) {
        Bug bugIn = (Bug) bugsItr.next();
        Bug cloneB;
        if (copy.isPublished()) { //we want published bugs
            cloneB = ErrataManager.createNewPublishedBug(bugIn.getId(), bugIn.getSummary(), bugIn.getUrl());
        } else { //we want unpublished bugs
            cloneB = ErrataManager.createNewUnpublishedBug(bugIn.getId(), bugIn.getSummary(), bugIn.getUrl());
        }
        copy.addBug(cloneB);
    }
}

From source file:com.bst.tags.TableTag.java

/**
 * Reads parameters from the request and initialize all the needed table model attributes.
 * @throws ObjectLookupException for problems in evaluating the expression in the "name" attribute
 * @throws FactoryInstantiationException for problems in instantiating a RequestHelperFactory
 *///from  w  ww .j  a v  a  2s .co  m
private void initParameters() throws ObjectLookupException, FactoryInstantiationException {
    if (rhf == null) {
        // first time initialization
        rhf = this.properties.getRequestHelperFactoryInstance();
    }

    RequestHelper requestHelper = rhf.getRequestHelperInstance(this.pageContext);

    initHref(requestHelper);

    Integer pageNumberParameter = requestHelper
            .getIntParameter(encodeParameter(TableTagParameters.PARAMETER_PAGE));
    this.pageNumber = (pageNumberParameter == null) ? 1 : pageNumberParameter.intValue();

    Integer sortColumnParameter = requestHelper
            .getIntParameter(encodeParameter(TableTagParameters.PARAMETER_SORT));
    int sortColumn = (sortColumnParameter == null) ? this.defaultSortedColumn : sortColumnParameter.intValue();
    this.tableModel.setSortedColumnNumber(sortColumn);

    // default value
    boolean finalSortFull = this.properties.getSortFullList();

    // user value for this single table
    if (this.sortFullTable != null) {
        finalSortFull = this.sortFullTable.booleanValue();
    }

    this.tableModel.setSortFullTable(finalSortFull);

    SortOrderEnum paramOrder = SortOrderEnum
            .fromCode(requestHelper.getIntParameter(encodeParameter(TableTagParameters.PARAMETER_ORDER)));

    // if no order parameter is set use default
    if (paramOrder == null) {
        paramOrder = this.defaultSortOrder;
    }

    boolean order = SortOrderEnum.DESCENDING != paramOrder;
    this.tableModel.setSortOrderAscending(order);

    Integer exportTypeParameter = requestHelper
            .getIntParameter(encodeParameter(TableTagParameters.PARAMETER_EXPORTTYPE));
    this.currentMediaType = MediaTypeEnum.fromCode(exportTypeParameter);
    if (this.currentMediaType == null) {
        this.currentMediaType = MediaTypeEnum.HTML;
    }

    String fullName = getFullObjectName();

    // only evaluate if needed, else use list attribute
    if (fullName != null) {
        this.list = evaluateExpression(fullName);
    } else if (this.list == null) {
        // needed to allow removing the collection of objects if not set directly
        this.list = this.listAttribute;
    }

    // do we really need to skip any row?
    boolean wishOptimizedIteration = (this.pagesize > 0 // we are paging
            || this.offset > 0 // or we are skipping some records using offset
            || this.length > 0 // or we are limiting the records using length
    );

    // can we actually skip any row?
    if (wishOptimizedIteration && (this.list instanceof Collection) // we need to know the size
            && ((sortColumn == -1 // and we are not sorting
                    || !finalSortFull // or we are sorting with the "page" behaviour
            ) && (this.currentMediaType == MediaTypeEnum.HTML // and we are not exporting
                    || !this.properties.getExportFullList()) // or we are exporting a single page
            )) {
        int start = 0;
        int end = 0;
        if (this.offset > 0) {
            start = this.offset;
        }
        if (length > 0) {
            end = start + this.length;
        }

        if (this.pagesize > 0) {
            int fullSize = ((Collection) this.list).size();
            start = (this.pageNumber - 1) * this.pagesize;

            // invalid page requested, go back to page one
            if (start > fullSize) {
                start = 0;
            }

            end = start + this.pagesize;
        }

        // rowNumber starts from 1
        filteredRows = new LongRange(start + 1, end);
    } else {
        filteredRows = new LongRange(1, Long.MAX_VALUE);
    }

    this.tableIterator = IteratorUtils.getIterator(this.list);
}

From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

private IIOImage createImage(InputStream istr, int attempt) throws ImageInterpreterException {
    ImageInputStream iis = null;/*  w w  w  .  ja  v a 2s.  c  o  m*/
    Iterator<ImageReader> ri = null;
    ImageReadParam param = null;
    ImageReader ir = null;
    BufferedImage bi = null;
    // Raster raster = null;
    // int[] bufferTypes = new int[] { DataBuffer.TYPE_BYTE, DataBuffer.TYPE_INT, DataBuffer.TYPE_FLOAT, DataBuffer.TYPE_DOUBLE,
    // DataBuffer.TYPE_SHORT, DataBuffer.TYPE_USHORT, DataBuffer.TYPE_UNDEFINED };

    // Create raster from image reader
    try {
        iis = ImageIO.createImageInputStream(istr);
        ri = ImageIO.getImageReaders(iis);
        if (!ri.hasNext()) {
            // List<ImageReader> list = new ArrayList<ImageReader>();
            // list.add(new JPEGImageReader(new JPEGImageReaderSpi()));
            ri = IteratorUtils.getIterator(new JPEGImageReader(new JPEGImageReaderSpi()));
        }
    } catch (IOException e) {
        throw new ImageInterpreterException("Error reading input stream: " + e.toString());
    }
    while (ri.hasNext()) {
        ir = ri.next();
        try {
            ir.setInput(iis);
            param = ir.getDefaultReadParam();
            bi = ir.read(0, param);
            // raster = ir.readRaster(0, param);
            if (bi != null) {
                break;
            }
        } catch (Error e) {
            LOGGER.error("Failed to render image with ImageReader: " + e.toString());
            continue;
        } catch (Exception e) {
            LOGGER.error("Failed to render image with ImageReader: " + e.toString());
            continue;
        }
    }

    // store metadata
    IIOMetadata md = null;
    try {
        md = getImageMetadata(ir);
    } catch (ImageInterpreterException e) {
        LOGGER.error("Failed to extract metadata from image: " + e.getMessage());
        InputStream patchedInputStream = null;
        if (attempt <= 1) {
            patchedInputStream = attempt == 0 ? new PatchInputStream(istr) : new RemoveHeaderInputStream(istr);
            if (istr != null) {
                try {
                    istr.close();
                } catch (IOException e1) {
                    LOGGER.error("Failed to close input stream");
                }
            }
            return createImage(patchedInputStream, attempt + 1);
        } else {
            LOGGER.error("Unable to read image metadata.");
            md = null;
        }
    } finally {
        if (iis != null) {
            try {
                iis.close();
            } catch (IOException e) {
                LOGGER.error("Failed to close image stream", e);
            }
        }
    }

    // // create buffered image from raster
    // int count = 0;
    // while (count < bufferTypes.length) {
    // int bufferType = bufferTypes[count++];
    // try {
    // SampleModel sm = RasterFactory.createPixelInterleavedSampleModel(bufferType, raster.getWidth(), raster.getHeight(),
    // raster.getNumBands());
    // ColorModel cm = PlanarImage.createColorModel(sm);
    // // cm = bi.getColorModel();
    // ColorSpace sourceColorSpace = cm.getColorSpace();
    // ColorSpace destColorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    // ColorConvertOp op = new ColorConvertOp(sourceColorSpace, destColorSpace, null);
    // // WritableRaster wraster = raster.createInterleavedRaster(bufferTypes[count-1], raster.getWidth(), raster.getHeight(),
    // raster.getNumBands(), null);
    // // WritableRaster wraster = op.createCompatibleDestRaster(raster);
    // WritableRaster wraster = op.filter(raster, null);
    // // Raster raster2 = bi.getRaster();
    // // cm = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, bufferType);
    // // sm = bi.getSampleModel();
    // // cm = bi.getColorModel();
    // // cm = ColorModel.getRGBdefault();
    // bi = new BufferedImage(cm, wraster, false, null);
    // cm.finalize();
    // } catch (Error e) {
    // LOGGER.debug("Failed to render image with BufferType " + bufferType);
    // continue;
    // } catch (Exception e) {
    // LOGGER.debug("Failed to render image with BufferType " + bufferType);
    // continue;
    // }
    // break;
    // }

    if (bi == null) {
        throw new ImageInterpreterException("Failed to extract buffered image from image reader");
    }
    IIOImage image = new IIOImage(bi, null, md);
    return image;
}

From source file:com.bst.tags.TableTag.java

/**
 * If no columns are provided, automatically add them from bean properties. Get the first object in the list and get
 * all the properties (except the "class" property which is automatically skipped). Of course this isn't possible
 * for empty lists.//www.j a v  a 2  s  .  c o  m
 */
private void describeEmptyTable() {
    this.tableIterator = IteratorUtils.getIterator(this.list);

    if (this.tableIterator.hasNext()) {
        Object iteratedObject = this.tableIterator.next();
        Map objectProperties = new HashMap();

        // if it's a String don't add the "Bytes" column
        if (iteratedObject instanceof String) {
            return;
        }
        // if it's a map already use key names for column headers
        if (iteratedObject instanceof Map) {
            objectProperties = (Map) iteratedObject;
        } else {
            try {
                objectProperties = BeanUtils.describe(iteratedObject);
            } catch (Exception e) {
                log.warn("Unable to automatically add columns: " + e.getMessage(), e);
            }
        }

        // iterator on properties names
        Iterator propertiesIterator = objectProperties.keySet().iterator();

        while (propertiesIterator.hasNext()) {
            // get the property name
            String propertyName = (String) propertiesIterator.next();

            // dont't want to add the standard "class" property
            if (!"class".equals(propertyName)) //$NON-NLS-1$
            {
                // creates a new header and add to the table model
                HeaderCell headerCell = new HeaderCell();
                headerCell.setBeanPropertyName(propertyName);

                // handle title i18n
                headerCell.setTitle(this.properties.geResourceProvider().getResource(null, propertyName, this,
                        this.pageContext));

                this.tableModel.addColumnHeader(headerCell);
            }
        }
    }
}