List of usage examples for java.util Collections emptyMap
@SuppressWarnings("unchecked") public static final <K, V> Map<K, V> emptyMap()
From source file:com.wso2telco.core.userprofile.prosser.UserClaimProsser.java
public Map<ClaimName, String> getUserClaimsByUserName(String userName) { try {//from w ww .j a v a 2 s .c o m APIManagerConfiguration config = HostObjectComponent.getAPIManagerConfiguration(); String remoteUserStoreManagerServiceEndpoint = config.getFirstProperty(APIConstants.AUTH_MANAGER_URL) + AdminServicePath.REMOTE_USER_STORE_MANAGER_SERVICE.getTObject(); String adminUsername = config.getFirstProperty(APIConstants.AUTH_MANAGER_USERNAME); String adminPassword = config.getFirstProperty(APIConstants.AUTH_MANAGER_PASSWORD); RemoteUserStoreManagerServiceStub userStoreManagerStub = new RemoteUserStoreManagerServiceStub( remoteUserStoreManagerServiceEndpoint); CarbonUtils.setBasicAccessSecurityHeaders(adminUsername, adminPassword, userStoreManagerStub._getServiceClient()); ClaimUtil claimUtil = new ClaimUtil(); Claim[] claims = claimUtil.convertToClaims( userStoreManagerStub.getUserClaimValues(userName, UserProfileType.DEFAULT.getTObject())); List<ClaimName> somethingList = Arrays.asList(ClaimName.values()); for (Iterator<ClaimName> iterator = somethingList.iterator(); iterator.hasNext();) { ClaimName claimName = iterator.next(); getClaimValue(claims, claimName); } } catch (RemoteException | RemoteUserStoreManagerServiceUserStoreExceptionException e) { log.error("unable to retrieve claims for user " + userName + " : ", e); return Collections.emptyMap(); } return userClaimDetails; }
From source file:org.n52.io.extension.StatusIntervalsExtension.java
@Override public Map<String, Object> getExtras(DatasetOutput output, IoParameters parameters) { if (!hasExtrasToReturn(output, parameters)) { return Collections.emptyMap(); }//from w w w . jav a 2 s. c o m if (hasSeriesConfiguration(output)) { final StatusInterval[] intervals = createIntervals(getSeriesIntervals(output)); checkForBackwardCompatiblity(output, intervals); // stay backwards compatible return wrapSingleIntoMap(intervals); } else if (hasPhenomenonConfiguration(output)) { final StatusInterval[] intervals = createIntervals(getPhenomenonIntervals(output)); checkForBackwardCompatiblity(output, intervals); // stay backwards compatible return wrapSingleIntoMap(intervals); } LOGGER.error("No status intervals found for {} (id={})", output, output.getId()); return Collections.emptyMap(); }
From source file:com.playbasis.android.playbasissdk.http.toolbox.BasicNetwork.java
@Override public NetworkResponse performRequest(Request<?> request) throws HttpError { long requestStart = SystemClock.elapsedRealtime(); while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = Collections.emptyMap(); try {/*from ww w. java 2 s.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) { 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); } // 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 (IOException e) { int statusCode = 0; NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { throw new NoConnectionError(e); } PlayBasisLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); if (responseContents != null) { try { String s = new String(responseContents, "UTF-8"); System.out.println(s); } catch (UnsupportedEncodingException dsds) { dsds.printStackTrace(); } //System.out.print(new String(responseContents, StandardCharsets.UTF_8)); 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 { // TODO: Only throw ServerError for 5xx status codes. try { String responseString = new BasicResponseHandler().handleResponse(httpResponse); System.out.println("Http response"); System.out.println(responseString); } catch (IOException ex) { ex.printStackTrace(); } System.out.println(networkResponse.getRestErrorMessage()); throw new ServerError(networkResponse); } } else { throw new NetworkError(networkResponse); } } } }
From source file:com.nxt.zyl.data.volley.toolbox.BasicNetwork.java
@SuppressLint("DefaultLocale") @Override/*from ww w . ja v a 2s . co m*/ public NetworkResponse performRequest(ResponseDelivery delivery, Request<?> request) throws VolleyError { long requestStart = SystemClock.elapsedRealtime(); while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = Collections.emptyMap(); try { if (!URLUtil.isNetworkUrl(request.getUrl())) { return new NetworkResponse(responseContents); } // 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); } // 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); } // 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) { if (request instanceof DownloadRequest) { DownloadRequest downloadRequest = (DownloadRequest) request; // ???range??? if (downloadRequest.isResume() && !isSupportRange(httpResponse)) { downloadRequest.setResume(false); } if (statusCode == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) { return new NetworkResponse(HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE, downloadRequest.getTarget().getBytes(), responseHeaders, false); } else if (statusCode >= 300) { responseContents = entityToBytes(delivery, request, httpResponse.getEntity()); } else { responseContents = handleEntity(delivery, (DownloadRequest) request, httpResponse.getEntity()); } } else { responseContents = entityToBytes(delivery, request, 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); } 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 (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); 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); } } finally { try { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } catch (IllegalStateException | IOException ignored) { } } } }
From source file:cd.go.contrib.elasticagents.dockerswarm.elasticagent.model.reports.SwarmCluster.java
private Map<String, Service> serviceIdToServiceMap(DockerClient dockerClient) throws DockerException, InterruptedException { final List<Service> services = dockerClient.listServices(); if (services == null || services.isEmpty()) { return Collections.emptyMap(); }//from w w w . j av a2 s .c o m final HashMap<String, Service> serviceIdToService = new HashMap<>(); for (Service service : services) { serviceIdToService.put(service.id(), service); } return serviceIdToService; }
From source file:com.arpnetworking.metrics.vertx.SinkHandlerTest.java
@Test public void testHandleWithMessageWithoutCounterSamples() throws JsonProcessingException { final String messageBody = OBJECT_MAPPER .writeValueAsString(ImmutableMap.of(TIMER_SAMPLES_KEY, Collections.emptyMap(), ANNOTATIONS_KEY, Collections.emptyMap(), GAUGE_SAMPLES_KEY, Collections.emptyMap())); Mockito.doReturn(messageBody).when(_message).body(); _handler.handle(_message);//from www.j a v a2s .c om Mockito.verifyZeroInteractions(_mockSink); }
From source file:io.hops.hopsworks.api.zeppelin.rest.NotebookRepoRestApi.java
/** * Update a specific note repo./*from w w w. j a va 2 s . co m*/ * * @param payload * @return */ @PUT @ZeppelinApi public Response updateRepoSetting(String payload) { if (StringUtils.isBlank(payload)) { return new JsonResponse<>(Status.NOT_FOUND, "", Collections.emptyMap()).build(); } AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal()); NotebookRepoSettingsRequest newSettings = NotebookRepoSettingsRequest.EMPTY; try { newSettings = NotebookRepoSettingsRequest.fromJson(payload); } catch (JsonSyntaxException e) { LOG.error("Cannot update notebook repo settings", e); return new JsonResponse<>(Status.NOT_ACCEPTABLE, "", ImmutableMap.of("error", "Invalid payload structure")).build(); } if (NotebookRepoSettingsRequest.isEmpty(newSettings)) { LOG.error("Invalid property"); return new JsonResponse<>(Status.NOT_ACCEPTABLE, "", ImmutableMap.of("error", "Invalid payload")) .build(); } LOG.info("User {} is going to change repo setting", subject.getUser()); NotebookRepoWithSettings updatedSettings = noteRepos.updateNotebookRepo(newSettings.name, newSettings.settings, subject); if (!updatedSettings.isEmpty()) { LOG.info("Broadcasting note list to user {}", subject.getUser()); notebookWsServer.broadcastReloadedNoteList(subject, null); } return new JsonResponse<>(Status.OK, "", updatedSettings).build(); }
From source file:org.elasticsearch.xpack.ml.integration.MlBasicMultiNodeIT.java
public void testMiniFarequote() throws Exception { String jobId = "mini-farequote-job"; createFarequoteJob(jobId);/* w w w . ja va 2 s . co m*/ Response response = client().performRequest("post", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_open"); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(Collections.singletonMap("opened", true), responseEntityToMap(response)); String postData = "{\"airline\":\"AAL\",\"responsetime\":\"132.2046\",\"sourcetype\":\"farequote\",\"time\":\"1403481600\"}\n" + "{\"airline\":\"JZA\",\"responsetime\":\"990.4628\",\"sourcetype\":\"farequote\",\"time\":\"1403481700\"}"; response = client().performRequest("post", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_data", Collections.emptyMap(), new StringEntity(postData, randomFrom(ContentType.APPLICATION_JSON, ContentType.create("application/x-ndjson")))); assertEquals(202, response.getStatusLine().getStatusCode()); Map<String, Object> responseBody = responseEntityToMap(response); assertEquals(2, responseBody.get("processed_record_count")); assertEquals(4, responseBody.get("processed_field_count")); assertEquals(177, responseBody.get("input_bytes")); assertEquals(6, responseBody.get("input_field_count")); assertEquals(0, responseBody.get("invalid_date_count")); assertEquals(0, responseBody.get("missing_field_count")); assertEquals(0, responseBody.get("out_of_order_timestamp_count")); assertEquals(0, responseBody.get("bucket_count")); assertEquals(1403481600000L, responseBody.get("earliest_record_timestamp")); assertEquals(1403481700000L, responseBody.get("latest_record_timestamp")); response = client().performRequest("post", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_flush"); assertEquals(200, response.getStatusLine().getStatusCode()); assertFlushResponse(response, true, 1403481600000L); response = client().performRequest("post", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_close", Collections.singletonMap("timeout", "20s")); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(Collections.singletonMap("closed", true), responseEntityToMap(response)); response = client().performRequest("get", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_stats"); assertEquals(200, response.getStatusLine().getStatusCode()); @SuppressWarnings("unchecked") Map<String, Object> dataCountsDoc = (Map<String, Object>) ((Map) ((List) responseEntityToMap(response) .get("jobs")).get(0)).get("data_counts"); assertEquals(2, dataCountsDoc.get("processed_record_count")); assertEquals(4, dataCountsDoc.get("processed_field_count")); assertEquals(177, dataCountsDoc.get("input_bytes")); assertEquals(6, dataCountsDoc.get("input_field_count")); assertEquals(0, dataCountsDoc.get("invalid_date_count")); assertEquals(0, dataCountsDoc.get("missing_field_count")); assertEquals(0, dataCountsDoc.get("out_of_order_timestamp_count")); assertEquals(0, dataCountsDoc.get("bucket_count")); assertEquals(1403481600000L, dataCountsDoc.get("earliest_record_timestamp")); assertEquals(1403481700000L, dataCountsDoc.get("latest_record_timestamp")); response = client().performRequest("delete", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId); assertEquals(200, response.getStatusLine().getStatusCode()); }
From source file:reactor.js.core.JavaScriptObject.java
public JavaScriptObject(Map<String, Object> properties, Map<String, Supplier<?>> propertySuppliers, List<String> readOnlyProperties, Object parent) { if (null == properties) { properties = Collections.emptyMap(); }/*from w ww . j a va 2 s . c o m*/ if (null == propertySuppliers) { propertySuppliers = Collections.emptyMap(); } if (null == readOnlyProperties) { readOnlyProperties = Collections.emptyList(); } this.properties = UnifiedMap.newMap(properties); this.propertySuppliers = UnifiedMap.newMap(propertySuppliers); this.readOnlyProperties = FastList.newList(readOnlyProperties).toImmutable(); setParent(parent); }
From source file:com.quinsoft.zeidon.jconsole.JConsoleEnvironment.java
@Override public Map<String, BrowserTask> refreshBrowserTaskList() { if (currentlySelectedOe == null) { Map<String, BrowserTask> map = Collections.emptyMap(); setCurrentTaskList(map);/*w ww .j a va2 s . c om*/ return map; } JmxObjectEngineMonitorMBean proxy = currentlySelectedOe.proxy; Map<String, BrowserTask> map = new HashMap<>(); for (String taskInfo : proxy.getTaskList()) { String[] strings = taskInfo.split(","); map.put(strings[0], new BrowserTask(strings[0], strings[1])); } setCurrentTaskList(map); return map; }