protected static <T extends Enum<T>> T parseEnum( Class<T> enumClass, String name, T defaultValue, Pair<String, T>... additionalPairs) { if (name == null) { return defaultValue; } name = name.toLowerCase(); for (T enumConstant : enumClass.getEnumConstants()) { if (enumConstant.name().equalsIgnoreCase(name)) { return enumConstant; } } for (T enumConstant : enumClass.getEnumConstants()) { if (enumConstant.name().toLowerCase().startsWith(name)) { return enumConstant; } } for (Pair<String, T> additional : additionalPairs) { if (additional.first().equalsIgnoreCase(name)) { return additional.other(); } } for (Pair<String, T> additional : additionalPairs) { if (additional.first().toLowerCase().startsWith(name)) { return additional.other(); } } throw new IllegalArgumentException("No '" + name + "' or '" + name + ".*' in " + enumClass); }
public static <T extends Enum> T toEnum(Class<T> cls, String value, Enum defaultEnum) { T[] enumConstants = cls.getEnumConstants(); for (T e : enumConstants) { if (e.name().equals(value)) { return e; } } value = value.toUpperCase().replace('-', '_'); for (T e : enumConstants) { if (e.name().equals(value)) { return e; } } value = Str.underBarCase(value); for (T e : enumConstants) { if (e.name().equals(value)) { return e; } } return (T) defaultEnum; }
public void setValue(T value) { if (value != null && value.name().equals("UNRECOGNIZED_VALUE")) { throw new IllegalArgumentException( "UNRECOGNIZED_VALUE reserved for soft enum deserialisation handling"); } this.value = value; this.rawValue = value != null ? value.name() : null; }
private <T extends Enum<T>> String getMessage(Map<T, String> map, T type) { String message = map.get(type); if (message == null) { log.warnFormat( "The message key {0} is missing from {1}", type.name(), EXECUTION_MESSAGES_FILE_PATH); message = type.name(); } return message; }
public static <T extends Enum<?>> EnumLookup<T> of( Class<T> className, Transform<String, String> t, Map<String, T> extras) { String name_ = className.getName(); int lastDot = name_.lastIndexOf('.'); EnumLookup<T> result = new EnumLookup<T>(name_.substring(lastDot + 1)); try { result.transform = t = t == null ? CLEAN : t; Method m = className.getMethod("values", (Class<?>[]) null); @SuppressWarnings("unchecked") T[] values = (T[]) m.invoke(null); for (T value : values) { result.map.put(t.transform(value.name()), value); result.map.put(t.transform(value.toString()), value); } } catch (Exception e) { throw new IllegalArgumentException(e); } if (extras == null) { return result; } for (Entry<String, T> entry : extras.entrySet()) { final String key = t.transform(entry.getKey()); final T newValue = entry.getValue(); final T old = result.map.get(key); if (old == null) { result.map.put(key, newValue); } else if (old != newValue) { throw new IllegalArgumentException( "Incompatible mapping: " + key + "=" + old + "!=" + newValue); } } return result; }
public <T extends Enum<T>> T getEnum(Class<T> enumClass, String key, T defaultValue) { String raw = this.map.get(key); if (raw == null) return defaultValue; for (T candidate : enumClass.getEnumConstants()) if (candidate.name().equals(raw)) return candidate; throw new IllegalArgumentException("No enum instance '" + raw + "' in " + enumClass.getName()); }
@Nonnull public static <T extends Enum<T> & Code.DescriptiveWrapper> String toString(@Nonnull T value) { return value.name() + "(0x" + UnsignedBytes.toString(value.getCode(), 16) + "): " + value.getDescription(); }
/** * Returns the member for the passed enum collector class that has a name match with the passed * name * * @param clazz The enum collector class * @param name The name of the member to get * @return the matching member or null if no match was made */ public T getMember(Class<T> clazz, CharSequence name) { if (name == null || name.toString().trim().isEmpty()) return null; String _name = name.toString().trim(); for (T t : clazz.getEnumConstants()) { if (_name.equalsIgnoreCase(t.name())) return t; } return null; }
/** * Determines if the passed name is a valid enum collector name for the passed enum collector * class. The name will be trimmed and matched ignoring case. * * @param clazz The enum collector class * @param name The name to test * @return true for match, false otherwise */ public boolean isMemberName(Class<T> clazz, CharSequence name) { if (name == null || name.toString().trim().isEmpty()) return false; String _name = name.toString().trim(); for (T t : clazz.getEnumConstants()) { if (_name.equalsIgnoreCase(t.name())) return true; } return false; }
protected static <T extends Enum<T>> String niceEnumAlternatives(Class<T> enumClass) { StringBuilder builder = new StringBuilder("["); int count = 0; for (T enumConstant : enumClass.getEnumConstants()) { builder.append((count++ == 0 ? "" : ", ")); builder.append(enumConstant.name()); } return builder.append("]").toString(); }
private static <T extends Enum<? extends IntValueHolder> & IntValueHolder> T valueOf( String name, T[] values) { for (T val : values) { if (val.name().equals(name)) { return val; } } return null; }
/** * 引数からEnumを取得する * * @param <T> * @param key * @param def * @return */ @SuppressWarnings("all") public <T extends Enum<?>> T getEnum(String key, T def) { String param = getArgment(key, def.name()); if (param.indexOf('.') > 0) { param = param.substring(param.lastIndexOf('.') + 1); } return (T) Enum.valueOf(def.getClass(), param); }
private <T extends Enum<T>> String getPropertyValue(T algo) { StringBuilder strb = new StringBuilder(); for (T it : active.algos(algo)) { strb.append(it.name()); strb.append(';'); } return strb.toString(); }
public <T extends Enum<T>> T readEnum(String name, Class<T> enumType, T defVal) throws IOException { String eVal = readString(name, defVal != null ? defVal.name() : null); if (eVal != null) { return Enum.valueOf(enumType, eVal); } else { return null; } }
/** * Returns enumeration item of the given class. * * @param <T> type of enumeration item * @param clazz enumeration class * @param name name of enumeration item (case insensitive) a * @return an instance of the given * enumeration class or <code>null</code> if an appropriate item cannot be found */ public static <T extends Enum<T>> T valueOf(final Class<T> clazz, final String name) { final T[] values = clazz.getEnumConstants(); if (LengthUtils.isNotEmpty(values)) { for (final T item : values) { if (item.name().equalsIgnoreCase(name)) { return item; } } } return null; }
@Override public Builder<?> read(T template) { this.name = template.name(); this.host = template.host(); this.port = template.port(); this.idleTimeout = template.idleTimeout(); this.recvBufSize = template.recvBufSize(); this.sendBufSize = template.sendBufSize(); this.tcpNoDelay = template.tcpNoDelay(); this.workerThreads = template.workerThreads(); this.ssl.read(template.ssl()); return this; }
/** * Parse an enumeration from the configuration. * * @param <T> type of the enumeration object. * @param all all possible values in the enumeration which should be recognized. Typically {@code * EnumType.values()}. * @param section section the key is grouped within. * @param subsection subsection name, such a remote or branch name. * @param name name of the key to get. * @param defaultValue default value to return if no value was present. * @return the selected enumeration value, or {@code defaultValue}. */ public <T extends Enum<?>> T getEnum( final T[] all, final String section, final String subsection, final String name, final T defaultValue) { String value = getString(section, subsection, name); if (value == null) return defaultValue; String n = value.replace(' ', '_'); T trueState = null; T falseState = null; for (T e : all) { if (StringUtils.equalsIgnoreCase(e.name(), n)) return e; else if (StringUtils.equalsIgnoreCase(e.name(), "TRUE")) trueState = e; else if (StringUtils.equalsIgnoreCase(e.name(), "FALSE")) falseState = e; } // This is an odd little fallback. C Git sometimes allows boolean // values in a tri-state with other things. If we have both a true // and a false value in our enumeration, assume its one of those. // if (trueState != null && falseState != null) { try { return StringUtils.toBoolean(n) ? trueState : falseState; } catch (IllegalArgumentException err) { // Fall through and use our custom error below. } } if (subsection != null) throw new IllegalArgumentException( MessageFormat.format(JGitText.get().enumValueNotSupported3, section, name, value)); else throw new IllegalArgumentException( MessageFormat.format(JGitText.get().enumValueNotSupported2, section, name, value)); }
public static <T extends Enum<? extends WritableIntValueHolder> & WritableIntValueHolder> void populateValues(Properties properties, T[] values, boolean sendops) { ExternalCodeTableGetter exc = new ExternalCodeTableGetter(properties); for (T code : values) { int val = exc.getValue(code.name(), values, -2); if (val != -2) { code.setValue(val); } else if (sendops) { System.out.println( "Check your Send Packet Opcodes - Something is wrong \r\n " + code.toString() + " is missing."); } } }
private <T extends Enum> T getValueAsEnum(Class<T> enumClass, MotechEvent event, String key) { String string = getValueAsString(event, key); T result = null; if (isNotBlank(string)) { for (T status : enumClass.getEnumConstants()) { if (status.name().equalsIgnoreCase(string)) { result = status; break; } } } return result; }
public EnumTypeAdapter(Class<T> classOfT) { try { for (T constant : classOfT.getEnumConstants()) { String name = constant.name(); SerializedName annotation = classOfT.getField(name).getAnnotation(SerializedName.class); if (annotation != null) { name = annotation.value(); } nameToConstant.put(name, constant); constantToName.put(constant, name); } } catch (NoSuchFieldException e) { throw new AssertionError(); } }
private String toHtml() { StringBuilder sb = new StringBuilder() .append("<font color='") .append(logLevel.toHtmlColor()) .append("'>") .append("[") .append(logTag.name()) .append("] ") .append(logLevel.name()) .append(": ") .append(logText) .append("</font>"); return sb.toString(); }
/** * Creates a <code>ChooserValues</code> with the specified enum values. * * @param enums enums for the <code>ChooserValues</code>. */ @SuppressWarnings("unchecked") public BaseEnumChooserValues(T... enums) { Utils.checkNotNull(enums, "enums"); Utils.checkArgument(enums.length > 0, "array enum cannot have zero elements"); resourceBundle = enums[0].getClass().getName() + "-bundle"; boolean isEnumWithLabels = enums[0] instanceof Label; values = new ArrayList<>(enums.length); labels = new ArrayList<>(enums.length); for (T e : enums) { String value = e.name(); values.add(value); String label = isEnumWithLabels ? ((Label) e).getLabel() : value; labels.add(label); } values = Collections.unmodifiableList(values); labels = Collections.unmodifiableList(labels); }
public static <T extends Enum> List<T> convertJSObjectToListOfEnum( JSObject jsObject, Class<T> enumClass) { List<T> result = new ArrayList<>(); if (jsObject != null) { try { String jsTypesString = jsObject.toString(); for (T value : enumClass.getEnumConstants()) { if (jsTypesString.toLowerCase().contains(value.name().toLowerCase())) { result.add(value); } } } catch (Exception e) { Logger.getLogger(GeocoderUtils.class.getName()).log(Level.SEVERE, "", e); } } return result; }
@Override public void show(PrintStream out) { byte tab[]; for (T champs : fieldsList) { tab = get(champs); out.print(champs.name() + "="); if (tab != null) { boolean start = true; for (byte b : tab) { if (!start) { out.print(','); } out.print(b); start = false; } } out.println(); } }
public static <T extends Enum> String getName(T enumValue) { if (enumValue == null) return null; return enumValue.name(); }
/** * Add or modify a configuration value. The parameters will result in a configuration entry like * this. * * <pre> * [section "subsection"] * name = value * </pre> * * @param <T> type of the enumeration object. * @param section section name, e.g "branch" * @param subsection optional subsection value, e.g. a branch name * @param name parameter name, e.g. "filemode" * @param value parameter value */ public <T extends Enum<?>> void setEnum( final String section, final String subsection, final String name, final T value) { String n = value.name().toLowerCase().replace('_', ' '); setString(section, subsection, name, n); }
public static <T extends Enum> String convertToString(T target) throws ConversionException { return (target != null ? target.name() : null); }
@Override public Object bind(final MappingHttpRequest httpRequest) throws BindingException { final String operationName = this.extractOperationName(httpRequest); final String operationNameType = operationName + "Type"; for (final T op : this.possibleParams) httpRequest.getParameters().remove(op.name()); final Map<String, String> params = httpRequest.getParameters(); BaseMessage eucaMsg = null; Map<String, String> fieldMap = null; Class<?> targetType = null; Binding currentBinding = null; try { if (this.getBinding().hasElementClass(operationName)) { currentBinding = this.getBinding(); targetType = currentBinding.getElementClass(operationName); } else if (this.getBinding().hasElementClass(operationNameType)) { currentBinding = this.getBinding(); targetType = currentBinding.getElementClass(operationNameType); } else if (this.getDefaultBinding().hasElementClass(operationName)) { currentBinding = this.getDefaultBinding(); targetType = currentBinding.getElementClass(operationName); } else if (this.getDefaultBinding().hasElementClass(operationNameType)) { currentBinding = this.getDefaultBinding(); targetType = currentBinding.getElementClass(operationNameType); } else if (BindingManager.getDefaultBinding().hasElementClass(operationName)) { currentBinding = BindingManager.getDefaultBinding(); targetType = currentBinding.getElementClass(operationName); } else if (BindingManager.getDefaultBinding().hasElementClass(operationNameType)) { currentBinding = BindingManager.getDefaultBinding(); targetType = currentBinding.getElementClass(operationNameType); } else { // this will necessarily fault. try { targetType = this.getBinding().getElementClass(operationName); } catch (final BindingException ex) { LOG.error(ex, ex); throw ex; } } fieldMap = this.buildFieldMap(targetType); eucaMsg = (BaseMessage) targetType.newInstance(); } catch (final BindingException e) { LOG.debug("Failed to construct message of type: " + operationName, e); LOG.error(e, e); throw e; } catch (final Exception e) { throw new BindingException("Failed to construct message of type " + operationName, e); } final List<String> failedMappings = this.populateObject((GroovyObject) eucaMsg, fieldMap, params); if (!failedMappings.isEmpty() || !params.isEmpty()) { final StringBuilder errMsg = new StringBuilder("Failed to bind the following fields:\n"); for (final String f : failedMappings) errMsg.append(f).append('\n'); for (final Map.Entry<String, String> f : params.entrySet()) errMsg.append(f.getKey()).append(" = ").append(f.getValue()).append('\n'); throw new BindingException(errMsg.toString()); } try { currentBinding.toOM(eucaMsg, this.getNamespace()); } catch (final RuntimeException e) { LOG.error( "Falling back to default (unvalidated) binding for: " + operationName + " with params=" + params); LOG.error("Failed to build a valid message: " + e.getMessage(), e); try { BindingManager.getDefaultBinding().toOM(eucaMsg, BindingManager.defaultBindingNamespace()); } catch (final RuntimeException ex) { throw new BindingException( "Default binding failed to build a valid message: " + ex.getMessage(), ex); } } return eucaMsg; }
@Override public String format(TypeSerializer serializer, T value, Object style) { return value != null ? value.name() : serializer.formatNull(); }
@Override protected String doBackward(T enumValue) { return enumValue.name(); }