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:cop.maven.plugins.MavenUtilsTest.java

@Test
public void shouldReturnEmptyWhenArrayNode() {
    assertThat(MavenUtils.readMap(createArray("name", "param", "one", "two", "three")))
            .isSameAs(Collections.emptyMap());
}

From source file:org.elasticsearch.http.DeprecationHttpIT.java

/**
 * Attempts to do a scatter/gather request that expects unique responses per sub-request.
 *//*w  w  w  .  j a v  a2s  .c om*/
@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/19222")
public void testUniqueDeprecationResponsesMergedTogether() throws IOException {
    final String[] indices = new String[randomIntBetween(2, 5)];

    // add at least one document for each index
    for (int i = 0; i < indices.length; ++i) {
        indices[i] = "test" + i;

        // create indices with a single shard to reduce noise; the query only deprecates uniquely by index anyway
        assertTrue(prepareCreate(indices[i]).setSettings(Settings.builder().put("number_of_shards", 1)).get()
                .isAcknowledged());

        int randomDocCount = randomIntBetween(1, 2);

        for (int j = 0; j < randomDocCount; ++j) {
            index(indices[i], "type", Integer.toString(j), "{\"field\":" + j + "}");
        }
    }

    refresh(indices);

    final String commaSeparatedIndices = Stream.of(indices).collect(Collectors.joining(","));

    final String body = "{\"query\":{\"bool\":{\"filter\":[{\"" + TestDeprecatedQueryBuilder.NAME
            + "\":{}}]}}}";

    // trigger all index deprecations
    Response response = getRestClient().performRequest("GET", "/" + commaSeparatedIndices + "/_search",
            Collections.emptyMap(), new StringEntity(body, ContentType.APPLICATION_JSON));
    assertThat(response.getStatusLine().getStatusCode(), equalTo(OK.getStatus()));

    final List<String> deprecatedWarnings = getWarningHeaders(response.getHeaders());
    final List<Matcher<String>> headerMatchers = new ArrayList<>(indices.length);

    for (String index : indices) {
        headerMatchers.add(containsString(LoggerMessageFormat.format("[{}] index", (Object) index)));
    }

    assertThat(deprecatedWarnings, hasSize(headerMatchers.size()));
    for (Matcher<String> headerMatcher : headerMatchers) {
        assertThat(deprecatedWarnings, hasItem(headerMatcher));
    }
}

From source file:org.kurento.tutorial.helloworld.HelloWorldRecHandler.java

private void start(final WebSocketSession session, JsonObject jsonMessage) {
    try {//from w  ww .  ja  va  2  s . c om
        // 0. Repository logic
        RepositoryItemRecorder repoItem = null;
        if (repositoryClient != null) {
            try {
                Map<String, String> metadata = Collections.emptyMap();
                repoItem = repositoryClient.createRepositoryItem(metadata);
            } catch (Exception e) {
                log.warn("Unable to create kurento repository items", e);
            }
        } else {
            String now = df.format(new Date());
            String filePath = HelloWorldRecApp.REPOSITORY_SERVER_URI + now + RECORDING_EXT;
            repoItem = new RepositoryItemRecorder();
            repoItem.setId(now);
            repoItem.setUrl(filePath);
        }
        log.info("Media will be recorded {}by KMS: id={} , url={}",
                (repositoryClient == null ? "locally " : ""), repoItem.getId(), repoItem.getUrl());

        // 1. Media logic (webRtcEndpoint in loopback)
        MediaPipeline pipeline = kurento.createMediaPipeline();
        WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
        webRtcEndpoint.connect(webRtcEndpoint);
        RecorderEndpoint recorder = new RecorderEndpoint.Builder(pipeline, repoItem.getUrl())
                .withMediaProfile(MediaProfileSpecType.WEBM).build();
        webRtcEndpoint.connect(recorder);

        // 2. Store user session
        UserSession user = new UserSession(session);
        user.setMediaPipeline(pipeline);
        user.setWebRtcEndpoint(webRtcEndpoint);
        user.setRepoItem(repoItem);
        registry.register(user);

        // 3. SDP negotiation
        String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
        String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);

        // 4. Gather ICE candidates
        webRtcEndpoint.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

            @Override
            public void onEvent(IceCandidateFoundEvent event) {
                JsonObject response = new JsonObject();
                response.addProperty("id", "iceCandidate");
                response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
                try {
                    synchronized (session) {
                        session.sendMessage(new TextMessage(response.toString()));
                    }
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        });

        JsonObject response = new JsonObject();
        response.addProperty("id", "startResponse");
        response.addProperty("sdpAnswer", sdpAnswer);

        synchronized (user) {
            session.sendMessage(new TextMessage(response.toString()));
        }

        webRtcEndpoint.gatherCandidates();

        recorder.record();
    } catch (Throwable t) {
        log.error("Start error", t);
        sendError(session, t.getMessage());
    }
}

From source file:com.smartitengineering.cms.api.impl.type.ContentTypeImpl.java

@Override
public Map<String, ContentStatus> getStatuses() {
    final Map<String, ContentStatus> statusMap = new LinkedHashMap<String, ContentStatus>();
    if (contentStatus.isEmpty() && getParent() != null) {
        ContentType parentContentType = getParent().getContentType();
        if (parentContentType != null) {
            return parentContentType.getStatuses();
        } else {/* w  ww.j a va2s  .  c om*/
            return Collections.emptyMap();
        }
    } else if (!contentStatus.isEmpty()) {
        for (ContentStatus status : contentStatus) {
            statusMap.put(status.getName(), status);
        }
        return Collections.unmodifiableMap(statusMap);
    } else {
        final ContentStatus status = new ContentStatus() {

            public int getId() {
                return 1;
            }

            public ContentTypeId getContentType() {
                return getContentTypeID();
            }

            public String getName() {
                return "default";
            }
        };
        statusMap.put(status.getName(), status);
        return Collections.unmodifiableMap(statusMap);
    }
}

From source file:org.callimachusproject.rewrite.RewriteAdvice.java

private Map<String, String> getVariables(Object[] parameters, String uri, FluidBuilder fb)
        throws IOException, FluidException {
    if (bindingNames == null || bindingNames.length == 0)
        return Collections.emptyMap();
    Map<String, String> map = new HashMap<String, String>(bindingNames.length);
    for (int i = 0; i < bindingNames.length; i++) {
        String key = bindingNames[i];
        if (key != null) {
            FluidType type = bindingTypes[i];
            Object param = parameters[i];
            if (param != null) {
                map.put(key, asString(param, type, uri, fb));
            }//from w  w w.ja v  a  2s  .c  o m
        }
    }
    return map;
}

From source file:com.adobe.acs.commons.hc.impl.SMTPMailServiceHealthCheck.java

@Override
@SuppressWarnings("squid:S1141")
public Result execute() {
    final FormattingResultLog resultLog = new FormattingResultLog();

    if (messageGatewayService == null) {
        resultLog.critical("MessageGatewayService OSGi service could not be found.");
        resultLog.info(//www .  j  ava 2s.  c o m
                "Verify the Default Mail Service is active: http://<host>:<port>/system/console/components/com.day.cq.mailer.impl.CqMailingService");
    } else {
        final MessageGateway<SimpleEmail> messageGateway = messageGatewayService.getGateway(SimpleEmail.class);
        if (messageGateway == null) {
            resultLog.critical("The AEM Default Mail Service is INACTIVE, thus e-mails cannot be sent.");
            resultLog.info(
                    "Verify the Default Mail Service is active and configured: http://<host>:<port>/system/console/components/com.day.cq.mailer.DefaultMailService");
            log.warn("Could not retrieve a SimpleEmail Message Gateway");

        } else {
            try {
                List<InternetAddress> emailAddresses = new ArrayList<InternetAddress>();
                emailAddresses.add(new InternetAddress(this.toEmail));
                MailTemplate mailTemplate = new MailTemplate(IOUtils.toInputStream(MAIL_TEMPLATE),
                        CharEncoding.UTF_8);
                SimpleEmail email = mailTemplate.getEmail(StrLookup.mapLookup(Collections.emptyMap()),
                        SimpleEmail.class);

                email.setSubject("AEM E-mail Service Health Check");
                email.setTo(emailAddresses);

                email.setSocketConnectionTimeout(TIMEOUT);
                email.setSocketTimeout(TIMEOUT);
                try {
                    messageGateway.send(email);
                    resultLog.info(
                            "The E-mail Service appears to be working properly. Verify the health check e-mail was sent to [ {} ]",
                            this.toEmail);
                } catch (Exception e) {
                    resultLog.critical(
                            "Failed sending e-mail. Unable to send a test toEmail via the configured E-mail server: "
                                    + e.getMessage(),
                            e);
                    log.warn("Failed to send E-mail for E-mail Service health check", e);
                }

                logMailServiceConfig(resultLog, email);
            } catch (Exception e) {
                resultLog.healthCheckError(
                        "Sling Health check could not formulate a test toEmail: " + e.getMessage(), e);
                log.error("Unable to execute E-mail health check", e);
            }
        }
    }

    return new Result(resultLog);
}

From source file:eu.europa.ec.fisheries.uvms.rules.service.bean.FactRuleEvaluator.java

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
private Map<String, String> generateExternalRulesFromTemplate(List<ExternalRuleType> externalRules) {
    if (CollectionUtils.isEmpty(externalRules)) {
        return Collections.emptyMap();
    }/*from   w w  w. ja  v  a  2  s.c o m*/
    Map<String, String> drlsAndBrId = new HashMap<>();
    for (ExternalRuleType extRuleType : externalRules) {
        String drl = extRuleType.getDrl();
        log.debug("DRL for BR Id {} : {} ", extRuleType.getBrId(), drl);
        drlsAndBrId.put(drl, extRuleType.getBrId());
    }
    return drlsAndBrId;
}

From source file:fr.pilato.elasticsearch.crawler.fs.client.ElasticsearchClient.java

public BulkResponse bulk(BulkRequest bulkRequest) throws Exception {
    StringBuffer sbf = new StringBuffer();
    for (SingleBulkRequest request : bulkRequest.getRequests()) {
        sbf.append("{");
        String header = JsonUtil.serialize(request);
        if (request instanceof DeleteRequest) {
            sbf.append("\"delete\":").append(header).append("}\n");
        }/*from  w w  w. j a v  a 2 s. c  o  m*/
        if (request instanceof IndexRequest) {
            sbf.append("\"index\":").append(header).append("}\n");
            // Index Request: header line + body
            sbf.append(((IndexRequest) request).content().replaceAll("\n", "")).append("\n");
        }
    }

    logger.trace("going to send a bulk");
    logger.trace("{}", sbf);

    StringEntity entity = new StringEntity(sbf.toString(), Charset.defaultCharset());
    Response restResponse = client.performRequest("POST", "/_bulk", Collections.emptyMap(), entity);
    BulkResponse response = JsonUtil.deserialize(restResponse, BulkResponse.class);
    logger.debug("bulk response: {}", response);
    return response;
}

From source file:com.swtxml.tinydom.TinyDomSaxHandler.java

private Map<INamespaceDefinition, Map<IAttributeDefinition, String>> processAttributes(
        INamespaceDefinition tagNamespace, ITagDefinition tagDefinition, Attributes attributes) {

    Map<INamespaceDefinition, Map<IAttributeDefinition, String>> attributeNsMap = new HashMap<INamespaceDefinition, Map<IAttributeDefinition, String>>();
    for (int i = 0; i < attributes.getLength(); i++) {
        String uri = attributes.getURI(i);
        INamespaceDefinition attributeNamespace = !StringUtils.isEmpty(uri) ? getNamespace(uri) : tagNamespace;
        Map<IAttributeDefinition, String> attributeMap = attributeNsMap.get(attributeNamespace);
        if (attributeMap == null) {
            attributeMap = new HashMap<IAttributeDefinition, String>();
            attributeNsMap.put(attributeNamespace, attributeMap);
        }//  w ww . ja  v  a  2 s .c o  m
        String name = attributes.getLocalName(i);
        String value = attributes.getValue(i);
        IAttributeDefinition attributeDefinition;
        if (attributeNamespace.equals(tagNamespace)) {
            attributeDefinition = tagDefinition.getAttribute(name);
        } else {
            attributeDefinition = attributeNamespace.getForeignAttribute(name);
            if (attributeDefinition instanceof ITagScope
                    && !((ITagScope) attributeDefinition).isAllowedIn(tagDefinition)) {
                throw new ParseException("Attribute " + attributes.getQName(i) + " is not allowed for tag \""
                        + tagDefinition.getName() + "\"");
            }
        }

        if (attributeDefinition == null) {
            throw new ParseException("Unknown attribute \"" + attributes.getQName(i) + "\" for tag \""
                    + tagDefinition.getName() + "\" (available are: "
                    + CollectionUtils.sortedToString(tagDefinition.getAttributeNames()) + ")");
        }
        attributeMap.put(attributeDefinition, value);

    }
    if (attributeNsMap.isEmpty()) {
        return Collections.emptyMap();
    }
    return attributeNsMap;
}

From source file:org.elasticsearch.smoketest.MonitoringWithWatcherRestIT.java

private String createMonitoringWatch() throws Exception {
    String clusterUUID = getClusterUUID();
    String watchId = clusterUUID + "_kibana_version_mismatch";
    String sampleWatch = WatchSourceBuilders.watchBuilder()
            .trigger(TriggerBuilders/*from   ww w .ja  v  a  2s.co  m*/
                    .schedule(new IntervalSchedule(new IntervalSchedule.Interval(1000, MINUTES))))
            .input(simpleInput()).addAction("logme", ActionBuilders.loggingAction("foo"))
            .buildAsBytes(XContentType.JSON).utf8ToString();
    client().performRequest("PUT", "_xpack/watcher/watch/" + watchId, Collections.emptyMap(),
            new StringEntity(sampleWatch, ContentType.APPLICATION_JSON));
    return watchId;
}