Example usage for java.util HashSet iterator

List of usage examples for java.util HashSet iterator

Introduction

In this page you can find the example usage for java.util HashSet iterator.

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this set.

Usage

From source file:org.deegree.ogcwebservices.wms.RemoteWMService.java

/**
 * reads feature infos from the remote WMS by performing a FeatureInfo request against it. As long the result of a
 * FeatureInfo request is generic (for usual it is som HTML) it isn't easy to combine the result with that of other
 * WMS's//www . ja  v  a 2  s.  c  om
 * 
 * @param request
 *            feature info request
 * @return the response of the GetFeatureInfo request.
 * @throws OGCWebServiceException
 *             if the request could not be excuted correctly.
 */
protected Object handleFeatureInfo(GetFeatureInfo request) throws OGCWebServiceException {

    URL url = null;

    if (request.getVersion().equals("1.0.0")) {
        url = addresses.get(FEATUREINFO_NAME);
    } else {
        url = addresses.get(GETFEATUREINFO_NAME);
    }

    if (url == null) {
        String msg = Messages.getMessage("REMOTEWMS_GFI_NOT_SUPPORTED",
                capabilities.getServiceIdentification().getTitle());
        throw new OGCWebServiceException(msg);
    }

    try {
        GetMap gm = request.getGetMapRequestCopy();
        Envelope requestBBOX = gm.getBoundingBox();
        HashSet<CoordinateSystem> crss = getSupportedCoordinateSystems(gm);
        CoordinateSystem requestCRS = CRSFactory.create(gm.getSrs());
        if (!crss.contains(requestCRS)) {
            CoordinateSystem dataCRS = crss.iterator().next();
            if (dataCRS != null) {
                GeoTransformer transformer = new GeoTransformer(dataCRS);
                GeoTransformer transformBack = new GeoTransformer(requestCRS);
                Envelope dataBBOX = transformer.transform(requestBBOX, requestCRS, true);

                int origWidth = gm.getWidth();
                int origHeight = gm.getHeight();

                double scale = calcScale(origWidth, origHeight, requestBBOX, requestCRS, DEFAULT_PIXEL_SIZE);
                double newScale = calcScale(origWidth, origHeight, dataBBOX, dataCRS, DEFAULT_PIXEL_SIZE);
                double ratio = scale / newScale;

                LOG.logDebug("Requesting transformed bounding box " + dataBBOX + " in srs "
                        + dataCRS.getIdentifier());
                gm.setBoundingBox(dataBBOX);
                gm.setSrs(dataCRS.getIdentifier());
                gm.setWidth((int) (origWidth * ratio));
                gm.setHeight((int) (origHeight * ratio));

                Object o = handleFeatureInfo(request);
                if (o instanceof BufferedImage) {
                    return transformBack.transform((BufferedImage) o, dataBBOX, requestBBOX, origWidth,
                            origHeight, 16, 3, null);
                }

                return o;
            }
        }
    } catch (UnknownCRSException e) {
        LOG.logError(e.getLocalizedMessage(), e);
    } catch (CRSTransformationException e) {
        LOG.logError("An error occurred while transforming bounding boxes (this should not happen)", e);
    }

    String us = constructRequestURL(request.getRequestParameter(),
            validateHTTPGetBaseURL(url.toExternalForm()));

    String result = null;
    try {
        LOG.logDebug("GetFeatureInfo: ", us);
        URL ur = new URL(us);
        // get map from the remote service
        NetWorker nw = new NetWorker(ur);
        byte[] b = nw.getDataAsByteArr(20000);
        String contentType = nw.getContentType();

        // extract content charset if available; otherwise use configured system charset
        String charset = null;
        LOG.logDebug("content type: ", contentType);
        if (contentType != null) {
            String[] tmp = StringTools.toArray(contentType, ";", false);
            if (tmp.length == 2) {
                charset = tmp[1].substring(tmp[1].indexOf('=') + 1, tmp[1].length());
            } else {
                charset = CharsetUtils.getSystemCharset();
            }
        } else {
            charset = CharsetUtils.getSystemCharset();
        }

        // commented out checks, we're trying to fix broken GFI responses here, after all
        // if ( contentType != null && contentType.toLowerCase().startsWith( "application/vnd.ogc.gml" ) ) {
        result = new String(b, charset);
        // } else {
        // throw new OGCWebServiceException( "RemoteWMS:handleFeatureInfo" );
        // }
    } catch (Exception e) {
        LOG.logError(e.getMessage(), e);
        String msg = Messages.getMessage("REMOTEWMS_GFI_GENERAL_ERROR",
                capabilities.getServiceIdentification().getTitle(), us);
        throw new OGCWebServiceException("RemoteWMS:handleFeatureInfo", msg);
    }

    return result;
}

From source file:org.paxle.core.impl.RuntimeSettings.java

/**
 * @see MetaTypeProvider#getObjectClassDefinition(String, String)
 *///from   www .jav  a  2s . c  o  m
public ObjectClassDefinition getObjectClassDefinition(String id, String localeStr) {
    final Locale locale = (localeStr == null) ? Locale.ENGLISH : new Locale(localeStr);
    final ResourceBundle rb = ResourceBundle.getBundle("OSGI-INF/l10n/" + RuntimeSettings.class.getSimpleName(),
            locale);

    final class OptAD implements AttributeDefinition {

        private final OptEntry entry;
        private final String option;

        public OptAD(final OptEntry entry, final String option) {
            this.entry = entry;
            this.option = option;
        }

        public String getID() {
            return entry.getPid();
        }

        public int getCardinality() {
            return 0;
        }

        public String getDescription() {
            return rb.getString(entry.pid + ".desc");
        }

        public String getName() {
            return rb.getString(entry.pid + ".name");
        }

        public String[] getDefaultValue() {
            return new String[] { entry.getValue(option, false).toString() };
        }

        public String[] getOptionLabels() {
            return null;
        }

        public String[] getOptionValues() {
            return null;
        }

        public int getType() {
            return (entry.split) ? STRING : BOOLEAN;
        }

        public String validate(String value) {
            return entry.matches(value);
        }
    }

    @Metadata(@Attribute(id = "org.paxle.core.impl.RuntimeSettings.jvm.other", multiline = true))
    final class OCD implements ObjectClassDefinition {
        public AttributeDefinition[] getAttributeDefinitions(int filter) {
            final List<AttributeDefinition> attribs = new ArrayList<AttributeDefinition>();

            // loading all currently avilable jvm options
            final List<String> runtimeSettings = readSettings();
            final HashSet<OptEntry> optEntries = new HashSet<OptEntry>(OPTIONS);
            String otherValues = "";
            if (runtimeSettings != null) {
                // process all known options and concatenate all unknown ones to one string
                // known options are those, that conform to an OptEntry saved in the OPTIONS-set
                final StringBuilder sb = new StringBuilder();
                outer: for (final String opt : runtimeSettings) {
                    final Iterator<OptEntry> it = optEntries.iterator();
                    while (it.hasNext()) {
                        final OptEntry e = it.next();
                        if (opt.startsWith(e.fixOpt)) {
                            attribs.add(new OptAD(e, opt));
                            it.remove();
                            continue outer;
                        }
                    }
                    if (sb.length() > 0)
                        sb.append(OPT_OTHER_SPLIT);
                    sb.append(opt);
                }
                otherValues = sb.toString();
            }
            for (final OptEntry e : optEntries)
                attribs.add(new OptAD(e, null));

            // put the remaining options into a multi-line AD allowing arbitrary strings
            attribs.add(new OptAD(CM_OTHER_ENTRY, otherValues));

            return attribs.toArray(new AttributeDefinition[attribs.size()]);
        }

        public String getDescription() {
            try {
                return MessageFormat.format(rb.getString("runtimeSettings.desc"),
                        iniFile.getCanonicalFile().toString());
            } catch (IOException e) {
                logger.error(e);
                return rb.getString("runtimeSettings.desc");
            }
        }

        public String getID() {
            return PID;
        }

        public InputStream getIcon(int size) throws IOException {
            return null;
        }

        public String getName() {
            return rb.getString("runtimeSettings.name");
        }
    }

    return new OCD();
}

From source file:com.fstx.stdlib2.author.AuthorizationBeanBuilder.java

public AuthorizationBean buildAuthorizationBean(String user) throws DaoException {

    HashSet rightsSet = new HashSet();
    HashSet rightsStringSet = new HashSet();
    GroupRightDao grDao = GroupRightDao.factory.build();
    //Get user groups
    UserGroupDao dao = UserGroupDao.factory.build();

    List l = dao.searchUserGroups(UserGroupDao.SELECT_BY_USER, user);

    //for each group
    Iterator i = l.iterator();//from   w  w w. jav  a  2 s . co  m
    UserGroup g3 = null;
    Collection rightsList = null;
    while (i.hasNext()) {
        g3 = (UserGroup) i.next();
        //get list of rights for group
        rightsList = grDao.find(g3);

        //         add groups rights to the users list
        rightsSet.addAll(rightsList);

        //log.info("\n\nI just queried this group for rights: "+
        // g3.getGroupname());
    }
    //We only want to deal with strings, not GroupRights objs. This makes
    // the
    // seach of the hash eazily.
    //Convert GroupRights to Strings.
    Iterator i2 = rightsSet.iterator();
    GroupRight grTemp = null;
    while (i2.hasNext()) {
        grTemp = (GroupRight) i2.next();
        //log.info("\n\nAdding the right" + grTemp.getRightCode());
        rightsStringSet.add(grTemp.getRightCode());
    }

    //      add composite to the bean.
    AuthorizationBean ab = new AuthorizationBean(rightsStringSet);

    //      Return bean.
    return ab;
}

From source file:org.apache.storm.utils.Utils.java

private static InputStream getConfigFileInputStream(String configFilePath) throws IOException {
    if (null == configFilePath) {
        throw new IOException("Could not find config file, name not specified");
    }/*w  ww  . ja va  2s .  co  m*/

    HashSet<URL> resources = new HashSet<URL>(findResources(configFilePath));
    if (resources.isEmpty()) {
        File configFile = new File(configFilePath);
        if (configFile.exists()) {
            return new FileInputStream(configFile);
        }
    } else if (resources.size() > 1) {
        throw new IOException("Found multiple " + configFilePath
                + " resources. You're probably bundling the Storm jars with your topology jar. " + resources);
    } else {
        LOG.debug("Using " + configFilePath + " from resources");
        URL resource = resources.iterator().next();
        return resource.openStream();
    }
    return null;
}

From source file:com.fstx.stdlib.author.old.AuthorizationBeanBuilder.java

public AuthorizationBean buildAuthorizationBean(String user) throws DAOException {

    HashSet rightsSet = new HashSet();
    HashSet rightsStringSet = new HashSet();
    GroupRightsDAO grDAO = GroupRightsDAO.factory.build();
    //Get user groups
    UserGroupDAO dao = UserGroupDAO.factory.build();

    List l = dao.find(UserGroupDAO.SELECT_BY_USER, user);

    //for each group
    Iterator i = l.iterator();//from  w w  w.j a v  a2  s  .  c  o m
    UserGroup g3 = null;
    List rightsList = null;
    while (i.hasNext()) {
        g3 = (UserGroup) i.next();
        //get list of rights for group
        rightsList = grDAO.find(GroupRightsDAO.SELECT_BY_GROUP, g3.getName());

        //         add groups rights to the users list
        rightsSet.addAll(rightsList);

        //log.info("\n\nI just queried this group for rights: "+
        // g3.getGroupname());
    }
    //We only want to deal with strings, not GroupRights objs. This makes
    // the
    // seach of the hash eazily.
    //Convert GroupRights to Strings.
    Iterator i2 = rightsSet.iterator();
    GroupRights grTemp = null;
    while (i2.hasNext()) {
        grTemp = (GroupRights) i2.next();
        //log.info("\n\nAdding the right" + grTemp.getRightCode());
        rightsStringSet.add(grTemp.getRightCode());
    }

    //      add composite to the bean.
    AuthorizationBean ab = new AuthorizationBean(rightsStringSet);

    //      Return bean.
    return ab;
}

From source file:edu.harvard.iq.dvn.core.index.IndexServiceBean.java

public void indexBatch() {
    long ioProblemCount = 0;
    boolean ioProblem = false;
    HashSet s = getUnindexedStudies();
    for (Iterator it = s.iterator(); it.hasNext();) {
        Study study = (Study) it.next();
        try {//from ww w  . j  a  v  a2s  .  c om
            addDocument(study.getId().longValue());
        } catch (IOException ex) {
            Logger.getLogger(IndexServiceBean.class.getName()).log(Level.SEVERE, null, ex);
            ioProblemCount++;
            ioProblem = true;
        }
    }
    handleIOProblems(ioProblem, ioProblemCount);
}

From source file:fr.aliasource.webmail.indexing.SearchAction.java

public void execute(IProxy p, IParameterSource req, IResponder responder) {
    long time = System.currentTimeMillis();
    String query = req.getParameter("query");
    int page = Integer.parseInt(req.getParameter("page"));
    int pageLength = Integer.parseInt(req.getParameter("pageLength"));

    SearchDirector sd = p.getAccount().getSearchDirector();

    int startIdx = (page - 1) * pageLength;

    List<Hit> results = sd.findByType(p.getAccount().getUserId(), query);
    if (logger.isInfoEnabled()) {
        time = System.currentTimeMillis() - time;
        logger.info("[" + p.getAccount().getUserId() + "] " + query + " p: " + page + " l: " + pageLength
                + " => " + results.size() + " result(s) in " + time + "ms.");
    }/*from  w  w w  .j a va  2s  . c  o m*/
    int endIdx = Math.min(results.size(), startIdx + pageLength);
    int resultsSize = results.size();
    VersionnedList<ConversationReference> resultPage = new VersionnedList<ConversationReference>();
    if (startIdx < results.size()) {
        HashSet<String> notFoundInCache = new HashSet<String>();
        ConversationCache cc = p.getAccount().getCache().getConversationCache();
        for (int i = startIdx; i < endIdx; i++) {
            Map<String, Object> payload = results.get(i).getPayload();
            String convId = payload.get("id").toString();
            ConversationReference cr = null;

            if (convId.contains("/")) {
                cr = cc.find(convId);
            } else {
                // chat ?
                cr = loadChat(payload);
            }

            if (cr != null) {
                resultPage.add(cr);
            } else {
                notFoundInCache.add(convId);
            }
        }
        if (notFoundInCache.size() > 0) {
            StringBuilder sb = new StringBuilder();
            sb.append("Messages with ids[");
            for (Iterator<String> it = notFoundInCache.iterator(); it.hasNext();) {
                sb.append(it.next());
                if (it.hasNext()) {
                    sb.append(", ");
                }
            }
            sb.append("] found by solr are not in cache");
            logger.warn(sb.toString());
            resultsSize -= notFoundInCache.size();
        }
    }
    ConversationReferenceList ret = new ConversationReferenceList(resultPage, resultsSize);
    responder.sendConversationsPage(ret);
}

From source file:com.gfactor.web.wicket.loader.OsgiClassResolver.java

/**
 * {@inheritDoc}/*from  w ww .j a  v  a 2  s.c o  m*/
 * 
 * @see org.apache.wicket.application.IClassResolver#getResources(java.lang.String)
 */
public Iterator<URL> getResources(String name) {
    logger.info("getResources = " + name);
    HashSet<URL> loadedFiles = new HashSet<URL>();
    try {
        // Try the classloader for the wicket jar/bundle
        Enumeration<URL> resources = Application.class.getClassLoader().getResources(name);
        loadResources(resources, loadedFiles);

        logger.info("resources 1 = " + resources);
        logger.info("loadedFiles = " + loadedFiles);

        // Try the classloader for the user's application jar/bundle
        resources = Application.get().getClass().getClassLoader().getResources(name);
        logger.info("resources 2 = " + resources);

        loadResources(resources, loadedFiles);

        // Try the context class loader
        resources = Thread.currentThread().getContextClassLoader().getResources(name);
        logger.info("resources 3 = " + resources);
        loadResources(resources, loadedFiles);
    } catch (IOException e) {
        throw new WicketRuntimeException(e);
    }

    return loadedFiles.iterator();
}

From source file:com.metaparadigm.jsonrpc.JSONRPCBridge.java

private Object resolveLocalArg(Object context[], HashSet resolverSet) throws UnmarshallException {

    Iterator i = resolverSet.iterator();
    while (i.hasNext()) {
        LocalArgResolverData resolverData = (LocalArgResolverData) i.next();
        for (int j = 0; j < context.length; j++) {
            if (resolverData.understands(context[j])) {
                try {
                    return resolverData.argResolver.resolveArg(context[j]);
                } catch (LocalArgResolveException e) {
                    throw new UnmarshallException("error resolving local argument: " + e);
                }//from ww  w . j  av a 2  s  .  com
            }
        }
    }
    throw new UnmarshallException("couldn't find local arg resolver");
}

From source file:org.sakaiproject.tool.assessment.ui.listener.evaluation.TotalScoreListener.java

/**
 * This will populate the TotalScoresBean with the data associated with the
 * particular versioned assessment based on the publishedId.
 *
 * @todo Some of this code will change when we move this to Hibernate persistence.
 * @param publishedId String//  w w w  .j  a  va2  s. c o m
 * @param bean TotalScoresBean
 * @return boolean
 */
public boolean totalScores(PublishedAssessmentFacade pubAssessment, TotalScoresBean bean,
        boolean isValueChange) {
    log.debug("TotalScoreListener: totalScores() starts");
    if (ContextUtil.lookupParam("sortBy") != null && !ContextUtil.lookupParam("sortBy").trim().equals("")) {
        bean.setSortType(ContextUtil.lookupParam("sortBy"));
        log.debug("TotalScoreListener: totalScores() :: sortBy = " + ContextUtil.lookupParam("sortBy"));
    }
    boolean sortAscending = true;
    if (ContextUtil.lookupParam("sortAscending") != null
            && !ContextUtil.lookupParam("sortAscending").trim().equals("")) {
        sortAscending = Boolean.valueOf(ContextUtil.lookupParam("sortAscending")).booleanValue();
        bean.setSortAscending(sortAscending);
        log.debug("TotalScoreListener: totalScores() :: sortAscending = " + sortAscending);
    }

    log.debug("totalScores()");
    try {
        // when will this happen? 
        boolean firstTime = true;
        PublishedAssessmentData p = (PublishedAssessmentData) pubAssessment.getData();

        // check if this is the first visit to total Scores page, if not, then firstTime is set to false, 
        // for example, if you click on 'scores' from authorIndex page, firstTime is true.  then you click
        // 'question scores' page. then if you click on 'totalscores' page again from 'question scores' 
        // page, this firstTime = false;

        if (bean.getPublishedId() != null
                && bean.getPublishedId().equals(p.getPublishedAssessmentId().toString())) {
            firstTime = false;
        }

        // this line below also call bean.setPublishedId() so that the previous if.. will return true for 
        // any subsequent click on 'totalscores' link.
        if (!isValueChange) {
            bean.setPublishedAssessment(p);
        }

        PublishedAccessControl ac = (PublishedAccessControl) p.getAssessmentAccessControl();
        if (ac.getTimeLimit() != null && ac.getTimeLimit().equals(Integer.valueOf(0))) {
            bean.setIsTimedAssessment(false);
        } else {
            bean.setIsTimedAssessment(true);
        }

        if (ac.getLateHandling() != null
                && ac.getLateHandling().equals(AssessmentAccessControlIfc.ACCEPT_LATE_SUBMISSION)) {
            bean.setAcceptLateSubmission(true);
        } else {
            bean.setAcceptLateSubmission(false);
        }

        //#1 - prepareAgentResultList prepare a list of AssesmentGradingData and set it as
        // bean.agents later in step #4
        // scores is a filtered list contains last AssessmentGradingData submitted for grade
        ArrayList scores = new ArrayList();
        ArrayList students_not_submitted = new ArrayList();

        Map useridMap = bean.getUserIdMap(TotalScoresBean.CALLED_FROM_TOTAL_SCORE_LISTENER);
        ArrayList agents = new ArrayList();
        prepareAgentResultList(bean, p, scores, students_not_submitted, useridMap);
        if ((scores.size() == 0) && (students_not_submitted.size() == 0))
        // no submission and no not_submitted students, return
        {
            bean.setAgents(agents);
            bean.setAllAgents(agents);
            return true;
        }

        // pass #1, proceed forward to prepare properties that set the link "Statistics"
        //#2 - the following methods are used to determine if the link "Statistics"
        // and "Questions" should be displayed in totalScore.jsp. Once set, they 
        // need not be executed everytime
        if (firstTime) {
            // if section set is null, initialize it - daisyf , 01/31/05
            HashSet sectionSet = PersistenceService.getInstance().getPublishedAssessmentFacadeQueries()
                    .getSectionSetForAssessment(p);
            p.setSectionSet(sectionSet);
            Iterator sectionIter = sectionSet.iterator();
            boolean isAutoScored = true;
            boolean hasFileUpload = false;
            while (sectionIter.hasNext()) {
                if (!isAutoScored) {
                    break;
                }
                if (hasFileUpload) {
                    break;
                }
                PublishedSectionData section = (PublishedSectionData) sectionIter.next();
                Set itemSet = section.getItemSet();
                Iterator itemIter = itemSet.iterator();
                while (itemIter.hasNext()) {
                    PublishedItemData item = (PublishedItemData) itemIter.next();
                    Long typeId = item.getTypeId();
                    if (typeId.equals(TypeIfc.ESSAY_QUESTION) || typeId.equals(TypeIfc.AUDIO_RECORDING)) {
                        bean.setIsAutoScored(false);
                        isAutoScored = false;
                        break;
                    }

                    if (typeId.equals(TypeIfc.FILE_UPLOAD)) {
                        bean.setIsAutoScored(false);
                        isAutoScored = false;
                        bean.setHasFileUpload(true);
                        hasFileUpload = true;
                        break;
                    }
                }
            }
            if (isAutoScored) {
                bean.setIsAutoScored(true);
            }
            if (!hasFileUpload) {
                bean.setHasFileUpload(false);
            }

            bean.setFirstItem(getFirstItem(p));
            log.debug("totallistener: firstItem = " + bean.getFirstItem());
            bean.setHasRandomDrawPart(hasRandomPart(p));
        }
        if (firstTime || (isValueChange)) {
            bean.setAnsweredItems(getAnsweredItems(scores, p)); // Save for QuestionScores
        }
        log.debug("**firstTime=" + firstTime);
        log.debug("**isValueChange=" + isValueChange);

        //#3 - Collect a list of all the users in the scores list
        ArrayList agentUserIds = getAgentIds(useridMap);
        AgentHelper helper = IntegrationContextFactory.getInstance().getAgentHelper();
        Map userRoles = helper.getUserRolesFromContextRealm(agentUserIds);
        //#4 - prepare agentResult list
        prepareAgentResult(p, scores.iterator(), agents, userRoles);
        prepareNotSubmittedAgentResult(students_not_submitted.iterator(), agents, userRoles);
        bean.setAgents(agents);
        bean.setAllAgents(agents);
        bean.setTotalPeople(Integer.toString(bean.getAgents().size()));

        //#5 - set role & sort selection
        setRoleAndSortSelection(bean, agents, sortAscending);

        //#6 - this is for audio questions?
        //setRecordingData(bean);

    }

    catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    return true;
}