private static <T> T getParamXPath( final Class<T> pClass, final String pXpath, final CompactFragment pBody) throws XmlException { // TODO Avoid JAXB where possible, use XMLDeserializer instead final boolean string = CharSequence.class.isAssignableFrom(pClass); Node match; DocumentFragment fragment = DomUtil.childrenToDocumentFragment(XMLFragmentStreamReader.from(pBody)); for (Node n = fragment.getFirstChild(); n != null; n = n.getNextSibling()) { match = xpathMatch(n, pXpath); if (match != null) { if (!string) { XmlDeserializer deserializer = pClass.getAnnotation(XmlDeserializer.class); if (deserializer != null) { try { XmlDeserializerFactory<?> factory = deserializer.value().newInstance(); factory.deserialize(XmlStreaming.newReader(new DOMSource(n))); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } else { return JAXB.unmarshal(new DOMSource(match), pClass); } } else { return pClass.cast(nodeToString(match)); } } } return null; }
/** * Get the protocol name. If the protocol class has a ProtocolAnnotation, then get the protocol * name from the annotation; otherwise the class name is the protocol name. */ public static String getProtocolName(Class<?> protocol) { if (protocol == null) { return null; } ProtocolInfo anno = protocol.getAnnotation(ProtocolInfo.class); return (anno == null) ? protocol.getName() : anno.protocolName(); }
public static <T> T getConfig(Class<T> c) { String key = c.getName(); T t = CacheManager.get(key, c); if (t != null) return t; System.out.println("not hit cache"); String path = getAbsolutePath(c.getAnnotation(XmlPath.class).value()); t = getXmlConfig(c, path); CacheManager.set(key, 1000 * 60 * 60 * 24, t); return t; }
/** * Check for an @RequestMapping annotation on the class and, if present, store the RequestMethod * and the URL mapping */ public void initialize() { Annotation ann = clazz.getAnnotation(RequestMapping.class); if (ann != null && (ann instanceof RequestMapping)) { RequestMapping rm = (RequestMapping) ann; RequestMethod[] reqMethod = rm.method(); if (reqMethod.length > 0) { this.methodName = reqMethod[0].name(); } String[] classValue = rm.value(); if (classValue.length > 0) { this.path = classValue[0]; } } }
/** * Method updates existing Spring bean definitions in a XML application context file. Bean * definition is identified by its type defining class. * * @param project * @param type * @param jaxbElement */ public void updateBeanDefinitions( File configFile, Project project, Class<?> type, Object jaxbElement) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource( new ClassPathResource("transform/update-bean-type.xsl").getInputStream()); xsltSource.setSystemId("update-bean"); List<File> configFiles = new ArrayList<>(); configFiles.add(configFile); configFiles.addAll(getConfigImports(configFile, project)); LSParser parser = XMLUtils.createLSParser(); GetSpringBeansFilter getBeanFilter = new GetSpringBeansFilter(type, null); parser.setFilter(getBeanFilter); for (File file : configFiles) { parser.parseURI(file.toURI().toString()); if (!CollectionUtils.isEmpty(getBeanFilter.getBeanDefinitions())) { xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file))); String beanElement = type.getAnnotation(XmlRootElement.class).name(); String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace(); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter("bean_element", beanElement); transformer.setParameter("bean_namespace", beanNamespace); transformer.setParameter( "bean_content", getXmlContent(jaxbElement) .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1") .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1")); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile( format(result.toString(), project.getSettings().getTabSize()), file); return; } } } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
private JAXBContext newJAXBContext(final Class<?>... pClasses) throws JAXBException { Class<?>[] classList; final Class<?> clazz = getDeclaringClass(); final XmlSeeAlso seeAlso = clazz.getAnnotation(XmlSeeAlso.class); if ((seeAlso != null) && (seeAlso.value().length > 0)) { final Class<?>[] seeAlsoClasses = seeAlso.value(); classList = new Class<?>[seeAlsoClasses.length + pClasses.length]; System.arraycopy(seeAlsoClasses, 0, classList, 0, seeAlsoClasses.length); System.arraycopy(pClasses, 0, classList, seeAlsoClasses.length, pClasses.length); } else { classList = pClasses; } return JAXBContext.newInstance(classList); }
private void processDefaultAnnotation(final Class<?> cmb) { final DefaultImplementation di = cmb.getAnnotation(DefaultImplementation.class); // XXX hack: move to helper method + unify with rest of Tang! if (di != null) { final String diName = di.value() == Void.class ? di.name() : ReflectionUtilities.getFullName(di.value()); final ClassNode<?> cn = (ClassNode<?>) ch.getNode(cmb); final String cnS = cn.getFullName(); if (!usages.contains(diName, cnS)) { usages.put(diName, cnS); if (!knownClasses.contains(cn)) { knownClasses.add(cn); } } } }
private String resolveTypeDiscriminator(final Class<?> persistentType) { final List<String> discrimintators = new ArrayList<String>(); TypeDiscriminator td = persistentType.getAnnotation(TypeDiscriminator.class); if (td != null) { if (td.value().length() == 0) { throw new ViewGenerationException( String.format( "@TypeDiscriminator declared on type level must specify custom discriminator condition", persistentType)); } if (hasTypeDiscriminatorFieldOrMethod(persistentType)) { throw new ViewGenerationException( String.format( "@TypeDiscriminator declared on type level may not be combined with @TypeDiscriminator in fields or on methods", persistentType)); } return td.value(); } eachField( persistentType, new Predicate<Field>() { public boolean apply(Field input) { if (hasAnnotation(input, TypeDiscriminator.class)) { discrimintators.add("doc." + input.getName()); } return false; } }); eachMethod( persistentType, new Predicate<Method>() { public boolean apply(Method input) { if (hasAnnotation(input, TypeDiscriminator.class)) { discrimintators.add("doc." + firstCharToLowerCase(input.getName().substring(3))); } return true; } }); return Joiner.join(discrimintators, " && "); }
/** * Get the protocol version from protocol class. If the protocol class has a ProtocolAnnotation, * then get the protocol name from the annotation; otherwise the class name is the protocol name. */ public static long getProtocolVersion(Class<?> protocol) { if (protocol == null) { throw new IllegalArgumentException("Null protocol"); } long version; ProtocolInfo anno = protocol.getAnnotation(ProtocolInfo.class); if (anno != null) { version = anno.protocolVersion(); if (version != -1) return version; } try { Field versionField = protocol.getField("versionID"); versionField.setAccessible(true); return versionField.getLong(protocol); } catch (NoSuchFieldException ex) { throw new RuntimeException(ex); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } }
/** Get the Plugin annotation for the class */ static Plugin getPluginMetadata(final Class<?> cls) throws PluginException { // try to get plugin provider name final String pluginname; if (!cls.isAnnotationPresent(Plugin.class)) { throw new PluginException("No Plugin annotation was found for the class: " + cls.getName()); } final Plugin annotation = (Plugin) cls.getAnnotation(Plugin.class); pluginname = annotation.name(); if (null == pluginname || "".equals(pluginname)) { throw new PluginException( "Plugin annotation 'name' cannot be empty for the class: " + cls.getName()); } // get service name from annotation final String servicename = annotation.service(); if (null == servicename || "".equals(servicename)) { throw new PluginException( "Plugin annotation 'service' cannot be empty for the class: " + cls.getName()); } return annotation; }
/** Returns an object deserialized from a child node of a given memento. */ public static <T> T getChild(Class<T> clazz, IMemento memento) throws IOException { Root root = clazz.getAnnotation(Root.class); if (root == null) { throw new IllegalArgumentException("Missing @Root annotation on: " + clazz.getName()); } String childName = root.name(); if (StringUtils.isEmpty(childName)) { childName = getClassName(clazz); } IMemento[] children = memento.getChildren(childName); if (children.length == 0) { return null; } if (children.length != 1) { throw new IOException("More than one child named '" + childName + "':" + children.length); } return fromMemento(clazz, children[0]); }
/** * Method removes all Spring bean definitions of given type from the XML application context file. * * @param project * @param type */ public void removeBeanDefinitions(File configFile, Project project, Class<?> type) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource( new ClassPathResource("transform/delete-bean-type.xsl").getInputStream()); xsltSource.setSystemId("delete-bean"); List<File> configFiles = new ArrayList<>(); configFiles.add(configFile); configFiles.addAll(getConfigImports(configFile, project)); for (File file : configFiles) { xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile))); String beanElement = type.getAnnotation(XmlRootElement.class).name(); String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace(); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter("bean_element", beanElement); transformer.setParameter("bean_namespace", beanNamespace); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file); return; } } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
private Object getParam( final Class<?> pClass, final String pName, final ParamType pType, final String pXpath, final HttpMessage pMessage) throws XmlException { Object result = null; switch (pType) { case GET: result = getParamGet(pName, pMessage); break; case POST: result = getParamPost(pName, pMessage); break; case QUERY: result = getParamGet(pName, pMessage); if (result == null) { result = getParamPost(pName, pMessage); } break; case VAR: result = mPathParams.get(pName); break; case XPATH: result = getParamXPath(pClass, pXpath, pMessage.getBody()); break; case BODY: result = getBody(pClass, pMessage); break; case ATTACHMENT: result = getAttachment(pClass, pName, pMessage); break; case PRINCIPAL: { final Principal principal = pMessage.getUserPrincipal(); if (pClass.isAssignableFrom(String.class)) { result = principal.getName(); } else { result = principal; } break; } } // XXX generizice this and share the same approach to unmarshalling in ALL code // TODO support collection/list parameters if ((result != null) && (!pClass.isInstance(result))) { if ((Types.isPrimitive(pClass) || (Types.isPrimitiveWrapper(pClass))) && (result instanceof String)) { try { result = Types.parsePrimitive(pClass, ((String) result)); } catch (NumberFormatException e) { throw new HttpResponseException( HttpServletResponse.SC_BAD_REQUEST, "The argument given is invalid", e); } } else if (Enum.class.isAssignableFrom(pClass)) { @SuppressWarnings({"rawtypes"}) final Class clazz = pClass; @SuppressWarnings("unchecked") final Enum<?> tmpResult = Enum.valueOf(clazz, result.toString()); result = tmpResult; } else if (result instanceof Node) { XmlDeserializer factory = pClass.getAnnotation(XmlDeserializer.class); if (factory != null) { try { result = factory .value() .newInstance() .deserialize(XmlStreaming.newReader(new DOMSource((Node) result))); } catch (IllegalAccessException | InstantiationException e) { throw new XmlException(e); } } else { result = JAXB.unmarshal(new DOMSource((Node) result), pClass); } } else { final String s = result.toString(); // Only wrap when we don't start with < final char[] requestBody = (s.startsWith("<") ? s : "<wrapper>" + s + "</wrapper>").toCharArray(); if (requestBody.length > 0) { result = JAXB.unmarshal(new CharArrayReader(requestBody), pClass); } else { result = null; } } } return result; }