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

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

Introduction

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

Prototype

public static UrlValidator getInstance() 

Source Link

Document

Returns the singleton instance of this class with default schemes and options.

Usage

From source file:net.sf.authorship.util.AuthorUtil.java

private static boolean isUrl(String input) {
    return UrlValidator.getInstance().isValid(input);
}

From source file:intelligent.wiki.editor.gui.fx.dialogs.ModifyLinkDialog.java

@Override
protected boolean validate(String url) {
    return UrlValidator.getInstance().isValid(url);
}

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  w  w .  ja  va 2s  .  c om
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:by.serzh.beatsub.servers.AddServerController.java

private boolean validate(String host, String username, String password) {
    if (!UrlValidator.getInstance().isValid("http://" + host)) {
        setError("add_server.error_host");
        return false;
    } else if (TextUtils.isBlank(username)) {
        setError("add_server.error_username");
        return false;
    } else if (TextUtils.isBlank(password)) {
        setError("add_server.error_password");
        return false;
    } else {/*ww  w .j  av a2  s.  c  om*/
        return true;
    }
}

From source file:com.denimgroup.threadfix.service.ManualFindingServiceImpl.java

@Override
@Transactional(readOnly = false)/*from   w  w  w  .j av a 2s . c  om*/
public boolean processManualFinding(Finding finding, Integer applicationId) {
    if (finding == null || applicationId == null) {
        log.debug("Null input to processManualFinding");
        return false;
    }

    ChannelType manualChannelType = channelTypeDao.retrieveByName(ScannerType.MANUAL.getDisplayName());

    Scan scan = getManualScan(applicationId);
    if (scan == null || scan.getApplicationChannel() == null || scan.getApplication() == null
            || scan.getFindings() == null) {
        log.debug("processManualFinding could not find or create the necessary manual scan.");
        return false;
    }

    String userName = SecurityContextHolder.getContext().getAuthentication().getName();

    User user = userDao.retrieveByName(userName);
    finding.setUser(user);

    // Set the channelVulnerability
    ChannelVulnerability channelVulnerability = channelVulnerabilityDao.retrieveByCode(manualChannelType,
            finding.getChannelVulnerability().getCode());
    finding.setChannelVulnerability(channelVulnerability);

    if (finding.getChannelSeverity() != null && finding.getChannelSeverity().getId() != null) {
        // Set the channelSeverity so we can get the corresponding
        // genericSeverity when appMerge is called.
        ChannelSeverity channelSeverity = channelSeverityDao.retrieveById(finding.getChannelSeverity().getId());
        finding.setChannelSeverity(channelSeverity);
    } else {
        ChannelSeverity channelSeverity = channelSeverityDao.retrieveByCode(manualChannelType,
                GenericSeverity.MEDIUM);
        finding.setChannelSeverity(channelSeverity);
    }

    if (finding.getSurfaceLocation() == null) {
        finding.setSurfaceLocation(new SurfaceLocation());
    }

    String path = finding.getSurfaceLocation().getPath();

    if (!finding.getIsStatic()) {
        finding.setDataFlowElements(null);

        if (path != null && UrlValidator.getInstance().isValid(path)) {
            try {
                finding.getSurfaceLocation().setUrl(new URL(path));
            } catch (MalformedURLException e) {
                throw new RestIOException(e, "Encountered URL Formatting error.");
            }
        }
    } else {

        // this code is intended to set the path properly when the user imports static scans
        // from different source folders
        // this has been largely replaced by HAM.
        // TODO consider removing this code
        if (path != null && scan.getApplication().getProjectRoot() != null
                && path.toLowerCase().contains(scan.getApplication().getProjectRoot().toLowerCase())) {
            path = path.substring(
                    path.toLowerCase().indexOf(scan.getApplication().getProjectRoot().toLowerCase()));
            finding.getSurfaceLocation().setPath(path);
        }
    }

    if (finding.getIsStatic()) {
        finding.setCalculatedFilePath(finding.getDataFlowElements().get(0).getSourceFileName());
    } else {
        finding.setCalculatedUrlPath(finding.getSurfaceLocation().getPath());
    }

    Scan tempScan = new Scan();
    tempScan.setFindings(listOf(Finding.class));
    tempScan.getFindings().add(finding);
    finding.setScan(scan);
    applicationMerger.applicationMerge(tempScan, applicationId, null);

    scan.getFindings().add(finding);
    if (finding.getId() == null) {
        scan.setNumberTotalVulnerabilities(scan.getNumberTotalVulnerabilities() + 1);
    }

    switch (finding.getChannelSeverity().getCode()) {
    case GenericSeverity.CRITICAL:
        scan.setNumberCriticalVulnerabilities(scan.getNumberCriticalVulnerabilities() + 1);
        break;
    case GenericSeverity.HIGH:
        scan.setNumberHighVulnerabilities(scan.getNumberHighVulnerabilities() + 1);
        break;
    case GenericSeverity.MEDIUM:
        scan.setNumberMediumVulnerabilities(scan.getNumberMediumVulnerabilities() + 1);
        break;
    case GenericSeverity.LOW:
        scan.setNumberLowVulnerabilities(scan.getNumberLowVulnerabilities() + 1);
        break;
    case GenericSeverity.INFO:
        scan.setNumberInfoVulnerabilities(scan.getNumberInfoVulnerabilities() + 1);
        break;
    }

    scanCleanerUtils.clean(scan);

    // Randomly generate NativeId
    if (finding.getNativeId() == null || finding.getNativeId().isEmpty())
        finding.setNativeId(getRandomNativeId());

    vulnerabilityService.storeVulnerability(finding.getVulnerability());

    scanDao.saveOrUpdate(scan);
    log.debug("Manual Finding submission was successful.");
    log.debug(userName + " has added a new finding to the Application "
            + finding.getScan().getApplication().getName());

    vulnerabilityService.updateVulnerabilityReport(applicationDao.retrieveById(applicationId));

    return true;
}

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

/**
 * Helper method that checks the validity of post sign options
 *
 * @param redirectUrl   The redirectUrl that needs to be validated.
 * @param redirectDelay The redirectDelay that needs to be validated.
 * @throws ApiException//ww w.j a va 2 s .c o  m
 */
public static void validatePostSignOptions(String redirectUrl, Integer redirectDelay) throws ApiException {

    if (StringUtil.isEmpty(redirectUrl))
        throw new ApiException(SdkErrorCodes.EMPTY_REDIRECT_URL);

    if (redirectDelay != null && redirectDelay < 0)
        throw new ApiException(SdkErrorCodes.INVALID_REDIRECT_DELAY);

    if (!UrlValidator.getInstance().isValid(redirectUrl))
        throw new ApiException(SdkErrorCodes.INVALID_REDIRECT_URL);
}

From source file:eu.europa.ec.eci.oct.admin.controller.SettingsController.java

@Override
protected String _doPost(Model model, SettingsBean bean, BindingResult result, SessionStatus status,
        HttpServletRequest request, HttpServletResponse response) throws OCTException {
    if (request.getParameter("saveSettings") != null) {
        ConfigurationParameter param;//from  w  ww .ja  v a  2  s. c o m

        // custom logo settings
        if (bean.isDeleteLogo()) {
            param = configurationService.getConfigurationParameter(Parameter.LOGO_PATH);

            // delete file from disk
            final String storagePath = systemManager.getSystemPreferences().getFileStoragePath();
            final File destFolder = new File(storagePath, "/custom");
            final File dest = new File(destFolder, param.getValue());
            dest.delete();

            // update db
            param.setValue(Parameter.LOGO_PATH.getDefaultValue());
            configurationService.updateParameter(param);
        } else {
            final CommonsMultipartFile file = bean.getLogoFile();
            if (file != null && !"".equals(file.getOriginalFilename())) {
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "Uploaded new logo file: " + file.getFileItem().getName() + " / " + file.getSize());
                }

                // validate uploaded logo file
                final Map<MultipartFileValidator.RejectReason, String> rejectDetailsMap = new HashMap<MultipartFileValidator.RejectReason, String>();
                rejectDetailsMap.put(RejectReason.EMPTY_CONTENT, "oct.settings.error.logo.missing");
                rejectDetailsMap.put(RejectReason.EMPTY_NAME, "oct.settings.error.logo.missing");
                rejectDetailsMap.put(RejectReason.BAD_EXTENSION, "oct.settings.error.logo.badExtension");
                rejectDetailsMap.put(RejectReason.MAX_SIZE_EXCEEDED, "oct.settings.error.logo.toobig");

                final Validator validator = new MultipartFileValidator(getCurrentMessageBundle(request),
                        "oct.settings.error.logo.upload", rejectDetailsMap, uploadExtensionWhitelist, 150000);
                validator.validate(file, result);
                if (result.hasErrors()) {
                    return doGet(model, request, response);
                }

                // validation passed, save file to needed location and
                // update the db
                final String storagePath = systemManager.getSystemPreferences().getFileStoragePath();
                final File destFolder = new File(storagePath, "/custom");
                if (!destFolder.exists()) {
                    boolean dirCreated = destFolder.mkdirs();
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "Storage directory \"" + destFolder.getPath() + "\" created? => " + dirCreated);
                    }
                }

                final String extension = file.getOriginalFilename()
                        .substring(file.getOriginalFilename().lastIndexOf('.'));
                final String fileName = new StringBuilder().append("customlogo")
                        .append(System.currentTimeMillis()).append(extension).toString();

                final File dest = new File(destFolder, fileName);
                try {
                    file.transferTo(dest);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Uploaded logo file successfully transfered to the local file "
                                + dest.getAbsolutePath());
                    }
                } catch (IllegalStateException e) {
                    logger.error("illegal state error while uploading logo", e);
                    result.reject("oct.settings.error.logo.upload", "Error uploading logo");
                    return doGet(model, request, response);
                } catch (IOException e) {
                    logger.error("input/output error while uploading logo", e);
                    result.reject("oct.settings.error.logo.upload", e.getMessage());
                    return doGet(model, request, response);
                }

                param = new ConfigurationParameter();
                param.setParam(Parameter.LOGO_PATH.getKey());
                param.setValue(fileName);
                configurationService.updateParameter(param);
            }
        }

        // callback url
        final String callbackUrl = bean.getCallbackUrl();
        if (callbackUrl != null && !"".equals(callbackUrl)) {
            // validate url
            UrlValidator validator = UrlValidator.getInstance();
            if (!validator.isValid(callbackUrl)) {
                result.rejectValue("callbackUrl", "oct.settings.error.callback.invalidurl",
                        "An invalid URL has been specified.");
                return doGet(model, request, response);
            }
        }
        param = new ConfigurationParameter();
        param.setParam(Parameter.CALLBACK_URL.getKey());
        param.setValue(callbackUrl);
        configurationService.updateParameter(param);

        // optional validation
        param = new ConfigurationParameter();
        param.setParam(Parameter.OPTIONAL_VALIDATION.getKey());
        param.setValue(new Boolean(bean.getOptionalValidation()).toString());
        configurationService.updateParameter(param);

        // distribution map
        param = new ConfigurationParameter();
        param.setParam(Parameter.SHOW_DISTRIBUTION_MAP.getKey());
        param.setValue(new Boolean(bean.getDisplayMap()).toString());
        configurationService.updateParameter(param);
    }

    return "redirect:settings.do";
}

From source file:eionet.util.Util.java

/**
 * Checks if the given string is a well-formed URL.
 *///w ww.j  ava  2 s .  co m
public static boolean isURL(String s) {
    return UrlValidator.getInstance().isValid(s);
}

From source file:org.apache.camel.component.cm.CMComponent.java

/**
 * Endpoints factory/* w w  w.j  ava 2 s .c o  m*/
 */
@Override
protected Endpoint createEndpoint(final String uri, final String remaining,
        final Map<String, Object> parameters) throws Exception {

    LOG.info("Creating CM Endpoint ... ");

    final String url = CMConstants.DEFAULT_SCHEME + remaining;
    if (!UrlValidator.getInstance().isValid(url)) {
        final String errorMessage = String
                .format("HOST provided: %s seem to be invalid. Remember SCHEME has to be excluded.", url);
        final Exception t = new InvalidURLException(errorMessage);
        LOG.error(errorMessage, t);
        throw t;
    }

    LOG.info("Uri=[{}], path=[{}], parameters=[{}]",
            new Object[] { URISupport.sanitizeUri(uri), URISupport.sanitizePath(remaining), parameters });

    // Set configuration based on uri parameters
    final CMConfiguration config = new CMConfiguration();
    setProperties(config, parameters);

    // Validate configuration
    LOG.info("Validating uri based configuration");
    final Set<ConstraintViolation<CMConfiguration>> constraintViolations = validator.validate(config);
    if (constraintViolations.size() > 0) {
        final StringBuffer msg = new StringBuffer();
        for (final ConstraintViolation<CMConfiguration> cv : constraintViolations) {
            msg.append(String.format("- Invalid value for %s: %s", cv.getPropertyPath().toString(),
                    cv.getMessage()));
        }
        LOG.error(msg.toString());
        throw new InvalidUriEndpointException(msg.toString());
    }
    LOG.info("CMConfiguration - OK!");

    // Component is an Endpoint factory. So far, just one Endpoint type.
    // Endpoint construction and configuration.

    LOG.info("Creating CMEndpoint");
    final CMEndpoint endpoint = new CMEndpoint(uri, this);
    endpoint.setConfiguration(config);
    endpoint.setHost(remaining);

    return endpoint;
}

From source file:org.apache.metron.common.field.validation.network.URLValidation.java

@Override
public Predicate<Object> getPredicate() {
    return url -> UrlValidator.getInstance().isValid(url == null ? null : url.toString());
}