Example usage for org.apache.commons.collections Transformer Transformer

List of usage examples for org.apache.commons.collections Transformer Transformer

Introduction

In this page you can find the example usage for org.apache.commons.collections Transformer Transformer.

Prototype

Transformer

Source Link

Usage

From source file:org.apache.cayenne.modeler.dialog.pref.DataSourcePreferences.java

/**
 * Tries to establish a DB connection, reporting the status of this
 * operation./*  w w w . ja  v  a  2 s . com*/
 */
public void testDataSourceAction() {
    DBConnectionInfo currentDataSource = getConnectionInfo();
    if (currentDataSource == null) {
        return;
    }

    if (currentDataSource.getJdbcDriver() == null) {
        JOptionPane.showMessageDialog(null, "No JDBC Driver specified", "Warning", JOptionPane.WARNING_MESSAGE);
        return;
    }

    if (currentDataSource.getUrl() == null) {
        JOptionPane.showMessageDialog(null, "No Database URL specified", "Warning",
                JOptionPane.WARNING_MESSAGE);
        return;
    }

    try {

        FileClassLoadingService classLoader = new FileClassLoadingService();

        List<File> oldPathFiles = ((FileClassLoadingService) getApplication().getClassLoadingService())
                .getPathFiles();

        Collection<String> details = new ArrayList<>();
        for (File oldPathFile : oldPathFiles) {
            details.add(oldPathFile.getAbsolutePath());
        }

        Preferences classPathPreferences = getApplication().getPreferencesNode(ClasspathPreferences.class, "");
        if (editor.getChangedPreferences().containsKey(classPathPreferences)) {
            Map<String, String> map = editor.getChangedPreferences().get(classPathPreferences);

            for (Map.Entry<String, String> en : map.entrySet()) {
                String key = en.getKey();
                if (!details.contains(key)) {
                    details.add(key);
                }
            }
        }

        if (editor.getRemovedPreferences().containsKey(classPathPreferences)) {
            Map<String, String> map = editor.getRemovedPreferences().get(classPathPreferences);

            for (Map.Entry<String, String> en : map.entrySet()) {
                String key = en.getKey();
                if (details.contains(key)) {
                    details.remove(key);
                }
            }
        }

        if (details.size() > 0) {

            // transform preference to file...
            Transformer transformer = new Transformer() {

                public Object transform(Object object) {
                    String pref = (String) object;
                    return new File(pref);
                }
            };

            classLoader.setPathFiles(CollectionUtils.collect(details, transformer));
        }

        Class<Driver> driverClass = classLoader.loadClass(Driver.class, currentDataSource.getJdbcDriver());
        Driver driver = driverClass.newInstance();

        // connect via Cayenne DriverDataSource - it addresses some driver
        // issues...
        // can't use try with resource here as we can loose meaningful exception
        Connection c = new DriverDataSource(driver, currentDataSource.getUrl(), currentDataSource.getUserName(),
                currentDataSource.getPassword()).getConnection();
        try {
            c.close();
        } catch (SQLException ignored) {
            // i guess we can ignore this...
        }

        JOptionPane.showMessageDialog(null, "Connected Successfully", "Success",
                JOptionPane.INFORMATION_MESSAGE);
    } catch (Throwable th) {
        th = Util.unwindException(th);
        String message = "Error connecting to DB: " + th.getLocalizedMessage();

        StringTokenizer st = new StringTokenizer(message);
        StringBuilder sbMessage = new StringBuilder();
        int len = 0;

        String tempString;
        while (st.hasMoreTokens()) {
            tempString = st.nextElement().toString();
            if (len < 110) {
                len = len + tempString.length() + 1;
            } else {
                sbMessage.append("\n");
                len = 0;
            }
            sbMessage.append(tempString).append(" ");
        }

        JOptionPane.showMessageDialog(null, sbMessage.toString(), "Warning", JOptionPane.WARNING_MESSAGE);
    }
}

From source file:org.apache.jackrabbit.core.query.lucene.SearchIndex.java

/**
 * This implementation forwards the call to
 * {@link MultiIndex#update(Collection, Collection)} and
 * transforms the two iterators to the required types.
 *
 * @param remove uuids of nodes to remove.
 * @param add    NodeStates to add. Calls to <code>next()</code> on this
 *               iterator may return <code>null</code>, to indicate that a
 *               node could not be indexed successfully.
 * @throws RepositoryException if an error occurs while indexing a node.
 * @throws IOException         if an error occurs while updating the index.
 *//*w w w . j a  va2 s  .c  o  m*/
public void updateNodes(NodeIdIterator remove, NodeStateIterator add) throws RepositoryException, IOException {
    checkOpen();
    final Map aggregateRoots = new HashMap();
    final HashSet removedUUIDs = new HashSet();
    final Set addedUUIDs = new HashSet();

    index.update(IteratorUtils.toList(new TransformIterator(remove, new Transformer() {
        public Object transform(Object input) {
            UUID uuid = ((NodeId) input).getUUID();
            removedUUIDs.add(uuid);
            return uuid;
        }
    })), IteratorUtils.toList(new TransformIterator(add, new Transformer() {
        public Object transform(Object input) {
            NodeState state = (NodeState) input;
            if (state == null) {
                return null;
            }
            UUID uuid = state.getNodeId().getUUID();
            addedUUIDs.add(uuid);
            removedUUIDs.remove(uuid);
            Document doc = null;
            try {
                doc = createDocument(state, getNamespaceMappings(), index.getIndexFormatVersion());
                retrieveAggregateRoot(state, aggregateRoots);
            } catch (RepositoryException e) {
                log.warn("Exception while creating document for node: " + state.getNodeId() + ": "
                        + e.toString());
            }
            return doc;
        }
    })));

    // remove any aggregateRoot nodes that are new
    // and therefore already up-to-date
    aggregateRoots.keySet().removeAll(addedUUIDs);

    // based on removed UUIDs get affected aggregate root nodes
    retrieveAggregateRoot(removedUUIDs, aggregateRoots);

    // update aggregates if there are any affected
    if (aggregateRoots.size() > 0) {
        Collection modified = TransformedCollection.decorate(new ArrayList(), new Transformer() {
            public Object transform(Object input) {
                NodeState state = (NodeState) input;
                try {
                    return createDocument(state, getNamespaceMappings(), index.getIndexFormatVersion());
                } catch (RepositoryException e) {
                    log.warn("Exception while creating document for node: " + state.getNodeId() + ": "
                            + e.toString());
                }
                return null;
            }
        });
        modified.addAll(aggregateRoots.values());
        index.update(aggregateRoots.keySet(), modified);
    }
}

From source file:org.apache.sling.contextaware.config.resource.impl.def.DefaultConfigurationResourceResolvingStrategy.java

/**
 * Searches the resource hierarchy upwards for all config references and returns them.
 * @param refs List to add found resources to
 * @param startResource Resource to start searching
 *///from w  w  w.  ja v  a2s . c o m
@SuppressWarnings("unchecked")
private Iterator<String> findConfigRefs(final Resource startResource) {
    Iterator<Resource> contextResources = contextPathStrategy.findContextResources(startResource);
    // get config resource path for each context resource, filter out items where not reference could be resolved
    return new FilterIterator(new TransformIterator(contextResources, new Transformer() {
        @Override
        public Object transform(Object input) {
            return getReference((Resource) input);
        }
    }), PredicateUtils.notNullPredicate());
}

From source file:org.apache.solr.search.xjoin.XJoinQParserPlugin.java

static private Transformer transformer(final FieldType ft) {
    return new Transformer() {

        BytesRefBuilder term = new BytesRefBuilder();

        @Override/*from  w ww  . j a  v  a2 s  .c o  m*/
        public BytesRef transform(Object joinId) {
            String joinStr = joinId.toString();
            // logic same as TermQParserPlugin
            if (ft != null) {
                ft.readableToIndexed(joinStr, term);
            } else {
                term.copyChars(joinStr);
            }
            return term.toBytesRef();
        }

    };
}

From source file:org.apache.spark.streaming.JavaWriteAheadLogSuiteHandle.java

@Override
public java.util.Iterator<java.nio.ByteBuffer> readAll() {
    Collection<ByteBuffer> buffers = CollectionUtils.collect(records, new Transformer() {
        @Override//  w  w  w.j  av  a  2 s.  co m
        public Object transform(Object input) {
            return ((Record) input).buffer;
        }
    });
    return buffers.iterator();
}

From source file:org.archive.crawler.frontier.precedence.SuccessCountsQueuePrecedencePolicy.java

@SuppressWarnings("unchecked")
@Override/* w w  w . j  av  a 2 s.  co m*/
protected int calculatePrecedence(WorkQueue wq) {
    // FIXME: it's ridiculously inefficient to do this every time, 
    // and optimizing will probably require inserting stateful policy 
    // helper object into WorkQueue -- expected when URI-precedence is
    // also supported
    int precedence = getBasePrecedence() - 1;
    Collection<Integer> increments = CollectionUtils.collect(Arrays.asList(getIncrementCounts().split(",")),
            new Transformer() {
                public Object transform(final Object string) {
                    return Integer.parseInt((String) string);
                }
            });
    Iterator<Integer> iter = increments.iterator();
    int increment = iter.next();
    long successes = wq.getSubstats().getFetchSuccesses();
    while (successes >= 0) {
        successes -= increment;
        precedence++;
        increment = iter.hasNext() ? iter.next() : increment;
    }
    return precedence;
}

From source file:org.broadleafcommerce.admin.server.service.handler.SkuCustomPersistenceHandler.java

/**
 * Returns a {@link Property} filled out with a delimited list of the <b>values</b> that are passed in. This should be
 * invoked on a fetch and the returned property should be added to the fetched {@link Entity} dto.
 * /*from  www .  j a  v a 2s  .c  o  m*/
 * @param values
 * @return
 * @see {@link #createConsolidatedOptionField(Class)};
 */
public Property getConsolidatedOptionProperty(Collection<ProductOptionValue> values) {
    Property optionValueProperty = new Property();
    optionValueProperty.setName(CONSOLIDATED_PRODUCT_OPTIONS_FIELD_NAME);

    //order the values by the display order of their correspond product option
    //        Collections.sort(values, new Comparator<ProductOptionValue>() {
    //
    //            @Override
    //            public int compare(ProductOptionValue value1, ProductOptionValue value2) {
    //                return new CompareToBuilder().append(value1.getProductOption().getDisplayOrder(),
    //                        value2.getProductOption().getDisplayOrder()).toComparison();
    //            }
    //        });

    ArrayList<String> stringValues = new ArrayList<String>();
    CollectionUtils.collect(values, new Transformer() {

        @Override
        public Object transform(Object input) {
            return ((ProductOptionValue) input).getAttributeValue();
        }
    }, stringValues);

    optionValueProperty.setValue(StringUtils.join(stringValues, CONSOLIDATED_PRODUCT_OPTIONS_DELIMETER));
    return optionValueProperty;
}

From source file:org.broadleafcommerce.core.catalog.domain.CategoryImpl.java

@Override
public List<CategorySearchFacet> getCumulativeSearchFacets() {
    List<CategorySearchFacet> returnCategoryFacets = new ArrayList<CategorySearchFacet>();
    returnCategoryFacets.addAll(getSearchFacets());
    Collections.sort(returnCategoryFacets, facetPositionComparator);

    final Collection<SearchFacet> facets = CollectionUtils.collect(returnCategoryFacets, new Transformer() {

        @Override/*from w  ww . j a  v  a  2 s  .  c om*/
        public Object transform(Object input) {
            return ((CategorySearchFacet) input).getSearchFacet();
        }
    });

    // Add in parent facets unless they are excluded
    List<CategorySearchFacet> parentFacets = null;
    if (defaultParentCategory != null) {
        parentFacets = defaultParentCategory.getCumulativeSearchFacets();
        CollectionUtils.filter(parentFacets, new Predicate() {
            @Override
            public boolean evaluate(Object arg) {
                CategorySearchFacet csf = (CategorySearchFacet) arg;
                return !getExcludedSearchFacets().contains(csf.getSearchFacet())
                        && !facets.contains(csf.getSearchFacet());
            }
        });
    }
    if (parentFacets != null) {
        returnCategoryFacets.addAll(parentFacets);
    }

    return returnCategoryFacets;
}

From source file:org.broadleafcommerce.core.offer.service.OfferServiceImpl.java

@Override
@SuppressWarnings("unchecked")
public Set<Offer> getUniqueOffersFromOrder(Order order) {
    HashSet<Offer> result = new HashSet<Offer>();

    Transformer adjustmentToOfferTransformer = new Transformer() {

        @Override//from ww w  .j ava 2  s . c om
        public Object transform(Object input) {
            return ((Adjustment) input).getOffer();
        }
    };

    result.addAll(CollectionUtils.collect(order.getOrderAdjustments(), adjustmentToOfferTransformer));

    if (order.getOrderItems() != null) {
        for (OrderItem item : order.getOrderItems()) {
            result.addAll(
                    CollectionUtils.collect(item.getOrderItemAdjustments(), adjustmentToOfferTransformer));

            //record usage for price details on the item as well
            if (item.getOrderItemPriceDetails() != null) {
                for (OrderItemPriceDetail detail : item.getOrderItemPriceDetails()) {
                    result.addAll(CollectionUtils.collect(detail.getOrderItemPriceDetailAdjustments(),
                            adjustmentToOfferTransformer));
                }
            }
        }
    }

    if (order.getFulfillmentGroups() != null) {
        for (FulfillmentGroup fg : order.getFulfillmentGroups()) {
            result.addAll(
                    CollectionUtils.collect(fg.getFulfillmentGroupAdjustments(), adjustmentToOfferTransformer));
        }
    }
    return result;
}

From source file:org.broadleafcommerce.core.workflow.BaseProcessor.java

/**
 * Called after the properties have been set, Ensures the list of activities
 *  is not empty and each activity is supported by this Workflow Processor
 *
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 *//*from  w  w w.  jav  a  2s .c  o  m*/
@Override
public void afterPropertiesSet() throws Exception {

    if (!(beanFactory instanceof ListableBeanFactory)) {
        throw new BeanInitializationException("The workflow processor [" + beanName + "] "
                + "is not managed by a ListableBeanFactory, please re-deploy using some derivative of ListableBeanFactory such as"
                + "ClassPathXmlApplicationContext ");
    }

    if (CollectionUtils.isEmpty(activities) && !isAllowEmptyActivities()) {
        throw new UnsatisfiedDependencyException(getBeanDesc(), beanName, "activities",
                "No activities were wired for this workflow");
    }

    //sort the activities based on their configured order
    OrderComparator.sort(activities);

    HashSet<String> moduleNames = new HashSet<String>();
    for (Iterator<Activity<ProcessContext<? extends Object>>> iter = activities.iterator(); iter.hasNext();) {
        Activity<? extends ProcessContext<? extends Object>> activity = iter.next();
        if (!supports(activity)) {
            throw new BeanInitializationException("The workflow processor [" + beanName + "] does "
                    + "not support the activity of type" + activity.getClass().getName());
        }

        if (activity instanceof ModuleActivity) {
            moduleActivities.add((ModuleActivity) activity);
            moduleNames.add(((ModuleActivity) activity).getModuleName());
        }
    }

    if (CollectionUtils.isNotEmpty(moduleActivities)) {
        //log the fact that we've got some modifications to the workflow
        StringBuffer message = new StringBuffer();
        message.append("The following modules have made changes to the " + getBeanName() + " workflow: ");
        message.append(Arrays.toString(moduleNames.toArray()));
        message.append("\n");
        message.append("The final ordering of activities for the " + getBeanName() + " workflow is: \n");
        ArrayList<String> activityNames = new ArrayList<String>();
        CollectionUtils.collect(activities, new Transformer() {

            @Override
            public Object transform(Object input) {
                return ((Activity) input).getBeanName();
            }
        }, activityNames);
        message.append(Arrays.toString(activityNames.toArray()));

        supportLogger.lifecycle(LifeCycleEvent.CONFIG, message.toString());
    }

}