Example usage for com.google.common.base Equivalence Equivalence

List of usage examples for com.google.common.base Equivalence Equivalence

Introduction

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

Prototype

protected Equivalence() 

Source Link

Document

Constructor for use by subclasses.

Usage

From source file:org.jpmml.evaluator.BatchUtil.java

static public List<MapDifference<FieldName, ?>> difference(Batch batch, final double precision,
        final double zeroThreshold) throws Exception {
    List<? extends Map<FieldName, ?>> input = CsvUtil.load(batch.getInput());
    List<? extends Map<FieldName, String>> output = CsvUtil.load(batch.getOutput());

    Evaluator evaluator = PMMLUtil.createModelEvaluator(batch.getModel(), ModelEvaluatorFactory.getInstance());

    List<FieldName> groupFields = evaluator.getGroupFields();
    List<FieldName> targetFields = evaluator.getTargetFields();

    if (groupFields.size() == 1) {
        FieldName groupField = groupFields.get(0);

        input = EvaluatorUtil.groupRows(groupField, input);
    } else/*from w w w  .ja va2  s . co m*/

    if (groupFields.size() > 1) {
        throw new EvaluationException();
    }

    Equivalence<Object> equivalence = new Equivalence<Object>() {

        @Override
        public boolean doEquivalent(Object expected, Object actual) {
            actual = EvaluatorUtil.decode(actual);

            return VerificationUtil.acceptable(TypeUtil.parseOrCast(TypeUtil.getDataType(actual), expected),
                    actual, precision, zeroThreshold);
        }

        @Override
        public int doHash(Object object) {
            return object.hashCode();
        }
    };

    if (output.size() > 0) {

        if (input.size() != output.size()) {
            throw new EvaluationException();
        }

        List<MapDifference<FieldName, ?>> differences = Lists.newArrayList();

        for (int i = 0; i < input.size(); i++) {
            Map<FieldName, ?> arguments = input.get(i);

            Map<FieldName, ?> result = evaluator.evaluate(arguments);

            // Delete the synthetic target field
            if (targetFields.size() == 0) {
                result = Maps.newLinkedHashMap(result);

                result.remove(evaluator.getTargetField());
            }

            MapDifference<FieldName, Object> difference = Maps.<FieldName, Object>difference(output.get(i),
                    result, equivalence);
            if (!difference.areEqual()) {
                differences.add(difference);
            }
        }

        return differences;
    } else

    {
        for (int i = 0; i < input.size(); i++) {
            Map<FieldName, ?> arguments = input.get(i);

            evaluator.evaluate(arguments);
        }

        return Collections.emptyList();
    }
}

From source file:com.github.buzztaiki.jenova.InterfaceMethod.java

private static Equivalence<Type> sameType(final Types types) {
    return new Equivalence<Type>() {
        @Override/*from ww w  .ja va2  s . c  o  m*/
        protected boolean doEquivalent(Type a, Type b) {
            return types.isSameType(a, b);
        }

        @Override
        protected int doHash(Type t) {
            return Types.hashCode(t);
        }
    };
}

From source file:org.decisiondeck.jlp.parameters.LpParametersUtils.java

static public Equivalence<LpParameters> getEquivalenceRelation() {
    return new Equivalence<LpParameters>() {
        @Override/*w w w .j a  v  a 2s.co  m*/
        public boolean doEquivalent(LpParameters a, LpParameters b) {
            if (!a.getDoubleParameters().equals(b.getDoubleParameters())) {
                return false;
            }
            if (!a.getIntParameters().equals(b.getIntParameters())) {
                return false;
            }
            if (!a.getStringParameters().equals(b.getStringParameters())) {
                return false;
            }
            if (!a.getObjectParameters().equals(b.getObjectParameters())) {
                return false;
            }
            return true;
        }

        @Override
        public int doHash(LpParameters t) {
            return Objects.hashCode(t.getDoubleParameters(), t.getIntParameters(), t.getStringParameters(),
                    t.getObjectParameters());
        }
    };
}

From source file:org.apache.abdera2.common.anno.AnnoUtil.java

public static Equivalence<Version> versionEquivalence(final boolean ignoreStatus) {
    return new Equivalence<Version>() {
        protected boolean doEquivalent(Version a, Version b) {
            if (!a.name().equalsIgnoreCase(b.name()))
                return false;
            if (!a.uri().equals(b.uri()))
                return false;
            if (!a.value().equals(b.value()))
                return false;
            if (!ignoreStatus && !a.status().equals(b.status()))
                return false;
            int cmp = a.major() - b.major();
            if (cmp == 0 && a.minor() > -1 && b.minor() > -1)
                cmp = a.minor() - b.minor();
            if (cmp == 0 && a.revision() > -1 && b.revision() > -1)
                cmp = a.revision() - b.revision();
            return cmp == 0;
        }/*  w w  w  . java  2 s  .  c o m*/

        protected int doHash(Version t) {
            return t.hashCode();
        }
    };
}

From source file:org.openhealthtools.mdht.mdmi.CmdLineApp.java

public static String transform(String srcMap, String srcMdl, String srcMsg, String trgMap, String trgMdl,
        String trgMsg, String cnvElm) {
    File rootDir = new File(System.getProperties().getProperty("user.dir"));
    System.out.println("  rootDir = " + rootDir.getAbsolutePath());
    System.out.println("");

    // initialize the runtime, using the current folder as the roo folder
    Mdmi.INSTANCE.initialize(rootDir);//from  ww  w .j a  va2  s  . c  o  m
    Mdmi.INSTANCE.start();

    String retVal = null;
    try {
        // 1. check to make sure the maps and messages exist
        File f = Mdmi.INSTANCE.fileFromRelPath(srcMap);
        if (!f.exists() || !f.isFile()) {
            System.out.println("Source map file '" + srcMap + "' does not exist!");
            usage();
        }

        f = Mdmi.INSTANCE.fileFromRelPath(trgMap);
        if (!f.exists() || !f.isFile()) {
            System.out.println("Target map file '" + trgMap + "' does not exist!");
            usage();
        }

        f = Mdmi.INSTANCE.fileFromRelPath(srcMsg);
        if (!f.exists() || !f.isFile()) {
            System.out.println("Source message file '" + srcMsg + "' does not exist!");
            usage();
        }

        f = Mdmi.INSTANCE.fileFromRelPath(trgMsg);
        if (!f.exists() || !f.isFile()) {
            System.out.println("Target message file '" + trgMsg + "' does not exist!");
            usage();
        }

        // 2. make sure the qualified message names are spelled right
        String[] a = srcMdl.split("\\.");
        if (a == null || a.length != 2) {
            System.out
                    .println("Invalid source model '" + srcMdl + "', must be formatted as MapName.MessageName");
            usage();
        }
        String srcMapName = a[0];
        String srcMsgMdl = a[1];

        a = trgMdl.split("\\.");
        if (a == null || a.length != 2) {
            System.out
                    .println("Invalid target model '" + trgMdl + "', must be formatted as MapName.MessageName");
            usage();
        }
        String trgMapName = a[0];
        String trgMsgMdl = a[1];

        // 3. parse the elements array
        final ArrayList<String> elements = new ArrayList<String>();
        String[] ss = cnvElm.split(";");
        for (String s : ss) {
            if (s != null && s.trim().length() > 0) {
                elements.add(s);
            }
        }

        // 4. load the maps into the runtime.
        Mdmi.INSTANCE.getConfig().putMapInfo(new MdmiConfig.MapInfo(srcMapName, srcMap));
        Mdmi.INSTANCE.getConfig().putMapInfo(new MdmiConfig.MapInfo(trgMapName, trgMap));
        Mdmi.INSTANCE.getResolver().resolveConfig(Mdmi.INSTANCE.getConfig());

        // 5. Construct the parameters to the call based on the values passed in
        MdmiModelRef sMod = new MdmiModelRef(srcMapName, srcMsgMdl);
        MdmiMessage sMsg = new MdmiMessage(Mdmi.INSTANCE.fileFromRelPath(srcMsg));
        MdmiModelRef tMod = new MdmiModelRef(trgMapName, trgMsgMdl);
        MdmiMessage tMsg = new MdmiMessage(Mdmi.INSTANCE.fileFromRelPath(trgMsg));

        Map<String, MdmiBusinessElementReference> left = sMod.getModel().getBusinessElementHashMap();

        Map<String, MdmiBusinessElementReference> right = tMod.getModel().getBusinessElementHashMap();

        Equivalence<MdmiBusinessElementReference> valueEquivalence = new Equivalence<MdmiBusinessElementReference>() {

            @Override
            protected boolean doEquivalent(MdmiBusinessElementReference a, MdmiBusinessElementReference b) {
                return a.getUniqueIdentifier().equals(b.getUniqueIdentifier());
            }

            @Override
            protected int doHash(MdmiBusinessElementReference t) {
                return t.getUniqueIdentifier().hashCode();
            }
        };

        MapDifference<String, MdmiBusinessElementReference> differences = Maps.difference(left, right,
                valueEquivalence);

        Predicate<MdmiBusinessElementReference> predicate = new Predicate<MdmiBusinessElementReference>() {

            @Override
            public boolean apply(MdmiBusinessElementReference input) {

                if (!elements.isEmpty()) {
                    for (String element : elements) {
                        if (input.getName().equalsIgnoreCase(element)) {
                            return true;
                        }

                    }
                    return false;
                }
                return true;

            }
        };
        ;

        ArrayList<MdmiBusinessElementReference> bers = new ArrayList<MdmiBusinessElementReference>();
        bers.addAll(Collections2.filter(differences.entriesInCommon().values(), predicate));

        MdmiTransferInfo ti = new MdmiTransferInfo(sMod, sMsg, tMod, tMsg, bers);
        ti.useDictionary = true;

        // 6. call the runtime
        Mdmi.INSTANCE.executeTransfer(ti);

        // 7. set the return value
        retVal = tMsg.getDataAsString();

        saveResults(retVal);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    Mdmi.INSTANCE.stop();
    return retVal; // return the target message transformed
}

From source file:com.vmware.appfactory.taskqueue.tasks.state.tasks.FeedScanTask.java

@Override
protected void runFeedTask(@Nonnull FeedDao feedDao, @Nonnull Feed feed) throws TaskException {
    long now = AfCalendar.Now();
    AfFailure failure = null;/*from   ww w .jav a2  s.  co m*/

    updateProgressAndStatus(0, FeedScanState.FeedScanStatus.scanning);
    try {
        /* tell the original feed that a scan is in progress */
        {
            AfFailure status = new AfFailure();
            status.setSummary(Feed.SCANNING);
            status.setDetails("The feed is currently being scanned.");
            feed.setFailure(status);

            feedDao.update(feed);
        }

        /* Parse JSON from the feed's URL */
        Feed newFeed = readFromUrl(feed.getUrl());

        /* Perform any required relative -> absolute URL conversions */
        calculateAbsoluteUrls(newFeed);

        /* Get an updated list of applications. */
        List<Delta> appDeltas = updateListInPlace(feed.getApplications(), newFeed.getApplications(), now,
                new AbstractApp.AppEquivalence<Application>());

        if (appDeltas == null) {
            /* Must have been aborted */
            markScanComplete(FeedScanState.FeedScanStatus.cancelled);
            return;
        }

        /* Make sure applications refer to parent feed */
        for (Application app : feed.getApplications()) {
            app.setDataSource(feed);
        }

        if (!appDeltas.isEmpty()) {
            _log.debug("Read " + appDeltas.size() + " application deltas from " + feed.getUrl());
            feed.setLastRemoteChange(now);
        }

        /* Get an updated list of recipes. */
        List<Delta> recipeDeltas = updateListInPlace(feed.getRecipes(), newFeed.getRecipes(), now,
                new Equivalence<Recipe>() {
                    @Override
                    protected boolean doEquivalent(Recipe a, Recipe b) {
                        return Objects.equal(a.getName(), b.getName());
                    }

                    @Override
                    protected int doHash(Recipe recipe) {
                        return recipe.getName().hashCode();
                    }
                });

        if (recipeDeltas == null) {
            /* Must have been aborted */
            markScanComplete(FeedScanState.FeedScanStatus.cancelled);
            return;
        }

        /* Make sure recipes refer to parent feed */
        for (Recipe recipe : feed.getRecipes()) {
            recipe.setDataSource(feed);
        }

        if (!recipeDeltas.isEmpty()) {
            _log.debug("Read " + recipeDeltas.size() + " recipe deltas from " + feed.getUrl());
            feed.setLastRemoteChange(now);
        }

        /* our scan was successful, so clear any error flag */
        feed.setFailure(null);

        /* Save any and all changes to the feed */
        feedDao.update(feed);

        // Cache feed icons locally: must be called after flushing changes to DB
        // since it needs access to app IDs
        cacheApplicationIcons(feed);

        _log.debug(feed + " is scanned (" + appDeltas.size() + " application deltas, " + recipeDeltas.size()
                + " recipe deltas)");
        markScanComplete(FeedScanState.FeedScanStatus.complete);
        feed.setLastScan(now);
        feedDao.update(feed);

        // only show a notification if there are changes!
        if (!appDeltas.isEmpty() || !recipeDeltas.isEmpty()) {
            NotificationService.INSTANCE.newInfoEvent(appDeltas.size() + " application changes and "
                    + recipeDeltas.size() + " recipe changes found in " + feed.getName() + " feed.",
                    Component.feeds);
        }

        if (feed.isOkToConvert()) {
            if (getCurrentTaskState().getConversionWorkpoolId() < 0) {
                _log.warn("Not auto-converting application becuase no default workpool exists");
            } else if (getCurrentTaskState().getConversionDatastoreId() < 0) {
                _log.warn("Not auto-converting application becuase no default datastore exists");
            } else {
                AppFactoryTask convTask = new FeedConvertTask(feed, getTaskHelperFactory(), _conversionsQueue,
                        getCurrentTaskState().getMaxConversionAttempts(),
                        getCurrentTaskState().getConversionWorkpoolId(),
                        getCurrentTaskState().getConversionDatastoreId(),
                        getCurrentTaskState().getConversionRuntimeId());
                _conversionsQueue.addTask(convTask);
            }
        }
    } catch (FileNotFoundException ex) {
        failure = new AfFailure();
        failure.setSummary("URL resource not found.");
        throw new TaskException(this, ex);
    } catch (UnknownHostException ex) {
        failure = new AfFailure();
        failure.setSummary("Unknown host " + ex.getMessage());
        throw new TaskException(this, ex);
    } catch (Exception ex) {
        _log.error("General feed scan error", ex);
        failure = new AfFailure(ex);
        throw new TaskException(this, ex);
    } finally {
        if (failure != null) {
            /* Mark task feedScanStatus as 'failed' */
            markScanComplete(FeedScanState.FeedScanStatus.failed);

            /* Update feedScanStatus in the ORIGINAL feed */
            Feed originalFeed = feedDao.find(feed.getId());
            if (originalFeed == null) {
                _log.warn("Feed named: {} ({}) no longer exists. Hence skipping scan process.", feed.getName(),
                        feed.getId());
                return;
            }
            originalFeed.setFailure(failure);
            feedDao.update(originalFeed);

            /* Log the error */
            _log.error("Failed scan of feed \"" + feed.getName() + "\": " + failure.getSummary());

            /* Record an event */
            NotificationService.INSTANCE.newErrorEvent(feed.getName() + " feed scan failed.", Component.feeds);
        }
    }
}

From source file:org.decisiondeck.jlp.utils.LpSolverUtils.java

static public Equivalence<LpConstraint<?>> getConstraintEquivalence() {
    return new Equivalence<LpConstraint<?>>() {

        @Override//  w ww.j a v a 2 s  . c om
        public boolean doEquivalent(LpConstraint<?> a, LpConstraint<?> b) {
            if (a.getRhs() != b.getRhs()) {
                return false;
            }
            if (!a.getLhs().equals(b.getLhs())) {
                return false;
            }
            if (!a.getOperator().equals(b.getOperator())) {
                return false;
            }
            return true;
        }

        @Override
        public int doHash(LpConstraint<?> c) {
            return Objects.hashCode(c.getLhs(), c.getOperator(), Double.valueOf(c.getRhs()));
        }
    };
}

From source file:org.decisiondeck.jlp.utils.LpSolverUtils.java

static public Equivalence<Number> getEquivalenceByDoubleValue() {
    return new Equivalence<Number>() {
        @Override//from   www .ja v a  2  s.  com
        public boolean doEquivalent(Number a, Number b) {
            return a.doubleValue() == b.doubleValue();
        }

        @Override
        public int doHash(Number t) {
            return Double.valueOf(t.doubleValue()).hashCode();
        }
    };
}

From source file:org.decisiondeck.jlp.utils.LpSolverUtils.java

static public Equivalence<LpLinear<?>> getLinearEquivalence() {
    return new Equivalence<LpLinear<?>>() {
        @Override/*from   w w w.j av  a  2  s  .  c  o  m*/
        public boolean doEquivalent(LpLinear<?> a, LpLinear<?> b) {
            return Iterables.elementsEqual(a, b);
        }

        @Override
        public int doHash(LpLinear<?> t) {
            int hashCode = 1;
            for (LpTerm<?> term : t) {
                hashCode = 31 * hashCode + term.hashCode();
            }
            return hashCode;
        }
    };
}

From source file:org.decisiondeck.jlp.utils.LpSolverUtils.java

static public Equivalence<LpProblem<? extends Object>> getProblemEquivalence() {
    return new Equivalence<LpProblem<? extends Object>>() {
        @Override//from   ww  w. j  av  a 2 s .c  o m
        public boolean doEquivalent(LpProblem<? extends Object> a, LpProblem<? extends Object> b) {
            return computeEquivalent(a, b);
        }

        private <T1, T2> boolean computeEquivalent(LpProblem<T1> a, LpProblem<T2> b) {
            if (!a.getConstraints().equals(b.getConstraints())) {
                return false;
            }
            if (!Objects.equal(a.getObjective(), b.getObjective())) {
                return false;
            }
            if (!a.getVariables().equals(b.getVariables())) {
                return false;
            }
            for (T1 variable : a.getVariables()) {
                if (!b.getVariables().contains(variable)) {
                    return false;
                }
                @SuppressWarnings("unchecked")
                final T2 varTyped = (T2) variable;

                if (!getEquivalenceByDoubleValue().equivalent(a.getVarLowerBound(variable),
                        b.getVarLowerBound(varTyped))) {
                    return false;
                }
                if (!Objects.equal(a.getVarType(variable), b.getVarType(varTyped))) {
                    return false;
                }
                if (!getEquivalenceByDoubleValue().equivalent(a.getVarUpperBound(variable),
                        b.getVarUpperBound(varTyped))) {
                    return false;
                }
            }
            return true;
        }

        @Override
        public int doHash(LpProblem<? extends Object> t) {
            final int hashCode = Objects.hashCode(t.getObjective());
            return hashCode + t.getConstraints().hashCode() + t.getVariables().hashCode();
        }
    };
}