Example usage for java.util SortedSet isEmpty

List of usage examples for java.util SortedSet isEmpty

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:com.spotify.heroic.filter.impl.AndFilterImpl.java

private static Filter optimize(SortedSet<Filter> statements) {
    final SortedSet<Filter> result = new TreeSet<>();

    root: for (final Filter f : statements) {
        if (f instanceof Filter.Not) {
            final Filter.Not not = (Filter.Not) f;

            if (statements.contains(not.first())) {
                return FalseFilterImpl.get();
            }/* w  w  w.j  a va  2  s.  c  o m*/

            result.add(f);
            continue;
        }

        /**
         * If there exists two MatchTag statements, but they check for different values.
         */
        if (f instanceof Filter.MatchTag) {
            final Filter.MatchTag outer = (Filter.MatchTag) f;

            for (final Filter inner : statements) {
                if (inner.equals(outer)) {
                    continue;
                }

                if (inner instanceof Filter.MatchTag) {
                    final Filter.MatchTag matchTag = (Filter.MatchTag) inner;

                    if (!outer.first().equals(matchTag.first())) {
                        continue;
                    }

                    if (!FilterComparatorUtils.isEqual(outer.second(), matchTag.second())) {
                        return FalseFilterImpl.get();
                    }
                }
            }

            result.add(f);
            continue;
        }

        if (f instanceof Filter.MatchTag) {
            final Filter.MatchTag outer = (Filter.MatchTag) f;

            for (final Filter inner : statements) {
                if (inner.equals(outer)) {
                    continue;
                }

                if (inner instanceof Filter.MatchTag) {
                    final Filter.MatchTag tag = (Filter.MatchTag) inner;

                    if (!outer.first().equals(tag.first())) {
                        continue;
                    }

                    if (!FilterComparatorUtils.isEqual(outer.second(), tag.second())) {
                        return FalseFilterImpl.get();
                    }
                }
            }

            result.add(f);
            continue;
        }

        // optimize away prefixes which encompass eachother.
        // Example: foo ^ hello and foo ^ helloworld -> foo ^ helloworld
        if (f instanceof Filter.StartsWith) {
            final Filter.StartsWith outer = (Filter.StartsWith) f;

            for (final Filter inner : statements) {
                if (inner.equals(outer)) {
                    continue;
                }

                if (inner instanceof Filter.StartsWith) {
                    final Filter.StartsWith starts = (Filter.StartsWith) inner;

                    if (!outer.first().equals(starts.first())) {
                        continue;
                    }

                    if (FilterComparatorUtils.prefixedWith(starts.second(), outer.second())) {
                        continue root;
                    }
                }
            }

            result.add(f);
            continue;
        }

        // all ok!
        result.add(f);
    }

    if (result.isEmpty()) {
        return FalseFilterImpl.get();
    }

    if (result.size() == 1) {
        return result.iterator().next();
    }

    return new AndFilterImpl(new ArrayList<>(result));
}

From source file:net.sf.jasperreports.engine.export.HtmlExporter.java

protected void exportTable(TableVisitor tableVisitor, Table table, boolean whiteBackground,
        boolean isMainReportTable) throws IOException {
    SortedSet<Column> columns = table.getColumns().getUserEntries();
    SortedSet<Row> rows = table.getRows().getUserEntries();
    if (columns.isEmpty() || rows.isEmpty()) {
        // TODO lucianc empty page
        return;/*from w  w w. ja v  a2 s.c om*/
    }

    if (isMainReportTable) {
        int totalWidth = columns.last().getEndCoord() - columns.first().getStartCoord();
        writer.write(
                "<table class=\"jrPage\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"empty-cells: show; width: ");
        writer.write(toSizeUnit(totalWidth));
        writer.write(";");
    } else {
        writer.write(
                "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"empty-cells: show; width: 100%;");
    }

    HtmlBorderCollapseEnum borderCollapse = getCurrentItemConfiguration().getBorderCollapseValue();
    if (borderCollapse != null) {
        writer.write(" border-collapse: ");
        writer.write(borderCollapse.getName());
        writer.write(";");
    }

    if (whiteBackground) {
        writer.write(" background-color: white;");
    }
    writer.write("\">\n");

    // TODO lucianc check whether we can use the first row for setting col widths
    writer.write("<tr valign=\"top\" style=\"height:0\">\n");
    for (Column col : columns) {
        writer.write("<td style=\"width:");
        writer.write(toSizeUnit(col.getExtent()));
        writer.write("\"></td>\n");
    }
    writer.write("</tr>\n");

    for (Row row : rows) {
        writer.write("<tr valign=\"top\" style=\"height:");
        writer.write(toSizeUnit(row.getExtent()));
        writer.write("\">\n");

        int emptySpan = 0;
        for (Column col : columns) {
            Cell cell = row.getCell(col);
            if (cell == null) {
                ++emptySpan;
            } else {
                if (emptySpan > 0) {
                    writeEmptyCell(emptySpan, 1);
                }
                emptySpan = 0;

                TablePosition position = new TablePosition(table, col, row);
                cell.accept(tableVisitor, position);
            }
        }
        if (emptySpan > 0) {
            writeEmptyCell(emptySpan, 1);
        }

        writer.write("</tr>\n");
    }

    writer.write("</table>\n");
}

From source file:fr.cnes.sitools.proxy.AbstractDirectoryServerResource.java

/**
 * Returns the list of variants for the given method.
 * //from ww  w .  ja  v  a 2 s.c  om
 * @param method
 *          The related method.
 * @return The list of variants for the given method.
 * 
 * @see DirectoryServerResource.getVariants(Method method)
 */
public List<Variant> getVariants(Method method) {

    List<Variant> result = null;

    if ((Method.GET.equals(method) || Method.HEAD.equals(method))) {
        if (variantsGet != null) {
            result = variantsGet;
        } else {
            getLogger().fine("Getting variants for : " + getTargetUri());

            if ((this.getDirectoryContent() != null) && (getReference() != null)
                    && (getReference().getBaseRef() != null)) {

                // Allows to sort the list of representations
                SortedSet<Representation> resultSet = new TreeSet<Representation>(
                        getRepresentationsComparator());

                // Compute the base reference (from a call's client point of
                // view)
                String baseRef = getReference().getBaseRef().toString(false, false);

                if (!baseRef.endsWith("/")) {
                    baseRef += "/";
                }

                int lastIndex = this.relativePart.lastIndexOf("/");

                if (lastIndex != -1) {
                    baseRef += this.relativePart.substring(0, lastIndex);
                }

                int rootLength = getDirectoryUri().length();

                if (this.getBaseName() != null) {
                    String filePath;
                    for (Reference ref : getVariantsReferences()) {
                        // Add the new variant to the result list
                        Response contextResponse = getRepresentation(ref.toString());
                        if (contextResponse.getStatus().isSuccess() && (contextResponse.getEntity() != null)) {
                            filePath = ref.toString(false, false).substring(rootLength);
                            Representation rep = contextResponse.getEntity();

                            if (filePath.startsWith("/")) {
                                rep.setLocationRef(baseRef + filePath);
                            } else {
                                rep.setLocationRef(baseRef + "/" + filePath);
                            }

                            resultSet.add(rep);
                        }
                    }
                }

                if (!resultSet.isEmpty()) {
                    result = new ArrayList<Variant>(resultSet);
                }

                if (resultSet.isEmpty()) {
                    if (isDirectoryTarget() && getDirectory().isListingAllowed()) {
                        ReferenceFileList userList = new ReferenceFileList(this.getDirectoryContent().size());
                        // Set the list identifier
                        userList.setIdentifier(baseRef);
                        userList.setRegexp(directory.getRegexp());

                        SortedSet<Reference> sortedSet = new TreeSet<Reference>(getDirectory().getComparator());
                        sortedSet.addAll(this.getDirectoryContent());

                        for (Reference ref : sortedSet) {
                            String filePart = ref.toString(false, false).substring(rootLength);
                            StringBuilder filePath = new StringBuilder();
                            if ((!baseRef.endsWith("/")) && (!filePart.startsWith("/"))) {
                                filePath.append('/');
                            }
                            filePath.append(filePart);

                            // SITOOLS2 - ReferenceFileList = reference and File
                            String path = ref.getPath();
                            String repertoire = Reference.decode(path);
                            File file = new File(repertoire);

                            userList.addFileReference(baseRef + filePath, file);
                            // SITOOLS2 instead of simple reference : userList.add(baseRef + filePath);
                        }
                        List<Variant> list = getDirectory().getIndexVariants(userList);
                        for (Variant variant : list) {
                            if (result == null) {
                                result = new ArrayList<Variant>();
                            }

                            result.add(getDirectory().getIndexRepresentation(variant, userList));
                        }

                    }
                }
            } else if (isFileTarget() && (this.fileContent != null)) {
                // Sets the location of the target representation.
                if (getOriginalRef() != null) {
                    this.fileContent.setLocationRef(getRequest().getOriginalRef());
                } else {
                    this.fileContent.setLocationRef(getReference());
                }

                result = new ArrayList<Variant>();
                result.add(this.fileContent);
            }

            this.variantsGet = result;
        }
    }

    return result;
}

From source file:org.rapla.storage.impl.server.LocalAbstractCachableOperator.java

/** updates the bindings of the resources and returns a map with all processed allocation changes*/
private void updateIndizes(UpdateResult result) {
    Map<Allocatable, AllocationChange> toUpdate = new HashMap<Allocatable, AllocationChange>();
    List<Allocatable> removedAllocatables = new ArrayList<Allocatable>();
    for (UpdateOperation operation : result.getOperations()) {
        Entity current = operation.getCurrent();
        RaplaType raplaType = current.getRaplaType();
        if (raplaType == Reservation.TYPE) {
            if (operation instanceof UpdateResult.Remove) {
                Reservation old = (Reservation) current;
                for (Appointment app : old.getAppointments()) {
                    updateBindings(toUpdate, old, app, true);
                }//  w w w . ja  va 2 s .co  m
            }
            if (operation instanceof UpdateResult.Add) {
                Reservation newReservation = (Reservation) ((UpdateResult.Add) operation).getNew();
                for (Appointment app : newReservation.getAppointments()) {
                    updateBindings(toUpdate, newReservation, app, false);
                }
            }
            if (operation instanceof UpdateResult.Change) {
                Reservation oldReservation = (Reservation) ((UpdateResult.Change) operation).getOld();
                Reservation newReservation = (Reservation) ((UpdateResult.Change) operation).getNew();
                Appointment[] oldAppointments = oldReservation.getAppointments();
                for (Appointment oldApp : oldAppointments) {
                    updateBindings(toUpdate, oldReservation, oldApp, true);
                }
                Appointment[] newAppointments = newReservation.getAppointments();
                for (Appointment newApp : newAppointments) {
                    updateBindings(toUpdate, newReservation, newApp, false);
                }
            }
        }
        if (raplaType == DynamicType.TYPE) {
            if (operation instanceof UpdateResult.Change) {
                DynamicType dynamicType = (DynamicType) current;
                DynamicType old = (DynamicType) ((UpdateResult.Change) operation).getOld();
                String conflictsNew = dynamicType.getAnnotation(DynamicTypeAnnotations.KEY_CONFLICTS);
                String conflictsOld = old.getAnnotation(DynamicTypeAnnotations.KEY_CONFLICTS);
                if (conflictsNew != conflictsOld) {
                    if (conflictsNew == null || conflictsOld == null || !conflictsNew.equals(conflictsOld)) {
                        Collection<Reservation> reservations = cache.getReservations();
                        for (Reservation reservation : reservations) {
                            if (dynamicType.equals(reservation.getClassification().getType())) {
                                Collection<AppointmentImpl> appointments = ((ReservationImpl) reservation)
                                        .getAppointmentList();
                                for (Appointment app : appointments) {
                                    updateBindings(toUpdate, reservation, app, true);
                                }
                                for (Appointment app : appointments) {
                                    updateBindings(toUpdate, reservation, app, false);
                                }
                            }
                        }
                    }
                }
            }
        }

        if (raplaType == Allocatable.TYPE) {
            if (operation instanceof UpdateResult.Remove) {
                Allocatable old = (Allocatable) current;
                removedAllocatables.add(old);
            }
        }

        if (raplaType == Conflict.TYPE) {
            Conflict conflict = (Conflict) current;
            String conflictId = conflict.getId();
            Date date = getCurrentTimestamp();
            boolean appointment1Enabled = conflict.isAppointment1Enabled();
            boolean appointment2Enabled = conflict.isAppointment2Enabled();
            conflictFinder.setConflictEnabledState(conflictId, date, appointment1Enabled, appointment2Enabled);
        }
    }

    for (Allocatable alloc : removedAllocatables) {
        SortedSet<Appointment> sortedSet = appointmentMap.get(alloc);
        if (sortedSet != null && !sortedSet.isEmpty()) {
            getLogger().error(
                    "Removing non empty appointment map for resource " + alloc + " Appointments:" + sortedSet);
        }
        appointmentMap.remove(alloc);
    }
    Date today = today();
    // processes the conflicts and adds the changes to the result
    conflictFinder.updateConflicts(toUpdate, result, today, removedAllocatables);
    checkAbandonedAppointments();
    for (UpdateOperation operation : result.getOperations()) {
        Entity current = operation.getCurrent();
        RaplaType raplaType = current.getRaplaType();
        if (raplaType == Conflict.TYPE || raplaType == Allocatable.TYPE || raplaType == Reservation.TYPE
                || raplaType == DynamicType.TYPE || raplaType == User.TYPE || raplaType == Preferences.TYPE
                || raplaType == Category.TYPE) {
            if (operation instanceof UpdateResult.Remove) {
                //LastChangedTimestamp old = (LastChangedTimestamp) current;
                //timestampSet.remove( old);
                addToDeleteUpdate(current, true);
            }
            if (operation instanceof UpdateResult.Add) {
                Entity newEntity = ((UpdateResult.Add) operation).getNew();
                addToDeleteUpdate(newEntity, false);
            }
            if (operation instanceof UpdateResult.Change) {
                Entity newEntity = ((UpdateResult.Change) operation).getNew();
                //LastChangedTimestamp oldEntity = (LastChangedTimestamp) ((UpdateResult.Change) operation).getOld();
                addToDeleteUpdate(newEntity, false);
            }
        }
    }
    // Order is important. Can't remove from database if removed from cache first
    removeConflictsFromDatabase(getConflictsToDeleteFromDatabase(result));
    removeConflictsFromCache(getConflictsToDeleteFromCache(result));
    //      Collection<Change> changes = result.getOperations( UpdateResult.Change.class);
    //      for ( Change change:changes)
    //      {
    //          Entity old = change.getOld();
    //          if (!( old instanceof Conflict))
    //          {
    //              continue;
    //          }
    //          Conflict conflict = (Conflict)change.getNew();
    //          if (conflict.isEnabledAppointment1() && conflict.isEnabledAppointment2())
    //          {
    //              conflicts.add( conflict);
    //          }
    //      }

}

From source file:org.wrml.runtime.schema.generator.SchemaGenerator.java

/**
 * Generate a {@link JavaBytecodeClass} from the specified {@link Schema}.
 * <p/>//w w w  .j a  v a2  s .c o  m
 * Like a *big* regex (regular expression), we can compile all of the
 * WRML schema metadata (as if it is a single *big* String input) into a
 * loaded Java class so that the rest of the WRML *runtime* can use
 * (Prototype-optimized) reflection to access WRML's type system.
 *
 * @param schema The Schema to represent as a Java class.
 * @return The Java class representation of the specified schema.
 */
public JavaBytecodeClass generateSchemaInterface(final Schema schema) {

    /*
     * Create the simple POJO that will return the transformation
     * information. By the end of this method, this will be full of Java
     * bytecode-oriented information gleaned from this method's schema
     * parameter.
     */
    final JavaBytecodeClass javaBytecodeClass = new JavaBytecodeClass();
    final JavaBytecodeAnnotation wrmlAnnotation = new JavaBytecodeAnnotation(
            SchemaGenerator.ANNOTATION_INTERNAL_NAME_WRML);
    wrmlAnnotation.setAttributeValue(AnnotationParameterName.uniqueName.name(),
            schema.getUniqueName().getFullName());
    javaBytecodeClass.getAnnotations().add(wrmlAnnotation);

    final SortedSet<String> keySlotNameSet = new TreeSet<>();

    /*
     * If the schema declares any key slots, note them with a
     * class-level annotation.
     */
    final List<String> keySlotNames = schema.getKeySlotNames();
    if (keySlotNames != null && keySlotNames.size() > 0) {
        keySlotNameSet.addAll(keySlotNames);
    }

    if (!keySlotNameSet.isEmpty()) {
        final String[] keySlotNamesArray = new String[keySlotNameSet.size()];
        wrmlAnnotation.setAttributeValue(AnnotationParameterName.keySlotNames.name(),
                keySlotNameSet.toArray(keySlotNamesArray));
    }

    /*
     * If the schema declares any comparable slots, note them with a
     * class-level annotation.
     */
    final List<String> comparableSlotNames = schema.getComparableSlotNames();
    if (comparableSlotNames != null && comparableSlotNames.size() > 0) {
        final String[] comparableSlotNamesArray = new String[comparableSlotNames.size()];
        wrmlAnnotation.setAttributeValue(AnnotationParameterName.comparableSlotNames.name(),
                comparableSlotNames.toArray(comparableSlotNamesArray));
    }

    wrmlAnnotation.setAttributeValue(AnnotationParameterName.titleSlotName.name(), schema.getTitleSlotName());

    /*
     * In Java, all interfaces extend java.lang.Object, so this can
     * remain constant for Schema too.
     */
    javaBytecodeClass.setSuperName(SchemaGenerator.OBJECT_INTERNAL_NAME);

    /*
     * Go from schema id (URI) to internal Java class name. This is a
     * simple matter of stripping the leading forward slash from the
     * URI's path. Internally (in the bytecode), Java's class names use
     * forward slash (/) instead of full stop dots (.).
     */
    final URI schemaUri = schema.getUri();
    final String interfaceInternalName = uriToInternalTypeName(schemaUri);
    // if (schema.getUniqueName() == null)
    // {
    // schema.setUniqueName(new UniqueName(schemaUri.getPath()));
    // }

    javaBytecodeClass.setInternalName(interfaceInternalName);

    /*
     * Add the class-level Description annotation to capture the
     * schema's description.
     */
    final String schemaDescription = schema.getDescription();
    if (schemaDescription != null && !schemaDescription.trim().isEmpty()) {
        final JavaBytecodeAnnotation schemaDescriptionAnnotation = new JavaBytecodeAnnotation(
                SchemaGenerator.ANNOTATION_INTERNAL_NAME_DESCRIPTION);
        schemaDescriptionAnnotation.setAttributeValue(AnnotationParameterName.value.name(), schemaDescription);
        javaBytecodeClass.getAnnotations().add(schemaDescriptionAnnotation);
    }

    String schemaTitle = schema.getTitle();
    if (schemaTitle == null || schemaTitle.trim().isEmpty()) {
        schemaTitle = schema.getUniqueName().getLocalName();
    }

    final JavaBytecodeAnnotation schemaTitleAnnotation = new JavaBytecodeAnnotation(
            SchemaGenerator.ANNOTATION_INTERNAL_NAME_TITLE);
    schemaTitleAnnotation.setAttributeValue(AnnotationParameterName.value.name(), schemaTitle);
    javaBytecodeClass.getAnnotations().add(schemaTitleAnnotation);

    final URI schemaThumbnailImageLocation = schema.getThumbnailLocation();
    if (schemaThumbnailImageLocation != null) {
        final JavaBytecodeAnnotation schemaThumbnailImageAnnotation = new JavaBytecodeAnnotation(
                SchemaGenerator.ANNOTATION_INTERNAL_NAME_THUMBNAIL_IMAGE);
        schemaThumbnailImageAnnotation.setAttributeValue(AnnotationParameterName.value.name(),
                schemaThumbnailImageLocation.toString());
        javaBytecodeClass.getAnnotations().add(schemaThumbnailImageAnnotation);
    }

    boolean isAggregate = false;

    /*
     * Turn the schema's base schema list into our Java class's base
     * (aka extended) interfaces.
     */
    final List<URI> baseSchemaUris = schema.getBaseSchemaUris();
    for (final URI baseSchemaUri : baseSchemaUris) {
        final String baseSchemaInternalName = uriToInternalTypeName(baseSchemaUri);
        javaBytecodeClass.getInterfaces().add(baseSchemaInternalName);

        if (!isAggregate && getSchemaLoader().getAggregateDocumentSchemaUri().equals(baseSchemaUri)) {
            isAggregate = true;

            final List<Slot> slots = schema.getSlots();
            for (final Slot slot : slots) {
                final Value value = slot.getValue();
                if (!(value instanceof LinkValue || value instanceof ModelValue
                        || value instanceof MultiSelectValue)) {
                    keySlotNameSet.add(slot.getName());
                }
            }
        }
    }

    // Add the Model base interface
    javaBytecodeClass.getInterfaces().add(SchemaGenerator.MODEL_INTERFACE_INTERNAL_NAME);

    /*
     * Add the class-level Tags annotation to capture the schema's tags.
     */
    final List<String> schemaTags = schema.getTags();
    if (schemaTags != null && schemaTags.size() > 0) {
        final JavaBytecodeAnnotation tagsAnnotation = new JavaBytecodeAnnotation(
                SchemaGenerator.ANNOTATION_INTERNAL_NAME_TAGS);
        final String[] tagsArray = new String[schemaTags.size()];
        tagsAnnotation.setAttributeValue(AnnotationParameterName.value.name(), schemaTags.toArray(tagsArray));
        javaBytecodeClass.getAnnotations().add(tagsAnnotation);
    }

    final Long schemaVersion = schema.getVersion();
    if (schemaVersion != null) {
        final JavaBytecodeAnnotation versionAnnotation = new JavaBytecodeAnnotation(
                SchemaGenerator.ANNOTATION_INTERNAL_NAME_VERSION);
        versionAnnotation.setAttributeValue(AnnotationParameterName.value.name(), schemaVersion);
        javaBytecodeClass.getAnnotations().add(versionAnnotation);
    }

    final Boolean maybeReadOnly = schema.isReadOnly();
    if (maybeReadOnly != null && maybeReadOnly) {
        final JavaBytecodeAnnotation readOnlyAnnotation = new JavaBytecodeAnnotation(
                SchemaGenerator.ANNOTATION_INTERNAL_NAME_READ_ONLY);
        javaBytecodeClass.getAnnotations().add(readOnlyAnnotation);
    }

    /*
     * Generate the interface method signatures.
     */
    generateSchemaInterfaceMethods(schema, javaBytecodeClass, isAggregate);

    // TODO: "Open slots" with signatures. Track the open slots via
    // the JavaBytecode types.

    //
    // TODO: The signature will need to be changed for generics:
    // Example:
    //
    // Java: public interface Test<T extends List<?>> extends List<T>
    // Class File: public abstract interface org.wrml.schema.Test
    // extends java.util.List
    // Signature:
    // <T::Ljava/util/List<*>;>Ljava/lang/Object;Ljava/util/List<TT;>;
    //

    javaBytecodeClass.setSignature(null);

    generateSchemaInterfaceBytecode(javaBytecodeClass);
    return javaBytecodeClass;
}

From source file:mondrian.olap.Util.java

/**
 * Returns the intersection of two sorted sets. Does not modify either set.
 *
 * <p>Optimized for the case that both sets are {@link ArraySortedSet}.</p>
 *
 * @param set1 First set//from w ww.j  a v a 2s.  com
 * @param set2 Second set
 * @return Intersection of the sets
 */
public static <E extends Comparable> SortedSet<E> intersect(SortedSet<E> set1, SortedSet<E> set2) {
    if (set1.isEmpty()) {
        return set1;
    }
    if (set2.isEmpty()) {
        return set2;
    }
    if (!(set1 instanceof ArraySortedSet) || !(set2 instanceof ArraySortedSet)) {
        final TreeSet<E> set = new TreeSet<E>(set1);
        set.retainAll(set2);
        return set;
    }
    final Comparable<?>[] result = new Comparable[Math.min(set1.size(), set2.size())];
    final Iterator<E> it1 = set1.iterator();
    final Iterator<E> it2 = set2.iterator();
    int i = 0;
    E e1 = it1.next();
    E e2 = it2.next();
    for (;;) {
        final int compare = e1.compareTo(e2);
        if (compare == 0) {
            result[i++] = e1;
            if (!it1.hasNext() || !it2.hasNext()) {
                break;
            }
            e1 = it1.next();
            e2 = it2.next();
        } else if (compare == 1) {
            if (!it2.hasNext()) {
                break;
            }
            e2 = it2.next();
        } else {
            if (!it1.hasNext()) {
                break;
            }
            e1 = it1.next();
        }
    }
    return new ArraySortedSet(result, 0, i);
}

From source file:org.codehaus.mojo.license.api.DefaultThirdPartyTool.java

/**
 * {@inheritDoc}/*from ww w .j  ava2s  .  c om*/
 */
public SortedProperties loadUnsafeMapping(LicenseMap licenseMap, SortedMap<String, MavenProject> artifactCache,
        String encoding, File missingFile) throws IOException {
    SortedSet<MavenProject> unsafeDependencies = getProjectsWithNoLicense(licenseMap, false);

    SortedProperties unsafeMappings = new SortedProperties(encoding);

    if (missingFile.exists()) {
        // there is some unsafe dependencies

        getLogger().info("Load missing file " + missingFile);

        // load the missing file
        unsafeMappings.load(missingFile);
    }

    // get from the missing file, all unknown dependencies
    List<String> unknownDependenciesId = new ArrayList<String>();

    // coming from maven-license-plugin, we used the full g/a/v/c/t. Now we remove classifier and type
    // since GAV is good enough to qualify a license of any artifact of it...
    Map<String, String> migrateKeys = migrateMissingFileKeys(unsafeMappings.keySet());

    for (Object o : migrateKeys.keySet()) {
        String id = (String) o;
        String migratedId = migrateKeys.get(id);

        MavenProject project = artifactCache.get(migratedId);
        if (project == null) {
            // now we are sure this is a unknown dependency
            unknownDependenciesId.add(id);
        } else {
            if (!id.equals(migratedId)) {

                // migrates id to migratedId
                getLogger().info("Migrates [" + id + "] to [" + migratedId + "] in the missing file.");
                Object value = unsafeMappings.get(id);
                unsafeMappings.remove(id);
                unsafeMappings.put(migratedId, value);
            }
        }
    }

    if (!unknownDependenciesId.isEmpty()) {

        // there is some unknown dependencies in the missing file, remove them
        for (String id : unknownDependenciesId) {
            getLogger().warn(
                    "dependency [" + id + "] does not exist in project, remove it from the missing file.");
            unsafeMappings.remove(id);
        }

        unknownDependenciesId.clear();
    }

    // push back loaded dependencies
    for (Object o : unsafeMappings.keySet()) {
        String id = (String) o;

        MavenProject project = artifactCache.get(id);
        if (project == null) {
            getLogger().warn("dependency [" + id + "] does not exist in project.");
            continue;
        }

        String license = (String) unsafeMappings.get(id);
        if (StringUtils.isEmpty(license)) {

            // empty license means not fill, skip it
            continue;
        }

        // add license in map
        addLicense(licenseMap, project, license);

        // remove unknown license
        unsafeDependencies.remove(project);
    }

    if (unsafeDependencies.isEmpty()) {

        // no more unknown license in map
        licenseMap.remove(LicenseMap.UNKNOWN_LICENSE_MESSAGE);
    } else {

        // add a "with no value license" for missing dependencies
        for (MavenProject project : unsafeDependencies) {
            String id = MojoHelper.getArtifactId(project.getArtifact());
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("dependency [" + id + "] has no license, add it in the missing file.");
            }
            unsafeMappings.setProperty(id, "");
        }
    }
    return unsafeMappings;
}

From source file:net.sourceforge.fenixedu.domain.StudentCurricularPlan.java

final public ExecutionYear getApprovedCurriculumLinesLastExecutionYear() {
    if (getRoot() != null) {
        return getRoot().getApprovedCurriculumLinesLastExecutionYear();
    } else {//from  ww w .  j  a  v  a  2  s. co m
        final SortedSet<ExecutionYear> executionYears = new TreeSet<ExecutionYear>(
                ExecutionYear.COMPARATOR_BY_YEAR);

        for (final CurriculumLine curriculumLine : getAprovedEnrolments()) {
            if (curriculumLine.hasExecutionPeriod()) {
                executionYears.add(curriculumLine.getExecutionPeriod().getExecutionYear());
            }
        }

        return executionYears.isEmpty() ? ExecutionYear.readCurrentExecutionYear() : executionYears.last();
    }
}

From source file:org.codehaus.mojo.license.LicenseMap.java

protected SortedProperties loadUnsafeMapping(SortedMap<String, MavenProject> artifactCache, String encoding,
        File missingFile) throws IOException, ProjectBuildingException {

    SortedSet<MavenProject> unsafeDependencies = getUnsafeDependencies();

    SortedProperties unsafeMappings = new SortedProperties(encoding);

    // there is some unsafe dependencies
    if (missingFile.exists()) {

        getLog().info("Load missing file " + missingFile);

        // load the missing file
        unsafeMappings.load(missingFile);
    }/*from   w  w  w.jav a 2s.  c  om*/

    // get from the missing file, all unknown dependencies
    List<String> unknownDependenciesId = new ArrayList<String>();

    // migrate unsafe mapping (before version 3.0 we do not have the type of
    // dependency in the missing file, now we must deal with it, so check it

    List<String> migrateId = new ArrayList<String>();
    //        SortedMap<String, MavenProject> artifactCache = AbstractAddThirdPartyMojo.getArtifactCache();
    for (Object o : unsafeMappings.keySet()) {
        String id = (String) o;
        MavenProject project = artifactCache.get(id);
        if (project == null) {
            // try with the --jar type
            project = artifactCache.get(id + "--jar");
            if (project == null) {

                // now we are sure this is a unknown dependency
                unknownDependenciesId.add(id);
            } else {

                // this dependency must be migrated
                migrateId.add(id);
            }
        }
    }

    if (!unknownDependenciesId.isEmpty()) {

        // there is some unknown dependencies in the missing file, remove them
        for (String id : unknownDependenciesId) {
            getLog().warn(
                    "dependency [" + id + "] does not exists in project, remove it from the missing file.");
            unsafeMappings.remove(id);
        }

        unknownDependenciesId.clear();
    }

    if (!migrateId.isEmpty()) {

        // there is some dependencies to migrate in the missing file
        for (String id : migrateId) {
            String newId = id + "--jar";
            getLog().info("Migrate " + id + " to " + newId + " in the missing file.");
            Object value = unsafeMappings.get(id);
            unsafeMappings.remove(id);
            unsafeMappings.put(newId, value);
        }

        migrateId.clear();
    }

    // push back loaded dependencies
    for (Object o : unsafeMappings.keySet()) {
        String id = (String) o;

        MavenProject project = artifactCache.get(id);
        if (project == null) {
            getLog().warn("dependency [" + id + "] does not exists in project.");
            continue;
        }

        String license = (String) unsafeMappings.get(id);
        if (StringUtils.isEmpty(license)) {

            // empty license means not fill, skip it
            continue;
        }

        // add license in map
        License l = new License();
        l.setName(license.trim());
        l.setUrl(license.trim());

        // add license
        addLicense(project, Arrays.asList(l));

        // remove unknown license
        unsafeDependencies.remove(project);
    }

    if (unsafeDependencies.isEmpty()) {

        // no more unknown license in map
        remove(getUnknownLicenseMessage());
    } else {

        // add a "with no value license" for missing dependencies
        for (MavenProject project : unsafeDependencies) {
            String id = ArtifactHelper.getArtifactId(project.getArtifact());
            unsafeMappings.setProperty(id, "");
        }
    }
    return unsafeMappings;
}

From source file:net.sourceforge.fenixedu.domain.StudentCurricularPlan.java

final public CurriculumLine getLastApprovement() {
    final SortedSet<CurriculumLine> curriculumLines = new TreeSet<CurriculumLine>(
            CurriculumLine.COMPARATOR_BY_APPROVEMENT_DATE_AND_ID);

    if (getRoot() != null) {
        for (final CurriculumModule module : getRoot().getCurriculumModulesSet()) {
            if (!module.isNoCourseGroupCurriculumGroup()) {
                module.addApprovedCurriculumLines(curriculumLines);
            }//from www .j  a v a2  s .  c  om
        }
    } else {
        curriculumLines.addAll(getAprovedEnrolments());
    }

    return curriculumLines.isEmpty() ? null : curriculumLines.last();
}