Example usage for org.apache.commons.validator.routines UrlValidator UrlValidator

List of usage examples for org.apache.commons.validator.routines UrlValidator UrlValidator

Introduction

In this page you can find the example usage for org.apache.commons.validator.routines UrlValidator UrlValidator.

Prototype

public UrlValidator(long options) 

Source Link

Document

Initialize a UrlValidator with the given validation options.

Usage

From source file:org.labkey.trialshare.data.StudyPublicationBean.java

private boolean isValidUrl(String url) {
    return new UrlValidator(new String[] { "http", "https" }).isValid(url);
}

From source file:org.lockss.crawljax.ParameterInterpreter.java

/**
 * Determine if the url is an http or https url.
 *
 * @param urlValue the url to test.//  w  w  w  .j  av a  2 s .c  om
 */
private void checkUrlValidity(String urlValue) {
    String[] schemes = { "http", "https" };
    if (urlValue == null || !new UrlValidator(schemes).isValid(urlValue)) {
        throw new IllegalArgumentException(
                "Invalid URL: " + urlValue + "" + ". Provide a valid URL like http://example.com");
    }
}

From source file:org.meruvian.yama.showcase.action.application.ApplicationAction.java

private void validateApplication(Application app, String appname) {
    if (StringUtils.isBlank(app.getDisplayName())) {
        addFieldError("app.displayName", getText("message.application.name.notempty"));
    }/*from   w ww.j  a  va  2s  .  c o  m*/

    if (StringUtils.isBlank(app.getSite())) {
        addFieldError("app.site", getText("message.application.site.notempty"));
    }

    UrlValidator validator = new UrlValidator(new String[] { "http", "https" });
    if (!validator.isValid(app.getSite())) {
        addFieldError("app.site", getText("message.application.site.notvalid"));
    }
}

From source file:org.mule.modules.validation.ValidationModule.java

/**
 * If the specified <code>url</code> is not a valid one throw an exception.
 * <p/>/*  ww  w .jav a 2s. co  m*/
 * {@sample.xml ../../../doc/mule-module-validation.xml.sample validation:validate-url}
 *
 * @param url                      URL to validate
 * @param allowTwoSlashes          Allow two slashes in the path component of the URL.
 * @param allowAllSchemes          Allows all validly formatted schemes to pass validation instead of supplying a set of valid schemes.
 * @param allowLocalURLs           Allow local URLs, such as http://localhost/ or http://machine/ .
 * @param noFragments              Enabling this options disallows any URL fragments.
 * @param customExceptionClassName Class name of the exception to throw
 * @throws Exception if not valid
 */
@Processor
public void validateUrl(String url, @Optional @Default("false") boolean allowTwoSlashes,
        @Optional @Default("false") boolean allowAllSchemes, @Optional @Default("false") boolean allowLocalURLs,
        @Optional @Default("false") boolean noFragments,
        @Optional @Default("org.mule.modules.validation.InvalidException") String customExceptionClassName)
        throws Exception {
    long options = 0;

    if (allowAllSchemes) {
        options |= UrlValidator.ALLOW_ALL_SCHEMES;
    }
    if (allowTwoSlashes) {
        options |= UrlValidator.ALLOW_2_SLASHES;
    }
    if (allowLocalURLs) {
        options |= UrlValidator.ALLOW_LOCAL_URLS;
    }
    if (noFragments) {
        options |= UrlValidator.NO_FRAGMENTS;
    }

    UrlValidator validator = new UrlValidator(options);

    if (!validator.isValid(url)) {
        throw buildException(customExceptionClassName);
    }
}

From source file:org.orcid.frontend.web.controllers.DeveloperToolsController.java

/**
 * Validates the ssoCredentials object//from   w w w .j av a2s. c o  m
 * 
 * @param ssoCredentials
 * @return true if any error is found in the ssoCredentials object
 * */
private boolean validateSSOCredentials(SSOCredentials ssoCredentials) {
    boolean hasErrors = false;
    Set<RedirectUri> redirectUris = ssoCredentials.getRedirectUris();
    if (PojoUtil.isEmpty(ssoCredentials.getClientName())) {
        if (ssoCredentials.getClientName() == null) {
            ssoCredentials.setClientName(new Text());
        }
        ssoCredentials.getClientName()
                .setErrors(Arrays.asList(getMessage("manage.developer_tools.name_not_empty")));
        hasErrors = true;
    } else if (ssoCredentials.getClientName().getValue().length() > CLIENT_NAME_LENGTH) {
        ssoCredentials.getClientName()
                .setErrors(Arrays.asList(getMessage("manage.developer_tools.name_too_long")));
        hasErrors = true;
    } else if (OrcidStringUtils.hasHtml(ssoCredentials.getClientName().getValue())) {
        ssoCredentials.getClientName().setErrors(Arrays.asList(getMessage("manage.developer_tools.name.html")));
        hasErrors = true;
    } else {
        ssoCredentials.getClientName().setErrors(new ArrayList<String>());
    }

    if (PojoUtil.isEmpty(ssoCredentials.getClientDescription())) {
        if (ssoCredentials.getClientDescription() == null) {
            ssoCredentials.setClientDescription(new Text());
        }
        ssoCredentials.getClientDescription()
                .setErrors(Arrays.asList(getMessage("manage.developer_tools.description_not_empty")));
        hasErrors = true;
    } else if (OrcidStringUtils.hasHtml(ssoCredentials.getClientDescription().getValue())) {
        ssoCredentials.getClientDescription()
                .setErrors(Arrays.asList(getMessage("manage.developer_tools.description.html")));
        hasErrors = true;
    } else {
        ssoCredentials.getClientDescription().setErrors(new ArrayList<String>());
    }

    if (PojoUtil.isEmpty(ssoCredentials.getClientWebsite())) {
        if (ssoCredentials.getClientWebsite() == null) {
            ssoCredentials.setClientWebsite(new Text());
        }
        ssoCredentials.getClientWebsite()
                .setErrors(Arrays.asList(getMessage("manage.developer_tools.website_not_empty")));
        hasErrors = true;
    } else {
        List<String> errors = new ArrayList<String>();
        String[] schemes = { "http", "https", "ftp" };
        UrlValidator urlValidator = new UrlValidator(schemes);
        String websiteString = ssoCredentials.getClientWebsite().getValue();
        if (!urlValidator.isValid(websiteString))
            websiteString = "http://" + websiteString;

        // test validity again
        if (!urlValidator.isValid(websiteString)) {
            errors.add(getMessage("manage.developer_tools.invalid_website"));
        }
        ssoCredentials.getClientWebsite().setErrors(errors);
    }

    if (redirectUris == null || redirectUris.isEmpty()) {
        List<String> errors = new ArrayList<String>();
        errors.add(getMessage("manage.developer_tools.at_least_one"));
        ssoCredentials.setErrors(errors);
        hasErrors = true;
    } else {
        for (RedirectUri redirectUri : redirectUris) {
            List<String> errors = validateRedirectUri(redirectUri);
            if (errors != null) {
                redirectUri.setErrors(errors);
                hasErrors = true;
            }
        }
    }
    return hasErrors;
}

From source file:org.sakaiproject.lrs.expapi.impl.TincanapiLearningResourceStoreProvider.java

/**
 * Read the setup from the configuration. All non-empty values will overwrite any values that may have been set due to DI
 * Values are prefixed with "lrs.[id]." so that multiple versions of this provider can be instantiated based on the id.
 */// www  . j a  v a  2 s. co m
private void readConfig() {
    if (StringUtils.isEmpty(id)) {
        throw new IllegalStateException("Invalid " + id + " for LRS provider, cannot start");
    }

    configPrefix = "lrs." + id + ".";

    String value = serverConfigurationService.getConfig(configPrefix + "url", "");
    url = StringUtils.isNotEmpty(value) ? value : url;

    // ensure the URL is valid and formatted the same way (add "/" if not on the end for example)
    UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);

    if (!urlValidator.isValid(url)) {
        throw new IllegalStateException("Invalid " + id + " LRS provider url (" + url + "), correct the "
                + configPrefix + "url config value");
    } /* won't work with some LRS
      else {
      if (!url.endsWith("/")) {
          url = url + "/";
      }
      }*/

    value = serverConfigurationService.getConfig(configPrefix + "request.timeout", "");

    try {
        timeout = StringUtils.isNotEmpty(value) ? Integer.parseInt(value) : timeout; // allow setter to override
    } catch (NumberFormatException e) {
        timeout = 0;
        logger.debug("{} request.timeout must be an integer value - using default setting", configPrefix, e);
    }

    // basic auth
    value = serverConfigurationService.getConfig(configPrefix + "basicAuthUserPass", "");
    basicAuthString = StringUtils.isNotEmpty(value) ? value : basicAuthString;

    // oauth fields
    value = serverConfigurationService.getConfig(configPrefix + "consumer.key", "");
    consumerKey = StringUtils.isNotEmpty(value) ? value : consumerKey;
    value = serverConfigurationService.getConfig(configPrefix + "consumer.secret", "");
    consumerSecret = StringUtils.isNotEmpty(value) ? value : consumerSecret;
    value = serverConfigurationService.getConfig(configPrefix + "realm", "");
    realm = StringUtils.isNotEmpty(value) ? value : realm;

    if (StringUtils.isEmpty(basicAuthString) && (StringUtils.isEmpty(consumerKey)
            || StringUtils.isEmpty(consumerSecret) || StringUtils.isEmpty(realm))) {
        throw new IllegalStateException(
                "No authentication configured properly for LRS provider, service cannot start. Please check the configuration");
    }
}

From source file:org.sakaiproject.portlets.PortletIFrame.java

public boolean validateURL(String urlToValidate) {
    // return FormattedText.validateURL(urlToValidate); // KNL-1105
    if (StringUtils.isBlank(urlToValidate))
        return false;

    if (ABOUT_BLANK.equals(urlToValidate))
        return true;

    // Check if the url is "Escapable" - run through the URL-URI-URL gauntlet
    String escapedURL = sanitizeHrefURL(urlToValidate);
    if (escapedURL == null)
        return false;

    // For a protocol-relative URL, we validate with protocol attached 
    // RFC 1808 Section 4
    if ((urlToValidate.startsWith("//")) && (urlToValidate.indexOf("://") == -1)) {
        urlToValidate = PROTOCOL_PREFIX + urlToValidate;
    }//from   w  ww  .j  a v a  2  s.  co  m

    // For a site-relative URL, we validate with host name and protocol attached 
    // SAK-13787 SAK-23752
    if ((urlToValidate.startsWith("/")) && (urlToValidate.indexOf("://") == -1)) {
        urlToValidate = HOST_PREFIX + urlToValidate;
    }

    // Validate the url
    UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);
    return urlValidator.isValid(urlToValidate);
}

From source file:org.sakaiproject.util.impl.FormattedTextImpl.java

public boolean validateURL(String urlToValidate) {
    if (StringUtils.isBlank(urlToValidate))
        return false;

    if (ABOUT_BLANK.equals(urlToValidate))
        return true;

    // Check if the url is "Escapable" - run through the URL-URI-URL gauntlet
    String escapedURL = sanitizeHrefURL(urlToValidate);
    if (escapedURL == null)
        return false;

    // For a protocol-relative URL, we validate with protocol attached 
    // RFC 1808 Section 4
    if ((urlToValidate.startsWith("//")) && (urlToValidate.indexOf("://") == -1)) {
        urlToValidate = PROTOCOL_PREFIX + urlToValidate;
    }/*  w w w  . j av a2 s. c  o m*/

    // For a site-relative URL, we validate with host name and protocol attached 
    // SAK-13787 SAK-23752
    if ((urlToValidate.startsWith("/")) && (urlToValidate.indexOf("://") == -1)) {
        urlToValidate = HOST_PREFIX + urlToValidate;
    }

    // Validate the url
    UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);
    return urlValidator.isValid(urlToValidate);
}

From source file:org.slc.sli.api.validation.impl.SimpleURLValidator.java

@Override
public boolean validate(URI url) {
    String[] schemes = { "http", "https" };
    UrlValidator validator = new UrlValidator(schemes);

    return validator.isValid(url.toString());
}

From source file:org.tightblog.rendering.processors.CommentProcessor.java

String validateComment(WeblogEntryComment incomingComment) {
    String errorProperty = null;//from  w w  w  .  j  a v a 2  s  .  co m

    if (StringUtils.isBlank(incomingComment.getContent())) {
        errorProperty = "error.commentPostContentMissing";
    } else if (StringUtils.isBlank(incomingComment.getName())) {
        errorProperty = "error.commentPostNameMissing";
    } else if (StringUtils.isEmpty(incomingComment.getEmail())
            || !incomingComment.getEmail().matches(EMAIL_ADDR_REGEXP)) {
        errorProperty = "error.commentPostFailedEmailAddress";
    } else if (StringUtils.isNotEmpty(incomingComment.getUrl())
            && !new UrlValidator(new String[] { "http", "https" }).isValid(incomingComment.getUrl())) {
        errorProperty = "error.commentPostFailedURL";
    }

    return errorProperty;
}