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:dao.DirectoryAuthorDaoDb.java

/**
*  This methods lists all users /*from   ww w.j ava 2s .  c  o  m*/
*  @param directoryId  - directoryId
*  @param userId - userId 
*  @param userLogin - userLogin
*  @param accessFlag the acess flag to read                                                                               slave(0) or master (1) 
*  @return List - list of all users alphabets (first,last,login) 
*  @throws BaseDaoException
*/
public List getAllUsersAlphabet(String directoryId, String userId, String userLogin, int accessFlag)
        throws BaseDaoException {

    if (RegexStrUtil.isNull(userLogin) || RegexStrUtil.isNull(userId) || RegexStrUtil.isNull(directoryId)) {
        throw new BaseDaoException("params are null");
    }

    /**
          *  check user permissions
          */
    if (!diaryAdmin.isDiaryAdmin(userLogin) && !isAuthor(directoryId, userId)) {
        throw new BaseDaoException("User does not have permission to list users for this directory, "
                + directoryId + " userId = " + userId);
    }

    List result = null;
    Fqn fqn = cacheUtil.fqn(DbConstants.ALPHABET_ALL_USERS);
    if (treeCache.exists(fqn, DbConstants.ALPHABET_ALL_USERS)) {
        // return (List)treeCache.get(fqn, DbConstants.ALPHABET_ALL_USERS);
        result = (List) treeCache.get(fqn, DbConstants.ALPHABET_ALL_USERS);
    } else {
        String queryName = null;
        if (accessFlag == 1) {
            queryName = scalabilityManager.getWriteZeroScalability("showallusersalphabetquery");
        } else {
            queryName = scalabilityManager.getReadZeroScalability("showallusersalphabetquery");
        }
        showAllUsersAlphabetQuery = getQueryMapper().getQuery(queryName);
        try {
            result = showAllUsersAlphabetQuery.execute();
        } catch (Exception e) {
            throw new BaseDaoException("error in getAllUsersAlphabet() " + showAllUsersAlphabetQuery.getSql(),
                    e);
        }
    }

    if (result == null) {
        return null;
    } else {
        HashSet authorSet = listAuthorsOfDirectory(directoryId, userId, userLogin, accessFlag);
        HashSet dirauthors = new HashSet();
        if (authorSet != null && authorSet.size() > 0) {
            Iterator it = authorSet.iterator();
            while (it.hasNext()) {
                Directory author = (Directory) it.next();
                if (author != null) {
                    dirauthors.add(author.getValue(DbConstants.LOGIN));
                }
            }

            if (result != null && result.size() > 0 && dirauthors.size() > 0) {
                List newUsers = new ArrayList();
                for (int i = 0; i < result.size(); i++) {
                    Hdlogin hdlogin = (Hdlogin) result.get(i);
                    if (hdlogin != null) {
                        if (!RegexStrUtil.isNull(hdlogin.getValue(DbConstants.LOGIN))) {
                            if (!dirauthors.contains(hdlogin.getValue(DbConstants.LOGIN))) {
                                newUsers.add(result.get(i));
                                // hdlogin.setValue(DbConstants.AUTHOR, "0");
                            }
                        }
                    }
                }
                treeCache.put(fqn, DbConstants.ALPHABET_ALL_USERS, newUsers);
                return newUsers;
            }
        }
    }
    return null;
}

From source file:org.itracker.services.implementations.UserServiceImpl.java

@Override
public List<User> getPossibleOwners(Issue issue, Integer projectId, Integer userId) {
    HashSet<User> users = new HashSet<User>();

    List<User> editUsers = getUsersWithProjectPermission(projectId, UserUtilities.PERMISSION_EDIT, true);
    for (User editUser : editUsers) {
        users.add(editUser);/*from  w w  w . j  av  a2  s.  c  o m*/
    }
    List<User> otherUsers = getUsersWithProjectPermission(projectId,
            new int[] { UserUtilities.PERMISSION_EDIT_USERS, UserUtilities.PERMISSION_ASSIGNABLE }, true, true);
    for (User otherUser : otherUsers) {
        users.add(otherUser);
    }

    if (issue != null) {
        // Now add in the creator if the have edit own issues, and always
        // the owner
        User creator = issue.getCreator();

        if (UserUtilities.hasPermission(getUsersMapOfProjectIdsAndSetOfPermissionTypes(creator, 0), projectId,
                PermissionType.ISSUE_EDIT_USERS)) {
            users.add(creator);
        }
        if (issue.getOwner() != null) {
            User owner = issue.getOwner();
            users.add(owner);
        }
    } else if (userId != null) {
        // New issue, so add in the creator if needed
        User creator = getUser(userId);
        if (UserUtilities.hasPermission(getUsersMapOfProjectIdsAndSetOfPermissionTypes(creator, 0), projectId,
                PermissionType.ISSUE_EDIT_USERS)) {
            users.add(creator);
        }
    }

    int i = 0;
    List<User> userList = new ArrayList<User>();
    for (Iterator<User> iter = users.iterator(); iter.hasNext(); i++) {
        userList.add((User) iter.next());
    }
    return userList;
}

From source file:org.mskcc.cbio.portal.servlet.QueryBuilder.java

/**
 * process a good request/*from w  w w  .j  ava2 s  . c o  m*/
 * 
*/
private void processData(String cancerStudyStableId, String geneList, HashSet<String> geneticProfileIdSet,
        ArrayList<GeneticProfile> profileList, String sampleSetId, String sampleIds,
        ArrayList<SampleList> sampleSetList, String patientCaseSelect, ServletContext servletContext,
        HttpServletRequest request, HttpServletResponse response, XDebug xdebug)
        throws IOException, ServletException, DaoException {

    request.setAttribute(PATIENT_CASE_SELECT, patientCaseSelect);

    HashSet<String> setOfSampleIds = null;

    String sampleIdsKey = null;

    // user-specified patients, but patient_ids parameter is missing,
    // so try to retrieve sample_ids by using sample_ids_key parameter.
    // this is required for survival plot requests  
    if (sampleSetId.equals("-1") && sampleIds == null) {
        sampleIdsKey = request.getParameter(CASE_IDS_KEY);

        if (sampleIdsKey != null) {
            sampleIds = SampleSetUtil.getSampleIds(sampleIdsKey);
        }
    }

    if (!sampleSetId.equals("-1")) {
        for (SampleList sampleSet : sampleSetList) {
            if (sampleSet.getStableId().equals(sampleSetId)) {
                sampleIds = sampleSet.getSampleListAsString();
                setOfSampleIds = new HashSet<String>(sampleSet.getSampleList());
                break;
            }
        }
    }
    //if user specifies patients, add these to hashset, and send to GetMutationData
    else if (sampleIds != null) {
        String[] sampleIdSplit = sampleIds.split("\\s+");
        setOfSampleIds = new HashSet<String>();

        for (String sampleID : sampleIdSplit) {
            if (null != sampleID) {
                setOfSampleIds.add(sampleID);
            }
        }

        sampleIds = sampleIds.replaceAll("\\s+", " ");
    }

    if (setOfSampleIds == null || setOfSampleIds.isEmpty()) {
        redirectStudyUnavailable(request, response);
    }

    request.setAttribute(SET_OF_CASE_IDS, sampleIds);

    // Map user selected samples Ids to patient Ids
    HashMap<String, String> patientSampleIdMap = new HashMap<String, String>();
    CancerStudy selectedCancerStudy = DaoCancerStudy.getCancerStudyByStableId(cancerStudyStableId);
    int cancerStudyInternalId = selectedCancerStudy.getInternalId();
    Iterator<String> itr = setOfSampleIds.iterator();
    while (itr.hasNext()) {
        String sampleId = itr.next();
        ArrayList<String> sampleIdList = new ArrayList<String>();
        sampleIdList.add(sampleId);

        Sample sample = DaoSample.getSampleByCancerStudyAndSampleId(cancerStudyInternalId, sampleId);
        Patient patient = DaoPatient.getPatientById(sample.getInternalPatientId());
        patientSampleIdMap.put(sampleId, patient.getStableId());
    }
    request.setAttribute(SELECTED_PATIENT_SAMPLE_ID_MAP, patientSampleIdMap);

    if (sampleIdsKey == null) {
        sampleIdsKey = SampleSetUtil.shortenSampleIds(sampleIds);
    }

    // retrieve information about the cancer types
    Map<String, List<String>> cancerTypeInfo = DaoClinicalData.getCancerTypeInfo(cancerStudyInternalId);
    request.setAttribute(CANCER_TYPES_MAP, cancerTypeInfo);

    // this will create a key even if the patient set is a predefined set,
    // because it is required to build a patient id string in any case
    request.setAttribute(CASE_IDS_KEY, sampleIdsKey);

    Iterator<String> profileIterator = geneticProfileIdSet.iterator();
    ArrayList<DownloadLink> downloadLinkSet = new ArrayList<>();
    while (profileIterator.hasNext()) {
        String profileId = profileIterator.next();
        GeneticProfile profile = GeneticProfileUtil.getProfile(profileId, profileList);
        if (null == profile) {
            continue;
        }
        GetProfileData remoteCall = new GetProfileData(profile,
                new ArrayList<>(Arrays.asList(geneList.split(" "))), StringUtils.join(setOfSampleIds, " "));
        DownloadLink downloadLink = new DownloadLink(profile,
                new ArrayList<>(Arrays.asList(geneList.split(" "))), sampleIds, remoteCall.getRawContent());
        downloadLinkSet.add(downloadLink);
    }

    request.getSession().setAttribute(DOWNLOAD_LINKS, downloadLinkSet);
    String tabIndex = request.getParameter(QueryBuilder.TAB_INDEX);
    if (tabIndex != null && tabIndex.equals(QueryBuilder.TAB_VISUALIZE)) {
        double zScoreThreshold = ZScoreUtil.getZScore(geneticProfileIdSet, profileList, request);
        double rppaScoreThreshold = ZScoreUtil.getRPPAScore(request);
        request.setAttribute(Z_SCORE_THRESHOLD, zScoreThreshold);
        request.setAttribute(RPPA_SCORE_THRESHOLD, rppaScoreThreshold);

        // Store download links in session (for possible future retrieval).
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/visualize.jsp");
        dispatcher.forward(request, response);
    } else if (tabIndex != null && tabIndex.equals(QueryBuilder.TAB_DOWNLOAD)) {
        ShowData.showDataAtSpecifiedIndex(servletContext, request, response, 0, xdebug);
    }
}

From source file:org.oscelot.blackboard.lti.Utils.java

public static String getIRoles(B2Context b2Context, List<PortalRole> iRoles, boolean isAdmin) {

    HashSet<String> roles = new HashSet<String>();
    for (Iterator<PortalRole> iter = iRoles.iterator(); iter.hasNext();) {
        PortalRole role = iter.next();//from www  .  ja  v a 2  s . co m
        String iRoleSetting = b2Context.getSetting(false, true,
                Constants.TOOL_PARAMETER_PREFIX + "." + Constants.TOOL_IROLE + "." + role.getRoleID(),
                b2Context.getSetting(Constants.TOOL_PARAMETER_PREFIX + "." + Constants.DEFAULT_TOOL_ID + "."
                        + Constants.TOOL_IROLE + "." + role.getRoleID(), ""));
        if (iRoleSetting.contains("F")) {
            roles.add(Constants.IROLE_FACULTY);
        }
        if (iRoleSetting.contains("S")) {
            roles.add(Constants.IROLE_STAFF);
        }
        if (iRoleSetting.contains("L")) {
            roles.add(Constants.IROLE_STUDENT);
        }
        if (iRoleSetting.contains("P")) {
            roles.add(Constants.IROLE_PROSPECTIVE_STUDENT);
        }
        if (iRoleSetting.contains("A")) {
            roles.add(Constants.IROLE_ALUMNI);
        }
        if (iRoleSetting.contains("O")) {
            roles.add(Constants.IROLE_OBSERVER);
        }
        if (iRoleSetting.contains("G")) {
            roles.add(Constants.IROLE_GUEST);
        }
        if (iRoleSetting.contains("Z")) {
            roles.add(Constants.IROLE_OTHER);
        }
    }

    StringBuilder sRoles = new StringBuilder();
    for (Iterator<String> iter = roles.iterator(); iter.hasNext();) {
        String role = iter.next();
        sRoles.append(role).append(",");
    }
    if (isAdmin) {
        sRoles.append(Constants.IROLE_ADMINISTRATOR).append(',');
    }
    String rolesParameter = sRoles.toString();
    if (rolesParameter.endsWith(",")) {
        rolesParameter = rolesParameter.substring(0, rolesParameter.length() - 1);
    }

    return rolesParameter;

}

From source file:axiom.objectmodel.db.NodeManager.java

public void evictKeys(HashSet<Key> keyset) {
    synchronized (cache) {
        Iterator<Key> keys = keyset.iterator();
        while (keys.hasNext()) {
            this.evictNodeByKey(keys.next());
        }/*from  w  w w  . j  av  a 2s. co m*/
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.LifeCycleManagerImpl.java

/**
 * Process a RegistryObject.//from   w  ww  . j  a  v  a 2  s . co m
 * 
 * Potential cases: 1) Composed object is submitted as a composed object 2)
 * Composed object is submitted as a top level object (e.g. create
 * Classification, call setClassifiedObject on it and save it.)
 * 
 */
@SuppressWarnings("unchecked")
private void processRegistryObject(ClientRequestContext context, RegistryObjectImpl ro, String pad)
        throws JAXRException {
    // log.debug(pad + "processRegistryObject entered: ro = " + ro);
    log.debug(pad + "processRegistryObject: entered candidateSubmitObjects.add on ro  = " + ro);
    context.getCandidateSubmitObjects().add(ro);

    // Get and process composed objects implicitly for RegistryObjects being
    // saved
    @SuppressWarnings("rawtypes")
    HashSet _composedObjects = ro.getComposedObjects();
    context.getComposedObjects().addAll(_composedObjects);

    for (Iterator<?> composedIter = _composedObjects.iterator(); composedIter.hasNext();) {
        Object obj = composedIter.next();

        if (obj instanceof RegistryObjectImpl) {
            RegistryObjectImpl composedObj = (RegistryObjectImpl) obj;
            if (composedObj.isNew() || composedObj.isModified()) {
                // log.debug(pad + "processRegistryObject: recursing on composedObj = " + composedObj);
                processObject(context, composedObj, pad.concat(" "));
            }
        } else if (obj instanceof RegistryObjectRef) {
            // This could be the case where a remote RegistryObjectRef is
            // being saved.
            // Not sure yet that we need to do anything as
            // FederationSystemTest seems to work as is.
            @SuppressWarnings("unused")
            int i = 0;// ??
        }
    }

    // Get and process objects referenced by RegistryObject
    HashSet<?> refObjects = ro.getRegistryObjectRefs();

    if (refObjects != null) {
        for (Iterator<?> refIter = refObjects.iterator(); refIter.hasNext();) {
            Object refObj = refIter.next();

            // log.debug(pad +
            // "processRegistryObject: recursing on refObj = " + refObj);
            processObject(context, refObj, pad.concat(" "));
        }
    }
}

From source file:com.modeln.build.ctrl.charts.CMnBuildListChart.java

/**
 * Generate a stacked bar graph representing test execution time for each 
 * product area. /*from   w w w .  ja  va2  s  .  c  o m*/
 *
 * @param   builds   List of builds
 * @param   suites   List of test suites
 * @param   areas    List of product areas 
 * 
 * @return  Stacked bar chart representing test execution times across all builds 
 */
public static final JFreeChart getAreaTestTimeChart(Vector<CMnDbBuildData> builds,
        Vector<CMnDbTestSuite> suites, Vector<CMnDbFeatureOwnerData> areas) {
    JFreeChart chart = null;

    // Collect the total times for each build, organized by area
    // This hashtable maps a build to the area/time information for that build
    Hashtable<Integer, Hashtable> buildTotals = new Hashtable<Integer, Hashtable>();

    // Generate placeholders for each build so the chart maintains a 
    // format consistent with the other charts that display build information
    HashSet areaNames = new HashSet();
    if (builds != null) {
        Enumeration buildList = builds.elements();
        while (buildList.hasMoreElements()) {
            CMnDbBuildData build = (CMnDbBuildData) buildList.nextElement();
            // Create the empty area list
            buildTotals.put(new Integer(build.getId()), new Hashtable<String, Long>());
        }
    }

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    if ((suites != null) && (suites.size() > 0)) {

        // Collect build test numbers for each of the builds in the list 
        Enumeration suiteList = suites.elements();
        while (suiteList.hasMoreElements()) {

            // Process the test summary for the current build
            CMnDbTestSuite suite = (CMnDbTestSuite) suiteList.nextElement();
            Integer buildId = new Integer(suite.getParentId());
            Long elapsedTime = new Long(suite.getElapsedTime());

            // Parse the build information so we can track the time by build
            Hashtable<String, Long> areaTime = null;
            if (buildTotals.containsKey(buildId)) {
                areaTime = (Hashtable) buildTotals.get(buildId);
            } else {
                areaTime = new Hashtable<String, Long>();
                buildTotals.put(buildId, areaTime);
            }

            // Iterate through each product area to determine who owns this suite
            CMnDbFeatureOwnerData area = null;
            Iterator iter = areas.iterator();
            while (iter.hasNext()) {
                CMnDbFeatureOwnerData currentArea = (CMnDbFeatureOwnerData) iter.next();
                if (currentArea.hasFeature(suite.getGroupName())) {
                    area = currentArea;
                }
            }

            // Add the elapsed time for the current suite to the area total
            Long totalValue = null;
            String areaName = area.getDisplayName();
            areaNames.add(areaName);
            if (areaTime.containsKey(areaName)) {
                Long oldTotal = (Long) areaTime.get(areaName);
                totalValue = oldTotal + elapsedTime;
            } else {
                totalValue = elapsedTime;
            }
            areaTime.put(areaName, totalValue);

        } // while list has elements

        // Populate the data set with the area times for each build
        Collections.sort(builds, new CMnBuildIdComparator());
        Iterator buildIter = builds.iterator();
        while (buildIter.hasNext()) {
            CMnDbBuildData build = (CMnDbBuildData) buildIter.next();
            Integer buildId = new Integer(build.getId());
            Hashtable areaTime = (Hashtable) buildTotals.get(buildId);

            Iterator areaKeys = areaNames.iterator();
            while (areaKeys.hasNext()) {
                String area = (String) areaKeys.next();
                Long time = (Long) areaTime.get(area);
                if (time != null) {
                    // Convert the time from milliseconds to minutes
                    time = time / (1000 * 60);
                } else {
                    time = new Long(0);
                }
                dataset.addValue(time, area, buildId);
            }
        }

    } // if list has elements

    // API: ChartFactory.createStackedBarChart(title, domainAxisLabel, rangeAxisLabel, dataset, orientation, legend, tooltips, urls)
    chart = ChartFactory.createStackedBarChart("Automated Tests by Area", "Builds", "Execution Time (min)",
            dataset, PlotOrientation.VERTICAL, true, true, false);

    // get a reference to the plot for further customization...
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    chartFormatter.formatAreaChart(plot, dataset);

    return chart;
}

From source file:dao.PblogTopicDaoDb.java

/**
 *  Get blogs within a specific month// w ww.  j av  a  2  s.c  o m
 *  @param pBlogId - the personal blogid
 *  @param accessFlag - the access Flag, which indicates the datasource from which topics are retrieved.
 *             READ_FROM_MASTER (1), READ_FROM_SLAVE(0)
 *  @param getLoginInfo - get the blogger's information
 *  @param entrydate - the date
 *  @return HashSet - the dates for each topic
 *  @throws BaseDaoException - when error occurs
 */
public HashSet getMonthlyTopicDates(String pBlogId, int accessFlag, boolean getLoginInfo, String entrydate)
        throws BaseDaoException {

    if (RegexStrUtil.isNull(pBlogId)) {
        throw new BaseDaoException("params are null");
    }

    /**
     *  Get scalability ds for topics, topics partitioned on pBlogId
     */
    String sourceName = scalabilityManager.getReadScalability(pBlogId);
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, getTopicDates() " + sourceName + " pBlogId = " + pBlogId);
    }

    HashSet result = null;
    Connection conn = null;
    try {
        conn = ds.getConnection();
        result = getMonthlyQuery.run(conn, pBlogId, MyUtils.getMonthNum(entrydate), MyUtils.getYear(entrydate));
    } catch (Exception e) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e1) {
            throw new BaseDaoException("error occured while listing pblogtopics getMonthlyQuery()" + pBlogId,
                    e1);
        }
        throw new BaseDaoException("error in getMonthlyQuery(), pBlogId =" + pBlogId, e);
    }

    try {
        if (conn != null) {
            conn.close();
        }
    } catch (Exception e2) {
        throw new BaseDaoException("conn.close() error in getMonthlyQuery(), pBlogId =" + pBlogId, e2);
    }

    HashSet dateSet = null;
    if ((result != null) && (result.size() > 0)) {
        Iterator it = result.iterator();
        dateSet = new HashSet();
        while (it.hasNext()) {
            Blog blog = (Blog) it.next();
            dateSet.add(blog.getValue(DbConstants.ENTRY_DATE));
        }
    }
    return dateSet;

    /*
            if ((result != null) && (result.size() > 0) ) {
          Iterator it = result.iterator();
          while (it.hasNext() ) {
      Blog blog = (Blog)it.next();
             String date = blog.getValue(DbConstants.ENTRY_DATE);
             if (date.equals(entrydate)) {
    //treeCache.put(fqn, pBlogId, result);
         return result;
             }
               }
            } */
}

From source file:dao.PblogTopicDaoDb.java

/**
 *  Allow users to view it, with session or without session
 *  topics are retrieved from datasource that is based on accessFlag
 *  Retrieves topics based on pBlogId and date
 *  @param pBlogId - the personal blogid
 *  @param accessFlag - the access Flag, which indicates the datasource from which topics are retrieved.
 *             READ_FROM_MASTER (1), READ_FROM_SLAVE(0)
 *  @param getLoginInfo - get the blogger's information
 *  @param entrydate - the date/*from  w  ww. j a  v a 2 s. c  o  m*/
 *  @return HashSet - the dates for each topic
 *  @throws BaseDaoException - when error occurs
 */
public HashSet getTopicDates(String pBlogId, int accessFlag, boolean getLoginInfo, String entrydate)
        throws BaseDaoException {

    if (RegexStrUtil.isNull(pBlogId)) {
        throw new BaseDaoException("params are null");
    }

    /**
     *  Get scalability ds for topics, topics partitioned on pBlogId
     */
    String sourceName = scalabilityManager.getReadScalability(pBlogId);
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, getTopicDates() " + sourceName + " pBlogId = " + pBlogId);
    }

    HashSet result = null;
    Connection conn = null;
    try {
        conn = ds.getConnection();
        result = getDateQuery.run(conn, pBlogId, MyUtils.getMonthNum(entrydate), MyUtils.getYear(entrydate),
                MyUtils.getDay(entrydate));
    } catch (Exception e) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e1) {
            throw new BaseDaoException("error occured while listing pblogtopics getDateQuery()" + pBlogId, e1);
        }
        throw new BaseDaoException("error in getDateQuery(), pBlogId =" + pBlogId, e);
    }

    try {
        if (conn != null) {
            conn.close();
        }
    } catch (Exception e2) {
        throw new BaseDaoException("conn.close() error in getDateQuery(), pBlogId =" + pBlogId, e2);
    }

    HashSet dateSet = null;
    if ((result != null) && (result.size() > 0)) {
        Iterator it = result.iterator();
        dateSet = new HashSet();
        while (it.hasNext()) {
            Blog blog = (Blog) it.next();
            dateSet.add(blog.getValue(DbConstants.ENTRY_DATE));
        }
    }
    return dateSet;

    /*
            if ((result != null) && (result.size() > 0) ) {
          Iterator it = result.iterator();
          while (it.hasNext() ) {
      Blog blog = (Blog)it.next();
             String date = blog.getValue(DbConstants.ENTRY_DATE);
             if (date.equals(entrydate)) {
    //treeCache.put(fqn, pBlogId, result);
         return result;
             }
               }
            } */
}

From source file:net.sourceforge.mipa.predicatedetection.lattice.sequence.SequenceWindowedLatticeChecker.java

private void updateReachableState(SequenceLatticeIDNode minCGS, AbstractLatticeIDNode maxCGS, int id) {
    // TODO Auto-generated method stub
    if (minCGS == null) {
        return;//from w  w  w.  j  a v  a2 s  . c o m
    }

    /*
     * minCGS.getReachedStates().clear();
     * 
     * String[] string = minCGS.getSatisfiedPredicates().split(" "); for
     * (int i = 0; i < string.length; i++) { State state =
     * automaton.getInitialState().step(string[i].charAt(0));
     * minCGS.addReachedStates(state); } //
     * minCGS.addReachedStates(automaton.getInitialState()); if (DEBUG) {
     * long time_t = (new Date()).getTime(); out.print("[ "); for (int i =
     * 0; i < minCGS.getID().length; i++) { out.print(minCGS.getID()[i] +
     * " "); } out.print("]: satisfied predicates: " +
     * minCGS.getSatisfiedPredicates()); out.print(" reachable states: ");
     * Iterator<State> it = minCGS.getReachedStates().iterator(); while
     * (it.hasNext()) { State state = it.next(); out.print(state.getName() +
     * " "); } out.println(); out.flush(); wastedTime += (new
     * Date()).getTime() - time_t; } long time = (new Date()).getTime();
     * ArrayList<SequenceLatticeIDNode> set = new
     * ArrayList<SequenceLatticeIDNode>(); ArrayList<String> setID = new
     * ArrayList<String>(); set.add(minCGS);
     * setID.add(StringUtils.join(minCGS.getID(), ' ')); while
     * (!set.isEmpty()) { SequenceLatticeIDNode node = set.remove(0); for
     * (int i = 0; i < children.length; i++) { String[] index = new
     * String[children.length]; for (int j = 0; j < children.length; j++) {
     * index[j] = node.getID()[j]; } index[i] =
     * Integer.toString(Integer.valueOf(index[i]) + 1); String ID =
     * StringUtils.join(index, ' '); if (!setID.contains(ID) &&
     * getMappedLattice().get(ID) != null) { SequenceLatticeIDNode newNode =
     * (SequenceLatticeIDNode) getMappedLattice() .get(ID); if
     * (newNode.getGlobalState()[id].getID().equals(
     * minCGS.getGlobalState()[id].getID())) {
     * newNode.getReachedStates().clear(); computeReachableStates(newNode);
     * set.add(newNode); setID.add(StringUtils.join(newNode.getID(), ' '));
     * } else { HashSet<State> oriState = new HashSet<State>();
     * Iterator<State> iterator = newNode.getReachedStates() .iterator();
     * while (iterator.hasNext()) { oriState.add(iterator.next()); }
     * newNode.getReachedStates().clear(); computeReachableStates(newNode);
     * 
     * boolean flag = true; if (oriState.size() ==
     * newNode.getReachedStates() .size()) { String ori = ""; iterator =
     * oriState.iterator(); while (iterator.hasNext()) { State state =
     * iterator.next(); ori += state.getName() + " ";
     * 
     * } String news = ""; iterator = newNode.getReachedStates().iterator();
     * while (iterator.hasNext()) { State state = iterator.next(); news +=
     * state.getName() + " "; }
     * 
     * String[] oriStates = ori.trim().split(" "); String[] newStates =
     * news.trim().split(" "); for (int j = 0; j < oriStates.length; j++) {
     * String s = oriStates[j]; boolean f = false; for (int k = 0; k <
     * newStates.length; k++) { if (s.equals(newStates[k])) { f = true;
     * break; } } if (f == false) { flag = false; break; } } } else { flag =
     * false; } if (flag == false) { set.add(newNode);
     * setID.add(StringUtils.join(newNode.getID(), ' ')); } } } } } for (int
     * i = 0; i < children.length; i++) { String[] index = new
     * String[children.length]; for (int j = 0; j < children.length; j++) {
     * index[j] = node.getID()[j]; } index[i] =
     * Integer.toString(Integer.valueOf(index[i]) + 1); String ID =
     * StringUtils.join(index, ' '); if (!setID.contains(ID) &&
     * getMappedLattice().get(ID) != null) { SequenceLatticeIDNode newNode =
     * (SequenceLatticeIDNode) getMappedLattice() .get(ID); if
     * (newNode.getGlobalState()[id].getID().equals(
     * minCGS.getGlobalState()[id].getID())) {
     * newNode.getReachedStates().clear(); computeReachableStates(newNode);
     * set.add(newNode); setID.add(StringUtils.join(newNode.getID(), ' '));
     * } else { HashSet<State> oriState = new HashSet<State>();
     * Iterator<State> iterator = newNode.getReachedStates() .iterator();
     * while (iterator.hasNext()) { oriState.add(iterator.next()); }
     * newNode.getReachedStates().clear(); computeReachableStates(newNode);
     * 
     * boolean flag = true; if (oriState.size() ==
     * newNode.getReachedStates() .size()) { String ori = ""; iterator =
     * oriState.iterator(); while (iterator.hasNext()) { State state =
     * iterator.next(); ori += state.getName() + " ";
     * 
     * } String news = ""; iterator = newNode.getReachedStates().iterator();
     * while (iterator.hasNext()) { State state = iterator.next(); news +=
     * state.getName() + " "; }
     * 
     * String[] oriStates = ori.trim().split(" "); String[] newStates =
     * news.trim().split(" "); for (int j = 0; j < oriStates.length; j++) {
     * String s = oriStates[j]; boolean f = false; for (int k = 0; k <
     * newStates.length; k++) { if (s.equals(newStates[k])) { f = true;
     * break; } } if (f == false) { flag = false; break; } } } else { flag =
     * false; } if (flag == false) { set.add(newNode);
     * setID.add(StringUtils.join(newNode.getID(), ' ')); } } } }
     */

    long time = (new Date()).getTime();
    ArrayList<SequenceLatticeIDNode> set = new ArrayList<SequenceLatticeIDNode>();
    ArrayList<String> setID = new ArrayList<String>();
    set.add(minCGS);
    while (!set.isEmpty()) {
        SequenceLatticeIDNode node = set.remove(0);
        if (!setID.contains(StringUtils.join(node.getID(), ' '))) {
            setID.add(StringUtils.join(node.getID(), ' '));
            HashSet<State> oriState = new HashSet<State>();
            Iterator<State> iterator = node.getReachedStates().iterator();
            while (iterator.hasNext()) {
                oriState.add(iterator.next());
            }
            if (node.equals(minCGS)) {
                node.getReachedStates().clear();
                String[] string = node.getSatisfiedPredicates().split(" ");
                for (int i = 0; i < string.length; i++) {
                    State state = automaton.getInitialState().step(string[i].charAt(0));
                    node.addReachedStates(state);
                }
                if (DEBUG) {
                    long time_t = (new Date()).getTime();
                    out.print("[ ");
                    for (int i = 0; i < node.getID().length; i++) {
                        out.print(node.getID()[i] + " ");
                    }
                    out.print("]: satisfied predicates: " + node.getSatisfiedPredicates());
                    out.print(" reachable states: ");
                    Iterator<State> it = node.getReachedStates().iterator();
                    while (it.hasNext()) {
                        State state = it.next();
                        out.print(state.getName() + " ");
                    }
                    out.println();
                    out.flush();
                    wastedTime += (new Date()).getTime() - time_t;
                }
            } else {
                node.getReachedStates().clear();
                computeReachableStates(node);
            }

            boolean flag = true;
            if (oriState.size() == node.getReachedStates().size()) {
                String ori = "";
                iterator = oriState.iterator();
                while (iterator.hasNext()) {
                    State state = iterator.next();
                    ori += state.getName() + " ";

                }
                String news = "";
                iterator = node.getReachedStates().iterator();
                while (iterator.hasNext()) {
                    State state = iterator.next();
                    news += state.getName() + " ";
                }

                String[] oriStates = ori.trim().split(" ");
                String[] newStates = news.trim().split(" ");
                for (int j = 0; j < oriStates.length; j++) {
                    String s = oriStates[j];
                    boolean f = false;
                    for (int k = 0; k < newStates.length; k++) {
                        if (s.equals(newStates[k])) {
                            f = true;
                            break;
                        }
                    }
                    if (f == false) {
                        flag = false;
                        break;
                    }
                }
            } else {
                flag = false;
            }
            if (flag == false) {
                for (int i = 0; i < children.length; i++) {
                    String[] index = new String[children.length];
                    for (int j = 0; j < children.length; j++) {
                        index[j] = node.getID()[j];
                    }
                    index[i] = Integer.toString(Integer.valueOf(index[i]) + 1);
                    String ID = StringUtils.join(index, ' ');
                    if (getMappedLattice().get(ID) != null) {
                        set.add((SequenceLatticeIDNode) getMappedLattice().get(ID));
                    }
                }
            } else {
                // [id] not change
                if (node.getID()[id].equals(windowedLocalStateSet.get(id).get(0).getID())) {
                    for (int i = 0; i < children.length; i++) {
                        if (i == id) {
                            continue;
                        }
                        String[] index = new String[children.length];
                        for (int j = 0; j < children.length; j++) {
                            index[j] = node.getID()[j];
                        }
                        index[i] = Integer.toString(Integer.valueOf(index[i]) + 1);
                        String ID = StringUtils.join(index, ' ');
                        if (getMappedLattice().get(ID) != null) {
                            set.add((SequenceLatticeIDNode) getMappedLattice().get(ID));
                        }
                    }
                }
            }
        }
    }
    updateNumber = setID.size();
    updateTime = (new Date()).getTime() - time;
}