List of usage examples for java.util.regex Pattern CASE_INSENSITIVE
int CASE_INSENSITIVE
To view the source code for java.util.regex Pattern CASE_INSENSITIVE.
Click Source Link
From source file:loggerplusplus.LogEntry.java
public void processRequest(int tool, IHttpRequestResponse requestResponse, URL url, IRequestInfo tempAnalyzedReq, IInterceptedProxyMessage message) { IHttpService tempRequestResponseHttpService = requestResponse.getHttpService(); String strFullRequest = new String(requestResponse.getRequest()); List<String> lstFullRequestHeader = tempAnalyzedReq.getHeaders(); requestHeaders = StringUtils.join(lstFullRequestHeader, ", "); LogTable logTable = LoggerPlusPlus.getInstance().getLogTable(); this.tool = tool; this.requestResponse = requestResponse; this.url = url; if (logTable.getColumnModel().isColumnEnabled("path")) // This is good to increase the speed when it is time consuming this.relativeURL = url.getPath(); this.host = tempRequestResponseHttpService.getHost(); this.protocol = tempRequestResponseHttpService.getProtocol(); this.isSSL = this.protocol.equals("https"); if (logTable.getColumnModel().isColumnEnabled("targetPort")) // This is good to increase the speed when it is time consuming this.targetPort = tempRequestResponseHttpService.getPort(); if (logTable.getColumnModel().isColumnEnabled("method")) // This is good to increase the speed when it is time consuming this.method = tempAnalyzedReq.getMethod(); try {//w w w . java2 s. com // I don't want to delete special characters such as ; or : from the extension as it may really be part of the extension! (burp proxy log ignores them) String tempPath = url.getPath().replaceAll("\\\\", "/"); tempPath = tempPath.substring(tempPath.lastIndexOf("/")); int tempPathDotLocation = tempPath.lastIndexOf("."); if (tempPathDotLocation >= 0) this.urlExtension = tempPath.substring(tempPathDotLocation + 1); } catch (Exception e) { this.urlExtension = ""; } if (message != null) { if (logTable.getColumnModel().isColumnEnabled("listenerInterface")) // This is good to increase the speed when it is time consuming this.listenerInterface = message.getListenerInterface(); if (logTable.getColumnModel().isColumnEnabled("clientIP")) // This is good to increase the speed when it is time consuming this.clientIP = message.getClientIpAddress().toString(); } requestBodyOffset = tempAnalyzedReq.getBodyOffset(); this.requestLength = requestResponse.getRequest().length - requestBodyOffset; this.hasBodyParam = requestLength > 0; this.params = this.url.getQuery() != null || this.hasBodyParam; this.hasCookieParam = false; // reading request headers like a boss! if (logTable.getColumnModel().isColumnEnabled("sentCookies") || logTable.getColumnModel().isColumnEnabled("hasCookieParam") || logTable.getColumnModel().isColumnEnabled("usesCookieJar") || logTable.getColumnModel().isColumnEnabled("referrer") || logTable.getColumnModel().isColumnEnabled("requestContentType")) { // This is good to increase the speed when it is time consuming for (String item : lstFullRequestHeader) { if (item.indexOf(":") >= 0) { String[] headerItem = item.split(":\\s", 2); headerItem[0] = headerItem[0].toLowerCase(); if (headerItem[0].equals("cookie")) { this.sentCookies = headerItem[1]; if (!this.sentCookies.isEmpty()) { this.hasCookieParam = true; this.sentCookies += ";"; // we need to ad this to search it in cookie Jar! // to ensure it is enabled as it is process consuming if (logTable.getColumnModel().isColumnEnabled("usesCookieJar")) { // Check to see if it uses cookie Jars! List<ICookie> cookieJars = LoggerPlusPlus.getCallbacks().getCookieJarContents(); boolean oneNotMatched = false; boolean anyParamMatched = false; for (ICookie cookieItem : cookieJars) { if (cookieItem.getDomain().equals(this.host)) { // now we want to see if any of these cookies have been set here! String currentCookieJarParam = cookieItem.getName() + "=" + cookieItem.getValue() + ";"; if (this.sentCookies.contains(currentCookieJarParam)) { anyParamMatched = true; } else { oneNotMatched = true; } } if (anyParamMatched && oneNotMatched) { break; // we do not need to analyse it more! } } if (oneNotMatched && anyParamMatched) { this.usesCookieJar = cookieJarStatus.PARTIALLY; } else if (!oneNotMatched && anyParamMatched) { this.usesCookieJar = cookieJarStatus.YES; } } } } else if (headerItem[0].equals("referer")) { this.referrerURL = headerItem[1]; } else if (headerItem[0].equals("content-type")) { this.requestContentType = headerItem[1]; } } } } // RegEx processing for requests - should be available only when we have a RegEx rule! // There are 5 RegEx rule for requests for (int i = 1; i < 5; i++) { String regexVarName = "regex" + (i + 1) + "Req"; if (logTable.getColumnModel().isColumnEnabled(regexVarName)) { // so this rule is enabled! // check to see if the RegEx is not empty LogTableColumn regexColumn = logTable.getColumnModel().getColumnByName(regexVarName); String regexString = regexColumn.getRegExData().getRegExString(); if (!regexString.isEmpty()) { // now we can process it safely! Pattern p = null; try { if (regexColumn.getRegExData().isRegExCaseSensitive()) p = Pattern.compile(regexString); else p = Pattern.compile(regexString, Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(strFullRequest); StringBuilder allMatches = new StringBuilder(); int counter = 1; while (m.find()) { if (counter == 2) { allMatches.insert(0, ""); allMatches.append(""); } if (counter > 1) { allMatches.append("" + m.group() + ""); } else { allMatches.append(m.group()); } counter++; } this.regexAllReq[i] = allMatches.toString(); } catch (Exception e) { LoggerPlusPlus.getCallbacks().printError("Error in regular expression: " + regexString); } } } } }
From source file:com.redhat.rhn.frontend.action.systems.virtualization.ProvisionVirtualizationWizardAction.java
private ActionErrors validateInput(DynaActionForm form) { ActionErrors errors = new ActionErrors(); String name = form.getString(GUEST_NAME); if (name.length() < ProvisionVirtualInstanceCommand.MIN_NAME_SIZE) { errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("frontend.actions.systems.virt.invalidguestnamelength", (ProvisionVirtualInstanceCommand.MIN_NAME_SIZE))); }//w w w .jav a2 s . com Pattern pattern = Pattern.compile(ProvisionVirtualInstanceCommand.GUEST_NAME_REGEXP, Pattern.CASE_INSENSITIVE); if (!pattern.matcher(name).matches()) { errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("frontend.actions.systems.virt.invalidregexp")); } if (!StringUtils.isEmpty(form.getString(MEMORY_ALLOCATION))) { try { Long memory = Long.parseLong(form.getString(MEMORY_ALLOCATION)); if (memory <= 0) { throw new NumberFormatException(); } } catch (NumberFormatException e) { errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("frontend.actions.systems.virt.invalidmemvalue")); } } if (!StringUtils.isEmpty(form.getString(VIRTUAL_CPUS))) { try { Long cpus = Long.parseLong(form.getString(VIRTUAL_CPUS)); if (cpus <= 0 || cpus > ProvisionVirtualInstanceCommand.MAX_CPU) { throw new NumberFormatException(); } } catch (NumberFormatException e) { errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("frontend.actions.systems.virt.invalidcpuvalue", (ProvisionVirtualInstanceCommand.MAX_CPU + 1))); } } if (!StringUtils.isEmpty(form.getString(LOCAL_STORAGE_GB))) { try { Long storage = Long.parseLong(form.getString(LOCAL_STORAGE_GB)); if (storage <= 0) { throw new NumberFormatException(); } } catch (NumberFormatException e) { errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("frontend.actions.systems.virt.invalidstoragevalue")); form.set(LOCAL_STORAGE_GB, ""); } } if (!StringUtils.isEmpty(form.getString(MAC_ADDRESS))) { try { String macAddress = form.getString(MAC_ADDRESS); macAddress = macAddress.replace(":", ""); if (macAddress.length() != 12 || !macAddress.matches("^[0-9a-fA-F]+$")) { throw new NumberFormatException(); } } catch (NumberFormatException e) { errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("frontend.actions.systems.virt.invalidmacaddressvalue")); form.set(MAC_ADDRESS, ""); } } return errors; }
From source file:de.mpg.mpdl.inge.syndication.feed.Feed.java
/** * Populate parameters with the values taken from the certain <code>uri</code> and populate * <code>paramHash</code> with the parameter/value paars. * // w w w . j a v a 2 s .com * @param uri * @throws SyndicationException */ private void populateParamsFromUri(String uri) throws SyndicationException { Utils.checkName(uri, "Uri is empty"); String um = getUriMatcher(); Utils.checkName(um, "Uri matcher is empty"); Matcher m = Pattern.compile(um, Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(uri); if (m.find()) { for (int i = 0; i < m.groupCount(); i++) paramHash.put((String) paramList.get(i), m.group(i + 1)); } // special handling of Organizational Unit Feed // TODO: should be resolved other way! if (getUriMatcher().equals("(.+)?/syndication/feed/(.+)?/publications/organization/(.+)?")) { TreeMap<String, String> outm = Utils.getOrganizationUnitTree(); String oid = (String) paramHash.get("${organizationId}"); for (Map.Entry<String, String> entry : outm.entrySet()) { if (entry.getValue().equals(oid)) { paramHash.put("${organizationName}", entry.getKey()); } } } logger.info("parameters: " + paramHash); }
From source file:com.morphoss.acal.service.connector.AcalRequestor.java
/** * Interpret the URI in the string to set protocol, host, port & path for the next request. * If the URI only matches a path part then protocol/host/port will be unchanged. This call * will only allow for path parts that are anchored to the web root. This is used internally * for following Location: redirects./*w ww .j a v a 2 s . c o m*/ * * This is also used to interpret the 'path' parameter to the request calls generally. * * @param uriString */ public void interpretUriString(String uriString) { if (uriString == null) return; // Match a URL, including an ipv6 address like http://[DEAD:BEEF:CAFE:F00D::]:8008/ final Pattern uriMatcher = Pattern.compile("^(?:(https?)://)?" + // Protocol "(" + // host spec "(?:(?:[a-z0-9-]+[.]){1,7}(?:[a-z0-9-]+))" + // Hostname or IPv4 address "|(?:\\[(?:[0-9a-f]{0,4}:)+(?:[0-9a-f]{0,4})?\\])" + // IPv6 address ")" + "(?:[:]([0-9]{2,5}))?" + // Port number "(/.*)?$" // Path bit. , Pattern.CASE_INSENSITIVE | Pattern.DOTALL); final Pattern pathMatcher = Pattern.compile("^(/.*)$"); if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Interpreting '" + uriString + "'"); Matcher m = uriMatcher.matcher(uriString); if (m.matches()) { if (m.group(1) != null && !m.group(1).equals("")) { if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Found protocol '" + m.group(1) + "'"); protocol = m.group(1); if (m.group(3) == null || m.group(3).equals("")) { port = (protocol.equals(PROTOCOL_HTTP) ? 80 : 443); } } if (m.group(2) != null) { if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Found hostname '" + m.group(2) + "'"); setHostName(m.group(2)); } if (m.group(3) != null && !m.group(3).equals("")) { if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Found port '" + m.group(3) + "'"); port = Integer.parseInt(m.group(3)); if (m.group(1) != null && (port == 0 || port == 80 || port == 443)) { port = (protocol.equals(PROTOCOL_HTTP) ? 80 : 443); } } if (m.group(4) != null && !m.group(4).equals("")) { if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Found path '" + m.group(4) + "'"); setPath(m.group(4)); } if (!initialised) initialise(); } else { m = pathMatcher.matcher(uriString); if (m.find()) { if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Found relative path '" + m.group(1) + "'"); setPath(m.group(1)); } else { if (Constants.LOG_DEBUG) Log.println(Constants.LOGD, TAG, "Using Uri class to process redirect..."); Uri newLocation = Uri.parse(uriString); if (newLocation.getHost() != null) setHostName(newLocation.getHost()); setPortProtocol(newLocation.getPort(), newLocation.getScheme()); setPath(newLocation.getPath()); if (Constants.LOG_VERBOSE) Log.println(Constants.LOGV, TAG, "Found new location at '" + fullUrl() + "'"); } } }
From source file:com.evon.injectTemplate.InjectTemplateFilter.java
private void loadContentTemplate(TemplateBean template, String domain, Integer port, boolean https, HttpServletRequest httpRequest) throws Exception { HTMLInfoBean htmlInfo = templates.get("/" + template.path); String sport = (port == null) ? "" : ":" + String.valueOf(port); String url = htmlInfo.getProtocol() + "://" + domain + sport + "/" + template.path; Request request = Request.Get(url); Enumeration<String> headerNames = httpRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); Enumeration<String> headerValues = httpRequest.getHeaders(name); while (headerValues.hasMoreElements()) { String value = headerValues.nextElement(); request = request.addHeader(name, value); }/*from www .ja va 2s . c om*/ } String content = request.execute().returnContent().asString(); Pattern pattern = Pattern.compile("<INJECT[ ]{1,}selector=[\"'](.*?)[\"']/>", Pattern.CASE_INSENSITIVE + Pattern.DOTALL); Matcher matcher = pattern.matcher(content); List<String> selectors = new ArrayList<String>(); while (matcher.find()) { String tagInject = matcher.group(0); String selector = matcher.group(1); selectors.add(selector); content = content.replace(tagInject, "<INJECT selector='" + selector + "'/>"); } String key = null; if (template.cache.equals("SESSION")) { String cookiesNames = getCookieHashs(httpRequest); key = template.path + cookiesNames; } else { key = template.path; } HtmlContentBean contentBean = new HtmlContentBean(); contentBean.setContent(content); contentBean.setLastAccess(System.currentTimeMillis()); htmlContents.remove(key); htmlContents.put(key, contentBean); htmlInfo.setSelectors(selectors); }
From source file:com.clustercontrol.agent.filecheck.FileCheck.java
private boolean matchFile(JobFileCheck check, String filename) { Pattern pattern = null;/*from www.j av a 2s. co m*/ String patternText = check.getFileName(); // ????? pattern = Pattern.compile(patternText, Pattern.DOTALL | Pattern.CASE_INSENSITIVE); // ??? // pattern = Pattern.compile(patternText, Pattern.DOTALL); Matcher matcher = pattern.matcher(filename); return matcher.matches(); }
From source file:de.undercouch.bson4jackson.BsonGeneratorTest.java
@Test public void patterns() throws Exception { Pattern pattern = Pattern.compile("a.*a", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Map<String, Object> data = new LinkedHashMap<String, Object>(); data.put("pattern", pattern); BSONObject obj = generateAndParse(data); Pattern result = (Pattern) obj.get("pattern"); assertNotNull(result);/*from w ww . j ava 2s . c om*/ assertEquals(pattern.pattern(), result.pattern()); assertEquals(pattern.flags(), result.flags()); }
From source file:io.fabric8.maven.core.util.KubernetesResourceUtil.java
private static Map<String, Object> readAndEnrichFragment(ResourceVersioning apiVersions, File file, String appName) throws IOException { Pattern pattern = Pattern.compile(FILENAME_PATTERN, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(file.getName()); if (!matcher.matches()) { throw new IllegalArgumentException( String.format("Resource file name '%s' does not match pattern <name>-<type>.(yaml|yml|json)", file.getName())); }//from www .j a v a 2s . c o m String name = matcher.group("name"); String type = matcher.group("type"); String ext = matcher.group("ext").toLowerCase(); String kind; Map<String, Object> fragment = readFragment(file, ext); if (type != null) { kind = getAndValidateKindFromType(file, type); } else { // Try name as type kind = FILENAME_TO_KIND_MAPPER.get(name.toLowerCase()); if (kind != null) { // Name is in fact the type, so lets erase the name. name = null; } } addKind(fragment, kind, file.getName()); String apiVersion = apiVersions.getCoreVersion(); if (Objects.equals(kind, "Deployment") || Objects.equals(kind, "Ingress")) { apiVersion = apiVersions.getExtensionsVersion(); } else if (Objects.equals(kind, "StatefulSet")) { apiVersion = apiVersions.getAppsVersion(); } addIfNotExistent(fragment, "apiVersion", apiVersion); Map<String, Object> metaMap = getMetadata(fragment); // No name means: generated app name should be taken as resource name addIfNotExistent(metaMap, "name", StringUtils.isNotBlank(name) ? name : appName); return fragment; }
From source file:com.xebia.incubator.xebium.ExtendedSeleniumCommand.java
/** * <p><i>(From the Selenium docs)</i></p> * <p>/*from w ww . j a v a 2 s .c o m*/ * Various Pattern syntaxes are available for matching string values: * </p> * <ul> * <li><strong>glob:</strong><em>pattern</em>: Match a string against a * "glob" (aka "wildmat") pattern. "Glob" is a kind of limited * regular-expression syntax typically used in command-line shells. In a * glob pattern, "*" represents any sequence of characters, and "?" * represents any single character. Glob patterns match against the entire * string.</li> * <li><strong>regexp:</strong><em>regexp</em>: Match a string using a * regular-expression. The full power of JavaScript regular-expressions is * available.</li> * <li><strong>regexpi:</strong><em>regexpi</em>: Match a string using a * case-insensitive regular-expression.</li> * <li><strong>exact:</strong><em>string</em>: * * Match a string exactly, verbatim, without any of that fancy wildcard * stuff.</li> * </ul> * <p> * If no pattern prefix is specified, Selenium assumes that it's a "glob" * pattern. * </p> * <p> * For commands that return multiple values (such as verifySelectOptions), * the string being matched is a comma-separated list of the return values, * where both commas and backslashes in the values are backslash-escaped. * When providing a pattern, the optional matching syntax (i.e. glob, * regexp, etc.) is specified once, as usual, at the beginning of the * pattern. * </p> * * @param expected expected result, optionally prefixed * @param actual Actual result coming from Selenium * @return is it a match? */ public boolean matches(String expected, String actual) { boolean result; // Be graceful with empty strings if (actual == null) { actual = ""; } if (isBooleanCommand()) { result = "true".equals(actual); } else if (expected.startsWith(REGEXP)) { final String regex = trim(removeStartIgnoreCase(expected, REGEXP)); result = Pattern.compile(regex, Pattern.DOTALL).matcher(actual).matches(); } else if (expected.startsWith(REGEXPI)) { final String regex = trim(removeStartIgnoreCase(expected, REGEXPI)); result = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(actual).matches(); } else if (expected.startsWith(EXACT)) { final String str = trim(removeStartIgnoreCase(expected, EXACT)); result = str.equals(actual); } else { // "glob:" final String pattern; if (expected.startsWith(GLOB)) { pattern = trim(removeStartIgnoreCase(expected, GLOB)); } else { pattern = expected; } result = globToRegExp(pattern).matcher(actual).matches(); } if (isNegateCommand()) { result = !result; } return result; }
From source file:de.zib.gndms.common.rest.UriFactory.java
public static Specifier<Void> parseSliceSpecifier(final String uri) { Pattern pattern = Pattern.compile("(.*)/dspace/_([^/]+)/_([^/]+)/_([^/]+)/?", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(uri); if (matcher.matches()) return createSliceSpecifier(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4)); else/* w w w . j ava 2 s . c o m*/ throw new IllegalArgumentException("URL describes no valid Slice specifier: " + uri); }