java.util.IllegalFormatException Java Examples

The following examples show how to use java.util.IllegalFormatException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Status.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
     * 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;

        }
    }
 
Example #2
Source File: AbstractExecutable.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: PromotionValidationException.java    From pnc with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: FuncWithFallbackTest.java    From cactoos with MIT License 6 votes vote down vote up
@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)
    );
}
 
Example #5
Source File: LogUtils.java    From talkback with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example #6
Source File: ScalarWithFallbackTest.java    From cactoos with MIT License 6 votes vote down vote up
@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();
}
 
Example #7
Source File: AppendableLogRecord.java    From buck with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #8
Source File: RepositoryManagerException.java    From pnc with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: ST_Format.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
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 + ")");
    }
}
 
Example #10
Source File: Babylon.java    From Dayon with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: S3FileOutputPlugin.java    From embulk-output-s3 with MIT License 5 votes vote down vote up
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);
    }
}
 
Example #12
Source File: ChannelState.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Publishes a value on MQTT. A command topic needs to be set in the configuration.
 *
 * @param command The command to send
 * @return A future that completes with true if the publishing worked and false and/or exceptionally otherwise.
 */
public CompletableFuture<@Nullable Void> publishValue(Command command) {
    cachedValue.update(command);

    String mqttCommandValue = cachedValue.getMQTTpublishValue();

    final MqttBrokerConnection connection = this.connection;

    if (!readOnly && connection != null) {
        // Formatter: Applied before the channel state value is published to the MQTT broker.
        if (config.formatBeforePublish.length() > 0) {
            try (Formatter formatter = new Formatter()) {
                Formatter format = formatter.format(config.formatBeforePublish, mqttCommandValue);
                mqttCommandValue = format.toString();
            } catch (IllegalFormatException e) {
                logger.debug("Format pattern incorrect for {}", channelUID, e);
            }
        }
        // Outgoing transformations
        for (ChannelStateTransformation t : transformationsOut) {
            mqttCommandValue = t.processValue(mqttCommandValue);
        }
        // Send retained messages if this is a stateful channel
        return connection.publish(config.commandTopic, mqttCommandValue.getBytes(), 1, config.retained)
                .thenRun(() -> {
                });
    } else {
        CompletableFuture<@Nullable Void> f = new CompletableFuture<>();
        f.completeExceptionally(new IllegalStateException("No connection or readOnly channel!"));
        return f;
    }
}
 
Example #13
Source File: FormatterTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void formatTo(Formatter formatter, int flags, int width,
        int precision) throws IllegalFormatException {
    if ((flags & FormattableFlags.UPPERCASE) != 0) {
        formatter.format("CUSTOMIZED FORMAT FUNCTION" + " WIDTH: "
                + width + " PRECISION: " + precision);
    } else {
        formatter.format("customized format function" + " width: "
                + width + " precision: " + precision);
    }
}
 
Example #14
Source File: InteractionResponse.java    From android-test with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #15
Source File: JavaConsole.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void printf(String format, Object... args) throws IllegalFormatException {
    if (hasConsole()) {
        theConsole.printf(format, args);
    } else {
        System.out.format(format, args);
    }
}
 
Example #16
Source File: FormatFunction.java    From presto with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #17
Source File: LogUtils.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example #18
Source File: LogUtils.java    From brailleback with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example #19
Source File: JavaConsole.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void format(String fmt, Object... args) throws IllegalFormatException {
    if (hasConsole()) {
        theConsole.format(fmt, args);
    } else {
        System.out.format(fmt, args);
    }
}
 
Example #20
Source File: ScenarioLoader.java    From megamek with GNU General Public License v2.0 5 votes vote down vote up
@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;
}
 
Example #21
Source File: JavaConsole.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public char[] readPassword(String fmt, Object... args) throws IllegalFormatException, IOError {
    if (hasConsole()) {
        return theConsole.readPassword(fmt, args);
    } else {
        throw ROOT_LOGGER.noConsoleAvailable();
    }
}
 
Example #22
Source File: PrinterTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimplifiedDisallowsPlaceholdersBesidesPercentS() {
  assertThat(makeSimplifiedFormatPrinter().format("Allowed: %%").toString())
      .isEqualTo("Allowed: %");
  assertThat(makeSimplifiedFormatPrinter().format("Allowed: %s", "abc").toString())
      .isEqualTo("Allowed: abc");
  assertThrows(
      IllegalFormatException.class,
      () -> makeSimplifiedFormatPrinter().format("Disallowed: %r", "abc"));
  assertThrows(
      IllegalFormatException.class,
      () -> makeSimplifiedFormatPrinter().format("Disallowed: %d", 5));
}
 
Example #23
Source File: Functions.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
public String evaluate(Number input, String pattern){

			// According to the java.util.Formatter javadoc, Java formatting is more strict than C's printf formatting.
			// For example, in Java, if a conversion is incompatible with a flag, an exception will be thrown. In C's printf, inapplicable flags are silently ignored.
			try {
				return String.format(pattern, input);
			} catch(IllegalFormatException ife){
				throw new FunctionException(this, "Invalid \"pattern\" value")
					.initCause(ife);
			}
		}
 
Example #24
Source File: Functions.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
public String evaluate(Date input, String pattern){
	pattern = translatePattern(pattern);

	try {
		return String.format(pattern, input);
	} catch(IllegalFormatException ife){
		throw new FunctionException(this, "Invalid \"pattern\" value")
			.initCause(ife);
	}
}
 
Example #25
Source File: Frame.java    From h2o-2 with Apache License 2.0 5 votes vote down vote up
public StringBuilder toString( StringBuilder sb, String[] fs, long idx ) {
  Vec vecs[] = vecs();
  for( int c=0; c<fs.length; c++ ) {
    Vec vec = vecs[c];
    if( vec.isEnum() ) {
      String s = "----------";
      if( !vec.isNA(idx) ) {
        int x = (int)vec.at8(idx);
        if( x >= 0 && x < vec._domain.length ) s = vec._domain[x];
      }
      sb.append(String.format(fs[c],s));
    } else if( vec.isInt() ) {
      if( vec.isNA(idx) ) {
        Chunk C = vec.chunkForChunkIdx(0);   // 1st Chunk
        int len = C.pformat_len0();  // Printable width
        for( int i=0; i<len; i++ ) sb.append('-');
      } else {
        try {
          if( vec.isUUID() ) sb.append(PrettyPrint.UUID(vec.at16l(idx),vec.at16h(idx)));
          else sb.append(String.format(fs[c],vec.at8(idx)));
        } catch( IllegalFormatException ife ) {
          System.out.println("Format: "+fs[c]+" col="+c+" not for ints");
          ife.printStackTrace();
        }
      }
    } else {
      sb.append(String.format(fs[c],vec.at (idx)));
      if( vec.isNA(idx) ) sb.append(' ');
    }
    sb.append(' ');           // Column seperator
  }
  sb.append('\n');
  return sb;
}
 
Example #26
Source File: ThrowableConsoleEvent.java    From buck with Apache License 2.0 5 votes vote down vote up
public static ThrowableConsoleEvent create(Throwable throwable, String message, Object... args) {
  String format;
  try {
    format = String.format(message, args);
  } catch (IllegalFormatException e) {
    format = "Malformed message: '" + message + "' args: [" + Joiner.on(",").join(args) + "]";
  }
  return new ThrowableConsoleEvent(throwable, format);
}
 
Example #27
Source File: Scanner.java    From alfresco-bulk-import with Apache License 2.0 5 votes vote down vote up
/**
 * Writes a detailed informational status message to the log, at INFO level
 */
private final void logStatusInfo()
{
    if (info(log))
    {
        try
        {
            final int   batchesInProgress           = importThreadPool.getQueueSize() + importThreadPool.getActiveCount();
            final Float batchesPerSecond            = importStatus.getTargetCounterRate(BulkImportStatus.TARGET_COUNTER_BATCHES_COMPLETE, SECONDS);
            final Long  estimatedCompletionTimeInNs = importStatus.getEstimatedRemainingDurationInNs();
            String      message                     = null;
            
            if (batchesPerSecond != null && estimatedCompletionTimeInNs != null)
            {
                message = String.format("Multithreaded import in progress - %d batch%s yet to be imported. " +
                                        "At current rate (%.3f batch%s per second), estimated completion in %s.",
                                        batchesInProgress, pluralise(batchesInProgress, "es"),
                                        batchesPerSecond,  pluralise(batchesPerSecond, "es"), getHumanReadableDuration(estimatedCompletionTimeInNs, false));
            }
            else
            {
                message = String.format("Multithreaded import in progress - %d batch%s yet to be imported.",
                                        batchesInProgress, pluralise(batchesInProgress, "es"));
            }
            
            info(log, message);
        }
        catch (final IllegalFormatException ife)
        {
            // To help troubleshoot bugs in the String.format calls above
            error(log, ife);
        }
    }
}
 
Example #28
Source File: MessageFormatter.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
protected String formatMessage(final String msgPattern, final Object... args)
{
    try
    {
        final MessageFormat temp = new MessageFormat(msgPattern);
        return temp.format(args);
    }
    catch (final IllegalFormatException ife)
    {
        return msgPattern;
    }
}
 
Example #29
Source File: StringFormattedMessage.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
protected String formatMessage(final String msgPattern, final Object... args) {
    try {
        return String.format(locale, msgPattern, args);
    } catch (final IllegalFormatException ife) {
        LOGGER.error("Unable to format msg: " + msgPattern, ife);
        return msgPattern;
    }
}
 
Example #30
Source File: MessageFormatMessage.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
protected String formatMessage(final String msgPattern, final Object... args) {
    try {
        final MessageFormat temp = new MessageFormat(msgPattern, locale);
        return temp.format(args);
    } catch (final IllegalFormatException ife) {
        LOGGER.error("Unable to format msg: " + msgPattern, ife);
        return msgPattern;
    }
}