List of usage examples for java.lang Class getMethods
@CallerSensitive public Method[] getMethods() throws SecurityException
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
/** * @param classes Generates all testcases for all the rest-full services found in the classes discovered *///w ww . j a va 2 s . c o m @SuppressWarnings({ "rawtypes", "unchecked" }) private void generateRestTestCases(List<Class> classes) { try { Map<String, Integer> classTypes = new HashMap<String, Integer>(); for (Class claz : classes) { classTypes.put(claz.getSimpleName(), 0); Annotation theClassPath = claz.getAnnotation(Path.class); if (theClassPath == null) theClassPath = claz.getAnnotation(RequestMapping.class); if (theClassPath != null) { List<TestCase> tcases = new ArrayList<TestCase>(); Method[] methods = claz.getMethods(); for (Method method : methods) { Annotation theMethodPath = method.getAnnotation(Path.class); if (theMethodPath == null) theMethodPath = method.getAnnotation(RequestMapping.class); if (theMethodPath != null) { TestCase tcase = new TestCase(); String completeServicePath = null; String httpMethod = ""; String consumes = "text/plain"; if (theClassPath instanceof Path && theMethodPath instanceof Path) { Path cpath = (Path) theClassPath; Path mpath = (Path) theMethodPath; completeServicePath = cpath.value() + mpath.value(); } else if (theClassPath instanceof RequestMapping && theMethodPath instanceof RequestMapping) { RequestMapping cpath = (RequestMapping) theClassPath; RequestMapping mpath = (RequestMapping) theMethodPath; completeServicePath = cpath.value()[0] + mpath.value()[0]; httpMethod = mpath.method()[0].name(); consumes = mpath.consumes()[0]; } else { throw new Exception( "Invalid Annotation found on the Service class - " + claz.getSimpleName()); } if (completeServicePath != null && completeServicePath.charAt(0) == '/') { completeServicePath = completeServicePath.substring(1); } String url = getUrl(completeServicePath); String completeServiceSubmitPath = url; Type[] argTypes = method.getGenericParameterTypes(); Annotation[][] argAnot = method.getParameterAnnotations(); boolean mayBemultipartContent = false; if (isDebugEnabled()) getLog().info( "Started looking at " + claz.getSimpleName() + " " + method.getName()); ViewField contentvf = null; Map<String, String> params = new HashMap<String, String>(); Map<String, String> hparams = new HashMap<String, String>(); for (int i = 0; i < argTypes.length; i++) { Annotation[] annotations = getRestArgAnnotation(argAnot[i]); if (annotations[0] != null) { String formpnm = null; if (annotations[0] instanceof FormParam) { formpnm = ((FormParam) annotations[0]).value(); if (annotations[1] != null) params.put(formpnm, ((DefaultValue) annotations[1]).value()); else params.put(formpnm, String.valueOf(getPrimitiveValue(argTypes[i]))); continue; } if (annotations[0] instanceof RequestParam) { if (completeServiceSubmitPath.indexOf("?") == -1) completeServiceSubmitPath += "?"; if (completeServiceSubmitPath .charAt(completeServiceSubmitPath.length() - 1) != '&') completeServiceSubmitPath += "&"; if (((RequestParam) annotations[0]).defaultValue() != null) completeServiceSubmitPath += ((RequestParam) annotations[0]).value() + "={" + ((RequestParam) annotations[0]).defaultValue() + "}&"; else completeServiceSubmitPath += ((RequestParam) annotations[0]).value() + "={" + ((RequestParam) annotations[0]).value() + "}&"; continue; } if (annotations[0] instanceof QueryParam) { if (completeServiceSubmitPath.indexOf("?") == -1) completeServiceSubmitPath += "?"; if (completeServiceSubmitPath .charAt(completeServiceSubmitPath.length() - 1) != '&') completeServiceSubmitPath += "&"; if (annotations[1] != null) completeServiceSubmitPath += ((QueryParam) annotations[0]).value() + "={" + ((DefaultValue) annotations[1]).value() + "}&"; else completeServiceSubmitPath += ((QueryParam) annotations[0]).value() + "={" + ((QueryParam) annotations[0]).value() + "}&"; continue; } if (annotations[0] instanceof HeaderParam) { formpnm = ((HeaderParam) annotations[0]).value(); if (annotations[1] != null) hparams.put(formpnm, ((DefaultValue) annotations[1]).value()); else hparams.put(formpnm, String.valueOf(getPrimitiveValue(argTypes[i]))); continue; } } else { ViewField vf = getViewField(argTypes[i]); if (vf != null) { contentvf = vf; if (isDebugEnabled()) getLog().info("Done looking at " + claz.getSimpleName() + " " + method.getName()); break; } else { mayBemultipartContent = true; } } } classTypes.put(claz.getSimpleName(), classTypes.get(claz.getSimpleName()) + 1); Annotation hm = method.getAnnotation(POST.class); if (hm != null) { httpMethod = "POST"; } else { hm = method.getAnnotation(GET.class); if (hm != null) { httpMethod = "GET"; } else { hm = method.getAnnotation(PUT.class); if (hm != null) { httpMethod = "PUT"; } else { hm = method.getAnnotation(DELETE.class); if (hm != null) { httpMethod = "DELETE"; } } } } Annotation annot = method.getAnnotation(Consumes.class); if (annot != null) { consumes = ((Consumes) annot).value()[0]; } String produces = null; if ("JSON".equalsIgnoreCase(getOutDataType())) { produces = MediaType.APPLICATION_JSON; } else if ("XML".equalsIgnoreCase(getOutDataType())) { produces = MediaType.APPLICATION_XML; } else { produces = MediaType.TEXT_PLAIN; } annot = method.getAnnotation(Produces.class); if (annot != null) { produces = ((Produces) annot).value()[0]; } String content = ""; try { if (!params.isEmpty() || consumes.equals(MediaType.APPLICATION_FORM_URLENCODED)) { for (Map.Entry<String, String> entry : params.entrySet()) { content += entry.getKey() + "=" + entry.getValue() + "&"; } consumes = MediaType.APPLICATION_FORM_URLENCODED; } else if (contentvf != null && contentvf.getValue() != null && contentvf.getValue() instanceof String) { content = (String) contentvf.getValue(); } else if (("JSON".equalsIgnoreCase(getInDataType()) || consumes.equals(MediaType.APPLICATION_JSON)) && contentvf != null && contentvf.getValue() != null) { content = new ObjectMapper().writerWithDefaultPrettyPrinter() .writeValueAsString(contentvf.getValue()); consumes = MediaType.APPLICATION_JSON; } else if (("XML".equalsIgnoreCase(getInDataType()) || consumes.equals(MediaType.APPLICATION_XML)) && contentvf != null && contentvf.getValue() != null) { JAXBContext context = JAXBContext.newInstance(contentvf.getValue().getClass()); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); StringWriter writer = new StringWriter(); m.marshal(contentvf.getValue(), writer); content = writer.toString(); consumes = MediaType.APPLICATION_XML; } else if ((httpMethod.equals("POST") || httpMethod.equals("PUT")) && mayBemultipartContent) { consumes = MediaType.MULTIPART_FORM_DATA; } else if (httpMethod.equals("GET") || httpMethod.equals("DELETE")) { consumes = ""; } } catch (Exception e) { getLog().error(e); } if (consumes != null && !consumes.trim().isEmpty()) { hparams.put(HttpHeaders.CONTENT_TYPE, consumes); } completeServiceSubmitPath = completeServiceSubmitPath.replaceAll("\\?&", "?"); completeServiceSubmitPath = completeServiceSubmitPath.replaceAll("&&", "&"); completeServiceSubmitPath = completeServiceSubmitPath.replaceAll("/\\?", "?"); completeServiceSubmitPath = completeServiceSubmitPath.trim(); if (completeServiceSubmitPath.charAt(completeServiceSubmitPath.length() - 1) == '&') { completeServiceSubmitPath = completeServiceSubmitPath.substring(0, completeServiceSubmitPath.length() - 1); } tcase.setUrl(completeServiceSubmitPath); tcase.setMethod(httpMethod); tcase.setContent(content); tcase.setName(claz.getName() + "." + method.getName()); tcase.setDescription(tcase.getName()); tcase.setDetailedLog(false); tcase.setSkipTest(false); tcase.setSecure(isOverrideSecure()); tcase.setSoapBase(false); tcase.setExpectedResCode(200); tcase.setExpectedResContentType(produces); if (hparams.size() > 0) tcase.setHeaders(hparams); if (tcase.getNumberOfExecutions() == null) tcase.setNumberOfExecutions(1); if (tcase.getExpectedNodes().size() == 0) tcase.setExpectedNodes(null); if (tcase.getWorkflowContextParameterMap().size() == 0) tcase.setWorkflowContextParameterMap(null); if (tcase.getSoapParameterValues().size() == 0) tcase.setSoapParameterValues(null); if (tcase.getRepeatScenarios().size() == 0) tcase.setRepeatScenarios(null); if (tcase.getMultipartContent().size() == 0) tcase.setMultipartContent(null); tcases.add(tcase); } } if (!tcases.isEmpty()) { if ("json".equalsIgnoreCase(getTestCaseFormat())) { String postManJson = new ObjectMapper().writeValueAsString(tcases); String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_rest.json"; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(postManJson); bw.close(); } else if ("csv".equalsIgnoreCase(getTestCaseFormat())) { StringBuilder build = new StringBuilder(); for (TestCase testCase : tcases) { build.append(testCase.toCSV()); build.append(SystemUtils.LINE_SEPARATOR); } String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_rest.csv"; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(build.toString()); bw.close(); } else { XStream xstream = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new GatfPrettyPrintWriter(out, TestCase.CDATA_NODES); } }); xstream.processAnnotations(new Class[] { TestCase.class }); xstream.alias("TestCases", List.class); String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_rest.xml"; xstream.toXML(tcases, new FileOutputStream(file)); } if (getPostmanCollectionVersion() > 0) { PostmanCollection postmanCollection = new PostmanCollection(); postmanCollection.setName(claz.getSimpleName()); postmanCollection.setDescription(postmanCollection.getName()); for (TestCase testCase : tcases) { postmanCollection.addTestCase(testCase, getPostmanCollectionVersion()); } String postManJson = new ObjectMapper().writeValueAsString(postmanCollection); String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_postman.json"; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(postManJson); bw.close(); } } } } } catch (Exception e) { getLog().error(e); } }
From source file:com.ng.mats.psa.mt.paga.data.JSONObject.java
private void populateMap(Object bean) { Class<?> klass = bean.getClass(); // If klass is a System class then set includeSuperClass to false. boolean includeSuperClass = klass.getClassLoader() != null; Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); for (int i = 0; i < methods.length; i += 1) { try {/*from w w w .j a va 2 s . c o m*/ Method method = methods[i]; if (Modifier.isPublic(method.getModifiers())) { String name = method.getName(); String key = ""; if (name.startsWith("get")) { if ("getClass".equals(name) || "getDeclaringClass".equals(name)) { key = ""; } else { key = name.substring(3); } } else if (name.startsWith("is")) { key = name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } Object result = method.invoke(bean, (Object[]) null); if (result != null) { this.map.put(key, wrap(result)); } } } } catch (Exception ignore) { } } }
From source file:org.openmrs.module.sync.SyncUtil.java
/** * Constructs a Method object for invocation on instances of objType class based on methodName * and the method parameter type. Handles only propery accessors - thus takes Class propValType * and not Class[] propValTypes./* w w w . j a v a 2 s. c o m*/ * <p> * If necessary, this implementation traverses both objType and propValTypes type hierarchies in * search for the method signature match. * * @param objType Type to examine. * @param methodName Method name. * @param propValType Type of the parameter that method takes. If none (i.e. getter), pass null. * @return Method object matching name and param, else null */ private static Method getPropertyAccessor(Class objType, String methodName, Class propValType) { // need to try to get setter, both in this object, and its parent class Method m = null; boolean continueLoop = true; // Fix - CA - 22 Jan 2008 - extremely odd Java Bean convention that says getter/setter for fields // where 2nd letter is capitalized (like "aIsToB") first letter stays lower in getter/setter methods // like "getaIsToB()". Hence we need to try that out too String altMethodName = methodName.substring(0, 3) + methodName.substring(3, 4).toLowerCase() + methodName.substring(4); try { Class[] setterParamClasses = null; if (propValType != null) { //it is a setter setterParamClasses = new Class[1]; setterParamClasses[0] = propValType; } Class clazz = objType; // it could be that the setter method itself is in a superclass of objectClass/clazz, so loop through those while (continueLoop && m == null && clazz != null && !clazz.equals(Object.class)) { try { m = clazz.getMethod(methodName, setterParamClasses); continueLoop = false; break; //yahoo - we got it using exact type match } catch (SecurityException e) { m = null; } catch (NoSuchMethodException e) { m = null; } //not so lucky: try to find method by name, and then compare params for compatibility //instead of looking for the exact method sig match Method[] mes = objType.getMethods(); for (Method me : mes) { if (me.getName().equals(methodName) || me.getName().equals(altMethodName)) { Class[] meParamTypes = me.getParameterTypes(); if (propValType != null && meParamTypes != null && meParamTypes.length == 1 && isAssignableFrom(meParamTypes[0], propValType)) { m = me; continueLoop = false; //aha! found it break; } } } if (continueLoop) clazz = clazz.getSuperclass(); } } catch (Exception ex) { //whatever happened, we didn't find the method - return null m = null; log.warn("Unexpected exception while looking for a Method object, returning null", ex); } if (m == null) { if (log.isWarnEnabled()) log.warn("Failed to find matching method. type: " + objType.getName() + ", methodName: " + methodName); } return m; }
From source file:com.weibo.api.motan.config.springsupport.MotanBeanDefinitionParser.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) throws ClassNotFoundException { RootBeanDefinition bd = new RootBeanDefinition(); bd.setBeanClass(beanClass);// www. j a v a 2 s. c o m // ??lazy init bd.setLazyInit(false); // id?id,idcontext String id = element.getAttribute("id"); if ((id == null || id.length() == 0) && required) { String generatedBeanName = element.getAttribute("name"); if (generatedBeanName == null || generatedBeanName.length() == 0) { generatedBeanName = element.getAttribute("class"); } if (generatedBeanName == null || generatedBeanName.length() == 0) { generatedBeanName = beanClass.getName(); } id = generatedBeanName; int counter = 2; while (parserContext.getRegistry().containsBeanDefinition(id)) { id = generatedBeanName + (counter++); } } if (id != null && id.length() > 0) { if (parserContext.getRegistry().containsBeanDefinition(id)) { throw new IllegalStateException("Duplicate spring bean id " + id); } parserContext.getRegistry().registerBeanDefinition(id, bd); } bd.getPropertyValues().addPropertyValue("id", id); if (ProtocolConfig.class.equals(beanClass)) { MotanNamespaceHandler.protocolDefineNames.add(id); } else if (RegistryConfig.class.equals(beanClass)) { MotanNamespaceHandler.registryDefineNames.add(id); } else if (BasicServiceInterfaceConfig.class.equals(beanClass)) { MotanNamespaceHandler.basicServiceConfigDefineNames.add(id); } else if (BasicRefererInterfaceConfig.class.equals(beanClass)) { MotanNamespaceHandler.basicRefererConfigDefineNames.add(id); } else if (ServiceConfigBean.class.equals(beanClass)) { String className = element.getAttribute("class"); if (className != null && className.length() > 0) { RootBeanDefinition classDefinition = new RootBeanDefinition(); classDefinition.setBeanClass( Class.forName(className, true, Thread.currentThread().getContextClassLoader())); classDefinition.setLazyInit(false); parseProperties(element.getChildNodes(), classDefinition); bd.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, id + "Impl")); } } Set<String> props = new HashSet<String>(); ManagedMap parameters = null; // ??setbd for (Method setter : beanClass.getMethods()) { String name = setter.getName(); // setXXX if (name.length() <= 3 || !name.startsWith("set") || !Modifier.isPublic(setter.getModifiers()) || setter.getParameterTypes().length != 1) { continue; } String property = (name.substring(3, 4).toLowerCase() + name.substring(4)).replaceAll("_", "-"); props.add(property); if ("id".equals(property)) { bd.getPropertyValues().addPropertyValue("id", id); continue; } String value = element.getAttribute(property); if ("methods".equals(property)) { parseMethods(id, element.getChildNodes(), bd, parserContext); } if (StringUtils.isBlank(value)) { continue; } value = value.trim(); if (value.length() == 0) { continue; } Object reference; if ("ref".equals(property)) { if (parserContext.getRegistry().containsBeanDefinition(value)) { BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value); if (!refBean.isSingleton()) { throw new IllegalStateException( "The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: <bean id=\"" + value + "\" scope=\"singleton\" ...>"); } } reference = new RuntimeBeanReference(value); } else if ("protocol".equals(property) && !StringUtils.isBlank(value)) { if (!value.contains(",")) { reference = new RuntimeBeanReference(value); } else { parseMultiRef("protocols", value, bd, parserContext); reference = null; } } else if ("registry".equals(property)) { parseMultiRef("registries", value, bd, parserContext); reference = null; } else if ("basicService".equals(property)) { reference = new RuntimeBeanReference(value); } else if ("basicReferer".equals(property)) { reference = new RuntimeBeanReference(value); } else if ("extConfig".equals(property)) { reference = new RuntimeBeanReference(value); } else { reference = new TypedStringValue(value); } if (reference != null) { bd.getPropertyValues().addPropertyValue(property, reference); } } if (ProtocolConfig.class.equals(beanClass)) { // protocolparameters? NamedNodeMap attributes = element.getAttributes(); int len = attributes.getLength(); for (int i = 0; i < len; i++) { Node node = attributes.item(i); String name = node.getLocalName(); if (!props.contains(name)) { if (parameters == null) { parameters = new ManagedMap(); } String value = node.getNodeValue(); parameters.put(name, new TypedStringValue(value, String.class)); } } bd.getPropertyValues().addPropertyValue("parameters", parameters); } return bd; }
From source file:fr.certu.chouette.command.Command.java
/** * @param beanClass/*from w ww . j a va2s. co m*/ * @param attribute * @return * @throws Exception */ private Method findRemover(Class<?> beanClass, String attribute, Class<?> argType) throws Exception { String methodName = "remove" + attribute; Method[] methods = beanClass.getMethods(); Method accessor = null; for (Method method : methods) { if (method.getName().equalsIgnoreCase(methodName)) { Class<?> parmType = method.getParameterTypes()[0]; if (argType.equals(parmType)) { accessor = method; break; } } } if (accessor == null) { throw new Exception( "unknown accessor remove for attribute " + attribute + " for object " + beanClass.getName() + " with argument type = " + argType.getSimpleName() + ", process stopped "); } return accessor; }
From source file:fr.certu.chouette.command.Command.java
/** * @param beanClass/* w w w . j a v a 2 s. c o m*/ * @param attribute * @return * @throws Exception */ private Method findAccessor(Class<?> beanClass, String attribute, String prefix, boolean ex) throws Exception { String methodName = prefix + attribute; Method[] methods = beanClass.getMethods(); Method accessor = null; for (Method method : methods) { if (method.getName().equalsIgnoreCase(methodName)) { accessor = method; break; } } if (ex && accessor == null) { throw new Exception("unknown accessor " + prefix + " for attribute " + attribute + " for object " + beanClass.getName() + ", process stopped "); } return accessor; }
From source file:com.cnaude.purpleirc.PurpleIRC.java
private void detectHooks() { logInfo("Detecting plugin hooks..."); if (isPluginEnabled(PL_HEROCHAT)) { hookList.add(hookFormat(PL_HEROCHAT, true)); getServer().getPluginManager().registerEvents(new HeroChatListener(this), this); heroConfig = new YamlConfiguration(); heroConfigFile = new File(getServer().getPluginManager().getPlugin(PL_HEROCHAT).getDataFolder(), "config.yml"); try {//from ww w. jav a2 s . com heroConfig.load(heroConfigFile); } catch (IOException | InvalidConfigurationException ex) { logError(ex.getMessage()); } heroChatEmoteFormat = heroConfig.getString("format.emote", ""); } else { hookList.add(hookFormat(PL_HEROCHAT, false)); } if (isPluginEnabled(PL_GRIEFPREVENTION)) { Class cls = null; boolean hooked = false; try { cls = Class.forName("me.ryanhamshire.GriefPrevention.DataStore"); } catch (ClassNotFoundException ex) { logDebug(ex.getMessage()); } if (cls != null) { for (Method m : cls.getMethods()) { if (m.getName().equals("isSoftMuted")) { hookList.add(hookFormat(PL_GRIEFPREVENTION, true)); griefPreventionHook = new GriefPreventionHook(this); hooked = true; break; } } } if (!hooked) { hookList.add(hookFormat(PL_GRIEFPREVENTION, false)); } } else { hookList.add(hookFormat(PL_GRIEFPREVENTION, false)); } if (isPluginEnabled(PL_TITANCHAT)) { hookList.add(hookFormat(PL_TITANCHAT, true)); getServer().getPluginManager().registerEvents(new TitanChatListener(this), this); } else { hookList.add(hookFormat(PL_TITANCHAT, false)); } if (isPluginEnabled(PL_VENTURECHAT)) { hookList.add(hookFormat(PL_VENTURECHAT, true)); ventureChatEnabled = true; vcHook = new VentureChatHook(this); getServer().getPluginManager().registerEvents(new VentureChatListener(this), this); } else { hookList.add(hookFormat(PL_VENTURECHAT, false)); ventureChatEnabled = false; vcHook = null; } if (isPluginEnabled(PL_PRISM)) { hookList.add(hookFormat(PL_PRISM, true)); getServer().getPluginManager().registerEvents(new PrismListener(this), this); } else { hookList.add(hookFormat(PL_PRISM, false)); } if (isPluginEnabled(PL_REDDITSTREAM)) { hookList.add(hookFormat(PL_REDDITSTREAM, true)); getServer().getPluginManager().registerEvents(new RedditStreamListener(this), this); } else { hookList.add(hookFormat(PL_REDDITSTREAM, false)); } if (isPluginEnabled(PL_TOWNYCHAT)) { hookList.add(hookFormat(PL_TOWNYCHAT, true)); getServer().getPluginManager().registerEvents(new TownyChatListener(this), this); tcHook = new TownyChatHook(this); } else { hookList.add(hookFormat(PL_TOWNYCHAT, false)); } if (isPluginEnabled(PL_CLEVERNOTCH)) { hookList.add(hookFormat(PL_CLEVERNOTCH, true)); getServer().getPluginManager().registerEvents(new CleverNotchListener(this), this); } else { hookList.add(hookFormat(PL_CLEVERNOTCH, false)); } if (isPluginEnabled(PL_MCMMO)) { hookList.add(hookFormat(PL_MCMMO, true)); getServer().getPluginManager().registerEvents(new McMMOChatListener(this), this); mcMMOChatHook = new McMMOChatHook(this); } else { hookList.add(hookFormat(PL_MCMMO, false)); } if (isFactionsEnabled()) { if (isPluginEnabled(PL_FACTIONCHAT)) { String factionChatVersion = getServer().getPluginManager().getPlugin(PL_FACTIONCHAT) .getDescription().getVersion(); if (factionChatVersion.startsWith("1.7")) { logError(PL_FACTIONCHAT + " v" + factionChatVersion + " not supported. Please install 1.8 or newer."); hookList.add(hookFormat(PL_FACTIONCHAT, false)); } else { hookList.add(hookFormat(PL_FACTIONCHAT, true)); fcHook = new FactionChatHook(this); } } else { hookList.add(hookFormat(PL_FACTIONCHAT, false)); } } else { hookList.add(hookFormat(PL_FACTIONCHAT, false)); } if (isPluginEnabled(PL_ADMINPRIVATECHAT)) { if (getServer().getPluginManager().getPlugin(PL_ADMINPRIVATECHAT).getDescription().getAuthors() .contains("cnaude")) { hookList.add(hookFormat(PL_ADMINPRIVATECHAT, true)); adminPrivateChatHook = new AdminPrivateChatHook(this); getServer().getPluginManager().registerEvents(new AdminChatListener(this), this); } else { logError(PL_ADMINPRIVATECHAT + "Version not supported. Please use the latest version from http://jenkins.cnaude.org/job/AdminPrivateChat/"); } } else { hookList.add(hookFormat(PL_ADMINPRIVATECHAT, false)); } if (isPluginEnabled(PL_COMMANDBOOK)) { hookList.add(hookFormat(PL_COMMANDBOOK, true)); commandBookHook = new CommandBookHook(this); } else { hookList.add(hookFormat(PL_COMMANDBOOK, false)); } if (isPluginEnabled(PL_JOBS)) { hookList.add(hookFormat(PL_JOBS, true)); jobsHook = new JobsHook(this); } else { hookList.add(hookFormat(PL_JOBS, false)); } if (isPluginEnabled(PL_DEATHMESSAGES)) { hookList.add(hookFormat(PL_DEATHMESSAGES, true)); getServer().getPluginManager().registerEvents(new DeathMessagesListener(this), this); } else { hookList.add(hookFormat(PL_DEATHMESSAGES, false)); } if (isPluginEnabled(PL_SHORTIFY)) { String shortifyVersion = getServer().getPluginManager().getPlugin(PL_SHORTIFY).getDescription() .getVersion(); if (shortifyVersion.startsWith("1.8")) { hookList.add(hookFormat(PL_SHORTIFY, true)); shortifyHook = new ShortifyHook(this); } else { hookList.add(hookFormat(PL_SHORTIFY, false)); logError(PL_SHORTIFY + " v" + shortifyVersion + " not supported. Please use the latest version from http://jenkins.cnaude.org/job/Shortify/"); } } else { hookList.add(hookFormat(PL_SHORTIFY, false)); } if (isPluginEnabled(PL_DYNMAP)) { hookList.add(hookFormat(PL_DYNMAP, true)); getServer().getPluginManager().registerEvents(new DynmapListener(this), this); dynmapHook = new DynmapHook(this); } else { hookList.add(hookFormat(PL_DYNMAP, false)); } if (isPluginEnabled(PL_OREBROADCAST)) { hookList.add(hookFormat(PL_OREBROADCAST, true)); getServer().getPluginManager().registerEvents(new OreBroadcastListener(this), this); } else { hookList.add(hookFormat(PL_OREBROADCAST, false)); } vanishHook = new VanishHook(this); if (isPluginEnabled(PL_VANISHNOPACKET)) { hookList.add(hookFormat(PL_VANISHNOPACKET, true)); getServer().getPluginManager().registerEvents(new VanishNoPacketListener(this), this); } else { hookList.add(hookFormat(PL_VANISHNOPACKET, false)); } if (isPluginEnabled(PL_SUPERVANISH)) { hookList.add(hookFormat(PL_SUPERVANISH, true)); superVanishHook = new SuperVanishHook(this); } else { hookList.add(hookFormat(PL_SUPERVANISH, false)); } if (isPluginEnabled(PL_REPORTRTS)) { hookList.add(hookFormat(PL_REPORTRTS, true)); getServer().getPluginManager().registerEvents(new ReportRTSListener(this), this); reportRTSHook = new ReportRTSHook(this); } else { hookList.add(hookFormat(PL_REPORTRTS, false)); } if (isPluginEnabled(PL_SIMPLETICKET)) { hookList.add(hookFormat(PL_SIMPLETICKET, true)); getServer().getPluginManager().registerEvents(new SimpleTicketManagerListener(this), this); } else { hookList.add(hookFormat(PL_SIMPLETICKET, false)); } if (isPluginEnabled(PL_NTHE_END_AGAIN)) { hookList.add(hookFormat(PL_NTHE_END_AGAIN, true)); getServer().getPluginManager().registerEvents(new NTheEndAgainListener(this), this); } else { hookList.add(hookFormat(PL_NTHE_END_AGAIN, false)); } if (isPluginEnabled(PL_ESSENTIALS)) { hookList.add(hookFormat(PL_ESSENTIALS, true)); getServer().getPluginManager().registerEvents(new EssentialsListener(this), this); } else { hookList.add(hookFormat(PL_ESSENTIALS, false)); } }
From source file:io.coala.json.DynaBean.java
/** * @param referenceType/*from w w w. j a va 2s . co m*/ * @param <S> * @param <T> * @return */ static final <S, T> JsonDeserializer<T> createJsonDeserializer(final ObjectMapper om, final Class<T> resultType, final Properties... imports) { return new JsonDeserializer<T>() { @Override public T deserializeWithType(final JsonParser jp, final DeserializationContext ctxt, final TypeDeserializer typeDeserializer) throws IOException, JsonProcessingException { return deserialize(jp, ctxt); } @Override public T deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) return null; // if( Wrapper.class.isAssignableFrom( resultType ) ) // { // // FIXME // LOG.trace( "deser wrapper intf of {}", jp.getText() ); // return (T) Wrapper.Util.valueOf( jp.getText(), // resultType.asSubclass( Wrapper.class ) ); // } if (Config.class.isAssignableFrom(resultType)) { final Map<String, Object> entries = jp.readValueAs(new TypeReference<Map<String, Object>>() { }); final Iterator<Entry<String, Object>> it = entries.entrySet().iterator(); for (Entry<String, Object> next = null; it.hasNext(); next = it.next()) if (next != null && next.getValue() == null) { LOG.trace("Ignoring null value: {}", next); it.remove(); } return resultType.cast(ConfigFactory.create(resultType.asSubclass(Config.class), entries)); } // else if (Config.class.isAssignableFrom(resultType)) // throw new JsonGenerationException( // "Config does not extend "+Mutable.class.getName()+" required for deserialization: " // + Arrays.asList(resultType // .getInterfaces())); // can't parse directly to interface type final DynaBean bean = new DynaBean(); final TreeNode tree = jp.readValueAsTree(); // override attributes as defined in interface getters final Set<String> attributes = new HashSet<>(); for (Method method : resultType.getMethods()) { if (method.getReturnType().equals(Void.TYPE) || method.getParameterTypes().length != 0) continue; final String attribute = method.getName(); if (attribute.equals("toString") || attribute.equals("hashCode")) continue; attributes.add(attribute); final TreeNode value = tree.get(attribute);// bean.any().get(attributeName); if (value == null) continue; bean.set(method.getName(), om.treeToValue(value, JsonUtil.checkRegistered(om, method.getReturnType(), imports))); } if (tree.isObject()) { // keep superfluous properties as TreeNodes, just in case final Iterator<String> fieldNames = tree.fieldNames(); while (fieldNames.hasNext()) { final String fieldName = fieldNames.next(); if (!attributes.contains(fieldName)) bean.set(fieldName, tree.get(fieldName)); } } else if (tree.isValueNode()) { for (Class<?> type : resultType.getInterfaces()) for (Method method : type.getDeclaredMethods()) { // LOG.trace( "Scanning {}", method ); if (method.isAnnotationPresent(JsonProperty.class)) { final String property = method.getAnnotation(JsonProperty.class).value(); // LOG.trace( "Setting {}: {}", property, // ((ValueNode) tree).textValue() ); bean.set(property, ((ValueNode) tree).textValue()); } } } else throw ExceptionFactory.createUnchecked("Expected {} but parsed: {}", resultType, tree.getClass()); return DynaBean.proxyOf(om, resultType, bean, imports); } }; }
From source file:AppearanceTest.java
public void actionPerformed(ActionEvent event) { // (primitive) menu command dispatch Class classObject = getClass(); Method[] methodArray = classObject.getMethods(); for (int n = methodArray.length - 1; n >= 0; n--) { if (("on" + event.getActionCommand()).equals(methodArray[n].getName())) { try { methodArray[n].invoke(this, null); } catch (InvocationTargetException ie) { System.err.println("Warning. Menu handler threw exception: " + ie.getTargetException()); } catch (Exception e) { System.err.println("Warning. Menu dispatch exception: " + e); }/*from ww w. j a v a 2 s . c o m*/ return; } } }