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:edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailMessage.java

public void setBodyMap(Map<String, Object> body) {
    if (body == null) {
        this.bodyMap = Collections.emptyMap();
    } else {/*w w w .  j a  va2s.  co m*/
        this.bodyMap = new HashMap<String, Object>(body);
    }
}

From source file:org.vas.test.rest.RestImpl.java

@Override
public <T> Response<T> put(String uri, Class<T> klass, Object... args) {
    return put(uri, Collections.emptyMap(), klass, args);
}

From source file:com.oplay.nohelper.volley.toolbox.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {

        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {//from w w  w  .  j  a v  a  2s .c om
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());

            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                Cache.Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true,
                            SystemClock.elapsedRealtime() - requestStart);
                }

                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true,
                        SystemClock.elapsedRealtime() - requestStart);
            }

            // Handle moved resources
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                String newUrl = responseHeaders.get("Location");
                request.setRedirectUrl(newUrl);
            }

            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }

            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);

            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                    SystemClock.elapsedRealtime() - requestStart);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (NetworkError e) {
            VolleyLog.e("%s", "?response");
            continue;
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(),
                        request.getUrl());
            } else {
                VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            }
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                        SystemClock.elapsedRealtime() - requestStart);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    attemptRetryOnException("redirect", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}

From source file:io.lavagna.service.CardDataRepository.java

public Map<Integer, String> findDataByIds(Collection<Integer> ids) {
    if (ids.isEmpty()) {
        return Collections.emptyMap();
    }/*from   w  w  w.j  a va  2 s  .co m*/
    Map<Integer, String> res = new HashMap<>();
    for (CardIdAndContent c : queries.findDataByIds(ids)) {
        res.put(c.getId(), c.getContent());
    }
    return res;
}

From source file:com.yahoo.bullet.result.MetadataTest.java

@Test
public void testConceptKeyExtractionWithMetadataNotEnabled() {
    Map<String, Object> configuration = new HashMap<>();
    configuration.put(BulletConfig.RESULT_METADATA_METRICS,
            asMetadataEntries(Pair.of("Estimated Result", "foo")));

    Set<Concept> concepts = new HashSet<>(singletonList(Concept.ESTIMATED_RESULT));

    Assert.assertEquals(Metadata.getConceptNames(configuration, concepts), Collections.emptyMap());
}

From source file:com.hortonworks.streamline.streams.runtime.storm.bolt.notification.NotificationBolt.java

@Override
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
    if (!stormConf.containsKey(CATALOG_ROOT_URL)) {
        throw new IllegalArgumentException("conf must contain " + CATALOG_ROOT_URL);
    }//from   ww  w.  j  a va  2  s.  c o m

    Map<String, Object> notificationConf = null;
    if (stormConf.get(NOTIFICATION_SERVICE_CONFIG_KEY) != null) {
        notificationConf = (Map<String, Object>) stormConf.get(NOTIFICATION_SERVICE_CONFIG_KEY);
    } else {
        notificationConf = Collections.emptyMap();
    }

    NotificationStore notificationStore = null;
    try {
        if (!StringUtils.isEmpty(notificationStoreClazz)) {
            Class<?> clazz = Class.forName(notificationStoreClazz);
            notificationStore = (NotificationStore) clazz.newInstance();
            Map<String, Object> config = (Map<String, Object>) stormConf.get(NOTIFICATION_STORE_CONFIG_KEY);
            if (config == null) {
                config = Collections.emptyMap();
            }
            notificationStore.init(config);
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
        throw new RuntimeException(ex);
    }

    notificationService = new NotificationServiceImpl(notificationConf, notificationStore);

    String jarPath = "";
    if (stormConf.containsKey(LOCAL_NOTIFIER_JAR_PATH)) {
        jarPath = String.format("%s%s%s", stormConf.get(LOCAL_NOTIFIER_JAR_PATH).toString(), File.separator,
                notificationSink.getNotifierJarFileName());
    }

    Properties props = new Properties();
    props.putAll(convertMapValuesToString(notificationSink.getNotifierProperties()));
    NotifierConfig notifierConfig = new NotifierConfigImpl(props,
            convertMapValuesToString(notificationSink.getNotifierFieldValues()),
            notificationSink.getNotifierClassName(), jarPath);

    notificationContext = new BoltNotificationContext(collector, notifierConfig);
    notificationService.register(notificationSink.getNotifierName(), notificationContext);
}

From source file:mondrian.rolap.RolapMemberBase.java

/**
 * Creates a RolapMemberBase./*from   ww w.  j av a 2 s.co m*/
 *
 * @param parentMember Parent member
 * @param level Level this member belongs to
 * @param key Key to this member in the underlying RDBMS
 * @param name Name of this member
 * @param memberType Type of member
 */
protected RolapMemberBase(RolapMember parentMember, RolapLevel level, Object key, String name,
        MemberType memberType) {
    super(parentMember, level, memberType);
    assert key != null;
    assert !(parentMember instanceof RolapCubeMember) || this instanceof RolapCalculatedMember
            || this instanceof VisualTotalsFunDef.VisualTotalMember;
    if (key instanceof byte[]) {
        // Some drivers (e.g. Derby) return byte arrays for binary columns
        // but byte arrays do not implement Comparable
        this.key = new String((byte[]) key);
    } else {
        this.key = key;
    }
    this.ordinal = -1;
    this.mapPropertyNameToValue = Collections.emptyMap();

    if (name != null && !(key != null && name.equals(key.toString()))) {
        // Save memory by only saving the name as a property if it's
        // different from the key.
        setProperty(Property.NAME.name, name);
    } else if (key != null) {
        setUniqueName(key);
    }
}

From source file:org.jboss.as.test.integration.management.http.HttpDeploymentUploadUnitTestCase.java

@Test
public void testHttpDeploymentUpload() throws Exception {
    final String basicUrl = "http://" + managementClient.getMgmtAddress() + ":" + managementClient.getMgmtPort()
            + "/" + MANAGEMENT_URL_PART;
    final String uploadUrl = basicUrl + "/" + UPLOAD_URL_PART;
    final Path deploymentFile = Files.createTempFile("test-http-deployment", ".sar");

    try (CloseableHttpClient client = createHttpClient()) {
        // Create the deployment
        final JavaArchive archive = ServiceActivatorDeploymentUtil
                .createServiceActivatorDeploymentArchive(DEPLOYMENT_NAME, Collections.emptyMap());
        // Create the HTTP connection to the upload URL
        final HttpPost addContentPost = new HttpPost(uploadUrl);

        // Create a deployment file
        archive.as(ZipExporter.class).exportTo(deploymentFile.toFile(), true);
        addContentPost.setEntity(createUploadEntity(deploymentFile.toFile()));

        final byte[] hash;

        // Execute the request and get the HTTP response
        try (CloseableHttpResponse response = client.execute(addContentPost)) {
            final ModelNode result = validateStatus(response);
            hash = Operations.readResult(result).asBytes();
            // JBAS-9291
            assertEquals("text/html; charset=utf-8", response.getEntity().getContentType().getValue());
        }//from   w  ww  .  j a  v a  2s. co m

        final HttpPost addHashContentPost = new HttpPost(basicUrl);
        addHashContentPost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        addHashContentPost.setEntity(createAddEntity(hash));
        try (CloseableHttpResponse response = client.execute(addHashContentPost)) {
            validateStatus(response);
        }

        // Remove the deployment
        final HttpPost removePost = new HttpPost(basicUrl);
        removePost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        removePost.setEntity(createRemoveEntity());
        try (CloseableHttpResponse response = client.execute(removePost)) {
            validateStatus(response);
        }
    } finally {
        Files.deleteIfExists(deploymentFile);
        boolean found = false;
        final ModelControllerClient client = managementClient.getControllerClient();
        // Use the management client to ensure we removed the deployment
        final ModelNode readOp = Operations.createOperation("read-children-names");
        readOp.get("child-type").set("deployment");
        ModelNode result = client.execute(readOp);
        if (Operations.isSuccessfulOutcome(result)) {
            final List<ModelNode> deployments = Operations.readResult(result).asList();
            for (ModelNode deployment : deployments) {
                if (deployment.asString().equals(DEPLOYMENT_NAME)) {
                    found = true;
                    break;
                }
            }
        }
        if (found) {
            result = client.execute(Operations.createRemoveOperation(deploymentAddress));
            if (!Operations.isSuccessfulOutcome(result)) {
                fail(String.format("Failed to remove deployment %s: %s", DEPLOYMENT_NAME,
                        Operations.getFailureDescription(result).asString()));
            }
        }
    }
}

From source file:org.apache.calcite.adapter.elasticsearch.EmbeddedElasticsearchPolicy.java

void insertDocument(String index, ObjectNode document) throws IOException {
    Objects.requireNonNull(index, "index");
    Objects.requireNonNull(document, "document");
    String uri = String.format(Locale.ROOT, "/%s/%s/?refresh", index, index);
    StringEntity entity = new StringEntity(mapper().writeValueAsString(document), ContentType.APPLICATION_JSON);

    restClient().performRequest("POST", uri, Collections.emptyMap(), entity);
}

From source file:com.perl5.lang.perl.parser.Exception.Class.psi.impl.PerlExceptionClassWrapper.java

private void processExceptionElement(@NotNull List<PsiElement> listElements, int currentIndex,
        @NotNull List<PerlDelegatingLightNamedElement> result) {
    PsiElement listElement = listElements.get(currentIndex);
    if (!isAcceptableIdentifierElement(listElement)) {
        return;//w w w . ja  va  2  s .co m
    }
    String namespaceName = ElementManipulators.getValueText(listElement);
    if (StringUtil.isEmpty(namespaceName)) {
        return;
    }

    Map<String, PerlHashEntry> exceptionSettings = listElements.size() > currentIndex + 1
            ? PerlHashUtil.collectHashMap(listElements.get(currentIndex + 1))
            : Collections.emptyMap();

    // Building fields
    Set<PerlSubArgument> throwArguments = Collections.emptySet();
    PerlHashEntry fieldsEntry = exceptionSettings.get("fields");
    if (fieldsEntry != null && fieldsEntry.isComplete()) {
        PsiElement fieldsContainer = fieldsEntry.getNonNullValueElement();
        if (fieldsContainer instanceof PsiPerlAnonArray) {
            fieldsContainer = ((PsiPerlAnonArray) fieldsContainer).getExpr();
        }
        List<PsiElement> elements = PerlArrayUtil.collectListElements(fieldsContainer);
        if (!elements.isEmpty()) {

            // Fields method
            result.add(new PerlLightMethodDefinitionElement<>(this, FIELDS_METHOD_NAME, LIGHT_METHOD_DEFINITION,
                    fieldsEntry.keyElement, namespaceName, Collections.emptyList(), null));

            // fields themselves
            throwArguments = new LinkedHashSet<>();
            for (PsiElement fieldElement : elements) {
                if (isAcceptableIdentifierElement(fieldElement)) {
                    String fieldName = PerlScalarUtil.getStringContent(fieldElement);
                    if (StringUtil.isNotEmpty(fieldName)) {
                        throwArguments.add(PerlSubArgument.mandatoryScalar(fieldName));
                        result.add(
                                new PerlLightMethodDefinitionElement<>(this, fieldName, LIGHT_METHOD_DEFINITION,
                                        fieldElement, namespaceName, Collections.emptyList(), null));
                    }
                }
            }
        }
    }

    // making exception class
    PerlHashEntry isaEntry = exceptionSettings.get("isa");
    String parentClass = "Exception::Class::Base";
    if (isaEntry != null && isaEntry.isComplete()) {
        String manualIsa = isaEntry.getValueString();
        if (manualIsa != null) {
            parentClass = manualIsa;
        }
    }

    result.add(new PerlLightExceptionClassDefinition(this, namespaceName, LIGHT_NAMESPACE_DEFINITION,
            listElement, PerlMroType.DFS, Collections.singletonList(parentClass),
            PerlNamespaceAnnotations.tryToFindAnnotations(listElement, getParent()), Collections.emptyList(),
            Collections.emptyList(), Collections.emptyMap()));

    // making alias
    PerlHashEntry aliasEntry = exceptionSettings.get("alias");
    if (aliasEntry != null && aliasEntry.isComplete()) {
        if (isAcceptableIdentifierElement(aliasEntry.valueElement)) {
            String aliasName = aliasEntry.getValueString();
            if (StringUtils.isNotEmpty(aliasName)) {
                result.add(new PerlLightSubDefinitionElement<>(this, aliasName, LIGHT_SUB_DEFINITION,
                        aliasEntry.getNonNullValueElement(), PerlPackageUtil.getContextPackageName(this),
                        new ArrayList<>(throwArguments), PerlSubAnnotations
                                .tryToFindAnnotations(aliasEntry.keyElement, aliasEntry.valueElement)));
            }
        }
    }
}