List of usage examples for java.util.regex Pattern matches
public static boolean matches(String regex, CharSequence input)
From source file:br.com.nordestefomento.jrimum.vallia.digitoverificador.CNPJDV.java
/** * @see br.com.nordestefomento.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(java.lang.String) * @since 0.2//from w ww . java 2s . c om */ @Override public int calcule(String numero) throws IllegalArgumentException { int dv1 = 0; int dv2 = 0; boolean isFormatoValido = false; validacao: { if (StringUtils.isNotBlank(numero)) { isFormatoValido = (Pattern.matches(REGEX_CNPJ_DV, numero) || Pattern.matches(REGEX_CNPJ_DV_FORMATTED, numero)); if (isFormatoValido) { numero = StringUtils.replaceChars(numero, ".", ""); numero = StringUtils.replaceChars(numero, "/", ""); dv1 = calculeDigito(numero); dv2 = calculeDigito(numero + dv1); break validacao; } } throw new IllegalArgumentException("O CNPJ [ " + numero + " ] deve conter apenas nmeros, sendo eles no formato ##.###.###/#### ou ############ !"); } return Integer.parseInt(dv1 + "" + dv2); }
From source file:com.adanac.module.blog.filter.DynamicFilter.java
private boolean loginFilter(Map<String, Object> data, String requestUri, ServletRequest request) { Map<String, String> user = AbstractServlet.getUser((HttpServletRequest) request); if (user != null) { data.put("user", user); return false; }/*from w w w . j av a2s . c o m*/ Set<String> cachedLoginFilterExcludeUrls = (Set<String>) CacheManager.getConcurrentHashMapCache() .get("loginFilterExcludeUrls"); if (cachedLoginFilterExcludeUrls != null && cachedLoginFilterExcludeUrls.contains(requestUri)) { return false; } Set<String> cachedLoginFilterUrls = (Set<String>) CacheManager.getConcurrentHashMapCache() .get("loginFilterUrls"); if (cachedLoginFilterUrls != null && cachedLoginFilterUrls.contains(requestUri)) { return true; } boolean isLoginFilterUrl = false; for (int i = 0; i < loginFilterUrls.length; i++) { if (Pattern.matches(loginFilterUrls[i], requestUri)) { isLoginFilterUrl = true; break; } } synchronized (this) { if (isLoginFilterUrl) { if (cachedLoginFilterUrls == null) { cachedLoginFilterUrls = new HashSet<>(); } cachedLoginFilterUrls.add(requestUri); CacheManager.getConcurrentHashMapCache().set("loginFilterUrls", cachedLoginFilterUrls); } else { if (cachedLoginFilterExcludeUrls == null) { cachedLoginFilterExcludeUrls = new HashSet<>(); } cachedLoginFilterExcludeUrls.add(requestUri); CacheManager.getConcurrentHashMapCache().set("loginFilterExcludeUrls", cachedLoginFilterExcludeUrls); } } if (isLoginFilterUrl) { return true; } else { return false; } }
From source file:com.blackberry.logtools.LogTools.java
public String parseDate(String time) throws Exception { String parsedTime = time;//from w w w. jav a 2s . c om if (Pattern.matches("[0-9]+", time) == false) { String[] dateCmd = { "/bin/sh", "-c", "date -d '" + time + "' +%s" }; ProcessBuilder pBuilder = new ProcessBuilder(dateCmd); pBuilder.redirectErrorStream(true); Process p = pBuilder.start(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); parsedTime = br.readLine() + "000"; if (parsedTime.contains("invalid date")) { logConsole(true, true, error, "Could not parse start time, invalid date."); System.exit(1); } } else if (time.length() != 13) { logConsole(true, true, error, "Could not parse start time."); logConsole(true, true, error, "Epoch date time must be in miliseconds. (13 digits)"); System.exit(1); } return parsedTime; }
From source file:com.vgi.mafscaling.MafCompare.java
public MafCompare() { compExcelAdapter = new ExcelAdapter() { //@override protected void onPaste(JTable table, boolean extendRows, boolean extendCols) { super.onPaste(table, extendRows, extendCols); int colCount = compMafTable.getColumnCount(); Utils.ensureColumnCount(colCount, origMafTable); Utils.ensureColumnCount(colCount, newMafTable); ArrayList<Object> values = new ArrayList<Object>(); int i; for (i = (table.getSelectedColumns())[0]; i < colCount; ++i) values.add(compMafTable.getValueAt(0, i)); double corr; int j = 0; for (i = (table.getSelectedColumns())[0]; i < colCount; ++i, ++j) { if (Pattern.matches(Utils.fpRegex, values.get(j).toString()) && Pattern.matches(Utils.fpRegex, origMafTable.getValueAt(1, i).toString())) { corr = Double.valueOf(values.get(j).toString()) / 100.0 + 1.0; newMafTable.setValueAt(Double.valueOf(origMafTable.getValueAt(1, i).toString()) * corr, 1, i);/*ww w .j av a2 s . c o m*/ } else break; } } }; initialize(); }
From source file:com.ejie.uda.jsonI18nEditor.Editor.java
public void importResources(Path dir) { Stream<Path> filter; try {/* w w w. ja v a2s .c o m*/ if (!closeCurrentSession()) { return; } if (Files.isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) { reset(); resourcesDir = dir; filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path)); } else { reset(); // Se ha arrastrado un fichero de 18n individual, se debe de obtener los recursos relacionados con el bundle al que pertenece. Pattern.matches(BUNDLE_REGEX, dir.getFileName().toString()); Pattern regex = Pattern.compile(BUNDLE_REGEX); resourcesDir = dir.getParent(); inputFile = dir; Matcher regexMatcher = regex.matcher(dir.getFileName().toString()); if (regexMatcher.find()) { this.bundle = regexMatcher.group(1); filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path, this.bundle)); } else { showError(MessageBundle.get("resources.open.error.multiple")); return; } // Pattern.matches("BUNDLE_REGEX", dir.getFileName().toString()); // showError(MessageBundle.get("resources.open.error.multiple")); // return; } filter.forEach(path -> { try { Resource resource = Resources.read(path); setupResource(resource); } catch (Exception e) { e.printStackTrace(); showError(MessageBundle.get("resources.open.error.single", path.toString())); } }); List<String> recentDirs = settings.getListProperty("history"); recentDirs.remove(dir); recentDirs.add(dir.toString()); if (recentDirs.size() > 5) { recentDirs.remove(0); } settings.setProperty("history", recentDirs); editorMenu.setRecentItems(Lists.reverse(recentDirs)); Map<String, String> keys = Maps.newTreeMap(); resources.forEach(resource -> keys.putAll(resource.getTranslations())); // resources.forEach(resource -> { // // // // }); List<String> keyList = Lists.newArrayList(keys.keySet()); translationTree.setModel(new TranslationTreeModel(keyList)); updateUI(); // for (String key : keyList) { // boolean anyEmpty = false; // // for (Resource resource : resources) { // if (StringUtils.isBlank(resource.getTranslation(key))){ // anyEmpty = true; // } // } // // TranslationTreeModel model = (TranslationTreeModel) translationTree.getModel(); // TranslationTreeNode node = model.getNodeByKey(key); // // node // } // keyList.stream().filter(key -> { // // resources.stream().filter(resource -> { // return StringUtils.isNotBlank(resource.getTranslation(key)); // }); // return true; // }); } catch (IOException e) { e.printStackTrace(); showError(MessageBundle.get("resources.open.error.multiple")); } }
From source file:com.cognifide.aet.executor.xmlparser.xml.utils.ValidationUtils.java
private static String validateNameAttribute(String parentElement, String name, String value, String pattern) throws ParseException { String result;// w w w . j a v a 2 s. c o m try { result = validateWhitespace(value, String.format( "Attribute: %s in %s definition shouldn't have whitespace (current: '%s'). Please fix it.", name, parentElement, value)); } catch (ParseException e) { throw new ParseException( String.format("Problem with attribute %s: '%s' in %s definition.", name, value, parentElement), e); } if (!Pattern.matches(pattern, result)) { throw new ParseException(String.format("Value '%s' of attribute %s in %s does not match pattern %s!", value, name, parentElement, pattern)); } return result; }
From source file:cn.com.loopj.android.http.BinaryHttpResponseHandler.java
@Override public final void sendResponseMessage(HttpResponse response) throws IOException { StatusLine status = response.getStatusLine(); Header[] contentTypeHeaders = response.getHeaders(AsyncHttpClient.HEADER_CONTENT_TYPE); if (contentTypeHeaders.length != 1) { //malformed/ambiguous HTTP Header, ABORT! sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException( status.getStatusCode(), "None, or more than one, Content-Type Header found!")); return;//from w w w .j a v a 2 s. c om } Header contentTypeHeader = contentTypeHeaders[0]; boolean foundAllowedContentType = false; for (String anAllowedContentType : getAllowedContentTypes()) { try { if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) { foundAllowedContentType = true; } } catch (PatternSyntaxException e) { AsyncHttpClient.log.e(LOG_TAG, "Given pattern is not valid: " + anAllowedContentType, e); } } if (!foundAllowedContentType) { //Content-Type not in allowed list, ABORT! sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException( status.getStatusCode(), "Content-Type (" + contentTypeHeader.getValue() + ") not allowed!")); return; } super.sendResponseMessage(response); }
From source file:com.gitblit.manager.FilestoreManager.java
@Override public boolean isValidOid(String oid) { //NOTE: Assuming SHA256 support only as per git-lfs return Pattern.matches("[a-fA-F0-9]{64}", oid); }
From source file:org.springframework.cloud.deployer.spi.local.AbstractLocalDeployerSupport.java
/** * Retain the environment variable strings in the provided set indicated by * {@link LocalDeployerProperties#getEnvVarsToInherit}. * This assumes that the provided set can be modified. * * @param vars set of environment variable strings *//*from ww w .j ava2s. com*/ protected void retainEnvVars(Set<String> vars) { List<String> patterns = new ArrayList<>(Arrays.asList(getLocalDeployerProperties().getEnvVarsToInherit())); patterns.addAll(Arrays.asList(this.envVarsSetByDeployer)); for (Iterator<String> iterator = vars.iterator(); iterator.hasNext();) { String var = iterator.next(); boolean retain = false; for (String pattern : patterns) { if (Pattern.matches(pattern, var)) { retain = true; break; } } if (!retain) { iterator.remove(); } } }
From source file:fr.univlorraine.mondossierweb.controllers.AdresseController.java
public List<CommuneDTO> getVilles(String codePostal) { List<CommuneDTO> lvilles = new LinkedList<CommuneDTO>(); try {//from w ww . j av a 2s. c om //if (Pattern.matches("^[0-9]{2}[0-9]*", codePostal)) { if (Pattern.matches("^[0-9]{5}", codePostal)) { CommuneDTO[] cdto = monProxyGeo.recupererCommune(codePostal, "O", "O"); if (cdto != null) { for (int i = 0; i < cdto.length; i++) { boolean insere = false; int j = 0; while (!insere && j < lvilles.size()) { if (lvilles.get(j).getLibCommune().compareTo(cdto[i].getLibCommune()) > 0) { lvilles.add(j, cdto[i]); insere = true; } if (lvilles.get(j).getLibCommune().equals(cdto[i].getLibCommune())) { insere = true; } if (!insere) { j++; } } if (!insere) { lvilles.add(cdto[i]); } } } } } catch (WebBaseException | RemoteException e) { LOG.info("Problme la rcupration de communes pour le code postal : " + codePostal, e); } return lvilles; }