List of usage examples for java.util Locale ROOT
Locale ROOT
To view the source code for java.util Locale ROOT.
Click Source Link
From source file:org.apache.solr.client.solrj.impl.HttpSolrClient.java
protected NamedList<Object> executeMethod(HttpRequestBase method, final ResponseParser processor) throws SolrServerException { method.addHeader("User-Agent", AGENT); org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = HttpClientUtil .createDefaultRequestConfigBuilder(); if (soTimeout != null) { requestConfigBuilder.setSocketTimeout(soTimeout); }/*from w w w. j a v a 2 s.co m*/ if (connectionTimeout != null) { requestConfigBuilder.setConnectTimeout(connectionTimeout); } if (followRedirects != null) { requestConfigBuilder.setRedirectsEnabled(followRedirects); } method.setConfig(requestConfigBuilder.build()); HttpEntity entity = null; InputStream respBody = null; boolean shouldClose = true; try { // Execute the method. HttpClientContext httpClientRequestContext = HttpClientUtil.createNewHttpClientRequestContext(); final HttpResponse response = httpClient.execute(method, httpClientRequestContext); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents entity = response.getEntity(); respBody = entity.getContent(); Header ctHeader = response.getLastHeader("content-type"); String contentType; if (ctHeader != null) { contentType = ctHeader.getValue(); } else { contentType = ""; } // handle some http level checks before trying to parse the response switch (httpStatus) { case HttpStatus.SC_OK: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_CONFLICT: // 409 break; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: if (!followRedirects) { throw new SolrServerException( "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ")."); } break; default: if (processor == null || "".equals(contentType)) { throw new RemoteSolrException(baseUrl, httpStatus, "non ok status: " + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase(), null); } } if (processor == null || processor instanceof InputStreamResponseParser) { // no processor specified, return raw stream NamedList<Object> rsp = new NamedList<>(); rsp.add("stream", respBody); // Only case where stream should not be closed shouldClose = false; return rsp; } String procCt = processor.getContentType(); if (procCt != null) { String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT); String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT); if (!procMimeType.equals(mimeType)) { // unexpected mime type String msg = "Expected mime type " + procMimeType + " but got " + mimeType + "."; Header encodingHeader = response.getEntity().getContentEncoding(); String encoding; if (encodingHeader != null) { encoding = encodingHeader.getValue(); } else { encoding = "UTF-8"; // try UTF-8 } try { msg = msg + " " + IOUtils.toString(respBody, encoding); } catch (IOException e) { throw new RemoteSolrException(baseUrl, httpStatus, "Could not parse response with encoding " + encoding, e); } throw new RemoteSolrException(baseUrl, httpStatus, msg, null); } } NamedList<Object> rsp = null; String charset = EntityUtils.getContentCharSet(response.getEntity()); try { rsp = processor.processResponse(respBody, charset); } catch (Exception e) { throw new RemoteSolrException(baseUrl, httpStatus, e.getMessage(), e); } if (httpStatus != HttpStatus.SC_OK) { NamedList<String> metadata = null; String reason = null; try { NamedList err = (NamedList) rsp.get("error"); if (err != null) { reason = (String) err.get("msg"); if (reason == null) { reason = (String) err.get("trace"); } metadata = (NamedList<String>) err.get("metadata"); } } catch (Exception ex) { } if (reason == null) { StringBuilder msg = new StringBuilder(); msg.append(response.getStatusLine().getReasonPhrase()).append("\n\n").append("request: ") .append(method.getURI()); reason = java.net.URLDecoder.decode(msg.toString(), UTF_8); } RemoteSolrException rss = new RemoteSolrException(baseUrl, httpStatus, reason, null); if (metadata != null) rss.setMetadata(metadata); throw rss; } return rsp; } catch (ConnectException e) { throw new SolrServerException("Server refused connection at: " + getBaseURL(), e); } catch (SocketTimeoutException e) { throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(), e); } catch (IOException e) { throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e); } finally { if (shouldClose) { Utils.consumeFully(entity); } } }
From source file:org.elasticsearch.xpack.watcher.common.http.HttpClientTests.java
public void testThatUrlPathIsNotEncoded() throws Exception { // %2F is a slash that needs to be encoded to not be misinterpreted as a path String path = "/%3Clogstash-%7Bnow%2Fd%7D%3E/_search"; webServer.enqueue(new MockResponse().setResponseCode(200).setBody("foo")); HttpRequest request;/* w w w. j a va2 s . c o m*/ if (randomBoolean()) { request = HttpRequest.builder("localhost", webServer.getPort()).path(path).build(); } else { // ensure that fromUrl acts the same way than the above builder request = HttpRequest.builder() .fromUrl(String.format(Locale.ROOT, "http://localhost:%s%s", webServer.getPort(), path)) .build(); } httpClient.execute(request); assertThat(webServer.requests(), hasSize(1)); // under no circumstances have a double encode of %2F => %25 (percent sign) assertThat(webServer.requests(), hasSize(1)); assertThat(webServer.requests().get(0).getUri().getRawPath(), not(containsString("%25"))); assertThat(webServer.requests().get(0).getUri().getPath(), is("/<logstash-{now/d}>/_search")); }
From source file:com.puppycrawl.tools.checkstyle.MainTest.java
@Test public void testExistingDirectoryWithViolations() throws Exception { // we just reference there all violations final String[][] outputValues = { { "ComplexityOverflow", "1", "172" }, }; exit.checkAssertionAfterwards(new Assertion() { @Override/*from w w w . j av a 2 s . c o m*/ public void checkAssertion() throws IOException { String currentPath = new File(".").getCanonicalPath(); String expectedPath = currentPath + "/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/".replace("/", File.separator); StringBuilder sb = new StringBuilder(); sb.append("Starting audit...").append(System.getProperty("line.separator")); String format = "%s.java:%s: warning: File length is %s lines (max allowed is 170)."; for (String[] outputValue : outputValues) { String line = String.format(Locale.ROOT, format, expectedPath + outputValue[0], outputValue[1], outputValue[2]); sb.append(line).append(System.getProperty("line.separator")); } sb.append("Audit done.").append(System.getProperty("line.separator")); assertEquals(sb.toString(), systemOut.getLog()); assertEquals("", systemErr.getLog()); } }); Main.main("-c", "src/test/resources/com/puppycrawl/tools/checkstyle/config-filelength.xml", "src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/"); }
From source file:net.yacy.crawler.retrieval.HTTPLoader.java
private static Response load(final Request request, ClientIdentification.Agent agent, final int retryCount) throws IOException { if (retryCount < 0) { throw new IOException( "Redirection counter exceeded for URL " + request.url().toString() + ". Processing aborted."); }/* w ww . j a v a 2s .c o m*/ final String host = request.url().getHost(); if (host == null || host.length() < 2) throw new IOException("host is not well-formed: '" + host + "'"); final String path = request.url().getFile(); int port = request.url().getPort(); final boolean ssl = request.url().getProtocol().equals("https"); if (port < 0) port = (ssl) ? 443 : 80; // check if url is in blacklist final String hostlow = host.toLowerCase(Locale.ROOT); if (Switchboard.urlBlacklist != null && Switchboard.urlBlacklist.isListed(BlacklistType.CRAWLER, hostlow, path)) { throw new IOException("CRAWLER Rejecting URL '" + request.url().toString() + "'. URL is in blacklist."); } // take a file from the net Response response = null; // create a request header final RequestHeader requestHeader = new RequestHeader(); requestHeader.put(HeaderFramework.USER_AGENT, agent.userAgent); requestHeader.put(HeaderFramework.ACCEPT_LANGUAGE, DEFAULT_LANGUAGE); requestHeader.put(HeaderFramework.ACCEPT_CHARSET, DEFAULT_CHARSET); requestHeader.put(HeaderFramework.ACCEPT_ENCODING, DEFAULT_ENCODING); final HTTPClient client = new HTTPClient(agent); client.setTimout(20000); client.setHeader(requestHeader.entrySet()); final byte[] responseBody = client.GETbytes(request.url(), null, null, false); final int code = client.getHttpResponse().getStatusLine().getStatusCode(); final ResponseHeader header = new ResponseHeader(code, client.getHttpResponse().getAllHeaders()); // FIXME: 30*-handling (bottom) is never reached // we always get the final content because httpClient.followRedirects = true if (responseBody != null && (code == 200 || code == 203)) { // the transfer is ok //statistics: ByteCount.addAccountCount(ByteCount.CRAWLER, responseBody.length); // we write the new cache entry to file system directly // create a new cache entry response = new Response(request, requestHeader, header, null, false, responseBody); return response; } else if (code > 299 && code < 310) { if (header.containsKey(HeaderFramework.LOCATION)) { // getting redirection URL String redirectionUrlString = header.get(HeaderFramework.LOCATION); redirectionUrlString = redirectionUrlString.trim(); if (redirectionUrlString.isEmpty()) { throw new IOException("CRAWLER Redirection of URL=" + request.url().toString() + " aborted. Location header is empty."); } // normalizing URL final DigestURL redirectionUrl = DigestURL.newURL(request.url(), redirectionUrlString); // if we are already doing a shutdown we don't need to retry crawling if (Thread.currentThread().isInterrupted()) { throw new IOException("CRAWLER Retry of URL=" + request.url().toString() + " aborted because of server shutdown."); } // retry crawling with new url request.redirectURL(redirectionUrl); return load(request, agent, retryCount - 1); } } else { // if the response has not the right response type then reject file throw new IOException("REJECTED WRONG STATUS TYPE '" + client.getHttpResponse().getStatusLine() + "' for URL " + request.url().toString()); } return response; }
From source file:org.elasticsearch.messy.tests.ContextAndHeaderTransportTests.java
private void assertRequestContainsHeader(ActionRequest request) { String msg = String.format(Locale.ROOT, "Expected header %s to be in request %s", randomHeaderKey, request.getClass().getName()); if (request instanceof IndexRequest) { IndexRequest indexRequest = (IndexRequest) request; msg = String.format(Locale.ROOT, "Expected header %s to be in index request %s/%s/%s", randomHeaderKey, indexRequest.index(), indexRequest.type(), indexRequest.id()); }//from w ww . ja v a 2 s. c o m assertThat(msg, request.hasHeader(randomHeaderKey), is(true)); assertThat(request.getHeader(randomHeaderKey).toString(), is(randomHeaderValue)); }
From source file:org.elasticsearch.plugins.PluginManagerIT.java
public void testInstallPluginWithBadChecksum() throws IOException { String pluginName = "fake-plugin"; Path pluginDir = createTempDir().resolve(pluginName); Files.createDirectories(pluginDir.resolve("_site")); Files.createFile(pluginDir.resolve("_site").resolve("somefile")); String pluginUrl = createPluginWithBadChecksum(pluginDir, "description", "fake desc", "version", "1.0", "site", "true"); assertStatus(String.format(Locale.ROOT, "install %s --verbose", pluginUrl), ExitStatus.IO_ERROR); assertThatPluginIsNotListed(pluginName); assertFileNotExists(environment.pluginsFile().resolve(pluginName).resolve("_site")); }
From source file:org.elasticsearch.client.RequestConverters.java
private static void addSearchRequestParams(Params params, SearchRequest searchRequest) { params.putParam(RestSearchAction.TYPED_KEYS_PARAM, "true"); params.withRouting(searchRequest.routing()); params.withPreference(searchRequest.preference()); params.withIndicesOptions(searchRequest.indicesOptions()); params.putParam("search_type", searchRequest.searchType().name().toLowerCase(Locale.ROOT)); if (searchRequest.requestCache() != null) { params.putParam("request_cache", Boolean.toString(searchRequest.requestCache())); }// ww w.j a v a 2s .co m if (searchRequest.allowPartialSearchResults() != null) { params.putParam("allow_partial_search_results", Boolean.toString(searchRequest.allowPartialSearchResults())); } params.putParam("batched_reduce_size", Integer.toString(searchRequest.getBatchedReduceSize())); if (searchRequest.scroll() != null) { params.putParam("scroll", searchRequest.scroll().keepAlive()); } }
From source file:org.elasticsearch.plugins.PluginManagerIT.java
private void singlePluginInstallAndRemove(String pluginDescriptor, String pluginName, String pluginCoordinates) throws IOException { logger.info("--> trying to download and install [{}]", pluginDescriptor); if (pluginCoordinates == null) { assertStatusOk(String.format(Locale.ROOT, "install %s --verbose", pluginDescriptor)); } else {/*from w ww . j a v a2 s . c o m*/ assertStatusOk(String.format(Locale.ROOT, "install %s --verbose", pluginCoordinates)); } assertThatPluginIsListed(pluginName); terminal.getTerminalOutput().clear(); assertStatusOk("remove " + pluginDescriptor); assertThat(terminal.getTerminalOutput(), hasItem(containsString("Removing " + pluginDescriptor))); // not listed anymore terminal.getTerminalOutput().clear(); assertStatusOk("list"); assertThat(terminal.getTerminalOutput(), not(hasItem(containsString(pluginName)))); }
From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XMLHTTPRequest.java
private boolean isPreflight() { final HttpMethod method = webRequest_.getHttpMethod(); if (method != HttpMethod.GET && method != HttpMethod.HEAD && method != HttpMethod.POST) { return true; }//w w w . j a va 2 s . c o m for (final Entry<String, String> header : webRequest_.getAdditionalHeaders().entrySet()) { if (isPreflightHeader(header.getKey().toLowerCase(Locale.ROOT), header.getValue())) { return true; } } return false; }
From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocumentTest.java
/** * Regression test for bug 2919853 (format of <tt>document.lastModified</tt> was incorrect). * @throws Exception if an error occurs//from www . java 2s. c o m */ @Test public void lastModified_format() throws Exception { final String html = "<html><body onload='document.getElementById(\"i\").value = document.lastModified'>\n" + "<input id='i'></input></body></html>"; final WebDriver driver = loadPageWithAlerts2(html); final String lastModified = driver.findElement(By.id("i")).getAttribute("value"); try { new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ROOT).parse(lastModified); } catch (final ParseException e) { fail(e.getMessage()); } }