Example usage for com.google.common.collect SetMultimap put

List of usage examples for com.google.common.collect SetMultimap put

Introduction

In this page you can find the example usage for com.google.common.collect SetMultimap put.

Prototype

boolean put(@Nullable K key, @Nullable V value);

Source Link

Document

Stores a key-value pair in this multimap.

Usage

From source file:lu.list.itis.dkd.aig.process.OnDemandTextOntologyCreationProcess.java

/**
 * {@inheritDoc}<br>/*from w  w  w. j  a v  a  2s.c o  m*/
 *
 * The method will execute a query to Jena, encoding key variables as
 * necessary. The latter will be stored in a local {@link BiMap} for easy
 * referencing. The query solution is then
 *
 * @throws ResolutionException
 *
 * @throws TemplateConsistencyException
 *             Thrown when one or more variables, respectively their values,
 *             were found in the query that could not be identified, i.e.
 *             their identifier was not a valid URI or not mapped due to
 *             variable definitions containing errors.
 */
@Override
public void initializeVariables(final Map<String, String> input, final SetMultimap<URI, Variable> variables)
        throws ResolutionException, TemplateConsistencyException {

    configureClozeGenerator();

    ClozeText clozeText = new ClozeText(input.get("text"), "body", Language.EN, approach, numberOfDistractors, //$NON-NLS-1$
            skipFirstSentence);

    TextOntology textOntology = new TextOntology(clozeText, "onDemandCloze");
    ClozeOntology clozeOntology = new ClozeOntology(clozeText, textOntology);
    //clozeOntology.save("C:\\Temp", "OWL");

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    clozeOntology.save(outputStream);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

    String dataSetNamePrefix = PropertiesFetcher.getProperties().getProperty(Externalization.FUSEKI_DATASET)
            + '_';
    String dataSetName = FusekiHttpHelper.createRandomDataSetName(dataSetNamePrefix);
    try {
        FusekiHttpHelper.createDataSet(dataSetName);
        FusekiHttpHelper.uploadOntology(inputStream, dataSetName, null);
    } catch (IOException | org.apache.http.HttpException e) {
        throw new ResolutionException("Failed to create dataset", e);
    }

    // set datasetname
    URL endpoint;
    try {
        endpoint = FusekiHttpHelper.getSparqlEndPoint(dataSetName);
    } catch (MalformedURLException e) {
        throw new ResolutionException("Failed to get endpoint address", e);
    }

    datasourceValue.setInnerValueTo(endpoint.toString());
    variables.put(datasourceVariable.getIdentifier(), datasourceVariable);

}

From source file:ome.services.graphs.GraphTraversal.java

/**
 * Get the model objects that are linked to by the given object via the given property.
 * Provides a window into the model object cache accumulated in planning a graph operation.
 * @param propertyValueClass the full name of the model class that declares the given property
 * @param propertyName a property name, may be nested
 * @param id the ID of the model object doing the linking
 * @return the class and ID of the model objects that are linked to by the given object, never {@code null}
 *//*w w  w .  j  a  va  2  s . c  om*/
public SetMultimap<String, Long> getLinkeds(String propertyValueClass, String propertyName, Long id) {
    if (!progress.contains(Milestone.PLANNED)) {
        throw new IllegalStateException("operation not yet planned");
    }
    final SetMultimap<String, Long> linkeds = HashMultimap.create();
    for (final CI linked : planning.forwardLinksCached.get(new CPI(propertyValueClass, propertyName, id))) {
        linkeds.put(linked.className, linked.id);
    }
    return linkeds;
}

From source file:ome.services.graphs.GraphTraversal.java

/**
 * Get the model objects that link to the given object via the given property.
 * Provides a window into the model object cache accumulated in planning a graph operation.
 * @param propertyValueClass the full name of the model class that declares the given property
 * @param propertyName a property name, may be nested
 * @param id the ID of the model object being linked to
 * @return the class and ID of the model objects that link to the given object, never {@code null}
 *///from  w  w w .  j  a va2 s.com
public SetMultimap<String, Long> getLinkers(String propertyValueClass, String propertyName, Long id) {
    if (!progress.contains(Milestone.PLANNED)) {
        throw new IllegalStateException("operation not yet planned");
    }
    final SetMultimap<String, Long> linkers = HashMultimap.create();
    for (final CI linker : planning.backwardLinksCached.get(new CPI(propertyValueClass, propertyName, id))) {
        linkers.put(linker.className, linker.id);
    }
    return linkers;
}

From source file:dagger.internal.codegen.ComponentValidator.java

/**
 * Validates the given component subject. Also validates any referenced subcomponents that aren't
 * already included in the {@code validatedSubcomponents} set.
 *//* w  w w . j  a  v  a 2  s.c o  m*/
public ComponentValidationReport validate(final TypeElement subject,
        Set<? extends Element> validatedSubcomponents, Set<? extends Element> validatedSubcomponentBuilders) {
    ValidationReport.Builder<TypeElement> builder = ValidationReport.about(subject);

    ComponentDescriptor.Kind componentKind = ComponentDescriptor.Kind.forAnnotatedElement(subject).get();

    if (!subject.getKind().equals(INTERFACE)
            && !(subject.getKind().equals(CLASS) && subject.getModifiers().contains(ABSTRACT))) {
        builder.addError(String.format("@%s may only be applied to an interface or abstract class",
                componentKind.annotationType().getSimpleName()), subject);
    }

    ImmutableList<DeclaredType> builders = enclosedBuilders(subject, componentKind.builderAnnotationType());

    if (builders.isEmpty()) {
        final String subjectName = subject.getQualifiedName().toString();
        builder.addError(
                String.format(ErrorMessages.builderMsgsFor(componentKind).noBuilderPresent(), subjectName));
    }

    if (builders.size() > 1) {
        builder.addError(String.format(ErrorMessages.builderMsgsFor(componentKind).moreThanOne(), builders),
                subject);
    }

    Optional<AnnotationMirror> reusableAnnotation = getAnnotationMirror(subject, Reusable.class);
    if (reusableAnnotation.isPresent()) {
        builder.addError(COMPONENT_ANNOTATED_REUSABLE, subject, reusableAnnotation.get());
    }

    DeclaredType subjectType = MoreTypes.asDeclared(subject.asType());

    SetMultimap<Element, ExecutableElement> referencedSubcomponents = LinkedHashMultimap.create();
    getLocalAndInheritedMethods(subject, types, elements).stream()
            .filter(method -> method.getModifiers().contains(ABSTRACT)).forEachOrdered(method -> {
                ExecutableType resolvedMethod = asExecutable(types.asMemberOf(subjectType, method));
                List<? extends TypeMirror> parameterTypes = resolvedMethod.getParameterTypes();
                List<? extends VariableElement> parameters = method.getParameters();
                TypeMirror returnType = resolvedMethod.getReturnType();

                // abstract methods are ones we have to implement, so they each need to be validated
                // first, check the return type. if it's a subcomponent, validate that method as such.
                Optional<AnnotationMirror> subcomponentAnnotation = checkForAnnotations(returnType,
                        FluentIterable.from(componentKind.subcomponentKinds()).transform(Kind::annotationType)
                                .toSet());
                Optional<AnnotationMirror> subcomponentBuilderAnnotation = checkForAnnotations(returnType,
                        FluentIterable.from(componentKind.subcomponentKinds())
                                .transform(Kind::builderAnnotationType).toSet());
                if (subcomponentAnnotation.isPresent()) {
                    referencedSubcomponents.put(MoreTypes.asElement(returnType), method);
                    validateSubcomponentMethod(builder,
                            ComponentDescriptor.Kind.forAnnotatedElement(MoreTypes.asTypeElement(returnType))
                                    .get(),
                            method, parameters, parameterTypes, returnType, subcomponentAnnotation);
                } else if (subcomponentBuilderAnnotation.isPresent()) {
                    referencedSubcomponents.put(MoreTypes.asElement(returnType).getEnclosingElement(), method);
                    validateSubcomponentBuilderMethod(builder, method, parameters, returnType,
                            validatedSubcomponentBuilders);
                } else {
                    // if it's not a subcomponent...
                    switch (parameters.size()) {
                    case 0:
                        // no parameters means that it is a provision method
                        // basically, there are no restrictions here.  \o/
                        break;
                    case 1:
                        // one parameter means that it's a members injection method
                        TypeMirror onlyParameter = Iterables.getOnlyElement(parameterTypes);
                        if (!(returnType.getKind().equals(VOID)
                                || types.isSameType(returnType, onlyParameter))) {
                            builder.addError(
                                    "Members injection methods may only return the injected type or void.",
                                    method);
                        }
                        break;
                    default:
                        // this isn't any method that we know how to implement...
                        builder.addError(
                                "This method isn't a valid provision method, members injection method or "
                                        + "subcomponent factory method. Dagger cannot implement this method",
                                method);
                        break;
                    }
                }
            });

    Maps.filterValues(referencedSubcomponents.asMap(), methods -> methods.size() > 1)
            .forEach((subcomponent,
                    methods) -> builder.addError(String.format(
                            ErrorMessages.SubcomponentBuilderMessages.INSTANCE.moreThanOneRefToSubcomponent(),
                            subcomponent, methods), subject));

    AnnotationMirror componentMirror = getAnnotationMirror(subject, componentKind.annotationType()).get();
    if (componentKind.isTopLevel()) {
        validateComponentDependencies(builder, getComponentDependencies(componentMirror));
    }
    builder.addSubreport(
            moduleValidator.validateReferencedModules(subject, componentMirror, componentKind.moduleKinds()));

    // Make sure we validate any subcomponents we're referencing, unless we know we validated
    // them already in this pass.
    // TODO(sameb): If subcomponents refer to each other and both aren't in
    //              'validatedSubcomponents' (e.g, both aren't compiled in this pass),
    //              then this can loop forever.
    ImmutableSet.Builder<Element> allSubcomponents = ImmutableSet.<Element>builder()
            .addAll(referencedSubcomponents.keySet());
    for (Element subcomponent : Sets.difference(referencedSubcomponents.keySet(), validatedSubcomponents)) {
        ComponentValidationReport subreport = subcomponentValidator.validate(MoreElements.asType(subcomponent),
                validatedSubcomponents, validatedSubcomponentBuilders);
        builder.addItems(subreport.report().items());
        allSubcomponents.addAll(subreport.referencedSubcomponents());
    }

    return new AutoValue_ComponentValidator_ComponentValidationReport(allSubcomponents.build(),
            builder.build());
}

From source file:ome.services.graphs.GraphTraversal.java

/**
 * Note a linked object to remove from a linker property's {@link Collection} value.
 * @param linkerToIdToLinked the map from linker property to linker ID to objects in {@link Collection}s
 * @param linker the linker object/*from   w  w w .  j  a  v a2s  . co m*/
 * @param linked the linked object
 */
private void addRemoval(Map<CP, SetMultimap<Long, Entry<String, Long>>> linkerToIdToLinked, CPI linker,
        CI linked) {
    if (model.isPropertyAccessible(linker.className, linker.propertyName)) {
        SetMultimap<Long, Entry<String, Long>> idMap = linkerToIdToLinked.get(linker.toCP());
        if (idMap == null) {
            idMap = HashMultimap.create();
            linkerToIdToLinked.put(linker.toCP(), idMap);
        }
        idMap.put(linker.id, Maps.immutableEntry(linked.className, linked.id));
    }
}

From source file:it.sayservice.platform.smartplanner.cache.annotated.AnnotatedReader.java

public void buildTimetable(String router, String agencyId, boolean setTripsIds,
        List<AnnotatedTimetable> timetables) throws Exception {
    AgencyCacheIndex aci = new AgencyCacheIndex(agencyId);
    aci.setVersion(1);/*from w w  w  .  ja  v  a  2s .c om*/

    ObjectMapper mapper = new ObjectMapper();

    String cacheDir = System.getenv("OTP_HOME") + System.getProperty("file.separator") + router
            + System.getProperty("file.separator") + "cache" + System.getProperty("file.separator") + "client";
    String agencyDir = cacheDir + System.getProperty("file.separator") + agencyId;
    File dir = new File(agencyDir);
    if (!dir.exists()) {
        dir.mkdir();
    } else {
        for (File f : dir.listFiles()) {
            f.delete();
        }
    }

    Map<String, WeekdayFilter> weekdayFilter = handler.readAgencyWeekDay(router, agencyId);
    Map<String, WeekdayException> weekdayException = handler.readAgencyWeekDayExceptions(router, agencyId);

    Multimap<String, ExtendedAnnotatedColumn> extendedAnnotatedColumn = createExtendedAnnotatedColumns(
            timetables);
    SetMultimap<String, String> tripsSymbolicRouteId = TreeMultimap.create();

    List<SymbolicRouteDayInfoHashCalendar> agencySrdihs = Lists.newArrayList();

    for (String rId : extendedAnnotatedColumn.keySet()) {
        System.out.println("Generating " + rId);

        Map<String, AnnotatedColumn> tripsColumns = Maps.newTreeMap();
        Map<String, AnnotatedTimetable> tripsTable = Maps.newTreeMap();
        Map<String, AnnotatedTimetable> serviceTable = Maps.newTreeMap();

        AnnotatedTimetable baseTable = null;

        Multimap<String, String> daysTrips = ArrayListMultimap.create();
        SetMultimap<String, String> daysServices = TreeMultimap.create();
        Map<String, AnnotatedTimetable> daysTable = Maps.newTreeMap();
        Map<String, String> daysHashes = Maps.newTreeMap();
        Map<String, String> tripsRoutes = Maps.newTreeMap();

        for (ExtendedAnnotatedColumn ac : extendedAnnotatedColumn.get(rId)) {
            baseTable = ac.getSource();

            String tripId = agencyId + "_" + ac.getTripId();
            tripsSymbolicRouteId.put(tripId, rId);
            tripsRoutes.put(ac.getTripId(), ac.getRouteId());

            tripsColumns.put(tripId, ac);

            tripsTable.put(tripId, ac.getSource());

            String serviceId = agencyId + "_" + ac.getServiceId();

            serviceTable.put(serviceId, ac.getSource());

            WeekdayFilter filter = weekdayFilter.get(serviceId);
            if (filter == null) {
                System.out.println("ServiceId not found: " + serviceId);
            }

            Set<String> days = Sets.newHashSet();

            DateFormat df = new SimpleDateFormat("yyyyMMdd");
            String from = filter.getFromDate();
            String to = filter.getToDate();

            Calendar fromDate = new GregorianCalendar();
            Calendar toDate = new GregorianCalendar();

            fromDate.setTime(df.parse(from));
            toDate.setTime(df.parse(to));
            Calendar date = new GregorianCalendar();
            date.setTime(fromDate.getTime());
            String prevDay = null;

            while (df.format(date.getTime()).compareTo(to) <= 0) {
                String day = df.format(date.getTime());

                boolean sameDay = day.equals(prevDay);

                if (!sameDay) {
                    int dotw = convertDayOfTheWeek(date.get(Calendar.DAY_OF_WEEK));
                    if (filter.getDays()[dotw]) {
                        days.add(day);
                    }
                }
                prevDay = day;
                date.setTime(new Date(date.getTime().getTime()));
                date.add(Calendar.DAY_OF_YEAR, 1);
            }

            WeekdayException ex = weekdayException.get(serviceId);
            if (ex != null) {
                for (String toAdd : ex.getAdded()) {
                    days.add(toAdd);
                }
                for (String toRemove : ex.getRemoved()) {
                    days.remove(toRemove);
                }
            }

            ac.setDays(Lists.newArrayList(days));

            for (String day : days) {
                daysTable.put(day, baseTable);
                daysTrips.put(day, tripId);
                daysServices.put(day, serviceId);
            }

        }

        Map<String, CacheTable> hashTable = Maps.newTreeMap();

        SymbolicRouteDayInfoHashCalendar srdihs = new SymbolicRouteDayInfoHashCalendar();
        srdihs.setAgencyId(agencyId);
        agencySrdihs.add(srdihs);

        Map<String, String> srdihsCalendar = Maps.newTreeMap();
        Map<String, SymbolicRouteDayInfo> srdihsValues = Maps.newTreeMap();
        srdihs.setCalendar(srdihsCalendar);
        srdihs.setValues(srdihsValues);
        srdihs.setRouteId(rId);

        for (String day : daysTrips.keySet()) {
            List<String> dayTrips = Lists.newArrayList(daysTrips.get(day));
            List<String> dayServices = Lists.newArrayList(daysServices.get(day));
            String hash = getEqString(dayServices, agencyId);

            if (daysHashes.containsKey(day)) {
                continue;
            }

            daysHashes.put(day, hash);
            Set<String> dayServicesSet = daysServices.get(day);

            AnnotatedTimetable reducedTable = reduceAnnotatedTimetable(daysTable.get(day), dayServicesSet,
                    agencyId);

            CacheTable ct = new CacheTable();

            List<String> tripIds = Lists.newArrayList();
            List<List<String>> compressedTimes = Lists.newArrayList();
            ct.setTimes(compressedTimes);

            for (String trip : dayTrips) {
                int index = trip.indexOf("_");
                tripIds.add(trip.substring(index + 1));
                compressedTimes.add(tripsColumns.get(trip).getTimes());
            }

            if (setTripsIds) {
                ct.setTripIds(tripIds);
            }

            List<String> routesIds = Lists.newArrayList();
            for (String ti : tripIds) {
                routesIds.add(tripsRoutes.get(ti));
            }

            ct.setStops(reducedTable.getStopNames());
            ct.setStopsId(reducedTable.getStopIds());
            ct.setInvisibles(reducedTable.getInvisibles());
            ct.setFrequency(reducedTable.getFrequency());
            ct.setLine(reducedTable.getLine());
            ct.setRoutesIds(routesIds);

            ct.setShortDescription(reducedTable.getShortDescription());
            ct.setLongDescription(reducedTable.getLongDescription());
            ct.setValidity(reducedTable.getValidity());
            ct.setSchedule(reducedTable.getSchedule());

            ct.compress();

            hashTable.put(hash, ct);

            if (!srdihsValues.containsKey(hash)) {
                SymbolicRouteDayInfo srdi = new SymbolicRouteDayInfo(reducedTable);
                StopNames sn = new StopNames();
                sn.setRouteId(rId);
                sn.setIds(reducedTable.getStopIds());
                sn.setNames(reducedTable.getStopNames());
                srdi.setStopNames(sn);
                srdi.setTripIds(tripIds);
                srdihsValues.put(hash, srdi);
            }
            srdihsCalendar.put(day, hash);
        }

        System.out.println("Writing " + rId);

        String calendar = agencyDir + System.getProperty("file.separator") + "calendar_" + rId + ".js";
        mapper.writeValue(new File(calendar), daysHashes);
        for (String hash : hashTable.keySet()) {
            String hashFile = agencyDir + System.getProperty("file.separator") + rId + "_" + hash + ".js";
            mapper.writeValue(new File(hashFile), hashTable.get(hash));

            CacheIndexEntry cie = new CacheIndexEntry();
            cie.setId(rId + "_" + hash);
            cie.setVersion(1);
            cie.setStatus(CacheEntryStatus.ADDED);
            aci.getEntries().put(rId + "_" + hash, cie);
        }

    }

    String indexFile = cacheDir + System.getProperty("file.separator") + agencyId + "_index.txt";
    File aciFile = new File(indexFile);
    if (aciFile.exists()) {
        AgencyCacheIndex oldAci = mapper.readValue(aciFile, AgencyCacheIndex.class);
        aci.setVersion(oldAci.getVersion() + 1);
    }
    mapper.writeValue(new File(indexFile), aci);

    String auxDir = cacheDir + System.getProperty("file.separator") + Constants.AUXILIARY_CACHE_DIR;
    String infoFile = auxDir + System.getProperty("file.separator") + agencyId + "_info.txt";
    mapper.writeValue(new File(infoFile), agencySrdihs);

    String symbolicFile = auxDir + System.getProperty("file.separator") + agencyId + "_symbolic_trips.txt";

    Map<String, Collection<String>> map = Maps.newTreeMap();
    for (String key : tripsSymbolicRouteId.keys()) {
        List<String> rids = Lists.newArrayList();
        rids.addAll(tripsSymbolicRouteId.get(key));
        map.put(key, rids);
    }

    mapper.writeValue(new File(symbolicFile), map);
}

From source file:ome.services.graphs.GraphTraversal.java

/**
 * Load a specific link property's object relationships into the various cache fields of {@link Planning}.
 * @param linkProperty the link property being processed
 * @param query the HQL to query the property's object relationships
 * @param ids the IDs of the related objects
 * @return which linker objects are related to which linked objects by the given property
 * @throws GraphException if the objects could not be converted to unloaded instances
 */// w  ww .jav a 2  s.com
private List<Entry<CI, CI>> getLinksToCache(CP linkProperty, String query, Collection<Long> ids)
        throws GraphException {
    final String linkedClassName = getLinkedClass(linkProperty);
    final boolean propertyIsAccessible = model.isPropertyAccessible(linkProperty.className,
            linkProperty.propertyName);
    final SetMultimap<Long, Long> linkerToLinked = HashMultimap.create();
    for (final List<Long> idsBatch : Iterables.partition(ids, BATCH_SIZE)) {
        for (final Object[] result : (List<Object[]>) session.createQuery(query)
                .setParameterList("ids", idsBatch).list()) {
            linkerToLinked.put((Long) result[0], (Long) result[1]);
        }
    }
    final List<Entry<CI, CI>> linkerLinked = new ArrayList<Entry<CI, CI>>();
    final Map<Long, CI> linkersById = findObjectDetails(linkProperty.className, linkerToLinked.keySet());
    final Map<Long, CI> linkedsById = findObjectDetails(linkedClassName,
            new HashSet<Long>(linkerToLinked.values()));
    for (final Entry<Long, Long> linkerIdLinkedId : linkerToLinked.entries()) {
        final CI linker = linkersById.get(linkerIdLinkedId.getKey());
        final CI linked = linkedsById.get(linkerIdLinkedId.getValue());
        if (!planning.detailsNoted.containsKey(linker)) {
            log.warn("failed to query for " + linker);
        } else if (!planning.detailsNoted.containsKey(linked)) {
            log.warn("failed to query for " + linked);
        } else {
            linkerLinked.add(Maps.immutableEntry(linker, linked));
            if (propertyIsAccessible) {
                planning.befores.put(linked, linker);
                planning.afters.put(linker, linked);
            }
            if (log.isDebugEnabled()) {
                log.debug(linkProperty.toCPI(linker.id) + " links to " + linked);
            }
        }
    }
    return linkerLinked;
}

From source file:ome.services.graphs.GraphTraversal.java

/**
 * Prepare to process the targeted model objects.
 * @return the actual processor for the targeted model objects, to be used by the caller
 * @throws GraphException if the user does not have permission to process the targets or
 * if a cycle is detected in the model object graph
 *//*from   w  w  w . java  2 s  .  c om*/
public PlanExecutor processTargets() throws GraphException {
    if (!progress.contains(Milestone.PLANNED)) {
        throw new IllegalStateException("operation not yet planned");
    }
    final List<Entry<Map<String, Collection<Long>>, Map<String, Collection<Long>>>> toJoinAndDelete = new ArrayList<Entry<Map<String, Collection<Long>>, Map<String, Collection<Long>>>>();
    /* process the targets forward across links */
    while (!planning.blockedBy.isEmpty()) {
        /* determine which objects can be processed in this step */
        final Collection<CI> nowUnblocked = new HashSet<CI>();
        final Iterator<Entry<CI, Set<CI>>> blocks = planning.blockedBy.entrySet().iterator();
        while (blocks.hasNext()) {
            final Entry<CI, Set<CI>> block = blocks.next();
            final CI object = block.getKey();
            if (block.getValue().isEmpty()) {
                blocks.remove();
                nowUnblocked.add(object);
            }
        }
        if (nowUnblocked.isEmpty()) {
            throw new GraphException(
                    "cycle detected among " + Joiner.on(", ").join(planning.blockedBy.keySet()));
        }
        for (final Set<CI> blockers : planning.blockedBy.values()) {
            blockers.removeAll(nowUnblocked);
        }
        final SetMultimap<String, Long> toJoin = HashMultimap.create();
        final SetMultimap<String, Long> toDelete = HashMultimap.create();
        for (final CI object : nowUnblocked) {
            if (planning.included.contains(object)) {
                toJoin.put(object.className, object.id);
            } else {
                toDelete.put(object.className, object.id);
            }
        }
        /* note this group's includes and deletes */
        final Map<String, Collection<Long>> eachToJoin = toJoin.asMap();
        for (final Entry<String, Collection<Long>> oneClassToJoin : eachToJoin.entrySet()) {
            final String className = oneClassToJoin.getKey();
            final Collection<Long> allIds = oneClassToJoin.getValue();
            assertMayBeProcessed(className, allIds);
        }
        final Map<String, Collection<Long>> eachToDelete = toDelete.asMap();
        for (final Entry<String, Collection<Long>> oneClassToDelete : eachToDelete.entrySet()) {
            final String className = oneClassToDelete.getKey();
            final Collection<Long> allIds = oneClassToDelete.getValue();
            assertMayBeDeleted(className, allIds);
        }
        toJoinAndDelete.add(Maps.immutableEntry(eachToJoin, eachToDelete));
    }
    return new PlanExecutor() {
        @Override
        public void execute() throws GraphException {
            if (!progress.contains(Milestone.UNLINKED)) {
                throw new IllegalStateException("model objects not yet unlinked");
            }
            if (progress.contains(Milestone.PROCESSED)) {
                throw new IllegalStateException("model objects already processed");
            }
            /* actually do the noted processing */
            for (final Entry<Map<String, Collection<Long>>, Map<String, Collection<Long>>> next : toJoinAndDelete) {
                final Map<String, Collection<Long>> toJoin = next.getKey();
                final Map<String, Collection<Long>> toDelete = next.getValue();
                /* perform this group's deletes */
                if (!toDelete.isEmpty()) {
                    for (final Entry<String, Collection<Long>> oneClassToDelete : toDelete.entrySet()) {
                        final String className = oneClassToDelete.getKey();
                        final Collection<Long> allIds = oneClassToDelete.getValue();
                        final Collection<Collection<Long>> idGroups;
                        if (OriginalFile.class.getName().equals(className)) {
                            idGroups = ModelObjectSequencer.sortOriginalFileIds(session, allIds);
                        } else {
                            idGroups = Collections.singleton(allIds);
                        }
                        for (final Collection<Long> idGroup : idGroups) {
                            for (final List<Long> ids : Iterables.partition(idGroup, BATCH_SIZE)) {
                                processor.deleteInstances(className, ids);
                            }
                        }
                    }
                }
                /* perform this group's includes */
                if (!toJoin.isEmpty()) {
                    for (final Entry<String, Collection<Long>> oneClassToJoin : toJoin.entrySet()) {
                        final String className = oneClassToJoin.getKey();
                        final Collection<Long> allIds = oneClassToJoin.getValue();
                        for (final List<Long> ids : Iterables.partition(allIds, BATCH_SIZE)) {
                            processor.processInstances(className, ids);
                        }
                    }
                }
            }
            progress.add(Milestone.PROCESSED);
        }
    };
}

From source file:dk.dma.nogoservice.service.NoGoResponseMerger.java

/**
 * Merge algorithm for multiple NoGoAreas.
 * <p>//from   w ww . j a  v a 2s .  co m
 * <ol>
 * <li>Find the exclusive zone for each area (the space that is not overlapped with other areas) </li>
 * <li>Find all the combinations of overlaps. </li>
 * <li>In the exclusive zone the nogo polygons (after the overlaps have been extracted) can be used directly</li>
 * <li>In the overlap zones the intersections of NoGo areas, will define the actual NoGo areas, because Go wins over NoGO (as foreign territory is nogo)</li>
 * </ol>
 *
 * @param areas the calculated NoGo areas
 * @return the response
 */
CalculatedNoGoArea merge(List<CalculatedNoGoArea> areas) {

    if (areas.size() == 1) {
        return areas.get(0);
    }

    SetMultimap<CalculatedNoGoArea, Geometry> unprocessed = HashMultimap.create();
    areas.forEach(a -> unprocessed.putAll(a, a.getNogoAreas()));

    List<Geometry> processedNogoAreas = new ArrayList<>();
    for (CalculatedNoGoArea area : areas) {
        List<CalculatedNoGoArea> copy = new ArrayList<>(areas);
        copy.remove(area);
        List<Geometry> otherAreas = copy.stream().map(CalculatedNoGoArea::getArea).collect(Collectors.toList());

        // we now have the exclusive zone for this area. Now find the polygons inside the exclusive zone, if a polygon intersects with the boundary of the
        // exclusive zone, then split it in two, the part inside the exclusive zone is done, the other part will be processed later inside the overlapped zone
        Set<Geometry> nogoAreas = new HashSet<>(unprocessed.get(area));

        // take all the nogo areas and calculate the intersection with the exclusive zone
        for (Geometry nogoArea : nogoAreas) {
            Geometry result = nogoArea;
            for (Geometry otherArea : otherAreas) {
                if (otherArea.intersects(nogoArea)) {
                    Geometry intersection = otherArea.intersection(nogoArea);
                    if (!intersection.isEmpty()) {
                        result = result.difference(otherArea);
                        // add the intersection pat of the NoGo area to the unprocessed set so we can process it during overlap handling
                        if (!result.isEmpty()) {
                            // if there was no difference, this nogo area is completely inside the other area
                            unprocessed.put(area, intersection);
                        }
                    }
                }
            }

            if (!result.isEmpty()) {
                processedNogoAreas.add(result);
                unprocessed.remove(area, nogoArea); // area has now been processed
            }
        }
    }

    // now process all combinations of overlaps
    Set<Overlap> overlapCombinations = calculateOverlapCombinations(areas);

    for (Overlap overlapCombination : overlapCombinations) {
        Geometry exclusiveOverlapArea = overlapCombination.getExclusiveArea();

        List<Geometry> nogoAreas = new ArrayList<>();
        overlapCombination.included.forEach(g -> nogoAreas.addAll(unprocessed.get(g)));
        List<Geometry> noGoLayers = overlapCombination.included.stream().map(unprocessed::get)
                .filter(g -> !g.isEmpty()).map(g -> iterativeOperation(g, Geometry::union))
                .collect(Collectors.toList());
        List<Geometry> goAreas = noGoLayers.stream().map(exclusiveOverlapArea::difference)
                .collect(Collectors.toList());
        if (!goAreas.isEmpty()) {
            // We need to join all the NoGo areas, in a way so Go wins over NoGo.
            Geometry totalGoArea = iterativeOperation(goAreas, Geometry::union);
            Geometry totalNoGoArea = exclusiveOverlapArea.difference(totalGoArea);
            if (!totalGoArea.isEmpty()) {
                processedNogoAreas.add(totalNoGoArea);
            }
        }
    }

    List<Geometry> collect = areas.stream().map(CalculatedNoGoArea::getArea).collect(Collectors.toList());
    Iterator<Geometry> iterator = collect.iterator();
    Geometry totalArea = iterator.next();
    while (iterator.hasNext()) {
        totalArea = totalArea.union(iterator.next());
    }

    TopologyPreservingSimplifier simplifier = new TopologyPreservingSimplifier(totalArea);
    totalArea = simplifier.getResultGeometry();

    // construct the result
    CalculatedNoGoArea result = new CalculatedNoGoArea();
    result.setArea(totalArea);
    result.setNogoAreas(processedNogoAreas);
    Optional<JSonWarning> optionalWarning = areas.stream().map(CalculatedNoGoArea::getWarning)
            .filter(Objects::nonNull).findFirst();
    optionalWarning.ifPresent(result::setWarning);

    return result;

}

From source file:ome.services.graphs.GraphTraversal.java

/**
 * Traverse model object graph to determine steps for the proposed operation.
 * @param session the Hibernate session to use for HQL queries
 * @param objectInstances the model objects to process, may be unloaded with ID only
 * @param include if the given model objects are to be included (instead of just deleted)
 * @param applyRules if the given model objects should have the policy rules applied to them
 * @return the model objects included in the operation, and the deleted objects, may be unloaded with ID only
 * @throws GraphException if the model objects were not as expected
 *///from  ww w  .  j  ava2  s . co  m
public Entry<Collection<IObject>, Collection<IObject>> planOperation(Session session,
        Collection<? extends IObject> objectInstances, boolean include, boolean applyRules)
        throws GraphException {
    if (progress.contains(Milestone.PLANNED)) {
        throw new IllegalStateException("operation already planned");
    }
    final Set<CI> targetSet = include ? planning.included : planning.deleted;
    /* note the object instances for processing */
    final SetMultimap<String, Long> objectsToQuery = HashMultimap.create();
    for (final IObject instance : objectInstances) {
        if (instance.isLoaded() && instance.getDetails() != null) {
            final CI object = new CI(instance);
            noteDetails(object, instance.getDetails());
            targetSet.add(object);
        } else {
            objectsToQuery.put(instance.getClass().getName(), instance.getId());
        }
    }
    targetSet.addAll(objectsToCIs(session, objectsToQuery));
    if (applyRules) {
        /* actually do the planning of the operation */
        planning.toProcess.addAll(targetSet);
        planOperation(session);
    } else {
        /* act as if the target objects have no links and no rules match them */
        for (final CI targetObject : targetSet) {
            planning.blockedBy.put(targetObject, new HashSet<CI>());
        }
    }
    progress.add(Milestone.PLANNED);
    /* report which objects are to be included in the operation or deleted so that it can proceed */
    final Collection<IObject> included = new ArrayList<IObject>(planning.included.size());
    for (final CI includedObject : planning.included) {
        included.add(includedObject.toIObject());
    }
    final Collection<IObject> deleted = new ArrayList<IObject>(planning.deleted.size());
    for (final CI deletedObject : planning.deleted) {
        deleted.add(deletedObject.toIObject());
    }
    return Maps.immutableEntry(included, deleted);
}