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(RegexValidator authorityValidator, long options) 

Source Link

Document

Initialize a UrlValidator with the given validation options.

Usage

From source file:de.micromata.jira.rest.core.util.URIParser.java

public static URI parseStringToURI(String uri) {
    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);
    if (urlValidator.isValid(uri)) {
        try {//from  www . j  a v a 2  s . co m
            return new URI(uri);
        } catch (URISyntaxException e) {
            return null;
        }
    }
    return null;
}

From source file:com.magnet.plugin.helpers.VerifyHelper.java

public static boolean isValidUrl(String url) {
    String templateURL = url;/*w w  w .  jav  a2 s  . c o m*/
    templateURL = templateURL.replaceAll(Rest2MobileConstants.START_TEMPLATE_VARIABLE_REGEX, "");
    templateURL = templateURL.replaceAll(Rest2MobileConstants.END_TEMPLATE_VARIABLE_REGEX, "");
    UrlValidator urlValidator = new UrlValidator(SUPPORTED_PROTOCOL_SCHEMES, URL_VALIDATION_OPTIONS);
    return urlValidator.isValid(templateURL);
}

From source file:com.coroptis.coidi.rp.services.impl.DiscoverySupportImpl.java

public DiscoverySupportImpl(final HttpService httpService, final XrdsService xrdsService) {
    this.httpService = Preconditions.checkNotNull(httpService);
    this.xrdsService = Preconditions.checkNotNull(xrdsService);
    patternEmail = Pattern.compile(EMAIL_PATTERN);
    patternXri = Pattern.compile(XRI_PATTERN);
    patternDomainSlash = Pattern.compile(DOMAIN_SLASH_PATTERN);
    String[] schemes = { "http", "https" };
    urlValidator = new UrlValidator(schemes,
            UrlValidator.ALLOW_2_SLASHES + UrlValidator.ALLOW_LOCAL_URLS + UrlValidator.NO_FRAGMENTS);
}

From source file:monasca.api.app.command.CreateNotificationMethodCommand.java

public void validate() {
    switch (type) {
    case EMAIL: {
        if (!EmailValidator.getInstance(true).isValid(address))
            throw Exceptions.unprocessableEntity("Address %s is not of correct format", address);
    }//from   w  w w.ja v  a2  s. c o m
        ;
        break;
    case WEBHOOK: {
        String[] schemes = { "http", "https" };
        UrlValidator urlValidator = new UrlValidator(schemes,
                UrlValidator.ALLOW_LOCAL_URLS | UrlValidator.ALLOW_2_SLASHES);
        if (!urlValidator.isValid(address))
            throw Exceptions.unprocessableEntity("Address %s is not of correct format", address);
    }
        ;
        break;
    case PAGERDUTY: {
        // No known validation for PAGERDUTY type at this time
    }
        ;
        break;
    }
}

From source file:com.edduarte.argus.rest.resources.RestV1Resource.java

@POST
@Path("subscribe")
@Consumes(MediaType.APPLICATION_JSON)//  w w  w  .j  a  va 2  s  .  c o  m
@Produces(MediaType.APPLICATION_JSON)
public Response watch(String watchRequestJson) {
    try {
        SubscribeRequest subscribeRequest = new Gson().fromJson(watchRequestJson, SubscribeRequest.class);
        String[] schemes = { "http", "https" };
        UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);

        String documentUrl = subscribeRequest.getDocumentUrl();
        if (documentUrl == null || documentUrl.isEmpty() || !urlValidator.isValid(documentUrl)) {
            ResponseBody responseBody = new ResponseBody(1, "The provided document URL is invalid.");
            return Response.status(400).type(MediaType.APPLICATION_JSON).entity(responseBody.toString())
                    .build();
        }

        String clientUrl = subscribeRequest.getClientUrl();
        if (clientUrl == null || clientUrl.isEmpty() || !urlValidator.isValid(clientUrl)) {
            ResponseBody responseBody = new ResponseBody(2, "The provided client URL is invalid.");
            return Response.status(400).type(MediaType.APPLICATION_JSON).entity(responseBody.toString())
                    .build();
        }

        List<String> keywords = subscribeRequest.getKeywords();
        if (keywords != null) {
            for (Iterator<String> it = keywords.iterator(); it.hasNext();) {
                String k = it.next();
                if (k == null || k.isEmpty()) {
                    it.remove();
                }
            }
        }

        if (keywords == null || keywords.isEmpty()) {
            ResponseBody responseBody = new ResponseBody(3, "You need to provide at least one valid keyword.");
            return Response.status(400).type(MediaType.APPLICATION_JSON).entity(responseBody.toString())
                    .build();
        }

        if (subscribeRequest.getIgnoreAdded() && subscribeRequest.getIgnoreRemoved()) {
            ResponseBody responseBody = new ResponseBody(4,
                    "At least one difference action (added or " + "removed) must not be ignored.");
            return Response.status(400).type(MediaType.APPLICATION_JSON).entity(responseBody.toString())
                    .build();
        }

        Context context = Context.getInstance();
        boolean created = context.createJob(subscribeRequest);
        if (created) {
            ResponseBody responseBody = new ResponseBody(0, "");
            return Response.status(200).type(MediaType.APPLICATION_JSON).entity(responseBody.toString())
                    .build();
        } else {
            ResponseBody responseBody = new ResponseBody(5,
                    "The request conflicts with a currently active watch "
                            + "job, since the provided document URL is "
                            + "already being watched and notified to the " + "provided client URL.");
            return Response.status(409).type(MediaType.APPLICATION_JSON).entity(responseBody.toString())
                    .build();
        }

    } catch (JsonSyntaxException ex) {
        // the job-request json had an invalid format
        ResponseBody responseBody = new ResponseBody(6, "The request body has an invalid format.");
        return Response.status(415).type(MediaType.APPLICATION_JSON).entity(responseBody.toString()).build();
    }
}

From source file:com.github.pjungermann.config.specification.constraint.url.UrlConstraint.java

/**
 * @param key            The key for which this {@link Constraint} gets defined for.
 * @param expectation    The expectation which needs to be fulfilled by the config key's value.
 * @param sourceLine     The {@link SourceLine} at which this expectation got expressed at.
 *//*from   w  ww.ja  v a2 s  . c  o  m*/
public UrlConstraint(@NotNull final String key, @Nullable final Object expectation,
        @NotNull final SourceLine sourceLine) {
    super(key, expectation, sourceLine);

    String[] allowedSchemes;
    try {
        allowedSchemes = configureAllowedSchemes();

    } catch (ClassCastException e) {
        allowedSchemes = null;
    }

    this.validExpectation = this.validExpectation && allowedSchemes != null;
    if (!this.validExpectation) {
        urlValidator = UrlValidator.getInstance();
        return;
    }

    long options = 0L;
    if (allowLocal) {
        options = UrlValidator.ALLOW_LOCAL_URLS;
    }
    if (allowedSchemes.length != 0) {
        urlValidator = new UrlValidator(allowedSchemes, options);

    } else {
        urlValidator = new UrlValidator(options);
    }
}

From source file:com.vmware.identity.openidconnect.protocol.URIUtils.java

public static URI parseURI(String uriString) throws ParseException {
    Validate.notEmpty(uriString, "uriString");

    URI uri;//from ww w .ja v  a 2s .c  om
    try {
        uri = new URI(uriString);
    } catch (URISyntaxException e) {
        throw new ParseException("failed to parse uri", e);
    }

    String[] allowedSchemes = { "https" };
    UrlValidator urlValidator = new UrlValidator(allowedSchemes, UrlValidator.ALLOW_LOCAL_URLS);
    if (!urlValidator.isValid(uri.toString())) {
        throw new ParseException("uri is not a valid https url");
    }

    return uri;
}

From source file:com.sonymobile.jenkins.plugins.mq.mqnotifier.MQNotifierConfig.java

/**
 * Tests connection to the server URI./*from w  w w.  j a  v  a2 s.  c  o m*/
 *
 * @param uri the URI.
 * @param name the user name.
 * @param pw the user password.
 * @return FormValidation object that indicates ok or error.
 * @throws javax.servlet.ServletException Exception for servlet.
 */
public FormValidation doTestConnection(@QueryParameter(SERVER_URI) final String uri,
        @QueryParameter(USERNAME) final String name, @QueryParameter(PASSWORD) final Secret pw)
        throws ServletException {
    UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);
    FormValidation result = FormValidation.ok();
    if (urlValidator.isValid(uri)) {
        try {
            ConnectionFactory conn = new ConnectionFactory();
            conn.setUri(uri);
            if (StringUtils.isNotEmpty(name)) {
                conn.setUsername(name);
                if (StringUtils.isNotEmpty(Secret.toString(pw))) {
                    conn.setPassword(Secret.toString(pw));
                }
            }
            conn.newConnection();
        } catch (URISyntaxException e) {
            result = FormValidation.error("Invalid Uri");
        } catch (PossibleAuthenticationFailureException e) {
            result = FormValidation.error("Authentication Failure");
        } catch (Exception e) {
            result = FormValidation.error(e.getMessage());
        }
    } else {
        result = FormValidation.error("Invalid Uri");

    }
    return result;
}

From source file:com.denimgroup.threadfix.remote.HttpRestUtils.java

@Nonnull
private String makeGetUrl(@Nonnull String path, @Nonnull String params) {
    String baseUrl = propertiesManager.getUrl();

    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);
    if (!urlValidator.isValid(baseUrl)) {
        LOGGER.debug("Base url " + baseUrl + " is not a valid url. Cannot build GET url with path " + path
                + ". Returning null.");
        return null;
    }/*w  w  w  .j  a  va2 s .  co m*/

    String apiKey = propertiesManager.getKey();

    LOGGER.debug("Building GET url with path " + path + " and base url " + baseUrl);

    if (baseUrl.endsWith("/rest") && path.charAt(0) != '/') {
        baseUrl = baseUrl + "/";
    }

    String finishedUrl = baseUrl + path + API_KEY_SEGMENT + apiKey + "&" + params;

    LOGGER.debug("Returning " + finishedUrl);

    return finishedUrl;
}

From source file:com.denimgroup.threadfix.remote.HttpRestUtils.java

@Nonnull
private String makePostUrl(@Nonnull String path) {
    String baseUrl = propertiesManager.getUrl();

    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);
    if (!urlValidator.isValid(baseUrl)) {
        LOGGER.debug("Base url " + baseUrl + " is not a valid url. Cannot build POST url with path " + path
                + ". Returning null.");
        return null;
    }//from  w w w . j  ava 2  s .c om

    LOGGER.debug("Building POST url with path " + path + " and base url " + baseUrl);

    if (baseUrl.endsWith("/rest") && path.charAt(0) != '/') {
        baseUrl = baseUrl + "/";
    }

    LOGGER.debug("Returning " + baseUrl + path);

    return baseUrl + path;
}