Example usage for java.util TreeSet addAll

List of usage examples for java.util TreeSet addAll

Introduction

In this page you can find the example usage for java.util TreeSet addAll.

Prototype

public boolean addAll(Collection<? extends E> c) 

Source Link

Document

Adds all of the elements in the specified collection to this set.

Usage

From source file:com.qpark.maven.plugin.springintegration.TestClientGeneratorMojo.java

/**
 * @see org.apache.maven.plugin.Mojo#execute()
 *//*from   www .j  a va 2 s. c  o m*/
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    StaticLoggerBinder.getSingleton().setLog(this.getLog());
    this.getLog().debug("+execute");
    this.getLog().debug("get xsds");
    XsdsUtil xsds = XsdsUtil.getInstance(this.baseDirectory, this.basePackageName,
            this.messagePackageNameSuffix, this.deltaPackageNameSuffix, this.serviceRequestSuffix,
            this.serviceResponseSuffix);
    String eipVersion = this.getEipVersion();

    TestClientGenerator tc;

    Collection<String> serviceIds = ServiceIdRegistry.splitServiceIds(this.serviceId);
    if (serviceIds.size() == 0) {
        serviceIds = xsds.getServiceIdRegistry().getAllServiceIds();
    }

    this.getLog().info("ServiceId size " + serviceIds.size());

    TreeSet<String> configImports = new TreeSet<String>();
    StringBuffer configClients = new StringBuffer();
    for (String sid : serviceIds) {
        this.getLog().info("ServiceId " + sid);
        StringBuffer sb = new StringBuffer(1024);
        TreeSet<String> imports = new TreeSet<String>();
        imports.add("javax.xml.bind.JAXBElement");
        imports.add("org.springframework.ws.client.core.support.WebServiceGatewaySupport");

        StringBuffer impl = new StringBuffer();

        String s;
        String packageName = this.basePackageName;
        String objectFactoryClassName = "";
        String contextPathName = "";

        for (ElementType element : xsds.getElementTypes()) {
            if (element.isRequest() && element.getServiceId().equals(sid)) {
                tc = new TestClientGenerator(xsds, element, this.useSpringInsightAnnotation, eipVersion,
                        this.getLog());
                s = tc.generate();
                if (s.length() > 0) {
                    if (packageName == null || packageName.trim().length() == 0) {
                        packageName = element.getPackageNameGateway().replace(".gateway", ".client");
                    }
                    objectFactoryClassName = new StringBuffer(element.getPackageName()).append(".ObjectFactory")
                            .toString();
                    contextPathName = element.getPackageName();
                    impl.append("\n").append(s);
                    imports.addAll(tc.getImports());
                    imports.add(objectFactoryClassName);
                }
            }
        }
        if (impl.length() > 0) {
            String className = new StringBuffer().append(Util.getXjcClassName(sid)).append("ServiceClient")
                    .toString();
            configClients.append(this.generateClientServiceConfig(className));
            configImports.add(new StringBuffer(packageName).append(".").append(className).toString());
            if (packageName.length() > 0) {
                sb.append("package ");
                sb.append(packageName);
                sb.append(";\n");
                sb.append("\n");
            }
            for (String imported : imports) {
                if (imported != null && imported.trim().length() > 0) {
                    sb.append("import ");
                    sb.append(imported);
                    sb.append(";\n");
                }
            }
            sb.append("/**\n");
            sb.append(" * Client implementation of service <code>");
            sb.append(sid);
            sb.append("</code> using\n");
            sb.append(" * the {@link WebServiceGatewaySupport}.\n");
            sb.append(Util.getGeneratedAtJavaDocClassHeader(this.getClass(), eipVersion));
            sb.append(" */\n");
            sb.append("public class ");
            sb.append(className);
            sb.append(" extends WebServiceGatewaySupport {\n");

            sb.append("\t/** The {@link org.springframework.oxm.jaxb.Jaxb2Marshaller}s context path. */\n");
            sb.append("\tpublic static final String CONTEXT_PATH_NAME = \"");
            sb.append(contextPathName);
            sb.append("\";\n");
            sb.append("\t/** The service id. */\n");
            sb.append("\tpublic static final String SERVICE_ID = \"");
            sb.append(sid);
            sb.append("\";\n");

            sb.append("\t/** Service {@link ObjectFactory}. */\n");
            sb.append("\tprivate final ObjectFactory objectFactory = new ObjectFactory();\n");

            sb.append("\n");
            sb.append("\t/**\n");
            sb.append("\t * @return the {@link ObjectFactory} of the service.\n");
            sb.append("\t */\n");
            sb.append("\tpublic ObjectFactory getObjectFactory() {\n");
            sb.append("\t\treturn this.objectFactory;\n");
            sb.append("\t}\n");
            sb.append("\n");

            sb.append(impl);

            sb.append("}\n");

            File f = Util.getFile(this.outputDirectory, packageName,
                    new StringBuffer(className).append(".java").toString());
            this.getLog().info(new StringBuffer().append("Write ").append(f.getAbsolutePath()));
            try {
                Util.writeToFile(f, sb.toString());
            } catch (Exception e) {
                this.getLog().error(e.getMessage());
                e.printStackTrace();
            }
        }
    }
    this.generateAbstractConfig(xsds, this.basePackageName, configClients.toString(), configImports);
    this.generateClientWss4jSecurityInterceptor(xsds, this.basePackageName);
    this.getLog().debug("-execute");
}

From source file:org.opencastproject.capture.impl.SchedulerImpl.java

/**
 * Sets this machine's schedule based on the iCal data passed in as a parameter. Note that this call wipes all
 * currently scheduled captures and then schedules based on the new data. Also note that any files which are in the
 * way when this call tries to save the iCal attachments are overwritten without prompting.
 * /*from   w w  w. j  a  va  2  s. c o m*/
 * @param sched
 *          The scheduler to schedule the new events on
 * @param newCal
 *          The new {@code Calendar} data
 */
private synchronized void setCaptureSchedule(Scheduler sched, Calendar newCal) {
    log.debug("setCaptureSchedule(sched, newCal)");

    try {
        Map<Long, String> scheduledEventStarts = new Hashtable<Long, String>();
        Map<String, Date> scheduledEventEnds = new Hashtable<String, Date>();
        // Sort the events into chronological starting order
        TreeSet<VEvent> list = new TreeSet<VEvent>(new VEventStartTimeComparator());
        list.addAll(newCal.getComponents(Component.VEVENT));
        VEvent[] startAry = list.toArray(new VEvent[list.size()]);

        for (int i = 0; i < startAry.length; i++) {
            Event event = new Event(startAry[i], captureAgent, this);
            if (!event.isValidEvent()) {
                continue;
            }

            boolean skipOnError = Boolean
                    .valueOf(configService.getItem(CaptureParameters.CAPTURE_SCHEDULE_DROP_EVENT_IF_CONFLICT));
            int bufferMinutes = 1;
            if (configService.getItem(CaptureParameters.CAPTURE_SCHEDULE_INTEREVENT_BUFFERTIME) != null) {
                try {
                    bufferMinutes = Integer.valueOf(
                            configService.getItem(CaptureParameters.CAPTURE_SCHEDULE_INTEREVENT_BUFFERTIME));
                } catch (NumberFormatException e) {
                    log.info("Unable to parse value for {}, defaulting to 1 minute",
                            CaptureParameters.CAPTURE_SCHEDULE_INTEREVENT_BUFFERTIME);
                }
            }
            long bufferTime = bufferMinutes * CaptureParameters.MINUTES * CaptureParameters.MILLISECONDS;

            // If there could be an event scheduled before this one
            if (i > 0 && startAry[i - 1] != null && scheduledEventEnds.size() > 0) {
                int j = i - 1;
                String otherUID = null;
                // Search through the list of captures which could possibly have been scheduled
                // checking to see which one is closest to us
                while (j > 0) {
                    String testUID = startAry[j].getUid().getValue();
                    if (scheduledEventEnds.containsKey(testUID)) {
                        otherUID = testUID;
                        break;
                    }
                    j--;
                }
                // If we found something
                if (otherUID != null) {
                    Date lastEndDate = scheduledEventEnds.get(otherUID);
                    if (event.getStart().before(lastEndDate)) {
                        if (skipOnError) {
                            log.warn("Start time for event {} is before end time of event {}!  Skipping...",
                                    event.getUID(), otherUID);
                            continue;
                        } else {
                            log.warn(
                                    "Start time for event {} is before end time of event {}!  Shortening to fit...",
                                    event.getUID(), otherUID);
                            event.setStart(new Date(lastEndDate.getTime() + bufferTime));
                        }
                    } else if (ONE_MINUTE_DURATION.compareTo(new Dur(lastEndDate, event.getStart())) >= 0) {
                        if (skipOnError) {
                            log.warn("Start time for event {} is within one minute of event {}!  Skipping...",
                                    event.getUID(), otherUID);
                            continue;
                        } else {
                            log.warn(
                                    "Start time for event {} is within one minute of event {}!  Shortening to fit...",
                                    event.getUID(), otherUID);
                            event.setStart(new Date(lastEndDate.getTime() + bufferTime));
                        }
                    }
                }
            }

            if (!event.isValidEvent()) {
                continue;
            }

            // Get the cron expression and make sure it doesn't conflict with any existing captures
            // Note that this means the order in which the scheduled events appear in the source iCal makes a functional
            // difference!
            String conflict = scheduledEventStarts.get(event.getStart().getTime());
            if (conflict != null) {
                // This case should have disappeared with MH-1253, but I'm leaving it here anyway just in case
                log.warn("Unable to schedule event {} because its starting time coinsides with event {}!",
                        event.getUID(), conflict);
                continue;
            }

            PropertyList attachments = event.getProperties(Property.ATTACH);
            scheduleEvent(sched, event, attachments);
            scheduledEventStarts.put(event.getStart().getTime(), event.getUID());
            scheduledEventEnds.put(event.getUID(), event.getEnd());
        }
    } catch (NullPointerException e) {
        log.error("Invalid calendar data, one of the start or end times is incorrect: {}.", e);
    } catch (ParseException e) {
        log.error("Parsing error: {}.", e);
    } catch (org.opencastproject.util.ConfigurationException e) {
        log.error("Configuration exception: {}.", e);
    } catch (MediaPackageException e) {
        log.error("MediaPackageException exception: {}.", e);
    } catch (MalformedURLException e) {
        log.error("MalformedURLException: {}.", e);
    }
}

From source file:org.geotools.styling.css.CssTranslator.java

private TreeSet<Integer> getZIndexesForRules(List<CssRule> rules) {
    // collect and sort all the indexes first
    TreeSet<Integer> indexes = new TreeSet<>(new ZIndexComparator());
    for (CssRule rule : rules) {
        Set<Integer> ruleIndexes = rule.getZIndexes();
        if (ruleIndexes.contains(null)) {
            ruleIndexes.remove(null);//from www. j  a  v  a 2s  . c  o  m
            ruleIndexes.add(0);
        }
        indexes.addAll(ruleIndexes);
    }
    return indexes;
}

From source file:com.ichi2.anki.CardEditor.java

private void actualizeTagDialog(StyledDialog ad) {
    TreeSet<String> tags = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
    for (String tag : mCol.getTags().all()) {
        tags.add(tag);// ww w .ja v  a  2 s. co m
    }
    tags.addAll(selectedTags);
    int len = tags.size();
    allTags = new String[len];
    boolean[] checked = new boolean[len];
    int i = 0;
    for (String t : tags) {
        allTags[i++] = t;
        if (selectedTags.contains(t)) {
            checked[i - 1] = true;
        }
    }
    ad.setMultiChoiceItems(allTags, checked, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface arg0, int which) {
            String tag = allTags[which];
            if (selectedTags.contains(tag)) {
                Log.i(AnkiDroidApp.TAG, "unchecked tag: " + tag);
                selectedTags.remove(tag);
            } else {
                Log.i(AnkiDroidApp.TAG, "checked tag: " + tag);
                selectedTags.add(tag);
            }
        }
    });
}

From source file:org.apache.hadoop.hbase.client.crosssite.CrossSiteHTable.java

/**
 * Gets all the cluster names.//from w ww  .  j av  a  2  s. co  m
 * 
 * @return
 * @throws KeeperException
 */
private Set<String> getClusterNames() throws KeeperException {
    List<String> clusterNames = znodes.listClusters();
    TreeSet<String> cns = new TreeSet<String>();
    if (clusterNames != null) {
        cns.addAll(clusterNames);
    }
    return cns;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.phd.academicAdminOffice.PhdIndividualProgramProcessDA.java

public ActionForward viewAllAlertMessages(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {/*from  ww w  . j ava  2s.  c  o m*/
    PhdIndividualProgramProcess process = getProcess(request);

    TreeSet<PhdAlertMessage> orderedMessages = new TreeSet<PhdAlertMessage>(
            Collections.reverseOrder(PhdAlertMessage.COMPARATOR_BY_WHEN_CREATED_AND_ID));
    orderedMessages.addAll(process.getAlertMessagesSet());

    request.setAttribute("alertMessages", orderedMessages);
    return mapping.findForward("viewAllAlertMessages");
}

From source file:net.spfbl.data.Block.java

public static TreeSet<String> getAll() throws ProcessException {
    TreeSet<String> blockSet = SET.getAll();
    blockSet.addAll(CIDR.getAll());
    blockSet.addAll(REGEX.getAll());/*from   w ww  . ja  v a2 s  .com*/
    blockSet.addAll(DNSBL.getAll());
    blockSet.addAll(WHOIS.getAll());
    return blockSet;
}

From source file:net.spfbl.data.Block.java

public static TreeSet<String> get(String user) throws ProcessException {
    TreeSet<String> blockSet = SET.get(user);
    blockSet.addAll(CIDR.get(user));
    blockSet.addAll(REGEX.get(user));/*  w  w  w  .j a  va2  s .c om*/
    blockSet.addAll(DNSBL.get(user));
    blockSet.addAll(WHOIS.get(user));
    return blockSet;
}

From source file:ca.sqlpower.architect.diff.CompareSQL.java

/**
 * Creates a List of DiffChunks that describe the differences between the
 * columns of the given tables./*w  w  w. jav  a 2  s . c o  m*/
 *
 * @param sourceTable The "left side" for the comparison.  If null, then all columns
 * in the target table will be considered obsolete.
 * @param targetTable The "right side" for the comparison.  If null, then all columns
 * in the source table will be considered new.
 * @throws SQLObjectException If the getColumns() methods of the source or target
 * tables run into trouble.
 */
private List<DiffChunk<SQLObject>> generateColumnDiffs(SQLTable sourceTable, SQLTable targetTable)
        throws SQLObjectException {
    TreeSet<SQLColumn> sourceColumnList;
    TreeSet<SQLColumn> targetColumnList;
    Iterator<SQLColumn> sourceColIter;
    Iterator<SQLColumn> targetColIter;
    SQLColumn sourceColumn;
    SQLColumn targetColumn;
    boolean sourceColContinue;
    boolean targetColContinue;
    boolean keyChangeFlag = false;

    sourceColumnList = new TreeSet<SQLColumn>(getObjectComparator());
    targetColumnList = new TreeSet<SQLColumn>(getObjectComparator());
    sourceColContinue = false;
    targetColContinue = false;
    sourceColIter = null;
    targetColIter = null;
    sourceColumn = null;
    targetColumn = null;

    // We store the diffs in here, then return this list
    List<DiffChunk<SQLObject>> diffs = new ArrayList<DiffChunk<SQLObject>>();

    if (sourceTable != null) {
        sourceColumnList.addAll(sourceTable.getColumns());
    }
    if (targetTable != null) {
        targetColumnList.addAll(targetTable.getColumns());
    }
    if (sourceColumnList.size() == 0) {
        sourceColumnList = null;
        sourceColContinue = false;
    } else {
        sourceColIter = sourceColumnList.iterator();
        sourceColumn = sourceColIter.next();
        sourceColContinue = true;
    }

    if (targetColumnList.size() == 0) {
        targetColumnList = null;
        targetColContinue = false;
    } else {

        targetColIter = targetColumnList.iterator();
        targetColumn = targetColIter.next();
        targetColContinue = true;
    }

    while (sourceColContinue && targetColContinue) {

        int compareResult = getObjectComparator().compare(sourceColumn, targetColumn);
        // Comparing Columns
        if (compareResult < 0) {
            diffs.add(new DiffChunk<SQLObject>(sourceColumn, DiffType.LEFTONLY));
            logger.debug("The source column is " + sourceColumn);
            if (sourceColumn.isPrimaryKey()) {
                keyChangeFlag = true;
            }
            if (sourceColIter.hasNext()) {
                sourceColumn = sourceColIter.next();
            } else {
                sourceColContinue = false;

            }

        }
        // Comparing Columns
        if (compareResult > 0) {
            diffs.add(new DiffChunk<SQLObject>(targetColumn, DiffType.RIGHTONLY));
            logger.debug("The target column is " + targetColumn);
            if (targetColumn.isPrimaryKey()) {
                keyChangeFlag = true;
            }
            if (targetColIter.hasNext()) {
                targetColumn = targetColIter.next();
            } else {
                targetColContinue = false;

            }
        }

        // Comparing Columns
        if (compareResult == 0) {

            if (targetColumn.isPrimaryKey() != sourceColumn.isPrimaryKey()) {
                keyChangeFlag = true;
                //diffs.add(new DiffChunk<SQLObject>(targetColumn, DiffType.KEY_CHANGED));
            }

            List<PropertyChange> changes = generatePropertyChanges(sourceColumn, targetColumn);
            if (changes.size() > 0) {
                DiffChunk<SQLObject> chunk = null;

                if (nameComparator.compare(sourceColumn, targetColumn) != 0) {
                    chunk = new DiffChunk<SQLObject>(targetColumn, DiffType.NAME_CHANGED);
                    chunk.setOriginalData(sourceColumn);
                } else if (ArchitectUtils.columnsDiffer(targetColumn, sourceColumn)) {
                    // Make sure the changes are worthy of a SQL script generation:
                    if (logger.isDebugEnabled()) {
                        logger.debug("Column " + sourceColumn.getName() + " differs!");
                        logger.debug(String.format("  Type:      %10d %10d", targetColumn.getType(),
                                sourceColumn.getType()));
                        logger.debug(String.format("  Precision: %10d %10d", targetColumn.getPrecision(),
                                sourceColumn.getPrecision()));
                        logger.debug(String.format("  Scale:     %10d %10d", targetColumn.getScale(),
                                sourceColumn.getScale()));
                        logger.debug(String.format("  Nullable:  %10d %10d", targetColumn.getNullable(),
                                sourceColumn.getNullable()));
                    }
                    chunk = new DiffChunk<SQLObject>(targetColumn, DiffType.SQL_MODIFIED);
                } else {
                    chunk = new DiffChunk<SQLObject>(targetColumn, DiffType.MODIFIED);
                }

                for (PropertyChange change : changes) {
                    chunk.addPropertyChange(change);
                }
                diffs.add(chunk);

            } else {
                if (!suppressSimilarities) {
                    diffs.add(new DiffChunk<SQLObject>(sourceColumn, DiffType.SAME));
                }
            }

            if (targetColIter.hasNext()) {
                targetColumn = targetColIter.next();
            } else {
                targetColContinue = false;
            }

            if (sourceColIter.hasNext()) {
                sourceColumn = sourceColIter.next();
            } else {
                sourceColContinue = false;
            }
        }
    }
    while (sourceColContinue) {
        diffs.add(new DiffChunk<SQLObject>(sourceColumn, DiffType.LEFTONLY));
        if (sourceColIter.hasNext()) {
            sourceColumn = sourceColIter.next();
        } else {
            sourceColContinue = false;
        }
    }

    while (targetColContinue) {
        diffs.add(new DiffChunk<SQLObject>(targetColumn, DiffType.RIGHTONLY));
        if (targetColIter.hasNext()) {
            targetColumn = targetColIter.next();
        } else {
            targetColContinue = false;
        }
    }

    if (keyChangeFlag) {
        if (sourceTable.getPkSize() > 0) {
            diffs.add(new DiffChunk<SQLObject>(sourceTable, DiffType.DROP_KEY));
        }
        diffs.add(new DiffChunk<SQLObject>(targetTable, DiffType.KEY_CHANGED));
    }
    return diffs;
}

From source file:org.apache.hadoop.mapred.HFSPScheduler.java

@Override
public List<Task> assignTasks(TaskTracker taskTracker) throws IOException {

    this.update();

    taskHelper.init(taskTracker.getStatus());

    // Update time waited for local maps for jobs skipped on last heartbeat
    if (this.delayEnabled)
        this.updateLocalityWaitTimes(taskHelper.currentTime);

    for (TaskType type : TASK_TYPES) {

        HelperForType helper = taskHelper.helper(type);

        if (!this.preemptionStrategy.isPreemptionActive() && helper.currAvailableSlots == 0) {
            // LOG.debug("assign(" + taskTracker.getTrackerName() + ", " + type
            // + "): no slots available");
            continue;
        }/*from  w ww  .ja va 2s  .  com*/

        TreeSet<JobInProgress> trainJobs = new TreeSet<JobInProgress>(
                type == TaskType.MAP ? TRAIN_COMPARATOR_MAP : TRAIN_COMPARATOR_REDUCE);

        Collection<JobInProgress> trainJips = this.getJobs(QueueType.TRAIN, type);
        synchronized (trainJips) {
            trainJobs.addAll(trainJips);
        }

        TreeMap<JobDurationInfo, JobInProgress> sizeBasedJobs = new TreeMap<JobDurationInfo, JobInProgress>(
                JOB_DURATION_COMPARATOR);

        TreeMap<JobDurationInfo, JobInProgress> jobQueue = this.getSizeBasedJobQueue(type);
        synchronized (jobQueue) {
            sizeBasedJobs.putAll(jobQueue);
        }

        TreeMap<JobDurationInfo, TaskStatuses> taskStatusesSizeBased = helper.taskStatusesSizeBased;

        if (helper.doTrainScheduling) {
            assignTrainTasks(type, helper, trainJobs, sizeBasedJobs, taskStatusesSizeBased);
        }

        if (helper.doSizeBasedScheduling) {
            assignSizeBasedTasks(type, helper, sizeBasedJobs, taskStatusesSizeBased);
        }

    }

    if (LOG.isDebugEnabled()) {
        taskHelper.logInfos(LOG);
    }

    return (List<Task>) taskHelper.result.clone();
}