下面列出了怎么用java.util.IllegalFormatException的API类实例代码及写法,或者点击链接到github查看源代码。
public Map<String, String> makeExtraInfo(Map<String, String> info) {
if (info == null) {
return Maps.newHashMap();
}
// post process
if (info.containsKey(MR_JOB_ID) && !info.containsKey(YARN_APP_ID)) {
String jobId = info.get(MR_JOB_ID);
if (jobId.startsWith("job_")) {
info.put(YARN_APP_ID, jobId.replace("job_", "application_"));
}
}
if (info.containsKey(YARN_APP_ID)
&& !org.apache.commons.lang3.StringUtils.isEmpty(getConfig().getJobTrackingURLPattern())) {
String pattern = getConfig().getJobTrackingURLPattern();
try {
String newTrackingURL = String.format(Locale.ROOT, pattern, info.get(YARN_APP_ID));
info.put(YARN_APP_URL, newTrackingURL);
} catch (IllegalFormatException ife) {
logger.error("Illegal tracking url pattern: {}", getConfig().getJobTrackingURLPattern());
}
}
return info;
}
@Test
public void usesTheClosestFallback() throws Exception {
final String expected = "Fallback from IllegalFormatException";
MatcherAssert.assertThat(
"Can't find the closest fallback",
new FuncWithFallback<>(
input -> {
throw new IllegalFormatWidthException(1);
},
new IterableOf<>(
new FallbackFrom<>(
IllegalArgumentException.class,
exp -> "Fallback from IllegalArgumentException"
),
new FallbackFrom<>(
IllegalFormatException.class,
exp -> expected
)
)
),
new FuncApplies<>(1, expected)
);
}
@Test
public void usesTheClosestFallback() throws Exception {
final String expected = "Fallback from IllegalFormatException";
new Assertion<>(
"Must find the closest fallback",
new ScalarWithFallback<>(
() -> {
throw new IllegalFormatWidthException(1);
},
new IterableOf<>(
new FallbackFrom<>(
new IterableOf<>(IllegalArgumentException.class),
exp -> "Fallback from IllegalArgumentException"
),
new FallbackFrom<>(
new IterableOf<>(IllegalFormatException.class),
exp -> expected
)
)
),
new ScalarHasValue<>(expected)
).affirm();
}
/**
* Construct a status object based on error code and a list of arguments. It is
* the most popular way to create status object from status.yml definition.
*
* @param code Error Code
* @param args A list of arguments that will be populated into the error description
*/
public Status(final String code, final Object... args) {
this.code = code;
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) config.get(code);
if (map != null) {
this.statusCode = (Integer) map.get("statusCode");
this.message = (String) map.get("message");
this.description = (String) map.get("description");
try {
this.description = format(this.description, args);
} catch (IllegalFormatException e) {
// logger.warn(format("Error formatting description of status %s", code), e);
}
if ((this.severity = (String) map.get("severity")) == null)
this.severity = defaultSeverity;
}
}
/**
* Attempt to format the tag value; if the actual tag value is missing or
* the tag value could not be formatted for whatever reason, then the
* <code>toString</code> of the argument array is appended to the tag
* value...
*/
@java.lang.SuppressWarnings("squid:S4973")
private static String formatValue(Locale locale, String tagValue, String tag, Object... arguments) {
String formattedTagValue;
// The identity equality is fine; that's what I want!
if (tagValue != tag) {
try {
// The locale is required for example to convert a double into
// its string representation
// when processing %s (of a double value) or even a %d I guess
// (e.g., using '.' or ',' )
formattedTagValue = String.format(locale, tagValue, arguments);
} catch (IllegalFormatException ex) {
Log.warn("Illegal format for tag [" + tag + "] - " + ex.getMessage(), ex);
formattedTagValue = tagValue + " " + Arrays.toString(arguments);
// what else can I do here?
}
} else {
formattedTagValue = tagValue + " " + Arrays.toString(arguments);
// what else can I do here?
}
return formattedTagValue;
}
public NodeValue exec(List<NodeValue> args, FunctionEnv env) {
if (args.size() < 1) {
LOG.debug("Expecting at least one arguments.");
throw new ExprEvalException("Expecting at least one arguments.");
}
final NodeValue format = args.get(0);
if (!format.isIRI() && !format.isString() && !format.asNode().isLiteral()) {
LOG.debug("First argument must be a URI or a String.");
throw new ExprEvalException("First argument must be a URI or a String.");
}
Object[] params = new String[args.size() - 1];
for (int i = 0; i < args.size() - 1; i++) {
params[i] = args.get(i + 1).asUnquotedString();
}
try {
String output = String.format(getString(format, env), params);
return new NodeValueString(output);
} catch (IllegalFormatException ex) {
throw new ExprEvalException("Exception while executing st:format(" + args + ")");
}
}
/**
* Logs a formatted string to the console.
*
* <p>Example usage: <br>
* <code>
* LogUtils.log("LogUtils", Log.ERROR, myException, "Invalid value: %d", value);
* </code>
*
* @param tag The tag that should be associated with the event
* @param priority The log entry priority, see {@link Log#println(int, String, String)}
* @param throwable A {@link Throwable} containing system state information to log
* @param format A format string, see {@link String#format(String, Object...)}
* @param args String formatter arguments
*/
public static void log(
String tag,
int priority,
@Nullable Throwable throwable,
@Nullable String format,
Object... args) {
if (priority < sLogLevel) {
return;
}
try {
String message = String.format(Strings.nullToEmpty(format), args);
if (throwable == null) {
Log.println(priority, tag, message);
} else {
Log.println(
priority, tag, String.format("%s\n%s", message, Log.getStackTraceString(throwable)));
}
} catch (IllegalFormatException e) {
Log.e(TAG, "Bad formatting string: \"" + format + "\"", e);
}
}
@Override
public String getMessage() {
if (formatted == null) {
formatted = super.getMessage();
if (params != null) {
try {
formatted = String.format(formatted.replaceAll("\\{\\}", "%s"), params);
} catch (final IllegalFormatException ife) {
try {
formatted = MessageFormat.format(formatted, params);
} catch (final IllegalArgumentException iae) {
}
}
}
}
return formatted;
}
@Override
public String getMessage() {
if (formatted == null) {
formatted = super.getMessage();
if (params != null) {
try {
formatted = String.format(formatted.replaceAll("\\{\\}", "%s"), params);
} catch (final IllegalFormatException ife) {
try {
formatted = MessageFormat.format(formatted, params);
} catch (final IllegalArgumentException iae) {
}
}
}
}
return formatted;
}
public void appendFormattedMessage(StringBuilder sb) {
// Unfortunately, there's no public API to reset a Formatter's
// Appendable. If this proves to be a perf issue, we can do
// runtime introspection to access the private Formatter.init()
// API to replace the Appendable.
try (Formatter f = new Formatter(sb, Locale.US)) {
f.format(getMessage(), getParameters());
} catch (IllegalFormatException e) {
sb.append("Invalid format string: ");
sb.append(displayLevel);
sb.append(" '");
sb.append(getMessage());
sb.append("' ");
Object[] params = getParameters();
if (params == null) {
params = new Object[0];
}
sb.append(Arrays.asList(params));
} catch (ConcurrentModificationException originalException) {
// This way we may be at least able to figure out where offending log was created.
throw new ConcurrentModificationException(
"Concurrent modification when logging for message " + getMessage(), originalException);
}
}
private static Slice sqlFormat(ConnectorSession session, String format, Object[] args)
{
try {
return utf8Slice(format(session.getLocale(), format, args));
}
catch (IllegalFormatException e) {
String message = e.toString().replaceFirst("^java\\.util\\.(\\w+)Exception", "$1");
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid format string: %s (%s)", format, message), e);
}
}
private static String format(String defaultMessage, @Nullable String message, @Nullable Object... args) {
if (message == null) {
return defaultMessage;
}
try {
return String.format(message, args);
} catch (IllegalFormatException ex) {
return message;
}
}
@Test
public void supportsInheritedException() {
new Assertion<>(
"Must support inherited exception class",
new FallbackFrom<>(
new IterableOf<>(RuntimeException.class),
exp -> "RuntimeException fallback #1"
).support(IllegalFormatException.class),
new IsEqual<>(2)
).affirm();
}
private void append(@NotNull String format, @NotNull Object... args) {
try {
sb.append(String.format(format, args));
} catch (IllegalFormatException e) {
require(false, "String from manifest contained format flags: %s", e.getMessage());
}
}
@NotNull
public static String safeFormat(@NotNull String format, Object ... args) {
try {
return String.format(format, args);
} catch (IllegalFormatException e) {
// It looks like format characters coming from the user in some way.
// Provide a safe alternative that has all the same information.
return format + " with parameters {" + joinOn(", ", args) + "}";
}
}
private static String formatMessage(String message, Throwable t, Object... args) {
try {
return String.format(Locale.ROOT, message, args);
} catch (IllegalFormatException e) {
BufferAllocationException substitute =
new BufferAllocationException(message + " [ILLEGAL FORMAT, ARGS SUPPRESSED]");
if (t != null) {
substitute.addSuppressed(t);
}
substitute.addSuppressed(e);
throw substitute;
}
}
private Object evaluateFormatExpression(ELContext context, Object method, Object[] params) {
if (!FORMAT.equals(method)) {
throw new ELException("Wrong method name 'formatter#" + method + "' does not exist. Only formatter#format is supported.");
}
if (params.length == 0) {
throw new ELException("Invalid number of arguments to Formatter#format");
}
if (!(params[0] instanceof String)) {
throw new ELException("The first argument to Formatter#format must be String");
}
FormatterWrapper formatterWrapper = (FormatterWrapper) context.getVariableMapper()
.resolveVariable(FORMATTER)
.getValue(context);
Object[] formattingParameters = new Object[params.length - 1];
System.arraycopy(params, 1, formattingParameters, 0, params.length - 1);
Object returnValue;
try {
returnValue = formatterWrapper.format((String) params[0], formattingParameters);
context.setPropertyResolved(true);
} catch (IllegalFormatException e) {
throw new ELException("Error in Formatter#format call", e);
}
return returnValue;
}
public void setLibProperties(Map<String, Object> dataModel) throws IllegalFormatException {
// get file name only
String libTopName = srcFile.getName();
// make a separate hash as well, easier to pass around
Map<String, Object> libInfo = makeObjectMap();
libInfo.put("libTopName", FtlDocUtil.replaceExtension(libTopName, ""));
libInfo.put("libFilename", getLibFilename());
libInfo.put("libFormat", getLibFormat());
libInfo.put("libName", getLibName());
libInfo.put("libDocPath", getLibDocPath());
// map for easy passing
dataModel.put("libInfo", libInfo);
// putall for easy access
dataModel.putAll(libInfo);
}
@Override
public String toString() {
try {
final String val = getValue();
return val == null ? key : "" + String.format(val, args);
} catch (final IllegalFormatException e) {
final String m = "The formatted message '" + key + "' uses an illegal format: " + e.getLocalizedMessage();
Skript.adminBroadcast("<red>" + m);
System.err.println("[Skript] " + m);
e.printStackTrace();
return "[ERROR]";
}
}
public String toString(final Object... args) {
try {
final String val = getValue();
return val == null ? key : "" + String.format(val, args);
} catch (final IllegalFormatException e) {
final String m = "The formatted message '" + key + "' uses an illegal format: " + e.getLocalizedMessage();
Skript.adminBroadcast("<red>" + m);
System.err.println("[Skript] " + m);
e.printStackTrace();
return "[ERROR]";
}
}
@Override
public String toCellRendererValue(Double value) {
String result = "";
if (value != null) {
try {
result = String.format("%.2f", value);
} catch (IllegalFormatException e) {
result = "#getter did not return a double";
}
}
return result;
}
@Override
public String toCellRendererValue(Integer value) {
String result = "";
if (value != null) {
try {
result = String.format("%d", value);
} catch (IllegalFormatException e) {
result = "#getter did not return an int";
}
}
return result;
}
/**
* Logs a formatted string to the console using the source object's name as the log tag. If the
* source object is null, the default tag (see {@link LogUtils#TAG}) is used.
*
* <p>Example usage: <br>
* <code>
* LogUtils.log(this, Log.ERROR, "Invalid value: %d", value);
* </code>
*
* @param source The object that generated the log event.
* @param priority The log entry priority, see {@link Log#println(int, String, String)}.
* @param throwable A {@link Throwable} containing system state information to log
* @param format A format string, see {@link String#format(String, Object...)}.
* @param args String formatter arguments.
*/
public static void log(
@Nullable Object source,
int priority,
@Nullable Throwable throwable,
String format,
Object... args) {
if (priority < sLogLevel) {
return;
}
final String sourceClass;
if (source == null) {
sourceClass = TAG;
} else if (source instanceof Class<?>) {
sourceClass = ((Class<?>) source).getSimpleName();
} else {
sourceClass = source.getClass().getSimpleName();
}
try {
String message = String.format(format, args);
if (throwable == null) {
Log.println(priority, sourceClass, message);
} else {
Log.println(
priority,
sourceClass,
String.format("%s\n%s", message, Log.getStackTraceString(throwable)));
}
} catch (IllegalFormatException e) {
Log.e(TAG, "Bad formatting string: \"" + format + "\"", e);
}
}
private void populateRatings(GetApp getApp) {
if (getApp.nodes == null || getApp.nodes.meta == null || getApp.nodes.meta.data== null
|| getApp.nodes.meta.data.stats == null|| getApp.nodes.meta.data.stats.rating == null){
return;
}
GetAppMeta.Stats.Rating ratings = getApp.nodes.meta.data.stats.rating;
try {
float numberfloat = ratings.avg.floatValue();
//Avg ratings
tvAgvRating.setText(String.format("%.1f", numberfloat));
} catch (NullPointerException | IllegalFormatException e) {
tvAgvRating.setText(ratings.avg.toString());
}
long numberVotes = ratings.votes.get(0).count.longValue() + ratings.votes.get(1).count.longValue()
+ ratings.votes.get(2).count.longValue() + ratings.votes.get(3).count.longValue()
+ ratings.votes.get(4).count.longValue();
tvNumberRates.setText(String.valueOf(numberVotes));
avgRatingBar.setRating(ratings.avg.floatValue());
//rating bars
progressBarRating5.setProgress(getPercentage(numberVotes, ratings.votes.get(0).count));
tvNumberOfStarts5.setText(ratings.votes.get(0).count.toString());
progressBarRating4.setProgress(getPercentage(numberVotes, ratings.votes.get(1).count));
tvNumberOfStarts4.setText(ratings.votes.get(1).count.toString());
progressBarRating3.setProgress(getPercentage(numberVotes, ratings.votes.get(2).count));
tvNumberOfStarts3.setText(ratings.votes.get(2).count.toString());
progressBarRating2.setProgress(getPercentage(numberVotes, ratings.votes.get(3).count));
tvNumberOfStarts2.setText(ratings.votes.get(3).count.toString());
progressBarRating1.setProgress(getPercentage(numberVotes, ratings.votes.get(4).count));
tvNumberOfStarts1.setText(ratings.votes.get(4).count.toString());
}
@Override
public String get(Locale locale, Object... args) {
// see net.minecraft.util.text.translation.LanguageMap
String unformatted = get(locale);
try {
return String.format(unformatted, args);
} catch (IllegalFormatException var5) {
return "Format error: " + unformatted;
}
}
public static TransportResult error(String format, Object... args)
{
String errorDescription;
try
{
errorDescription = String.format(format, args);
}
catch(IllegalFormatException e)
{
LOGGER.log(Level.SEVERE, "Formating error in string " + format, e);
errorDescription = format;
}
return new TransportResultImpl(ERROR, errorDescription, null);
}
/**
* Logs a formatted string to the console.
*
* <p>Example usage: <br>
* <code>
* LogUtils.log("LogUtils", Log.ERROR, myException, "Invalid value: %d", value);
* </code>
*
* @param tag The tag that should be associated with the event
* @param priority The log entry priority, see {@link Log#println(int, String, String)}
* @param throwable A {@link Throwable} containing system state information to log
* @param format A format string, see {@link String#format(String, Object...)}
* @param args String formatter arguments
*/
public static void log(
String tag,
int priority,
@Nullable Throwable throwable,
@Nullable String format,
Object... args) {
if (priority < sLogLevel) {
return;
}
String prefixedTag = sLogTagPrefix + tag;
try {
String message = String.format(Strings.nullToEmpty(format), args);
if (throwable == null) {
Log.println(priority, prefixedTag, message);
} else {
Log.println(
priority,
prefixedTag,
String.format("%s\n%s", message, Log.getStackTraceString(throwable)));
}
} catch (IllegalFormatException e) {
Log.e(TAG, "Bad formatting string: \"" + format + "\"", e);
}
}
@Override
public String getMessage() {
String result = Messages.getString("ScenarioLoaderException." + super.getMessage()); //$NON-NLS-1$
if(null != params) {
try {
return String.format(result, params);
} catch(IllegalFormatException ifex) {
// Ignore, return the base translation instead
}
}
return result;
}
private void validateSequenceFormat(PluginTask task)
{
try {
@SuppressWarnings("unused")
String dontCare = String.format(Locale.ENGLISH,
task.getSequenceFormat(), 0, 0);
}
catch (IllegalFormatException ex) {
throw new ConfigException(
"Invalid sequence_format: parameter for file output plugin",
ex);
}
}
private static String formatDescription(
String description, int errorCode, String detailedError) {
checkState(!TextUtils.isEmpty(description), "description cannot be empty!");
if (detailedError != null) {
try {
description = String.format(Locale.ROOT, description, errorCode, detailedError);
} catch (IllegalFormatException ife) {
Log.w(TAG, "Cannot format remote error description: " + description);
}
}
return description;
}