Example usage for java.util Collections emptyMap

List of usage examples for java.util Collections emptyMap

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public static final <K, V> Map<K, V> emptyMap() 

Source Link

Document

Returns an empty map (immutable).

Usage

From source file:gridool.dht.TcbLocalDirectory.java

@SuppressWarnings("unchecked")
public Map<String, List<GridNode>> prefixSearch(String key, Set<GridNode> includeValues) throws DbException {
    final long startTime = System.currentTimeMillis();

    final byte[] prefix = StringUtils.getBytes(key);
    final byte[] rightEdge = calculateRightEdgeValue(prefix);

    final List<byte[]> matchedKeys = tcb.range(prefix, true, rightEdge, false, -1);
    if (matchedKeys.isEmpty()) {
        return Collections.emptyMap();
    }//  w w  w .  j  a va  2s.  c  o m

    final Map<String, List<GridNode>> mapping = new HashMap<String, List<GridNode>>(matchedKeys.size());
    int count = 0;
    for (byte[] k : matchedKeys) {
        final String path = StringUtils.toString(k);
        final List<byte[]> values = tcb.getlist(k);
        for (byte[] v : values) {
            count++;
            final GridNodeInfo node = GridNodeInfo.fromBytes(v);
            if (includeValues.contains(node)) {
                List<GridNode> nodes = mapping.get(path);
                if (nodes == null) {
                    nodes = new ArrayList<GridNode>(32);
                    mapping.put(path, nodes);
                }
                if (!nodes.contains(node)) {
                    nodes.add(node);
                }
            }
        }
    }

    if (LOG.isInfoEnabled()) {
        long elapsedTime = System.currentTimeMillis() - startTime;
        LOG.info("Elapsed time for TcbLocalDirectory#prefixSearch with a '" + key + "' [ " + count
                + " items found. ] is " + StopWatch.elapsedTime(elapsedTime));
    }

    return mapping;
}

From source file:guru.qas.martini.jmeter.config.DefaultApplicationContextBuilder.java

protected Properties getProperties(Arguments arguments) {
    Properties properties = new Properties();
    Map<String, String> asMap = null == arguments ? Collections.emptyMap() : arguments.getArgumentsAsMap();
    properties.putAll(asMap);/*from w  w w. j a  v  a 2s  .co  m*/
    return properties;
}

From source file:com.mweagle.tereus.commands.CreateCommand.java

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "DM_EXIT", "OBL_UNSATISFIED_OBLIGATION" })
@SuppressWarnings("unchecked")
@Override/*from   w ww .  ja  v a2s.  c o m*/
public void run() {
    int exitCode = 0;
    try {
        final String argumentJSON = (null != this.jsonParamAndTagsPath)
                ? new String(Files.readAllBytes(Paths.get(this.jsonParamAndTagsPath)), Charsets.UTF_8)
                : null;

        Map<String, Object> jsonJavaRootObject = (null != argumentJSON)
                ? new Gson().fromJson(argumentJSON, Map.class)
                : Collections.emptyMap();
        Map<String, Object> parameters = (Map<String, Object>) jsonJavaRootObject
                .getOrDefault(CONSTANTS.ARGUMENT_JSON_KEYNAMES.PARAMETERS, new HashMap<>());
        final String jsonS3BucketName = ((String) parameters
                .getOrDefault(CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME, "")).trim();
        final String cliS3BucketName = (null == this.s3BucketName) ? "" : this.s3BucketName.trim();

        if (!jsonS3BucketName.isEmpty() && !cliS3BucketName.isEmpty()) {
            final String msg = String.format("S3 bucketname defined in both %s and via command line argument",
                    this.jsonParamAndTagsPath);
            throw new IllegalArgumentException(msg);
        } else if (!cliS3BucketName.isEmpty()) {
            parameters.put(CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME, cliS3BucketName);
        }

        Map<String, Object> tags = (Map<String, Object>) jsonJavaRootObject
                .getOrDefault(CONSTANTS.ARGUMENT_JSON_KEYNAMES.TAGS, Collections.emptyMap());

        TereusInput tereusInput = new TereusInput(this.stackTemplatePath, this.region, parameters, tags,
                this.dryRun);

        Optional<OutputStream> osSink = Optional.empty();
        try {
            if (null != this.outputFilePath) {
                final Path outputPath = Paths.get(this.outputFilePath);
                osSink = Optional.of(new FileOutputStream(outputPath.toFile()));
            }
            this.create(tereusInput, osSink);
        } catch (Exception ex) {
            LogManager.getLogger().error(ex.getCause());
            exitCode = 2;
        } finally {
            if (osSink.isPresent()) {
                try {
                    osSink.get().close();
                } catch (Exception e) {
                    // NOP
                }
            }
        }
    } catch (Exception ex) {
        LogManager.getLogger().error(ex);
        Help.help(this.helpOption.commandMetadata);
        exitCode = 1;
    }
    System.exit(exitCode);
}

From source file:com.ikanow.aleph2.analytics.hadoop.assets.SampleReduceEnrichmentModule.java

@Override
public void onStageInitialize(IEnrichmentModuleContext context, DataBucketBean bucket,
        EnrichmentControlMetadataBean control, Tuple2<ProcessingStage, ProcessingStage> previous_next,
        Optional<List<String>> next_grouping_fields) {

    _context.set(context);/*from  ww  w  . j a  va 2  s. com*/

    // Infer what the stage is from the grouping info

    // input -> ... -> chain (map) -> grouping -> chain (combine) -> grouping -> chain (reduce) -> ...
    // input -> ... -> chain (map) -> grouping -> chain (reduce) -> ...

    _stage.set(Patterns.match(previous_next).<Stage>andReturn()
            .when(t2 -> t2.equals(Tuples._2T(ProcessingStage.grouping, ProcessingStage.grouping)),
                    __ -> Stage.combine)
            .when(t2 -> ProcessingStage.grouping == t2._1(), // (grouping,*)
                    __ -> Stage.reduce)
            .when(t2 -> ProcessingStage.grouping == t2._2(), // (*.grouping)
                    __ -> Stage.map)
            .otherwiseAssert());

    _logger.info("STAGE = " + _stage + "(from = " + previous_next);

    final ConfigBean config = BeanTemplateUtils
            .from(Optional.ofNullable(control.config()).orElse(Collections.emptyMap()), ConfigBean.class).get();

    next_grouping_fields.filter(ngf -> !ngf.isEmpty()) //if empty then in auto mode
            .map(Optional::of).orElseGet(() -> Optional.ofNullable(config.key_field_override))
            .ifPresent(kf -> _key_fields.set(kf));

    _logger.info("NEXT GROUPING FIELDS = " + _key_fields + "( from = " + next_grouping_fields);

}

From source file:com.ikanow.aleph2.v1.document_db.utils.V1DocumentDbHadoopUtils.java

/** 
 * @param input_config - the input settings
 * @return/*from   ww  w.  j  a  va 2  s.  co  m*/
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static IAnalyticsAccessContext<InputFormat> getInputFormat(final String user_id,
        final AnalyticThreadJobBean.AnalyticThreadJobInputBean job_input,
        final Optional<ISecurityService> maybe_security, final V1DocDbConfigBean config) {
    //TODO (ALEPH-20): need to perform security in here

    return new IAnalyticsAccessContext<InputFormat>() {
        private LinkedHashMap<String, Object> _mutable_output = null;

        @Override
        public String describe() {
            //(return the entire thing)
            return ErrorUtils.get("service_name={0} options={1}",
                    this.getAccessService().right().value().getSimpleName(),
                    this.getAccessConfig().get().entrySet().stream()
                            .filter(kv -> !DESCRIBE_FILTER.contains(kv.getKey()))
                            .collect(Collectors.toMap(kv -> kv.getKey(), kv -> kv.getValue())));
        }

        /* (non-Javadoc)
         * @see com.ikanow.aleph2.data_model.interfaces.data_analytics.IAnalyticsAccessContext#getAccessService()
         */
        @Override
        public Either<InputFormat, Class<InputFormat>> getAccessService() {
            return Either.right((Class<InputFormat>) (Class<?>) Aleph2V1InputFormat.class);
        }

        /* (non-Javadoc)
         * @see com.ikanow.aleph2.data_model.interfaces.data_analytics.IAnalyticsAccessContext#getAccessConfig()
         */
        @Override
        public Optional<Map<String, Object>> getAccessConfig() {
            if (null != _mutable_output) {
                return Optional.of(_mutable_output);
            }
            _mutable_output = new LinkedHashMap<>();

            // Parse various inputs:

            final List<String> communities = Arrays
                    .stream(job_input.resource_name_or_id()
                            .substring(BucketUtils.EXTERNAL_BUCKET_PREFIX.length()).split("_"))
                    .collect(Collectors.toList());

            // Validate communities:
            maybe_security.ifPresent(sec -> {
                communities.stream().filter(cid -> !sec.isUserPermitted(user_id, Tuples._2T("community", cid),
                        Optional.of(ISecurityService.ACTION_READ))).findAny().ifPresent(cid -> {
                            throw new RuntimeException(ErrorUtils
                                    .get(V1DocumentDbErrorUtils.V1_DOCUMENT_USER_PERMISSIONS, user_id, cid));
                        });
            });

            final String query = _mapper
                    .convertValue(Optional.ofNullable(job_input.filter()).orElse(Collections.emptyMap()),
                            JsonNode.class)
                    .toString();

            final Tuple4<String, Tuple2<Integer, Integer>, BasicDBObject, DBObject> horrible_object = LegacyV1HadoopUtils
                    .parseQueryObject(query, communities);

            final String db_server = config.mongodb_connection();

            // Here's all the fields to fill in

            // 1) Generic MongoDB fields:
            //name of job shown in jobtracker --><name>mongo.job.name</name><value>title
            //run the job verbosely ? --><name>mongo.job.verbose</name><value>true
            //Run the job in the foreground and wait for response, or background it? --><name>mongo.job.background</name><value>false
            //If you are reading from mongo, the URI --><name>mongo.input.uri</name><value>mongodb://"+dbserver+"/"+input
            //The number of documents to limit to for read [OPTIONAL] --><name>mongo.input.limit</name><value>" + nLimit
            //The query, in JSON, to execute [OPTIONAL] --><name>mongo.input.query</name><value>" + StringEscapeUtils.escapeXml(query)
            //The fields, in JSON, to read [OPTIONAL] --><name>mongo.input.fields</name><value>"+( (fields==null) ? ("") : fields )
            //InputFormat Class --><name>mongo.job.input.format</name><value>com.ikanow.infinit.e.data_model.custom.InfiniteMongoInputFormat

            _mutable_output.put("mongo.job.name",
                    Optional.ofNullable(job_input.data_service()).orElse("unknown") + ":"
                            + Optional.ofNullable(job_input.resource_name_or_id()).orElse("unknown")); // (i think this is ignored in fact)            
            _mutable_output.put("mongo.job.verbose", "true");
            _mutable_output.put("mongo.job.background", "false");
            _mutable_output.put("mongo.input.uri", "mongodb://" + db_server + "/doc_metadata.metadata");
            _mutable_output.put("mongo.input.query", horrible_object._1());
            _mutable_output.put("mongo.input.fields",
                    Optional.ofNullable(horrible_object._4()).map(o -> o.toString()).orElse(""));
            _mutable_output.put("mongo.input.limit", Optional.ofNullable(job_input.config())
                    .map(cfg -> cfg.test_record_limit_request()).map(o -> o.toString()).orElse("0"));

            // 2) Basic Infinit.e/MongoDB fields:
            //Maximum number of splits [optional] --><name>max.splits</name><value>"+nSplits
            //Maximum number of docs per split [optional] --><name>max.docs.per.split</name><value>"+nDocsPerSplit
            _mutable_output.put("max.splits", horrible_object._2()._1().toString());
            _mutable_output.put("max.docs.per.split", horrible_object._2()._2().toString());

            // 3) Advanced Infinit.e/MongoDB fields:            
            //Infinit.e src tags filter [optional] --><name>infinit.e.source.tags.filter</name><value>"+srcTags.toString()
            if (null != horrible_object._3()) {
                _mutable_output.put("infinit.e.source.tags.filter", horrible_object._3().toString());
            }
            return Optional.of(Collections.unmodifiableMap(_mutable_output));
        }
    };
}

From source file:com.sinosoft.one.mvc.web.portal.impl.WindowImpl.java

public Map<String, Object> getAttributes() {
    if (privateAttributes == null) {
        return Collections.emptyMap();
    } else {/* w w w. jav a  2 s  .  c o m*/
        return Collections.unmodifiableMap(privateAttributes);
    }
}

From source file:alfio.controller.api.admin.AdminWaitingQueueApiController.java

@RequestMapping(value = "/status", method = RequestMethod.PUT)
public Map<String, Boolean> setStatusForEvent(@PathVariable("eventName") String eventName,
        @RequestBody SetStatusForm form, Principal principal) {
    return optionally(() -> eventManager.getSingleEvent(eventName, principal.getName())).map(event -> {
        configurationManager.saveAllEventConfiguration(event.getId(), event.getOrganizationId(),
                singletonList(new ConfigurationModification(null,
                        ConfigurationKeys.STOP_WAITING_QUEUE_SUBSCRIPTIONS.name(),
                        String.valueOf(form.status))),
                principal.getName());//from  www  .  j a  v  a 2 s  .com
        return loadStatus(event);
    }).orElse(Collections.emptyMap());
}

From source file:com.adobe.acs.commons.wcm.impl.DynamicClassicUiClientLibraryServletTest.java

@Test
public void testDefault() throws Exception {
    servlet.activate(Collections.emptyMap());

    servlet.doGet(request, response);/*from w  ww  .  ja  v a  2  s  .c o m*/
    JSONAssert.assertEquals(
            "{'js':['/etc/clientlibs/limit.js','/etc/clientlibs/placeholder.js'], 'css':['/etc/clientlibs/limit.css','/etc/clientlibs/placeholder.css']}",
            writer.toString(), false);
}

From source file:edu.umich.flowfence.common.TaintSet.java

private TaintSet(Map<? extends ComponentName, ? extends Float> taintMap) {
    if (taintMap == null || taintMap.isEmpty()) {
        taints = Collections.emptyMap();
    } else {/*w ww . j a  v a 2 s. c o  m*/
        taints = Collections.unmodifiableMap(taintMap);
    }
}

From source file:com.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java

@Override
public JsonObject performIO_Action(String url, String method, String[] headers, JsonObject payload) {
    return process(url, Collections.emptyMap(), method, headers, payload);
}