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:io.confluent.support.metrics.submitters.ConfluentSubmitter.java

private boolean testEndpointValid(String[] schemes, String endpoint) {
    UrlValidator urlValidator = new UrlValidator(schemes);
    if (urlValidator.isValid(endpoint)) {
        return true;
    } else {// w ww . j a v a  2 s  .  c  o m
        return false;
    }
}

From source file:it.polimi.tower4clouds.rules.actions.RestCall.java

@Override
protected Collection<? extends Problem> validate(MonitoringRule rule, List<MonitoringRule> otherRules) {
    Set<Problem> problems = new HashSet<Problem>();
    Map<String, String> parameters = getParameters();
    String method = parameters.get(METHOD).toUpperCase();
    if (!(method.equals(DELETE) || method.equals(GET) || method.equals(POST) || method.equals(PUT))) {
        problems.add(new Problem(rule.getId(), EnumErrorType.INVALID_ACTION, METHOD,
                "Method parameter must be one of DELETE, GET, POST or PUT"));
    }// www.ja  va2 s.co m
    if (!new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS).isValid(parameters.get(URL))) {
        problems.add(new Problem(rule.getId(), EnumErrorType.INVALID_ACTION, URL,
                "The specified URL is not a valid URL: " + parameters.get(URL)));
    }
    return problems;
}

From source file:com.intel.podm.rest.HttpServletRequestValidator.java

private void validateUrlSyntax(String urlString) throws HttpServletRequestValidationException {
    UrlValidator urlValidator = new UrlValidator(ALLOW_LOCAL_URLS);
    if (!urlValidator.isValid(urlString)) {
        String errorMessage = format("Requested URI %s is not valid", urlString);
        LOGGER.w(errorMessage);//from w w w.  j ava  2  s . c o  m
        throw new HttpServletRequestValidationException(errorMessage, MALFORMED_URI);
    }
}

From source file:com.safestream.sdk.api.video.VideoAPI.java

/**
 * Creates a new video allowing a specific timeout while waiting for the video to downloaded and encoded.
 *
 * This will block until either the video is ingested OR the timeout is reached.
 *
 * @param video {@link Video}//from  w  w w. ja v a 2  s .  c  om
 * @param waitForIngest Time in millis to wait for the video to be ingested
 * @return The newly created video {@link Video}
 * @throws VideoAPIException
 */
public Video create(Video video, long waitForIngest) throws VideoAPIException {

    // We need a source URL before we can ingest the video
    UrlValidator urlValidator = new UrlValidator(new String[] { "http", "https" });
    if (video.getSourceUrl() == null || video.getSourceUrl().isEmpty()
            || !urlValidator.isValid(video.getSourceUrl())) {
        throw new VideoAPIException("Invalid source URL. Cannot ingest video.");
    }

    final String ingestedStatus = "INGESTED";

    try {
        // Make the request to the SafeStream REST API
        Video videoResponse = safeStreamHttpClient.post(apiResourcePath, video).getEntity(Video.class);

        // Wait for the video to be ingested before returning
        // TODO: Have the ingest wait be on a separate thread
        if (waitForIngest > 0 && !ingestedStatus.equals(videoResponse.getStatus())) {
            long startTime = System.currentTimeMillis();
            boolean ingested = false;
            while (!ingested && (System.currentTimeMillis() - startTime) < waitForIngest) {
                Video test = find(video.getKey());
                if (ingestedStatus.equals(videoResponse.getStatus())) {
                    return test;
                }

                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    throw new VideoAPIException("Thread interrupted while waiting for watermarking", e);
                }
            }

            throw new VideoAPIException("Timeout reached waiting for video to be ingested");

        } else {
            return videoResponse;
        }
    } catch (SafeStreamHttpClientException e) {
        throw new VideoAPIException(e);
    }
}

From source file:com.intel.rsa.podm.rest.filters.UrlValidationFilter.java

private boolean isUrlValid(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
    if (String.format("%s %s HTTP/1.1\n\r", httpServletRequest.getMethod(), httpServletRequest.getRequestURL())
            .getBytes(StandardCharsets.UTF_8).length > URL_MAX_LENGTH_IN_BYTES) {
        logger.w("Requested URI exceeds maximum URI length which is set to {} octets", URL_MAX_LENGTH_IN_BYTES);
        setErrorResponse(httpServletResponse, ErrorResponse.URI_TOO_LONG);
        return false;
    }/*  ww  w.j a va2s.c  o  m*/

    String url = httpServletRequest.getRequestURL().toString();
    UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);
    if (urlValidator.isValid(url) && isUrlDecodingPossible(url)) {
        return true;
    } else {
        setErrorResponse(httpServletResponse, ErrorResponse.MALFORMED_URI);
        return false;
    }
}

From source file:it.polimi.tower4clouds.manager.ManagerConfig.java

private ManagerConfig() throws ConfigurationException {
    UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);

    try {//from  w  w w. java 2s  .  c  om
        daPort = Integer
                .parseInt(getEnvVar(Env.MODACLOUDS_TOWER4CLOUDS_DATA_ANALYZER_ENDPOINT_PORT_PUBLIC, "8175"));
        mmPort = Integer.parseInt(getEnvVar(Env.MODACLOUDS_TOWER4CLOUDS_MANAGER_ENDPOINT_PORT, "8170"));
        rdfHistoryDbPort = Integer
                .parseInt(getEnvVar(Env.MODACLOUDS_TOWER4CLOUDS_RDF_HISTORY_DB_ENDPOINT_PORT, "31337"));
    } catch (NumberFormatException e) {
        throw new ConfigurationException("The chosen port is not a valid number");
    }

    daIP = getEnvVar(Env.MODACLOUDS_TOWER4CLOUDS_DATA_ANALYZER_ENDPOINT_IP_PUBLIC, "127.0.0.1");
    mmIP = getEnvVar(Env.MODACLOUDS_TOWER4CLOUDS_MANAGER_ENDPOINT_IP, "127.0.0.1");
    rdfHistoryDbIP = getEnvVar(Env.MODACLOUDS_TOWER4CLOUDS_RDF_HISTORY_DB_ENDPOINT_IP, null);

    if (!validator.isValid(getDaUrl()))
        throw new ConfigurationException(getDaUrl() + " is not a valid URL");

}

From source file:com.formkiq.core.service.formInterceptor.SystemConfigInterceptor.java

/**
 * Validate Host.//from   w ww. j  av  a2 s.  c  o m
 * @param host {@link FormJSONField}
 * @param errors {@link Map}
 */
private void validateHost(final FormJSONField host, final Map<String, String> errors) {

    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes);

    if (!urlValidator.isValid(host.getValue())) {
        errors.put("" + host.getId(), "Invalid URL");
    }
}

From source file:it.polimi.modaclouds.monitoring.monitoring_manager.configuration.ManagerConfig.java

private ManagerConfig() throws ConfigurationException {
    UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);

    try {/*from  ww  w  .j a  v a2s .  c  om*/
        ddaPort = Integer.parseInt(getEnvVar(Env.MODACLOUDS_MONITORING_DDA_ENDPOINT_PORT, "8175"));
        kbPort = Integer.parseInt(getEnvVar(Env.MODACLOUDS_KNOWLEDGEBASE_ENDPOINT_PORT, "3030"));
        mmPort = Integer.parseInt(getEnvVar(Env.MODACLOUDS_MONITORING_MANAGER_PORT, "8170"));
        mmPrivatePort = Integer.parseInt(getEnvVar(Env.MODACLOUDS_MONITORING_MANAGER_PRIVATE_PORT, "8070"));
    } catch (NumberFormatException e) {
        throw new ConfigurationException("The chosen port is not a valid number");
    }

    monitoringMetricsFileName = getEnvVar(Env.MODACLOUDS_MONITORING_MONITORING_METRICS_FILE, null);

    ddaIP = getEnvVar(Env.MODACLOUDS_MONITORING_DDA_ENDPOINT_IP, "127.0.0.1");
    kbIP = getEnvVar(Env.MODACLOUDS_KNOWLEDGEBASE_ENDPOINT_IP, "127.0.0.1");
    mmPrivateIP = getEnvVar(Env.MODACLOUDS_MONITORING_MANAGER_PRIVATE_IP, "127.0.0.1");
    kbPath = getEnvVar(Env.MODACLOUDS_KNOWLEDGEBASE_DATASET_PATH, "/modaclouds/kb");

    ddaUrl = "http://" + ddaIP + ":" + ddaPort;
    kbUrl = "http://" + kbIP + ":" + kbPort + kbPath;
    actionsExecutorUrl = "http://" + mmPrivateIP + ":" + mmPrivatePort + actionsExecutorPath;

    if (!validator.isValid(ddaUrl))
        throw new ConfigurationException(ddaUrl + " is not a valid URL");
    if (!validator.isValid(kbUrl))
        throw new ConfigurationException(kbUrl + " is not a valid URL");

}

From source file:$.ApplicationAction.java

private void validateApplication(Application app, String appname) {
        if (StringUtils.isBlank(app.getDisplayName())) {
            addFieldError("app.displayName", getText("message.application.name.notempty"));
        }//from  w  w w  . j  av a2  s  . co  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:com.pearson.developer.xapi.proxy.SSOServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*ww  w  .j a  va 2  s  .c o m*/
        // verify consumer key
        String ltiKey = this.getInitParameter("ltiConsumerKey");
        if (!ltiKey.equals(request.getParameter("oauth_consumer_key"))) {
            // TODO - consider redirecting to launch_presentation_return_url if present
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        // verify SSO with Basic LTI
        String ssoEndpoint = request.getRequestURL().toString(); // TODO - better to use parameter?
        String ltiSecret = this.getInitParameter("ltiSharedSecret");
        LtiVerificationResult ltiResult = BasicLTIUtil.validateMessage(request, ssoEndpoint, ltiSecret);
        if (!ltiResult.getSuccess()) {
            // TODO - consider redirecting to launch_presentation_return_url if present
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        // load the parameters 
        String activityProvider = request.getParameter("custom_xapi_ap_url");
        String email = request.getParameter("lis_person_contact_email_primary");
        String fullName = request.getParameter("lis_person_name_full");
        String userId = request.getParameter("user_id");

        // validate the incoming data has the expected data
        if (activityProvider == null || activityProvider.trim().length() == 0 || email == null
                || email.trim().length() == 0 || fullName == null || fullName.trim().length() == 0
                || userId == null || userId.trim().length() == 0) {
            // TODO - consider redirecting to launch_presentation_return_url if present
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing Data");
            return;
        }

        // the parameter is passed double encoded, so decode it once more.
        activityProvider = URLDecoder.decode(activityProvider, "UTF-8");

        // validate the incoming data is valid
        try {
            // userId is expected to be numeric for LearningStudio (TODO - change accordingly)
            Long.parseLong(userId);

            // activity provider url must be valid
            UrlValidator urlValidator = new UrlValidator(new String[] { "http", "https" });
            if (!urlValidator.isValid(activityProvider))
                throw new RuntimeException();

            // learner email must be valid
            EmailValidator emailValidator = EmailValidator.getInstance();
            if (!emailValidator.isValid(email))
                throw new RuntimeException();

            // simple name validation (TODO - handle more complex names)
            if (!fullName.matches("[a-zA-Z .,-]+"))
                throw new RuntimeException();
        } catch (Exception e) {
            // TODO - consider redirecting to launch_presentation_return_url if present
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid Data");
            return;
        }

        // generate and save secret for session
        String sessionSecret = UUID.randomUUID().toString();
        SessionDatabase.save(userId, sessionSecret);

        // prepare auth for launch link
        String basicAuth = new String(Base64.encodeBase64((userId + ":" + sessionSecret).getBytes("UTF-8")),
                "UTF-8");
        basicAuth = URLEncoder.encode("Basic " + basicAuth, "UTF-8");

        // prepare endpoint for launch link
        String xapiEndpoint = ssoEndpoint.substring(0, ssoEndpoint.length() - request.getServletPath().length())
                + "/xapi";
        xapiEndpoint = URLEncoder.encode(xapiEndpoint, "UTF-8");

        // prepare actor for launch link
        String actor = "{\"mbox\":\"mailto:" + email + "\",\"name\":\"" + fullName
                + "\",\"objectType\":\"Agent\"}";
        actor = URLEncoder.encode(actor, "UTF-8");

        // append the appropriate first delimiter
        if (activityProvider.indexOf("?") == -1) {
            activityProvider += "?";
        } else {
            activityProvider += "&";
        }

        // add launch link parameters
        activityProvider += "auth=" + basicAuth;
        activityProvider += "&endpoint=" + xapiEndpoint;
        activityProvider += "&actor=" + actor;

        response.sendRedirect(activityProvider);
    } catch (Throwable t) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server Error");
    }
}