Example usage for java.util Collection clear

List of usage examples for java.util Collection clear

Introduction

In this page you can find the example usage for java.util Collection clear.

Prototype

void clear();

Source Link

Document

Removes all of the elements from this collection (optional operation).

Usage

From source file:com.globalsight.everest.webapp.pagehandler.administration.fileprofile.FileProfileMainHandler.java

/**
 * Get data for main table./*from w ww  . j  a v a 2s  .  c  o  m*/
 */
private void dataForTable(HttpServletRequest p_request, HttpSession p_session)
        throws RemoteException, NamingException, GeneralException {
    SessionManager sessionMgr = (SessionManager) p_session.getAttribute(SESSION_MANAGER);
    StringBuffer condition = new StringBuffer();
    String[][] array = new String[][] { { "uNameFilter", "f.name" }, { "uLPFilter", "lp.name" },
            { "uSourceFileFormatFilter", "kft.name" }, { "uCompanyFilter", "c.name" } };
    // filterTableName
    String uFNFilter = (String) sessionMgr.getAttribute("uFNFilter");
    boolean needRemove = false;
    Map<String, String> filres = new HashMap<String, String>();
    if (StringUtils.isNotBlank(uFNFilter)) {
        condition.append(" and  f.filterTableName IS NOT null");
        filres = FilterHelper.getallFiltersLikeName(StringUtil.transactSQLInjection(uFNFilter.trim()));
        needRemove = true;

    }
    for (int i = 0; i < array.length; i++) {
        makeCondition(sessionMgr, condition, array[i][0], array[i][1]);
    }
    Collection fileprofiles = null;
    try {
        fileprofiles = ServerProxy.getFileProfilePersistenceManager()
                .getAllFileProfilesByCondition(condition.toString());
        if (needRemove) {
            if (filres.size() > 0) {
                LOOP: for (Iterator iter = fileprofiles.iterator(); iter.hasNext();) {
                    FileprofileVo fileprofilevo = (FileprofileVo) iter.next();
                    FileProfile FileProfile = fileprofilevo.getFileProfile();
                    String filterName = filres
                            .get(FileProfile.getFilterTableName() + FileProfile.getFilterId());
                    if (filterName == null) {
                        iter.remove();
                    }
                }
            } else {
                fileprofiles.clear();
            }
        }
    } catch (Exception e) {
        throw new EnvoyServletException(e);
    }

    Locale uiLocale = (Locale) p_session.getAttribute(WebAppConstants.UILOCALE);

    String numOfPerPage = p_request.getParameter("numOfPageSize");
    if (StringUtil.isNotEmpty(numOfPerPage)) {
        try {
            NUM_PER_PAGE = Integer.parseInt(numOfPerPage);
        } catch (Exception e) {
            NUM_PER_PAGE = Integer.MAX_VALUE;
        }
    }
    HashMap<Long, String> idViewExtensions = ServerProxy.getFileProfilePersistenceManager()
            .getIdViewFileExtensions();
    setTableNavigation(p_request, p_session, (List) fileprofiles,
            new FileProfileComparator(uiLocale, idViewExtensions), NUM_PER_PAGE,
            FileProfileConstants.FILEPROFILE_LIST, FileProfileConstants.FILEPROFILE_KEY);

    CVSFileProfileManagerLocal cvsFPManager = new CVSFileProfileManagerLocal();
    ArrayList<CVSFileProfile> cvsfps = (ArrayList<CVSFileProfile>) cvsFPManager.getAllCVSFileProfiles();
    ArrayList<String> existCVSFPs = new ArrayList<String>();
    ;
    if (cvsfps != null) {
        for (CVSFileProfile f : cvsfps) {
            existCVSFPs.add(String.valueOf(f.getFileProfile().getId()));
        }
    }
    p_request.setAttribute("existCVSFPs", existCVSFPs);
    p_request.setAttribute("idViewExtensions", idViewExtensions);
    Hashtable l10nprofiles = ServerProxy.getProjectHandler().getAllL10nProfileNames();
    checkPreReqData(p_request, p_session, l10nprofiles);
}

From source file:com.haulmont.cuba.core.app.RdbmsStore.java

@SuppressWarnings("unchecked")
protected <E extends Entity> List<E> getResultListIteratively(LoadContext<E> context, Query query,
        Collection<E> filteredCollection, int initialSize, boolean needApplyConstraints) {
    int requestedFirst = context.getQuery().getFirstResult();
    int requestedMax = context.getQuery().getMaxResults();

    if (requestedMax == 0) {
        // set contains all items if query without paging
        return new ArrayList<>(filteredCollection);
    }//  w ww.j  av a 2s  . c om

    int setSize = initialSize + requestedFirst;
    int factor = filteredCollection.size() == 0 ? 2 : initialSize / filteredCollection.size() * 2;

    filteredCollection.clear();

    int firstResult = 0;
    int maxResults = (requestedFirst + requestedMax) * factor;
    int i = 0;
    while (filteredCollection.size() < setSize) {
        if (i++ > 10000) {
            log.warn("In-memory distinct: endless loop detected for " + context);
            break;
        }
        query.setFirstResult(firstResult);
        query.setMaxResults(maxResults);
        //noinspection unchecked
        List<E> list = query.getResultList();
        if (list.size() == 0) {
            break;
        }
        if (needApplyConstraints) {
            security.filterByConstraints((Collection<Entity>) list);
        }
        filteredCollection.addAll(list);

        firstResult = firstResult + maxResults;
    }

    // Copy by iteration because subList() returns non-serializable class
    int max = Math.min(requestedFirst + requestedMax, filteredCollection.size());
    List<E> result = new ArrayList<>(max - requestedFirst);
    int j = 0;
    for (E item : filteredCollection) {
        if (j >= max)
            break;
        if (j >= requestedFirst)
            result.add(item);
        j++;
    }
    return result;
}

From source file:edu.brown.costmodel.SingleSitedCostModel.java

@Override
public void clear(boolean force) {
    super.clear(force);

    this.txn_entries.clear();
    this.last_invalidateTxns.clear();

    for (Collection<QueryCacheEntry> c : this.cache_tableXref.values()) {
        c.clear();
    }//from   w  w w. ja  v  a 2  s.c om
    for (Collection<QueryCacheEntry> c : this.cache_stmtXref.values()) {
        c.clear();
    }
    for (Collection<TransactionCacheEntry> c : this.cache_procXref.values()) {
        c.clear();
    }

    assert (this.histogram_txn_partitions.getSampleCount() == 0);
    assert (this.histogram_txn_partitions.getValueCount() == 0);
    assert (this.histogram_query_partitions.getSampleCount() == 0);
    assert (this.histogram_query_partitions.getValueCount() == 0);
}

From source file:es.ucm.fdi.dalgs.acl.service.AclObjectService.java

public void addPermissionCASCADE(User user, Object object, Long id_academic, Long id_course, Long id_group) {
    if (user != null) {
        if (object instanceof Course) { // Coordinator

            this.addPermissionToAnObject_READ(user, id_academic, AcademicTerm.class.getName());
            this.addPermissionToAnObject_ADMINISTRATION(user, id_academic, AcademicTerm.class.getName());

            this.addPermissionToAnObject_ADMINISTRATION(user, id_course, Course.class.getName());

            this.addPermissionToAnObject_WRITE(user, id_course, Course.class.getName());

            // Course Activities
            Collection<Activity> activities_aux = activityService.getActivitiesForCourse(id_course, true);
            for (Activity a : activities_aux) {
                this.addPermissionToAnObject_ADMINISTRATION(user, a.getId(), a.getClass().getName());
                this.addPermissionToAnObject_WRITE(user, a.getId(), a.getClass().getName());
            }//from   w  w w.java 2 s . co m

            // Groups
            Collection<Group> groups_aux = groupService.getGroupsForCourse(id_course, true);
            for (Group g : groups_aux) {
                this.addPermissionToAnObject_READ(user, g.getId(), g.getClass().getName());
                this.addPermissionToAnObject_WRITE(user, g.getId(), g.getClass().getName());
                this.addPermissionToAnObject_ADMINISTRATION(user, g.getId(), g.getClass().getName());
                activities_aux.clear();

                // Group activities
                activities_aux = activityService.getActivitiesForGroup(g.getId(), true);
                for (Activity a : activities_aux) {
                    this.addPermissionToAnObject_WRITE(user, a.getId(), a.getClass().getName());
                    this.addPermissionToAnObject_ADMINISTRATION(user, a.getId(), a.getClass().getName());
                }
            }
        }

        else if (object instanceof Group) {

            this.addPermissionToAnObject_READ(user, id_academic, AcademicTerm.class.getName());

            this.addPermissionToAnObject_READ(user, id_course, Course.class.getName());

            if (userService.hasRole(user, "ROLE_STUDENT"))
                this.addPermissionToAnObject_READ(user, id_group, Group.class.getName());
            else if (userService.hasRole(user, "ROLE_PROFESSOR")) {
                this.addPermissionToAnObject_ADMINISTRATION(user, id_group, Group.class.getName());
                this.addPermissionToAnObject_WRITE(user, id_group, Group.class.getName());

                this.addPermissionToAnObject_ADMINISTRATION(user, id_academic, AcademicTerm.class.getName());

                this.addPermissionToAnObject_ADMINISTRATION(user, id_course, Course.class.getName());
            }

            // Group activities
            Collection<Activity> activities_aux = activityService.getActivitiesForGroup(id_group, true);
            for (Activity a : activities_aux) {
                if (userService.hasRole(user, "ROLE_STUDENT"))
                    this.addPermissionToAnObject_READ(user, a.getId(), a.getClass().getName());
                else if (userService.hasRole(user, "ROLE_PROFESSOR")) {
                    this.addPermissionToAnObject_ADMINISTRATION(user, a.getId(), a.getClass().getName());
                    this.addPermissionToAnObject_WRITE(user, a.getId(), a.getClass().getName());
                }
            }
            activities_aux.clear();

            // Course activities
            activities_aux = activityService.getActivitiesForCourse(id_course, true);
            for (Activity a : activities_aux) {
                this.addPermissionToAnObject_READ(user, a.getId(), a.getClass().getName());
                this.addPermissionToAnObject_ADMINISTRATION(user, a.getId(), a.getClass().getName());
            }
        }
    }
}

From source file:org.cruk.mga.CreateReport.java

@Override
protected void run() throws IOException, ValidityException, ParsingException, TransformerException {
    readReferenceGenomeMapping();/*from   w w  w . j  av a  2s .  c om*/
    readCountSummaryFiles();
    readSamplingSummaryFiles();
    readAdapterAlignmentFiles();
    readAlignments();
    OrderedProperties runProperties = readSampleSheet();
    String imageFilename = outputPrefix + ".png";
    String htmlFilename = outputPrefix + ".html";
    createSummaryPlot(multiGenomeAlignmentSummaries.values(), imageFilename);
    writeReport(multiGenomeAlignmentSummaries.values(), runProperties, out, imageFilename, outputFilename,
            htmlFilename);

    if (separateDatasetReports) {
        Collection<MultiGenomeAlignmentSummary> summaries = new ArrayList<MultiGenomeAlignmentSummary>();
        for (MultiGenomeAlignmentSummary multiGenomeAlignmentSummary : multiGenomeAlignmentSummaries.values()) {
            summaries.clear();
            summaries.add(multiGenomeAlignmentSummary);
            String datasetId = multiGenomeAlignmentSummary.getDatasetId();
            String prefix = datasetReportFilenamePrefix + datasetId;
            htmlFilename = prefix + ".html";
            imageFilename = prefix + ".png";
            String xmlFilename = prefix + ".xml";
            createSummaryPlot(summaries, imageFilename);
            PrintStream printStream = new PrintStream(
                    new BufferedOutputStream(new FileOutputStream(xmlFilename)));
            writeReport(summaries, runProperties, printStream, imageFilename, xmlFilename, htmlFilename);
            printStream.close();
        }
    }
}

From source file:es.ucm.fdi.dalgs.acl.service.AclObjectService.java

public void removePermissionCASCADE(User user, Object object, Long id_academic, Long id_course, Long id_group) {
    if (user != null) {
        if (object instanceof Course) { // Coordinator

            this.removePermissionToAnObject_READ(user, id_academic, AcademicTerm.class.getName());
            this.removePermissionToAnObject_ADMINISTRATION(user, id_academic, AcademicTerm.class.getName());

            this.removePermissionToAnObject_ADMINISTRATION(user, id_course, Course.class.getName());

            this.removePermissionToAnObject_WRITE(user, id_course, Course.class.getName());

            // Course Activities
            Collection<Activity> activities_aux = activityService.getActivitiesForCourse(id_course, true);
            for (Activity a : activities_aux) {
                this.removePermissionToAnObject_ADMINISTRATION(user, a.getId(), a.getClass().getName());
                this.removePermissionToAnObject_WRITE(user, a.getId(), a.getClass().getName());
            }//w  w w .j a  v  a2  s . co  m

            // Groups
            Collection<Group> groups_aux = groupService.getGroupsForCourse(id_course, true);
            for (Group g : groups_aux) {
                this.removePermissionToAnObject_READ(user, g.getId(), g.getClass().getName());
                this.removePermissionToAnObject_WRITE(user, g.getId(), g.getClass().getName());
                this.removePermissionToAnObject_ADMINISTRATION(user, g.getId(), g.getClass().getName());
                activities_aux.clear();

                // Group activities
                activities_aux = activityService.getActivitiesForGroup(g.getId(), true);
                for (Activity a : activities_aux) {
                    this.removePermissionToAnObject_WRITE(user, a.getId(), a.getClass().getName());
                    this.removePermissionToAnObject_ADMINISTRATION(user, a.getId(), a.getClass().getName());
                }
            }
        }

        else if (object instanceof Group) {

            this.removePermissionToAnObject_READ(user, id_academic, AcademicTerm.class.getName());

            this.removePermissionToAnObject_READ(user, id_course, Course.class.getName());

            if (userService.hasRole(user, "ROLE_STUDENT"))
                this.removePermissionToAnObject_READ(user, id_group, Group.class.getName());
            else if (userService.hasRole(user, "ROLE_PROFESSOR")) {
                this.removePermissionToAnObject_ADMINISTRATION(user, id_group, Group.class.getName());
                this.removePermissionToAnObject_WRITE(user, id_group, Group.class.getName());

                this.removePermissionToAnObject_ADMINISTRATION(user, id_academic, AcademicTerm.class.getName());

                this.removePermissionToAnObject_ADMINISTRATION(user, id_course, Course.class.getName());
            }

            // Group activities
            Collection<Activity> activities_aux = activityService.getActivitiesForGroup(id_group, true);
            for (Activity a : activities_aux) {
                if (userService.hasRole(user, "ROLE_STUDENT"))
                    this.removePermissionToAnObject_READ(user, a.getId(), a.getClass().getName());
                else if (userService.hasRole(user, "ROLE_PROFESSOR")) {
                    this.removePermissionToAnObject_ADMINISTRATION(user, a.getId(), a.getClass().getName());
                    this.removePermissionToAnObject_WRITE(user, a.getId(), a.getClass().getName());
                }
            }
            activities_aux.clear();

            // Course activities
            activities_aux = activityService.getActivitiesForCourse(id_course, true);
            for (Activity a : activities_aux) {
                this.removePermissionToAnObject_READ(user, a.getId(), a.getClass().getName());
                this.removePermissionToAnObject_ADMINISTRATION(user, a.getId(), a.getClass().getName());
            }
        }
    }
}

From source file:org.schedulesdirect.grabber.Grabber.java

private void updateZip(NetworkEpgClient clnt) throws IOException, JSONException, JsonParseException {
    Set<String> completedListings = new HashSet<String>();
    LOG.debug(String.format("Using %d worker threads", globalOpts.getMaxThreads()));
    pool = createThreadPoolExecutor();//from w  ww. ja  va  2s. c  om
    start = System.currentTimeMillis();
    File dest = grabOpts.getTarget();
    cachedSeriesIds = new HashSet<String>();
    boolean rmDest = false;
    if (dest.exists()) {
        ZipEpgClient zipClnt = null;
        try {
            zipClnt = new ZipEpgClient(dest);
            if (!zipClnt.getUserStatus().getLastServerRefresh()
                    .before(clnt.getUserStatus().getLastServerRefresh())) {
                LOG.info(
                        "Current cache file contains latest data from Schedules Direct server; use --force-download to force a new download from server.");
                boolean force = grabOpts.isForce();
                if (!force)
                    return;
                else
                    LOG.warn("Forcing an update of data with the server due to user request!");
            }
        } catch (Exception e) {
            if (grabOpts.isKeep()) {
                LOG.error("Existing cache is invalid, keeping by user request!", e);
                return;
            } else {
                LOG.warn("Existing cache is invalid, deleting it; use --keep-bad-cache to keep existing cache!",
                        e);
                rmDest = true;
            }
        } finally {
            if (zipClnt != null)
                try {
                    zipClnt.close();
                } catch (IOException e) {
                }
            if (rmDest && !dest.delete())
                throw new IOException("Unable to delete " + dest);
        }
    }

    freshZip = !dest.exists();
    try (FileSystem vfs = FileSystems.newFileSystem(new URI(String.format("jar:%s", dest.toURI())),
            Collections.singletonMap("create", "true"))) {
        if (freshZip) {
            Path target = vfs.getPath(ZipEpgClient.ZIP_VER_FILE);
            Files.write(target, Integer.toString(ZipEpgClient.ZIP_VER).getBytes(ZipEpgClient.ZIP_CHARSET));
        }
        ProgramCache progCache = ProgramCache.get(vfs);
        Path lineups = vfs.getPath("lineups.txt");
        Files.deleteIfExists(lineups);
        Path scheds = vfs.getPath("/schedules/");
        if (!Files.isDirectory(scheds))
            Files.createDirectory(scheds);
        Path maps = vfs.getPath("/maps/");
        PathUtils.removeDirectory(maps);
        Files.createDirectory(maps);
        Path progs = vfs.getPath("/programs/");
        if (!Files.isDirectory(progs))
            Files.createDirectory(progs);
        Path logos = vfs.getPath("/logos/");
        if (!Files.isDirectory(logos))
            Files.createDirectory(logos);
        Path md5s = vfs.getPath("/md5s/");
        if (!Files.isDirectory(md5s))
            Files.createDirectory(md5s);
        Path cache = vfs.getPath(LOGO_CACHE);
        if (Files.exists(cache)) {
            String cacheData = new String(Files.readAllBytes(cache), ZipEpgClient.ZIP_CHARSET);
            logoCache = Config.get().getObjectMapper().readValue(cacheData, JSONObject.class);
        } else
            logoCache = new JSONObject();
        Path seriesInfo = vfs.getPath("/seriesInfo/");
        if (!Files.isDirectory(seriesInfo))
            Files.createDirectories(seriesInfo);
        loadSeriesInfoIds(seriesInfo);
        missingSeriesIds = Collections.synchronizedSet(new HashSet<String>());
        loadRetryIds(vfs.getPath(SERIES_INFO_DATA));

        JSONObject resp = Config.get().getObjectMapper().readValue(
                factory.get(DefaultJsonRequest.Action.GET, RestNouns.LINEUPS, clnt.getHash(),
                        clnt.getUserAgent(), globalOpts.getUrl().toString()).submitForJson(null),
                JSONObject.class);
        if (!JsonResponseUtils.isErrorResponse(resp))
            Files.write(lineups, resp.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET));
        else
            LOG.error("Received error response when requesting lineup data!");

        for (Lineup l : clnt.getLineups()) {
            buildStationList();
            JSONObject o = Config.get().getObjectMapper()
                    .readValue(
                            factory.get(DefaultJsonRequest.Action.GET, l.getUri(), clnt.getHash(),
                                    clnt.getUserAgent(), globalOpts.getUrl().toString()).submitForJson(null),
                            JSONObject.class);
            Files.write(vfs.getPath("/maps", ZipEpgClient.scrubFileName(String.format("%s.txt", l.getId()))),
                    o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET));
            JSONArray stations = o.getJSONArray("stations");
            JSONArray ids = new JSONArray();
            for (int i = 0; i < stations.length(); ++i) {
                JSONObject obj = stations.getJSONObject(i);
                String sid = obj.getString("stationID");
                if (stationList != null && !stationList.contains(sid))
                    LOG.debug(String.format("Skipped %s; not listed in station file", sid));
                else if (completedListings.add(sid)) {
                    ids.put(sid);
                    if (!grabOpts.isNoLogos()) {
                        if (logoCacheInvalid(obj))
                            pool.execute(new LogoTask(obj, vfs, logoCache));
                        else if (LOG.isDebugEnabled())
                            LOG.debug(String.format("Skipped logo for %s; already cached!",
                                    obj.optString("callsign", null)));
                    } else if (!logosWarned) {
                        logosWarned = true;
                        LOG.warn("Logo downloads disabled by user request!");
                    }
                } else
                    LOG.debug(String.format("Skipped %s; already downloaded.", sid));
                //pool.setMaximumPoolSize(5); // Processing these new schedules takes all kinds of memory!
                if (ids.length() == grabOpts.getMaxSchedChunk()) {
                    pool.execute(new ScheduleTask(ids, vfs, clnt, progCache, factory));
                    ids = new JSONArray();
                }
            }
            if (ids.length() > 0)
                pool.execute(new ScheduleTask(ids, vfs, clnt, progCache, factory));
        }
        pool.shutdown();
        try {
            LOG.debug("Waiting for SchedLogoExecutor to terminate...");
            if (pool.awaitTermination(15, TimeUnit.MINUTES))
                LOG.debug("SchedLogoExecutor: Terminated successfully.");
            else {
                failedTask = true;
                LOG.warn(
                        "SchedLogoExecutor: Termination timed out; some tasks probably didn't finish properly!");
            }
        } catch (InterruptedException e) {
            failedTask = true;
            LOG.warn(
                    "SchedLogoExecutor: Termination interrupted); some tasks probably didn't finish properly!");
        }
        Files.write(cache, logoCache.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET),
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        ScheduleTask.commit(vfs);

        pool = createThreadPoolExecutor();
        //pool.setMaximumPoolSize(5); // Again, we've got memory problems
        String[] dirtyPrograms = progCache.getDirtyIds();
        progCache.markAllClean();
        progCache = null;
        LOG.info(String.format("Identified %d program ids requiring an update!", dirtyPrograms.length));
        Collection<String> progIds = new ArrayList<String>();
        for (String progId : dirtyPrograms) {
            progIds.add(progId);
            if (progIds.size() == grabOpts.getMaxProgChunk()) {
                pool.execute(new ProgramTask(progIds, vfs, clnt, factory, missingSeriesIds, "programs", null,
                        false));
                progIds.clear();
            }
        }
        if (progIds.size() > 0)
            pool.execute(
                    new ProgramTask(progIds, vfs, clnt, factory, missingSeriesIds, "programs", null, false));
        pool.shutdown();
        try {
            LOG.debug("Waiting for ProgramExecutor to terminate...");
            if (pool.awaitTermination(15, TimeUnit.MINUTES)) {
                LOG.debug("ProgramExecutor: Terminated successfully.");
                Iterator<String> itr = missingSeriesIds.iterator();
                while (itr.hasNext()) {
                    String id = itr.next();
                    if (cachedSeriesIds.contains(id))
                        itr.remove();
                }
                if (missingSeriesIds.size() > 0) {
                    LOG.info(String.format("Grabbing %d series info programs!", missingSeriesIds.size()));
                    Set<String> retrySet = new HashSet<>();
                    try {
                        new ProgramTask(missingSeriesIds, vfs, clnt, factory, missingSeriesIds, "seriesInfo",
                                retrySet, true).run();
                    } catch (RuntimeException e) {
                        LOG.error("SeriesInfo task failed!", e);
                        Grabber.failedTask = true;
                    }
                    Path seriesInfoData = vfs.getPath(SERIES_INFO_DATA);
                    if (retrySet.size() > 0) {
                        StringBuilder sb = new StringBuilder();
                        for (String id : retrySet)
                            sb.append(id + "\n");
                        Files.write(seriesInfoData, sb.toString().getBytes(ZipEpgClient.ZIP_CHARSET),
                                StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING,
                                StandardOpenOption.CREATE);
                    } else if (Files.exists(seriesInfoData))
                        Files.delete(seriesInfoData);
                }
            } else {
                failedTask = true;
                LOG.warn("ProgramExecutor: Termination timed out; some tasks probably didn't finish properly!");
            }
        } catch (InterruptedException e) {
            failedTask = true;
            LOG.warn("ProgramExecutor: Termination interrupted); some tasks probably didn't finish properly!");
        }

        String userData = clnt.getUserStatus().toJson();
        if (failedTask) {
            LOG.error("One or more tasks failed!  Resetting last data refresh timestamp to zero.");
            SimpleDateFormat fmt = Config.get().getDateTimeFormat();
            String exp = fmt.format(new Date(0L));
            JSONObject o = Config.get().getObjectMapper().readValue(userData, JSONObject.class);
            o.put("lastDataUpdate", exp);
            userData = o.toString(2);
        }
        Path p = vfs.getPath(USER_DATA);
        Files.write(p, userData.getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
        removeIgnoredStations(vfs);
    } catch (URISyntaxException e1) {
        throw new RuntimeException(e1);
    } finally {
        Runtime rt = Runtime.getRuntime();
        LOG.info(String.format("MemStats:%n\tFREE: %s%n\tUSED: %s%n\t MAX: %s",
                FileUtils.byteCountToDisplaySize(rt.freeMemory()),
                FileUtils.byteCountToDisplaySize(rt.totalMemory()),
                FileUtils.byteCountToDisplaySize(rt.maxMemory())));
    }
}

From source file:com.github.helenusdriver.driver.impl.PersistedMap.java

/**
 * {@inheritDoc}/*from w  ww . j av  a 2s.c o m*/
 *
 * @author paouelle
 *
 * @see java.util.Map#values()
 */
@Override
public Collection<T> values() {
    if (vcol == null) {
        final Collection<PersistedValue<T, PT>> vcol = map.values();

        this.vcol = new AbstractCollection<T>() {
            @Override
            public int size() {
                return vcol.size();
            }

            @Override
            public boolean isEmpty() {
                return vcol.isEmpty();
            }

            @Override
            public Iterator<T> iterator() {
                return new TransformIterator<PersistedValue<T, PT>, T>(vcol.iterator()) {
                    @Override
                    protected T transform(PersistedValue<T, PT> pv) {
                        return pv.getDecodedValue();
                    }
                };
            }

            @Override
            public Stream<T> stream() {
                return vcol.stream().map(pv -> pv.getDecodedValue());
            }

            @Override
            public Stream<T> parallelStream() {
                return vcol.parallelStream().map(pv -> pv.getDecodedValue());
            }

            @Override
            public void clear() {
                vcol.clear();
            }

            @Override
            public String toString() {
                return vcol.toString();
            }
        };
    }
    return vcol;
}

From source file:edu.ksu.cis.indus.staticanalyses.concurrency.DeadlockAnalysisCLI.java

/**
 * This contains the driver logic.//from   w  w w.  j  a  v a 2  s  . c om
 * 
 * @param <T> dummy type parameter.
 */
private <T extends ITokens<T, Value>> void execute() {
    setInfoLogger(LOGGER);

    final String _tagName = "SideEffect:FA";
    final IValueAnalyzer<Value> _aa = OFAnalyzer.getFSOSAnalyzer(_tagName,
            TokenUtil.<T, Value, Type>getTokenManager(new SootValueTypeManager()), getStmtGraphFactory());
    final ValueAnalyzerBasedProcessingController _pc = new ValueAnalyzerBasedProcessingController();
    final Collection<IProcessor> _processors = new ArrayList<IProcessor>();
    final PairManager _pairManager = new PairManager(false, true);
    final CallGraphInfo _cgi = new CallGraphInfo(new PairManager(false, true));
    final MonitorAnalysis _monitorInfo = new MonitorAnalysis();
    final OFABasedCallInfoCollector _callGraphInfoCollector = new OFABasedCallInfoCollector();
    final IThreadGraphInfo _tgi = new ThreadGraph(_cgi, new CFGAnalysis(_cgi, getBbm()), _pairManager);
    final ValueAnalyzerBasedProcessingController _cgipc = new ValueAnalyzerBasedProcessingController();
    final OneAllStmtSequenceRetriever _ssr = new OneAllStmtSequenceRetriever();

    _ssr.setStmtGraphFactory(getStmtGraphFactory());

    _pc.setStmtSequencesRetriever(_ssr);
    _pc.setAnalyzer(_aa);
    _pc.setProcessingFilter(new TagBasedProcessingFilter(_tagName));

    _cgipc.setAnalyzer(_aa);
    _cgipc.setProcessingFilter(new CGBasedProcessingFilter(_cgi));
    _cgipc.setStmtSequencesRetriever(_ssr);

    final Map _info = new HashMap();
    _info.put(ICallGraphInfo.ID, _cgi);
    _info.put(IThreadGraphInfo.ID, _tgi);
    _info.put(PairManager.ID, _pairManager);
    _info.put(IEnvironment.ID, _aa.getEnvironment());
    _info.put(IValueAnalyzer.ID, _aa);

    initialize();
    _aa.analyze(getEnvironment(), getRootMethods());

    _processors.clear();
    _processors.add(_callGraphInfoCollector);
    _pc.reset();
    _pc.driveProcessors(_processors);
    _cgi.reset();
    _cgi.createCallGraphInfo(_callGraphInfoCollector.getCallInfo());
    writeInfo("CALL GRAPH:\n" + _cgi.toString());

    _processors.clear();
    ((ThreadGraph) _tgi).reset();
    _processors.add((IProcessor) _tgi);
    _cgipc.reset();
    _cgipc.driveProcessors(_processors);
    writeInfo("THREAD GRAPH:\n" + ((ThreadGraph) _tgi).toString());
    final EquivalenceClassBasedEscapeAnalysis _ecba = new EquivalenceClassBasedEscapeAnalysis(_cgi, _tgi,
            getBbm());
    final IEscapeInfo _escapeInfo = _ecba.getEscapeInfo();
    final AnalysesController _ac = new AnalysesController(_info, _cgipc, getBbm());
    _ac.addAnalyses(EquivalenceClassBasedEscapeAnalysis.ID, Collections.singleton(_ecba));
    _ac.addAnalyses(IMonitorInfo.ID, Collections.singleton(_monitorInfo));
    _ac.initialize();
    _ac.execute();
    writeInfo("END: Escape analysis");

    final LockAcquisitionBasedEquivalence _lbe = new LockAcquisitionBasedEquivalence(_escapeInfo, _cgi);
    _lbe.hookup(_cgipc);
    _cgipc.process();
    _lbe.unhook(_cgipc);

    System.out.println("Deadlock Analysis:");
    System.out.println("Total number of monitors: " + _monitorInfo.getMonitorTriples().size());
    calculateDeadlockInfo(_aa, _monitorInfo, null, null);
    calculateDeadlockInfo(_aa, _monitorInfo, _escapeInfo, null);
    calculateDeadlockInfo(_aa, _monitorInfo, null, _lbe);
    calculateDeadlockInfo(_aa, _monitorInfo, _escapeInfo, _lbe);
}