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.manifoldcf.agents.output.solr.HttpPoster.java
/** Handle an IOException. * I'm not actually sure where these exceptions come from in SolrJ, but we handle them * as real I/O errors, meaning they should be retried. *///from w ww.ja v a 2s .c om protected static void handleIOException(IOException e, String context) throws ManifoldCFException, ServiceInterruption { if ((e instanceof InterruptedIOException) && (!(e instanceof java.net.SocketTimeoutException))) throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED); long currentTime = System.currentTimeMillis(); if (e instanceof java.net.ConnectException) { // Server isn't up at all. Try for a brief time then give up. String message = "Server could not be contacted during " + context + ": " + e.getMessage(); Logging.ingest.warn(message, e); throw new ServiceInterruption(message, e, currentTime + interruptionRetryTime, -1L, 3, true); } if (e instanceof java.net.SocketTimeoutException) { String message2 = "Socket timeout exception during " + context + ": " + e.getMessage(); Logging.ingest.warn(message2, e); throw new ServiceInterruption(message2, e, currentTime + interruptionRetryTime, currentTime + 20L * 60000L, -1, false); } if (e.getClass().getName().equals("java.net.SocketException")) { // In the past we would have treated this as a straight document rejection, and // treated it in the same manner as a 400. The reasoning is that the server can // perfectly legally send out a 400 and drop the connection immediately thereafter, // this a race condition. // However, Solr 4.0 (or the Jetty version that the example runs on) seems // to have a bug where it drops the connection when two simultaneous documents come in // at the same time. This is the final version of Solr 4.0 so we need to deal with // this. if (e.getMessage().toLowerCase(Locale.ROOT).indexOf("broken pipe") != -1 || e.getMessage().toLowerCase(Locale.ROOT).indexOf("connection reset") != -1 || e.getMessage().toLowerCase(Locale.ROOT).indexOf("target server failed to respond") != -1) { // Treat it as a service interruption, but with a limited number of retries. // In that way we won't burden the user with a huge retry interval; it should // give up fairly quickly, and yet NOT give up if the error was merely transient String message = "Server dropped connection during " + context + ": " + e.getMessage(); Logging.ingest.warn(message, e); throw new ServiceInterruption(message, e, currentTime + interruptionRetryTime, -1L, 3, false); } // Other socket exceptions are service interruptions - but if we keep getting them, it means // that a socket timeout is probably set too low to accept this particular document. So // we retry for a while, then skip the document. String message2 = "Socket exception during " + context + ": " + e.getMessage(); Logging.ingest.warn(message2, e); throw new ServiceInterruption(message2, e, currentTime + interruptionRetryTime, currentTime + 20L * 60000L, -1, false); } // Otherwise, no idea what the trouble is, so presume that retries might fix it. String message3 = "IO exception during " + context + ": " + e.getMessage(); Logging.ingest.warn(message3, e); throw new ServiceInterruption(message3, e, currentTime + interruptionRetryTime, currentTime + 2L * 60L * 60000L, -1, true); }
From source file:com.puppycrawl.tools.checkstyle.MainTest.java
@Test public void testExistingIncorrectConfigFile() throws Exception { exit.expectSystemExitWithStatus(-2); exit.checkAssertionAfterwards(new Assertion() { @Override//from www . j a v a2 s . c om public void checkAssertion() { assertTrue(systemOut.getLog() .startsWith(String.format(Locale.ROOT, "unable to parse configuration stream - Content is not allowed in prolog.:7:1%n" + "Cause: org.xml.sax.SAXParseException; systemId: file:"))); assertTrue(systemOut.getLog().endsWith(String.format(Locale.ROOT, "com/puppycrawl/tools/checkstyle/config-Incorrect.xml; lineNumber: 7; columnNumber: 1; " + "Content is not allowed in prolog.%n" + "Checkstyle ends with 1 errors.%n"))); assertEquals("", systemErr.getLog()); } }); Main.main("-c", "src/test/resources/com/puppycrawl/tools/checkstyle/" + "config-Incorrect.xml", "src/test/resources/com/puppycrawl/tools/checkstyle/InputMain.java"); }
From source file:com.puppycrawl.tools.checkstyle.CheckerTest.java
@Test public void testClearExistingCache() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); final DefaultConfiguration treeWalkerConfig = createCheckConfig(TreeWalker.class); treeWalkerConfig.addChild(checkConfig); final DefaultConfiguration checkerConfig = new DefaultConfiguration("myConfig"); checkerConfig.addAttribute("charset", "UTF-8"); checkerConfig.addChild(treeWalkerConfig); checkerConfig.addAttribute("cacheFile", temporaryFolder.newFile().getPath()); final Checker checker = new Checker(); final Locale locale = Locale.ROOT; checker.setLocaleCountry(locale.getCountry()); checker.setLocaleLanguage(locale.getLanguage()); checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); checker.configure(checkerConfig);//from ww w. ja v a2 s . co m checker.addListener(new BriefUtLogger(stream)); final String pathToEmptyFile = temporaryFolder.newFile("file.java").getPath(); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verify(checker, pathToEmptyFile, pathToEmptyFile, expected); checker.clearCache(); // one more time, but file that should be audited is not in cache verify(checker, pathToEmptyFile, pathToEmptyFile, expected); }
From source file:com.google.gwt.emultest.java.util.IdentityHashMapTest.java
public void testKeySet() { IdentityHashMap hashMap = new IdentityHashMap(); checkEmptyHashMapAssumptions(hashMap); Set keySet = hashMap.keySet(); assertNotNull(keySet);/*from w w w. ja v a 2 s .c om*/ assertTrue(keySet.isEmpty()); assertTrue(keySet.size() == 0); hashMap.put(KEY_TEST_KEY_SET, VALUE_TEST_KEY_SET); assertTrue(keySet.size() == SIZE_ONE); assertTrue(keySet.contains(KEY_TEST_KEY_SET)); assertFalse(keySet.contains(VALUE_TEST_KEY_SET)); assertFalse(keySet.contains(KEY_TEST_KEY_SET.toUpperCase(Locale.ROOT))); }
From source file:com.gargoylesoftware.htmlunit.html.HtmlPage.java
/** * {@inheritDoc}// w ww. j a v a2s . co m * @param tagName the tag name, preferably in lowercase */ @Override public DomElement createElement(String tagName) { if (tagName.indexOf(':') == -1) { tagName = tagName.toLowerCase(Locale.ROOT); } return HTMLParser.getFactory(tagName).createElementNS(this, null, tagName, null, true); }
From source file:com.nkang.kxmoment.util.SolrUtils.HttpSolrServer.java
public NamedList<Object> request(final SolrRequest request, final ResponseParser processor) throws SolrServerException, IOException { HttpRequestBase method = null;// w w w . ja va 2 s .c o m InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = DEFAULT_PATH; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = this.parser; } // The parser 'wt=' and 'version=' params are used instead of the original // params ModifiableSolrParams wparams = new ModifiableSolrParams(params); if (parser != null) { wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); } if (invariantParams != null) { wparams.add(invariantParams); } int tries = maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new HttpGet(baseUrl + path + ClientUtils.toQueryString(wparams, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = baseUrl + path; boolean hasNullStreamName = false; if (streams != null) { for (ContentStream cs : streams) { if (cs.getName() == null) { hasNullStreamName = true; break; } } } boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1)) && !hasNullStreamName; // only send this list of params as query string params ModifiableSolrParams queryParams = new ModifiableSolrParams(); for (String param : this.queryParams) { String[] value = wparams.getParams(param); if (value != null) { for (String v : value) { queryParams.add(param, v); } wparams.remove(param); } } LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>(); if (streams == null || isMultipart) { HttpPost post = new HttpPost(url + ClientUtils.toQueryString(queryParams, false)); post.setHeader("Content-Charset", "UTF-8"); if (!isMultipart) { post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<FormBodyPart> parts = new LinkedList<FormBodyPart>(); Iterator<String> iter = wparams.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = wparams.getParams(p); if (vals != null) { for (String v : vals) { if (isMultipart) { parts.add(new FormBodyPart(p, new StringBody(v, Charset.forName("UTF-8")))); } else { postParams.add(new BasicNameValuePair(p, v)); } } } } if (isMultipart && streams != null) { for (ContentStream content : streams) { String contentType = content.getContentType(); if (contentType == null) { contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default } String name = content.getName(); if (name == null) { name = ""; } parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(), contentType, content.getName()))); } } if (parts.size() > 0) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); for (FormBodyPart p : parts) { entity.addPart(p); } post.setEntity(entity); } else { //not using multipart post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8")); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(wparams, false); HttpPost post = new HttpPost(url + pstr); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } else { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if (tries < 1) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } // client already has this set, is this needed method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects); method.addHeader("User-Agent", AGENT); // add jauth information //String username = WebServiceLoaderUtils.getWebServiceProperty(Constants.SECURITY_USERNAME).toString(); //String password = WebServiceLoaderUtils.getWebServiceProperty(Constants.SECURITY_PASSWORD).toString(); ResourceBundle bundle = ResourceBundle.getBundle("solrconfig"); String username; String password; username = bundle.getString("wsUsername.url"); password = bundle.getString("wsPassword.url"); method.addHeader("username", username); method.addHeader("password", password); InputStream respBody = null; boolean shouldClose = true; boolean success = false; try { // Execute the method. final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents respBody = response.getEntity().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) { throw new RemoteSolrException(httpStatus, "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase(), null); } } if (processor == null) { // no processor specified, return raw stream NamedList<Object> rsp = new NamedList<Object>(); rsp.add("stream", respBody); // Only case where stream should not be closed shouldClose = false; success = true; 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(httpStatus, "Could not parse response with encoding " + encoding, e); } RemoteSolrException e = new RemoteSolrException(httpStatus, msg, null); throw e; } } // if(true) { // ByteArrayOutputStream copy = new ByteArrayOutputStream(); // IOUtils.copy(respBody, copy); // String val = new String(copy.toByteArray()); // System.out.println(">RESPONSE>"+val+"<"+val.length()); // respBody = new ByteArrayInputStream(copy.toByteArray()); // } NamedList<Object> rsp = null; String charset = EntityUtils.getContentCharSet(response.getEntity()); try { rsp = processor.processResponse(respBody, charset); } catch (Exception e) { throw new RemoteSolrException(httpStatus, e.getMessage(), e); } if (httpStatus != HttpStatus.SC_OK) { String reason = null; try { NamedList<?> err = (NamedList<?>) rsp.get("error"); if (err != null) { reason = (String) err.get("msg"); // TODO? get the trace? } } catch (Exception ex) { } if (reason == null) { StringBuilder msg = new StringBuilder(); msg.append(response.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append("request: " + method.getURI()); reason = java.net.URLDecoder.decode(msg.toString(), UTF_8); } throw new RemoteSolrException(httpStatus, reason, null); } success = true; 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 (respBody != null && shouldClose) { try { respBody.close(); } catch (IOException e) { //log.error("", e); } finally { if (!success) { method.abort(); } } } } }
From source file:org.elasticsearch.xpack.qa.sql.rest.RestSqlTestCase.java
public void testNextPageText() throws IOException { int size = 20; String[] docs = new String[size]; for (int i = 0; i < size; i++) { docs[i] = "{\"text\":\"text" + i + "\", \"number\":" + i + "}\n"; }/* w w w. ja v a 2 s .c om*/ index(docs); String request = "{\"query\":\"SELECT text, number, number + 5 AS sum FROM test ORDER BY number\", \"fetch_size\":2}"; String cursor = null; for (int i = 0; i < 20; i += 2) { Tuple<String, String> response; if (i == 0) { response = runSqlAsText("", new StringEntity(request, ContentType.APPLICATION_JSON), "text/plain"); } else { response = runSqlAsText("", new StringEntity("{\"cursor\":\"" + cursor + "\"}", ContentType.APPLICATION_JSON), "text/plain"); } StringBuilder expected = new StringBuilder(); if (i == 0) { expected.append(" text | number | sum \n"); expected.append("---------------+---------------+---------------\n"); } expected.append(String.format(Locale.ROOT, "%-15s|%-15d|%-15d\n", "text" + i, i, i + 5)); expected.append(String.format(Locale.ROOT, "%-15s|%-15d|%-15d\n", "text" + (i + 1), i + 1, i + 6)); cursor = response.v2(); assertEquals(expected.toString(), response.v1()); assertNotNull(cursor); } Map<String, Object> expected = new HashMap<>(); expected.put("rows", emptyList()); assertResponse(expected, runSql("", new StringEntity("{\"cursor\":\"" + cursor + "\"}", ContentType.APPLICATION_JSON))); Map<String, Object> response = runSql("", new StringEntity("{\"cursor\":\"" + cursor + "\"}", ContentType.APPLICATION_JSON), "/close"); assertEquals(true, response.get("succeeded")); assertEquals(0, getNumberOfSearchContexts("test")); }
From source file:com.odoko.solrcli.actions.CrawlPostAction.java
/** * Guesses the type of a file, based on file name suffix * @param file the file// w w w . j a v a 2 s. c om * @return the content-type guessed */ protected static String guessType(File file) { String name = file.getName(); String suffix = name.substring(name.lastIndexOf(".")+1); return mimeMap.get(suffix.toLowerCase(Locale.ROOT)); }