Example usage for java.util LinkedList isEmpty

List of usage examples for java.util LinkedList isEmpty

Introduction

In this page you can find the example usage for java.util LinkedList isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:net.spfbl.spf.SPF.java

/**
 * Merge nas listas de fixao de SPF.//w  ww  . j a v  a2s .c om
 *
 * @param midleList lista dos mecanismos centrais.
 * @param errorList lista dos mecanismos com erro de sintaxe.
 */
private static void mergeMechanism(LinkedList<String> midleList, LinkedList<String> errorList) {
    while (!errorList.isEmpty()) {
        boolean fixed = false;
        if (errorList.size() > 1) {
            for (int index = 1; index < errorList.size(); index++) {
                String tokenFix = errorList.getFirst();
                for (String tokenError : errorList.subList(1, index + 1)) {
                    tokenFix += tokenError;
                }
                if (isMechanismMiddle(tokenFix)) {
                    midleList.add(tokenFix);
                    int k = 0;
                    while (k++ <= index) {
                        errorList.removeFirst();
                    }
                    fixed = true;
                    break;
                }
            }

        }
        if (!fixed) {
            // No foi capaz de corrigir o erro.
            midleList.add(errorList.removeFirst());
        }
    }
}

From source file:com.ikanow.infinit.e.harvest.extraction.document.file.FileHarvester.java

private void processFiles(SourcePojo source) throws Exception {

    // Can override system settings if less:
    if ((null != source.getThrottleDocs()) && (source.getThrottleDocs() < maxDocsPerCycle)) {
        maxDocsPerCycle = source.getThrottleDocs();
    }//from w  w  w  . j  a v  a 2 s  .co m
    sourceUrlsGettingUpdated = new HashSet<String>();
    LinkedList<String> duplicateSources = new LinkedList<String>();
    try {
        // Compile regexes if they are present
        if ((null != source.getFileConfig()) && (null != source.getFileConfig().pathInclude)) {
            includeRegex = Pattern.compile(source.getFileConfig().pathInclude, Pattern.CASE_INSENSITIVE);
        }
        if ((null != source.getFileConfig()) && (null != source.getFileConfig().pathExclude)) {
            excludeRegex = Pattern.compile(source.getFileConfig().pathExclude, Pattern.CASE_INSENSITIVE);
        }
        if ((null != source.getFileConfig()) && (null != source.getFileConfig().maxDepth)) {
            this.maxDepth = source.getFileConfig().maxDepth;
        }

        // Process the fileshare
        getFiles(source);
    } catch (Exception e) {
        // If an exception here this is catastrophic, throw it upwards:
        errors++;
        throw e;
    }

    try {
        //Dedup code, ironically enough partly duplicated in parse(), probably unnecessarily
        DuplicateManager qr = _context.getDuplicateManager();
        for (DocumentPojo doc : files) {
            try {
                duplicateSources.clear();
                if (null != doc.getSourceUrl()) {

                    boolean add = true;

                    // However still need to check for duplicates so can update entities correctly (+maintain _ids, etc)
                    // We only do this if the source URL changes (unless URL is taken from the object in which case all bets are off) 

                    boolean sourceUrlUpdated = sourceUrlsGettingUpdated.contains(doc.getSourceUrl());
                    if (!doc.getHasDefaultUrl() || sourceUrlUpdated) { // src URL for a given URL                     
                        // (only if the the sourceUrl is not new...)
                        if (qr.isDuplicate_Url(doc.getUrl(), source, duplicateSources)) {
                            doc.setUpdateId(qr.getLastDuplicateId()); // (set _id to doc we're going to replace)

                            if (!sourceUrlUpdated && !_deleteExistingFilesBySourceKey) {
                                // Here update instead so we delete the old doc and add the new one
                                add = false;
                                docsToUpdate.add(doc);
                            } //TESTED
                            else {
                                // (else *still* don't add this to updates because we've added the source URL or source key to the delete list)
                                // (hence approximate create with the updateId...)
                                if (null != doc.getUpdateId()) {
                                    doc.setCreated(new Date(doc.getUpdateId().getTime()));
                                } //TESTED                           
                            } //TESTED
                        }
                        //(note we don't get about duplicate sources in this case - just too complex+rare a case)

                    } //TESTED (src url changing, different src url, non-default URL)

                    // For composite files we (almost always) delete everything that already exists (via docsToRemove) and then add new docs
                    if (add) {
                        docsToAdd.add(doc);
                    }
                    //TESTED
                } else if (qr.isDuplicate_Url(doc.getUrl(), source, duplicateSources)) {
                    // Other files, if the file already exists then update it (essentially, delete/add)
                    doc.setUpdateId(qr.getLastDuplicateId()); // (set _id to doc we're going to replace)
                    docsToUpdate.add(doc);
                } else { // if duplicateSources is non-empty then this URL is a duplicate of one from a different source 
                    if (!duplicateSources.isEmpty()) {
                        doc.setDuplicateFrom(duplicateSources.getFirst());
                    }
                    docsToAdd.add(doc);
                }
            } catch (Exception e) {
                errors++;
                _context.getHarvestStatus()
                        .logMessage(HarvestExceptionUtils.createExceptionMessage(e).toString(), true);
            }
        }
    } catch (Exception e) {
        // If an exception here this is catastrophic, throw it upwards:
        errors++;
        throw e;
    }
}

From source file:org.hammurapi.HammurapiTask.java

public void execute() throws BuildException {
    long started = System.currentTimeMillis();

    if (!suppressLogo) {
        log("Hammurapi 3.18.4 Copyright (C) 2004 Hammurapi Group");
    }/*from w  w  w.j  a  va  2  s  . co m*/

    File archiveTmpDir = processArchive();

    try {
        Logger logger = new AntLogger(this);

        final VisitorStack[] visitorStack = { null };
        final VisitorStackSource visitorStackSource = new VisitorStackSource() {
            public VisitorStack getVisitorStack() {
                return visitorStack[0];
            }
        };

        final SessionImpl reviewSession = new SessionImpl();

        InspectorSet inspectorSet = new InspectorSet(new InspectorContextFactory() {
            public InspectorContext newContext(InspectorDescriptor descriptor, Logger logger) {
                return new InspectorContextImpl(descriptor, logger, visitorStackSource, reviewSession,
                        violationFilters);
            }
        }, logger);

        if (embeddedInspectors) {
            log("Loading embedded inspectors", Project.MSG_VERBOSE);
            loadEmbeddedInspectors(inspectorSet);
        }

        log("Loading inspectors", Project.MSG_VERBOSE);
        Iterator it = inspectors.iterator();
        while (it.hasNext()) {
            Object o = it.next();
            if (o instanceof InspectorSource) {
                ((InspectorSource) o).loadInspectors(inspectorSet);
            } else {
                InspectorEntry inspectorEntry = (InspectorEntry) o;
                inspectorSet.addDescriptor(inspectorEntry);
                inspectorSet.addInspectorSourceInfo(
                        new InspectorSourceInfo("Inline inspector " + inspectorEntry.getName(),
                                "Build file: " + inspectorEntry.getLocation().toString(), ""));
            }
        }

        log("Inspectors loaded: " + inspectorSet.size(), Project.MSG_VERBOSE);

        log("Loading waivers", Project.MSG_VERBOSE);
        Date now = new Date();
        WaiverSet waiverSet = new WaiverSet();
        it = waivers.iterator();
        while (it.hasNext()) {
            ((WaiverSource) it.next()).loadWaivers(waiverSet, now);
        }

        log("Waivers loaded: " + waiverSet.size(), Project.MSG_VERBOSE);

        log("Loading listeners", Project.MSG_VERBOSE);
        List listeners = new LinkedList();
        it = listenerEntries.iterator();
        while (it.hasNext()) {
            listeners.add(((ListenerEntry) it.next()).getObject(null));
        }

        //Outputs
        listeners.addAll(outputs);
        listeners.add(new ReviewToLogListener(project));

        log("Loading source files", Project.MSG_VERBOSE);

        RepositoryConfig config = new RepositoryConfig();
        if (classPath != null) {
            log("Loading class files to repository", Project.MSG_DEBUG);
            config.setClassLoader(new AntClassLoader(project, classPath, false));
            reviewSession.setClassPath(classPath.list());
        }

        config.setLogger(logger);
        config.setCalculateDependencies(calculateDependencies);
        config.setStoreSource(storeSource);

        it = srcFileSets.iterator();
        while (it.hasNext()) {
            HammurapiFileSet fs = (HammurapiFileSet) it.next();
            fs.setDefaultIncludes();
            DirectoryScanner scanner = fs.getDirectoryScanner(project);
            config.addFile(scanner.getBasedir(), scanner.getIncludedFiles());
        }

        /**
         * For command-line interface
         */
        it = srcFiles.iterator();
        while (it.hasNext()) {
            config.addFile((File) it.next());
        }

        config.setName(title);

        if (revisionMapper != null) {
            config.setRevisionMapper((RevisionMapper) revisionMapper.getObject(null));
        }

        ConnectionPerThreadDataSource dataSource = createDataSource(reviewSession);

        reviewSession.setDatasource(dataSource);

        final LinkedList repoWarnings = new LinkedList();
        config.setWarningSink(new WarningSink() {
            public void consume(final String source, final String message) {
                repoWarnings.add(new Violation() {
                    public String getMessage() {
                        return message;
                    }

                    public InspectorDescriptor getDescriptor() {
                        return null;
                    }

                    SourceMarker sm = new SimpleSourceMarker(0, 0, source, null);

                    public SourceMarker getSource() {
                        return sm;
                    }

                    public int compareTo(Object obj) {
                        if (obj instanceof Violation) {
                            Violation v = (Violation) obj;
                            int c = SourceMarkerComparator._compare(getSource(), v.getSource());
                            return c == 0 ? getMessage().compareTo(v.getMessage()) : c;
                        }

                        return hashCode() - obj.hashCode();
                    }
                });
            }
        });

        config.setDataSource(dataSource);
        final SQLProcessor sqlProcessor = new SQLProcessor(dataSource, null);
        sqlProcessor.setTimeIntervalCategory(tic);

        DbRepositoryImpl repositoryImpl = new DbRepositoryImpl(config);
        Repository repository = wrap ? (Repository) repositoryImpl.getProxy() : repositoryImpl;

        //new SimpleResultsFactory(waiverSet).install();

        ResultsFactoryConfig rfConfig = new ResultsFactoryConfig();
        rfConfig.setInspectorSet(inspectorSet);
        rfConfig.setName(title);
        rfConfig.setReportNumber(repository.getScanNumber());
        rfConfig.setRepository(repository);
        rfConfig.setSqlProcessor(sqlProcessor);
        rfConfig.setHostId(hostId);
        rfConfig.setBaseLine(baseLine);
        rfConfig.setDescription(reviewDescription);

        try {
            rfConfig.setHostName(InetAddress.getLocalHost().getHostName());
        } catch (Exception e) {
            log("Cannot resolve host name: " + e);
        }

        CompositeStorage storage = new CompositeStorage();
        storage.addStorage("jdbc", new JdbcStorage(sqlProcessor));
        storage.addStorage("file",
                new FileStorage(new File(System.getProperties().getProperty("java.io.tmpdir"))));
        storage.addStorage("memory", new MemoryStorage());

        rfConfig.setStorage(storage);
        rfConfig.setWaiverSet(waiverSet);

        ResultsFactory resultsFactory = new ResultsFactory(rfConfig);
        resultsFactory.install();

        CompositeResults summary = ResultsFactory.getInstance().newCompositeResults(title);
        ResultsFactory.getInstance().setSummary(summary);
        ResultsFactory.pushThreadResults(summary);

        Collection inspectorsPerSe = new LinkedList(inspectorSet.getInspectors());
        reviewSession.setInspectors(inspectorSet);
        Iterator inspectorsIt = inspectorsPerSe.iterator();
        log("Inspectors mapping", Project.MSG_VERBOSE);
        while (inspectorsIt.hasNext()) {
            Inspector inspector = (Inspector) inspectorsIt.next();
            log("\t" + inspector.getContext().getDescriptor().getName() + " -> "
                    + inspector.getClass().getName(), Project.MSG_VERBOSE);
        }

        // Initializes listeners
        it = listeners.iterator();
        while (it.hasNext()) {
            ((Listener) it.next()).onBegin(inspectorSet);
        }

        Iterator vfit = violationFilters.iterator();
        while (vfit.hasNext()) {
            Object vf = vfit.next();
            if (vf instanceof DataAccessObject) {
                ((DataAccessObject) vf).setSQLProcessor(sqlProcessor);
            }
        }

        ResultsCollector collector = new ResultsCollector(this, inspectorSet, waiverSet, summary, listeners);
        inspectorsPerSe.add(collector);

        // Storing repo warnings 
        while (!repoWarnings.isEmpty()) {
            collector.getSummary().addWarning((Violation) repoWarnings.removeFirst());
        }

        log("Reviewing", Project.MSG_VERBOSE);

        inspectorsPerSe.add(new ViolationFilterVisitor());

        SimpleReviewEngine rengine = new SimpleReviewEngine(inspectorsPerSe, this);
        reviewSession.setVisitor(rengine.getVisitor());
        visitorStack[0] = rengine.getVisitorStack();

        rengine.review(repository);

        writeWaiverStubs(waiverSet.getRejectedRequests());

        ResultsFactory.getInstance().commit(System.currentTimeMillis() - started);

        if (cleanup) {
            repositoryImpl.cleanupOldScans();
            resultsFactory.cleanupOldReports();
        }

        repositoryImpl.shutdown();
        reviewSession.shutdown();
        resultsFactory.shutdown();
        dataSource.shutdown();

        //log("SQL metrics:\n"+resultsFactory.getSQLMetrics(),Project.MSG_VERBOSE);

        if (hadExceptions) {
            throw new BuildException("There have been exceptions during execution. Check log output.");
        }
    } catch (JselException e) {
        throw new BuildException(e);
    } catch (HammurapiException e) {
        throw new BuildException(e);
    } catch (ConfigurationException e) {
        throw new BuildException(e);
    } catch (FileNotFoundException e) {
        throw new BuildException(e);
    } catch (ClassNotFoundException e) {
        throw new BuildException(e);
    } catch (IOException e) {
        throw new BuildException(e);
    } catch (SQLException e) {
        throw new BuildException(e);
    } catch (RenderingException e) {
        throw new BuildException(e);
    } finally {
        if (archiveTmpDir != null) {
            deleteFile(archiveTmpDir);
        }
    }
}

From source file:org.gcaldaemon.core.Synchronizer.java

final byte[] syncronizeNow(CachedCalendar calendar) throws Exception {
    log.debug("Starting Google Calendar synchronizer...");

    // Create processing variables
    boolean remoteEventChanged;
    Event entry;//  w  w w  . j  ava  2 s  .  c o m
    String uid, remoteUID;
    long remoteDate;
    Long storedDate;
    VEvent event;
    int i;

    // Load offline history
    loadEventRegistry();

    // Get historical parameters
    HashMap uids = (HashMap) eventRegistry.get(calendar.url);
    if (uids == null) {
        uids = new HashMap();
    }

    // Processed unique IDs
    HashSet processedUids = new HashSet();

    // Parse ics files
    Calendar localCalendar = ICalUtilities.parseCalendar(calendar.body);
    Calendar remoteCalendar = ICalUtilities.parseCalendar(calendar.previousBody);

    // Get local and remote changes
    VEvent[] localChanges = ICalUtilities.getNewEvents(remoteCalendar, localCalendar, true, calendar.url);
    VEvent[] remoteChanges = ICalUtilities.getNewEvents(localCalendar, remoteCalendar, false, null);

    // Updatable and removable events
    LinkedList insertableList = new LinkedList();
    LinkedList updatableList = new LinkedList();
    LinkedList removableList = new LinkedList();

    // Process local changes
    for (i = 0; i < localChanges.length; i++) {
        event = localChanges[i];
        uid = ICalUtilities.getUid(event);
        if (uid == null) {
            log.error("Invalid ical file (missing event ID)!");
            continue;
        }

        // Find remote pair
        entry = GCalUtilities.findEvent(calendar, event);
        if (entry == null) {
            if (uids.containsKey(uid)) {

                // Event removed at Google side -> download & remove
                if (log.isDebugEnabled()) {
                    log.debug("Removed event (" + ICalUtilities.getEventTitle(event)
                            + ") found in the Google Calendar.");
                }
            } else {

                // New local event -> insert
                if (log.isDebugEnabled()) {
                    log.debug("New event (" + ICalUtilities.getEventTitle(event)
                            + ") found in the local calendar.");
                }
                insertableList.addLast(event);
            }
        } else {

            // Add local and remote ID to processed UIDs
            processedUids.add(entry.getId());

            // Get remote event's modification date
            remoteDate = entry.getUpdated().getValue();
            storedDate = (Long) uids.get(uid);
            remoteEventChanged = true;
            if (storedDate == null) {
                remoteUID = GCalUtilities.getRemoteUID(calendar, uid);
                if (remoteUID != null) {
                    storedDate = (Long) uids.get(remoteUID);
                }
            }
            if (storedDate != null) {

                // FIXME If a 'reminder' changes in GCal singly,
                // Google Calendar does NOT update the LAST_MODIFIED
                // timestamp. Otherwise this comparison works.
                // there is no ms info in ics file
                remoteEventChanged = storedDate.longValue() != remoteDate / 1000 * 1000;
            }
            if (remoteEventChanged) {

                // Event modified at Google side -> download & update
                if (log.isDebugEnabled()) {
                    log.debug("Updated event (" + ICalUtilities.getEventTitle(event)
                            + ") found in the Google Calendar.");
                }
            } else {

                // Local event modified -> update
                if (log.isDebugEnabled()) {
                    log.debug("Updated event (" + ICalUtilities.getEventTitle(event)
                            + ") found in the local calendar.");
                }
                updatableList.addLast(event);
            }
        }
    }

    // Process remote changes
    for (i = 0; i < remoteChanges.length; i++) {
        event = remoteChanges[i];

        // Verify remote ID
        entry = GCalUtilities.findEvent(calendar, event);
        if (entry == null || processedUids.contains(entry.getId())) {
            continue;
        }

        // Verify local ID
        uid = ICalUtilities.getUid(event);
        if (uid == null) {
            log.error("Invalid ical file (missing event ID)!");
            continue;
        }

        // Find ID in history
        if (uids.containsKey(uid)) {

            // Local event removed -> remove event
            if (log.isDebugEnabled()) {
                log.debug("Removed event (" + ICalUtilities.getEventTitle(event)
                        + ") found in the local calendar.");
            }
            removableList.addLast(event);
        } else {

            // New remote event -> download & create
            if (log.isDebugEnabled()) {
                log.debug(
                        "New event (" + ICalUtilities.getEventTitle(event) + ") found in the Google Calendar.");
            }
        }
    }

    // Check changes
    if (localChanges.length == 0 && remoteChanges.length == 0) {

        // Save offline registry
        saveEventRegistry(calendar.url, calendar.previousBody);

        // Return previous body
        return calendar.previousBody;
    }

    // Show progress monitor
    if (monitor != null) {
        monitor.setVisible(true);
    }
    try {

        // Do modifications
        if (!removableList.isEmpty() && deleteEnabled) {

            // Remove Google entries
            VEvent[] events = new VEvent[removableList.size()];
            removableList.toArray(events);
            GCalUtilities.removeEvents(calendar, events);
        }
        VTimeZone[] timeZones;
        if (!updatableList.isEmpty() || !insertableList.isEmpty()) {

            // Get timezones
            timeZones = ICalUtilities.getTimeZones(localCalendar);
        } else {
            timeZones = new VTimeZone[0];
        }
        if (!updatableList.isEmpty()) {

            // Update Google entries
            VEvent[] events = new VEvent[updatableList.size()];
            updatableList.toArray(events);
            GCalUtilities.updateEvents(calendar, timeZones, events);
        }
        if (!insertableList.isEmpty()) {

            // Insert new Google entries
            VEvent[] events = new VEvent[insertableList.size()];
            insertableList.toArray(events);
            GCalUtilities.insertEvents(calendar, timeZones, events);
        }

        // Load new calendar from Google
        byte[] newBytes = GCalUtilities.loadCalendar(calendar);

        // Save offline registry
        saveEventRegistry(calendar.url, newBytes);

        // Return new ics file
        return newBytes;
    } finally {

        // Hide progress monitor
        if (monitor != null) {
            try {
                monitor.setVisible(false);
            } catch (Throwable ignored) {
            }
        }
    }
}

From source file:org.jahia.utils.maven.plugin.contentgenerator.bo.PageBO.java

private void buildPageElement() {

    pageElement = new Element(getName());
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_JCR);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_NT);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_JNT);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_TEST);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_SV);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_JMIX);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_J);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_SV);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_REP);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_WEM);

    pageElement.setAttribute("changefreq", "monthly");
    pageElement.setAttribute("templateName", pageTemplate, ContentGeneratorCst.NS_J);
    pageElement.setAttribute("primaryType", "jnt:page", ContentGeneratorCst.NS_JCR);
    pageElement.setAttribute("priority", "0.5");

    String mixinTypes = "jmix:sitemap";
    if (hasVanity) {
        mixinTypes = mixinTypes + " jmix:vanityUrlMapped";
    }/*  ww w .  ja  v a  2  s.c o  m*/
    pageElement.setAttribute("mixinTypes", mixinTypes, ContentGeneratorCst.NS_JCR);

    if (idCategory != null) {
        pageElement.setAttribute("jcategorized", StringUtils.EMPTY, ContentGeneratorCst.NS_JMIX);
        pageElement.setAttribute("defaultCategory", "/sites/systemsite/categories/category" + idCategory,
                ContentGeneratorCst.NS_J);
    }

    if (idTag != null) {
        pageElement.setAttribute("tags", "/sites/" + siteKey + "/tags/tag" + idTag, ContentGeneratorCst.NS_J);
    }

    // articles
    for (Map.Entry<String, ArticleBO> entry : articles.entrySet()) {
        Element translationNode = new Element("translation_" + entry.getKey(), ContentGeneratorCst.NS_J);
        translationNode.setAttribute("language", entry.getKey(), ContentGeneratorCst.NS_JCR);
        translationNode.setAttribute("mixinTypes", "mix:title", ContentGeneratorCst.NS_JCR);
        translationNode.setAttribute("primaryType", "jnt:translation", ContentGeneratorCst.NS_JCR);
        translationNode.setAttribute("title", entry.getValue().getTitle(), ContentGeneratorCst.NS_JCR);

        if (StringUtils.isNotEmpty(description)) {
            translationNode.setAttribute("description", description, ContentGeneratorCst.NS_JCR);
        }
        pageElement.addContent(translationNode);
    }

    if (!acls.isEmpty()) {
        Element aclNode = new Element("acl", ContentGeneratorCst.NS_J);
        aclNode.setAttribute("inherit", "true", ContentGeneratorCst.NS_J);
        aclNode.setAttribute("primaryType", "jnt:acl", ContentGeneratorCst.NS_JCR);

        for (Map.Entry<String, List<String>> entry : acls.entrySet()) {
            String roles = "";
            for (String s : entry.getValue()) {
                roles += s + " ";
            }
            Element aceNode = new Element("GRANT_" + entry.getKey().replace(":", "_"));
            aceNode.setAttribute("aceType", "GRANT", ContentGeneratorCst.NS_J);
            aceNode.setAttribute("principal", entry.getKey(), ContentGeneratorCst.NS_J);
            aceNode.setAttribute("protected", "false", ContentGeneratorCst.NS_J);
            aceNode.setAttribute("roles", roles.trim(), ContentGeneratorCst.NS_J);
            aceNode.setAttribute("primaryType", "jnt:ace", ContentGeneratorCst.NS_JCR);

            aclNode.addContent(aceNode);
        }
        pageElement.addContent(aclNode);
    }

    // begin content list
    Element listNode = new Element("listA");
    listNode.setAttribute("primaryType", "jnt:contentList", ContentGeneratorCst.NS_JCR);

    LinkedList<Element> personalizableElements = new LinkedList<Element>();

    if (pageTemplate.equals(ContentGeneratorCst.PAGE_TPL_QALIST)) {

        List<String> languages = new ArrayList<String>();
        for (Map.Entry<String, ArticleBO> entry : articles.entrySet()) {
            languages.add(entry.getKey());
        }
        for (int i = 1; i <= ContentGeneratorCst.NB_NEWS_IN_QALIST; i++) {
            Element newsNode = new NewsBO(namePrefix + "-" + "news" + i, languages).getElement();
            listNode.addContent(newsNode);
            if (i <= ContentGeneratorCst.NB_NEWS_PER_PAGE_IN_QALIST) {
                // News are split to multiple pages by Jahia at runtime, so only personalize items present on the first page.
                personalizableElements.add(newsNode);
            }
        }
    } else if (pageTemplate.equals(ContentGeneratorCst.PAGE_TPL_DEFAULT)) {
        for (int i = 1; i <= numberBigText.intValue(); i++) {
            Element bigTextNode = new Element("bigText_" + i);
            bigTextNode.setAttribute("primaryType", "jnt:bigText", ContentGeneratorCst.NS_JCR);
            bigTextNode.setAttribute("mixinTypes", "jmix:renderable", ContentGeneratorCst.NS_JCR);
            for (Map.Entry<String, ArticleBO> entry : articles.entrySet()) {
                Element translationNode = new Element("translation_" + entry.getKey(),
                        ContentGeneratorCst.NS_J);
                translationNode.setAttribute("language", entry.getKey(), ContentGeneratorCst.NS_JCR);
                translationNode.setAttribute("primaryType", "jnt:translation", ContentGeneratorCst.NS_JCR);
                translationNode.setAttribute("text", entry.getValue().getContent());
                bigTextNode.addContent(translationNode);
            }
            listNode.addContent(bigTextNode);
            personalizableElements.add(bigTextNode);
        }
    }

    // for pages with external/internal file reference, we check the page name
    if (StringUtils.startsWith(namePrefix, ContentGeneratorCst.PAGE_TPL_QAEXTERNAL)) {
        for (int i = 0; i < externalFilePaths.size(); i++) {
            String externalFilePath = externalFilePaths.get(i);
            Element externalFileReference = new Element("external-file-reference-" + i);
            externalFileReference.setAttribute("node", "/mounts/" + ContentGeneratorCst.CMIS_MOUNT_POINT_NAME
                    + "/Sites/" + cmisSite + externalFilePath, ContentGeneratorCst.NS_J);
            externalFileReference.setAttribute("primaryType", "jnt:fileReference", ContentGeneratorCst.NS_JCR);
            listNode.addContent(externalFileReference);
            personalizableElements.add(externalFileReference);
        }
    }

    if (StringUtils.startsWith(namePrefix, ContentGeneratorCst.PAGE_TPL_QAINTERNAL) && fileName != null) {

        Element randomFileNode = new Element("rand-file");
        randomFileNode.setAttribute("primaryType", "jnt:fileReference", ContentGeneratorCst.NS_JCR);

        Element fileTranslationNode = new Element("translation_en", ContentGeneratorCst.NS_J);
        fileTranslationNode.setAttribute("language", "en", ContentGeneratorCst.NS_JCR);
        fileTranslationNode.setAttribute("primaryType", "jnt:translation", ContentGeneratorCst.NS_JCR);
        fileTranslationNode.setAttribute("title", "My file", ContentGeneratorCst.NS_JCR);

        randomFileNode.addContent(fileTranslationNode);

        Element publicationNode = new Element("publication");
        publicationNode.setAttribute("primaryType", "jnt:publication", ContentGeneratorCst.NS_JCR);

        Element publicationTranslationNode = new Element("translation_en", ContentGeneratorCst.NS_J);
        publicationTranslationNode.setAttribute("author", "Jahia Content Generator");
        publicationTranslationNode.setAttribute("body", "&lt;p&gt;  Random publication&lt;/p&gt;");
        publicationTranslationNode.setAttribute("title", "Random publication", ContentGeneratorCst.NS_JCR);
        publicationTranslationNode.setAttribute("file", "/sites/" + siteKey + "/files/contributed/"
                + org.apache.jackrabbit.util.ISO9075.encode(fileName));
        publicationTranslationNode.setAttribute("language", "en", ContentGeneratorCst.NS_JCR);
        publicationTranslationNode.setAttribute("primaryType", "jnt:translation", ContentGeneratorCst.NS_JCR);
        publicationTranslationNode.setAttribute("source", "Jahia");

        publicationNode.addContent(publicationTranslationNode);

        listNode.addContent(publicationNode);
    }

    if (personalized) {
        if (personalizableElements.isEmpty()) {
            personalized = false;
            pageElement.setName(getName()); // Re-set the root element name: it must change according to page personalization change.
        } else {
            Element element = personalizableElements
                    .get(ThreadLocalRandom.current().nextInt(personalizableElements.size()));
            int elementIndex = listNode.indexOf(element);
            listNode.removeContent(element);
            element = getPersonalizedElement(element);
            listNode.addContent(elementIndex, element);
        }
    }

    // end content list
    pageElement.addContent(listNode);

    if (hasVanity) {

        Element vanityNode = new Element("vanityUrlMapping");
        vanityNode.setAttribute("primaryType", "jnt:vanityUrls", ContentGeneratorCst.NS_JCR);

        Element vanitySubNode = new Element(namePrefix);
        vanitySubNode.setAttribute("active", "true", ContentGeneratorCst.NS_J);
        vanitySubNode.setAttribute("default", "true", ContentGeneratorCst.NS_J);
        vanitySubNode.setAttribute("url", "/" + namePrefix, ContentGeneratorCst.NS_J);
        vanitySubNode.setAttribute("language", "en", ContentGeneratorCst.NS_JCR);
        vanitySubNode.setAttribute("primaryType", "jnt:vanityUrl", ContentGeneratorCst.NS_JCR);

        vanityNode.addContent(vanitySubNode);
        pageElement.addContent(vanityNode);
    }

    if (visibilityEnabled) {

        Element visibilityNode = new Element("conditionalVisibility", ContentGeneratorCst.NS_J);
        visibilityNode.setAttribute("conditionalVisibility", null, ContentGeneratorCst.NS_J);
        visibilityNode.setAttribute("forceMatchAllConditions", "true", ContentGeneratorCst.NS_J);
        visibilityNode.setAttribute("primaryType", "jnt:conditionalVisibility", ContentGeneratorCst.NS_JCR);

        Element visibilityConditionNode = new Element("startEndDateCondition0", ContentGeneratorCst.NS_JNT);
        visibilityConditionNode.setAttribute("primaryType", "jnt:startEndDateCondition",
                ContentGeneratorCst.NS_JCR);
        visibilityConditionNode.setAttribute("start", visibilityStartDate);
        visibilityConditionNode.setAttribute("end", visibilityEndDate);

        visibilityNode.addContent(visibilityConditionNode);
        pageElement.addContent(visibilityNode);
    }

    if (null != subPages) {
        for (Iterator<PageBO> iterator = subPages.iterator(); iterator.hasNext();) {
            PageBO subPage = iterator.next();
            pageElement.addContent(subPage.getElement());
        }
    }
}

From source file:de.uni_koblenz.jgralab.utilities.rsa.Rsa2Tg.java

private List<EdgeClass> getEdgeClassesInTopologicalOrder() {
    List<EdgeClass> result = new ArrayList<EdgeClass>();
    Map<EdgeClass, Integer> numberOfPredecessors = new HashMap<EdgeClass, Integer>();
    LinkedList<EdgeClass> zeroValued = new LinkedList<EdgeClass>();

    for (EdgeClass ec : sg.getEdgeClassVertices()) {
        if (!BinaryEdgeClass.class.isInstance(ec)) {
            int numberOfPred = ec.getDegree(SpecializesTypedElementClass_subclass.class);
            if (numberOfPred == 0) {
                zeroValued.add(ec);/*from   ww  w  .j  ava2 s  .  com*/
            } else {
                numberOfPredecessors.put(ec, numberOfPred);
            }
        }
    }

    while (!zeroValued.isEmpty()) {
        EdgeClass current = zeroValued.removeFirst();
        result.add(current);
        for (SpecializesEdgeClass sec : current.getIncidentEdges(SpecializesEdgeClass.class,
                de.uni_koblenz.jgralab.Direction.EDGE_TO_VERTEX)) {
            EdgeClass otherEnd = (EdgeClass) sec.getAlpha();
            Integer numberOfPred = numberOfPredecessors.get(otherEnd);
            if (numberOfPred != null) {
                if (numberOfPred == 1) {
                    numberOfPredecessors.remove(otherEnd);
                    zeroValued.add(otherEnd);
                } else {
                    numberOfPredecessors.put(otherEnd, --numberOfPred);
                }
            }
        }
    }

    if (numberOfPredecessors.isEmpty()) {
        return result;
    } else {
        return null;
    }
}

From source file:com.cognizant.trumobi.PersonaLauncher.java

private void bindAppWidgets(PersonaLauncher.DesktopBinder binder,
        LinkedList<PersonaLauncherAppWidgetInfo> appWidgets) {

    final PersonaWorkspace personaWorkspace = mWorkspace;
    final boolean desktopLocked = mDesktopLocked;

    if (!appWidgets.isEmpty()) {
        final PersonaLauncherAppWidgetInfo item = appWidgets.removeFirst();

        final int appWidgetId = item.appWidgetId;
        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);

        if (LOGD) {
            PersonaLog.d(LOG_TAG,/*w w w .  j a va  2 s  .  c  o  m*/
                    String.format("about to setAppWidget for id=%d, info=%s", appWidgetId, appWidgetInfo));
        }

        item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
        item.hostView.setTag(item);

        personaWorkspace.addInScreen(item.hostView, item.screen, item.cellX, item.cellY, item.spanX, item.spanY,
                !desktopLocked);

        personaWorkspace.requestLayout();
        // finish load a widget, send it an intent
        if (appWidgetInfo != null)
            appwidgetReadyBroadcast(appWidgetId, appWidgetInfo.provider, new int[] { item.spanX, item.spanY });
    }

    if (appWidgets.isEmpty()) {
        if (PROFILE_ROTATE) {
            android.os.Debug.stopMethodTracing();
        }
    } else {
        binder.obtainMessage(DesktopBinder.MESSAGE_BIND_APPWIDGETS).sendToTarget();
    }
}

From source file:hudson.plugins.project_inheritance.projects.InheritanceProject.java

/**
 * Tests if this project's configuration leads to a cyclic, diamond or
 * multiple dependency.<br/>/*from www .j  a v  a2s  . co  m*/
 * <br/>
 * See <a href="http://en.wikipedia.org/wiki/Cycle_detection">cycle detection</a> and
 * <a href="http://en.wikipedia.org/wiki/Diamond_problem">diamond problem</a>.
 * 
 * @return true, if there is a cyclic, diamond or repeated dependency among
 * this project's parents.
 */
public final boolean hasCyclicDependency(String... whenTheseProjectsAdded) {
    /* TODO: While this method runs reasonably fast, it is run very often
     * As such, find a way to buffer the result across all projects and
     * only rebuild if necessary.
     */

    /* TODO: Further more, this method is not space-optimal
     * See: http://en.wikipedia.org/wiki/Cycle_detection
     * But do note that any replacement algorithm also, by contract, needs
     * to detect multiple inheritance and its special case of diamond
     * inheritance.
     */

    //Preparing the set of project names that were seen at least once
    HashSet<String> closed = new HashSet<String>();

    //Creating the list of parent projects to still explore
    LinkedList<InheritanceProject> open = new LinkedList<InheritanceProject>();
    //And scheduling ourselves as the first to evaluate
    open.push(this);

    //And finally, creating a list of additional references the caller
    //wishes to eventually add to THIS project
    LinkedList<String> additionalRefs = new LinkedList<String>();
    for (String pName : whenTheseProjectsAdded) {
        //We need to ignore those, that we already refer to as parents
        //Do note that this makes direct multiple inheritance impossible
        //to detect in advance, but such errors should be obvious anyway
        boolean isAlreadyReferenced = false;
        for (AbstractProjectReference par : this.getParentReferences()) {
            if (par.getName().equals(pName)) {
                isAlreadyReferenced = true;
                break;
            }
        }
        if (!isAlreadyReferenced) {
            additionalRefs.add(pName);
        }
    }

    //Processing the open stack, checking if we're already met that parent
    //and if not, adding its parent to our open stack
    while (open.isEmpty() == false) {
        //Popping the first element
        InheritanceProject p = open.pop();
        //Checking if we've seen that parent already
        if (closed.contains(p.name)) {
            //Detected a cyclic dependency
            return true;
        }
        // Otherwise, we add all its parents to our open set
        for (AbstractProjectReference ref : p.getParentReferences()) {
            InheritanceProject refP = ref.getProject();
            if (refP != null) {
                open.push(refP);
            }
        }
        //And if the current object is active, we also need to check the
        //new future refs
        if (p == this && !additionalRefs.isEmpty()) {
            for (String ref : additionalRefs) {
                InheritanceProject ip = InheritanceProject.getProjectByName(ref);
                if (ip != null) {
                    open.push(ip);
                }
            }
        }
        closed.add(p.name);
    }
    // If we reach this spot, there is no such dependency
    return false;
}

From source file:org.hyperledger.fabric.sdk.Channel.java

void runSweeper() {

    if (shutdown || DELTA_SWEEP < 1) {
        return;/* w  ww .  jav  a2s.  co  m*/
    }

    if (sweeper == null) {

        sweeperExecutorService = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            return t;
        });
        sweeper = sweeperExecutorService.scheduleAtFixedRate(() -> {
            try {

                if (txListeners != null) {

                    synchronized (txListeners) {

                        for (Iterator<Map.Entry<String, LinkedList<TL>>> it = txListeners.entrySet()
                                .iterator(); it.hasNext();) {

                            Map.Entry<String, LinkedList<TL>> es = it.next();

                            LinkedList<TL> tlLinkedList = es.getValue();
                            tlLinkedList.removeIf(TL::sweepMe);
                            if (tlLinkedList.isEmpty()) {
                                it.remove();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                logger.warn("Sweeper got error:" + e.getMessage(), e);
            }

        }, 0, DELTA_SWEEP, TimeUnit.MILLISECONDS);
    }

}

From source file:net.spfbl.spf.SPF.java

/**
 * Consulta o registro SPF nos registros DNS do domnio. Se houver mais de
 * dois registros diferentes, realiza o merge do forma a retornar um nico
 * registro.// w ww .j  a v a2 s. c o  m
 *
 * @param hostname o nome do hostname para consulta do SPF.
 * @param bgWhenUnavailable usar best-guess quando houver erro temporrio
 * para alcanar o registro.
 * @return o registro SPF consertado, padronuzado e mergeado.
 * @throws ProcessException
 */
private static LinkedList<String> getRegistrySPF(String hostname, boolean bgWhenUnavailable)
        throws ProcessException {
    LinkedList<String> registryList = new LinkedList<String>();
    try {
        //            if (CacheGuess.containsExact(hostname)) {
        //                // Sempre que houver registro de
        //                // chute, sobrepor registro atual.
        //                registryList.add(CacheGuess.get(hostname));
        //            } else {
        //                // Caso contrrio procurar nos
        //                // registros oficiais do domnio.
        try {
            Attributes attributes = Server.getAttributesDNS(hostname, new String[] { "SPF" });
            Attribute attribute = attributes.get("SPF");
            if (attribute != null) {
                for (int index = 0; index < attribute.size(); index++) {
                    String registry = (String) attribute.get(index);
                    if (registry.contains("v=spf1 ")) {
                        registry = fixRegistry(registry);
                        if (!registryList.contains(registry)) {
                            registryList.add(registry);
                        }
                    }
                }
            }
        } catch (InvalidAttributeIdentifierException ex) {
            // No encontrou registro SPF.
        }
        if (registryList.isEmpty()) {
            try {
                Attributes attributes = Server.getAttributesDNS(hostname, new String[] { "TXT" });
                Attribute attribute = attributes.get("TXT");
                if (attribute != null) {
                    for (int index = 0; index < attribute.size(); index++) {
                        String registry = (String) attribute.get(index);
                        if (registry.contains("v=spf1 ")) {
                            registry = fixRegistry(registry);
                            if (!registryList.contains(registry)) {
                                registryList.add(registry);
                            }
                        }
                    }

                }
            } catch (InvalidAttributeIdentifierException ex2) {
                // No encontrou registro TXT.
            }
        }
        //            }
        if (registryList.isEmpty()) {
            //                hostname = "." + hostname;
            //                if (CacheGuess.containsExact(hostname)) {
            //                    // Significa que um palpite SPF
            //                    // foi registrado para este hostname.
            //                    // Neste caso utilizar o paltpite especfico.
            //                    registryList.add(CacheGuess.get(hostname));
            //                } else {
            //                    // Se no hoouver palpite especfico para o hostname,
            //                    // utilizar o palpite padro, porm adaptado para IPv6.
            //                    // http://www.openspf.org/FAQ/Best_guess_record
            //                    registryList.add(CacheGuess.BEST_GUESS);
            //                }

            // Como o domnio no tem registro SPF,
            // utilizar um registro SPF de chute do sistema.
            String guess = CacheGuess.get(hostname);
            registryList.add(guess);
        }
        return registryList;
    } catch (NameNotFoundException ex) {
        return null;
    } catch (NamingException ex) {
        if (bgWhenUnavailable) {
            // Na indisponibilidade do DNS
            // utilizar um registro SPF de chute do sistema.
            String guess = CacheGuess.get(hostname);
            registryList.add(guess);
            return registryList;
        } else if (ex instanceof CommunicationException) {
            throw new ProcessException("ERROR: DNS UNAVAILABLE");
        } else {
            throw new ProcessException("ERROR: DNS UNAVAILABLE", ex);
        }
    } catch (Exception ex) {
        throw new ProcessException("ERROR: FATAL", ex);
    }
}