Example usage for com.google.common.base Predicates instanceOf

List of usage examples for com.google.common.base Predicates instanceOf

Introduction

In this page you can find the example usage for com.google.common.base Predicates instanceOf.

Prototype

@GwtIncompatible("Class.isInstance")
public static Predicate<Object> instanceOf(Class<?> clazz) 

Source Link

Document

Returns a predicate that evaluates to true if the object being tested is an instance of the given class.

Usage

From source file:org.eclipse.sirius.diagram.sequence.business.internal.operation.SynchronizeISequenceEventsSemanticOrderingOperation.java

private void updateSemanticPosition(ISequenceEvent eventToUpdate) {
    DDiagramElement dde = resolveDiagramElement(eventToUpdate);
    if (dde == null || reordered.contains(eventToUpdate)) {
        return;/*from   w w w . j a  v  a2 s  .  co  m*/
    }

    ReorderTool reorderTool = findReorderTool(dde);
    if (reorderTool == null) {
        return;
    }

    EObject semanticElement = dde.getTarget();
    EList<EventEnd> endsBySemanticOrder = sequenceDiagram.getSemanticOrdering().getEventEnds();
    EList<EventEnd> endsByGraphicalOrder = sequenceDiagram.getGraphicalOrdering().getEventEnds();

    List<EventEnd> ends = EventEndHelper.findEndsFromSemanticOrdering(eventToUpdate);
    List<EventEnd> compoundEnds = getCompoundEnds(eventToUpdate, ends);

    // Ignore the ends of the descendants: they are treated by recursive
    // calls.
    Set<EventEnd> toIgnore = selectEndsToIgnore(eventToUpdate, endsBySemanticOrder, ends, compoundEnds);

    // The semantic ordering contains the state before the move
    EventEnd startingEndPredecessorBefore = findEndPredecessor(semanticElement, STARTING_END,
            endsBySemanticOrder, toIgnore);
    EventEnd finishingEndPredecessorBefore = findEndPredecessor(semanticElement, FINISHING_END,
            endsBySemanticOrder, toIgnore);

    // The graphical ordering contains the state after
    EventEnd startingEndPredecessorAfter = findEndPredecessor(semanticElement, STARTING_END,
            endsByGraphicalOrder, toIgnore);
    EventEnd finishingEndPredecessorAfter = findEndPredecessor(semanticElement, FINISHING_END,
            endsByGraphicalOrder, toIgnore);

    // Handle lost messages
    if (eventToUpdate.isLogicallyInstantaneous() && eventToUpdate instanceof Message && ends.size() == 1
            && !Iterables.any(ends, Predicates.instanceOf(CompoundEventEnd.class))) {
        SingleEventEnd see = (SingleEventEnd) ends.iterator().next();
        if (see.isStart()) {
            finishingEndPredecessorBefore = startingEndPredecessorBefore;
            finishingEndPredecessorAfter = startingEndPredecessorAfter;
        } else {
            startingEndPredecessorBefore = finishingEndPredecessorBefore;
            startingEndPredecessorAfter = finishingEndPredecessorAfter;
        }

    }

    if (!Objects.equal(startingEndPredecessorBefore, startingEndPredecessorAfter)
            || !Objects.equal(finishingEndPredecessorBefore, finishingEndPredecessorAfter)
            || !Iterables.elementsEqual(endsByGraphicalOrder, endsBySemanticOrder)) {
        applySemanticReordering(semanticElement, startingEndPredecessorAfter, finishingEndPredecessorAfter,
                reorderTool);
        applyCompoundReordering(semanticElement, ends, compoundEnds, startingEndPredecessorAfter,
                finishingEndPredecessorAfter, reorderTool);
        reordered.add(eventToUpdate);

        new RefreshSemanticOrderingsOperation(sequenceDiagram).execute();
        updateSubEventsSemanticPositions(eventToUpdate);
    }
}

From source file:org.apache.brooklyn.entity.nosql.riak.RiakClusterImpl.java

protected void onServerPoolMemberChanged(final Entity member) {
    synchronized (mutex) {
        log.trace("For {}, considering membership of {} which is in locations {}",
                new Object[] { this, member, member.getLocations() });

        Map<Entity, String> nodes = getAttribute(RIAK_CLUSTER_NODES);
        if (belongsInServerPool(member)) {
            // TODO can we discover the nodes by asking the riak cluster, rather than assuming what we add will be in there?
            // TODO and can we do join as part of node starting?

            if (nodes == null) {
                nodes = Maps.newLinkedHashMap();
            }//from  ww w. j a  va2s  . co m
            String riakName = getRiakName(member);
            Preconditions.checkNotNull(riakName);

            // flag a first node to be the first node in the riak cluster.
            Boolean firstNode = getAttribute(IS_FIRST_NODE_SET);
            if (!Boolean.TRUE.equals(firstNode)) {
                sensors().set(IS_FIRST_NODE_SET, Boolean.TRUE);

                nodes.put(member, riakName);
                sensors().set(RIAK_CLUSTER_NODES, nodes);

                ((EntityInternal) member).sensors().set(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE);

                log.info("Added initial Riak node {}: {}; {} to new cluster",
                        new Object[] { this, member, getRiakName(member) });
            } else {
                // TODO: be wary of erroneous nodes but are still flagged 'in cluster'
                // add the new node to be part of the riak cluster.
                Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(), Predicates.and(
                        Predicates.instanceOf(RiakNode.class),
                        EntityPredicates.attributeEqualTo(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, true)));
                if (anyNodeInCluster.isPresent()) {
                    if (!nodes.containsKey(member)
                            && member.getAttribute(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER) == null) {
                        String anyNodeName = anyNodeInCluster.get().getAttribute(RiakNode.RIAK_NODE_NAME);
                        Entities.invokeEffectorWithArgs(this, member, RiakNode.JOIN_RIAK_CLUSTER, anyNodeName)
                                .blockUntilEnded();
                        nodes.put(member, riakName);
                        sensors().set(RIAK_CLUSTER_NODES, nodes);
                        log.info("Added Riak node {}: {}; {} to cluster",
                                new Object[] { this, member, getRiakName(member) });
                    }
                } else {
                    log.error("isFirstNodeSet, but no cluster members found to add {}", member.getId());
                }
            }
        } else {
            if (nodes != null && nodes.containsKey(member)) {
                DependentConfiguration.attributeWhenReady(member, RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER,
                        Predicates.equalTo(false)).blockUntilEnded(Duration.TWO_MINUTES);
                @SuppressWarnings("unchecked")
                Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(),
                        Predicates.and(Predicates.instanceOf(RiakNode.class),
                                EntityPredicates.attributeEqualTo(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, true),
                                Predicates.not(Predicates.equalTo(member))));
                if (anyNodeInCluster.isPresent()) {
                    Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(), RiakNode.REMOVE_FROM_CLUSTER,
                            getRiakName(member)).blockUntilEnded();
                }
                nodes.remove(member);
                sensors().set(RIAK_CLUSTER_NODES, nodes);
                log.info("Removed Riak node {}: {}; {} from cluster",
                        new Object[] { this, member, getRiakName(member) });
            }
        }

        ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyMap(this, RIAK_CLUSTER_NODES);

        calculateClusterAddresses();
    }
}

From source file:org.apache.impala.analysis.SelectStmt.java

/**
 * Creates resultExprs and baseTblResultExprs.
 *//*from   ww  w .  j a  v a 2  s .c om*/
@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
    if (isAnalyzed())
        return;
    super.analyze(analyzer);

    fromClause_.analyze(analyzer);

    // Generate !empty() predicates to filter out empty collections.
    // Skip this step when analyzing a WITH-clause because CollectionTableRefs
    // do not register collection slots in their parent in that context
    // (see CollectionTableRef.analyze()).
    if (!analyzer.isWithClause())
        registerIsNotEmptyPredicates(analyzer);

    // analyze plan hints from select list
    selectList_.analyzePlanHints(analyzer);

    // populate resultExprs_, aliasSmap_, and colLabels_
    for (int i = 0; i < selectList_.getItems().size(); ++i) {
        SelectListItem item = selectList_.getItems().get(i);
        if (item.isStar()) {
            if (item.getRawPath() != null) {
                Path resolvedPath = analyzeStarPath(item.getRawPath(), analyzer);
                expandStar(resolvedPath, analyzer);
            } else {
                expandStar(analyzer);
            }
        } else {
            // Analyze the resultExpr before generating a label to ensure enforcement
            // of expr child and depth limits (toColumn() label may call toSql()).
            item.getExpr().analyze(analyzer);
            if (item.getExpr().contains(Predicates.instanceOf(Subquery.class))) {
                throw new AnalysisException("Subqueries are not supported in the select list.");
            }
            resultExprs_.add(item.getExpr());
            String label = item.toColumnLabel(i, analyzer.useHiveColLabels());
            SlotRef aliasRef = new SlotRef(label);
            Expr existingAliasExpr = aliasSmap_.get(aliasRef);
            if (existingAliasExpr != null && !existingAliasExpr.equals(item.getExpr())) {
                // If we have already seen this alias, it refers to more than one column and
                // therefore is ambiguous.
                ambiguousAliasList_.add(aliasRef);
            }
            aliasSmap_.put(aliasRef, item.getExpr().clone());
            colLabels_.add(label);
        }
    }

    // Star exprs only expand to the scalar-typed columns/fields, so
    // the resultExprs_ could be empty.
    if (resultExprs_.isEmpty()) {
        throw new AnalysisException("The star exprs expanded to an empty select list "
                + "because the referenced tables only have complex-typed columns.\n"
                + "Star exprs only expand to scalar-typed columns because complex-typed exprs "
                + "are currently not supported in the select list.\n" + "Affected select statement:\n"
                + toSql());
    }

    for (Expr expr : resultExprs_) {
        // Complex types are currently not supported in the select list because we'd need
        // to serialize them in a meaningful way.
        if (expr.getType().isComplexType()) {
            throw new AnalysisException(String.format(
                    "Expr '%s' in select list returns a complex type '%s'.\n"
                            + "Only scalar types are allowed in the select list.",
                    expr.toSql(), expr.getType().toSql()));
        }
        if (!expr.getType().isSupported()) {
            throw new AnalysisException(
                    "Unsupported type '" + expr.getType().toSql() + "' in '" + expr.toSql() + "'.");
        }
    }

    if (TreeNode.contains(resultExprs_, AnalyticExpr.class)) {
        if (fromClause_.isEmpty()) {
            throw new AnalysisException("Analytic expressions require FROM clause.");
        }

        // do this here, not after analyzeAggregation(), otherwise the AnalyticExprs
        // will get substituted away
        if (selectList_.isDistinct()) {
            throw new AnalysisException("cannot combine SELECT DISTINCT with analytic functions");
        }
    }

    if (whereClause_ != null) {
        whereClause_.analyze(analyzer);
        if (whereClause_.contains(Expr.isAggregatePredicate())) {
            throw new AnalysisException("aggregate function not allowed in WHERE clause");
        }
        whereClause_.checkReturnsBool("WHERE clause", false);
        Expr e = whereClause_.findFirstOf(AnalyticExpr.class);
        if (e != null) {
            throw new AnalysisException("WHERE clause must not contain analytic expressions: " + e.toSql());
        }
        analyzer.registerConjuncts(whereClause_, false);
    }

    createSortInfo(analyzer);
    analyzeAggregation(analyzer);
    createAnalyticInfo(analyzer);
    if (evaluateOrderBy_)
        createSortTupleInfo(analyzer);

    // Remember the SQL string before inline-view expression substitution.
    sqlString_ = toSql();
    resolveInlineViewRefs(analyzer);

    // If this block's select-project-join portion returns an empty result set and the
    // block has no aggregation, then mark this block as returning an empty result set.
    if (analyzer.hasEmptySpjResultSet() && aggInfo_ == null) {
        analyzer.setHasEmptyResultSet();
    }

    ColumnLineageGraph graph = analyzer.getColumnLineageGraph();
    if (aggInfo_ != null && !aggInfo_.getAggregateExprs().isEmpty()) {
        graph.addDependencyPredicates(aggInfo_.getGroupingExprs());
    }
    if (sortInfo_ != null && hasLimit()) {
        // When there is a LIMIT clause in conjunction with an ORDER BY, the ordering exprs
        // must be added in the column lineage graph.
        graph.addDependencyPredicates(sortInfo_.getOrderingExprs());
    }

    if (aggInfo_ != null) {
        if (LOG.isTraceEnabled())
            LOG.trace("post-analysis " + aggInfo_.debugString());
    }
}

From source file:org.eclipse.viatra.query.patternlanguage.emf.ui.quickfix.EMFPatternLanguageQuickfixProvider.java

@Fix(IssueCodes.MISSING_PACKAGE_IMPORT)
public void addMissingPackageImport(final Issue issue, IssueResolutionAcceptor acceptor) {

    acceptor.accept(issue, "Add missing import", "Add missing import", null, (IModification) context -> {
        final IXtextDocument document = context.getXtextDocument();
        Integer offset = document.readOnly(state -> {
            final VQLImportSection importSection = (VQLImportSection) Iterators.find(state.getAllContents(),
                    Predicates.instanceOf(VQLImportSection.class), null);
            final ICompositeNode node = NodeModelUtils.getNode(importSection);

            return Integer.valueOf(node.getTotalEndOffset());
        });//from  w w w. j  a  v a2s  .c o m
        if (offset != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("\n");
            sb.append("import \"");
            sb.append(issue.getData()[0]);
            sb.append("\"");
            document.replace(offset, 0, sb.toString());
        }
    });
}

From source file:org.eclipse.sirius.diagram.ui.tools.internal.layout.provider.PinnedElementsLayoutProvider.java

/**
 * Finds the "real" children of the specified edit part that needs to be
 * laid out.//from   w w  w .j a  v a 2 s  . c  o m
 */
private Collection<IGraphicalEditPart> getChildrenOfInterest(final IGraphicalEditPart gep) {
    final Iterable<IGraphicalEditPart> rawChildren = Iterables.filter(gep.getChildren(),
            IGraphicalEditPart.class);
    // Ignore these, which are technically children edit parts but not
    // "inside" the container.
    final Predicate<Object> invalidChildKind = Predicates.or(
            Predicates.instanceOf(IDiagramBorderNodeEditPart.class),
            Predicates.instanceOf(IDiagramNameEditPart.class));
    // These are OK.
    final Predicate<Object> validChildKind = Predicates.or(Predicates.instanceOf(IDiagramNodeEditPart.class),
            Predicates.instanceOf(IDiagramContainerEditPart.class),
            Predicates.instanceOf(IDiagramListEditPart.class));
    final Predicate<Object> isProperChild = Predicates.and(validChildKind, Predicates.not(invalidChildKind));
    final Collection<IGraphicalEditPart> result = Lists
            .newArrayList(Iterables.filter(rawChildren, isProperChild));
    // Containers have an intermediate level of children edit parts. We
    // ignore these "wrapper" parts, but must look inside for proper
    // children of the container.
    for (IGraphicalEditPart part : Iterables.filter(rawChildren, Predicates.not(isProperChild))) {
        if (part instanceof DNodeContainerViewNodeContainerCompartmentEditPart
                || part instanceof DNodeContainerViewNodeContainerCompartment2EditPart) {
            result.addAll(getChildrenOfInterest(part));
        }
    }
    return result;
}

From source file:org.eclipse.sirius.diagram.ui.tools.internal.actions.delete.DeleteFromDiagramAction.java

/**
 * Check if the action should be enabled for this edit parts :
 * <UL>/*ww w. j  a  v  a  2 s.c  om*/
 * <LI>First check that all edit parts has his edit mode enabled</LI>
 * <LI>And then do some checks on target of edit parts.</LI>
 * </UL>
 * 
 * @param selectedParts
 *            the selected objects
 * @return true if the action should be enabled, false otherwise.
 */
public static boolean shouldBeEnabledForEditParts(Iterable<? extends IGraphicalEditPart> selectedParts) {
    Predicate<IGraphicalEditPart> isEditModeEnabledPredicate = new Predicate<IGraphicalEditPart>() {
        public boolean apply(IGraphicalEditPart input) {
            return input.isEditModeEnabled();
        }
    };

    if (Iterables.all(selectedParts, isEditModeEnabledPredicate)
            && !Iterables.all(selectedParts, Predicates.instanceOf(IDiagramNameEditPart.class))) {
        return shouldBeEnabled(getSelectedEObject(selectedParts));
    }
    return false;
}

From source file:org.apache.impala.analysis.BinaryPredicate.java

@Override
protected void analyzeImpl(Analyzer analyzer) throws AnalysisException {
    super.analyzeImpl(analyzer);
    convertNumericLiteralsFromDecimal(analyzer);
    String opName = op_.getName().equals("null_matching_eq") ? "eq" : op_.getName();
    fn_ = getBuiltinFunction(analyzer, opName, collectChildReturnTypes(),
            CompareMode.IS_NONSTRICT_SUPERTYPE_OF);
    if (fn_ == null) {
        // Construct an appropriate error message and throw an AnalysisException.
        String errMsg = "operands of type " + getChild(0).getType().toSql() + " and "
                + getChild(1).getType().toSql() + " are not comparable: " + toSql();

        // Check if any of the children is a Subquery that does not return a
        // scalar.
        for (Expr expr : children_) {
            if (expr instanceof Subquery && !expr.getType().isScalarType()) {
                errMsg = "Subquery must return a single row: " + expr.toSql();
                break;
            }/*from w ww .j av a 2  s .c  o  m*/
        }

        throw new AnalysisException(errMsg);
    }
    Preconditions.checkState(fn_.getReturnType().isBoolean());

    ArrayList<Expr> subqueries = Lists.newArrayList();
    collectAll(Predicates.instanceOf(Subquery.class), subqueries);
    if (subqueries.size() > 1) {
        // TODO Remove that restriction when we add support for independent subquery
        // evaluation.
        throw new AnalysisException(
                "Multiple subqueries are not supported in binary " + "predicates: " + toSql());
    }
    if (contains(ExistsPredicate.class)) {
        throw new AnalysisException(
                "EXISTS subquery predicates are not " + "supported in binary predicates: " + toSql());
    }

    List<InPredicate> inPredicates = Lists.newArrayList();
    collect(InPredicate.class, inPredicates);
    for (InPredicate inPredicate : inPredicates) {
        if (inPredicate.contains(Subquery.class)) {
            throw new AnalysisException(
                    "IN subquery predicates are not supported in " + "binary predicates: " + toSql());
        }
    }

    // Don't perform any casting for predicates with subqueries here. Any casting
    // required will be performed when the subquery is unnested.
    if (!contains(Subquery.class))
        castForFunctionCall(true);

    // Determine selectivity
    // TODO: Compute selectivity for nested predicates.
    // TODO: Improve estimation using histograms.
    Reference<SlotRef> slotRefRef = new Reference<SlotRef>();
    if ((op_ == Operator.EQ || op_ == Operator.NOT_DISTINCT) && isSingleColumnPredicate(slotRefRef, null)) {
        long distinctValues = slotRefRef.getRef().getNumDistinctValues();
        if (distinctValues > 0) {
            selectivity_ = 1.0 / distinctValues;
            selectivity_ = Math.max(0, Math.min(1, selectivity_));
        }
    }

    // Compute cost.
    if (hasChildCosts()) {
        if (getChild(0).getType().isFixedLengthType()) {
            evalCost_ = getChildCosts() + BINARY_PREDICATE_COST;
        } else if (getChild(0).getType().isStringType()) {
            evalCost_ = getChildCosts() + (float) (getAvgStringLength(getChild(0))
                    + getAvgStringLength(getChild(1)) * BINARY_PREDICATE_COST);
        } else {
            //TODO(tmarshall): Handle other var length types here.
            evalCost_ = getChildCosts() + VAR_LEN_BINARY_PREDICATE_COST;
        }
    }
}

From source file:org.eclipse.sirius.diagram.ui.business.api.query.ConnectionQuery.java

/**
 * Return the constraint of the connection as list of RelativeBendpoint only
 * if the constraint is a list of absolute bendpoints.
 * //from   w ww . j  a v  a  2  s .c o  m
 * @return an optional list of {@link AbsoluteBendpoint}
 */
public Option<List<AbsoluteBendpoint>> getAbsoluteBendpointsConstraint() {

    Object cons = connection.getRoutingConstraint();
    if (cons instanceof List) {
        List<?> constraintsList = (List<?>) cons;
        if (Iterators.all(constraintsList.iterator(), Predicates.instanceOf(AbsoluteBendpoint.class))) {
            List<AbsoluteBendpoint> result = Lists.newLinkedList();
            for (Object object : constraintsList) {
                result.add((AbsoluteBendpoint) object);
            }
            return Options.newSome(result);
        }
    }
    return Options.newNone();
}

From source file:org.polymap.core.data.operations.feature.CopyFeaturesOperation2.java

public Status execute(IProgressMonitor monitor) throws Exception {
    monitor.beginTask(context.adapt(FeatureOperationExtension.class).getLabel(), 10);

    source = (PipelineFeatureSource) context.featureSource();

    if (!(source.getSchema() instanceof SimpleFeatureType)) {
        throw new Exception(i18n.get("notSimpleType"));
    }//w  w w.ja va  2 s . c om

    // open wizard dialog
    monitor.subTask("Eingaben vom Nutzer...");
    IUndoableOperation op = context.adapt(IUndoableOperation.class);
    final OperationWizard wizard = new OperationWizard(op, context, monitor) {
        public boolean doPerformFinish() throws Exception {
            ((FeatureEditorPage2) getPage(FeatureEditorPage2.ID)).performFinish();
            return true;
        }
    };
    Polymap.getSessionDisplay().asyncExec(new Runnable() {
        public void run() {
            wizard.getShell().setMinimumSize(600, 600);
            wizard.getShell().layout(true);
        }
    });

    // ChooseLayerPage
    final ChooseLayerPage chooseLayerPage = new ChooseLayerPage(i18n.get("ChooseLayerPage_title"),
            i18n.get("ChooseLayerPage_description"), true);
    ILayer layer = context.adapt(ILayer.class);
    if (ACLUtils.checkPermission(layer, AclPermission.WRITE, false)) {
        chooseLayerPage.preset(layer);
    }
    chooseLayerPage.addFilter(new ViewerFilter() {
        @Override
        public boolean select(Viewer viewer, Object parentElm, Object elm) {
            if (elm instanceof ILayer) {
                return ACLUtils.checkPermission((ILayer) elm, AclPermission.WRITE, false);
            }
            return true;
        }
    });
    wizard.addPage(chooseLayerPage);
    final FeatureEditorPage2 featureEditorPage = new FeatureEditorPage2();
    wizard.addPage(featureEditorPage);
    DirectCopyPage directCopyPage = new DirectCopyPage();
    wizard.addPage(directCopyPage);

    // get/set chosen layer
    wizard.addPageChangedListener(new IPageChangedListener() {
        public void pageChanged(PageChangedEvent ev) {
            log.info("Page: " + ev.getSelectedPage());
            if (featureEditorPage == ev.getSelectedPage()) {
                dest = chooseLayerPage.getResult();
            }
        }
    });
    monitor.worked(1);

    // copy features
    if (OperationWizard.openDialog(wizard)) {
        final IProgressMonitor copyMonitor = new SubProgressMonitor(monitor, 8,
                SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);

        destFs = PipelineFeatureSource.forLayer(dest, true);
        features = context.features();
        int featuresSize = features.size();

        copyMonitor.beginTask(i18n.get("taskTitle", featuresSize), featuresSize);

        // direct copy?
        if (directCopyPage.isDirectCopy()) {
            Pipeline pipe = destFs.getPipeline();
            Iterables.removeIf(pipe, Predicates.instanceOf(FeatureBufferProcessor.class));
        }

        // tranform schema
        features = featureEditorPage.retyped(features);

        // transform CRS
        SimpleFeatureType destSchema = destFs.getSchema();
        final CoordinateReferenceSystem destCrs = destSchema.getCoordinateReferenceSystem();
        SimpleFeatureType sourceSchema = (SimpleFeatureType) features.getSchema();
        // XXX do not use sourceSchema here as featureEditorPage ff. has set CRS to destFs schema CRS
        CoordinateReferenceSystem sourceCrs = sourceSchema.getCoordinateReferenceSystem();

        if (destCrs != null && !destCrs.equals(sourceCrs)) {
            // features = new ReprojectingFeatureCollection( features, destCrs );

            final MathTransform transform = Geometries.transform(sourceCrs, destCrs);
            final String geomName = sourceSchema.getGeometryDescriptor().getLocalName();

            // actually copy features; the above just sets attribute which is not supported by caching data sources
            final SimpleFeatureType retypedSchema = SimpleFeatureTypeBuilder.retype(sourceSchema, destCrs);
            features = new RetypingFeatureCollection(features, retypedSchema) {
                protected Feature retype(Feature feature) {
                    try {
                        SimpleFeatureBuilder fb = new SimpleFeatureBuilder(retypedSchema);
                        fb.init((SimpleFeature) feature);
                        Geometry geom = (Geometry) feature.getProperty(geomName).getValue();
                        fb.set(geomName, JTS.transform(geom, transform));
                        return fb.buildFeature(feature.getIdentifier().getID());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            };
        }

        // transform geometry types
        SimpleFeatureType featuresSchema = (SimpleFeatureType) features.getSchema();
        final GeometryDescriptor featureGeom = featuresSchema.getGeometryDescriptor();
        final GeometryDescriptor destGeom = destSchema.getGeometryDescriptor();
        if (featureGeom != null && destGeom != null
                && !featureGeom.getType().getBinding().equals(destGeom.getType().getBinding())) {

            SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder();
            ftb.init(featuresSchema);
            ftb.remove(featureGeom.getLocalName());
            ftb.add(destGeom.getLocalName(), destGeom.getType().getBinding(),
                    destGeom.getCoordinateReferenceSystem());
            final SimpleFeatureType retypedSchema = ftb.buildFeatureType();

            features = new RetypingFeatureCollection(features, retypedSchema) {
                protected Feature retype(Feature feature) {
                    try {
                        SimpleFeatureBuilder fb = new SimpleFeatureBuilder(retypedSchema);
                        fb.init((SimpleFeature) feature);
                        Geometry geom = (Geometry) feature.getProperty(featureGeom.getLocalName()).getValue();

                        // Point -> MultiPolygon
                        if (destGeom.getType().getBinding().equals(MultiPolygon.class)
                                || destGeom.getType().getBinding().equals(Polygon.class)) {
                            geom = Geometries.transform(geom, destCrs, Geometries.crs("EPSG:3857"));
                            geom = geom.buffer(10, 3);
                            geom = Geometries.transform(geom, Geometries.crs("EPSG:3857"), destCrs);

                            fb.set(destGeom.getLocalName(), geom);
                            return fb.buildFeature(feature.getIdentifier().getID());
                        }
                        // Geometry -> anything
                        else if (geom instanceof Geometry) {
                            fb.set(destGeom.getLocalName(), geom);
                            return fb.buildFeature(feature.getIdentifier().getID());
                        } else {
                            throw new UnsupportedOperationException(
                                    "Unsupported geometry transformation: " + geom.getClass().getSimpleName()
                                            + " -> " + destGeom.getType().getBinding().getSimpleName());
                        }
                    } catch (RuntimeException e) {
                        throw e;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            };
        }

        createdFeatureIds = destFs.addFeatures(features, new ProgressListenerAdaptor(copyMonitor));

        monitor.done();
        return Status.OK;
    }
    return Status.Cancel;
}

From source file:eu.stratosphere.sopremo.expressions.ExpressionUtil.java

/**
 * Replaces fragments in the form of path expression (InputSelection, ArrayAccess).
 *///from  w  w  w.  jav a2  s .c o m
public static EvaluationExpression replaceIndexAccessWithAggregation(
        final EvaluationExpression baseExpression) {
    return baseExpression.replace(Predicates.instanceOf(ArrayAccess.class), new TransformFunction() {
        @Override
        public EvaluationExpression apply(final EvaluationExpression argument) {
            final ArrayAccess arrayAccess = (ArrayAccess) argument;
            // only process array access directly on the input stream
            if (!(arrayAccess.getInputExpression() instanceof InputSelection))
                return arrayAccess;
            if (arrayAccess.getStartIndex() < 0 || arrayAccess.getEndIndex() < 0)
                throw new IllegalArgumentException("Negative indexes cannot replaced currently");
            if (arrayAccess.getStartIndex() > arrayAccess.getEndIndex())
                throw new IllegalArgumentException("Array inversion is not directly supported");

            if (arrayAccess.getStartIndex() == 0 && arrayAccess.getEndIndex() == 0)
                return new AggregationExpression(CoreFunctions.FIRST)
                        .withInputExpression(arrayAccess.getInputExpression());
            return new AggregationExpression(new ArrayAccessAsAggregation(arrayAccess.getStartIndex(),
                    arrayAccess.getEndIndex(), arrayAccess.isSelectingRange()))
                            .withInputExpression(arrayAccess.getInputExpression());
            // final FunctionCall aggregation = new FunctionCall("array access",
            // new AggregationexFunction(new ArrayAccessAsAggregation(arrayAccess.getStartIndex(),
            // arrayAccess.getEndIndex(), arrayAccess.isSelectingRange())),
            // arrayAccess.getInputExpression().clone());
            // return aggregation;
        }
    });
}