List of usage examples for java.lang.reflect Method getDeclaredAnnotations
public Annotation[] getDeclaredAnnotations()
From source file:com.strandls.alchemy.rest.client.RestInterfaceAnalyzer.java
/** * Get rest meta data for the method.//from ww w .j a va2 s . c o m * * @param method * the method to analyze. * @return the metadata for a method. */ private RestMethodMetadata analyzeMethod(final Method method) { String path = ""; String httpMethod = null; final List<String> produced = new ArrayList<String>(); final List<String> consumed = new ArrayList<String>(); final Annotation[] annotations = method.getDeclaredAnnotations(); for (final Annotation annotation : annotations) { if (annotation instanceof Path) { path = ((Path) annotation).value(); } else if (annotation instanceof GET) { httpMethod = HttpMethod.GET; } else if (annotation instanceof PUT) { httpMethod = HttpMethod.PUT; } else if (annotation instanceof POST) { httpMethod = HttpMethod.POST; } else if (annotation instanceof DELETE) { httpMethod = HttpMethod.DELETE; } else if (annotation instanceof Produces) { final Produces produces = (Produces) annotation; produced.addAll(Arrays.asList(produces.value())); } else if (annotation instanceof Consumes) { final Consumes consumes = (Consumes) annotation; consumed.addAll(Arrays.asList(consumes.value())); } } if (StringUtils.isBlank(httpMethod)) { // no http method specified. return null; } return new RestMethodMetadata(path, httpMethod, produced, consumed, method.getParameterAnnotations()); }
From source file:org.wso2.carbon.device.mgt.extensions.feature.mgt.util.AnnotationUtil.java
private List<Feature> getFeatures(Method[] annotatedMethods) throws Throwable { List<Feature> featureList = new ArrayList<>(); for (Method method : annotatedMethods) { Annotation methodAnnotation = method.getAnnotation(featureClazz); if (methodAnnotation != null) { Annotation[] annotations = method.getDeclaredAnnotations(); for (int i = 0; i < annotations.length; i++) { if (annotations[i].annotationType().getName() .equals(org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature.class .getName())) { Feature feature = new Feature(); Method[] featureAnnoMethods = featureClazz.getMethods(); Annotation featureAnno = method.getAnnotation(featureClazz); for (int k = 0; k < featureAnnoMethods.length; k++) { switch (featureAnnoMethods[k].getName()) { case "name": feature.setName(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); break; case "code": feature.setCode(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); break; case "description": feature.setDescription(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); break; case "type": feature.setType(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); break; }//from w w w . j a v a2 s . c o m } //Extracting method with which feature is exposed if (annotations[i].annotationType().getName().equals(GET.class.getName())) { feature.setMethod(HttpMethod.GET); } if (annotations[i].annotationType().getName().equals(POST.class.getName())) { feature.setMethod(HttpMethod.POST); } if (annotations[i].annotationType().getName().equals(OPTIONS.class.getName())) { feature.setMethod(HttpMethod.OPTIONS); } if (annotations[i].annotationType().getName().equals(DELETE.class.getName())) { feature.setMethod(HttpMethod.DELETE); } if (annotations[i].annotationType().getName().equals(PUT.class.getName())) { feature.setMethod(HttpMethod.PUT); } try { Class<FormParam> formParamClazz = (Class<FormParam>) classLoader .loadClass(FormParam.class.getName()); Method[] formMethods = formParamClazz.getMethods(); //Extract method parameter information and store same as feature meta info List<Feature.MetadataEntry> metaInfoList = new ArrayList<>(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); for (int j = 0; j < paramAnnotations.length; j++) { for (Annotation anno : paramAnnotations[j]) { if (anno.annotationType().getName().equals(FormParam.class.getName())) { Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry(); metadataEntry.setId(j); metadataEntry.setValue(invokeMethod(formMethods[0], anno, STRING)); metaInfoList.add(metadataEntry); } } } feature.setMetadataEntries(metaInfoList); } catch (ClassNotFoundException e) { log.debug("No Form Param found for class " + featureClazz.getName()); } featureList.add(feature); } } } } return featureList; }
From source file:org.wso2.carbon.device.mgt.core.config.permission.AnnotationProcessor.java
/** * Get Resources for each API// w w w . j av a 2 s . c o m * * @param resourceRootContext * @param annotatedMethods * @return * @throws Throwable */ private List<Permission> getApiResources(String resourceRootContext, Method[] annotatedMethods) throws Throwable { List<Permission> permissions = new ArrayList<>(); Permission permission; String subCtx; for (Method method : annotatedMethods) { Annotation[] annotations = method.getDeclaredAnnotations(); if (isHttpMethodAvailable(annotations)) { Annotation methodContextAnno = method.getAnnotation(pathClazz); if (methodContextAnno != null) { subCtx = invokeMethod(pathClazzMethods[0], methodContextAnno, STRING); } else { subCtx = WILD_CARD; } permission = new Permission(); // this check is added to avoid url resolving conflict which happens due // to adding of '*' notation for dynamic path variables. if (WILD_CARD.equals(subCtx)) { subCtx = makeContextURLReady(resourceRootContext); } else { subCtx = makeContextURLReady(resourceRootContext) + makeContextURLReady(subCtx); } permission.setUrl(replaceDynamicPathVariables(subCtx)); String httpMethod; for (int i = 0; i < annotations.length; i++) { httpMethod = getHTTPMethodAnnotation(annotations[i]); if (httpMethod != null) { permission.setMethod(httpMethod); } if (annotations[i].annotationType().getName() .equals(io.swagger.annotations.ApiOperation.class.getName())) { this.setPermission(annotations[i], permission); } } if (permission.getName() == null || permission.getPath() == null) { log.warn("Permission not assigned to the resource url - " + permission.getMethod() + ":" + permission.getUrl()); } else { permissions.add(permission); } } } return permissions; }
From source file:org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor.java
/** * Get Resources for each API/*from www . j a v a 2s .c o m*/ * * @param resourceRootContext * @param annotatedMethods * @return * @throws Throwable */ private List<APIResource> getApiResources(String resourceRootContext, Method[] annotatedMethods) throws Throwable { List<APIResource> resourceList = new ArrayList<>(); String subCtx = null; for (Method method : annotatedMethods) { Annotation[] annotations = method.getDeclaredAnnotations(); APIResource resource = new APIResource(); if (isHttpMethodAvailable(annotations)) { Annotation methodContextAnno = method.getAnnotation(pathClazz); if (methodContextAnno != null) { subCtx = invokeMethod(pathClazzMethods[0], methodContextAnno, STRING); } else { subCtx = WILD_CARD; } resource.setUriTemplate(makeContextURLReady(subCtx)); resource.setUri(APIPublisherUtil.getServerBaseUrl() + makeContextURLReady(resourceRootContext) + makeContextURLReady(subCtx)); resource.setAuthType(AUTH_TYPE); for (int i = 0; i < annotations.length; i++) { processHTTPMethodAnnotation(resource, annotations[i]); if (annotations[i].annotationType().getName().equals(Consumes.class.getName())) { Method[] consumesClassMethods = consumesClass.getMethods(); Annotation consumesAnno = method.getAnnotation(consumesClass); resource.setConsumes(invokeMethod(consumesClassMethods[0], consumesAnno, STRING_ARR)); } if (annotations[i].annotationType().getName().equals(Produces.class.getName())) { Method[] producesClassMethods = producesClass.getMethods(); Annotation producesAnno = method.getAnnotation(producesClass); resource.setProduces(invokeMethod(producesClassMethods[0], producesAnno, STRING_ARR)); } if (annotations[i].annotationType().getName().equals(ApiOperation.class.getName())) { ApiScope scope = this.getScope(annotations[i]); if (scope != null) { resource.setScope(scope); } else { log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) + makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope"); scope = new ApiScope(); scope.setName(DEFAULT_SCOPE_NAME); scope.setDescription(DEFAULT_SCOPE_NAME); scope.setKey(DEFAULT_SCOPE_KEY); scope.setRoles(DEFAULT_SCOPE_PERMISSION); resource.setScope(scope); } } } resourceList.add(resource); } } return resourceList; }
From source file:gda.jython.scriptcontroller.logging.LoggingScriptController.java
private void determineColumns() { Method[] gettersWeWant = new Method[0]; columnGetters = new LinkedHashMap<Method, String>(); refreshColumnGetters = new HashMap<Method, String>(); // loop over all methods to find ones with the correct annotation Method[] methods = messageClassToLog.getDeclaredMethods(); for (Method method : methods) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ScriptControllerLogColumn) { gettersWeWant = (Method[]) ArrayUtils.add(gettersWeWant, method); continue; }/* ww w . j a v a2 s .co m*/ } } // order the methods bsed on the annotation's column index Method[] gettersWeWant_ordered = new Method[gettersWeWant.length]; for (Method method : gettersWeWant) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ScriptControllerLogColumn) { gettersWeWant_ordered[((ScriptControllerLogColumn) annotation).columnIndex()] = method; } } } // add the method references and their column labels to the hashmaps for (Method method : gettersWeWant_ordered) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ScriptControllerLogColumn) { columnGetters.put(method, ((ScriptControllerLogColumn) annotation).columnName()); if (((ScriptControllerLogColumn) annotation).refresh()) { refreshColumnGetters.put(method, ((ScriptControllerLogColumn) annotation).columnName()); } } } } }
From source file:org.wso2.carbon.device.mgt.extensions.feature.mgt.util.AnnotationProcessor.java
private List<Feature> getFeatures(Method[] methodsList) throws Throwable { List<Feature> featureList = new ArrayList<>(); for (Method currentMethod : methodsList) { Annotation featureAnnotation = currentMethod.getAnnotation(featureAnnotationClazz); if (featureAnnotation != null) { Feature feature = new Feature(); feature = processFeatureAnnotation(feature, currentMethod); Annotation[] annotations = currentMethod.getDeclaredAnnotations(); Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry(); metadataEntry.setId(-1);/*from w w w .ja v a2s . c o m*/ Map<String, Object> apiParams = new HashMap<>(); for (int i = 0; i < annotations.length; i++) { Annotation currentAnnotation = annotations[i]; processHttpMethodAnnotation(apiParams, currentAnnotation); if (currentAnnotation.annotationType().getName().equals(Path.class.getName())) { String uri = getPathAnnotationValue(currentMethod); apiParams.put("uri", uri); } apiParams = processParamAnnotations(apiParams, currentMethod); } metadataEntry.setValue(apiParams); List<Feature.MetadataEntry> metaInfoList = new ArrayList<>(); metaInfoList.add(metadataEntry); feature.setMetadataEntries(metaInfoList); featureList.add(feature); } } return featureList; }
From source file:com.github.steveash.typedconfig.ConfigFactoryContext.java
/** * Given the class and method on the proxy this will create a new ConfigBinding whcih represents a particular * "binding" between a proxy call site and the configuration target (not the configuration instance, but the * location (key) within a configuration instance (w.r.t the same configuration context)) * @param interfaze//from ww w. j a va 2 s . c o m * @param method * @param config * @return */ public ConfigBinding getBindingFor(Class<?> interfaze, Method method, HierarchicalConfiguration config) { ConfigProxy configProxy = getAnnotationResolver().getConfigProxy(interfaze); Config configValue = getAnnotationResolver().getConfigAnnotation(method); List<Option> options = Arrays.asList(configValue.options()); String localKey = getLocalConfigKey(method, configValue); String baseKey = configProxy.basekey(); String combinedLocalKey = getCombinedKey(baseKey, localKey, config); List<Annotation> anns = Lists.newArrayList(method.getDeclaredAnnotations()); return new ConfigBinding(combinedLocalKey, TypeToken.of(method.getGenericReturnType()), options, anns); }
From source file:com.app.server.JarDeployer.java
/** * This method implements the jar deployer which configures the executor services. * Frequently monitors the deploy directory and configures the executor services map * once the jar is deployed in deploy directory and reconfigures if the jar is modified and * placed in the deploy directory.//from www .jav a 2s .c o m */ public void run() { StandardFileSystemManager fsManager = new StandardFileSystemManager(); try { fsManager.init(); DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } File file = new File(scanDirectory.split(";")[0]); File[] files = file.listFiles(); CopyOnWriteArrayList<String> classList = new CopyOnWriteArrayList<String>(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) continue; //Long lastModified=(Long) fileMap.get(files[i].getName()); if (files[i].getName().endsWith(".jar")) { String filePath = files[i].getAbsolutePath(); FileObject jarFile = null; try { jarFile = fsManager.resolveFile("jar:" + filePath); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //logger.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".jar")); WebClassLoader customClassLoader = null; try { URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); try { customClassLoader = new WebClassLoader(urls); log.info(customClassLoader.geturlS()); customClassLoader.addURL(new URL("file:/" + files[i].getAbsolutePath())); CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList(); getUsersJars(new File(libDir), jarList); for (String jarFilePath : jarList) customClassLoader.addURL(new URL("file:/" + jarFilePath.replace("\\", "/"))); log.info("deploy=" + customClassLoader.geturlS()); this.urlClassLoaderMap.put(scanDirectory + "/" + files[i].getName(), customClassLoader); jarsDeployed.add(files[i].getName()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } log.info(urlClassLoaderMap); getChildren(jarFile, classList); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for (int classCount = 0; classCount < classList.size(); classCount++) { String classwithpackage = classList.get(classCount).substring(0, classList.get(classCount).indexOf(".class")); classwithpackage = classwithpackage.replace("/", "."); log.info("classList:" + classwithpackage.replace("/", ".")); try { if (!classwithpackage.contains("$")) { Class executorServiceClass = customClassLoader.loadClass(classwithpackage); //log.info("executor class in ExecutorServicesConstruct"+executorServiceClass); //log.info(); if (!executorServiceClass.isInterface()) { Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof RemoteCall) { RemoteCall remoteCall = (RemoteCall) classServicesAnnot[annotcount]; //registry.unbind(remoteCall.servicename()); log.info(remoteCall.servicename().trim()); try { //for(int count=0;count<500;count++){ RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject .exportObject((Remote) executorServiceClass.newInstance(), 2004); registry.rebind(remoteCall.servicename().trim(), reminterface); //} } catch (Exception ex) { ex.printStackTrace(); } } } } } Method[] methods = executorServiceClass.getDeclaredMethods(); for (Method method : methods) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ExecutorServiceAnnot) { ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation; ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo(); executorServiceInfo.setExecutorServicesClass(executorServiceClass); executorServiceInfo.setMethod(method); executorServiceInfo.setMethodParams(method.getParameterTypes()); //log.info("method="+executorServiceAnnot.servicename()); //log.info("method info="+executorServiceInfo); //if(servicesMap.get(executorServiceAnnot.servicename())==null)throw new Exception(); executorServiceMap.put(executorServiceAnnot.servicename(), executorServiceInfo); } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } ClassLoaderUtil.closeClassLoader(customClassLoader); try { jarFile.close(); } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fsManager.closeFileSystem(jarFile.getFileSystem()); } } fsManager.close(); fsManager = new StandardFileSystemManager(); try { DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JarFileListener jarFileListener = new JarFileListener(executorServiceMap, libDir, urlClassLoaderMap, jarsDeployed); DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener); jarFileListener.setFm(fm); FileObject listendir = null; String[] dirsToScan = scanDirectory.split(";"); try { FileSystemOptions opts = new FileSystemOptions(); FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); fsManager.init(); for (String dir : dirsToScan) { if (dir.startsWith("ftp://")) { listendir = fsManager.resolveFile(dir, opts); } else { listendir = fsManager.resolveFile(dir); } fm.addFile(listendir); } } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fm.setRecursive(true); fm.setDelay(3000); fm.start(); //fsManager.close(); }
From source file:com.web.server.JarDeployer.java
/** * This method implements the jar deployer which configures the executor services. * Frequently monitors the deploy directory and configures the executor services map * once the jar is deployed in deploy directory and reconfigures if the jar is modified and * placed in the deploy directory.// ww w.ja v a2s .c o m */ public void run() { StandardFileSystemManager fsManager = new StandardFileSystemManager(); try { fsManager.init(); DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } File file = new File(scanDirectory.split(";")[0]); File[] files = file.listFiles(); CopyOnWriteArrayList<String> classList = new CopyOnWriteArrayList<String>(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) continue; //Long lastModified=(Long) fileMap.get(files[i].getName()); if (files[i].getName().endsWith(".jar")) { String filePath = files[i].getAbsolutePath(); FileObject jarFile = null; try { jarFile = fsManager.resolveFile("jar:" + filePath); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //logger.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".jar")); WebClassLoader customClassLoader = null; try { URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); try { customClassLoader = new WebClassLoader(urls); System.out.println(customClassLoader.geturlS()); new WebServer().addURL(new URL("file:/" + files[i].getAbsolutePath()), customClassLoader); CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList(); getUsersJars(new File(libDir), jarList); for (String jarFilePath : jarList) new WebServer().addURL(new URL("file:/" + jarFilePath.replace("\\", "/")), customClassLoader); System.out.println("deploy=" + customClassLoader.geturlS()); this.urlClassLoaderMap.put(scanDirectory + "/" + files[i].getName(), customClassLoader); jarsDeployed.add(files[i].getName()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(urlClassLoaderMap); getChildren(jarFile, classList); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for (int classCount = 0; classCount < classList.size(); classCount++) { String classwithpackage = classList.get(classCount).substring(0, classList.get(classCount).indexOf(".class")); classwithpackage = classwithpackage.replace("/", "."); System.out.println("classList:" + classwithpackage.replace("/", ".")); try { if (!classwithpackage.contains("$")) { Class executorServiceClass = customClassLoader.loadClass(classwithpackage); //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass); //System.out.println(); if (!executorServiceClass.isInterface()) { Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof RemoteCall) { RemoteCall remoteCall = (RemoteCall) classServicesAnnot[annotcount]; //registry.unbind(remoteCall.servicename()); System.out.println(remoteCall.servicename().trim()); try { //for(int count=0;count<500;count++){ RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject .exportObject((Remote) executorServiceClass.newInstance(), 2004); registry.rebind(remoteCall.servicename().trim(), reminterface); //} } catch (Exception ex) { ex.printStackTrace(); } } } } } Method[] methods = executorServiceClass.getDeclaredMethods(); for (Method method : methods) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ExecutorServiceAnnot) { ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation; ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo(); executorServiceInfo.setExecutorServicesClass(executorServiceClass); executorServiceInfo.setMethod(method); executorServiceInfo.setMethodParams(method.getParameterTypes()); //System.out.println("method="+executorServiceAnnot.servicename()); //System.out.println("method info="+executorServiceInfo); //if(servicesMap.get(executorServiceAnnot.servicename())==null)throw new Exception(); executorServiceMap.put(executorServiceAnnot.servicename(), executorServiceInfo); } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } ClassLoaderUtil.closeClassLoader(customClassLoader); try { jarFile.close(); } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fsManager.closeFileSystem(jarFile.getFileSystem()); } } fsManager.close(); fsManager = new StandardFileSystemManager(); try { DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JarFileListener jarFileListener = new JarFileListener(executorServiceMap, libDir, urlClassLoaderMap, jarsDeployed); DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener); jarFileListener.setFm(fm); FileObject listendir = null; String[] dirsToScan = scanDirectory.split(";"); try { FileSystemOptions opts = new FileSystemOptions(); FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); fsManager.init(); for (String dir : dirsToScan) { if (dir.startsWith("ftp://")) { listendir = fsManager.resolveFile(dir, opts); } else { listendir = fsManager.resolveFile(dir); } fm.addFile(listendir); } } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fm.setRecursive(true); fm.setDelay(3000); fm.start(); //fsManager.close(); }
From source file:io.stallion.restfulEndpoints.ResourceToEndpoints.java
public List<JavaRestEndpoint> convert(EndpointResource resource) { Class cls = resource.getClass(); List<JavaRestEndpoint> endpoints = new ArrayList<>(); // Get defaults from the resource Role defaultMinRole = Settings.instance().getUsers().getDefaultEndpointRoleObj(); MinRole minRoleAnno = (MinRole) cls.getAnnotation(MinRole.class); if (minRoleAnno != null) { defaultMinRole = minRoleAnno.value(); }/*from w ww . j a v a 2s . c o m*/ String defaultProduces = "text/html"; Produces producesAnno = (Produces) cls.getAnnotation(Produces.class); if (producesAnno != null && producesAnno.value().length > 0) { defaultProduces = producesAnno.value()[0]; } Path pathAnno = (Path) cls.getAnnotation(Path.class); if (pathAnno != null) { basePath += pathAnno.value(); } Class defaultJsonViewClass = null; DefaultJsonView jsonView = (DefaultJsonView) cls.getAnnotation(DefaultJsonView.class); if (jsonView != null) { defaultJsonViewClass = jsonView.value(); } for (Method method : cls.getDeclaredMethods()) { JavaRestEndpoint endpoint = new JavaRestEndpoint(); endpoint.setRole(defaultMinRole); endpoint.setProduces(defaultProduces); if (defaultJsonViewClass != null) { endpoint.setJsonViewClass(defaultJsonViewClass); } Log.finer("Resource class method: {0}", method.getName()); for (Annotation anno : method.getDeclaredAnnotations()) { if (Path.class.isInstance(anno)) { Path pth = (Path) anno; endpoint.setRoute(getBasePath() + pth.value()); } else if (GET.class.isInstance(anno)) { endpoint.setMethod("GET"); } else if (POST.class.isInstance(anno)) { endpoint.setMethod("POST"); } else if (DELETE.class.isInstance(anno)) { endpoint.setMethod("DELETE"); } else if (PUT.class.isInstance(anno)) { endpoint.setMethod("PUT"); } else if (Produces.class.isInstance(anno)) { endpoint.setProduces(((Produces) anno).value()[0]); } else if (MinRole.class.isInstance(anno)) { endpoint.setRole(((MinRole) anno).value()); } else if (XSRF.class.isInstance(anno)) { endpoint.setCheckXSRF(((XSRF) anno).value()); } else if (JsonView.class.isInstance(anno)) { Class[] classes = ((JsonView) anno).value(); if (classes == null || classes.length != 1) { throw new UsageException("JsonView annotation for method " + method.getName() + " must have exactly one view class"); } endpoint.setJsonViewClass(classes[0]); } } if (!empty(endpoint.getMethod()) && !empty(endpoint.getRoute())) { endpoint.setJavaMethod(method); endpoint.setResource(resource); endpoints.add(endpoint); Log.fine("Register endpoint {0} {1}", endpoint.getMethod(), endpoint.getRoute()); } else { continue; } int x = -1; for (Parameter param : method.getParameters()) { x++; RequestArg arg = new RequestArg(); for (Annotation anno : param.getAnnotations()) { arg.setAnnotationInstance(anno); Log.finer("Param Annotation is: {0}, {1}", anno, anno.getClass().getName()); if (BodyParam.class.isInstance(anno)) { BodyParam bodyAnno = (BodyParam) (anno); arg.setType("BodyParam"); if (empty(bodyAnno.value())) { arg.setName(param.getName()); } else { arg.setName(((BodyParam) anno).value()); } arg.setAnnotationClass(BodyParam.class); arg.setRequired(bodyAnno.required()); arg.setEmailParam(bodyAnno.isEmail()); arg.setMinLength(bodyAnno.minLength()); arg.setAllowEmpty(bodyAnno.allowEmpty()); if (!empty(bodyAnno.validationPattern())) { arg.setValidationPattern(Pattern.compile(bodyAnno.validationPattern())); } } else if (ObjectParam.class.isInstance(anno)) { ObjectParam oParam = (ObjectParam) anno; arg.setType("ObjectParam"); arg.setName("noop"); if (oParam.targetClass() == null || oParam.targetClass().equals(Object.class)) { arg.setTargetClass(param.getType()); } else { arg.setTargetClass(oParam.targetClass()); } arg.setAnnotationClass(ObjectParam.class); } else if (MapParam.class.isInstance(anno)) { arg.setType("MapParam"); arg.setName("noop"); arg.setAnnotationClass(MapParam.class); } else if (QueryParam.class.isInstance(anno)) { arg.setType("QueryParam"); arg.setName(((QueryParam) anno).value()); arg.setAnnotationClass(QueryParam.class); } else if (PathParam.class.isInstance(anno)) { arg.setType("PathParam"); arg.setName(((PathParam) anno).value()); arg.setAnnotationClass(PathParam.class); } else if (DefaultValue.class.isInstance(anno)) { arg.setDefaultValue(((DefaultValue) anno).value()); } else if (NotNull.class.isInstance(anno)) { arg.setRequired(true); } else if (Nullable.class.isInstance(anno)) { arg.setRequired(false); } else if (NotEmpty.class.isInstance(anno)) { arg.setRequired(true); arg.setAllowEmpty(false); } else if (Email.class.isInstance(anno)) { arg.setEmailParam(true); } } if (StringUtils.isEmpty(arg.getType())) { arg.setType("ObjectParam"); arg.setName(param.getName()); arg.setTargetClass(param.getType()); arg.setAnnotationClass(ObjectParam.class); } if (StringUtils.isEmpty(arg.getName())) { arg.setName(param.getName()); } endpoint.getArgs().add(arg); } } return endpoints; }