Example usage for java.util Locale ROOT

List of usage examples for java.util Locale ROOT

Introduction

In this page you can find the example usage for java.util Locale ROOT.

Prototype

Locale ROOT

To view the source code for java.util Locale ROOT.

Click Source Link

Document

Useful constant for the root locale.

Usage

From source file:com.ehsy.solr.util.SimplePostTool.java

/**
 * Computes the full URL based on a base url and a possibly relative link found
 * in the href param of an HTML anchor./*  w w w  .ja  v  a2 s .com*/
 * @param baseUrl the base url from where the link was found
 * @param link the absolute or relative link
 * @return the string version of the full URL
 */
protected String computeFullUrl(URL baseUrl, String link) {
    if (link == null || link.length() == 0) {
        return null;
    }
    if (!link.startsWith("http")) {
        if (link.startsWith("/")) {
            link = baseUrl.getProtocol() + "://" + baseUrl.getAuthority() + link;
        } else {
            if (link.contains(":")) {
                return null; // Skip non-relative URLs
            }
            String path = baseUrl.getPath();
            if (!path.endsWith("/")) {
                int sep = path.lastIndexOf("/");
                String file = path.substring(sep + 1);
                if (file.contains(".") || file.contains("?"))
                    path = path.substring(0, sep);
            }
            link = baseUrl.getProtocol() + "://" + baseUrl.getAuthority() + path + "/" + link;
        }
    }
    link = normalizeUrlEnding(link);
    String l = link.toLowerCase(Locale.ROOT);
    // Simple brute force skip images
    if (l.endsWith(".jpg") || l.endsWith(".jpeg") || l.endsWith(".png") || l.endsWith(".gif")) {
        return null; // Skip images
    }
    return link;
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.java

/**
 * {@inheritDoc}//  w  ww. j  a v a 2  s  . com
 */
@Override
public String getLocalName() {
    final DomNode domNode = getDomNodeOrDie();
    if (domNode.getHtmlPageOrNull() != null) {
        final String prefix = domNode.getPrefix();
        if (prefix != null) {
            // create string builder only if needed (performance)
            final StringBuilder localName = new StringBuilder(prefix.toLowerCase(Locale.ROOT));
            localName.append(':');
            localName.append(domNode.getLocalName().toLowerCase(Locale.ROOT));
            return localName.toString();
        }
        return domNode.getLocalName().toLowerCase(Locale.ROOT);
    }
    return domNode.getLocalName();
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest.java

/**
 * The real send job.//  w w w  . j a v a 2  s .  c  o  m
 * @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(HEADERS_RECEIVED, context);
                setState(LOADING, context);
                setState(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) {
            String value = webResponse.getResponseHeaderValue(HEADER_ACCESS_CONTROL_ALLOW_ORIGIN);
            allowOriginResponse = originHeaderValue.equals(value);
            if (getWithCredentials()) {
                allowOriginResponse = allowOriginResponse
                        || (getBrowserVersion().hasFeature(XHR_WITHCREDENTIALS_ALLOW_ORIGIN_ALL)
                                && ALLOW_ORIGIN_ALL.equals(value));

                // second step: check the allow-credentials header for true
                value = webResponse.getResponseHeaderValue(HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS);
                allowOriginResponse = allowOriginResponse && Boolean.parseBoolean(value);
            } else {
                allowOriginResponse = allowOriginResponse || ALLOW_ORIGIN_ALL.equals(value);
            }
        }
        if (allowOriginResponse) {
            if (overriddenMimeType_ == null) {
                webResponse_ = webResponse;
            } else {
                final int index = overriddenMimeType_.toLowerCase(Locale.ROOT).indexOf("charset=");
                String charsetString = "";
                if (index != -1) {
                    charsetString = overriddenMimeType_.substring(index + "charset=".length());
                }
                final String charset;
                if (!charsetString.isEmpty()) {
                    charset = charsetString;
                } else {
                    charset = null;
                }
                webResponse_ = new WebResponseWrapper(webResponse) {
                    @Override
                    public String getContentType() {
                        return overriddenMimeType_;
                    }

                    @Override
                    public String getContentCharset() {
                        if (charset != null) {
                            return charset;
                        }
                        return super.getContentCharset();
                    }
                };
            }
        }
        if (allowOriginResponse) {
            setState(HEADERS_RECEIVED, context);
            setState(LOADING, context);
            setState(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(HEADERS_RECEIVED, context);
        setState(DONE, context);
        if (async_) {
            processError(context);
        } else {
            Context.throwAsScriptRuntimeEx(e);
        }
    }
}

From source file:com.stratelia.silverpeas.silvertrace.SilverTrace.java

/**
 * Reset all modules, messages, appenders and all set debug levels.
 *//*from   w  w  w .j a  v a2 s. c  o  m*/
static public void resetAll() {

    availableModules.clear();
    // Reset all appenders and debug levels
    Logger.getRootLogger().getLoggerRepository().resetConfiguration();
    Logger.getRootLogger().setAdditivity(true);
    Logger.getRootLogger().setLevel(Level.ERROR);
    ResourceBundle resources = FileUtil.loadBundle("org.silverpeas.silvertrace.settings.silverTrace",
            Locale.ROOT);
    String pathFiles = resources.getString("pathSilverTrace");
    String languageMessage = resources.getString("language");
    errorDir = resources.getString("ErrorDir");
    // Load the available messages
    traceMessages.initFromProperties(pathFiles, languageMessage);
    // Get available modules
    List<File> theFiles = traceMessages.getPropertyFiles(pathFiles, "");
    for (File theFile : theFiles) {
        InputStream is = null;
        try {
            is = new FileInputStream(theFile);
            Properties currentFileProperties = new Properties();
            currentFileProperties.load(is);
            initFromProperties(currentFileProperties);
        } catch (IOException e) {
            if (initFinished) {
                SilverTrace.error("silvertrace", "SilverTrace.resetAll()",
                        "silvertrace.ERR_INIT_TRACE_FROM_PROP", "File:[" + theFile.getAbsolutePath() + "]", e);
            } else {
                emergencyTrace("Error in SilverTrace initialization : Cant load property file : '"
                        + theFile.getAbsolutePath() + "'", e);
            }
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:com.stratelia.webactiv.yellowpages.control.YellowpagesSessionController.java

/**
 * @param query/*w w w  .j a  v  a2s.c om*/
 * @return list of UserCompleteContact
 * @throws PublicationTemplateException
 * @throws FormException
 */
private List<UserCompleteContact> searchCompleteUsers(String query)
        throws PublicationTemplateException, FormException {
    String searchQuery = query.toLowerCase(Locale.ROOT);
    Iterator<UserCompleteContact> it = this.currentCompleteUsers.iterator();
    List<UserCompleteContact> result = new ArrayList<UserCompleteContact>();
    UserCompleteContact userComplete;

    String xmlFormName;
    String xmlFormShortName;
    PublicationTemplate pubTemplate;
    RecordSet recordSet;
    DataRecord data;
    String fieldName;
    Field field;
    String value;
    while (it.hasNext()) {
        userComplete = it.next();
        ContactDetail detail = userComplete.getContact().getContactDetail();
        if (StringUtil.isDefined(detail.getFirstName())
                && detail.getFirstName().toLowerCase().indexOf(searchQuery) != -1) {
            result.add(userComplete);
        } else if (StringUtil.isDefined(detail.getLastName())
                && detail.getLastName().toLowerCase().indexOf(searchQuery) != -1) {
            result.add(userComplete);
        } else if (StringUtil.isDefined(userComplete.getContact().getContactDetail().getEmail())) {
            if (userComplete.getContact().getContactDetail().getEmail().toLowerCase()
                    .indexOf(searchQuery) != -1) {
                result.add(userComplete);
            }
        } else if (StringUtil.isDefined(userComplete.getContact().getContactDetail().getPhone())) {
            if (userComplete.getContact().getContactDetail().getPhone().toLowerCase()
                    .indexOf(searchQuery) != -1) {
                result.add(userComplete);
            }
        } else if (StringUtil.isDefined(userComplete.getContact().getContactDetail().getFax())) {
            if (userComplete.getContact().getContactDetail().getFax().toLowerCase()
                    .indexOf(searchQuery) != -1) {
                result.add(userComplete);
            }
        } else if (userComplete.getContact().getModelId().endsWith(".xml")) {
            // Recherche sur les infos XML
            xmlFormName = userComplete.getContact().getModelId();
            xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf("."));

            // recuperation des donnees du formulaire (via le DataRecord)
            pubTemplate = getPublicationTemplateManager()
                    .getPublicationTemplate(getComponentId() + ":" + xmlFormShortName);

            recordSet = pubTemplate.getRecordSet();
            data = recordSet.getRecord(userComplete.getContact().getContactDetail().getPK().getId());
            if (data != null) {
                for (int i = 0; i < data.getFieldNames().length; i++) {
                    fieldName = data.getFieldNames()[i];
                    field = data.getField(fieldName);
                    value = field.getStringValue();
                    if (value != null && value.toLowerCase().indexOf(searchQuery) != -1) {
                        result.add(userComplete);
                        break;
                    }
                }
            }
        }
    }
    return result;
}

From source file:com.gargoylesoftware.htmlunit.util.EncodingSniffer.java

/**
 * Attempts to sniff an encoding from an HTML <tt>meta</tt> tag in the specified byte array.
 *
 * @param bytes the bytes to check for an HTML <tt>meta</tt> tag
 * @return the encoding sniffed from the specified bytes, or {@code null} if the encoding
 *         could not be determined//ww w  .ja  v a 2 s .  c om
 */
static String sniffEncodingFromMetaTag(final byte[] bytes) {
    for (int i = 0; i < bytes.length; i++) {
        if (matches(bytes, i, COMMENT_START)) {
            i = indexOfSubArray(bytes, new byte[] { '-', '-', '>' }, i);
            if (i == -1) {
                break;
            }
            i += 2;
        } else if (matches(bytes, i, META_START)) {
            i += META_START.length;
            for (Attribute att = getAttribute(bytes, i); att != null; att = getAttribute(bytes, i)) {
                i = att.getUpdatedIndex();
                final String name = att.getName();
                final String value = att.getValue();
                if ("charset".equals(name) || "content".equals(name)) {
                    String charset = null;
                    if ("charset".equals(name)) {
                        charset = value;
                    } else if ("content".equals(name)) {
                        charset = extractEncodingFromContentType(value);
                        if (charset == null) {
                            continue;
                        }
                    }
                    if (UTF16_BE.equalsIgnoreCase(charset) || UTF16_LE.equalsIgnoreCase(charset)) {
                        charset = UTF8;
                    }
                    if (isSupportedCharset(charset)) {
                        charset = charset.toUpperCase(Locale.ROOT);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Encoding found in meta tag: '" + charset + "'.");
                        }
                        return charset;
                    }
                }
            }
        } else if (i + 1 < bytes.length && bytes[i] == '<' && Character.isLetter(bytes[i + 1])) {
            i = skipToAnyOf(bytes, i, new byte[] { 0x09, 0x0A, 0x0C, 0x0D, 0x20, 0x3E });
            if (i == -1) {
                break;
            }
            Attribute att;
            while ((att = getAttribute(bytes, i)) != null) {
                i = att.getUpdatedIndex();
            }
        } else if (i + 2 < bytes.length && bytes[i] == '<' && bytes[i + 1] == '/'
                && Character.isLetter(bytes[i + 2])) {
            i = skipToAnyOf(bytes, i, new byte[] { 0x09, 0x0A, 0x0C, 0x0D, 0x20, 0x3E });
            if (i == -1) {
                break;
            }
            Attribute attribute;
            while ((attribute = getAttribute(bytes, i)) != null) {
                i = attribute.getUpdatedIndex();
            }
        } else if (matches(bytes, i, OTHER_START)) {
            i = skipToAnyOf(bytes, i, new byte[] { 0x3E });
            if (i == -1) {
                break;
            }
        }
    }
    return null;
}

From source file:net.yacy.yacy.java

/**
 * Main-method which is started by java. Checks for special arguments or
 * starts up the application./*from  w  w  w. j a v  a  2 s.co m*/
 *
 * @param args
 *            Given arguments from the command line.
 */
public static void main(String args[]) {

    try {
        // check assertion status
        //ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
        boolean assertionenabled = false;
        assert (assertionenabled = true) == true; // compare to true to remove warning: "Possible accidental assignement"
        if (assertionenabled)
            System.out.println("Asserts are enabled");

        // check memory amount
        System.gc();
        final long startupMemFree = MemoryControl.free();
        final long startupMemTotal = MemoryControl.total();

        // maybe go into headless awt mode: we have three cases depending on OS and one exception:
        // windows   : better do not go into headless mode
        // mac       : go into headless mode because an application is shown in gui which may not be wanted
        // linux     : go into headless mode because this does not need any head operation
        // exception : if the -gui option is used then do not go into headless mode since that uses a gui
        boolean headless = true;
        if (OS.isWindows)
            headless = false;
        if (args.length >= 1 && args[0].toLowerCase(Locale.ROOT).equals("-gui"))
            headless = false;
        System.setProperty("java.awt.headless", headless ? "true" : "false");

        String s = "";
        for (final String a : args)
            s += a + " ";
        yacyRelease.startParameter = s.trim();

        File applicationRoot = new File(System.getProperty("user.dir").replace('\\', '/'));
        File dataRoot = applicationRoot;
        //System.out.println("args.length=" + args.length);
        //System.out.print("args=["); for (int i = 0; i < args.length; i++) System.out.print(args[i] + ", "); System.out.println("]");
        if ((args.length >= 1)
                && (args[0].toLowerCase(Locale.ROOT).equals("-startup") || args[0].equals("-start"))) {
            // normal start-up of yacy
            if (args.length > 1) {
                if (args[1].startsWith(File.separator)) {
                    /* data root folder provided as an absolute path */
                    dataRoot = new File(args[1]);
                } else {
                    /* data root folder provided as a path relative to the user home folder */
                    dataRoot = new File(System.getProperty("user.home").replace('\\', '/'), args[1]);
                }
            }
            preReadSavedConfigandInit(dataRoot);
            startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, false);
        } else if (args.length >= 1 && args[0].toLowerCase(Locale.ROOT).equals("-gui")) {
            // start-up of yacy with gui
            if (args.length > 1) {
                if (args[1].startsWith(File.separator)) {
                    /* data root folder provided as an absolute path */
                    dataRoot = new File(args[1]);
                } else {
                    /* data root folder provided as a path relative to the user home folder */
                    dataRoot = new File(System.getProperty("user.home").replace('\\', '/'), args[1]);
                }
            }
            preReadSavedConfigandInit(dataRoot);
            startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, true);
        } else if ((args.length >= 1)
                && ((args[0].toLowerCase(Locale.ROOT).equals("-shutdown")) || (args[0].equals("-stop")))) {
            // normal shutdown of yacy
            if (args.length == 2)
                applicationRoot = new File(args[1]);
            shutdown(applicationRoot);
        } else if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-update"))) {
            // aut-update yacy
            if (args.length == 2)
                applicationRoot = new File(args[1]);
            update(applicationRoot);
        } else if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-version"))) {
            // show yacy version
            System.out.println(copyright);
        } else if ((args.length > 1) && (args[0].toLowerCase(Locale.ROOT).equals("-config"))) {
            // set config parameter. Special handling of adminAccount=user:pwd (generates md5 encoded password)
            // on Windows parameter should be enclosed in doublequotes to accept = sign (e.g. -config "port=8090" "port.ssl=8043")
            File f = new File(dataRoot, "DATA/SETTINGS/");
            if (!f.exists()) {
                mkdirsIfNeseccary(f);
            } else {
                if (new File(dataRoot, "DATA/yacy.running").exists()) {
                    System.out.println("please restart YaCy");
                }
            }
            // use serverSwitch to read config properties (including init values from yacy.init
            serverSwitch ss = new serverSwitch(dataRoot, applicationRoot, "defaults/yacy.init",
                    "DATA/SETTINGS/yacy.conf");

            for (int icnt = 1; icnt < args.length; icnt++) {
                String cfg = args[icnt];
                int pos = cfg.indexOf('=');
                if (pos > 0) {
                    String cmd = cfg.substring(0, pos);
                    String val = cfg.substring(pos + 1);

                    if (!val.isEmpty()) {
                        if (cmd.equalsIgnoreCase(SwitchboardConstants.ADMIN_ACCOUNT)) { // special command to set adminusername and md5-pwd
                            int cpos = val.indexOf(':'); //format adminAccount=adminname:adminpwd
                            if (cpos >= 0) {
                                String username = val.substring(0, cpos);
                                String pwdtxt = val.substring(cpos + 1);
                                if (!username.isEmpty()) {
                                    ss.setConfig(SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME, username);
                                    System.out.println("Set property "
                                            + SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME + " = " + username);
                                } else {
                                    username = ss.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME,
                                            "admin");
                                }
                                ss.setConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5,
                                        "MD5:" + Digest.encodeMD5Hex(username + ":"
                                                + ss.getConfig(SwitchboardConstants.ADMIN_REALM, "YaCy") + ":"
                                                + pwdtxt));
                                System.out.println("Set property " + SwitchboardConstants.ADMIN_ACCOUNT_B64MD5
                                        + " = " + ss.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, ""));
                            }
                        } else {
                            ss.setConfig(cmd, val);
                            System.out.println("Set property " + cmd + " = " + val);
                        }
                    }
                } else {
                    System.out.println(
                            "skip parameter " + cfg + " (equal sign missing, put parameter in doublequotes)");
                }
                System.out.println();
            }
        } else {
            if (args.length == 1) {
                applicationRoot = new File(args[0]);
            }
            preReadSavedConfigandInit(dataRoot);
            startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, false);
        }
    } finally {
        ConcurrentLog.shutdown();
    }
}

From source file:org.elasticsearch.client.RequestConverters.java

private static Request resize(ResizeRequest resizeRequest) throws IOException {
    String endpoint = new EndpointBuilder().addPathPart(resizeRequest.getSourceIndex())
            .addPathPartAsIs("_" + resizeRequest.getResizeType().name().toLowerCase(Locale.ROOT))
            .addPathPart(resizeRequest.getTargetIndexRequest().index()).build();
    Request request = new Request(HttpPut.METHOD_NAME, endpoint);

    Params params = new Params(request);
    params.withTimeout(resizeRequest.timeout());
    params.withMasterTimeout(resizeRequest.masterNodeTimeout());
    params.withWaitForActiveShards(resizeRequest.getTargetIndexRequest().waitForActiveShards());

    request.setEntity(createEntity(resizeRequest, REQUEST_BODY_CONTENT_TYPE));
    return request;
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

/**
 * Get Mime type from the response header
 * @return mime type (trimmed and lower cased) or null when not specified
 *//* ww w.ja  v  a  2 s . c  o  m*/
public String getMimeType() {
    String mimeType = null;
    if (this.httpResponse != null) {

        Header contentType = this.httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE);

        if (contentType != null) {

            mimeType = contentType.getValue();

            if (mimeType != null) {
                mimeType = mimeType.trim().toLowerCase(Locale.ROOT);

                final int pos = mimeType.indexOf(';');
                if (pos >= 0) {
                    mimeType = mimeType.substring(0, pos);
                }
            }
        }
    }
    return mimeType;
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlPage.java

/**
 * Returns all the HTML elements that are assigned to the specified access key. An
 * access key (aka mnemonic key) is used for keyboard navigation of the
 * page.<p>/*from  www .ja  v a 2s  .com*/
 *
 * The HTML specification seems to indicate that one accesskey cannot be used
 * for multiple elements however Internet Explorer does seem to support this.
 * It's worth noting that Mozilla does not support multiple elements with one
 * access key so you are making your HTML browser specific if you rely on this
 * feature.<p>
 *
 * Only the following HTML elements may have <tt>accesskey</tt>s defined: A, AREA,
 * BUTTON, INPUT, LABEL, LEGEND, and TEXTAREA.
 *
 * @param accessKey the key to look for
 * @return the elements that are assigned to the specified accesskey
 */
public List<HtmlElement> getHtmlElementsByAccessKey(final char accessKey) {
    final List<HtmlElement> elements = new ArrayList<>();

    final String searchString = Character.toString(accessKey).toLowerCase(Locale.ROOT);
    for (final HtmlElement element : getHtmlElementDescendants()) {
        if (ACCEPTABLE_TAG_NAMES.contains(element.getTagName())) {
            final String accessKeyAttribute = element.getAttribute("accesskey");
            if (searchString.equalsIgnoreCase(accessKeyAttribute)) {
                elements.add(element);
            }
        }
    }

    return elements;
}