Example usage for java.util Map equals

List of usage examples for java.util Map equals

Introduction

In this page you can find the example usage for java.util Map equals.

Prototype

boolean equals(Object o);

Source Link

Document

Compares the specified object with this map for equality.

Usage

From source file:ugr.cristian.serverVideoApp.PacketHandler.java

/**
*This function return the time for a Edge Packet association
*@param edge The edge/*from  w w w  .j av a 2  s  .c  o m*/
*@param packet The packet
*@return time The stored time
*/

private Long returnPacketTime(Edge edge, Packet packet) {

    Set<Map<Edge, Packet>> temp = this.packetTime.keySet();
    Map<Edge, Packet> temp2 = new HashMap<Edge, Packet>();
    temp2.clear();
    temp2.put(edge, packet);

    for (Iterator<Map<Edge, Packet>> it = temp.iterator(); it.hasNext();) {

        Map<Edge, Packet> temp3 = it.next();
        if (temp3.equals(temp2)) {
            Long time = this.packetTime.get(temp3);
            this.packetTime.remove(temp3);
            log.trace("Returning time for the solicitated packet" + time);
            return time;
        }
    }

    return null;

}

From source file:org.pentaho.mantle.server.MantleServlet.java

public void setSolutionFileInfo(SolutionFileInfo fileInfo) throws SimpleMessageException {
    if ("true".equalsIgnoreCase(PentahoSystem.getSystemSetting("kiosk-mode", "false"))) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        throw new SimpleMessageException(ServerMessages.getString("featureDisabled")); //$NON-NLS-1$
    }// w  w  w.  j a v  a2  s  .c o m
    try {
        ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, getPentahoSession());
        if (repository.supportsAccessControls()) {
            String fullPath = ActionInfo.buildSolutionPath(fileInfo.solution, fileInfo.path, fileInfo.name);
            ISolutionFile solutionFile = repository.getSolutionFile(fullPath, ISolutionRepository.ACTION_SHARE);

            Map<IPermissionRecipient, IPermissionMask> origAcl = repository
                    .getEffectivePermissions((solutionFile));

            Map<IPermissionRecipient, IPermissionMask> acl = new HashMap<IPermissionRecipient, IPermissionMask>();
            for (UserPermission userPermission : fileInfo.userPermissions) {
                acl.put(new SimpleUser(userPermission.name), new SimplePermissionMask(userPermission.mask));
            }
            for (RolePermission rolePermission : fileInfo.rolePermissions) {
                acl.put(new SimpleRole(rolePermission.name), new SimplePermissionMask(rolePermission.mask));
            }

            // only set the permissions if the user made a change to the effective
            // acls (otherwise, keep inheriting);
            // this will avoid creating access control entries in the database when
            // they are the same as the ACEs
            // that would be inherited!
            if (!origAcl.equals(acl)) {
                repository.setPermissions(solutionFile, acl);
                repository.resetRepository();
            }

            if (!solutionFile.isDirectory()) {
                ISubscriptionRepository subscriptionRepository = PentahoSystem
                        .get(ISubscriptionRepository.class, getPentahoSession());
                String actionRef = fileInfo.solution + fileInfo.path + "/" + fileInfo.name; //$NON-NLS-1$
                ISubscribeContent subscribeContent = subscriptionRepository
                        .getContentByActionReference(actionRef);
                if (fileInfo.isSubscribable && subscribeContent == null) {
                    // make this actionRef subscribable
                    subscriptionRepository.addContent(actionRef, ""); //$NON-NLS-1$
                } else if (!fileInfo.isSubscribable && subscribeContent != null) {
                    // remove this actionRef from the subscribable list
                    subscriptionRepository.deleteSubscribeContent(subscribeContent);
                }
            }
        }
    } catch (Exception e) {
        // e.printStackTrace();
        throw new SimpleMessageException(e.getMessage());
    } finally {
    }
}

From source file:jenkins.branch.OrganizationFolder.java

/**
 * {@inheritDoc}//from ww w. j  a  v  a 2s . c  o m
 */
@Override
protected void computeChildren(final ChildObserver<MultiBranchProject<?, ?>> observer,
        final TaskListener listener) throws IOException, InterruptedException {
    // capture the current digests to prevent unnecessary rescan if re-saving after scan
    try {
        navDigest = Util.getDigestOf(Items.XSTREAM2.toXML(navigators));
    } catch (XStreamException e) {
        navDigest = null;
    }
    try {
        facDigest = Util.getDigestOf(Items.XSTREAM2.toXML(projectFactories));
    } catch (XStreamException e) {
        facDigest = null;
    }
    long start = System.currentTimeMillis();
    listener.getLogger().format("[%tc] Starting organization scan...%n", start);
    try {
        listener.getLogger().format("[%tc] Updating actions...%n", System.currentTimeMillis());
        Map<SCMNavigator, List<Action>> navigatorActions = new HashMap<>();
        for (SCMNavigator navigator : navigators) {
            List<Action> actions;
            try {
                actions = navigator.fetchActions(this, null, listener);
            } catch (IOException e) {
                MultiBranchProject.printStackTrace(e,
                        listener.error("[%tc] Could not refresh actions for navigator %s",
                                System.currentTimeMillis(), navigator));
                // preserve previous actions if we have some transient error fetching now (e.g. API rate limit)
                actions = Util.fixNull(state.getActions().get(navigator));
            }
            navigatorActions.put(navigator, actions);
        }
        // update any persistent actions for the SCMNavigator
        if (!navigatorActions.equals(state.getActions())) {
            boolean saveProject = false;
            for (List<Action> actions : navigatorActions.values()) {
                for (Action a : actions) {
                    // undo any hacks that attached the contributed actions without attribution
                    saveProject = removeActions(a.getClass()) || saveProject;
                }
            }
            BulkChange bc = new BulkChange(state);
            try {
                state.setActions(navigatorActions);
                try {
                    bc.commit();
                } catch (IOException | RuntimeException e) {
                    MultiBranchProject.printStackTrace(e, listener
                            .error("[%tc] Could not persist folder level actions", System.currentTimeMillis()));
                    throw e;
                }
                if (saveProject) {
                    try {
                        save();
                    } catch (IOException | RuntimeException e) {
                        MultiBranchProject.printStackTrace(e,
                                listener.error("[%tc] Could not persist folder level configuration changes",
                                        System.currentTimeMillis()));
                        throw e;
                    }
                }
            } finally {
                bc.abort();
            }
        }
        for (SCMNavigator navigator : navigators) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }
            listener.getLogger().format("[%tc] Consulting %s%n", System.currentTimeMillis(),
                    navigator.getDescriptor().getDisplayName());
            try {
                navigator.visitSources(
                        new SCMSourceObserverImpl(listener, observer, navigator, (SCMSourceEvent<?>) null));
            } catch (IOException | InterruptedException | RuntimeException e) {
                MultiBranchProject.printStackTrace(e,
                        listener.error("[%tc] Could not fetch sources from navigator %s",
                                System.currentTimeMillis(), navigator));
                throw e;
            }
        }
    } finally {
        long end = System.currentTimeMillis();
        listener.getLogger().format("[%tc] Finished organization scan. Scan took %s%n", end,
                Util.getTimeSpanString(end - start));

    }
}

From source file:org.openspaces.core.bean.DefaultBeanServer.java

public boolean replaceBeanAssignableTo(Class<?>[] interfaceClasses, String newBeanClassName,
        Map<String, String> newBeanProperties) throws BeanInitializationException {

    if (newBeanClassName == null) {
        throw new IllegalArgumentException("config.getBeanClassName() cannot be null.");
    }/*from   ww  w . ja va2 s .  c om*/

    if (newBeanProperties == null) {
        throw new IllegalArgumentException("config.getProperties() cannot be null.");
    }

    List<String> enabledBeansClassNames;
    try {

        if (!isClassNameAssignableFrom(newBeanClassName, interfaceClasses)) {
            throw new BeanConfigurationException(newBeanClassName
                    + " does not implement any of the supplied classes " + Arrays.toString(interfaceClasses));
        }

        enabledBeansClassNames = getEnabledBeansClassNamesAssignableTo(interfaceClasses);

        if (enabledBeansClassNames.size() > 1) {
            throw new IllegalStateException(
                    "Calling replaceBeanAssignableTo assumes there is only one enabled bean assignable to "
                            + Arrays.toString(interfaceClasses) + ". " + "Instead there are "
                            + enabledBeansClassNames.size() + ": "
                            + Arrays.toString(enabledBeansClassNames.toArray(new String[] {})));
        }

    } catch (ClassNotFoundException e) {
        throw new BeanConfigurationException("Problem creating new bean instance of class " + newBeanClassName,
                e);
    }

    // old bean
    String enabledBeanClassName = null;
    Map<String, String> beanProperties = null;

    // should we change the old bean with the new bean?
    boolean noChangeRequired = false;
    if (enabledBeansClassNames.size() == 0) {
        if (logger.isDebugEnabled()) {
            logger.debug("Request was made to enable bean instance " + newBeanClassName);
        }
    } else {
        enabledBeanClassName = enabledBeansClassNames.get(0);
        beanProperties = getBeanConfig(enabledBeanClassName);
        noChangeRequired = newBeanClassName.equals(enabledBeanClassName)
                && newBeanProperties.equals(beanProperties);

        if (logger.isDebugEnabled()) {
            if (!newBeanClassName.equals(enabledBeanClassName)) {
                logger.debug("Request was made to replace enabled bean instance " + enabledBeanClassName + " "
                        + "with " + newBeanClassName);
            } else if (!newBeanProperties.equals(beanProperties)) {
                logger.debug("Request was made to update enabled bean instance " + enabledBeanClassName + " "
                        + "with new configuration.");
            } else {
                logger.debug("Request to update enabled bean instance " + enabledBeanClassName + " "
                        + "is ignored since no configuration change detected.");
            }
        }
    }

    if (!noChangeRequired) {

        if (enabledBeanClassName != null) {
            disableBean(enabledBeanClassName);
        }

        setBeanConfig(newBeanClassName, newBeanProperties);
        enableBean(newBeanClassName);
    }

    return !noChangeRequired;
}

From source file:io.warp10.continuum.egress.EgressFetchHandler.java

/**
 * Output a tab separated version of fetched data. Deduplication is done on the fly so we don't decode twice.
 * /*www .j ava2  s .com*/
 */
private static void tsvDump(PrintWriter pw, GTSDecoderIterator iter, long now, long timespan, boolean raw,
        boolean dedup, boolean signed, AtomicReference<Metadata> lastMeta, AtomicLong lastCount,
        boolean sortMeta) throws IOException {

    String name = null;
    Map<String, String> labels = null;

    StringBuilder classSB = new StringBuilder();
    StringBuilder labelsSB = new StringBuilder();
    StringBuilder attributesSB = new StringBuilder();
    StringBuilder valueSB = new StringBuilder();

    Metadata lastMetadata = lastMeta.get();
    long currentCount = lastCount.get();

    while (iter.hasNext()) {
        GTSDecoder decoder = iter.next();

        if (!decoder.next()) {
            continue;
        }

        long toDecodeCount = Long.MAX_VALUE;

        if (timespan < 0) {
            Metadata meta = decoder.getMetadata();
            if (!meta.equals(lastMetadata)) {
                lastMetadata = meta;
                currentCount = 0;
            }
            toDecodeCount = Math.max(0, -timespan - currentCount);
        }

        //
        // Only display the class + labels if they have changed since the previous GTS
        //

        Map<String, String> lbls = decoder.getLabels();

        //
        // Compute the new name
        //

        boolean displayName = false;

        if (null == name || (!name.equals(decoder.getName()) || !labels.equals(lbls))) {
            displayName = true;
            name = decoder.getName();
            labels = lbls;
            classSB.setLength(0);
            GTSHelper.encodeName(classSB, name);
            labelsSB.setLength(0);
            attributesSB.setLength(0);
            boolean first = true;

            if (sortMeta) {
                lbls = new TreeMap<String, String>(lbls);
            }
            for (Entry<String, String> entry : lbls.entrySet()) {
                //
                // Skip owner/producer labels and any other 'private' labels
                //
                if (!signed) {
                    if (Constants.PRODUCER_LABEL.equals(entry.getKey())) {
                        continue;
                    }
                    if (Constants.OWNER_LABEL.equals(entry.getKey())) {
                        continue;
                    }
                }

                if (!first) {
                    labelsSB.append(",");
                }
                GTSHelper.encodeName(labelsSB, entry.getKey());
                labelsSB.append("=");
                GTSHelper.encodeName(labelsSB, entry.getValue());
                first = false;
            }

            first = true;
            if (decoder.getMetadata().getAttributesSize() > 0) {

                if (sortMeta) {
                    decoder.getMetadata()
                            .setAttributes(new TreeMap<String, String>(decoder.getMetadata().getAttributes()));
                }

                for (Entry<String, String> entry : decoder.getMetadata().getAttributes().entrySet()) {
                    if (!first) {
                        attributesSB.append(",");
                    }
                    GTSHelper.encodeName(attributesSB, entry.getKey());
                    attributesSB.append("=");
                    GTSHelper.encodeName(attributesSB, entry.getValue());
                    first = false;
                }
            }

        }

        long timestamp = 0L;
        long location = GeoTimeSerie.NO_LOCATION;
        long elevation = GeoTimeSerie.NO_ELEVATION;
        Object value = null;

        boolean dup = true;

        long decoded = 0;

        do {

            if (toDecodeCount == decoded) {
                break;
            }

            //
            // Filter out any value not in the time range
            //

            long newTimestamp = decoder.getTimestamp();

            if (newTimestamp > now || (timespan >= 0 && newTimestamp <= (now - timespan))) {
                continue;
            }

            //
            // TODO(hbs): filter out values with no location or outside the selected geozone when a geozone was set
            //

            long newLocation = decoder.getLocation();
            long newElevation = decoder.getElevation();
            Object newValue = decoder.getValue();

            dup = true;

            if (dedup) {
                if (location != newLocation || elevation != newElevation) {
                    dup = false;
                } else {
                    if (null == newValue) {
                        // Consider nulls as duplicates (can't happen!)
                        dup = false;
                    } else if (newValue instanceof Number) {
                        if (!((Number) newValue).equals(value)) {
                            dup = false;
                        }
                    } else if (newValue instanceof String) {
                        if (!((String) newValue).equals(value)) {
                            dup = false;
                        }
                    } else if (newValue instanceof Boolean) {
                        if (!((Boolean) newValue).equals(value)) {
                            dup = false;
                        }
                    }
                }
            }

            decoded++;

            location = newLocation;
            elevation = newElevation;
            timestamp = newTimestamp;
            value = newValue;

            if (raw) {
                if (!dedup || !dup) {
                    pw.print(classSB);
                    pw.print('\t');
                    pw.print(labelsSB);
                    pw.print('\t');
                    pw.print(attributesSB);
                    pw.print('\t');

                    pw.print(timestamp);
                    pw.print('\t');

                    if (GeoTimeSerie.NO_LOCATION != location) {
                        double[] latlon = GeoXPLib.fromGeoXPPoint(location);
                        pw.print(latlon[0]);
                        pw.print('\t');
                        pw.print(latlon[1]);
                    } else {
                        pw.print('\t');
                    }

                    pw.print('\t');

                    if (GeoTimeSerie.NO_ELEVATION != elevation) {
                        pw.print(elevation);
                    }
                    pw.print('\t');

                    valueSB.setLength(0);
                    GTSHelper.encodeValue(valueSB, value);
                    pw.println(valueSB);
                }
            } else {
                // Display the name only if we have at least one value to display
                // We force 'dup' to be false when we must show the name
                if (displayName) {
                    pw.print("# ");
                    pw.print(classSB);
                    pw.print("{");
                    pw.print(labelsSB);
                    pw.print("}");
                    pw.print("{");
                    pw.print(attributesSB);
                    pw.println("}");
                    displayName = false;
                    dup = false;
                }

                if (!dedup || !dup) {
                    pw.print(timestamp);
                    pw.print('\t');
                    if (GeoTimeSerie.NO_LOCATION != location) {
                        double[] latlon = GeoXPLib.fromGeoXPPoint(location);
                        pw.print(latlon[0]);
                        pw.print('\t');
                        pw.print(latlon[1]);
                    } else {
                        pw.print('\t');
                    }

                    pw.print('\t');

                    if (GeoTimeSerie.NO_ELEVATION != elevation) {
                        pw.print(elevation);
                    }
                    pw.print('\t');

                    valueSB.setLength(0);
                    GTSHelper.encodeValue(valueSB, value);
                    pw.println(valueSB);
                }
            }
        } while (decoder.next());

        // Update currentcount
        if (timespan < 0) {
            currentCount += decoded;
        }

        // Print any remaining value
        if (dedup && dup) {
            if (raw) {
                pw.print(classSB);
                pw.print('\t');
                pw.print(labelsSB);
                pw.print('\t');
                pw.print(attributesSB);
                pw.print('\t');

                pw.print(timestamp);
                pw.print('\t');

                if (GeoTimeSerie.NO_LOCATION != location) {
                    double[] latlon = GeoXPLib.fromGeoXPPoint(location);
                    pw.print(latlon[0]);
                    pw.print('\t');
                    pw.print(latlon[1]);
                } else {
                    pw.print('\t');
                }

                pw.print('\t');

                if (GeoTimeSerie.NO_ELEVATION != elevation) {
                    pw.print(elevation);
                }
                pw.print('\t');

                valueSB.setLength(0);
                GTSHelper.encodeValue(valueSB, value);
                pw.println(valueSB);
            } else {
                pw.print(timestamp);
                pw.print('\t');
                if (GeoTimeSerie.NO_LOCATION != location) {
                    double[] latlon = GeoXPLib.fromGeoXPPoint(location);
                    pw.print(latlon[0]);
                    pw.print('\t');
                    pw.print(latlon[1]);
                } else {
                    pw.print('\t');
                }

                pw.print('\t');

                if (GeoTimeSerie.NO_ELEVATION != elevation) {
                    pw.print(elevation);
                }
                pw.print('\t');

                valueSB.setLength(0);
                GTSHelper.encodeValue(valueSB, value);
                pw.println(valueSB);
            }

        }

        //
        // If displayName is still true it means we should have displayed the name but no value matched,
        // so set name to null so we correctly display the name for the next decoder if it has values
        //

        if (displayName) {
            name = null;
        }
    }

    lastMeta.set(lastMetadata);
    lastCount.set(currentCount);
}

From source file:io.warp10.continuum.egress.EgressFetchHandler.java

private static void jsonDump(PrintWriter pw, GTSDecoderIterator iter, long now, long timespan, boolean dedup,
        boolean signed, AtomicReference<Metadata> lastMeta, AtomicLong lastCount) throws IOException {

    String name = null;//from   w w w. jav a2s  .com
    Map<String, String> labels = null;

    pw.print("[");

    boolean hasValues = false;

    Metadata lastMetadata = lastMeta.get();
    long currentCount = lastCount.get();

    try {
        StringBuilder sb = new StringBuilder();

        JsonSerializer serializer = new JsonSerializerFactory().create();

        boolean firstgts = true;

        long mask = (long) (Math.random() * Long.MAX_VALUE);

        while (iter.hasNext()) {
            GTSDecoder decoder = iter.next();

            if (dedup) {
                decoder = decoder.dedup();
            }

            if (!decoder.next()) {
                continue;
            }

            long toDecodeCount = Long.MAX_VALUE;

            if (timespan < 0) {
                Metadata meta = decoder.getMetadata();
                if (!meta.equals(lastMetadata)) {
                    lastMetadata = meta;
                    currentCount = 0;
                }
                toDecodeCount = Math.max(0, -timespan - currentCount);
            }

            //
            // Only display the class + labels if they have changed since the previous GTS
            //

            Map<String, String> lbls = decoder.getLabels();

            //
            // Compute the new name
            //

            boolean displayName = false;

            if (null == name || (!name.equals(decoder.getName()) || !labels.equals(lbls))) {
                displayName = true;
                name = decoder.getName();
                labels = lbls;
                sb.setLength(0);

                sb.append("{\"c\":");

                //sb.append(gson.toJson(name));
                sb.append(serializer.serialize(name));

                boolean first = true;

                sb.append(",\"l\":{");

                for (Entry<String, String> entry : lbls.entrySet()) {
                    //
                    // Skip owner/producer labels and any other 'private' labels
                    //
                    if (!signed) {
                        if (Constants.PRODUCER_LABEL.equals(entry.getKey())) {
                            continue;
                        }
                        if (Constants.OWNER_LABEL.equals(entry.getKey())) {
                            continue;
                        }
                    }

                    if (!first) {
                        sb.append(",");
                    }

                    //sb.append(gson.toJson(entry.getKey()));
                    sb.append(serializer.serialize(entry.getKey()));
                    sb.append(":");
                    //sb.append(gson.toJson(entry.getValue()));
                    sb.append(serializer.serialize(entry.getValue()));
                    first = false;
                }
                sb.append("}");

                sb.append(",\"a\":{");

                first = true;
                for (Entry<String, String> entry : decoder.getMetadata().getAttributes().entrySet()) {
                    if (!first) {
                        sb.append(",");
                    }

                    //sb.append(gson.toJson(entry.getKey()));
                    sb.append(serializer.serialize(entry.getKey()));
                    sb.append(":");
                    //sb.append(gson.toJson(entry.getValue()));
                    sb.append(serializer.serialize(entry.getValue()));
                    first = false;
                }

                sb.append("}");
                sb.append(",\"i\":\"");
                sb.append(decoder.getLabelsId() & mask);
                sb.append("\",\"v\":[");
            }

            long decoded = 0L;

            do {

                if (toDecodeCount == decoded) {
                    break;
                }

                // FIXME(hbs): only display the results which match the authorized (according to token) timerange and geo zones

                //
                // Filter out any value not in the time range
                //

                if (decoder.getTimestamp() > now
                        || (timespan >= 0 && decoder.getTimestamp() <= (now - timespan))) {
                    continue;
                }

                decoded++;

                //
                // TODO(hbs): filter out values with no location or outside the selected geozone when a geozone was set
                //

                // Display the name only if we have at least one value to display
                if (displayName) {
                    if (!firstgts) {
                        pw.print("]},");
                    }
                    pw.print(sb.toString());
                    firstgts = false;
                    displayName = false;
                } else {
                    pw.print(",");
                }
                hasValues = true;
                pw.print("[");
                pw.print(decoder.getTimestamp());
                if (GeoTimeSerie.NO_LOCATION != decoder.getLocation()) {
                    double[] latlon = GeoXPLib.fromGeoXPPoint(decoder.getLocation());
                    pw.print(",");
                    pw.print(latlon[0]);
                    pw.print(",");
                    pw.print(latlon[1]);
                }
                if (GeoTimeSerie.NO_ELEVATION != decoder.getElevation()) {
                    pw.print(",");
                    pw.print(decoder.getElevation());
                }
                pw.print(",");
                Object value = decoder.getValue();

                if (value instanceof Number) {
                    pw.print(value);
                } else if (value instanceof Boolean) {
                    pw.print(Boolean.TRUE.equals(value) ? "true" : "false");
                } else {
                    //pw.print(gson.toJson(value.toString()));
                    pw.print(serializer.serialize(value.toString()));
                }
                pw.print("]");
            } while (decoder.next());

            if (timespan < 0) {
                currentCount += decoded;
            }

            //
            // If displayName is still true it means we should have displayed the name but no value matched,
            // so set name to null so we correctly display the name for the next decoder if it has values
            //

            if (displayName) {
                name = null;
            }
        }

    } catch (Throwable t) {
        throw t;
    } finally {
        if (hasValues) {
            pw.print("]}");
        }
        pw.print("]");
    }

    lastMeta.set(lastMetadata);
    lastCount.set(currentCount);
}

From source file:jenkins.branch.MultiBranchProject.java

/**
 * {@inheritDoc}/*w w  w.  j  a  v  a2  s . c  o m*/
 */
@Override
protected void computeChildren(final ChildObserver<P> observer, final TaskListener listener)
        throws IOException, InterruptedException {
    // capture the current digests to prevent unnecessary reindex if re-saving after index
    try {
        srcDigest = Util.getDigestOf(Items.XSTREAM2.toXML(sources));
    } catch (XStreamException e) {
        srcDigest = null;
    }
    try {
        facDigest = Util.getDigestOf(Items.XSTREAM2.toXML(getProjectFactory()));
    } catch (XStreamException e) {
        facDigest = null;
    }
    long start = System.currentTimeMillis();
    listener.getLogger().format("[%tc] Starting branch indexing...%n", start);
    try {
        final BranchProjectFactory<P, R> _factory = getProjectFactory();
        List<SCMSource> scmSources = getSCMSources();
        Map<String, List<Action>> sourceActions = new LinkedHashMap<>();
        for (SCMSource source : scmSources) {
            try {
                sourceActions.put(source.getId(), source.fetchActions(null, listener));
            } catch (IOException | InterruptedException | RuntimeException e) {
                printStackTrace(e, listener.error("[%tc] Could not update folder level actions from source %s",
                        System.currentTimeMillis(), source.getId()));
                throw e;
            }
        }
        // update any persistent actions for the SCMSource
        if (!sourceActions.equals(state.sourceActions)) {
            boolean saveProject = false;
            for (List<Action> actions : sourceActions.values()) {
                for (Action a : actions) {
                    // undo any hacks that attached the contributed actions without attribution
                    saveProject = removeActions(a.getClass()) || saveProject;
                }
            }
            BulkChange bc = new BulkChange(state);
            try {
                state.sourceActions.keySet().retainAll(sourceActions.keySet());
                state.sourceActions.putAll(sourceActions);
                try {
                    bc.commit();
                } catch (IOException | RuntimeException e) {
                    printStackTrace(e, listener.error("[%tc] Could not persist folder level actions",
                            System.currentTimeMillis()));
                    throw e;
                }
                if (saveProject) {
                    try {
                        save();
                    } catch (IOException | RuntimeException e) {
                        printStackTrace(e,
                                listener.error("[%tc] Could not persist folder level configuration changes",
                                        System.currentTimeMillis()));
                        throw e;
                    }
                }
            } finally {
                bc.abort();
            }
        }
        for (final SCMSource source : scmSources) {
            try {
                source.fetch(new SCMHeadObserverImpl(source, observer, listener, _factory,
                        new IndexingCauseFactory(), null), listener);
            } catch (IOException | InterruptedException | RuntimeException e) {
                printStackTrace(e, listener.error("[%tc] Could not fetch branches from source %s",
                        System.currentTimeMillis(), source.getId()));
                throw e;
            }
        }
    } finally {
        long end = System.currentTimeMillis();
        listener.getLogger().format("[%tc] Finished branch indexing. Indexing took %s%n", end,
                Util.getTimeSpanString(end - start));
    }
}

From source file:org.springframework.extensions.webscripts.AbstractRuntime.java

/**
 * Execute the Web Script encapsulated by this Web Script Runtime
 *///from  w w w  .j  a v  a 2  s  .c  om
final public void executeScript() {
    final boolean debug = logger.isDebugEnabled();
    long startRuntime = 0L;
    if (debug)
        startRuntime = System.nanoTime();

    final String method = getScriptMethod();
    String scriptUrl = null;
    Match match = null;

    try {
        // extract script url
        scriptUrl = getScriptUrl();
        if (scriptUrl == null || scriptUrl.length() == 0) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Script URL not specified");
        }

        if (debug)
            logger.debug("(Runtime=" + getName() + ", Container=" + container.getName()
                    + ") Processing script url (" + method + ") " + scriptUrl);

        WebScriptRequest scriptReq = null;
        WebScriptResponse scriptRes = null;
        Authenticator auth = null;

        RequiredAuthentication containerRequiredAuth = container.getRequiredAuthentication();

        if (!containerRequiredAuth.equals(RequiredAuthentication.none)) {
            // Create initial request & response
            scriptReq = createRequest(null);
            scriptRes = createResponse();
            auth = createAuthenticator();

            if (debug)
                logger.debug("(Runtime=" + getName() + ", Container=" + container.getName()
                        + ") Container requires pre-auth: " + containerRequiredAuth);

            boolean preAuth = true;

            if (auth != null && auth.emptyCredentials()) {
                // check default (unauthenticated) domain
                match = container.getRegistry().findWebScript(method, scriptUrl);
                if ((match != null) && (match.getWebScript().getDescription().getRequiredAuthentication()
                        .equals(RequiredAuthentication.none))) {
                    preAuth = false;
                }
            }

            if (preAuth && (!container.authenticate(auth, containerRequiredAuth))) {
                return; // return response (eg. prompt for un/pw if status is 401 or redirect)
            }
        }

        if (match == null) {
            match = container.getRegistry().findWebScript(method, scriptUrl);
        }

        if (match == null || match.getKind() == Match.Kind.URI) {
            if (match == null) {
                String msg = "Script url " + scriptUrl + " does not map to a Web Script.";
                if (debug)
                    logger.debug(msg);
                throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, msg);
            } else {
                String msg = "Script url " + scriptUrl + " does not support the method " + method;
                if (debug)
                    logger.debug(msg);
                throw new WebScriptException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
            }
        }

        // create web script request & response
        scriptReq = createRequest(match);
        scriptRes = createResponse();

        if (auth == null) {
            // not pre-authenticated
            auth = createAuthenticator();
        }

        if (debug)
            logger.debug("Agent: " + scriptReq.getAgent());

        long startScript = System.nanoTime();
        final WebScript script = match.getWebScript();
        final Description description = script.getDescription();

        try {
            if (debug) {
                String reqFormat = scriptReq.getFormat();
                String format = (reqFormat == null || reqFormat.length() == 0) ? "[undefined]" : reqFormat;
                Description desc = scriptReq.getServiceMatch().getWebScript().getDescription();
                logger.debug("Invoking Web Script " + description.getId() + " (format " + format + ", style: "
                        + desc.getFormatStyle() + ", default: " + desc.getDefaultFormat() + ")");
            }

            executeScript(scriptReq, scriptRes, auth);
        } finally {
            if (debug) {
                long endScript = System.nanoTime();
                logger.debug("Web Script " + description.getId() + " executed in "
                        + (endScript - startScript) / 1000000f + "ms");
            }
        }
    } catch (Throwable e) {
        if (beforeProcessError(match, e)) {
            if (e instanceof WebScriptException
                    && (((WebScriptException) e).getStatus() == HttpServletResponse.SC_NOT_FOUND
                            || ((WebScriptException) e).getStatus() == HttpServletResponse.SC_UNAUTHORIZED)) {
                // debug level output for "missing" WebScripts and API URLs entered incorrectly
                String errorCode = ((WebScriptException) e).getStatus() == HttpServletResponse.SC_NOT_FOUND
                        ? "NOT FOUND"
                        : "UNAUTHORIZED";
                logger.debug("Webscript did not execute. (" + errorCode + "): " + e.getMessage());
            }
            // log error on server so its not swallowed and lost
            else if (logger.isErrorEnabled()) {
                logger.error("Exception from executeScript - redirecting to status template error: "
                        + e.getMessage(), e);
            }

            // setup context
            WebScriptRequest req = createRequest(match);
            WebScriptResponse res = createResponse();
            String format = req.getFormat();

            // extract status code, if specified
            int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
            StatusTemplate statusTemplate = null;
            Map<String, Object> statusModel = null;
            if (e instanceof WebScriptException) {
                WebScriptException we = (WebScriptException) e;
                statusCode = we.getStatus();
                statusTemplate = we.getStatusTemplate();
                statusModel = we.getStatusModel();
            }

            // retrieve status template for response rendering
            if (statusTemplate == null) {
                // locate status template
                // NOTE: search order...
                //   1) root located <status>.ftl
                //   2) root located <format>.status.ftl
                //   3) root located status.ftl
                statusTemplate = getStatusCodeTemplate(statusCode);

                String validTemplatePath = container.getTemplateProcessorRegistry()
                        .findValidTemplatePath(statusTemplate.getPath());
                if (validTemplatePath == null) {
                    if (format != null && format.length() > 0) {
                        // if we have a format try and get the format specific status template
                        statusTemplate = getFormatStatusTemplate(format);
                        validTemplatePath = container.getTemplateProcessorRegistry()
                                .findValidTemplatePath(statusTemplate.getPath());
                    }

                    // if we don't have a valid template path get the default status template
                    if (validTemplatePath == null) {
                        statusTemplate = getStatusTemplate();
                        validTemplatePath = container.getTemplateProcessorRegistry()
                                .findValidTemplatePath(statusTemplate.getPath());
                    }

                    // throw error if a status template could not be found
                    if (validTemplatePath == null) {
                        throw new WebScriptException("Failed to find status template "
                                + statusTemplate.getPath() + " (format: " + statusTemplate.getFormat() + ")");
                    }
                }
            }

            // create basic model for all information known at this point, if one hasn't been pre-provided
            if (statusModel == null || statusModel.equals(Collections.EMPTY_MAP)) {
                statusModel = new HashMap<String, Object>(8, 1.0f);
                statusModel.putAll(container.getTemplateParameters());
                statusModel.put("url", createURLModel(req));
                if (match != null && match.getWebScript() != null) {
                    statusModel.put("webscript", match.getWebScript().getDescription());
                }
            }

            // add status to model
            Status status = new Status();
            status.setCode(statusCode);
            status.setMessage(e.getMessage() != null ? e.getMessage() : e.toString());
            if (exceptionLogger.isDebugEnabled()) {
                status.setException(e);
            }
            statusModel.put("status", status);

            // render output
            String mimetype = container.getFormatRegistry().getMimeType(req.getAgent(),
                    statusTemplate.getFormat());
            if (mimetype == null) {
                throw new WebScriptException(
                        "Web Script format '" + statusTemplate.getFormat() + "' is not registered");
            }

            if (debug) {
                logger.debug("Force success status header in response: " + req.forceSuccessStatus());
                logger.debug("Sending status " + statusCode + " (Template: " + statusTemplate.getPath() + ")");
                logger.debug("Rendering response: content type=" + mimetype);
            }

            Cache cache = new Cache();
            cache.setNeverCache(true);
            res.setCache(cache);
            res.setStatus(req.forceSuccessStatus() ? HttpServletResponse.SC_OK : statusCode);
            res.setContentType(mimetype + ";charset=UTF-8");
            try {
                String validTemplatePath = container.getTemplateProcessorRegistry()
                        .findValidTemplatePath(statusTemplate.getPath());
                TemplateProcessor statusProcessor = container.getTemplateProcessorRegistry()
                        .getTemplateProcessor(validTemplatePath);
                statusProcessor.process(validTemplatePath, statusModel, res.getWriter());
            } catch (Exception e1) {
                logger.error("Internal error", e1);
                throw new WebScriptException("Internal error", e1);
            }
        }
    } finally {
        if (debug) {
            long endRuntime = System.nanoTime();
            logger.debug("Processed script url (" + method + ") " + scriptUrl + " in "
                    + (endRuntime - startRuntime) / 1000000f + "ms");
        }
    }
}

From source file:org.apache.hadoop.hive.metastore.TestHiveMetaStore.java

public void testNameMethods() {
    Map<String, String> spec = new LinkedHashMap<String, String>();
    spec.put("ds", "2008-07-01 14:13:12");
    spec.put("hr", "14");
    List<String> vals = new ArrayList<String>();
    for (String v : spec.values()) {
        vals.add(v);//from w w w  .  ja  va2s.c  o m
    }
    String partName = "ds=2008-07-01 14%3A13%3A12/hr=14";

    try {
        List<String> testVals = client.partitionNameToVals(partName);
        assertTrue("Values from name are incorrect", vals.equals(testVals));

        Map<String, String> testSpec = client.partitionNameToSpec(partName);
        assertTrue("Spec from name is incorrect", spec.equals(testSpec));

        List<String> emptyVals = client.partitionNameToVals("");
        assertTrue("Values should be empty", emptyVals.size() == 0);

        Map<String, String> emptySpec = client.partitionNameToSpec("");
        assertTrue("Spec should be empty", emptySpec.size() == 0);
    } catch (Exception e) {
        assert (false);
    }
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

/**
 * Test method for 'java.util.Object.equals(Object)'.
 *
 * @see java.util.Map#equals(Object)//from ww  w.j a v  a2  s  .c o m
 */
public void testEquals() {
    K[] keys = getKeys();
    V[] values = getValues();
    Map<K, V> map0 = createMap();
    Map<K, V> map1 = createMap();
    assertTrue(map0.equals(map1));
    map0.put(keys[0], values[0]);
    map1.put(keys[0], values[0]);
    assertTrue(map0.equals(map0));
    assertTrue(map0.equals(map1));
    map0.put(keys[1], values[1]);
    assertFalse(map0.equals(map1));
}