public static String getDirectoryName(String path) { if (path != null) { int index = path.lastIndexOf(DIRECTORY_SEPARATOR_CHAR); int index2 = path.lastIndexOf(ALT_DIRECTORY_SEPARATOR_CHAR); if (index2 > index) { index = index2; } if (index != -1) { if (index == path.length() - 1) { if (path.indexOf(VOLUME_SEPARATOR_CHAR) == index - 1) { return null; } else { path = path.substring(0, index); } } else { if (path.indexOf(VOLUME_SEPARATOR_CHAR) == index - 1) { path = path.substring(0, index + 1); } else { path = path.substring(0, index); } } if (path.length() == 2 && path[1] == VOLUME_SEPARATOR_CHAR) { return ""; } } return path; } return null; }
internal static boolean containsMoreThanOneSlashInNationalNumber(PhoneNumber number, String candidate) { int firstSlashInBodyIndex = candidate.indexOf('/'); if (firstSlashInBodyIndex < 0) { // No slashes, this is okay. return(false); } // Now look for a second one. int secondSlashInBodyIndex = candidate.indexOf('/', firstSlashInBodyIndex + 1); if (secondSlashInBodyIndex < 0) { // Only one slash, this is okay. return(false); } // If the first slash is after the country calling code, this is permitted. boolean candidateHasCountryCode = (number.getCountryCodeSource() == CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN || number.getCountryCodeSource() == CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN); if (candidateHasCountryCode && PhoneNumberUtil.normalizeDigitsOnly(candidate.substring(0, firstSlashInBodyIndex)) .equals(Integer.toString(number.getCountryCode()))) { // Any more slashes and this is illegal. return(candidate.substring(secondSlashInBodyIndex + 1).contains("/")); } return(true); }
internal static boolean containsOnlyValidXChars( PhoneNumber number, String candidate, PhoneNumberUtil util) { // The characters 'x' and 'X' can be (1) a carrier code, in which case they always precede the // national significant number or (2) an extension sign, in which case they always precede the // extension number. We assume a carrier code is more than 1 digit, so the first case has to // have more than 1 consecutive 'x' or 'X', whereas the second case can only have exactly 1 'x' // or 'X'. We ignore the character if it appears as the last character of the string. for (int index = 0; index < candidate.length() - 1; index++) { char charAtIndex = candidate.charAt(index); if (charAtIndex == 'x' || charAtIndex == 'X') { char charAtNextIndex = candidate.charAt(index + 1); if (charAtNextIndex == 'x' || charAtNextIndex == 'X') { // This is the carrier code case, in which the 'X's always precede the national // significant number. index++; if (util.isNumberMatch(number, candidate.substring(index)) != MatchType.NSN_MATCH) { return(false); } // This is the extension sign case, in which the 'x' or 'X' should always precede the // extension number. } else if (!PhoneNumberUtil.normalizeDigitsOnly(candidate.substring(index)).equals( number.getExtension())) { return(false); } } } return(true); }
/** * Attempts to extract a match from {@code candidate} if the whole candidate does not qualify as a * match. * * @param candidate the candidate text that might contain a phone number * @param offset the current offset of {@code candidate} within {@link #text} * @return the match found, null if none can be found */ private PhoneNumberMatch extractInnerMatch(String candidate, int offset) { // Try removing either the first or last "group" in the number and see if this gives a result. // We consider white space to be a possible indication of the start or end of the phone number. Matcher groupMatcher = GROUP_SEPARATOR.matcher(candidate); if (groupMatcher.find()) { // Try the first group by itself. CharSequence firstGroupOnly = candidate.substring(0, groupMatcher.start()); firstGroupOnly = trimAfterFirstMatch(PhoneNumberUtil.UNWANTED_END_CHAR_PATTERN, firstGroupOnly); PhoneNumberMatch match = parseAndVerify(firstGroupOnly.toString(), offset); if (match != null) { return(match); } maxTries--; int withoutFirstGroupStart = groupMatcher.end(); // Try the rest of the candidate without the first group. CharSequence withoutFirstGroup = candidate.substring(withoutFirstGroupStart); withoutFirstGroup = trimAfterFirstMatch(PhoneNumberUtil.UNWANTED_END_CHAR_PATTERN, withoutFirstGroup); match = parseAndVerify(withoutFirstGroup.toString(), offset + withoutFirstGroupStart); if (match != null) { return(match); } maxTries--; if (maxTries > 0) { int lastGroupStart = withoutFirstGroupStart; while (groupMatcher.find()) { // Find the last group. lastGroupStart = groupMatcher.start(); } CharSequence withoutLastGroup = candidate.substring(0, lastGroupStart); withoutLastGroup = trimAfterFirstMatch(PhoneNumberUtil.UNWANTED_END_CHAR_PATTERN, withoutLastGroup); if (withoutLastGroup.equals(firstGroupOnly)) { // If there are only two groups, then the group "without the last group" is the same as // the first group. In these cases, we don't want to re-check the number group, so we exit // already. return(null); } match = parseAndVerify(withoutLastGroup.toString(), offset); if (match != null) { return(match); } maxTries--; } } return(null); }
public static Long decode(String nm) { int radix = 10; int index = 0; boolean negative = false; Long result; if (nm.length() == 0) { throw new NumberFormatException("Zero length string"); } char firstChar = nm.charAt(0); // Handle sign, if present if (firstChar == '-') { negative = true; index++; } else if (firstChar == '+') { index++; } // Handle radix specifier, if present if (nm.startsWith(new String("0x"), index) || nm.startsWith(new String("0X"), index)) { index += 2; radix = 16; } else if (nm.startsWith(new String("#"), index)) { index++; radix = 16; } else if (nm.startsWith(new String("0"), index) && nm.length() > 1 + index) { index++; radix = 8; } if (nm.startsWith(new String("-"), index) || nm.startsWith(new String("+"), index)) { throw new NumberFormatException("Sign character in wrong position"); } try { result = Long.valueOf(nm.substring(index), radix); result = negative ? Long.valueOf(-result.longValue()) : result; } catch (NumberFormatException) { // If number is Long.MIN_VALUE, we'll end up here. The next line // handles this case, and causes any genuine format error to be // rethrown. String constant = negative ? new String("-" + nm.substring(index)) : nm.substring(index); result = Long.valueOf(constant, radix); } return(result); }
/** * Returns the description of the geographical area the {@code number} corresponds to. This method * distinguishes the case of an invalid prefix and a prefix for which the name is not available in * the current language. If the description is not available in the current language an empty * string is returned. If no description was found for the provided number, null is returned. * * @param number the phone number to look up * @return the description of the geographical area */ internal String lookup(PhoneNumber number) { int numOfEntries = areaCodeMapStorage.getNumOfEntries(); if (numOfEntries == 0) { return(null); } long phonePrefix = Long.parseLong(number.getCountryCode() + phoneUtil.getNationalSignificantNumber(number)); int currentIndex = numOfEntries - 1; SortedSet <Integer> currentSetOfLengths = areaCodeMapStorage.getPossibleLengths(); while (currentSetOfLengths.size() > 0) { Integer possibleLength = currentSetOfLengths.last(); String phonePrefixStr = String.valueOf(phonePrefix); if (phonePrefixStr.length() > possibleLength) { phonePrefix = Long.parseLong(phonePrefixStr.substring(0, possibleLength)); } currentIndex = binarySearch(0, currentIndex, phonePrefix); if (currentIndex < 0) { return(null); } int currentPrefix = areaCodeMapStorage.getPrefix(currentIndex); if (phonePrefix == currentPrefix) { return(areaCodeMapStorage.getDescription(currentIndex)); } currentSetOfLengths = currentSetOfLengths.headSet(possibleLength); } return(null); }
/** * Helper method to get the national-number part of a number, formatted without any national * prefix, and return it as a set of digit blocks that would be formatted together. */ private static String[] getNationalNumberGroups(PhoneNumberUtil util, PhoneNumber number, NumberFormat formattingPattern) { if (formattingPattern == null) { // This will be in the format +CC-DG;ext=EXT where DG represents groups of digits. String rfc3966Format = util.format(number, PhoneNumberFormat.RFC3966); // We remove the extension part from the formatted string before splitting it into different // groups. int endIndex = rfc3966Format.indexOf(';'); if (endIndex < 0) { endIndex = rfc3966Format.length(); } // The country-code will have a '-' following it. int startIndex = rfc3966Format.indexOf('-') + 1; return(rfc3966Format.substring(startIndex, endIndex).split("-")); } else { // We format the NSN only, and split that according to the separator. String nationalSignificantNumber = util.getNationalSignificantNumber(number); return(util.formatNsnUsingPattern(nationalSignificantNumber, formattingPattern, PhoneNumberFormat.RFC3966).split("-")); } }
public static String getFileName(String path) { if (path != null) { int index = path.lastIndexOf(DIRECTORY_SEPARATOR_CHAR); if (index == -1) { index = path.lastIndexOf(ALT_DIRECTORY_SEPARATOR_CHAR); } if (index == -1) { return path; } return path.substring(index + 1); } return null; }
public static String getFileNameWithoutExtension(String path) { if (path != null) { int index = path.lastIndexOf(DIRECTORY_SEPARATOR_CHAR); if (index == -1) { index = path.lastIndexOf(ALT_DIRECTORY_SEPARATOR_CHAR); } if (index != -1) { path = path.substring(index + 1); } index = path.lastIndexOf('.'); if (index == -1) { return path; } return path.substring(0, index); } return null; }
private String produceEquivalentAlternation(String source) { int len = countChars(source, 0, 1); if (source.length() == len) // source has one character. return source; String @base = source.substring(0,len); String combiningMarks = source.substring(len); String[] perms = producePermutations(combiningMarks); StringBuilder result = new StringBuilder(source); // Add combined permutations for(int x=0; x<perms.Length; x++) { String next = @base + perms[x]; if (x>0) result.append("|"+next); next = composeOneStep(next); if (next != null) result.append("|"+produceEquivalentAlternation(next)); } return result.toString(); }
private String[] producePermutations(String input) { if (input.length() == countChars(input, 0, 1)) return new String[] {input}; if (input.length() == countChars(input, 0, 2)) { int c0 = Character.codePointAt(input, 0); int c1 = Character.codePointAt(input, Character.charCount(c0)); if (getClass(c1) == getClass(c0)) { return new String[] {input}; } String[] result = new String[2]; result[0] = input; StringBuilder sb = new StringBuilder(2); sb.appendCodePoint(c1); sb.appendCodePoint(c0); result[1] = sb.toString(); return result; } int length = 1; int nCodePoints = countCodePoints(input); for(int x=1; x<nCodePoints; x++) length = length * (x+1); String[] temp = new String[length]; int[] combClass = new int[nCodePoints]; for(int x=0, i=0; x<nCodePoints; x++) { int c = Character.codePointAt(input, i); combClass[x] = getClass(c); i += Character.charCount(c); } // For each char, take it out and add the permutations // of the remaining chars int index = 0; int len; // offset maintains the index in code units. for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) { continue1: len = countChars(input, offset, 1); boolean skip = false; for(int y=x-1; y>=0; y--) { if (combClass[y] == combClass[x]) { offset+=len; if (x < nCodePoints) goto continue1; goto end1; } } StringBuilder sb = new StringBuilder(input); String otherChars = sb.delete(offset, offset+len).toString(); String[] subResult = producePermutations(otherChars); String prefix = input.substring(offset, offset+len); for(int y=0; y<subResult.Length; y++) temp[index++] = prefix + subResult[y]; } end1: String[] _result = new String[index]; for (int x=0; x<index; x++) _result[x] = temp[x]; return _result; }
private TypeInfo getType(String name) { name = name.trim(); int dimensions = 0; while (name.endsWith("[]")) { dimensions++; name = name.substring(0, name.length() - 2); } TypeInfo result; switch (name) { case "boolean": result = context.TypeSystem.BooleanType; break; case "byte": result = context.TypeSystem.ByteType; break; case "char": result = context.TypeSystem.CharType; break; case "short": result = context.TypeSystem.ShortType; break; case "int": result = context.TypeSystem.IntType; break; case "long": result = context.TypeSystem.LongType; break; case "float": result = context.TypeSystem.FloatType; break; case "double": result = context.TypeSystem.DoubleType; break; default: int idx = name.indexOf("."); String prefix; if (idx == -1) { prefix = name; name = null; } else { prefix = name.substring(0, idx); name = name.substring(idx + 1); } var members = context.MemberResolver.resolveName(context.CurrentType, prefix, Query.empty<TypeInfo>()).toList(); if (!members.any()) { if (name == null) { return null; } var packageName = context.MemberResolver.getPackageFromAlias(prefix); if (packageName == null) { if (context.MemberResolver.TypeFinder.getSubPackages(prefix).any() || context.MemberResolver.TypeFinder.getClasses(prefix).any()) { packageName = prefix; } else { return null; } } var found = false; do { idx = name.indexOf('.'); if (idx == -1) { prefix = name; name = null; } else { prefix = name.substring(0, idx); name = name.substring(idx + 1); } foreach (var s in context.MemberResolver.TypeFinder.getSubPackages(packageName)) { if (s.equals(prefix)) { packageName = packageName + '/' + prefix; found = true; break; } } if (!found && !context.MemberResolver.TypeFinder.getClasses(packageName).contains(prefix)) { return null; } } while (name != null && found); result = context.TypeSystem.getType(packageName + '/' + prefix); } else if (members.count() > 1) { return null; } else { result = members.first().Type; } break; } while (dimensions-- > 0) { type = type.ArrayType; } return result; }
private void replaceCref(Element element, bool exception, Iterable<MemberInfo> members, String suffix, String arguments) { if (members.count() > 1 && !members.all(p => p.MemberKind == MemberKind.Method)) { context.addWarning(CompileErrorId.UnresolvedCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); return; } var member = members.first(); switch (member.MemberKind) { case Type: replaceCref(element, exception, member.Type, suffix, arguments); break; case Field: if (exception) { context.addWarning(CompileErrorId.ExpectedExceptionInCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); return; } if (suffix != null || arguments != null) { context.addWarning(CompileErrorId.UnresolvedCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); return; } element.setAttribute("cref", getIdString(member.Field)); break; case Property: if (exception) { context.addWarning(CompileErrorId.ExpectedExceptionInCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); return; } if (suffix != null || arguments != null) { context.addWarning(CompileErrorId.UnresolvedCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); return; } element.setAttribute("cref", getIdString(member.GetAccessor ?? member.SetAccessor)); break; case Method: if (!exception && suffix == null) { if (arguments == null && members.count() == 1) { element.setAttribute("cref", getIdString(member.Method)); return; } else if (arguments != null && arguments.endsWith(")")) { var args = new ArrayList<TypeInfo>(); if (arguments.length() > 2) { arguments = arguments.substring(1, arguments.length() - 1); int idx; while ((idx = arguments.indexOf(',')) != -1) { var name = arguments.substring(0, idx); arguments = arguments.substring(idx + 1); var type = getType(name); if (type == null) { goto failed; } args.add(type); } if (arguments.length() == 0) { goto failed; } var type = getType(arguments); if (type == null) { goto failed; } args.add(type); } foreach (var m in members) { if (m.Method.Parameters.select(p => p.Type).sequenceEqual(args)) { element.setAttribute("cref", getIdString(m.Method)); return; } } } } failed: context.addWarning(CompileErrorId.UnresolvedCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); break; default: break; } }
private void replaceCref(Element element, bool exception, TypeInfo type, String suffix, String arguments) { if (suffix == null) { if (arguments != null) { context.addWarning(CompileErrorId.UnresolvedCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); return; } if (exception) { if (!context.TypeSystem.getType("java/lang/Throwable").isAssignableFrom(type)) { context.addWarning(CompileErrorId.ExpectedExceptionInCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); return; } } element.setAttribute("cref", getIdString(type)); } else { int idx = suffix.indexOf('.'); String name; if (idx == -1) { name = suffix; suffix = null; } else { name = suffix.substring(0, idx); suffix = suffix.substring(idx + 1); } var members = MemberInfo.getMembers(context.AnnotatedTypeSystem, context.CurrentType, type, name, true); replaceCref(element, exception, members, suffix, arguments); } }
public static String quote(String s) { int slashEIndex = s.indexOf(new String("\\E")); if (slashEIndex == -1) return new String("\\Q" + s + "\\E"); StringBuilder sb = new StringBuilder(s.length() * 2); sb.append("\\Q"); slashEIndex = 0; int current = 0; while ((slashEIndex = s.indexOf(new String("\\E"), current)) != -1) { sb.append(s.substring(current, slashEIndex)); current = slashEIndex + 2; sb.append("\\E\\\\E\\Q"); } sb.append(s.substring(current, s.length())); sb.append("\\E"); return sb.toString(); }
private TypeInfo getTypeInfo(String name) { int idx = name.indexOf('$'); if (idx == -1) { return typeSystem.getType(name); } var type = typeSystem.getType(name.substring(0, idx)); name = name.substring(idx + 1); while ((idx = name.indexOf('$')) != -1) { type = type.getNestedType(name.substring(0, idx)); name = name.substring(idx + 1); } return type; }
private String composeOneStep(String input) { int len = countChars(input, 0, 2); String firstTwoCharacters = input.substring(0, len); String result = Normalizer.normalize(firstTwoCharacters, Normalizer.Form.NFC); if (result.equals(firstTwoCharacters)) return null; else { String remainder = input.substring(len); return result + remainder; } }
public static TypeInfo getType(Library typeSystem, String fullName) { TypeInfo result = null; int index; while ((index = fullName.indexOf('$')) != -1) { String prefix = fullName.substring(0, index); if (result == null) { result = typeSystem.getType(prefix); } else { result = result.getNestedType(prefix); } fullName = fullName.substring(index + 1); } if (result == null) { result = typeSystem.getType(fullName); } else { result = result.getNestedType(fullName); } return result; }
public static String getExtension(String path) { if (path != null) { int index = path.lastIndexOf('.'); if (index == -1) { return ""; } return path.substring(index); } return null; }
/** * Exhaustively searches for phone numbers from each index within {@code text} to test that * finding matches always terminates. */ private void ensureTermination(String text, String defaultCountry, Leniency leniency) { for (int index = 0; index <= text.length(); index++) { String sub = text.substring(index); StringBuilder matches = new StringBuilder(); // Iterates over all matches. foreach(PhoneNumberMatch match in phoneUtil.findNumbers(sub, defaultCountry, leniency, Long.MAX_VALUE)) { matches.append(", ").append(match.toString()); } } }