/** * Constructs a new pattern, with a given format string * and list of attribute field names. */ public LabelPattern(String format, List<String> argNames) throws FormatException { this.format = format; this.argNames.addAll(argNames); List<Object> testValues1 = new ArrayList<>(); List<Object> testValues2 = new ArrayList<>(); for (int i = 0; i < argNames.size(); i++) { this.argPositions.put(argNames.get(i), i); testValues1.add(null); testValues2.add(""); } try { getLabel(testValues1.toArray()); getLabel(testValues2.toArray()); } catch (IllegalFormatException exc) { throw new FormatException("Format string \"%s\" not valid for %d arguments", format, argNames.size()); } }
/** * Returns the instantiated output string for a given transition, if any. * @return the instantiated output string, or {@code null} if there is none * @throws FormatException if the format string of the rule * does not correspond to the actual rule parameters. */ public static String getOutputString(GraphTransition trans) throws FormatException { String result = null; String formatString = trans.getAction() .getFormatString(); if (formatString != null && !formatString.isEmpty()) { List<Object> args = new ArrayList<>(); for (HostNode arg : trans.label() .getArguments()) { if (arg instanceof ValueNode) { args.add(((ValueNode) arg).getValue()); } else { args.add(arg.toString()); } } try { result = String.format(formatString, args.toArray()); } catch (IllegalFormatException e) { throw new FormatException("Error in rule output string: %s", e.getMessage()); } } return result; }
public static String getString(String id, Object... args) { synchronized (lock) { if (mStrings.containsKey(id)) { try { return String.format(mStrings.get(id).toString(), args); } catch (IllegalFormatException e) { Log.e(TAG, "A string was found with wrong format parameters! The string is: " + id); return mStrings.get(id).toString(); } } else { Crashlytics.logException(new RuntimeException("String not found: " + id)); return ""; } } }
@Test public void testGet() throws Exception { assertThat(map.get(new BadRequestException()), is(equalTo(HttpStatus.BAD_REQUEST))); assertThat(map.get(BadRequestException.class), is(equalTo(HttpStatus.BAD_REQUEST))); assertThat(map.get(ConflictException.class), is(equalTo(HttpStatus.CONFLICT))); assertThat(map.get(NotFoundException.class), is(equalTo(HttpStatus.NOT_FOUND))); assertThat(map.get(NotModifiedException.class), is(equalTo(HttpStatus.NOT_MODIFIED))); assertThat(map.get(UnauthorizedException.class), is(equalTo(HttpStatus.UNAUTHORIZED))); assertThat(map.get(Exception.class), is(equalTo(HttpStatus.INTERNAL_SERVER_ERROR))); assertThat(map.get(IllegalArgumentException.class), is(equalTo(HttpStatus.INTERNAL_SERVER_ERROR))); map.put(IllegalArgumentException.class, HttpStatus.ACCEPTED); assertThat(map.get(IllegalFormatException.class), is(either(equalTo(HttpStatus.INTERNAL_SERVER_ERROR)).or(equalTo(HttpStatus.ACCEPTED)))); }
private void updateDisplay(int value) { if (!TextUtils.isEmpty(mFormat)) { mValue.setVisibility(View.VISIBLE); value = (value + mSteppedMinValue) * mStepValue; String text; try { if (mUseDisplayDividerValue) { float floatValue = (float) value / mDisplayDividerValue; text = String.format(mFormat, floatValue); } else { text = String.format(mFormat, value); } } catch (IllegalFormatException e) { text = Integer.toString(value); } mValue.setText(text); } else { mValue.setVisibility(View.GONE); } }
/** * 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 format A format string, see * {@link String#format(String, Object...)}. * @param args String formatter arguments. */ public static void log(Object source, int priority, String format, Object... args) { if (priority < LOG_LEVEL) { return; } final String sourceClass; if (source == null) { sourceClass = TAG; } else if (source instanceof Class<?>) { sourceClass = ((Class<?>) source).getSimpleName(); } else { sourceClass = source.getClass().getSimpleName(); } try { Log.println(priority, sourceClass, String.format(format, args)); } catch (IllegalFormatException e) { Log.e(TAG, "Bad formatting string: \"" + format + "\"", e); } }
public static final String resolve( String key, Object[] parameters ) { // assertion if (key == null) { return ""; } ResourceBundle bundle; String formatString; try { bundle = ResourceBundle.getBundle("TopologyBundle", Locale.getDefault(), ProjectBundleResolver.class.getClassLoader()); // resolving key String s = bundle.getString(key); formatString = String.format(s, parameters); return formatString; } catch (MissingResourceException ex) { return key; } catch (IllegalFormatException ife){ return key; } }
private final String resolve( String key, Locale locale ) { if (key == null) { return ""; } ResourceBundle bundle; try { bundle = ResourceBundle.getBundle("de.linogistix.los.inventory.res.Bundle", locale, InventoryBundleResolver.class.getClassLoader()); String s = bundle.getString(key); return s; } catch (MissingResourceException ex) { log.error("Exception: "+ex.getMessage()); return key; } catch (IllegalFormatException ife){ log.error("Exception: "+ife.getMessage()); return key; } }
private final String resolve( String key, Locale locale ) { if (key == null) { return ""; } ResourceBundle bundle; try { bundle = ResourceBundle.getBundle("de.linogistix.los.location.res.Bundle", locale, BundleResolver.class.getClassLoader()); String s = bundle.getString(key); return s; } catch (MissingResourceException ex) { log.error("Exception: "+ex.getMessage()); return key; } catch (IllegalFormatException ife){ log.error("Exception: "+ife.getMessage()); return key; } }
private final String resolve( String key, Locale locale ) { if (key == null) { return ""; } ResourceBundle bundle; try { bundle = ResourceBundle.getBundle("de.linogistix.los.res.Bundle", locale, BundleResolver.class.getClassLoader()); String s = bundle.getString(key); return s; } catch (MissingResourceException ex) { log.error("Exception: "+ex.getMessage()); return key; } catch (IllegalFormatException ife){ log.error("Exception: "+ife.getMessage()); return key; } }
@Override public IpAddress evaluate(FunctionArgs args, EvaluationContext context) { final String ipString = String.valueOf(ipParam.required(args, context)); try { final InetAddress inetAddress = InetAddresses.forString(ipString); return new IpAddress(inetAddress); } catch (IllegalArgumentException e) { final Optional<String> defaultValue = defaultParam.optional(args, context); if (!defaultValue.isPresent()) { return new IpAddress(ANYV4); } try { return new IpAddress(InetAddresses.forString(defaultValue.get())); } catch (IllegalFormatException e1) { log.warn("Parameter `default` for to_ip() is not a valid IP address: {}", defaultValue.get()); throw e1; } } }
private String getTableNameFormat(Config config, PersistenceConfig defaultValues) { String formatStr = config.tableNameFormat; if ( null == formatStr && null != defaultValues ) { formatStr = defaultValues.getTableNameFormat(); } if ( null == formatStr ) return null; try { String.format(formatStr, ""); } catch ( IllegalFormatException ex ) { throw new IllegalArgumentException( "Expected 'tableNameFormat' in "+_file+ " to be format string containing a single %s: "+ ex.getMessage()); } return formatStr; }
/** * 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... */ private static String formatValue(Locale locale, String tagValue, String tag, Object... arguments) { String formattedTagValue; if (tagValue != tag) // The identity equality is fine; that's what I want! { 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 static String modifySSHKeyName(String name) { String[] nameRaw = name.split("_"); String indexStr = nameRaw[nameRaw.length - 1]; Integer index = 2; if (StringUtils.isNumeric(indexStr)) { try { index = Integer.parseInt(indexStr) + 1; nameRaw = Arrays.copyOf(nameRaw, nameRaw.length - 1); } catch (IllegalFormatException e) { //nop } } return StringUtils.join(nameRaw) + "_" + index; }
/** * Condense a file size in bytes to it's highest form (i.e. KB, MB, GB, etc) * * @param bytes the size in bytes * @param precision the precision constant {@code ONE_DIGIT}, {@code TWO_DIGIT}, {@code THREE_DIGIT} * @return the condensed string */ public static String condenseFileSize(long bytes, String precision) throws IllegalFormatException { // Kilobyte Check float kilo = bytes / 1024f; float mega = kilo / 1024f; float giga = mega / 1024f; float tera = giga / 1024f; float peta = tera / 1024f; // Determine which value to send back if(peta > 1) return String.format(precision + " PB", peta); else if (tera > 1) return String.format(precision + " TB", tera); else if(giga > 1) return String.format(precision + " GB", giga); else if(mega > 1) return String.format(precision + " MB", mega); else if(kilo > 1) return String.format(precision + " KB", kilo); else return bytes + " b"; }
private void welcomeRider(final String rider, int triesLeft) { final String message = getWelcomeString(rider); try { sayRightNow(formatFirstName("welcome", message, rider)); } catch (IllegalFormatException | NullPointerException e) { if (Log.isLoggable(TAG, Log.ERROR)) { Log.e(TAG, "Bad welcome message: '" + message + "'"); } if (triesLeft > 0) { // pull an alternate message welcomeRider(rider, triesLeft - 1); } else { // willing to trust that resource messages won't throw an exception sayRightNow(formatFirstName("welcome alt", getRandomResWelcome(), rider)); } } }
private void returningRider(final String rider, boolean isLast, int triesLeft) { final String message = getReturnsString(rider, isLast); try { sayRightNow(formatFirstName("returning", message, rider)); } catch (IllegalFormatException | NullPointerException e) { if (Log.isLoggable(TAG, Log.ERROR)) { Log.e(TAG, "Bad return message: '" + message + "': " + e); } if (triesLeft > 0) { // pull an alternate message returningRider(rider, isLast, triesLeft - 1); } else { // willing to trust that resource messages won't throw an exception sayRightNow(formatFirstName("returning alt", getRandomResReturn(), rider)); } } }
/** * This allows you to get the exact current time of the stop watch, * in case you want to format it differently. * * @param format * @return the formatted time */ public String getCurrentTime(String format) { //Format(format); long seconds = currentTime /1000; String text = DateUtils.formatElapsedTime(mRecycle, seconds); if (format != null) { Locale loc = Locale.getDefault(); if (mFormatter == null || !loc.equals(mFormatterLocale)) { mFormatterLocale = loc; mFormatter = new Formatter(mFormatBuilder, loc); } mFormatBuilder.setLength(0); mFormatterArgs[0] = text; try { mFormatter.format(format, mFormatterArgs); text = mFormatBuilder.toString(); } catch (IllegalFormatException ex) { if (!mLogged) { Log.w(TAG, "Illegal format string: " + format); mLogged = true; } } } return text; }
public String readPassword() { String password = null; Console cons; char[] passwd; try { if ((cons = System.console()) != null && (passwd = cons.readPassword("[%s]", "Enter password")) != null) { /* for (int i = 0; i < passwd.length; i++) { if (password == null) { password = ""; } password = password + Character.toString(passwd[i]); }*/ password = String.valueOf(passwd); } } catch (IllegalFormatException ife) { error(new BroadSQLException(ife)); } return (password); }
private static String composeHeapStatus(final long... memoryStatus) { final StringBuilder strBldr = new StringBuilder(); strBldr.append("%d M of %d M"); //NOPMD String output = Constants.EMPTY; //NOPMD try (final Formatter formatter = new Formatter(Locale.UK);) { formatter.format(strBldr.toString(), memoryStatus[0], memoryStatus[1]); //NOPMD output = formatter.toString(); //NOPMD } catch (IllegalFormatException | FormatterClosedException e) { LoggerFactory.getLogger(HeapStatusSimpleProvider.class).error("Error while composing Heap status ", e); //NOPMD } return output; }
/** * Condense a file size in bytes into a more proper form * of kilobytes, megabytes, gigabytes * * @param bits the size in bytes * @param precision the precision constant {@code ONE_DIGIT}, {@code TWO_DIGIT}, {@code THREE_DIGIT} * @return the condensed string */ public static String condenseBitRate(long bits, String precision) throws IllegalFormatException{ // Kilobyte Check float kilo = bits / 1000f; float mega = kilo / 1000f; float giga = mega / 1000f; // Determine which value to send back if(giga > 1) return String.format(precision + " gbits/s", giga); else if(mega > 1) return String.format(precision + " mbits/s", mega); else if(kilo > 1) return String.format(precision + " kbits/s", kilo); else return bits + " bits/s"; }
@SuppressWarnings("boxing") public void test_format_Locale() { Locale l = new Locale("UK"); assertEquals("13% of sum is 0x11", String.format(l, "%d%% of %s is 0x%x", 13, "sum", 17)); assertEquals("empty format", "", String.format("", 123, this)); try { String.format(l, null, ""); fail("NPE is expected on null format"); } catch (NullPointerException ok){} try { String.format(l, "%d", "test"); fail("IllegalFormatException wasn't thrown."); } catch(IllegalFormatException ife) { //expected } }
private void verifyPrintf(MethodInvocationTree tree, FormatParameters parameters) throws FormatFlagsConversionMismatchException, IllegalFormatException, FormatterException { List<? extends ExpressionTree> args = tree.getArguments(); JCLiteral format = (JCLiteral) args.get(parameters.getFormatIndex()); String formatString = (String) format.getValue(); List<String> argTypes = new ArrayList<String>(); for (int i = parameters.getFormatIndex() + 1; i < args.size(); ++i) { Type type = ((JCExpression) args.get(i)).type; argTypes.add(getFormatterType(type)); } try { Formatter.check(formatString, argTypes.toArray(new String[0])); } catch (ExtraFormatArgumentsException e) { return; // We can handle this. } }
@Override public Void visitLiteral(LiteralTree tree, AnnotatedTypeMirror type) { if (!type.isAnnotatedInHierarchy(FORMAT)) { String format = null; if (tree.getKind() == Tree.Kind.STRING_LITERAL) { format = (String) tree.getValue(); } else if (tree.getKind() == Tree.Kind.CHAR_LITERAL) { format = Character.toString((Character) tree.getValue()); } if (format != null) { AnnotationMirror anno; try { ConversionCategory[] cs = FormatUtil.formatParameterCategories(format); anno = FormatterAnnotatedTypeFactory.this.treeUtil.categoriesToFormatAnnotation(cs); } catch (IllegalFormatException e) { anno = FormatterAnnotatedTypeFactory.this.treeUtil.exceptionToInvalidFormatAnnotation(e); } type.addAnnotation(anno); } } return super.visitLiteral(tree, type); }
/** * Returns if the format string is satisfiable, and if the * format's parameters match the passed @link{ConversionCategory}s. * Otherwise an @link{Error} is thrown. * * TODO introduce more such functions, see RegexUtil for examples */ @ReturnsFormat public static String asFormat(String format, ConversionCategory... cc) throws IllegalFormatException { ConversionCategory[] fcc = formatParameterCategories(format); if (fcc.length != cc.length) { throw new ExcessiveOrMissingFormatArgumentException(cc.length, fcc.length); } for (int i = 0; i < cc.length; i++) { if (cc[i] != fcc[i]) { throw new IllegalFormatConversionCategoryException(cc[i],fcc[i]); } } return format; }
/** * perform actual formatting using standard String.format() method. * * @param message * log message * @param args * var args * @return formatted messages */ protected String formatMessage(String message, Object... args) { if (args != null && args.length > 0) { Object[] newValues = new Object[args.length]; for (int i = 0; i < args.length; i++) { newValues[i] = (args[i] instanceof Throwable) ? ExceptionUtils .getFullStackTrace((Throwable) args[i]) : args[i]; } try { return String.format(message, newValues); } catch (IllegalFormatException ex) { logger.error( String.format( "log message [%s] is not constructed correctly for args = [%s]." + SEPARATOR + "visit java formatting http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html", message, Arrays.toString(args)), ex); } } return message; }
@Override public FieldValue evaluate(List<FieldValue> arguments){ checkArguments(arguments, 2); FieldValue value = arguments.get(0); FieldValue pattern = arguments.get(1); String result; // 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 { result = String.format(pattern.asString(), value.asNumber()); } catch(IllegalFormatException ife){ throw new FunctionException(this, "Invalid format value") .initCause(ife); } return FieldValueUtil.create(DataType.STRING, OpType.CATEGORICAL, result); }
@Override public FieldValue evaluate(List<FieldValue> arguments){ checkArguments(arguments, 2); FieldValue value = arguments.get(0); FieldValue pattern = arguments.get(1); String result; try { result = String.format(translatePattern(pattern.asString()), (value.asDateTime()).toDate()); } catch(IllegalFormatException ife){ throw new FunctionException(this, "Invalid format value") .initCause(ife); } return FieldValueUtil.create(DataType.STRING, OpType.CATEGORICAL, result); }
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).toString()); } 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); } }
/** * Sets name tag for players. * If a player has PVP enabled, their name is prefixed by the value * specified in the config * * @param event event being handled */ @EventHandler (priority = EventPriority.HIGH, ignoreCancelled = true) public void onNameTag(AsyncPlayerReceiveNameTagEvent event) { final Player playerSeen = event.getNamedPlayer(); final Object[] formatObjects = {playerSeen.getDisplayName()}; if (PVPConfigUtils.getPlayerStatus(playerSeen, playerSeen.getWorld(), plugin)) { try { event.setTag(String.format(ColorUtils.addColor(PrefixConfigUtils.getPlayerPrefix(playerSeen, playerSeen.getWorld(), plugin)) + "%s", formatObjects)); } catch (IllegalFormatException ex) { plugin.getLogger().log(Level.WARNING, "{0}Invalid prefix in config", ChatColor.RED); plugin.getLogger().log(Level.WARNING, "{0}Player tags not changed", ChatColor.RED); plugin.getLogger().log(Level.WARNING, "{0}Edit or update your config to resolve", ChatColor.RED); } } }
/** * Condense a file size in bytes into a more proper form * of kilobytes, megabytes, gigabytes * @param bytes the size in bytes * @param precision the precision constant {@code ONE_DIGIT}, {@code TWO_DIGIT}, {@code THREE_DIGIT} * @return the condensed string */ public static String condenseFileSize(long bytes, String precision) throws IllegalFormatException{ // Kilobyte Check float kilo = bytes / 1024f; float mega = kilo / 1024f; float giga = mega / 1024f; // Determine which value to send back if(giga > 1) return String.format(precision + " GB", giga); else if(mega > 1) return String.format(precision + " MB", mega); else if(kilo > 1) return String.format(precision + " KB", kilo); else return bytes + " b"; }
/** * Condense a file size in bytes into a more proper form * of kilobytes, megabytes, gigabytes * @param bytes the size in bytes * @return the condensed string */ public static String condenseFileSize(long bytes, String precision) throws IllegalFormatException{ // Kilobyte Check float kilo = bytes / 1024f; float mega = kilo / 1024f; float giga = mega / 1024f; // Determine which value to send back if(giga > 1) return String.format(precision + " GB", giga); else if(mega > 1) return String.format(precision + " MB", mega); else if(kilo > 1) return String.format(precision + " KB", kilo); else return bytes + " b"; }
private static void doLog(Level level, Throwable throwable, String message, Object... args){ if(canLog(level) && message != null){ if(args.length > 0){ try{ message = String.format(message, args); }catch(IllegalFormatException e){ message = "Error formatting log message [level="+level+"]: "+message; level = Level.ERROR; } } android.util.Log.println(level.getLevel(), TAG, message); if(throwable != null){ if(throwable.getMessage() != null){ android.util.Log.println(level.getLevel(), TAG, throwable.getMessage()); } android.util.Log.println(level.getLevel(), TAG, android.util.Log.getStackTraceString(throwable)); } } }
/** * Configures the meter with a human readable message that explains the task's purpose. * * @param format message format ({@link String#format(java.lang.String, java.lang.Object...)}) * @param args message arguments * @return reference to the meter itself. */ public Meter m(final String format, final Object... args) { if (format == null) { /* Logs message and exception with stacktrace forged to the inconsistent caller method. */ logger.error(Markers.ILLEGAL, ERROR_MSG_ILLEGAL_ARGUMENT, "m(message, args...)", ERROR_MSG_NULL_ARGUMENT, getFullID(), new IllegalMeterUsage(2)); this.description = null; return this; } try { this.description = String.format(format, args); } catch (final IllegalFormatException e) { /* Logs message and exception with stacktrace forged to the inconsistent caller method. */ logger.error(Markers.ILLEGAL, ERROR_MSG_ILLEGAL_ARGUMENT, "m(format, args...)", ERROR_MSG_ILLEGAL_STRING_FORMAT, getFullID(), new IllegalMeterUsage(2, e)); } return this; }
/** * Adds an entry to the context map. The entry value is made up of a formatted message with arguments. * * @param name key of the entry to add. * @param format message format ({@link String#format(java.lang.String, java.lang.Object...) * }) * @param args message arguments * @return reference to the meter itself. */ public Meter ctx(final String name, final String format, final Object... args) { if (name == null || format == null) { /* Logs message and exception with stacktrace forged to the inconsistent caller method. */ logger.error(Markers.ILLEGAL, ERROR_MSG_ILLEGAL_ARGUMENT, "ctx(name, format, args...)", ERROR_MSG_NULL_ARGUMENT, getFullID(), new IllegalMeterUsage(2)); return this; } if (context == null) { this.context = new LinkedHashMap<String, String>(); } try { ctx(name, String.format(format, args)); } catch (final IllegalFormatException e) { /* Logs message and exception with stacktrace forged to the inconsistent caller method. */ logger.error(Markers.ILLEGAL, ERROR_MSG_ILLEGAL_ARGUMENT, "ctx(name, format, args...)", ERROR_MSG_ILLEGAL_STRING_FORMAT, getFullID(), new IllegalMeterUsage(2, e)); } return this; }
/** * Send a formatted log message. * * @param level Logging level * @param tag Used to identify the source of a log message. It usually identifies the class * or activity where the log call occurs. * @param msg The message you would like logged. * @param args Arguments for msg's String formatting. * @param tr A Throwable for printing stack traces. */ private static int log(final int level, final String tag, final String msg, final Object[] args, final Throwable tr) { // try String.format first if (msg.contains("%")) { try { return log(level, tag, String.format(msg, args), tr); } catch (IllegalFormatException e) { // failed } } // just concatenate Objects.toString() StringBuilder sb = new StringBuilder(msg); for (Object a : args) { sb.append(a); } return log(level, tag, sb.toString(), tr); }