Example usage for java.net IDN toASCII

List of usage examples for java.net IDN toASCII

Introduction

In this page you can find the example usage for java.net IDN toASCII.

Prototype

public static String toASCII(String input) 

Source Link

Document

Translates a string from Unicode to ASCII Compatible Encoding (ACE), as defined by the ToASCII operation of <a href="http://www.ietf.org/rfc/rfc3490.txt">RFC 3490</a>.

Usage

From source file:com.cnnic.whois.controller.oauth.EchoController.java

/**
 * access query api/*from  www .  j  a  v a 2  s .c om*/
 * @param accessToken
 * @param request
 * @param response
 * @throws Exception
 */
private void accessApi(String accessToken, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    OAuthAccessorBean oauthAccessorBean = oauthAccessorDao.getOAuthAccessorBeanByAccessToken(accessToken);
    AuthenticationHolder.setAuthentication(new Authentication(oauthAccessorBean.getOauth_user_role()));

    for (Object item : request.getParameterMap().entrySet()) {
        Map.Entry parameter = (Map.Entry) item;
        String[] values = (String[]) parameter.getValue();
        for (String value : values) {

            if (value.equals("ip")) {

                String net = "0";
                String ip = StringUtils.trim("1.1.1.1");

                Map<String, Object> resultMap = null;
                IpQueryParam queryParam = super.praseIpQueryParams(request);
                String strInfo = ip;
                if (!ValidateUtils.verifyIP(strInfo, net)) {
                    resultMap = WhoisUtil.processError(WhoisUtil.COMMENDRRORCODE, queryParam);
                    viewResolver.writeResponse(queryParam.getFormat(), queryParam.getQueryType(), request,
                            response, resultMap);
                    return;
                }
                queryParam.setQ(ip);
                queryParam.setIpInfo(strInfo);
                queryParam.setIpLength(Integer.parseInt(net));
                resultMap = queryService.queryIP(queryParam);
                request.setAttribute("queryPara", ip);
                request.setAttribute("queryType", "ip");
                viewResolver.writeResponse(queryParam.getFormat(), queryParam.getQueryType(), request, response,
                        resultMap);
            }
            if (value.equals("domain")) {
                String domainName = StringUtils.trim("z.cn");
                String queryParaPuny = IDN.toASCII(domainName);
                Map<String, Object> resultMap = null;
                QueryParam queryParam = super.praseQueryParams(request);
                if (!ValidateUtils.validateDomainNameIsValidIdna(queryParaPuny)) {
                    resultMap = WhoisUtil.processError(WhoisUtil.COMMENDRRORCODE, queryParam);
                } else {
                    queryParam.setQ(domainName);
                    resultMap = queryService.queryDomain(queryParam);
                    System.err.println(resultMap);
                }
                viewResolver.writeResponse(queryParam.getFormat(), queryParam.getQueryType(), request, response,
                        resultMap);
            }
            if (value.equals("entity")) {
                EntityQueryParam queryParam = super.praseEntityQueryParams(request);
                queryParam.setQ("IBM-1");
                Map<String, Object> resultMap = queryService.queryEntity(queryParam);
                request.setAttribute("queryType", "entity");
                request.setAttribute("queryPara", "IBM-1");
                renderResponse(request, response, resultMap, queryParam);
            }
        }
    }
}

From source file:at.bitfire.davdroid.ui.setup.LoginCredentialsFragment.java

protected LoginCredentials validateLoginData() {
    if (radioUseEmail.isChecked()) {
        URI uri = null;/*  w  w w .  j a v  a  2 s.  c  o  m*/
        boolean valid = true;

        String email = editEmailAddress.getText().toString();
        if (!email.matches(".+@.+")) {
            editEmailAddress.setError(getString(R.string.login_email_address_error));
            valid = false;
        } else
            try {
                uri = new URI("mailto", email, null);
            } catch (URISyntaxException e) {
                editEmailAddress.setError(e.getLocalizedMessage());
                valid = false;
            }

        String password = editEmailPassword.getText().toString();
        if (password.isEmpty()) {
            editEmailPassword.setError(getString(R.string.login_password_required));
            valid = false;
        }

        return valid ? new LoginCredentials(uri, email, password) : null;

    } else if (radioUseURL.isChecked()) {
        URI uri = null;
        boolean valid = true;

        Uri baseUrl = Uri.parse(editBaseURL.getText().toString());
        String scheme = baseUrl.getScheme();
        if ("https".equalsIgnoreCase(scheme) || "http".equalsIgnoreCase(scheme)) {
            String host = baseUrl.getHost();
            if (StringUtils.isEmpty(host)) {
                editBaseURL.setError(getString(R.string.login_url_host_name_required));
                valid = false;
            } else
                try {
                    host = IDN.toASCII(host);
                } catch (IllegalArgumentException e) {
                    Constants.log.log(Level.WARNING, "Host name not conforming to RFC 3490", e);
                }

            String path = baseUrl.getEncodedPath();
            int port = baseUrl.getPort();
            try {
                uri = new URI(baseUrl.getScheme(), null, host, port, path, null, null);
            } catch (URISyntaxException e) {
                editBaseURL.setError(e.getLocalizedMessage());
                valid = false;
            }
        } else {
            editBaseURL.setError(getString(R.string.login_url_must_be_http_or_https));
            valid = false;
        }

        String userName = editUserName.getText().toString();
        if (userName.isEmpty()) {
            editUserName.setError(getString(R.string.login_user_name_required));
            valid = false;
        }

        String password = editUrlPassword.getText().toString();
        if (password.isEmpty()) {
            editUrlPassword.setError(getString(R.string.login_password_required));
            valid = false;
        }

        return valid ? new LoginCredentials(uri, userName, password) : null;
    }

    return null;
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Converts domain to punycode if needed.
 * For ascii domains -- does nothing./*from w  w  w  .  j av  a2 s.c om*/
 *
 * @param domainName Domain name
 * @return Punycode domain name
 */
public static String toPunycode(String domainName) {

    try {
        return IDN.toASCII(domainName);
    } catch (Exception ex) {
        LOG.debug("Cannot convert " + domainName + " to punycode", ex);
    }

    return domainName;
}

From source file:com.jaspersoft.studio.server.protocol.restv2.RestV2ConnectionJersey.java

@Override
public boolean connect(IProgressMonitor monitor, ServerProfile sp) throws Exception {
    monitor.subTask("Trying RESTv2");
    super.connect(monitor, sp);
    this.eh = new RESTv2ExceptionHandler(this);

    ClientConfig clientConfig = new ClientConfig();

    // values are in milliseconds
    // clientConfig.property(ClientProperties.READ_TIMEOUT,
    // sp.getTimeout());
    clientConfig.property(ClientProperties.CONNECT_TIMEOUT, sp.getTimeout());
    if (sp.isChunked())
        clientConfig.property(ClientProperties.CHUNKED_ENCODING_SIZE, 1024);
    clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);

    // config your ssl for apache connector
    SslConfigurator sslConfig = SslConfigurator.newInstance(true);
    clientConfig.property(ApacheClientProperties.SSL_CONFIG, sslConfig);

    PoolingHttpClientConnectionManager cxMgr = new PoolingHttpClientConnectionManager();
    cxMgr.setMaxTotal(50);//from  www.  j  a v a 2s  .  c o  m
    cxMgr.setDefaultMaxPerRoute(20);
    clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, cxMgr);

    // MultiThreadedHttpConnectionManager connectionManager = new
    // MultiThreadedHttpConnectionManager();
    // connectionManager.getParams().setDefaultMaxConnectionsPerHost(20);
    // connectionManager.getParams().setMaxTotalConnections(20);
    // clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER,
    // connectionManager);

    connector = new JSSApacheConnectorFactory();
    clientConfig.connectorProvider(connector);

    // clientConfig.connector(connector);
    HttpUtils.setupProxy(clientConfig, sp.getURL().toURI());

    Client client = ClientBuilder.newBuilder().withConfig(clientConfig).build();
    // client.register(new org.glassfish.jersey.filter.LoggingFilter());
    // client.register(JacksonFeature.class);
    // String user = sp.getUser();
    // if (!Misc.isNullOrEmpty(sp.getOrganisation()))
    // user += "|" + sp.getOrganisation();
    // client.register(new HttpBasicAuthFilter(user,
    // Pass.getPass(sp.getPass())));
    String url = sp.getUrl().trim();
    if (url.endsWith("/services/repository/"))
        url = url.substring(0, url.lastIndexOf("/services/repository/"));
    else if (url.endsWith("services/repository"))
        url = url.substring(0, url.lastIndexOf("/services/repository"));
    if (!url.endsWith("/"))
        url += "/";
    try {
        target = client.target(url + "j_spring_security_check");
        target = target.queryParam("forceDefaultRedirect", "false");
        if (sp.isUseSSO()) {
            String token = CASUtil.getToken(sp, monitor);
            target = target.queryParam("ticket", token);
        } else {
            target = target.queryParam("j_username", sp.getUser());
            target = target.queryParam("j_password", Pass.getPass(sp.getPass()));
        }
        target = target.queryParam("orgId", sp.getOrganisation());
        if (!Misc.isNullOrEmpty(sp.getLocale()))
            target = target.queryParam("userLocale", "true");
        if (!Misc.isNullOrEmpty(sp.getTimeZone()))
            target = target.queryParam("userTimezone", "true");

        Builder req = target.request();
        toObj(connector.get(req, monitor), String.class, monitor);
    } finally {
        // ok, now check others
        target = client.target(IDN.toASCII(url + SUFFIX));
    }
    getServerInfo(monitor);
    return serverInfo != null && serverInfo.getVersion().compareTo("5.5") >= 0;
}

From source file:com.reizes.shiva.utils.CommonUtil.java

/**
 * http  https URL ??  //w ww.jav  a  2 s .c  om
 * @param url
 * @return
 * @throws MalformedURLException 
 */
public static boolean isValidHttpUrl(String url) {
    if (url.length() > 255) { // 255?  url ?  ?
        return false;
    }

    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes);
    if (urlValidator.isValid(url)) {
        return true;
    }

    // ?   ??  
    URL urlTemp;
    try {
        urlTemp = new URL(url);
    } catch (MalformedURLException e) {
        return false;
    }
    String forUnicodeUrl = urlTemp.getProtocol() + "://" + IDN.toASCII(urlTemp.getHost());
    if (urlValidator.isValid(forUnicodeUrl)) {
        // ???  http://.com  www      ? 
        return true;
    }

    String regex = "([a-zA-Z0-9-.\\-&/%=?:#$(),.+;~\\_]+)"; // ?  ??  
    if (urlTemp.getHost().startsWith("\"")) {
        // ?? ? ??  ? URL
        return false;
    } else if (urlTemp.getHost().startsWith(".")) {
        // ?? ? ??  ? URL
        return false;
    } else if (urlTemp.getProtocol().startsWith("http") && urlTemp.getHost().matches(regex)) {
        return true;
    }

    return false;
}

From source file:serposcope.controllers.google.GoogleGroupController.java

@FilterWith({ XSRFFilter.class, AdminFilter.class })
public Result addTarget(Context context, @Param("target-radio") String targetType,
        @Params("name[]") String[] names, @Params("pattern[]") String[] patterns) {
    FlashScope flash = context.getFlashScope();
    Group group = context.getAttribute("group", Group.class);

    if (targetType == null || names == null || names.length == 0 || patterns == null || patterns.length == 0
            || names.length != patterns.length) {
        flash.error("error.invalidParameters");
        return Results.redirect(
                router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
    }/* w ww .  j  a  v  a  2  s  .c o m*/

    Set<GoogleTarget> targets = new HashSet<>();
    for (int i = 0; i < names.length; i++) {
        String name = names[i];
        String pattern = patterns[i];

        if (name != null) {
            name = name.replaceAll("(^\\s+)|(\\s+$)", "");
        }

        if (pattern != null) {
            pattern = pattern.replaceAll("(^\\s+)|(\\s+$)", "");
        }

        if (Validator.isEmpty(name)) {
            flash.error("error.invalidName");
            return Results.redirect(
                    router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
        }

        PatternType type = null;
        try {
            type = PatternType.valueOf(targetType);
        } catch (Exception ex) {
            flash.error("error.invalidTargetType");
            return Results.redirect(
                    router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
        }

        if (PatternType.DOMAIN.equals(type) || PatternType.SUBDOMAIN.equals(type)) {
            try {
                pattern = IDN.toASCII(pattern);
            } catch (Exception ex) {
                pattern = null;
            }
        }

        if (!GoogleTarget.isValidPattern(type, pattern)) {
            flash.error("error.invalidPattern");
            return Results.redirect(
                    router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
        }

        targets.add(new GoogleTarget(group.getId(), name, type, pattern));
    }

    if (googleDB.target.insert(targets) < 1) {
        flash.error("error.internalError");
        return Results.redirect(
                router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
    }
    googleDB.serpRescan.rescan(null, targets, getSearches(context), true);

    Run runningGoogleTask = taskManager.getRunningGoogleTask();
    if (runningGoogleTask != null) {
        flash.put("warning", msg.get("google.group.websiteInsertedWhileRun", context, Optional.absent(),
                runningGoogleTask.getId()).or(""));
    } else {
        flash.success("google.group.websiteInserted");
    }

    return Results
            .redirect(router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
}

From source file:org.jivesoftware.util.StringUtils.java

/**
 * Returns a valid domain name, possibly as an ACE-encoded IDN 
 * (per <a href="http://www.ietf.org/rfc/rfc3490.txt">RFC 3490</a>).
 * /* w  w w . jav  a  2  s .c o m*/
 * @param domain Proposed domain name
 * @return The validated domain name, possibly ACE-encoded
 * @throws IllegalArgumentException The given domain name is not valid
 */
public static String validateDomainName(String domain) {
    if (domain == null || domain.trim().length() == 0) {
        throw new IllegalArgumentException("Domain name cannot be null or empty");
    }
    String result = IDN.toASCII(domain);
    if (result.equals(domain)) {
        // no conversion; validate again via USE_STD3_ASCII_RULES
        IDN.toASCII(domain, IDN.USE_STD3_ASCII_RULES);
    } else {
        Log.info(MessageFormat.format("Converted domain name: from '{0}' to '{1}'", domain, result));
    }
    return result;
}