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:com.gargoylesoftware.htmlunit.util.EncodingSniffer.java
/** * Returns {@code true} if the specified HTTP response headers contain a <tt>Content-Type</tt> that * ends with one of the specified strings. * * @param headers the HTTP response headers * @param contentTypeEndings the content type endings to search for * @return {@code true} if the specified HTTP response headers contain a <tt>Content-Type</tt> that * ends with one of the specified strings */// www .j a va 2s . co m static boolean contentTypeEndsWith(final List<NameValuePair> headers, final String... contentTypeEndings) { for (final NameValuePair pair : headers) { final String name = pair.getName(); if ("content-type".equalsIgnoreCase(name)) { String value = pair.getValue(); final int i = value.indexOf(';'); if (i != -1) { value = value.substring(0, i); } value = value.trim().toLowerCase(Locale.ROOT); for (String ending : contentTypeEndings) { if (value.endsWith(ending.toLowerCase(Locale.ROOT))) { return true; } } return false; } } return false; }
From source file:com.google.gwt.emultest.java.util.LinkedHashMapTest.java
/** * Test method for 'java.util.LinkedHashMap.putAll(Map)'. *//*from w ww .j av a 2 s. co m*/ public void testPutAll() { LinkedHashMap<String, String> srcMap = new LinkedHashMap<String, String>(); checkEmptyLinkedHashMapAssumptions(srcMap); srcMap.put(KEY_1, VALUE_1); srcMap.put(KEY_2, VALUE_2); srcMap.put(KEY_3, VALUE_3); // Make sure that the data is copied correctly LinkedHashMap<String, String> dstMap = new LinkedHashMap<String, String>(); checkEmptyLinkedHashMapAssumptions(dstMap); dstMap.putAll(srcMap); assertEquals(srcMap.size(), dstMap.size()); assertTrue(dstMap.containsKey(KEY_1)); assertTrue(dstMap.containsValue(VALUE_1)); assertFalse(dstMap.containsKey(KEY_1.toUpperCase(Locale.ROOT))); assertFalse(dstMap.containsValue(VALUE_1.toUpperCase(Locale.ROOT))); assertTrue(dstMap.containsKey(KEY_2)); assertTrue(dstMap.containsValue(VALUE_2)); assertFalse(dstMap.containsKey(KEY_2.toUpperCase(Locale.ROOT))); assertFalse(dstMap.containsValue(VALUE_2.toUpperCase(Locale.ROOT))); assertTrue(dstMap.containsKey(KEY_3)); assertTrue(dstMap.containsValue(VALUE_3)); assertFalse(dstMap.containsKey(KEY_3.toUpperCase(Locale.ROOT))); assertFalse(dstMap.containsValue(VALUE_3.toUpperCase(Locale.ROOT))); // Check that an empty map does not blow away the contents of the // destination map LinkedHashMap<String, String> emptyMap = new LinkedHashMap<String, String>(); checkEmptyLinkedHashMapAssumptions(emptyMap); dstMap.putAll(emptyMap); assertTrue(dstMap.size() == srcMap.size()); // Check that put all overwrite any existing mapping in the destination map srcMap.put(KEY_1, VALUE_2); srcMap.put(KEY_2, VALUE_3); srcMap.put(KEY_3, VALUE_1); dstMap.putAll(srcMap); assertEquals(dstMap.size(), srcMap.size()); assertEquals(dstMap.get(KEY_1), VALUE_2); assertEquals(dstMap.get(KEY_2), VALUE_3); assertEquals(dstMap.get(KEY_3), VALUE_1); // Check that a putAll does adds data but does not remove it srcMap.put(KEY_4, VALUE_4); dstMap.putAll(srcMap); assertEquals(dstMap.size(), srcMap.size()); assertTrue(dstMap.containsKey(KEY_4)); assertTrue(dstMap.containsValue(VALUE_4)); assertEquals(dstMap.get(KEY_1), VALUE_2); assertEquals(dstMap.get(KEY_2), VALUE_3); assertEquals(dstMap.get(KEY_3), VALUE_1); assertEquals(dstMap.get(KEY_4), VALUE_4); dstMap.putAll(dstMap); }
From source file:net.yacy.cora.document.id.MultiProtocolURL.java
public MultiProtocolURL(final MultiProtocolURL baseURL, String relPath) throws MalformedURLException { if (baseURL == null) throw new MalformedURLException("base URL is null"); if (relPath == null) throw new MalformedURLException("relPath is null"); this.protocol = baseURL.protocol; this.host = baseURL.host; this.port = baseURL.port; this.userInfo = baseURL.userInfo; if (relPath.startsWith("//")) { // a "network-path reference" as defined in rfc2396 denotes // a relative path that uses the protocol from the base url relPath = baseURL.protocol + ":" + relPath; }/*from w w w. j a v a 2 s .c o m*/ if (relPath.toLowerCase(Locale.ROOT).startsWith("javascript:")) { this.path = baseURL.path; } else if (isHTTP(relPath) || isHTTPS(relPath) || isFTP(relPath) || isFile(relPath) || isSMB(relPath)) { this.path = baseURL.path; } else if (relPath.contains(":") && patternMail.matcher(relPath.toLowerCase(Locale.ROOT)).find()) { // discards also any unknown protocol from previous if throw new MalformedURLException("relative path malformed: " + relPath); } else if (relPath.length() > 0 && relPath.charAt(0) == '/') { this.path = relPath; } else if (baseURL.path.endsWith("/")) { /* According to RFC 3986 example in Appendix B. (https://tools.ietf.org/html/rfc3986) such an URL is valid : http://www.ics.uci.edu/pub/ietf/uri/#Related We also find similar usages in the 2016 URL living standard (https://url.spec.whatwg.org/), for example : https://url.spec.whatwg.org/#syntax-url-absolute-with-fragment java.lang.URL constructor also accepts this form.*/ if (relPath.startsWith("/")) this.path = baseURL.path + relPath.substring(1); else this.path = baseURL.path + relPath; } else { if (relPath.length() > 0 && (relPath.charAt(0) == '#' || relPath.charAt(0) == '?')) { this.path = baseURL.path + relPath; } else { final int q = baseURL.path.lastIndexOf('/'); if (q < 0) { this.path = relPath; } else { this.path = baseURL.path.substring(0, q + 1) + relPath; } } } this.searchpart = baseURL.searchpart; this.anchor = baseURL.anchor; this.path = resolveBackpath(this.path); identAnchor(); identSearchpart(); escape(); }
From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XMLHTTPRequest.java
/** * The real send job./*www . j av a 2s . c om*/ * @param context the current context */ private void doSend(final Context context) { final WebClient wc = getWindow().getWebWindow().getWebClient(); try { final String originHeaderValue = webRequest_.getAdditionalHeaders().get(HEADER_ORIGIN); final boolean crossOriginResourceSharing = originHeaderValue != null; if (crossOriginResourceSharing && isPreflight()) { final WebRequest preflightRequest = new WebRequest(webRequest_.getUrl(), HttpMethod.OPTIONS); // header origin preflightRequest.setAdditionalHeader(HEADER_ORIGIN, originHeaderValue); // header request-method preflightRequest.setAdditionalHeader(HEADER_ACCESS_CONTROL_REQUEST_METHOD, webRequest_.getHttpMethod().name()); // header request-headers final StringBuilder builder = new StringBuilder(); for (final Entry<String, String> header : webRequest_.getAdditionalHeaders().entrySet()) { final String name = header.getKey().toLowerCase(Locale.ROOT); if (isPreflightHeader(name, header.getValue())) { if (builder.length() != 0) { builder.append(REQUEST_HEADERS_SEPARATOR); } builder.append(name); } } preflightRequest.setAdditionalHeader(HEADER_ACCESS_CONTROL_REQUEST_HEADERS, builder.toString()); // do the preflight request final WebResponse preflightResponse = wc.loadWebResponse(preflightRequest); if (!isPreflightAuthorized(preflightResponse)) { setState(STATE_HEADERS_RECEIVED, context); setState(STATE_LOADING, context); setState(STATE_DONE, context); if (LOG.isDebugEnabled()) { LOG.debug("No permitted request for URL " + webRequest_.getUrl()); } Context.throwAsScriptRuntimeEx( new RuntimeException("No permitted \"Access-Control-Allow-Origin\" header.")); return; } } final WebResponse webResponse = wc.loadWebResponse(webRequest_); if (LOG.isDebugEnabled()) { LOG.debug("Web response loaded successfully."); } boolean allowOriginResponse = true; if (crossOriginResourceSharing) { final String value = webResponse.getResponseHeaderValue(HEADER_ACCESS_CONTROL_ALLOW_ORIGIN); allowOriginResponse = originHeaderValue.equals(value); allowOriginResponse = allowOriginResponse || ALLOW_ORIGIN_ALL.equals(value); } if (allowOriginResponse) { webResponse_ = webResponse; } if (allowOriginResponse) { setState(STATE_HEADERS_RECEIVED, context); setState(STATE_LOADING, context); setState(STATE_DONE, context); } else { if (LOG.isDebugEnabled()) { LOG.debug( "No permitted \"Access-Control-Allow-Origin\" header for URL " + webRequest_.getUrl()); } throw new IOException("No permitted \"Access-Control-Allow-Origin\" header."); } } catch (final IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("IOException: returning a network error response.", e); } webResponse_ = new NetworkErrorWebResponse(webRequest_); setState(STATE_HEADERS_RECEIVED, context); setState(STATE_DONE, context); if (!async_) { throw Context.reportRuntimeError("Object not found."); } } }
From source file:com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest.java
/** * Assigns the destination URL, method and other optional attributes of a pending request. * @param method the method to use to send the request to the server (GET, POST, etc) * @param urlParam the URL to send the request to * @param asyncParam Whether or not to send the request to the server asynchronously, defaults to {@code true} * @param user If authentication is needed for the specified URL, the username to use to authenticate * @param password If authentication is needed for the specified URL, the password to use to authenticate *//*from w ww. jav a2s . c o m*/ @JsxFunction public void open(final String method, final Object urlParam, final Object asyncParam, final Object user, final Object password) { if ((urlParam == null || "".equals(urlParam)) && !getBrowserVersion().hasFeature(XHR_OPEN_ALLOW_EMTPY_URL)) { throw Context.reportRuntimeError("URL for XHR.open can't be empty!"); } // async defaults to true if not specified boolean async = true; if (asyncParam != Undefined.instance) { async = ScriptRuntime.toBoolean(asyncParam); } if (!async && getWithCredentials() && getBrowserVersion().hasFeature(XHR_OPEN_WITHCREDENTIALS_TRUE_IN_SYNC_EXCEPTION)) { throw Context.reportRuntimeError( "open() in sync mode is not possible because 'withCredentials' is set to true"); } final String url = Context.toString(urlParam); // (URL + Method + User + Password) become a WebRequest instance. containingPage_ = (HtmlPage) getWindow().getWebWindow().getEnclosedPage(); try { final URL fullUrl = containingPage_.getFullyQualifiedUrl(url); final URL originUrl = containingPage_.getFullyQualifiedUrl(""); if (!isAllowCrossDomainsFor(originUrl, fullUrl)) { throw Context.reportRuntimeError("Access to restricted URI denied"); } final WebRequest request = new WebRequest(fullUrl, getBrowserVersion().getXmlHttpRequestAcceptHeader()); request.setCharset("UTF-8"); request.setAdditionalHeader("Referer", containingPage_.getUrl().toExternalForm()); if (!isSameOrigin(originUrl, fullUrl)) { final StringBuilder origin = new StringBuilder().append(originUrl.getProtocol()).append("://") .append(originUrl.getHost()); if (originUrl.getPort() != -1) { origin.append(':').append(originUrl.getPort()); } request.setAdditionalHeader(HEADER_ORIGIN, origin.toString()); } try { request.setHttpMethod(HttpMethod.valueOf(method.toUpperCase(Locale.ROOT))); } catch (final IllegalArgumentException e) { LOG.info("Incorrect HTTP Method '" + method + "'"); return; } // password is ignored if no user defined final boolean userIsNull = null == user || Undefined.instance == user; if (!userIsNull) { final String userCred = user.toString(); final boolean passwordIsNull = null == password || Undefined.instance == password; String passwordCred = ""; if (!passwordIsNull) { passwordCred = password.toString(); } request.setCredentials(new UsernamePasswordCredentials(userCred, passwordCred)); } webRequest_ = request; } catch (final MalformedURLException e) { LOG.error("Unable to initialize XMLHttpRequest using malformed URL '" + url + "'."); return; } // Async stays a boolean. async_ = async; // Change the state! setState(OPENED, null); }
From source file:com.facebook.share.internal.LikeActionController.java
private static String getCacheKeyForObjectId(String objectId) { String accessTokenPortion = null; AccessToken accessToken = AccessToken.getCurrentAccessToken(); if (accessToken != null) { accessTokenPortion = accessToken.getToken(); }/* w ww . j av a 2s .c om*/ if (accessTokenPortion != null) { // Cache-key collisions are not something to worry about here, since we only store state // for one access token. Even in the case where the previous access tokens serialized // files have not been deleted yet, the objectSuffix will be different due to the access // token change, thus making the key different. accessTokenPortion = Utility.md5hash(accessTokenPortion); } return String.format(Locale.ROOT, "%s|%s|com.fb.sdk.like|%d", objectId, Utility.coerceValueIfNullOrEmpty(accessTokenPortion, ""), objectSuffix); }
From source file:com.google.gwt.emultest.java.util.HashMapTest.java
/** * Test method for 'java.util.HashMap.putAll(Map)'. *//*from w w w .j av a2 s. c o m*/ public void testPutAll() { HashMap<String, String> srcMap = new HashMap<String, String>(); checkEmptyHashMapAssumptions(srcMap); srcMap.put(KEY_1, VALUE_1); srcMap.put(KEY_2, VALUE_2); srcMap.put(KEY_3, VALUE_3); // Make sure that the data is copied correctly HashMap<String, String> dstMap = new HashMap<String, String>(); checkEmptyHashMapAssumptions(dstMap); dstMap.putAll(srcMap); assertEquals(srcMap.size(), dstMap.size()); assertTrue(dstMap.containsKey(KEY_1)); assertTrue(dstMap.containsValue(VALUE_1)); assertFalse(dstMap.containsKey(KEY_1.toUpperCase(Locale.ROOT))); assertFalse(dstMap.containsValue(VALUE_1.toUpperCase(Locale.ROOT))); assertTrue(dstMap.containsKey(KEY_2)); assertTrue(dstMap.containsValue(VALUE_2)); assertFalse(dstMap.containsKey(KEY_2.toUpperCase(Locale.ROOT))); assertFalse(dstMap.containsValue(VALUE_2.toUpperCase(Locale.ROOT))); assertTrue(dstMap.containsKey(KEY_3)); assertTrue(dstMap.containsValue(VALUE_3)); assertFalse(dstMap.containsKey(KEY_3.toUpperCase(Locale.ROOT))); assertFalse(dstMap.containsValue(VALUE_3.toUpperCase(Locale.ROOT))); // Check that an empty map does not blow away the contents of the // destination map HashMap<String, String> emptyMap = new HashMap<String, String>(); checkEmptyHashMapAssumptions(emptyMap); dstMap.putAll(emptyMap); assertTrue(dstMap.size() == srcMap.size()); // Check that put all overwrite any existing mapping in the destination map srcMap.put(KEY_1, VALUE_2); srcMap.put(KEY_2, VALUE_3); srcMap.put(KEY_3, VALUE_1); dstMap.putAll(srcMap); assertEquals(dstMap.size(), srcMap.size()); assertEquals(dstMap.get(KEY_1), VALUE_2); assertEquals(dstMap.get(KEY_2), VALUE_3); assertEquals(dstMap.get(KEY_3), VALUE_1); // Check that a putAll does adds data but does not remove it srcMap.put(KEY_4, VALUE_4); dstMap.putAll(srcMap); assertEquals(dstMap.size(), srcMap.size()); assertTrue(dstMap.containsKey(KEY_4)); assertTrue(dstMap.containsValue(VALUE_4)); assertEquals(dstMap.get(KEY_1), VALUE_2); assertEquals(dstMap.get(KEY_2), VALUE_3); assertEquals(dstMap.get(KEY_3), VALUE_1); assertEquals(dstMap.get(KEY_4), VALUE_4); dstMap.putAll(dstMap); }
From source file:org.apache.manifoldcf.agents.output.amazoncloudsearch.AmazonCloudSearchConnector.java
protected void flushDocuments(IOutputHistoryActivity activities) throws ManifoldCFException, ServiceInterruption { Logging.ingest.info("AmazonCloudSearch: Starting flush to Amazon"); // Repeat until we are empty of cached stuff int chunkNumber = 0; while (true) { DocumentRecord[] records = documentChunkManager.readChunk(serverHost, serverPath, CHUNK_SIZE); try {//from w w w.j av a 2s . c om if (records.length == 0) break; // The records consist of up to 1000 individual input streams, which must be all concatenated together into the post // To do that, we go into and out of Reader space once again... JSONArrayReader arrayReader = new JSONArrayReader(); for (DocumentRecord dr : records) { arrayReader.addArrayElement( new JSONValueReader(new InputStreamReader(dr.getDataStream(), Consts.UTF_8))); } //post data.. String responsbody = postData(new ReaderInputStream(arrayReader, Consts.UTF_8)); // check status String status = getStatusFromJsonResponse(responsbody); if ("success".equals(status)) { // Activity-log the individual documents we sent for (DocumentRecord dr : records) { activities.recordActivity(null, dr.getActivity(), dr.getDataSize(), dr.getUri(), "OK", null); } Logging.ingest.info("AmazonCloudSearch: Successfully sent document chunk " + chunkNumber); //remove documents from table.. documentChunkManager.deleteChunk(records); } else { // Activity-log the individual documents that failed for (DocumentRecord dr : records) { activities.recordActivity(null, dr.getActivity(), dr.getDataSize(), dr.getUri(), "FAILED", responsbody); } Logging.ingest.error("AmazonCloudSearch: Error sending document chunk " + chunkNumber + ": '" + responsbody + "'"); throw new ManifoldCFException( "Received error status from service after feeding document. Response body: '" + responsbody + "'"); } } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) throw e; for (DocumentRecord dr : records) { activities.recordActivity(null, dr.getActivity(), dr.getDataSize(), dr.getUri(), e.getClass().getSimpleName().toUpperCase(Locale.ROOT), e.getMessage()); } throw e; } catch (ServiceInterruption e) { for (DocumentRecord dr : records) { activities.recordActivity(null, dr.getActivity(), dr.getDataSize(), dr.getUri(), e.getClass().getSimpleName().toUpperCase(Locale.ROOT), e.getMessage()); } throw e; } finally { Throwable exception = null; for (DocumentRecord dr : records) { try { dr.close(); } catch (Throwable e) { exception = e; } } if (exception != null) { if (exception instanceof ManifoldCFException) throw (ManifoldCFException) exception; else if (exception instanceof Error) throw (Error) exception; else if (exception instanceof RuntimeException) throw (RuntimeException) exception; else throw new RuntimeException("Unknown exception class thrown: " + exception.getClass().getName() + ": " + exception.getMessage(), exception); } } } }
From source file:onl.area51.httpd.HttpRequestHandlerBuilder.java
static HttpRequestHandlerBuilder create() { return new HttpRequestHandlerBuilder() { private boolean unscoped; private final Map<String, Action> actions = new ConcurrentHashMap<>(); private Map<String, String> links = null; private Logger logger; private Level level; private RequestPredicate requestPredicate; private Predicate<Request> predicate; @Override/*from w w w . j av a2 s .co m*/ public HttpRequestHandlerBuilder unscoped() { unscoped = true; return this; } @Override public HttpRequestHandlerBuilder log(Logger logger, Level level) { this.logger = logger; this.level = level; return this; } @Override public ChainBuilder method(String method) { HttpRequestHandlerBuilder b = this; ChainBuilder c = new ChainBuilder() { private Action action; private RequestPredicate requestPredicate; private Predicate<Request> predicate; @Override public ChainBuilder add(Action action) { Objects.requireNonNull(action); this.action = this.action == null ? action : this.action.andThen(action); return this; } @Override public ChainBuilder filterRequest(RequestPredicate predicate) { requestPredicate = RequestPredicate.and(requestPredicate, predicate); return this; } @Override public ChainBuilder filter(Predicate<Request> predicate) { this.predicate = this.predicate == null ? predicate : this.predicate.and(predicate); return this; } @Override public HttpRequestHandlerBuilder end() { Objects.requireNonNull(action, "No action defined for " + method); actions.merge(method.toUpperCase(Locale.ROOT), action.filterRequest(requestPredicate).filter(predicate), Action::andThen); return b; } }; return c; } @Override public HttpRequestHandlerBuilder filterRequest(RequestPredicate predicate) { requestPredicate = RequestPredicate.and(requestPredicate, predicate); return this; } @Override public HttpRequestHandlerBuilder filter(Predicate<Request> predicate) { this.predicate = this.predicate == null ? predicate : this.predicate.and(predicate); return this; } @Override public HttpRequestHandlerBuilder linkMethod(String method, String substitute) { if (links == null) { links = new HashMap<>(); } String existing = links.putIfAbsent(method.toUpperCase(Locale.ROOT), substitute.toUpperCase(Locale.ROOT)); if (existing != null) { throw new IllegalArgumentException( "Cannot link " + method + " to " + substitute + " as already linked to " + existing); } return this; } @Override public HttpRequestHandler build() { if (links != null && !links.isEmpty()) { links.forEach((m, s) -> { if (actions.containsKey(m)) { throw new IllegalStateException( "Cannot link " + m + " to " + s + " as it has an action defined"); } if (!actions.containsKey(s)) { throw new IllegalStateException( "Cannot link " + m + " to " + s + " as it's target has not been defined"); } actions.put(m, actions.get(s)); }); } // If we have GET defined then link HEAD to it - follows HttpServlet if (actions.containsKey("GET") && !actions.containsKey("HEAD")) { actions.put("HEAD", actions.get("GET")); } Action router = Action.filterRequest(r -> actions .getOrDefault(r.getHttpRequest().getRequestLine().getMethod().toUpperCase(Locale.ROOT), r1 -> Actions.sendError(r1, HttpStatus.SC_METHOD_NOT_ALLOWED, "Method not allowed")) .apply(r), requestPredicate).filter(predicate) // unscoped then set attribute before the action .composeIf(unscoped, () -> r -> r.setAttribute("request.unscoped", true)) // Wrap with the logger .wrapif(logger != null && level != null, a -> new LogAction(logger, level, a)); return (req, resp, ctx) -> { Request request = Request.create(req, resp, ctx); try { router.apply(request); } finally { if (request.isResponsePresent()) { resp.setEntity(request.getResponse().getEntity()); } } }; } }; }