List of usage examples for org.apache.commons.lang.reflect MethodUtils invokeMethod
public static Object invokeMethod(Object object, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
Invoke a named method whose parameter type matches the object type.
This method delegates the method search to #getMatchingAccessibleMethod(Class,String,Class[]) .
This method supports calls to methods taking primitive parameters via passing in wrapping classes.
From source file:com.ocs.dynamo.utils.ClassUtils.java
/** * Checks if the specified property can be set for the specified object. This method supports * nested properties/*from ww w .ja v a2s. co m*/ * * @param obj * the object * @param fieldName * the name of the field * @return */ public static boolean canSetProperty(Object obj, String fieldName) { try { int p = fieldName.indexOf("."); if (p >= 0) { String firstProperty = fieldName.substring(0, p); Object first = MethodUtils.invokeMethod(obj, GET + StringUtils.capitalize(firstProperty), new Object[] {}); if (first != null) { return canSetProperty(first, fieldName.substring(p + 1)); } return false; } else { return hasMethod(obj, SET + StringUtils.capitalize(fieldName)); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new OCSRuntimeException(e.getMessage(), e); } }
From source file:com.ocs.dynamo.utils.ClassUtils.java
/** * Clears a field//from w w w. ja va2 s. com * * @param obj * the object on which to clear the field * @param fieldName * the name of the field * @param argType */ public static void clearFieldValue(Object obj, String fieldName, Class<?> argType) { try { int p = fieldName.indexOf("."); if (p >= 0) { String firstProperty = fieldName.substring(0, p); Object first = MethodUtils.invokeMethod(obj, GET + StringUtils.capitalize(firstProperty), new Object[] {}); if (first != null) { clearFieldValue(first, fieldName.substring(p + 1), argType); } } else { Method m = obj.getClass().getMethod(SET + StringUtils.capitalize(fieldName), new Class[] { argType }); m.invoke(obj, new Object[] { null }); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new OCSRuntimeException(e.getMessage(), e); } }
From source file:com.cloudera.training.metrics.JobHistoryHelper.java
public static long extractLongFieldValue(TaskMetrics m, String fieldName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (Long) MethodUtils.invokeMethod(m, fieldName, null); }
From source file:com.jroossien.boxx.util.item.ItemParser.java
/** * Parse the given string in to a item.//from w w w. j a v a2 s . c o m * * @param string String with item format. * @param ignoreErrors If this is true it will continue parsing even if there are non breaking errors. */ public ItemParser(String string, CommandSender sender, boolean ignoreErrors) { this.string = string; if (string == null || string.isEmpty()) { error = Msg.getString("itemparser.no-input"); return; } List<String> sections = Str.splitQuotes(string, ' ', false); //Go through all the sections. for (int i = 0; i < sections.size(); i++) { String section = sections.get(i); //Get ItemData from first section if (i == 0) { ItemData item = Items.getItem(section); if (item == null) { error = Msg.getString("itemparser.invalid-item", Param.P("input", section)); return; } this.item = new EItem(item.getType(), item.getData()); continue; } //Set amount if it's a number Integer amount = Parse.Int(section); if (amount != null) { item.setAmount(amount); continue; } String[] split = section.split(":", 2); String key = split[0].toUpperCase().replace("_", "").replace(" ", ""); String value = split.length > 1 ? split[1] : ""; //Allow key only //Try to parse ItemTag ItemTag tag = ItemTag.fromString(key); if (tag == null) { error = Msg.getString("parser.invalid-tag", Param.P("tag", key), Param.P("value", value), Param.P("type", Msg.getString("itemparser.type")), Param.P("tags", Utils .getAliasesString("parser.tag-entry", ItemTag.getTagsMap(item.getItemMeta())))); if (!ignoreErrors) { return; } continue; } //Make sure the item tag can be used for the meta of the item. if (!ItemTag.getTags(item.getItemMeta()).contains(tag)) { error = Msg.getString("parser.unusable-tag", Param.P("tag", key), Param.P("type", Msg.getString("itemparser.type")), Param.P("tags", Utils .getAliasesString("parser.tag-entry", ItemTag.getTagsMap(item.getItemMeta())))); System.out.println(Msg.fromString(error).get()); if (!ignoreErrors) { return; } continue; } //Parse the value for the tag SingleOption option = (SingleOption) tag.getOption().clone(); if (option instanceof BoolO && value.isEmpty()) { value = "true"; //Allow empty tags for booleans like 'glow' instead of 'glow:true' } if (!option.parse(sender, value)) { error = option.getError(); if (!ignoreErrors) { return; } continue; } //Apply the tag to the item if (tag.hasCallback()) { if (!tag.getCallback().onSet(sender, item, option)) { error = Msg.getString("parser.tag-fail", Param.P("tag", key), Param.P("value", value)); if (!ignoreErrors) { return; } continue; } } else { boolean success = false; try { MethodUtils.invokeMethod(item, tag.setMethod(), option.getValue()); success = true; } catch (NoSuchMethodException e) { error = Msg.getString("parser.missing-method", Param.P("tag", key), Param.P("value", value), Param.P("method", tag.setMethod() + "(" + option.getValue().getClass().getSimpleName() + ")")); } catch (IllegalAccessException e) { error = Msg.getString("parser.inaccessible-method", Param.P("tag", key), Param.P("value", value), Param.P("method", tag.setMethod() + "(" + option.getValue().getClass().getSimpleName() + ")")); } catch (InvocationTargetException e) { error = Msg.getString("parser.non-invokable-method", Param.P("tag", key), Param.P("value", value), Param.P("method", tag.setMethod() + "(" + option.getValue().getClass().getSimpleName() + ")")); } if (!success && !ignoreErrors) { return; } } } }
From source file:com.jroossien.boxx.util.item.ItemParser.java
public ItemParser(EItem item) { this.item = item; if (item == null) { return;/*from ww w.j ava 2 s .c o m*/ } //Air can't have any meta. if (item.getType() == Material.AIR) { this.string = Items.getName(Material.AIR, (byte) 0); return; } List<String> sections = new ArrayList<>(); sections.add(Items.getName(item.getData()).replaceAll(" ", "")); if (item.getAmount() > 1) { sections.add(Integer.toString(item.getAmount())); } for (ItemTag tag : ItemTag.getTags(item.getItemMeta())) { if (tag.hasCallback()) { String result = tag.getCallback().onGet(item); if (result == null || result.isEmpty()) { continue; } if (!result.toLowerCase().contains(tag.getTag().toLowerCase() + ":")) { result = Str.escapeWords(Str.escapeQuotes(result)); } else { result = Str.escapeQuotes(result); } sections.add(tag.getTag().toLowerCase() + ":" + result); } else { if (tag.getMethod() == null || tag.getMethod().isEmpty() || tag.getMethod().equalsIgnoreCase("null")) { continue; } try { Object result = MethodUtils.invokeMethod(item, tag.getMethod(), new Class[0]); if (result == null) { continue; } SingleOption option = (SingleOption) tag.getOption().clone(); if (!option.parse(result)) { Boxx.get().warn("Failed to parse entity data! [tag=" + tag.getTag() + " value=" + result.toString() + " error='" + option.getError() + "']"); continue; } if (option.getValue().equals(option.getDefault())) { continue; } sections.add(tag.getTag().toLowerCase() + ":" + Str.escapeWords(Str.escapeQuotes(option.serialize()))); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } this.string = Str.implode(sections, " "); }
From source file:de.tudarmstadt.ukp.dkpro.core.snowball.SnowballStemmer.java
/** * Creates a Stem annotation with same begin and end as the AnnotationFS fs, the value is the * stemmed value derived by applying the featurepath. * * @param fs//from w w w .jav a 2 s .c om * the AnnotationFS where the Stem annotation is created */ private void createStemAnnotation(JCas jcas, AnnotationFS fs) throws AnalysisEngineProcessException { // Check for blank text, it makes no sense to add a stem then (and raised an exception) String value = fp.getValue(fs); if (!StringUtils.isBlank(value)) { if (lowerCase) { // Fixme - should use locale/language defined in CAS. value = value.toLowerCase(Locale.US); } Stem stemAnnot = new Stem(jcas, fs.getBegin(), fs.getEnd()); SnowballProgram programm = getSnowballProgram(jcas); programm.setCurrent(value); try { // The patched snowball from Lucene has this as a method on SnowballProgram // but if we have some other snowball also in the classpath, Java might // choose to use the other. So to be safe, we use a reflection here. // -- REC, 2011-04-17 MethodUtils.invokeMethod(programm, "stem", null); } catch (Exception e) { throw new AnalysisEngineProcessException(e); } stemAnnot.setValue(programm.getCurrent()); stemAnnot.addToIndexes(jcas); // Try setting the "stem" feature on Tokens. Feature feat = fs.getType().getFeatureByBaseName("stem"); if (feat != null && feat.getRange() != null && jcas.getTypeSystem().subsumes(feat.getRange(), stemAnnot.getType())) { fs.setFeatureValue(feat, stemAnnot); } } }
From source file:com.ocs.dynamo.utils.ClassUtils.java
/** * Retrieves a field value/* ww w. ja va2s. c o m*/ * * @param obj * the object from which to retrieve the field value * @param fieldName * the name of the field * @return */ public static Object getFieldValue(Object obj, String fieldName) { try { int p = fieldName.indexOf("."); if (p >= 0) { String firstProperty = fieldName.substring(0, p); Object first = MethodUtils.invokeMethod(obj, GET + StringUtils.capitalize(firstProperty), new Object[] {}); return getFieldValue(first, fieldName.substring(p + 1)); } else { if (hasMethod(obj, GET + StringUtils.capitalize(fieldName))) { // first check for a getter return MethodUtils.invokeMethod(obj, GET + StringUtils.capitalize(fieldName), new Object[] {}); } else { // next, check for an "is" method in case of a boolean return MethodUtils.invokeMethod(obj, IS + StringUtils.capitalize(fieldName), new Object[] {}); } } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new OCSRuntimeException(e.getMessage(), e); } }
From source file:com.jroossien.boxx.util.entity.EntityParser.java
/** * Parses the given entity string in to an {@link EEntity}. * It uses {@link EntityTag}s for parsing the string. * <p/>// w ww . j av a2s . co m * If ignoreErrors is set to true it will still set the errors but it will try to continue parsing the rest. * It would still fail in some cases for example if there is an invalid entity specified or if there is no input. * * @param string entity string with all entity data from {@link EntityTag}s. * @param sender optional sender used for parsing (may be {@code null}) will be used for options parsing like @ and such. * @param ignoreErrors If true it will continue parsing even when there is an error. * @param maxAmount The maximum amount that can be set/spawned. (this does not count stacked entities) (set to null to use the default=100) * @param allowStacked If true entities will be stacked and if false entities can't be stacked. */ public EntityParser(String string, CommandSender sender, boolean ignoreErrors, Integer maxAmount, boolean allowStacked) { this.string = string; if (string == null || string.isEmpty()) { error = Msg.getString("entityparser.no-input"); return; } //Split the string by > for stacked entities. (> within quotes will be ignored) List<String> entitySections = Str.splitIgnoreQuoted(string, '>', true); if (entitySections.size() < 1) { error = Msg.getString("entityparser.no-input"); return; } if (!allowStacked && entitySections.size() > 1) { error = Msg.getString("entityparser.cant-stack"); return; } //Get location and amount Location location = null; int amount = 1; for (String entitySection : entitySections) { List<String> sections = Str.splitQuotes(string, ' ', false); for (String section : sections) { String[] split = section.split(":", 2); if (split.length < 2) { continue; } if (split[0].equalsIgnoreCase("LOC") || split[0].equalsIgnoreCase("LOCATION")) { LocationO locOpt = new LocationO(); if (locOpt.parse(sender, split[1])) { location = locOpt.getValue(); } else { error = locOpt.getError(); if (!ignoreErrors) { return; } } } else if (split[0].equalsIgnoreCase("AMT") || split[0].equalsIgnoreCase("AMOUNT")) { IntO amtOpt = new IntO().min(1).max(maxAmount == null ? MAX_AMOUNT : maxAmount); if (amtOpt.parse(split[1])) { amount = amtOpt.getValue(); } else { error = amtOpt.getError(); if (!ignoreErrors) { return; } } } } } if (location == null) { error = Msg.getString("entityparser.no-location"); return; } EntityStack stack = new EntityStack(); //Go through all the entity sections. for (String entitySection : entitySections) { //Split the string by spaces keeping quoted strings together to get all the sections for tags. List<String> sections = Str.splitQuotes(entitySection, ' ', false); EEntity entity = null; //Go through all the sections. for (int i = 0; i < sections.size(); i++) { String section = sections.get(i); //Get entity from first section if (i == 0) { EntityType type = EntityTypes.get(section); if (type == null) { error = Msg.getString("entityparser.invalid-entity", Param.P("input", section), Param.P( "entities", Utils.getAliasesString("entityparser.entities.entry", EntityTypes.getAliasMap()))); stack.killAll(); return; } entity = new EEntity(type, location); if (entity == null || entity.bukkit() == null) { error = Msg.getString("entityparser.cant-spawn"); stack.killAll(); return; } continue; } String[] split = section.split(":", 2); String key = split[0].toUpperCase().replace("_", "").replace(" ", ""); String value = split.length > 1 ? split[1] : ""; //Allow key only if (key.equals("AMT") || key.equals("AMOUNT") || key.equals("LOC") || key.equals("LOCATION")) { continue; } //Try to parse EntityTag EntityTag tag = EntityTag.fromString(key); if (tag == null) { error = Msg.getString("parser.invalid-tag", Param.P("tag", key), Param.P("type", Msg.getString("entityparser.type")), Param.P("tags", Utils .getAliasesString("parser.tag-entry", EntityTag.getTagsMap(entity.getType())))); if (!ignoreErrors) { entity.remove(); stack.killAll(); return; } else { continue; } } //Make sure the entity tag can be used for the entity. if (!EntityTag.getTags(entity.getType()).contains(tag)) { error = Msg.getString("parser.unusable-tag", Param.P("tag", key), Param.P("type", Msg.getString("entityparser.type")), Param.P("tags", Utils .getAliasesString("parser.tag-entry", EntityTag.getTagsMap(entity.getType())))); if (!ignoreErrors) { entity.remove(); stack.killAll(); return; } else { continue; } } //Parse the value for the tag SingleOption option = (SingleOption) tag.getOption().clone(); if (option instanceof BoolO && value.isEmpty()) { value = "true"; //Allow empty tags for booleans like 'baby' instead of 'baby:true' } if (!option.parse(sender, value)) { error = option.getError(); if (!ignoreErrors) { entity.remove(); stack.killAll(); return; } else { continue; } } //Apply the tag to the entity if (tag.hasCallback()) { if (!tag.getCallback().onSet(sender, entity, option)) { error = Msg.getString("parser.tag-fail", Param.P("tag", key), Param.P("value", value)); if (!ignoreErrors) { entity.remove(); stack.killAll(); return; } else { continue; } } } else { boolean success = false; try { MethodUtils.invokeMethod(entity, tag.setMethod(), option.getValue()); success = true; } catch (NoSuchMethodException e) { error = Msg.getString("parser.missing-method", Param.P("tag", key), Param.P("value", value), Param.P("method", tag.setMethod() + "(" + option.getValue().getClass().getSimpleName() + ")")); } catch (IllegalAccessException e) { error = Msg.getString("parser.inaccessible-method", Param.P("tag", key), Param.P("value", value), Param.P("method", tag.setMethod() + "(" + option.getValue().getClass().getSimpleName() + ")")); } catch (InvocationTargetException e) { error = Msg.getString("parser.non-invokable-method", Param.P("tag", key), Param.P("value", value), Param.P("method", tag.setMethod() + "(" + option.getValue().getClass().getSimpleName() + ")")); } if (!success) { if (!ignoreErrors) { entity.remove(); stack.killAll(); return; } else { continue; } } } //Done with section! } //Done with entity! stack.add(entity); } //Done with all entities! if (stack.getAmount() < 1) { error = "No entities.."; return; } stack.stack(); this.entities = stack; }
From source file:com.opoopress.maven.plugins.plugin.AbstractDeployMojo.java
private static void configureScpWagonIfRequired(Wagon wagon, Log log) { log.debug("configureScpWagonIfRequired: " + wagon.getClass().getName()); if (System.console() == null) { log.debug("No System.console(), skip configure Wagon"); return;//from w w w . ja v a2 s . c o m } ClassLoader parent = Thread.currentThread().getContextClassLoader(); if (parent == null) { parent = AbstractDeployMojo.class.getClassLoader(); } List<ClassLoader> loaders = new ArrayList<ClassLoader>(); loaders.add(wagon.getClass().getClassLoader()); ChainingClassLoader loader = new ChainingClassLoader(parent, loaders); Class<?> scpWagonClass; try { scpWagonClass = ClassUtils.getClass(loader, "org.apache.maven.wagon.providers.ssh.jsch.ScpWagon"); } catch (ClassNotFoundException e) { log.debug( "Class 'org.apache.maven.wagon.providers.ssh.jsch.ScpWagon' not found, skip configure Wagon."); return; } //is ScpWagon if (scpWagonClass.isInstance(wagon)) { try { Class<?> userInfoClass = ClassUtils.getClass(loader, "com.opoopress.maven.plugins.plugin.ssh.SystemConsoleInteractiveUserInfo"); Object userInfo = userInfoClass.newInstance(); MethodUtils.invokeMethod(wagon, "setInteractiveUserInfo", userInfo); log.debug("ScpWagon using SystemConsoleInteractiveUserInfo(Java 6+)."); } catch (ClassNotFoundException e) { log.debug( "Class 'com.opoopress.maven.plugins.plugin.ssh.SystemConsoleInteractiveUserInfo' not found, skip configure Wagon."); } catch (InstantiationException e) { log.debug("Instantiate class exception", e); } catch (IllegalAccessException e) { log.debug(e.getMessage(), e); } catch (NoSuchMethodException e) { log.debug(e.getMessage(), e); } catch (InvocationTargetException e) { log.debug(e.getMessage(), e); } } else { log.debug("Not a ScpWagon."); } }
From source file:com.jroossien.boxx.util.entity.EntityParser.java
public EntityParser(EEntity eentity) { if (eentity == null || eentity.bukkit() == null) { return;//from w w w .j a v a2s .com } this.entities = new EntityStack(eentity); if (entities.getAmount() < 1) { return; } List<String> entitySections = new ArrayList<>(); for (EEntity entity : entities.getEntities()) { List<String> sections = new ArrayList<>(); sections.add(EntityTypes.getName(entity.getType())); for (EntityTag tag : EntityTag.getTags(entity.getType())) { if (tag.hasCallback()) { String result = tag.getCallback().onGet(entity); if (result == null || result.isEmpty()) { continue; } if (!result.toLowerCase().contains(tag.getTag().toLowerCase() + ":")) { result = Str.escapeWords(Str.escapeQuotes(result)); } else { result = Str.escapeQuotes(result); } sections.add(tag.getTag().toLowerCase() + ":" + result); } else { if (tag.getMethod() == null || tag.getMethod().isEmpty() || tag.getMethod().equalsIgnoreCase("null")) { continue; } try { Object result = MethodUtils.invokeMethod(entity, tag.getMethod(), new Class[0]); if (result == null) { continue; } SingleOption option = (SingleOption) tag.getOption().clone(); if (!option.parse(result)) { Boxx.get().warn("Failed to parse entity data! [tag=" + tag.getTag() + " value=" + result.toString() + " error='" + option.getError() + "']"); continue; } if (option.getValue().equals(option.getDefault())) { continue; } String val = option.serialize(); if (option instanceof DoubleO) { val = ((DoubleO) option).serialize(2); } val = Str.escapeWords(Str.escapeQuotes(val)); sections.add(tag.getTag().toLowerCase() + ":" + val); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } entitySections.add(Str.implode(sections, " ")); } LocationO location = new LocationO(); location.parse(entities.getBottom().getLocation()); this.string = Str.implode(entitySections, " > ") + " loc:" + location.serialize(2); }