List of usage examples for java.lang String regionMatches
public boolean regionMatches(int toffset, String other, int ooffset, int len)
From source file:org.apache.jsp.happyaxis_jsp.java
/** * Get a replaced string by the specified message. * @param source The original message//from www . j ava 2 s. c om * @param pattern The key message for replacing * @param replace The message to place in the key variable - 'pattern' * @return The replaced message */ String replaceAll(String source, String pattern, String replace) { int i = 0; boolean ret = false; StringBuffer buf = new StringBuffer(); int lenSource = source.length(); int lenPattern = pattern.length(); for (i = 0; i < lenSource; i++) { ret = source.regionMatches(i, pattern, 0, lenPattern); if (ret) { buf.append(source.substring(0, i)); buf.append(replace); buf.append(source.substring(i + lenPattern)); source = replaceAll(buf.toString(), pattern, replace); break; } } return source; }
From source file:org.soaplab.tools.Substitutor.java
/****************************************************************************** * Parses given 'template'//ww w .j a v a 2s .c om * and tries to locate and substitute there some expressions using rules * described at the beginning of this class. *<P> * @return substituted string ******************************************************************************/ public synchronized String[] process() { List<String> results = new ArrayList<String>(); StringBuffer result = new StringBuffer(100); int sepLen = separator.length(); String[] paramValue = null; Token token; boolean insideQuotes = false; for (int i = 0; i < template.length(); i++) { // first process escape characters if ((token = getTokenEscape(i)) != null) { result.append(token.id); i += token.length - 1; // we might change the mode: inside quotes vs. outside quotes // (note that if you need a real quotes, you must escape it) } else if (template.charAt(i) == '"') { insideQuotes = !insideQuotes; // do we have a counter of repetitions? } else if (template.charAt(i) == '#') { log.debug("Found counter at position: " + i); if (idx == -1) result.append(accessor.getCount()); else result.append(idx + 1); // because we want the output to be "one-based" // do we have an identifier (candidate for a value substitution) ? } else if ((token = getTokenValue(i)) != null || (token = getFunction(i)) != null) { if (log.isDebugEnabled()) log.debug("Found: " + token.id + " of length " + token.length + " (" + (token.quoted ? "quoted" : "non-quoted") + ")"); // we found an identifier or a function, and get their value // (actually the value can be an array of values, already separated into // individual command line arguments) paramValue = token.replaceBy; // the found value can contain separators, so we might make several values from it if (paramValue != null && paramValue.length > 0) { // if we have got an array of values we send it to the output exactly the same, // so we do not try to concatenate it with the previous and/or the next text // (even if the value is not marked as quoted) if (paramValue.length > 1) { if (result.length() > 0) // process the previous buffer results.add(result.toString()); for (int j = 0; j < paramValue.length; j++) // then send all values to output results.add(paramValue[j]); result = new StringBuffer(100); // and then clean the whole buffer // if we have got only one value we must look if it is marked as quoted or not; // a non-quoted value is simply concatenated to the current buffer, and we go // through it looking for separators } else if (!token.quoted && !insideQuotes) { int lastPos = result.length(); // everything before lastPos was already processed result.append(paramValue[0]); String tmpStr = result.toString(); boolean firstSeparator = true; int delayedPos = 0; // always at the beginning of a not-yet-processed parameter for (int j = lastPos; j < tmpStr.length(); j++) if (tmpStr.regionMatches(j, separator, 0, sepLen)) { if (firstSeparator) { firstSeparator = false; if (delayedPos < j) results.add(tmpStr.substring(delayedPos, j)); } j += sepLen - 1; delayedPos = j + 1; } else { firstSeparator = true; } result = new StringBuffer(tmpStr.substring(delayedPos)); // and here we have got again only one value, but it is marked as quoted, // so we do not search for separators inside the value and transfer it directly } else { result.append(paramValue[0]); } } i += token.length - 1; // or, do we have a plea for a qualifier name ? } else if ((token = getTokenName(i)) != null) { if (log.isDebugEnabled()) log.debug("Found qualifier: " + token.id + " of length " + token.length); result.append(accessor.getQualifier(token.id)); i += token.length - 1; // or, do we have a separator ? } else if (template.regionMatches(i, separator, 0, sepLen) && !insideQuotes) { if (result.length() > 0) { results.add(result.toString()); result = new StringBuffer(100); } i += sepLen - 1; // or, finally, do we have something else ? } else { result.append(template.charAt(i)); } } // do not forget the last piece if (result.length() > 0) results.add(result.toString()); // make resulting strings and return them String[] paramList = new String[results.size()]; return results.toArray(paramList); }
From source file:HexFormat.java
/** * Parse a hex number into a Number object. Hexadecimal numbers may be * indicated with a leading character designation of '0x'. If up to 1 byte * is parsed, returns a Byte. If more than 1 and up to 2 bytes are parsed, * return a Short. If more than 2 and up to 4 bytes are parsed, return an * Integer. If more than 4 and up to 8 bytes are parsed, return a Long. * // ww w . j a va 2 s . c o m * @param text * a hexadecimal number * @param parsePosition * position to start parsing from * @return return an integer form of Number object if parse is successful; * <CODE>null</CODE> otherwise * * @since 1.0 */ public Number parse(String text, ParsePosition parsePosition) { boolean skipWhitespace = true; int startIndex, nibbles; // remove whitespace StringCharacterIterator iter = new StringCharacterIterator(text, parsePosition.getIndex()); for (char c = iter.current(); c != CharacterIterator.DONE; c = iter.next()) { if (skipWhitespace && Character.isWhitespace(c)) { // skip whitespace continue; } break; } // skip a leading hex designation of the characters '0x' if (text.regionMatches(iter.getIndex(), "0x", 0, 2)) { parsePosition.setIndex(iter.getIndex() + 2); } else { parsePosition.setIndex(iter.getIndex()); } startIndex = parsePosition.getIndex(); Number result = (Number) parseObject(text, parsePosition); if (result == null) { return (result); } nibbles = parsePosition.getIndex() - startIndex; if (nibbles <= 2) { result = new Byte(result.byteValue()); } else if (nibbles <= 4) { result = new Short(result.shortValue()); } else if (nibbles <= 8) { result = new Integer(result.intValue()); } else if (nibbles <= 16) { result = new Long(result.longValue()); } return (result); }
From source file:cl.utfsm.cdbChecker.CDBChecker.java
/************************************************************************************************************************** * Add bhola.panta@naoj 2010/05/12, in order to support hierarchical component names (separated by "/") * I am quoting a comment from Heiko Sommer, ref. #COMP-4247 * We must support hierarchical component names (separated by "/"), where the path of the xml * file should match the component name.//from w w w . j a va2 s .c o m * eg. File path: /alma/ACS-9.0/acsdata/config/defaultCDB/CDB/MACI/Components/ARCHIVE/TMCDB/MONITOR_BLOBBER2/MONITOR_BLOBBER2.xml * Component name: 'ARCHIVE/TMCDB/MONITOR_BLOBBER2' * File name: 'MONITOR_BLOBBER2.xml' * Under "CDB/MACI/Components", there is the path "ARCHIVE/TMCDB/MONITOR_BLOBBER2", * which does match the component name. * (It's a convention of the CDB that for hierarchical components, but also for other nodes, * the xml file name and the directory name where the xml file is in, are the same * except for the .xml ending. For matching the component name we count it only once, * instead of taking "ARCHIVE/TMCDB/MONITOR_BLOBBER2/MONITOR_BLOBBER2".) * Credit: http://java.sun.com/docs/books/tutorial/java/data/comparestrings.html *****************************************************************************************************************************/ private boolean checkHierarchical(File fSearchMe, String findMe) { String searchMe = fSearchMe.getPath(); int searchMeLength = searchMe.length(); int findMeLength = findMe.length(); boolean foundIt = false; for (int i = 0; i <= (searchMeLength - findMeLength); i++) { if (searchMe.regionMatches(i, findMe, 0, findMeLength)) { foundIt = true; break; } } return foundIt; }
From source file:org.apache.catalina.realm.RealmBase.java
/** * Return the SecurityConstraints configured to guard the request URI for * this request, or <code>null</code> if there is no such constraint. * * @param request Request we are processing * @param context Context the Request is mapped to *//* w w w .ja v a 2 s .c om*/ public SecurityConstraint[] findSecurityConstraints(HttpRequest request, Context context) { ArrayList results = null; // Are there any defined security constraints? SecurityConstraint constraints[] = context.findConstraints(); if ((constraints == null) || (constraints.length == 0)) { if (log.isDebugEnabled()) log.debug(" No applicable constraints defined"); return (null); } // Check each defined security constraint HttpServletRequest hreq = (HttpServletRequest) request.getRequest(); String uri = request.getRequestPathMB().toString(); String method = hreq.getMethod(); int i; boolean found = false; for (i = 0; i < constraints.length; i++) { SecurityCollection[] collection = constraints[i].findCollections(); if (log.isDebugEnabled()) log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); for (int j = 0; j < collection.length; j++) { String[] patterns = collection[j].findPatterns(); for (int k = 0; k < patterns.length; k++) { if (uri.equals(patterns[k])) { found = true; if (collection[j].findMethod(method)) { if (results == null) { results = new ArrayList(); } results.add(constraints[i]); } } } } } if (found) { return resultsToArray(results); } int longest = -1; for (i = 0; i < constraints.length; i++) { SecurityCollection[] collection = constraints[i].findCollections(); if (log.isDebugEnabled()) log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); for (int j = 0; j < collection.length; j++) { String[] patterns = collection[j].findPatterns(); boolean matched = false; int length = -1; for (int k = 0; k < patterns.length; k++) { String pattern = patterns[k]; if (pattern.startsWith("/") && pattern.endsWith("/*") && pattern.length() >= longest) { if (pattern.length() == 2) { matched = true; length = pattern.length(); } else if (pattern.regionMatches(0, uri, 0, pattern.length() - 2)) { matched = true; length = pattern.length(); } } } if (matched) { found = true; if (length > longest) { if (results != null) { results.clear(); } longest = length; } if (collection[j].findMethod(method)) { if (results == null) { results = new ArrayList(); } results.add(constraints[i]); } } } } if (found) { return resultsToArray(results); } for (i = 0; i < constraints.length; i++) { SecurityCollection[] collection = constraints[i].findCollections(); if (log.isDebugEnabled()) log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); boolean matched = false; int pos = -1; for (int j = 0; j < collection.length; j++) { String[] patterns = collection[j].findPatterns(); for (int k = 0; k < patterns.length && !matched; k++) { String pattern = patterns[k]; if (pattern.startsWith("*.")) { int slash = uri.lastIndexOf("/"); int dot = uri.lastIndexOf("."); if (slash >= 0 && dot > slash && dot != uri.length() - 1 && uri.length() - dot == pattern.length() - 1) { if (pattern.regionMatches(1, uri, dot, uri.length() - dot)) { matched = true; pos = j; } } } } } if (matched) { found = true; if (collection[pos].findMethod(method)) { if (results == null) { results = new ArrayList(); } results.add(constraints[i]); } } } if (found) { return resultsToArray(results); } for (i = 0; i < constraints.length; i++) { SecurityCollection[] collection = constraints[i].findCollections(); if (log.isDebugEnabled()) log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); for (int j = 0; j < collection.length; j++) { String[] patterns = collection[j].findPatterns(); boolean matched = false; for (int k = 0; k < patterns.length && !matched; k++) { String pattern = patterns[k]; if (pattern.equals("/")) { matched = true; } } if (matched) { if (results == null) { results = new ArrayList(); } results.add(constraints[i]); } } } if (results == null) { // No applicable security constraint was found if (log.isDebugEnabled()) log.debug(" No applicable constraint located"); } return resultsToArray(results); }
From source file:com.cyberway.issue.crawler.scope.DomainScope.java
/** * Check if an URI is part of this scope. * * @param o An instance of UURI or of CandidateURI. * @return True if focus filter accepts passed object. *///from ww w . jav a 2 s . c om protected boolean focusAccepts(Object o) { UURI u = UURI.from(o); if (u == null) { return false; } // Get the seeds to refresh and then get an iterator inside a // synchronization block. The seeds list may get updated during our // iteration. This will throw a concurrentmodificationexception unless // we synchronize. String seedDomain = null; String candidateDomain = null; // Get candidate domain where www[0-9]*\. is stripped. try { candidateDomain = u.getHostBasename(); } catch (URIException e1) { logger.severe("UURI getHostBasename failed for candidate URI: " + u); } if (candidateDomain == null) { // either an opaque, unfetchable, or unparseable URI return false; } Iterator iter = seedsIterator(); while (iter.hasNext()) { UURI s = (UURI) iter.next(); // Get seed domain where www[0-9]*\. is stripped. try { seedDomain = s.getHostBasename(); } catch (URIException e) { logger.severe("UURI getHostBasename failed for seed: " + s); } if (seedDomain == null) { // GetHost can come back null. See bug item // [ 910120 ] java.net.URI#getHost fails when leading digit continue; } // Check if stripped hosts are same. if (seedDomain.equals(candidateDomain)) { checkClose(iter); return true; } // Hosts are not same. Adjust seed basename to check if // candidate domain ends with .seedDomain seedDomain = DOT + seedDomain; if (seedDomain.regionMatches(0, candidateDomain, candidateDomain.length() - seedDomain.length(), seedDomain.length())) { // Domain suffix congruence checkClose(iter); return true; } // Else keep trying other seeds } // if none found, fail checkClose(iter); return false; }
From source file:org.agnitas.util.AgnUtils.java
public static boolean rmatch(String mask, String target) { int moreCharacters = mask.indexOf('%'); int oneCharacter = mask.indexOf('_'); int pattern = -1; if (moreCharacters >= 0) { pattern = moreCharacters;/*from w w w .j a va 2 s. c o m*/ } if (oneCharacter >= 0 && (oneCharacter < pattern || pattern < 0)) { pattern = oneCharacter; } if (pattern == -1) { if (mask.compareTo(target) == 0) { return true; //match! } return false; } if (!mask.regionMatches(0, target, 0, pattern)) { return false; } if (pattern == oneCharacter) { // '_' found return rmatch(mask.substring(pattern + 1), target.substring(pattern + 1)); } String after = mask.substring(moreCharacters + 1, mask.length()); for (int c = pattern; c < target.length(); c++) { if (rmatch(after, target.substring(c, target.length()))) { return true; } } return false; }
From source file:org.pengyou.client.lib.DavResource.java
/** * Set WebDAV properties following to the given http URL. * This method is fundamental for getting information of a collection. * * @param responses An enumeration over {@link ResponseEntity} items, one * for each resource for which information was returned via PROPFIND. * * @exception HttpException/*from w w w.jav a 2 s . c o m*/ * @exception IOException The socket error with a server. */ protected void setWebdavProperties(Enumeration responses) throws HttpException, IOException { // Make the resources in the collection empty. childResources.removeAll(); while (responses.hasMoreElements()) { ResponseEntity response = (ResponseEntity) responses.nextElement(); boolean itself = false; String href = response.getHref(); if (!href.startsWith("/")) href = URIUtil.getPath(href); href = decodeMarks(href); /* * Decode URIs to common (unescaped) format for comparison * as HttpClient.URI.setPath() doesn't escape $ and : chars. */ //String httpURLPath = httpURL.getPath(); String httpURLPath = context.getBaseUrl() + getPath(); String escapedHref = URIUtil.decode(href); // Normalize them to both have trailing slashes if they differ by one in length. int lenDiff = escapedHref.length() - httpURLPath.length(); int compareLen = 0; if (lenDiff == -1 && !escapedHref.endsWith("/")) { compareLen = escapedHref.length(); lenDiff = 0; } else if (lenDiff == 1 && !httpURLPath.endsWith("/")) { compareLen = httpURLPath.length(); lenDiff = 0; } // if they are the same length then compare them. if (lenDiff == 0) { if ((compareLen == 0 && httpURLPath.equals(escapedHref)) || httpURLPath.regionMatches(0, escapedHref, 0, compareLen)) { // escaped href and http path are the same // Set the status code for this resource. if (response.getStatusCode() > 0) this.statusCode = response.getStatusCode(); this.exist = true; itself = true; } } // Get to know each resource. DavResource workingResource = null; if (itself) { workingResource = this; } else { workingResource = createWebdavResource(client); } // clear the current lock set workingResource.setLockDiscovery(null); // Process the resource's properties Enumeration properties = response.getProperties(); while (properties.hasMoreElements()) { Property property = (Property) properties.nextElement(); // ------------------------------ Checking WebDAV properties workingResource.processProperty(property); } String displayName = workingResource.displayName; if (displayName == null || displayName.trim().equals("")) { displayName = getName(href); } if (!itself) { String myPath = getPath(); String childPath = myPath + (myPath.endsWith("/") ? "" : "/") + DavResource.getName(href); //(myPath.endsWith("/") ? "" : "/") + URIUtil.getName(href); workingResource.setEncodedPath(childPath); workingResource.setExistence(true); } if (!itself) childResources.addResource(workingResource); } }
From source file:org.apache.sshd.server.filesystem.NativeSshFile.java
public final static String getPhysicalName(final String rootDir, final String currDir, final String fileName, final boolean caseInsensitive) { // get the starting directory String normalizedRootDir = normalizeSeparateChar(rootDir); if (normalizedRootDir.charAt(normalizedRootDir.length() - 1) != '/') { normalizedRootDir += '/'; }//from w w w . j a v a2 s . c o m String normalizedFileName = normalizeSeparateChar(fileName); String resArg; String normalizedCurrDir = currDir; if (normalizedFileName.charAt(0) != '/') { if (normalizedCurrDir == null) { normalizedCurrDir = "/"; } if (normalizedCurrDir.length() == 0) { normalizedCurrDir = "/"; } normalizedCurrDir = normalizeSeparateChar(normalizedCurrDir); if (normalizedCurrDir.charAt(0) != '/') { normalizedCurrDir = '/' + normalizedCurrDir; } if (normalizedCurrDir.charAt(normalizedCurrDir.length() - 1) != '/') { normalizedCurrDir += '/'; } resArg = normalizedRootDir + normalizedCurrDir.substring(1); } else { resArg = normalizedRootDir; } // strip last '/' if (resArg.charAt(resArg.length() - 1) == '/') { resArg = resArg.substring(0, resArg.length() - 1); } // replace ., ~ and .. // in this loop resArg will never end with '/' StringTokenizer st = new StringTokenizer(normalizedFileName, "/"); while (st.hasMoreTokens()) { String tok = st.nextToken(); // . => current directory if (tok.equals(".")) { continue; } // .. => parent directory (if not root) if (tok.equals("..")) { if (resArg.startsWith(normalizedRootDir)) { int slashIndex = resArg.lastIndexOf('/'); if (slashIndex != -1) { resArg = resArg.substring(0, slashIndex); } } continue; } // ~ => home directory (in this case the root directory) if (tok.equals("~")) { resArg = normalizedRootDir.substring(0, normalizedRootDir.length() - 1); continue; } if (caseInsensitive) { File[] matches = new File(resArg).listFiles(new NameEqualsFileFilter(tok, true)); if (matches != null && matches.length > 0) { tok = matches[0].getName(); } } resArg = resArg + '/' + tok; } // add last slash if necessary if ((resArg.length()) + 1 == normalizedRootDir.length()) { resArg += '/'; } // final check if (!resArg.regionMatches(0, normalizedRootDir, 0, normalizedRootDir.length())) { resArg = normalizedRootDir; } return resArg; }
From source file:NumericTextField.java
public void insertString(int offset, String str, AttributeSet a) throws BadLocationException { if (str == null || str.length() == 0) { return;/*from w w w . j a va 2 s .c o m*/ } Content content = getContent(); int length = content.length(); int originalLength = length; parsePos.setIndex(0); // Create the result of inserting the new data, // but ignore the trailing newline String targetString = content.getString(0, offset) + str + content.getString(offset, length - offset - 1); // Parse the input string and check for errors do { boolean gotPositive = targetString.startsWith(positivePrefix); boolean gotNegative = targetString.startsWith(negativePrefix); length = targetString.length(); // If we have a valid prefix, the parse fails if the // suffix is not present and the error is reported // at index 0. So, we need to add the appropriate // suffix if it is not present at this point. if (gotPositive == true || gotNegative == true) { String suffix; int suffixLength; int prefixLength; if (gotPositive == true && gotNegative == true) { // This happens if one is the leading part of // the other - e.g. if one is "(" and the other "((" if (positivePrefixLen > negativePrefixLen) { gotNegative = false; } else { gotPositive = false; } } if (gotPositive == true) { suffix = positiveSuffix; suffixLength = positiveSuffixLen; prefixLength = positivePrefixLen; } else { // Must have the negative prefix suffix = negativeSuffix; suffixLength = negativeSuffixLen; prefixLength = negativePrefixLen; } // If the string consists of the prefix alone, // do nothing, or the result won't parse. if (length == prefixLength) { break; } // We can't just add the suffix, because part of it // may already be there. For example, suppose the // negative prefix is "(" and the negative suffix is // "$)". If the user has typed "(345$", then it is not // correct to add "$)". Instead, only the missing part // should be added, in this case ")". if (targetString.endsWith(suffix) == false) { int i; for (i = suffixLength - 1; i > 0; i--) { if (targetString.regionMatches(length - i, suffix, 0, i)) { targetString += suffix.substring(i); break; } } if (i == 0) { // None of the suffix was present targetString += suffix; } length = targetString.length(); } } format.parse(targetString, parsePos); int endIndex = parsePos.getIndex(); if (endIndex == length) { break; // Number is acceptable } // Parse ended early // Since incomplete numbers don't always parse, try // to work out what went wrong. // First check for an incomplete positive prefix if (positivePrefixLen > 0 && endIndex < positivePrefixLen && length <= positivePrefixLen && targetString.regionMatches(0, positivePrefix, 0, length)) { break; // Accept for now } // Next check for an incomplete negative prefix if (negativePrefixLen > 0 && endIndex < negativePrefixLen && length <= negativePrefixLen && targetString.regionMatches(0, negativePrefix, 0, length)) { break; // Accept for now } // Allow a number that ends with the group // or decimal separator, if these are in use char lastChar = targetString.charAt(originalLength - 1); int decimalIndex = targetString.indexOf(decimalSeparator); if (format.isGroupingUsed() && lastChar == groupingSeparator && decimalIndex == -1) { // Allow a "," but only in integer part break; } if (format.isParseIntegerOnly() == false && lastChar == decimalSeparator && decimalIndex == originalLength - 1) { // Allow a ".", but only one break; } // No more corrections to make: must be an error if (errorListener != null) { errorListener.insertFailed(this, offset, str, a); } return; } while (true == false); // Finally, add to the model super.insertString(offset, str, a); }