下面列出了怎么用java.util.UnknownFormatConversionException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void onProgressUpdate(Integer... values) {
try {
//LogUtils.i(TAG, "progress:" + ((tmp + loaded) / Float.valueOf(totals) * 100) + "tmp:" + tmp + " load=:" + loaded + " total:" + totals);
long c = System.currentTimeMillis();
if (mNotify != null && c - time > 800) {
time = c;
if (!mNotify.hasDeleteContent())
mNotify.setDelecte(buildCancelContent(mDownLoadTask.getContext().getApplicationContext(), mDownLoadTask.getId()));
int mProgress = (int) ((tmp + loaded) / Float.valueOf(totals) * 100);
mNotify.setContentText(String.format(mDownLoadTask.getDownLoadMsgConfig().getLoading(), mProgress + "%"));
mNotify.setProgress(100, mProgress, false);
}
} catch (UnknownFormatConversionException e) {
e.printStackTrace();
}
long current = System.currentTimeMillis();
used = current - begin;
}
public static String getFormattedString(@StringRes int resId, Resources resources,
Object... formatArgs) {
String result;
try {
result = resources.getString(resId, formatArgs);
} catch (UnknownFormatConversionException ex) {
final String resourceEntryName = resources.getResourceEntryName(resId);
final String displayLanguage = Locale.getDefault()
.getDisplayLanguage();
Logger.getInstance()
.e("UnknownFormatConversion",
"String: " + resourceEntryName + " Locale: " + displayLanguage);
result = ResourseU.getString(resId, resources);
}
return result;
}
private void checkText() {
if (precision != -1)
throw new IllegalFormatPrecisionException(precision);
switch (c) {
case Conversion.PERCENT_SIGN:
if (f.valueOf() != Flags.LEFT_JUSTIFY.valueOf()
&& f.valueOf() != Flags.NONE.valueOf())
throw new IllegalFormatFlagsException(f.toString());
// '-' requires a width
if (width == -1 && f.contains(Flags.LEFT_JUSTIFY))
throw new MissingFormatWidthException(toString());
break;
case Conversion.LINE_SEPARATOR:
if (width != -1)
throw new IllegalFormatWidthException(width);
if (f.valueOf() != Flags.NONE.valueOf())
throw new IllegalFormatFlagsException(f.toString());
break;
default:
throw new UnknownFormatConversionException(String.valueOf(c));
}
}
@Test(expected = UnknownFormatConversionException.class)
public void failsForInvalidPattern() throws Exception {
new FormattedText(
new TextOf("%%. Formatted %$"),
new ListOf<>(1, "invalid")
).asString();
}
@Override
protected String doInBackground(InputStream... params) {
try {
parseELF(callback, params[0]);
} catch (UnknownFormatConversionException | IOException e) {
e.printStackTrace();
return "failed";
}
return getString(R.string.success);
}
public Long fromString(String string) {
if (string == null || string.isEmpty()) return null;
Matcher matcher = ValueWithUnit.matcher(string.toLowerCase());
if (!matcher.matches()) throw new UnknownFormatConversionException(String.format("Invalid format %s", string));
Long value = Long.valueOf(matcher.group(1));
String unit = matcher.group(2);
if (unit.isEmpty()) return value;
int index = units.toLowerCase().indexOf(unit.toLowerCase());
return value * (long) Math.pow(getBase(), (double) index + 1);
}
public static String getFormattedString(Context context, @StringRes int resId, Object... formatArgs) {
String result;
final Resources resources = context.getResources();
try {
result = resources.getString(resId, formatArgs);
}catch (UnknownFormatConversionException ex){
final String resourceEntryName = resources.getResourceEntryName(resId);
final String displayLanguage = Locale.getDefault().getDisplayLanguage();
Logger.e("UnknownFormatConversion", "String: " + resourceEntryName + " Locale: " + displayLanguage);
Crashlytics.log(3, "UnknownFormatConversion", "String: " + resourceEntryName + " Locale: " + displayLanguage);
result = resources.getString(resId);
}
return result;
}
private static String safeFormatString(int maxIterations, String format, Object... args) {
while (maxIterations-- > 0) {
try {
return String.format(format, args);
} catch (UnknownFormatConversionException e) {
format = format.replace("%" + e.getConversion(), "%s"); // NOI18N
}
}
return format;
}
@Override
public char asCharacter() {
if (value.length() != 1) {
throw new UnknownFormatConversionException("Unable to convert string to character!");
}
return value.charAt(0);
}
/**
* java.util.UnknownFormatConversionException#UnknownFormatConversionException(String)
*/
public void test_unknownFormatConversionException() {
// RI 5.0 will not throw NullPointerException, it is the bug according
// to spec.
try {
new UnknownFormatConversionException(null);
fail("should throw NullPointerExcepiton");
} catch (NullPointerException e) {
}
}
/**
* java.util.UnknownFormatConversionException#getConversion()
*/
public void test_getConversion() {
String s = "MYTESTSTRING";
UnknownFormatConversionException UnknownFormatConversionException = new UnknownFormatConversionException(
s);
assertEquals(s, UnknownFormatConversionException.getConversion());
}
/**
* java.util.UnknownFormatConversionException#getMessage()
*/
public void test_getMessage() {
String s = "MYTESTSTRING";
UnknownFormatConversionException UnknownFormatConversionException = new UnknownFormatConversionException(
s);
assertTrue(null != UnknownFormatConversionException.getMessage());
}
public void assertDeserialized(Serializable initial,
Serializable deserialized) {
SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
deserialized);
UnknownFormatConversionException initEx = (UnknownFormatConversionException) initial;
UnknownFormatConversionException desrEx = (UnknownFormatConversionException) deserialized;
assertEquals("Conversion", initEx.getConversion(), desrEx
.getConversion());
}
/**
* serialization/deserialization compatibility with RI.
*/
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this,
new UnknownFormatConversionException("MYTESTSTRING"),
exComparator);
}
private char conversion(String s) {
c = s.charAt(0);
if (!dt) {
if (!Conversion.isValid(c))
throw new UnknownFormatConversionException(String.valueOf(c));
if (Character.isUpperCase(c))
f.add(Flags.UPPERCASE);
c = Character.toLowerCase(c);
if (Conversion.isText(c))
index = -2;
}
return c;
}
FormatSpecifier(String source, String[] sa)
throws FormatFlagsConversionMismatchException,
FormatterNumberFormatException {
int idx = 0;
this.source = source;
index(sa[idx++]);
flags(sa[idx++]);
width(sa[idx++]);
precision(sa[idx++]);
if (sa[idx] != null) {
dt = true;
if (sa[idx].equals("T"))
f.add(Flags.UPPERCASE);
}
conversion(sa[++idx]);
if (dt)
checkDateTime();
else if (Conversion.isGeneral(c))
checkGeneral();
else if (Conversion.isCharacter(c))
checkCharacter();
else if (Conversion.isInteger(c))
checkInteger();
else if (Conversion.isFloat(c))
checkFloat();
else if (Conversion.isText(c))
checkText();
else
throw new UnknownFormatConversionException(String.valueOf(c));
}
private void checkDateTime() throws FormatFlagsConversionMismatchException {
if (precision != -1)
throw new IllegalFormatPrecisionException(precision);
if (!DateTime.isValid(c))
throw new UnknownFormatConversionException("t" + c);
checkBadFlags(Flags.ALTERNATE, Flags.PLUS, Flags.LEADING_SPACE,
Flags.ZERO_PAD, Flags.GROUP, Flags.PARENTHESES);
// '-' requires a width
if (width == -1 && f.contains(Flags.LEFT_JUSTIFY))
throw new MissingFormatWidthException(toString());
}
private static void checkText(String s) {
int idx;
// If there are any '%' in the given string, we got a bad format
// specifier.
if ((idx = s.indexOf('%')) != -1) {
char c = (idx > s.length() - 2 ? '%' : s.charAt(idx + 1));
throw new UnknownFormatConversionException(String.valueOf(c));
}
}
default RDFNode getBindingValue(RDFNode node, Shape shape) {
// when non formatting query exists return the same value
if (!getValueFormatter().isPresent()) {
return node;
}
Resource formatter = getValueFormatter().get();
if (RDFUNIT_SHACL_EXT.FormatListCommaSeparated.equals(formatter)) {
return ResourceFactory.createStringLiteral(
RdfListUtils.getListItemsOrEmpty(node).stream()
.map(NodeFormatter::formatNode)
.collect(Collectors.joining(" , ")).trim()
);
}
if (RDFUNIT_SHACL_EXT.FormatListSpaceSeparated.equals(formatter)) {
return ResourceFactory.createStringLiteral(
RdfListUtils.getListItemsOrEmpty(node).stream()
.map(NodeFormatter::formatNode)
.collect(Collectors.joining(" ")).trim()
);
}
// get sh:property/sh:path (where sh:path is not a blank node
if (RDFUNIT_SHACL_EXT.FormatClosedPredicatesAsCommaSeparated.equals(formatter)) {
return ResourceFactory.createStringLiteral(
shape.getElement().listProperties(SHACL.property).toSet().stream()
.map(Statement::getObject)
.filter(RDFNode::isResource)
.map(RDFNode::asResource)
.flatMap(s -> s.listProperties(SHACL.path).toSet().stream())
.map(Statement::getObject)
.filter(RDFNode::isResource)
.map(RDFNode::asResource)
.filter(Resource::isURIResource)
.map(NodeFormatter::formatNode)
.collect(Collectors.joining(" , ")).trim()
);
}
throw new UnknownFormatConversionException("Cannot find formatter for " + formatter);
}
/**
* Finds a {@link TypeConverter} for the given {@link Type}, falling back to an assignment-compatible TypeConverter
* if none exist for the given type. That is, if the given Type does not have a TypeConverter, but another Type
* which can be assigned to the given Type <em>does</em> have a TypeConverter, then that TypeConverter will be
* used and registered.
*
* @param type the Type to find a TypeConverter for (must not be {@code null}).
* @return a TypeConverter for the given Type.
* @throws UnknownFormatConversionException if no TypeConverter can be found for the given type.
*/
public TypeConverter<?> findCompatibleConverter(final Type type) {
Objects.requireNonNull(type, "No type was provided");
final TypeConverter<?> primary = registry.get(type);
// cached type converters
if (primary != null) {
return primary;
}
// dynamic enum support
if (type instanceof Class<?>) {
final Class<?> clazz = (Class<?>) type;
if (clazz.isEnum()) {
@SuppressWarnings({"unchecked","rawtypes"})
final EnumConverter<? extends Enum> converter = new EnumConverter(clazz.asSubclass(Enum.class));
registry.putIfAbsent(type, converter);
return converter;
}
}
// look for compatible converters
for (final Map.Entry<Type, TypeConverter<?>> entry : registry.entrySet()) {
final Type key = entry.getKey();
if (TypeUtil.isAssignable(type, key)) {
LOGGER.debug("Found compatible TypeConverter<{}> for type [{}].", key, type);
final TypeConverter<?> value = entry.getValue();
registry.putIfAbsent(type, value);
return value;
}
}
throw new UnknownFormatConversionException(type.toString());
}
public Elf(File file) throws IOException, UnknownFormatConversionException {
this(new ByteArrayInputStream(readFile(file)));
}
public Elf(String file) throws IOException, UnknownFormatConversionException {
this(new File(file));
}
public Elf(String file, boolean closeNow) throws IOException, UnknownFormatConversionException {
this(file);
if (closeNow) {
mReader.close();
}
}
/**
* serialization/deserialization.
*/
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new UnknownFormatConversionException(
"MYTESTSTRING"), exComparator);
}
/**
* Perform Python-style string formatting, similar to the {@code pattern % tuple} syntax.
*
* <p>Same as {@link #format(String, Object...)}, but with a list instead of variadic args.
*/
@Override
public BasePrinter formatWithList(String pattern, List<?> arguments) {
// TODO(bazel-team): support formatting arguments, and more complex Python patterns.
// N.B. MissingFormatWidthException is the only kind of IllegalFormatException
// whose constructor can take and display arbitrary error message, hence its use below.
int length = pattern.length();
int argLength = arguments.size();
int i = 0; // index of next character in pattern
int a = 0; // index of next argument in arguments
while (i < length) {
int p = pattern.indexOf('%', i);
if (p == -1) {
Printer.append(buffer, pattern, i, length);
break;
}
if (p > i) {
Printer.append(buffer, pattern, i, p);
}
if (p == length - 1) {
throw new MissingFormatWidthException(
"incomplete format pattern ends with %: " + this.repr(pattern));
}
char directive = pattern.charAt(p + 1);
i = p + 2;
switch (directive) {
case '%':
this.append('%');
continue;
case 'd':
case 'r':
case 's':
if (simplifiedFormatStrings && (directive != 's')) {
throw new UnknownFormatConversionException(
"cannot use %" + directive + " substitution placeholder when "
+ "simplifiedFormatStrings is set");
}
if (a >= argLength) {
throw new MissingFormatWidthException(
"not enough arguments for format pattern "
+ Starlark.repr(pattern)
+ ": "
+ Starlark.repr(Tuple.copyOf(arguments)));
}
Object argument = arguments.get(a++);
switch (directive) {
case 'd':
if (argument instanceof Integer) {
this.append(argument.toString());
continue;
} else {
throw new MissingFormatWidthException(
"invalid argument " + Starlark.repr(argument) + " for format pattern %d");
}
case 'r':
this.repr(argument);
continue;
case 's':
this.str(argument);
continue;
}
// fall through
default:
throw new MissingFormatWidthException(
// The call to Starlark.repr doesn't cause an infinite recursion because it's
// only used to format a string properly
String.format(
"unsupported format character \"%s\" at index %s in %s",
String.valueOf(directive), p + 1, Starlark.repr(pattern)));
}
}
if (a < argLength) {
throw new MissingFormatWidthException(
"not all arguments converted during string formatting");
}
return this;
}
public void print(String arg, int argIndex)
throws IllegalFormatConversionException,
FormatFlagsConversionMismatchException {
try {
if (arg.charAt(0) == '[')
failConversion(arg);
if (dt) {
printDateTime(arg);
return;
}
switch (c) {
case Conversion.DECIMAL_INTEGER:
case Conversion.OCTAL_INTEGER:
case Conversion.HEXADECIMAL_INTEGER:
printInteger(arg);
break;
case Conversion.SCIENTIFIC:
case Conversion.GENERAL:
case Conversion.DECIMAL_FLOAT:
case Conversion.HEXADECIMAL_FLOAT:
printFloat(arg);
break;
case Conversion.CHARACTER:
case Conversion.CHARACTER_UPPER:
printCharacter(arg);
break;
case Conversion.BOOLEAN:
printBoolean(arg);
break;
case Conversion.STRING:
case Conversion.HASHCODE:
case Conversion.LINE_SEPARATOR:
case Conversion.PERCENT_SIGN:
break;
default:
throw new UnknownFormatConversionException(String.valueOf(c));
}
} catch (IllegalFormatConversionException e) {
e.setArgIndex(argIndex);
throw e;
}
}
/**
* ELF解析器
*
* @param result
* 用来存放结果
* @param is
* 文件输入流
**/
public void parseELF(ResourceCallBack callBack, InputStream is)
throws UnknownFormatConversionException, IOException {
elfParser = new Elf(new ByteArrayInputStream(InputStream2ByteArray(is)), callBack);
}