Example usage for java.util Collections EMPTY_MAP

List of usage examples for java.util Collections EMPTY_MAP

Introduction

In this page you can find the example usage for java.util Collections EMPTY_MAP.

Prototype

Map EMPTY_MAP

To view the source code for java.util Collections EMPTY_MAP.

Click Source Link

Document

The empty map (immutable).

Usage

From source file:com.ikon.dao.HibernateUtil.java

/**
 * HQL to SQL translator//from   ww  w .  j  a v  a  2s  .c  o  m
 */
public static String toSql(String hql) {
    if (hql != null && hql.trim().length() > 0) {
        final QueryTranslatorFactory qtf = new ASTQueryTranslatorFactory();
        final SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory;
        final QueryTranslator translator = qtf.createQueryTranslator(hql, hql, Collections.EMPTY_MAP, sfi);
        translator.compile(Collections.EMPTY_MAP, false);
        return translator.getSQLString();
    }

    return null;
}

From source file:org.apache.nifi.processors.standard.EvaluateJsonPath.java

@Override
public void onTrigger(final ProcessContext processContext, final ProcessSession processSession)
        throws ProcessException {
    FlowFile flowFile = processSession.get();
    if (flowFile == null) {
        return;/*from  w  w w.ja  v  a2 s  .c om*/
    }

    final ComponentLog logger = getLogger();

    DocumentContext documentContext;
    try {
        documentContext = validateAndEstablishJsonContext(processSession, flowFile);
    } catch (InvalidJsonException e) {
        logger.error("FlowFile {} did not have valid JSON content.", new Object[] { flowFile });
        processSession.transfer(flowFile, REL_FAILURE);
        return;
    }

    Set<Map.Entry<String, JsonPath>> attributeJsonPathEntries = attributeToJsonPathEntrySetQueue.poll();
    if (attributeJsonPathEntries == null) {
        attributeJsonPathEntries = processContext.getProperties().entrySet().stream()
                .filter(e -> e.getKey().isDynamic())
                .collect(Collectors.toMap(e -> e.getKey().getName(), e -> JsonPath.compile(e.getValue())))
                .entrySet();
    }

    try {
        // We'll only be using this map if destinationIsAttribute == true
        final Map<String, String> jsonPathResults = destinationIsAttribute
                ? new HashMap<>(attributeJsonPathEntries.size())
                : Collections.EMPTY_MAP;

        for (final Map.Entry<String, JsonPath> attributeJsonPathEntry : attributeJsonPathEntries) {
            final String jsonPathAttrKey = attributeJsonPathEntry.getKey();
            final JsonPath jsonPathExp = attributeJsonPathEntry.getValue();

            Object result;
            try {
                Object potentialResult = documentContext.read(jsonPathExp);
                if (returnType.equals(RETURN_TYPE_SCALAR) && !isJsonScalar(potentialResult)) {
                    logger.error(
                            "Unable to return a scalar value for the expression {} for FlowFile {}. Evaluated value was {}. Transferring to {}.",
                            new Object[] { jsonPathExp.getPath(), flowFile.getId(), potentialResult.toString(),
                                    REL_FAILURE.getName() });
                    processSession.transfer(flowFile, REL_FAILURE);
                    return;
                }
                result = potentialResult;
            } catch (PathNotFoundException e) {
                if (pathNotFound.equals(PATH_NOT_FOUND_WARN)) {
                    logger.warn("FlowFile {} could not find path {} for attribute key {}.",
                            new Object[] { flowFile.getId(), jsonPathExp.getPath(), jsonPathAttrKey }, e);
                }

                if (destinationIsAttribute) {
                    jsonPathResults.put(jsonPathAttrKey, StringUtils.EMPTY);
                    continue;
                } else {
                    processSession.transfer(flowFile, REL_NO_MATCH);
                    return;
                }
            }

            final String resultRepresentation = getResultRepresentation(result, nullDefaultValue);
            if (destinationIsAttribute) {
                jsonPathResults.put(jsonPathAttrKey, resultRepresentation);
            } else {
                flowFile = processSession.write(flowFile, out -> {
                    try (OutputStream outputStream = new BufferedOutputStream(out)) {
                        outputStream.write(resultRepresentation.getBytes(StandardCharsets.UTF_8));
                    }
                });
                processSession.getProvenanceReporter().modifyContent(flowFile,
                        "Replaced content with result of expression " + jsonPathExp.getPath());
            }
        }

        // jsonPathResults map will be empty if this is false
        if (destinationIsAttribute) {
            flowFile = processSession.putAllAttributes(flowFile, jsonPathResults);
        }
        processSession.transfer(flowFile, REL_MATCH);
    } finally {
        attributeToJsonPathEntrySetQueue.offer(attributeJsonPathEntries);
    }
}

From source file:edu.internet2.middleware.psp.shibboleth.ChangeLogDataConnector.java

/**
 * Return attributes representing the subject with the given source id and subject id.
 * //from   ww w  .j  av a2 s .  c o  m
 * The subject is found via SubjectFinder.findByIdAndSource();
 * 
 * The subject name is returned via the 'subjectName' attribute. The subject description is returned via the
 * 'subjectDescription' attribute.
 * 
 * Subject attributes returned from subject.getAttributes() are named 'subject' + attribute name, for example,
 * 'subjectdisplayextension'.
 * 
 * @param sourceId the source id
 * @param subjectId the subject id
 * @return attributes representing the subject
 */
protected Map<String, BaseAttribute> buildSubjectAttributes(String sourceId, String subjectId) {

    // look up subject
    Subject subject = SubjectFinder.findByIdAndSource(subjectId, sourceId, false);
    if (subject == null) {
        return Collections.EMPTY_MAP;
    }

    Map<String, BaseAttribute> attributes = new LinkedHashMap<String, BaseAttribute>();

    String subjectName = subject.getName();
    if (!DatatypeHelper.isEmpty(subjectName)) {
        BasicAttribute<String> attribute = new BasicAttribute<String>();
        attribute.setId("subjectName");
        attribute.getValues().add(subjectName);
        attributes.put(attribute.getId(), attribute);
    }

    String subjectDescription = subject.getDescription();
    if (!DatatypeHelper.isEmpty(subjectDescription)) {
        BasicAttribute<String> attribute = new BasicAttribute<String>();
        attribute.setId("subjectDescription");
        attribute.getValues().add(subjectDescription);
        attributes.put(attribute.getId(), attribute);
    }

    Map<String, Set<String>> attributeMap = subject.getAttributes();
    if (attributeMap != null) {
        for (String attributeName : attributeMap.keySet()) {
            BasicAttribute<String> attribute = new BasicAttribute<String>();
            attribute.setId("subject" + attributeName);
            attribute.getValues().addAll(attributeMap.get(attributeName));
            attributes.put(attribute.getId(), attribute);
        }
    }

    return attributes;
}

From source file:eu.openanalytics.rsb.RestJobsITCase.java

@Test
@SuppressWarnings("unchecked")
public void submitMultipartValidZipJob() throws Exception {
    final String applicationName = newTestApplicationName();
    final Document resultDoc = doSubmitValidMultipartJob(applicationName,
            Collections.singletonList(new UploadedFile("r-job-sample.zip")), Collections.EMPTY_MAP);
    final String resultUri = getResultUri(resultDoc);
    ponderRetrieveAndValidateZipResult(resultUri);
}

From source file:org.apache.nifi.web.server.JettyServer.java

/**
 * Loads the WARs in the specified NAR working directories. A WAR file must
 * have a ".war" extension.//from w w  w .  j a  v  a 2  s . com
 *
 * @param narWorkingDirectories dirs
 */
private void loadWars(final Set<File> narWorkingDirectories) {

    // load WARs
    Map<File, File> warToNarWorkingDirectoryLookup = findWars(narWorkingDirectories);

    // locate each war being deployed
    File webUiWar = null;
    File webApiWar = null;
    File webErrorWar = null;
    File webDocsWar = null;
    File webContentViewerWar = null;
    List<File> otherWars = new ArrayList<>();
    for (File war : warToNarWorkingDirectoryLookup.keySet()) {
        if (war.getName().toLowerCase().startsWith("nifi-web-api")) {
            webApiWar = war;
        } else if (war.getName().toLowerCase().startsWith("nifi-web-error")) {
            webErrorWar = war;
        } else if (war.getName().toLowerCase().startsWith("nifi-web-docs")) {
            webDocsWar = war;
        } else if (war.getName().toLowerCase().startsWith("nifi-web-content-viewer")) {
            webContentViewerWar = war;
        } else if (war.getName().toLowerCase().startsWith("nifi-web")) {
            webUiWar = war;
        } else {
            otherWars.add(war);
        }
    }

    // ensure the required wars were found
    if (webUiWar == null) {
        throw new RuntimeException("Unable to load nifi-web WAR");
    } else if (webApiWar == null) {
        throw new RuntimeException("Unable to load nifi-web-api WAR");
    } else if (webDocsWar == null) {
        throw new RuntimeException("Unable to load nifi-web-docs WAR");
    } else if (webErrorWar == null) {
        throw new RuntimeException("Unable to load nifi-web-error WAR");
    } else if (webContentViewerWar == null) {
        throw new RuntimeException("Unable to load nifi-web-content-viewer WAR");
    }

    // handlers for each war and init params for the web api
    final HandlerCollection handlers = new HandlerCollection();
    final Map<String, String> mimeMappings = new HashMap<>();
    final ClassLoader frameworkClassLoader = getClass().getClassLoader();
    final ClassLoader jettyClassLoader = frameworkClassLoader.getParent();

    // deploy the other wars
    if (CollectionUtils.isNotEmpty(otherWars)) {
        // hold onto to the web contexts for all ui extensions
        componentUiExtensionWebContexts = new ArrayList<>();
        contentViewerWebContexts = new ArrayList<>();

        // ui extension organized by component type
        final Map<String, List<UiExtension>> componentUiExtensionsByType = new HashMap<>();
        for (File war : otherWars) {
            // identify all known extension types in the war
            final Map<UiExtensionType, List<String>> uiExtensionInWar = new HashMap<>();
            identifyUiExtensionsForComponents(uiExtensionInWar, war);

            // only include wars that are for custom processor ui's
            if (!uiExtensionInWar.isEmpty()) {
                // get the context path
                String warName = StringUtils.substringBeforeLast(war.getName(), ".");
                String warContextPath = String.format("/%s", warName);

                // attempt to locate the nar class loader for this war
                ClassLoader narClassLoaderForWar = NarClassLoaders.getInstance()
                        .getExtensionClassLoader(warToNarWorkingDirectoryLookup.get(war));

                // this should never be null
                if (narClassLoaderForWar == null) {
                    narClassLoaderForWar = jettyClassLoader;
                }

                // create the extension web app context
                WebAppContext extensionUiContext = loadWar(war, warContextPath, narClassLoaderForWar);

                // create the ui extensions
                for (final Map.Entry<UiExtensionType, List<String>> entry : uiExtensionInWar.entrySet()) {
                    final UiExtensionType extensionType = entry.getKey();
                    final List<String> types = entry.getValue();

                    if (UiExtensionType.ContentViewer.equals(extensionType)) {
                        // consider each content type identified
                        for (final String contentType : types) {
                            // map the content type to the context path
                            mimeMappings.put(contentType, warContextPath);
                        }

                        // this ui extension provides a content viewer
                        contentViewerWebContexts.add(extensionUiContext);
                    } else {
                        // consider each component type identified
                        for (final String componentType : types) {
                            logger.info(String.format("Loading UI extension [%s, %s] for %s", extensionType,
                                    warContextPath, types));

                            // record the extension definition
                            final UiExtension uiExtension = new UiExtension(extensionType, warContextPath);

                            // create if this is the first extension for this component type
                            List<UiExtension> componentUiExtensionsForType = componentUiExtensionsByType
                                    .get(componentType);
                            if (componentUiExtensionsForType == null) {
                                componentUiExtensionsForType = new ArrayList<>();
                                componentUiExtensionsByType.put(componentType, componentUiExtensionsForType);
                            }

                            // record this extension
                            componentUiExtensionsForType.add(uiExtension);
                        }

                        // this ui extension provides a component custom ui
                        componentUiExtensionWebContexts.add(extensionUiContext);
                    }
                }

                // include custom ui web context in the handlers
                handlers.addHandler(extensionUiContext);
            }

        }

        // record all ui extensions to give to the web api
        componentUiExtensions = new UiExtensionMapping(componentUiExtensionsByType);
    } else {
        componentUiExtensions = new UiExtensionMapping(Collections.EMPTY_MAP);
    }

    // load the web ui app
    handlers.addHandler(loadWar(webUiWar, "/nifi", frameworkClassLoader));

    // load the web api app
    webApiContext = loadWar(webApiWar, "/nifi-api", frameworkClassLoader);
    handlers.addHandler(webApiContext);

    // load the content viewer app
    webContentViewerContext = loadWar(webContentViewerWar, "/nifi-content-viewer", frameworkClassLoader);
    webContentViewerContext.getInitParams().putAll(mimeMappings);
    handlers.addHandler(webContentViewerContext);

    // create a web app for the docs
    final String docsContextPath = "/nifi-docs";

    // load the documentation war
    webDocsContext = loadWar(webDocsWar, docsContextPath, frameworkClassLoader);

    // overlay the actual documentation
    final ContextHandlerCollection documentationHandlers = new ContextHandlerCollection();
    documentationHandlers.addHandler(createDocsWebApp(docsContextPath));
    documentationHandlers.addHandler(webDocsContext);
    handlers.addHandler(documentationHandlers);

    // load the web error app
    handlers.addHandler(loadWar(webErrorWar, "/", frameworkClassLoader));

    // deploy the web apps
    server.setHandler(gzip(handlers));
}

From source file:org.fusesource.ide.foundation.ui.archetypes.ArchetypeHelper.java

public static Map<String, String> getArchetypeRequiredProperties(URL jarURL)
        throws IOException, XPathExpressionException, ParserConfigurationException, SAXException {
    ZipInputStream zis = new ZipInputStream(jarURL.openStream());
    try {/*w w w .j ava2  s. c o  m*/
        ZipEntry entry = null;
        while ((entry = zis.getNextEntry()) != null) {
            try {
                if (!entry.isDirectory() && "META-INF/maven/archetype-metadata.xml".equals(entry.getName())) {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    copy(zis, bos);
                    bos.flush();
                    return getArchetypeRequiredProperties(bos, true, true);
                }
            } finally {
                zis.closeEntry();
            }
        }
    } finally {
        zis.close();
    }
    return Collections.EMPTY_MAP;
}

From source file:it.units.malelab.ege.util.DUMapper.java

private static double[][][] buildSGEData(int generations, int depth, Problem problem)
        throws InterruptedException, ExecutionException {
    SGEMapper<String> m = new SGEMapper<>(depth, problem.getGrammar());
    StandardConfiguration<SGEGenotype<String>, String, NumericFitness> configuration = new StandardConfiguration<>(
            500, generations, new RandomInitializer<>(new SGEGenotypeFactory<>(m)),
            new Any<SGEGenotype<String>>(), m,
            new Utils.MapBuilder<GeneticOperator<SGEGenotype<String>>, Double>()
                    .put(new SGECrossover<String>(), 0.8d).put(new SGEMutation<>(0.01d, m), 0.2d).build(),
            new ComparableRanker<>(new IndividualComparator<SGEGenotype<String>, String, NumericFitness>(
                    IndividualComparator.Attribute.FITNESS)),
            new Tournament<Individual<SGEGenotype<String>, String, NumericFitness>>(3),
            new LastWorst<Individual<SGEGenotype<String>, String, NumericFitness>>(), 500, true, problem, false,
            -1, -1);//from w  w  w  .j  a va 2s .c  o m
    StandardEvolver evolver = new StandardEvolver(configuration, false);
    List<EvolverListener> listeners = new ArrayList<>();
    final EvolutionImageSaverListener evolutionImageSaverListener = new EvolutionImageSaverListener(
            Collections.EMPTY_MAP, null, EvolutionImageSaverListener.ImageType.DU);
    listeners.add(evolutionImageSaverListener);
    listeners.add(new CollectorGenerationLogger<>(Collections.EMPTY_MAP, System.out, true, 10, " ", " | ",
            new Population(), new NumericFirstBest(false, problem.getTestingFitnessComputer(), "%6.2f"),
            new Diversity(), new BestPrinter(problem.getPhenotypePrinter(), "%30.30s")));
    ExecutorService executorService = Executors.newCachedThreadPool();
    evolver.solve(executorService, new Random(1), listeners);
    return evolutionImageSaverListener.getLastEvolutionData();
}

From source file:ei.ne.ke.cassandra.cql3.EntitySpecificationUtils.java

/**
 *
 *
 * @param field//ww  w  . j ava 2s  .co  m
 * @param entity
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> ByteBuffer serializeAttribute(AttributeAccessor accessor, T entity) {
    Preconditions.checkNotNull(accessor);
    Preconditions.checkNotNull(entity);
    Serializer serializer = SerializerFactory.inferSerializer(accessor);
    Object value = accessor.get(entity);
    if (value == null) {
        /*
         * While the column value of a collection type column is null, the
         * column representation isn't necessarily the empty byte buffer. If
         * we have a null value for collection type on the Java side, we
         * must marshal the corresponding empty collection type to a
         * ByteBuffer representation to set the column value.
         */
        if (List.class.isAssignableFrom(accessor.getClazz())) {
            return serializer.toByteBuffer(Collections.EMPTY_LIST);
        } else if (Map.class.isAssignableFrom(accessor.getClazz())) {
            return serializer.toByteBuffer(Collections.EMPTY_MAP);
        } else if (Set.class.isAssignableFrom(accessor.getClazz())) {
            return serializer.toByteBuffer(Collections.EMPTY_SET);
        } else {
            return EMPTY_BYTE_BUFFER;
        }
    }
    ByteBuffer buf = serializer.toByteBuffer(value);
    return buf;
}

From source file:org.apache.jackrabbit.core.state.ChildNodeEntries.java

/**
 * Returns a shallow copy of this <code>ChildNodeEntries</code> instance;
 * the entries themselves are not cloned.
 *
 * @return a shallow copy of this instance.
 *///from  w  w w.  j  av  a 2  s.co m
protected Object clone() {
    try {
        ChildNodeEntries clone = (ChildNodeEntries) super.clone();
        if (nameMap != Collections.EMPTY_MAP) {
            clone.shared = true;
            shared = true;
        }
        return clone;
    } catch (CloneNotSupportedException e) {
        // never happens, this class is cloneable
        throw new InternalError();
    }
}

From source file:org.geoserver.wps.sextante.SextanteProcessFactory.java

public Map<Key, ?> getImplementationHints() {
    return Collections.EMPTY_MAP;
}