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

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

Introduction

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

Prototype

public boolean isValid(String value) 

Source Link

Document

Checks if a field has a valid url address.

Usage

From source file:eu.freme.common.rest.NIFParameterFactory.java

public NIFParameterSet constructFromHttp(String input, String informat, String outformat, String postBody,
        String acceptHeader, String contentTypeHeader, String prefix, String nifVersion,
        boolean allowEmptyInput) throws BadRequestException {

    String thisInput;//from   w  w w .j a v a2s .com
    if (!allowEmptyInput && input == null && postBody == null) {
        throw new BadRequestException("no input found in request");
    } else if (input != null) {
        thisInput = input;
    } else {
        thisInput = postBody;
    }

    String thisInformat;
    if (informat == null && contentTypeHeader == null) {
        thisInformat = TURTLE;
    } else if (informat != null) {
        thisInformat = serializationFormatMapper.get(informat);
        if (thisInformat == null) {
            throw new BadRequestException("parameter informat has invalid value \"" + informat
                    + "\". Please use one of the registered serialization format values: "
                    + serializationFormatMapper.keySet().stream().collect(Collectors.joining(", ")));
        }
    } else {
        String[] contentTypeHeaderParts = contentTypeHeader.split(";");
        thisInformat = serializationFormatMapper.get(contentTypeHeaderParts[0]);
        if (thisInformat == null) {
            throw new BadRequestException("Content-Type header has invalid value \"" + contentTypeHeader
                    + "\". Please use one of the registered serialization format values: "
                    + serializationFormatMapper.keySet().stream().collect(Collectors.joining(", ")));
        }
    }
    if (!RDFConstants.SERIALIZATION_FORMATS.contains(thisInformat)
            && !thisInformat.equals(SerializationFormatMapper.PLAINTEXT)) {
        throw new UnsupportedRDFSerializationException("Parameter informat has invalid value \"" + thisInformat
                + "\". Please use one of: "
                + SERIALIZATION_FORMATS.stream()
                        .map(v -> MapUtils.invertMap(serializationFormatMapper).get(v).toString())
                        .collect(Collectors.joining(", "))
                + " or " + SerializationFormatMapper.PLAINTEXT);
    }

    String thisOutformat;
    if (acceptHeader != null && acceptHeader.equals("*/*")) {
        acceptHeader = TURTLE;
    }
    if (outformat == null && acceptHeader == null) {
        thisOutformat = TURTLE;
    } else if (outformat != null) {
        thisOutformat = serializationFormatMapper.get(outformat);
        if (thisOutformat == null) {
            throw new BadRequestException("Parameter outformat has invalid value \"" + outformat
                    + "\". Please use one of the registered serialization format values: "
                    + serializationFormatMapper.keySet().stream().collect(Collectors.joining(", ")));
        }
    } else {
        thisOutformat = serializationFormatMapper.get(acceptHeader.split(";")[0]);
        if (thisOutformat == null) {
            throw new BadRequestException("Accept header has invalid value \"" + acceptHeader.split(";")[0]
                    + "\". Please use one of the registered serialization format values: "
                    + serializationFormatMapper.keySet().stream().collect(Collectors.joining(", ")));
        }
    }
    if (!RDFConstants.SERIALIZATION_FORMATS.contains(thisOutformat)) {
        throw new UnsupportedRDFSerializationException(
                "Parameter outformat has invalid value \"" + thisOutformat + "\". Please use one of: "
                        + SERIALIZATION_FORMATS.stream()
                                .map(v -> MapUtils.invertMap(serializationFormatMapper).get(v).toString())
                                .collect(Collectors.joining(", ")));
    }

    String thisPrefix;
    if (prefix == null) {
        thisPrefix = getDefaultPrefix();
    } else {
        thisPrefix = prefix;
    }
    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes);
    if (!urlValidator.isValid(thisPrefix)) {
        throw new BadRequestException("invalid prefix");
    }

    if (nifVersion == null) {
        nifVersion = RDFConstants.nifVersion2_0;
    } else if (!(nifVersion.equals(RDFConstants.nifVersion2_0)
            || nifVersion.equals(RDFConstants.nifVersion2_1))) {
        throw new NIFVersionNotSupportedException("NIF version \"" + nifVersion + "\" is not supported");
    }

    return new NIFParameterSet(thisInput, thisInformat, thisOutformat, thisPrefix, nifVersion);
}

From source file:com.pearson.developer.xapi.proxy.SSOServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//from  w  w w . j  a v  a 2 s. c om
        // 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");
    }
}

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   www . j  av  a  2s .  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:ching.icecreaming.action.EditAction.java

public void validate() {
    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes);
    if (StringUtils.isNotBlank(sid)) {
        if (!urlValidator.isValid(sid))
            addFieldError("sid", getText("URL.is.invalid"));
        if (StringUtils.isBlank(uid))
            addFieldError("uid", getText("Username.is.required"));
        if (StringUtils.isBlank(pid))
            addFieldError("pid", getText("Password.cannot.be.empty"));
    }/*  ww  w  . j  a v  a 2 s.c  om*/
}

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

@POST
@Path("subscribe")
@Consumes(MediaType.APPLICATION_JSON)/* ww w .  j  av  a  2  s. com*/
@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.sonymobile.jenkins.plugins.mq.mqnotifier.MQNotifierConfig.java

/**
 * Tests connection to the server URI./*w w w . j a  v  a2s  .c om*/
 *
 * @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 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 a  va  2  s.  c o m*/

    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;
}

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;
    }//from  w  w  w.j  a  va 2  s.c o  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:de.goldbachinteractive.gbi.redirecthandler.client.Error404HandlerServlet.java

/**
 * Splits the given String into a List by means of the specified separator.
 * Converts all elements to lower case, and removes all duplicates. Checks
 * each element for a valid URL.//from  w w  w .  j  ava  2s  . c o  m
 * 
 * @param string
 *            The string to split.
 * @param separator
 *            The separator to use.
 * @return see above
 */
private List<String> getUrlList(String string, String separator) {

    List<String> urls = new ArrayList<String>();
    String[] stringArray = string.split(separator);
    if (stringArray == null || stringArray.length == 0) {
        return urls;
    }

    UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);

    // check duplicates
    for (String currentString : stringArray) {

        if (urlValidator.isValid(currentString) && !urls.contains(currentString)) {
            urls.add(currentString);
        }
    }
    return urls;
}

From source file:checkwebsite.Mainframe.java

public boolean checkURL(String url) {
    String[] schemes = { "http", "https" }; // DEFAULT schemes = "http", "https", "ftp"
    UrlValidator urlValidator = new UrlValidator(schemes);
    return urlValidator.isValid(url);
}