Example usage for org.apache.commons.collections MapUtils invertMap

List of usage examples for org.apache.commons.collections MapUtils invertMap

Introduction

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

Prototype

public static Map invertMap(Map map) 

Source Link

Document

Inverts the supplied map returning a new HashMap such that the keys of the input are swapped with the values.

Usage

From source file:eu.freme.common.rest.NIFParameterFactory.java

public NIFParameterSet constructFromHttp(String input, String informat, String outformat, String postBody,
        String acceptHeader, String contentTypeHeader, String prefix, String nifVersion,
        boolean allowEmptyInput) throws BadRequestException {

    String thisInput;//from   w w  w .java 2  s . c  om
    if (!allowEmptyInput && input == null && postBody == null) {
        throw new BadRequestException("no input found in request");
    } else if (input != null) {
        thisInput = input;
    } else {
        thisInput = postBody;
    }

    String thisInformat;
    if (informat == null && contentTypeHeader == null) {
        thisInformat = TURTLE;
    } else if (informat != null) {
        thisInformat = serializationFormatMapper.get(informat);
        if (thisInformat == null) {
            throw new BadRequestException("parameter informat has invalid value \"" + informat
                    + "\". Please use one of the registered serialization format values: "
                    + serializationFormatMapper.keySet().stream().collect(Collectors.joining(", ")));
        }
    } else {
        String[] contentTypeHeaderParts = contentTypeHeader.split(";");
        thisInformat = serializationFormatMapper.get(contentTypeHeaderParts[0]);
        if (thisInformat == null) {
            throw new BadRequestException("Content-Type header has invalid value \"" + contentTypeHeader
                    + "\". Please use one of the registered serialization format values: "
                    + serializationFormatMapper.keySet().stream().collect(Collectors.joining(", ")));
        }
    }
    if (!RDFConstants.SERIALIZATION_FORMATS.contains(thisInformat)
            && !thisInformat.equals(SerializationFormatMapper.PLAINTEXT)) {
        throw new UnsupportedRDFSerializationException("Parameter informat has invalid value \"" + thisInformat
                + "\". Please use one of: "
                + SERIALIZATION_FORMATS.stream()
                        .map(v -> MapUtils.invertMap(serializationFormatMapper).get(v).toString())
                        .collect(Collectors.joining(", "))
                + " or " + SerializationFormatMapper.PLAINTEXT);
    }

    String thisOutformat;
    if (acceptHeader != null && acceptHeader.equals("*/*")) {
        acceptHeader = TURTLE;
    }
    if (outformat == null && acceptHeader == null) {
        thisOutformat = TURTLE;
    } else if (outformat != null) {
        thisOutformat = serializationFormatMapper.get(outformat);
        if (thisOutformat == null) {
            throw new BadRequestException("Parameter outformat has invalid value \"" + outformat
                    + "\". Please use one of the registered serialization format values: "
                    + serializationFormatMapper.keySet().stream().collect(Collectors.joining(", ")));
        }
    } else {
        thisOutformat = serializationFormatMapper.get(acceptHeader.split(";")[0]);
        if (thisOutformat == null) {
            throw new BadRequestException("Accept header has invalid value \"" + acceptHeader.split(";")[0]
                    + "\". Please use one of the registered serialization format values: "
                    + serializationFormatMapper.keySet().stream().collect(Collectors.joining(", ")));
        }
    }
    if (!RDFConstants.SERIALIZATION_FORMATS.contains(thisOutformat)) {
        throw new UnsupportedRDFSerializationException(
                "Parameter outformat has invalid value \"" + thisOutformat + "\". Please use one of: "
                        + SERIALIZATION_FORMATS.stream()
                                .map(v -> MapUtils.invertMap(serializationFormatMapper).get(v).toString())
                                .collect(Collectors.joining(", ")));
    }

    String thisPrefix;
    if (prefix == null) {
        thisPrefix = getDefaultPrefix();
    } else {
        thisPrefix = prefix;
    }
    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes);
    if (!urlValidator.isValid(thisPrefix)) {
        throw new BadRequestException("invalid prefix");
    }

    if (nifVersion == null) {
        nifVersion = RDFConstants.nifVersion2_0;
    } else if (!(nifVersion.equals(RDFConstants.nifVersion2_0)
            || nifVersion.equals(RDFConstants.nifVersion2_1))) {
        throw new NIFVersionNotSupportedException("NIF version \"" + nifVersion + "\" is not supported");
    }

    return new NIFParameterSet(thisInput, thisInformat, thisOutformat, thisPrefix, nifVersion);
}

From source file:org.apache.accumulo.core.util.shell.commands.TablesCommand.java

@SuppressWarnings("unchecked")
@Override//from   w  ww.j  a  va  2s  . c  o  m
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState)
        throws AccumuloException, AccumuloSecurityException, IOException, NamespaceNotFoundException {

    final String namespace = cl.hasOption(OptUtil.namespaceOpt().getOpt())
            ? OptUtil.getNamespaceOpt(cl, shellState)
            : null;
    Map<String, String> tables = shellState.getConnector().tableOperations().tableIdMap();

    // filter only specified namespace
    tables = Maps.filterKeys(tables, new Predicate<String>() {
        @Override
        public boolean apply(String tableName) {
            return namespace == null || Tables.qualify(tableName).getFirst().equals(namespace);
        }
    });

    final boolean sortByTableId = cl.hasOption(sortByTableIdOption.getOpt());
    tables = new TreeMap<String, String>((sortByTableId ? MapUtils.invertMap(tables) : tables));

    Iterator<String> it = Iterators.transform(tables.entrySet().iterator(),
            new Function<Entry<String, String>, String>() {
                @Override
                public String apply(Map.Entry<String, String> entry) {
                    String tableName = String.valueOf(sortByTableId ? entry.getValue() : entry.getKey());
                    String tableId = String.valueOf(sortByTableId ? entry.getKey() : entry.getValue());
                    if (namespace != null)
                        tableName = Tables.qualify(tableName).getSecond();
                    if (cl.hasOption(tableIdOption.getOpt()))
                        return String.format(NAME_AND_ID_FORMAT, tableName, tableId);
                    else
                        return tableName;
                };
            });

    shellState.printLines(it, !cl.hasOption(disablePaginationOpt.getOpt()));
    return 0;
}

From source file:org.apache.accumulo.shell.commands.TablesCommand.java

@SuppressWarnings("unchecked")
@Override/*w  w w  .ja  v a 2  s .  c  om*/
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState)
        throws AccumuloException, AccumuloSecurityException, IOException, NamespaceNotFoundException {

    final String namespace = cl.hasOption(OptUtil.namespaceOpt().getOpt())
            ? OptUtil.getNamespaceOpt(cl, shellState)
            : null;
    Map<String, String> tables = shellState.getConnector().tableOperations().tableIdMap();

    // filter only specified namespace
    tables = Maps.filterKeys(tables,
            tableName -> namespace == null || Tables.qualify(tableName).getFirst().equals(namespace));

    final boolean sortByTableId = cl.hasOption(sortByTableIdOption.getOpt());
    tables = new TreeMap<String, String>((sortByTableId ? MapUtils.invertMap(tables) : tables));

    Iterator<String> it = Iterators.transform(tables.entrySet().iterator(), entry -> {
        String tableName = String.valueOf(sortByTableId ? entry.getValue() : entry.getKey());
        String tableId = String.valueOf(sortByTableId ? entry.getKey() : entry.getValue());
        if (namespace != null)
            tableName = Tables.qualify(tableName).getSecond();
        if (cl.hasOption(tableIdOption.getOpt()))
            return String.format(NAME_AND_ID_FORMAT, tableName, tableId);
        else
            return tableName;
    });

    shellState.printLines(it, !cl.hasOption(disablePaginationOpt.getOpt()));
    return 0;
}

From source file:org.jahia.services.content.rules.RulesListener.java

public void onEvent(EventIterator eventIterator) {
    final int operationType = ((JCREventIterator) eventIterator).getOperationType();

    final JCRSessionWrapper session = ((JCREventIterator) eventIterator).getSession();
    final String userId = session.getUser() != null ? session.getUser().getName() : null;
    final String userRealm = session.getUser() != null ? session.getUser().getRealm() : null;
    final Locale locale = session.getLocale();

    final Map<String, AddedNodeFact> eventsMap = new HashMap<String, AddedNodeFact>();

    if (Boolean.TRUE.equals(inRules.get())) {
        return;//from w ww .j a va 2 s. c o m
    }

    if (ruleBase == null || SettingsBean.getInstance().isDevelopmentMode() && lastModified() > lastRead) {
        try {
            initRules();
        } catch (Exception e) {
            logger.error("Cannot compile rules", e);
        }
        if (ruleBase == null) {
            return;
        }
    }

    final List<Event> events = new ArrayList<Event>();
    while (eventIterator.hasNext()) {
        Event event = eventIterator.nextEvent();
        if (!isExternal(event)) {
            events.add(event);
        }
    }
    if (events.isEmpty()) {
        return;
    }

    try {
        JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(session.getUser(), workspace, locale,
                new JCRCallback<Object>() {

                    Map<String, String> copies = null;

                    public Object doInJCR(JCRSessionWrapper s) throws RepositoryException {
                        Iterator<Event> it = events.iterator();

                        final List<Object> list = new ArrayList<Object>();

                        String nodeFactOperationType = getNodeFactOperationType(operationType);
                        while (it.hasNext()) {
                            Event event = it.next();
                            String path = event.getPath();
                            try {
                                if (!path.startsWith("/jcr:system/")) {
                                    String eventUuid = event.getIdentifier();
                                    int type = event.getType();
                                    if (type == Event.NODE_ADDED) {
                                        JCRNodeWrapper n = eventUuid != null ? s.getNodeByIdentifier(eventUuid)
                                                : s.getNode(path);
                                        if (n.isNodeType("jmix:observable")
                                                && !n.isNodeType("jnt:translation")) {
                                            final String identifier = n.getIdentifier();
                                            AddedNodeFact rn = eventsMap.get(identifier);
                                            if (rn == null) {
                                                rn = getFact(n, session);
                                                rn.setOperationType(nodeFactOperationType);
                                                final JCRSiteNode resolveSite = n.getResolveSite();
                                                if (resolveSite != null) {
                                                    rn.setInstalledModules(
                                                            resolveSite.getAllInstalledModules());
                                                } else {
                                                    rn.setInstalledModules(new ArrayList<String>());
                                                }
                                                eventsMap.put(identifier, rn);
                                            }
                                            list.add(rn);
                                        }
                                    } else if (type == Event.PROPERTY_ADDED || type == Event.PROPERTY_CHANGED) {
                                        String propertyName = path.substring(path.lastIndexOf('/') + 1);
                                        if (!propertiesToIgnore.contains(propertyName)) {
                                            try {
                                                JCRPropertyWrapper p = null;
                                                try {
                                                    p = (JCRPropertyWrapper) s.getItem(path);
                                                } catch (PathNotFoundException e) {
                                                    // the node could be moved in between
                                                    try {
                                                        p = s.getNodeByIdentifier(eventUuid)
                                                                .getProperty(propertyName);
                                                    } catch (RepositoryException infe) {
                                                        throw e;
                                                    }
                                                }

                                                JCRNodeWrapper parent = p.getParent();
                                                if (parent.isNodeType("jnt:translation")) {
                                                    parent = parent.getParent();
                                                }
                                                if (parent.isNodeType(Constants.NT_RESOURCE)
                                                        || parent.isNodeType("jmix:observable")) {
                                                    AddedNodeFact rn;
                                                    if (parent.isNodeType(Constants.MIX_REFERENCEABLE)) {
                                                        final String identifier = parent.getIdentifier();
                                                        rn = eventsMap.get(identifier);
                                                        if (rn == null) {
                                                            rn = type == Event.PROPERTY_ADDED
                                                                    ? getFact(parent, session)
                                                                    : new AddedNodeFact(parent);
                                                            rn.setOperationType(nodeFactOperationType);
                                                            final JCRSiteNode resolveSite = parent
                                                                    .getResolveSite();
                                                            if (resolveSite != null) {
                                                                rn.setInstalledModules(
                                                                        resolveSite.getAllInstalledModules());
                                                            } else {
                                                                rn.setInstalledModules(new ArrayList<String>());
                                                            }
                                                            eventsMap.put(identifier, rn);
                                                        }
                                                    } else {
                                                        rn = new AddedNodeFact(parent);
                                                        rn.setOperationType(nodeFactOperationType);
                                                        final JCRSiteNode resolveSite = parent.getResolveSite();
                                                        if (resolveSite != null) {
                                                            rn.setInstalledModules(
                                                                    resolveSite.getAllInstalledModules());
                                                        } else {
                                                            rn.setInstalledModules(new ArrayList<String>());
                                                        }
                                                    }
                                                    list.add(new ChangedPropertyFact(rn, p));
                                                }
                                            } catch (PathNotFoundException pnfe) {
                                                if (JCRSessionFactory.getInstance().getProvider(path,
                                                        false) == null || logger.isDebugEnabled()) {
                                                    logger.error("Couldn't access path {}, ignoring it.", pnfe);
                                                }
                                            }
                                        } else if (propertyName.equals("j:published")) {
                                            JCRNodeWrapper n = eventUuid != null
                                                    ? s.getNodeByIdentifier(eventUuid)
                                                    : s.getNode(path);
                                            if (n.isNodeType("jmix:observable")
                                                    && !n.isNodeType("jnt:translation")) {
                                                final PublishedNodeFact e = new PublishedNodeFact(n);
                                                e.setOperationType(nodeFactOperationType);
                                                final JCRSiteNode resolveSite = n.getResolveSite();
                                                if (resolveSite != null) {
                                                    e.setInstalledModules(resolveSite.getAllInstalledModules());
                                                } else {
                                                    e.setInstalledModules(new ArrayList<String>());
                                                }
                                                list.add(e);
                                            }
                                        }
                                    } else if (type == Event.NODE_REMOVED) {
                                        String parentPath = null;
                                        try {
                                            parentPath = StringUtils.substringBeforeLast(path, "/");
                                            JCRNodeWrapper parent = s.getNode(parentPath);
                                            final String identifier = parent.getIdentifier();
                                            AddedNodeFact w = eventsMap.get(identifier);
                                            if (w == null) {
                                                w = new AddedNodeFact(parent);
                                                w.setOperationType(nodeFactOperationType);
                                                final JCRSiteNode resolveSite = parent.getResolveSite();
                                                if (resolveSite != null) {
                                                    w.setInstalledModules(resolveSite.getAllInstalledModules());
                                                } else {
                                                    w.setInstalledModules(new ArrayList<String>());
                                                }
                                                eventsMap.put(identifier, w);
                                            }

                                            final DeletedNodeFact e = new DeletedNodeFact(w, path);
                                            e.setIdentifier(eventUuid);
                                            e.setSession(s);
                                            e.setOperationType(nodeFactOperationType);
                                            e.setTypes(JCRObservationManager.getNodeTypesForDeletedNode(event));
                                            list.add(e);
                                        } catch (PathNotFoundException e) {
                                        }
                                    } else if (type == Event.PROPERTY_REMOVED) {
                                        int index = path.lastIndexOf('/');
                                        String nodePath = path.substring(0, index);
                                        String propertyName = path.substring(index + 1);
                                        if (!propertiesToIgnore.contains(propertyName)) {
                                            try {
                                                JCRNodeWrapper n = s.getNode(nodePath);
                                                String key = n.isNodeType(Constants.MIX_REFERENCEABLE)
                                                        ? n.getIdentifier()
                                                        : n.getPath();
                                                AddedNodeFact rn = eventsMap.get(key);
                                                if (rn == null) {
                                                    rn = new AddedNodeFact(n);
                                                    rn.setOperationType(nodeFactOperationType);
                                                    final JCRSiteNode resolveSite = n.getResolveSite();
                                                    if (resolveSite != null) {
                                                        rn.setInstalledModules(
                                                                resolveSite.getAllInstalledModules());
                                                    } else {
                                                        rn.setInstalledModules(new ArrayList<String>());
                                                    }
                                                    eventsMap.put(key, rn);
                                                }
                                                list.add(new DeletedPropertyFact(rn, propertyName));
                                            } catch (PathNotFoundException e) {
                                                // ignore if parent has also been deleted ?
                                            }
                                        }
                                    } else if (type == Event.NODE_MOVED) {
                                        JCRNodeWrapper n = eventUuid != null ? s.getNodeByIdentifier(eventUuid)
                                                : s.getNode(path);
                                        if (n.isNodeType("jmix:observable")
                                                && !n.isNodeType("jnt:translation")) {
                                            final MovedNodeFact e = new MovedNodeFact(n,
                                                    (String) event.getInfo().get("srcAbsPath"));
                                            e.setOperationType(nodeFactOperationType);
                                            final JCRSiteNode resolveSite = n.getResolveSite();
                                            if (resolveSite != null) {
                                                e.setInstalledModules(resolveSite.getAllInstalledModules());
                                            } else {
                                                e.setInstalledModules(new ArrayList<String>());
                                            }
                                            list.add(e);
                                        }
                                    }
                                }
                            } catch (PathNotFoundException pnfe) {
                                logger.debug(
                                        "Error when executing event. Unable to find node or property for path: "
                                                + path,
                                        pnfe);
                            } catch (ItemNotFoundException infe) {
                                logger.debug(
                                        "Error when executing event. Unable to find node or property for item: "
                                                + event.getIdentifier(),
                                        infe);
                            } catch (Exception e) {
                                logger.error("Error when executing event", e);
                            }
                        }
                        if (!list.isEmpty()) {
                            long time = System.currentTimeMillis();
                            if (logger.isDebugEnabled()) {
                                if (list.size() > 3) {
                                    logger.debug("Executing rules for " + list.subList(0, 3) + " ... and "
                                            + (list.size() - 3) + " other nodes");
                                } else {
                                    logger.debug("Executing rules for " + list);
                                }
                            }
                            final List<Updateable> delayedUpdates = new ArrayList<Updateable>();

                            Map<String, Object> globals = getGlobals(userId, userRealm, delayedUpdates);

                            try {
                                inRules.set(Boolean.TRUE);
                                list.add(new OperationTypeFact(nodeFactOperationType));
                                executeRules(list, globals);

                                if (list.size() > 3) {
                                    logger.info("Rules executed for " + workspace + " " + list.subList(0, 3)
                                            + " ... and " + (list.size() - 3) + " other nodes in "
                                            + (System.currentTimeMillis() - time) + "ms");
                                } else {
                                    logger.info("Rules executed for " + workspace + " " + list + " in "
                                            + (System.currentTimeMillis() - time) + "ms");
                                }

                                if (s.hasPendingChanges()) {
                                    s.save();
                                }
                            } finally {
                                inRules.set(null);
                            }

                            if (!delayedUpdates.isEmpty()) {
                                TimerTask t = new DelayedUpdatesTimerTask(userId, userRealm, delayedUpdates);
                                rulesTimer.schedule(t, UPDATE_DELAY_FOR_LOCKED_NODE);
                            }
                        }
                        return null;
                    }

                    @SuppressWarnings("unchecked")
                    private AddedNodeFact getFact(JCRNodeWrapper node, JCRSessionWrapper session)
                            throws RepositoryException {
                        if (copies == null) {
                            copies = session.getUuidMapping().isEmpty() ? Collections.<String, String>emptyMap()
                                    : MapUtils.invertMap(session.getUuidMapping());
                        }
                        String sourceUuid = !copies.isEmpty() ? copies.get(node.getIdentifier()) : null;
                        return sourceUuid != null
                                ? new CopiedNodeFact(node, sourceUuid,
                                        session.getUuidMapping().containsKey("top-" + sourceUuid))
                                : new AddedNodeFact(node);
                    }
                });
    } catch (Exception e) {
        logger.error("Error when executing event", e);
    }
}