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:de.hybris.platform.b2b.punchout.services.impl.DefaultPunchOutServiceIntegrationTest.java

/**
 * Tests that sending a proper {@link PunchOutSetupRequest} in the form of a parsed from a file cXML object will
 * yield a proper cXML {@link PunchOutSetupResponse}. The operation is 'edit'.
 * //from  w  ww.j a  v a  2 s . c  om
 * @throws FileNotFoundException
 */
@Test
public void testPunchOutSetUpRequestEditOperation() throws FileNotFoundException {
    // sanity check
    CartModel cart = cartService.getSessionCart();
    assertEquals("Before the punchout setup request no items are expected in the cart", 0,
            cart.getEntries().size());

    final CXML requestBody = PunchOutUtils
            .unmarshallCXMLFromFile("b2bpunchout/test/punchoutSetupRequestEditOperation.xml");

    final CXML responseCXml = punchOutService.processPunchOutSetUpRequest(requestBody);

    final CXMLElementBrowser cxmlElementBrowser = new CXMLElementBrowser(responseCXml);
    final Response response = cxmlElementBrowser.findResponse();

    assertNotNull("Response must always exist in the response", response);

    assertEquals("Response code is expected to be success (200)", "200", response.getStatus().getCode());
    final PunchOutSetupResponse punchOutResponse = cxmlElementBrowser
            .findResponseByType(PunchOutSetupResponse.class);
    assertNotNull(punchOutResponse);

    final String url = punchOutResponse.getStartPage().getURL().getvalue();

    assertNotNull("StartPage URL must be part of the response", url);

    assertTrue("Must be a well formed URL", new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS).isValid(url));

    cart = cartService.getSessionCart();
    assertEquals("Expected 3 cart items as the items should match the itemOut elements in the CXML", 3,
            cart.getEntries().size());
}

From source file:com.adobe.sign.utils.validator.ApiValidatorHelper.java

/**
 * Helper function to validate the url passed to it.
 *
 * @param url          The url that needs to be validated.
 * @param sdkErrorCode The error message that needs to be thrown.
 * @throws ApiException//  w  w w .j  a  va 2s  .c  om
 */
public static void validateUrlParameter(String url, SdkErrorCodes sdkErrorCode) throws ApiException {
    UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);
    if (!urlValidator.isValid(url))
        throw new ApiException(sdkErrorCode);
}

From source file:de.hybris.platform.b2b.punchout.services.impl.DefaultPunchOutServiceIntegrationTest.java

/**
 * Tests that getting a {@link ProfileRequest} CXML will yield a proper {@link ProfileResponse} back.
 * //from   w  ww  .  j av a  2s  .co  m
 * @throws FileNotFoundException
 */
@Test
public void testProfileTransactionHappyPath() throws FileNotFoundException {
    final CXML request = PunchOutUtils.unmarshallCXMLFromFile("b2bpunchout/test/sampleProfileRequest.xml");
    final CXML result = punchOutService.processProfileRequest(request);

    final CXMLElementBrowser cxmlElementBrowser = new CXMLElementBrowser(result);
    final ProfileResponse profileResponse = cxmlElementBrowser.findResponseByType(ProfileResponse.class);

    final List<Transaction> transactions = profileResponse.getTransaction();
    assertTrue("At least one supported transaction is expected", CollectionUtils.isNotEmpty(transactions));

    for (final Transaction transaction : transactions) {
        assertNotNull("Request name should never be null", transaction.getRequestName());
        assertTrue("Request name should never be empty", StringUtils.isNotBlank(transaction.getRequestName()));
        assertTrue("Must be a well formed URL",
                new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS).isValid(transaction.getURL().getvalue()));
    }
}

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  ww w .  j  a v  a 2s  .co  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:com.nwn.NwnUpdaterHomeView.java

/**
 * Add server and save it to config/*w ww  .  ja  va  2s  .  c  o m*/
 * Ensure the server name and url are valid and follow the same pattern 
 * that we expect to read from the config
 * @param evt 
 */
private void btnAddServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddServerActionPerformed
    //Regex validation is here to make sure we can read the config later. 
    //this should be changed both here and on the config object
    //todo: enum for regex values
    String newServerName, newServerFileUrl = null;
    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes);
    String nameMessage = "Server Name:\n";
    String urlMessage = "Server File URL:\n";
    do {
        newServerName = (String) JOptionPane.showInputDialog(null, nameMessage, "Add Server",
                JOptionPane.PLAIN_MESSAGE);
        if (newServerName == null) {
            break;
        }
        if (newServerName.contains(",")) {
            nameMessage = "Name cannot have commas:\n";
            newServerName = "";
        }
    } while ((newServerName.length() == 0));
    do {
        if (newServerName == null) {
            break;
        }
        newServerFileUrl = (String) JOptionPane.showInputDialog(null, urlMessage, "Add Server",
                JOptionPane.PLAIN_MESSAGE);
        if (newServerFileUrl == null) {
            break;
        }
        if (!urlValidator.isValid(newServerFileUrl)) {
            urlMessage = "Please Enter Valid Url:\n";
            newServerFileUrl = "";
        }
    } while ((newServerFileUrl.length() == 0));
    if (newServerName != null && newServerFileUrl != null) {
        try {
            ServerInfo newServer = new ServerInfo(newServerName, new URL(newServerFileUrl));
            config.getServerList().add(newServer);
            cmbServerList.addItem(newServer);
            nwnUpdaterConfig.getInstance().save();
        } catch (Exception ex) {
            //            ex.printStackTrace();
            appendOutputText("\nERROR: Unknown error occured, cannot add server: " + newServerName);
        }
    }
}

From source file:io.frictionlessdata.datapackage.Package.java

private JSONObject getDereferencedObject(Object obj)
        throws IOException, FileNotFoundException, MalformedURLException {
    // The JSONObject that will represent the schema.
    JSONObject dereferencedObj = null;/*  w w w  . j ava2s  .c  o  m*/

    // Object is already a dereferences object.
    if (obj instanceof JSONObject) {

        // Don't need to do anything, just cast and return.
        dereferencedObj = (JSONObject) obj;

    } else if (obj instanceof String) {

        // The string value of the given object value.
        String objStr = (String) obj;

        // If object value is Url.
        // Grab the JSON string content of that remote file.
        String[] schemes = { "http", "https" };
        UrlValidator urlValidator = new UrlValidator(schemes);

        if (urlValidator.isValid(objStr)) {

            // Create the dereferenced object from the remote file.
            String jsonContentString = this.getJsonStringContentFromRemoteFile(new URL(objStr));
            dereferencedObj = new JSONObject(jsonContentString);

        } else {
            // If schema is file path.
            File sourceFile = new File(objStr);
            if (sourceFile.exists()) {
                // Create the dereferenced schema object from the local file.
                String jsonContentString = this.getJsonStringContentFromLocalFile(sourceFile.getAbsolutePath());
                dereferencedObj = new JSONObject(jsonContentString);

            } else {
                throw new FileNotFoundException("Local file not found: " + sourceFile);
            }
        }
    }

    return dereferencedObj;
}

From source file:org.ambraproject.wombat.controller.MediaCurationController.java

/**
 * Validate the input from the form/*w ww.j  av  a2 s  .  c om*/
 *
 * @param model data passed in from the view
 * @param link  link pointing to media content relating to the article
 * @param name  name of the user submitting the media curation request
 * @param email email of the user submitting the media curation request
 * @return true if everything is ok
 */

private boolean validateMediaCurationInput(Model model, String link, String name, String email, String title,
        String publishedOn, String consent) throws IOException {

    boolean isValid = true;

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

    if (consent == null || !"true".equals(consent)) {
        model.addAttribute("consentError", "This field is required.");
        isValid = false;
    }

    if (StringUtils.isBlank(link)) {
        model.addAttribute("linkError", "This field is required.");
        isValid = false;
    } else if (!urlValidator.isValid(link)) {
        model.addAttribute("linkError", "Invalid Media link URL");
        isValid = false;
    }

    if (StringUtils.isBlank(name)) {
        model.addAttribute("nameError", "This field is required.");
        isValid = false;
    }

    if (StringUtils.isBlank(title)) {
        model.addAttribute("titleError", "This field is required.");
        isValid = false;
    }

    if (StringUtils.isBlank(publishedOn)) {
        model.addAttribute("publishedOnError", "This field is required.");
        isValid = false;
    } else {
        try {
            LocalDate.parse(publishedOn);
        } catch (DateTimeParseException e) {
            model.addAttribute("publishedOnError", "Invalid Date Format, should be YYYY-MM-DD");
            isValid = false;
        }
    }

    if (StringUtils.isBlank(email)) {
        model.addAttribute("emailError", "This field is required.");
        isValid = false;
    } else if (!EmailValidator.getInstance().isValid(email)) {
        model.addAttribute("emailError", "Invalid e-mail address");
        isValid = false;
    }

    model.addAttribute("isValid", isValid);
    return isValid;
}

From source file:org.apache.cxf.fediz.service.idp.beans.PassiveRequestorValidator.java

public boolean isValid(RequestContext context, String endpointAddress, String realm) throws Exception {
    if (endpointAddress == null) {
        return true;
    }/*from   w w  w  . j  a  v  a  2  s .  co  m*/

    Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(context, "idpConfig");
    Application serviceConfig = idpConfig.findApplication(realm);
    if (serviceConfig == null) {
        LOG.warn("No service config found for " + realm);
        return true;
    }

    // The endpointAddress address must match the passive endpoint requestor constraint 
    // (if it is specified)
    // Also, it must be a valid URL + start with https
    // Validate it first using commons-validator
    UrlValidator urlValidator = new UrlValidator(
            UrlValidator.ALLOW_LOCAL_URLS + UrlValidator.ALLOW_ALL_SCHEMES);
    if (!urlValidator.isValid(endpointAddress)) {
        LOG.warn("The given endpointAddress parameter {} is not a valid URL", endpointAddress);
        return false;
    }

    if (serviceConfig.getCompiledPassiveRequestorEndpointConstraint() == null) {
        LOG.warn("No passive requestor endpoint constraint is configured for the application. "
                + "This could lead to a malicious redirection attack");
        return true;
    }

    Matcher matcher = serviceConfig.getCompiledPassiveRequestorEndpointConstraint().matcher(endpointAddress);
    if (!matcher.matches()) {
        LOG.error("The endpointAddress value of {} does not match any of the passive requestor values",
                endpointAddress);
        return false;
    }

    return true;
}

From source file:org.apache.maven.report.projectinfo.LicenseReport.java

/**
 * @param project not null/*from www.  j a  v  a  2  s . c  om*/
 * @param url     not null
 * @return a valid URL object from the url string
 * @throws IOException if any
 */
protected static URL getLicenseURL(MavenProject project, String url) throws IOException {
    URL licenseUrl;
    UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_ALL_SCHEMES);
    // UrlValidator does not accept file URLs because the file
    // URLs do not contain a valid authority (no hostname).
    // As a workaround accept license URLs that start with the
    // file scheme.
    if (urlValidator.isValid(url) || StringUtils.defaultString(url).startsWith("file://")) {
        try {
            licenseUrl = new URL(url);
        } catch (MalformedURLException e) {
            throw new MalformedURLException(
                    "The license url '" + url + "' seems to be invalid: " + e.getMessage());
        }
    } else {
        File licenseFile = new File(project.getBasedir(), url);
        if (!licenseFile.exists()) {
            // Workaround to allow absolute path names while
            // staying compatible with the way it was...
            licenseFile = new File(url);
        }
        if (!licenseFile.exists()) {
            throw new IOException("Maven can't find the file '" + licenseFile + "' on the system.");
        }
        try {
            licenseUrl = licenseFile.toURI().toURL();
        } catch (MalformedURLException e) {
            throw new MalformedURLException(
                    "The license url '" + url + "' seems to be invalid: " + e.getMessage());
        }
    }

    return licenseUrl;
}

From source file:org.apache.stratos.adc.mgt.cli.StratosApplication.java

/**
 * @return {@code true} if required properties are loaded
 *///from   w w  w .j av a  2s.c o  m
private boolean loadRequiredProperties() {
    if (logger.isDebugEnabled()) {
        logger.debug("Loading properties...");
    }
    // Load properties
    String stratosURL = null;
    String username = null;
    String password = null;

    stratosURL = System.getenv(CliConstants.STRATOS_URL_ENV_PROPERTY);
    username = System.getenv(CliConstants.STRATOS_USERNAME_ENV_PROPERTY);
    password = System.getenv(CliConstants.STRATOS_PASSWORD_ENV_PROPERTY);

    if (StringUtils.isBlank(stratosURL)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Required configuration not found.");
        }
        // Stratos Controller details are not set.
        System.out.format("Could not find required \"%s\" variable in your environment.%n",
                CliConstants.STRATOS_URL_ENV_PROPERTY);
        return false;
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Required configuration found. Validating {}", stratosURL);
        }
        UrlValidator urlValidator = new UrlValidator(new String[] { "https" });
        if (!urlValidator.isValid(stratosURL)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Stratos Controller URL {} is not valid", stratosURL);
            }
            System.out.format(
                    "The \"%s\" variable in your environment is not a valid URL. You have provided \"%s\".%n"
                            + "Please provide the Stratos Controller URL as follows%nhttps://<host>:<port>%n",
                    CliConstants.STRATOS_URL_ENV_PROPERTY, stratosURL);
            return false;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Stratos Controller URL {} is valid.", stratosURL);
            logger.debug("Adding the values to context.");
        }
        context.put(CliConstants.STRATOS_URL_ENV_PROPERTY, stratosURL);
        context.put(CliConstants.STRATOS_USERNAME_ENV_PROPERTY, username);
        context.put(CliConstants.STRATOS_PASSWORD_ENV_PROPERTY, password);
        return true;
    }
}