List of usage examples for org.apache.commons.validator.routines InetAddressValidator getInstance
public static InetAddressValidator getInstance()
From source file:org.cloudsimulator.validator.URLValidator.java
@Override public void validate(final FacesContext facesContext, final UIComponent uiComponent, final Object value) { String ipAddress;/*from ww w. j av a 2s . co m*/ int port = 0; if (((String) value).contains(":")) { ipAddress = ((String) value).substring(0, ((String) value).indexOf(':')); port = Integer.parseInt(((String) value).substring(((String) value).indexOf(':') + 1)); if (port < 0 || port > 65535) { FacesMessage facesMessage = new FacesMessage(); String message = "The port number is invalid!"; facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR); facesMessage.setSummary(message); facesMessage.setDetail(message); throw new ValidatorException(facesMessage); } } else { ipAddress = ((String) value); } if (ipAddress.matches("^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$")) { if (!InetAddressValidator.getInstance().isValidInet4Address(ipAddress)) { FacesMessage facesMessage = new FacesMessage(); String message = "The string inserted is not a valid IP Address!"; facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR); facesMessage.setSummary(message); facesMessage.setDetail(message); throw new ValidatorException(facesMessage); } } else { if (!UrlValidator.getInstance().isValid("http://" + ipAddress) && !"localhost".equals(ipAddress)) { FacesMessage facesMessage = new FacesMessage(); String message = "The string inserted is not a valid URL!"; facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR); facesMessage.setSummary(message); facesMessage.setDetail(message); throw new ValidatorException(facesMessage); } } }
From source file:org.codice.alliance.video.security.validator.videographer.VideographerValidator.java
private boolean validIpAddress(String address) { String processedAddress = address.split("%")[0]; LOGGER.debug("checking address: {}", address); return InetAddressValidator.getInstance().isValid(processedAddress); }
From source file:org.epics.archiverappliance.config.DefaultConfigService.java
@Override public void initialize(ServletContext sce) throws ConfigException { this.servletContext = sce; String contextPath = sce.getContextPath(); logger.info("DefaultConfigService was created with a servlet context " + contextPath); try {/*from ww w .ja v a 2 s . co m*/ String pathToVersionTxt = sce.getRealPath("ui/comm/version.txt"); logger.debug("The full path to the version.txt is " + pathToVersionTxt); List<String> lines = Files.readAllLines(Paths.get(pathToVersionTxt), Charset.forName("UTF-8")); for (String line : lines) { configlogger.info(line); } } catch (Throwable t) { logger.fatal("Unable to determine appliance version", t); } try { // We first try Java system properties for this appliance's identity // If a property is not defined, then we check the environment. // This gives us the ability to cater to unit tests as well as running using buildAndDeploy scripts without touching the server.xml file. // Probably not the most standard way but suited to this need. // Finally, we use the local machine's hostname as the myidentity. myIdentity = System.getProperty(ARCHAPPL_MYIDENTITY); if (myIdentity == null) { myIdentity = System.getenv(ARCHAPPL_MYIDENTITY); if (myIdentity != null) { logger.info("Obtained my identity from environment variable " + myIdentity); } else { logger.info("Using the local machine's hostname " + myIdentity + " as my identity"); myIdentity = InetAddress.getLocalHost().getCanonicalHostName(); } if (myIdentity == null) { throw new ConfigException("Unable to determine identity of this appliance"); } } else { logger.info("Obtained my identity from Java system properties " + myIdentity); } logger.info("My identity is " + myIdentity); } catch (Exception ex) { String msg = "Cannot determine this appliance's identity using either the environment variable " + ARCHAPPL_MYIDENTITY + " or the java system property " + ARCHAPPL_MYIDENTITY; configlogger.fatal(msg); throw new ConfigException(msg, ex); } // Appliances should be local and come straight from persistence. try { appliances = AppliancesList.loadAppliancesXML(servletContext); } catch (Exception ex) { throw new ConfigException("Exception loading appliances.xml", ex); } myApplianceInfo = appliances.get(myIdentity); if (myApplianceInfo == null) throw new ConfigException("Unable to determine applianceinfo using identity " + myIdentity); configlogger.info("My identity is " + myApplianceInfo.getIdentity() + " and my mgmt URL is " + myApplianceInfo.getMgmtURL()); // To make sure we are not starting multiple appliance with the same identity, we make sure that the hostnames match try { String machineHostName = InetAddress.getLocalHost().getCanonicalHostName(); String[] myAddrParts = myApplianceInfo.getClusterInetPort().split(":"); String myHostNameFromInfo = myAddrParts[0]; if (myHostNameFromInfo.equals("localhost")) { logger.debug( "Using localhost for the cluster inet port. If you are indeed running a cluster, the cluster members will not join the cluster."); } else if (myHostNameFromInfo.equals(machineHostName)) { logger.debug( "Hostname from config and hostname from InetAddress match exactly; we are correctly configured " + machineHostName); } else if (InetAddressValidator.getInstance().isValid(myHostNameFromInfo)) { logger.debug("Using ipAddress for cluster config " + myHostNameFromInfo); } else { String msg = "The hostname from appliances.xml is " + myHostNameFromInfo + " and from a call to InetAddress.getLocalHost().getCanonicalHostName() (typially FQDN) is " + machineHostName + ". These are not identical. They are probably equivalent but to prevent multiple appliances binding to the same identity we enforce this equality."; configlogger.fatal(msg); throw new ConfigException(msg); } } catch (UnknownHostException ex) { configlogger.error( "Got an UnknownHostException when trying to determine the hostname. This happens when DNS is not set correctly on this machine (for example, when using VM's. See the documentation for InetAddress.getLocalHost().getCanonicalHostName()"); } try { String archApplPropertiesFileName = System.getProperty(ARCHAPPL_PROPERTIES_FILENAME); if (archApplPropertiesFileName == null) { archApplPropertiesFileName = System.getenv(ARCHAPPL_PROPERTIES_FILENAME); } if (archApplPropertiesFileName == null) { archApplPropertiesFileName = new URL(this.getClass().getClassLoader() .getResource(DEFAULT_ARCHAPPL_PROPERTIES_FILENAME).toString()).getPath(); configlogger.info( "Loading archappl.properties from the webapp classpath " + archApplPropertiesFileName); } else { configlogger.info("Loading archappl.properties using the environment/JVM property from " + archApplPropertiesFileName); } try (InputStream is = new FileInputStream(new File(archApplPropertiesFileName))) { archapplproperties.load(is); configlogger.info( "Done loading installation specific properties file from " + archApplPropertiesFileName); } catch (Exception ex) { throw new ConfigException( "Exception loading installation specific properties file " + archApplPropertiesFileName, ex); } } catch (ConfigException cex) { throw cex; } catch (Exception ex) { configlogger.fatal("Exception loading the appliance properties file", ex); } switch (contextPath) { case "/mgmt": warFile = WAR_FILE.MGMT; this.mgmtRuntime = new MgmtRuntimeState(this); break; case "/engine": warFile = WAR_FILE.ENGINE; this.engineContext = new EngineContext(this); break; case "/retrieval": warFile = WAR_FILE.RETRIEVAL; this.retrievalState = new RetrievalState(this); break; case "/etl": this.etlPVLookup = new PBThreeTierETLPVLookup(this); warFile = WAR_FILE.ETL; break; default: logger.error("We seem to have introduced a new component into the system " + contextPath); } String pvName2KeyMappingClass = this.getInstallationProperties() .getProperty(ARCHAPPL_PVNAME_TO_KEY_MAPPING_CLASSNAME); if (pvName2KeyMappingClass == null || pvName2KeyMappingClass.equals("") || pvName2KeyMappingClass.length() < 1) { logger.info("Using the default key mapping class"); pvName2KeyConverter = new ConvertPVNameToKey(); pvName2KeyConverter.initialize(this); } else { try { logger.info("Using " + pvName2KeyMappingClass + " as the name to key mapping class"); pvName2KeyConverter = (PVNameToKeyMapping) Class.forName(pvName2KeyMappingClass).newInstance(); pvName2KeyConverter.initialize(this); } catch (Exception ex) { logger.fatal("Cannot initialize pv name to key mapping class " + pvName2KeyMappingClass, ex); throw new ConfigException( "Cannot initialize pv name to key mapping class " + pvName2KeyMappingClass, ex); } } String runtimeFieldsListStr = this.getInstallationProperties() .getProperty("org.epics.archiverappliance.config.RuntimeKeys"); if (runtimeFieldsListStr != null && !runtimeFieldsListStr.isEmpty()) { logger.debug("Got runtime fields from the properties file " + runtimeFieldsListStr); String[] runTimeFieldsArr = runtimeFieldsListStr.split(","); for (String rf : runTimeFieldsArr) { this.runTimeFields.add(rf.trim()); } } startupExecutor = Executors.newScheduledThreadPool(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("Startup executor"); return t; } }); this.addShutdownHook(new Runnable() { @Override public void run() { logger.info("Shutting down startup scheduled executor..."); startupExecutor.shutdown(); } }); this.startupState = STARTUP_SEQUENCE.READY_TO_JOIN_APPLIANCE; if (this.warFile == WAR_FILE.MGMT) { logger.info("Scheduling webappReady's for the mgmt webapp "); MgmtPostStartup mgmtPostStartup = new MgmtPostStartup(this); ScheduledFuture<?> postStartupFuture = startupExecutor.scheduleAtFixedRate(mgmtPostStartup, 10, 20, TimeUnit.SECONDS); mgmtPostStartup.setCancellingFuture(postStartupFuture); } else { logger.info("Scheduling webappReady's for the non-mgmt webapp " + this.warFile.toString()); NonMgmtPostStartup nonMgmtPostStartup = new NonMgmtPostStartup(this, this.warFile.toString()); ScheduledFuture<?> postStartupFuture = startupExecutor.scheduleAtFixedRate(nonMgmtPostStartup, 10, 20, TimeUnit.SECONDS); nonMgmtPostStartup.setCancellingFuture(postStartupFuture); } // Measure some JMX metrics once a minute startupExecutor.scheduleAtFixedRate(new Runnable() { @Override public void run() { processMetrics.takeMeasurement(); } }, 60, 60, TimeUnit.SECONDS); }
From source file:org.jboss.wsf.test.JBossWSTestHelper.java
public static String toIPv6URLFormat(final String host) { try {//from w ww. ja v a 2 s .c o m if (host.startsWith("[") || host.startsWith(":")) { if (System.getProperty("java.net.preferIPv4Stack") == null) { throw new IllegalStateException( "always provide java.net.preferIPv4Stack JVM property when using IPv6 address format"); } if (System.getProperty("java.net.preferIPv6Addresses") == null) { throw new IllegalStateException( "always provide java.net.preferIPv6Addresses JVM property when using IPv6 address format"); } } final boolean isIPv6Address = InetAddress.getByName(host) instanceof Inet6Address; final boolean isIPv6Literal = isIPv6Address && InetAddressValidator.getInstance() .isValidInet6Address(host.replaceAll("^\\[(.*)\\]$", "$1")); final boolean isIPv6LiteralFormattedForURI = isIPv6Literal && host.startsWith("["); return isIPv6Literal && !isIPv6LiteralFormattedForURI ? "[" + host + "]" : host; } catch (final UnknownHostException e) { throw new RuntimeException(e); } }
From source file:org.kaaproject.kaa.sandbox.web.services.SandboxServiceImpl.java
@Override public void validateKaaHost(String host) throws SandboxServiceException { if (host == null || host.length() == 0) { throw new SandboxServiceException("Kaa host field can not be empty!"); } else if (!InetAddressValidator.getInstance().isValid(host) && !DomainValidator.getInstance(true).isValid(host)) { throw new SandboxServiceException("Invalid hostname/ip address format!"); }//from w w w . j a v a2 s. c o m }
From source file:org.lirazs.gbackbone.validation.client.rule.IpAddressRule.java
@Override public boolean isValid(final String ipAddress, String attribute) { return InetAddressValidator.getInstance().isValid(ipAddress); }
From source file:org.mule.modules.validation.ValidationModule.java
/** * If the specified <code>ipAddress</code> is not a valid one throw an exception. * <p/>/*from w w w. j a va2 s.com*/ * {@sample.xml ../../../doc/mule-module-validation.xml.sample validation:validate-ip-address} * * @param ipAddress IP address to validate * @param customExceptionClassName Class name of the exception to throw * @throws Exception if not valid */ @Processor public void validateIpAddress(String ipAddress, @Optional @Default("org.mule.modules.validation.InvalidException") String customExceptionClassName) throws Exception { InetAddressValidator validator = InetAddressValidator.getInstance(); if (!validator.isValid(ipAddress)) { throw buildException(customExceptionClassName); } }
From source file:org.orcid.frontend.web.forms.validate.OrcidUrlValidator.java
protected boolean isValidAuthority(String authority) { if (authority == null) { return false; }//from w w w .ja v a 2s. c o m Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authority); if (!authorityMatcher.matches()) { return false; } String hostLocation = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP); // check if authority is hostname or IP address: // try a hostname first since that's much more likely OrcidDomainValidator domainValidator = new OrcidDomainValidator(); if (!domainValidator.isValid(hostLocation)) { // try an IP address InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance(); if (!inetAddressValidator.isValid(hostLocation)) { // isn't either one, so the URL is invalid return false; } } String port = authorityMatcher.group(PARSE_AUTHORITY_PORT); if (port != null) { if (!PORT_PATTERN.matcher(port).matches()) { return false; } } String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA); if (extra != null && extra.trim().length() > 0) { return false; } return true; }
From source file:org.wikimedia.analytics.refinery.core.IpUtil.java
/** * Trims and validates the given IP address string * <p>//from w w w. j a v a 2 s . c o m * Trims the input string and validates whether the resulting string is a * valid IPv4 or IPv6 address. However, no canonicalization is done * @param ip IP address * @return String sanitized IP address, if the given string is a valid * IPv4 or IPv6 address. {@code null} otherwise. */ private static String sanitizeIp(String ip) { String sanitizedIp = null; if (ip != null) { ip = ip.trim(); if (InetAddressValidator.getInstance().isValid(ip)) { // We have a valid non-empty ip address sanitizedIp = ip; } } return sanitizedIp; }
From source file:password.pwm.http.filter.RequestInitializationFilter.java
/** * Returns the IP address of the user. If there is an X-Forwarded-For header in the request, that address will * be used. Otherwise, the source address of the request is used. * * @return String containing the textual representation of the source IP address, or null if the request is invalid. *///from ww w.jav a 2 s . c om public static String readUserIPAddress(final PwmRequest pwmRequest) throws PwmUnrecoverableException { final Configuration config = pwmRequest.getConfig(); final boolean useXForwardedFor = config != null && config.readSettingAsBoolean(PwmSetting.USE_X_FORWARDED_FOR_HEADER); String userIP = ""; if (useXForwardedFor) { userIP = pwmRequest.readHeaderValueAsString(HttpHeader.XForwardedFor); if (!StringUtil.isEmpty(userIP)) { final int commaIndex = userIP.indexOf(','); if (commaIndex > -1) { userIP = userIP.substring(0, commaIndex); } } if (!StringUtil.isEmpty(userIP)) { if (!InetAddressValidator.getInstance().isValid(userIP)) { LOGGER.warn("discarding bogus network address '" + userIP + "' in " + HttpHeader.XForwardedFor.getHttpName() + " header"); userIP = null; } } } if (StringUtil.isEmpty(userIP)) { userIP = pwmRequest.getHttpServletRequest().getRemoteAddr(); } return userIP == null ? "" : userIP; }