code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public void addGroupElement(final String groupName, final MetadataElement groupElement) { for (MetadataItem item : groupList) { if (item.getName().equals(groupName) && item.getNamespace().equals(getCurrentNamespace())) { item.getElements().add(groupElement); return; } } final MetadataItem newItem = new MetadataItem(groupName); newItem.getElements().add(groupElement); newItem.setNamespace(getCurrentNamespace()); newItem.setSchemaName(getCurrentSchmema()); newItem.setPackageApi(getCurrentPackageApi()); newItem.setPackageImpl(getCurrentPackageImpl()); groupList.add(newItem); }
Adds a new element to the specific group element class. If no group element class is found, then a new group element class. will be created. @param groupName the group class name of @param groupElement the new element to be added.
public void addGroupReference(final String groupName, final MetadataElement groupReference) { groupReference.setRef(getNamespaceValue(groupReference.getRef())); for (MetadataItem item : groupList) { if (item.getName().equals(groupName) && item.getNamespace().equals(getCurrentNamespace())) { item.getReferences().add(groupReference); return; } } final MetadataItem newItem = new MetadataItem(groupName); newItem.getReferences().add(groupReference); newItem.setNamespace(getCurrentNamespace()); newItem.setSchemaName(getCurrentSchmema()); newItem.setPackageApi(getCurrentPackageApi()); newItem.setPackageImpl(getCurrentPackageImpl()); groupList.add(newItem); }
Adds a new reference to the specific group element class. If no group element class is found, then a new group element class. will be created. @param groupName the group class name of @param groupReference the new reference to be added.
public void addClassElement(final String className, final MetadataElement classElement) { classElement.setType(getNamespaceValue(classElement.getType())); if (classElement.getMaxOccurs() != null && !classElement.getMaxOccurs().equals("1")) { classElement.setMaxOccurs("unbounded"); } for (MetadataItem item : classList) { if (item.getName().equals(className) && item.getNamespace().equals(getCurrentNamespace()) && item.getPackageApi().equals(getCurrentPackageApi())) { // check for a element with the same name, if found then set 'maxOccurs = unbounded' for (MetadataElement element : item.getElements()) { if (element.getName().equals(classElement.getName()) && !classElement.getIsAttribute()) { element.setMaxOccurs("unbounded"); return; } } item.getElements().add(classElement); return; } } final MetadataItem newItem = new MetadataItem(className); newItem.getElements().add(classElement); newItem.setNamespace(getCurrentNamespace()); newItem.setSchemaName(getCurrentSchmema()); newItem.setPackageApi(getCurrentPackageApi()); newItem.setPackageImpl(getCurrentPackageImpl()); classList.add(newItem); }
Adds a new element to the specific element class. If no element class is found, then a new element class. will be created. @param className the class name @param classElement the new element to be added.
public void addClassReference(final String className, final MetadataElement classReference) { classReference.setRef(getNamespaceValue(classReference.getRef())); for (MetadataItem item : classList) { if (item.getName().equals(className) && item.getNamespace().equals(getCurrentNamespace()) && item.getPackageApi().equals(getCurrentPackageApi())) { item.getReferences().add(classReference); return; } } final MetadataItem newItem = new MetadataItem(className); newItem.getReferences().add(classReference); newItem.setNamespace(getCurrentNamespace()); newItem.setSchemaName(getCurrentSchmema()); newItem.setPackageApi(getCurrentPackageApi()); newItem.setPackageImpl(getCurrentPackageImpl()); classList.add(newItem); }
Adds a new reference to the specific element class. If no element class is found, then a new element class. will be created. @param className the class name @param classReference the new reference to be added.
public void preResolveDataTypes() { for (MetadataItem metadataClass : classList) { preResolveDataTypeImpl(metadataClass); } for (MetadataItem metadataClass : groupList) { preResolveDataTypeImpl(metadataClass); } }
Replaces all data type occurrences found in the element types for all classes with the simple data type. This simplifies later the XSLT ddJavaAll step.
private String getNamespaceValue(final String value) { if (value == null || value.contains(":") || value.equals("text")) { return value; } else { return getCurrentNamespace() + ":" + value; } }
----------------------------------------------------------------------------------------------------------||
public void write(final Metadata metadata, final String pathToMetadata, final List<? extends MetadataJavaDoc> javadocTags) { try { final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements final Document doc = docBuilder.newDocument(); final Element rootElement = doc.createElement("metadata"); doc.appendChild(rootElement); final Element javadocsElement = doc.createElement("javadocs"); rootElement.appendChild(javadocsElement); final Set<String> commonPathSet = new HashSet<String>(); final List<File> fileList = new ArrayList<File>(); for (final MetadataDescriptor descr : metadata.getMetadataDescriptorList()) { if (descr.getCommon() != null) { final String pathTo = descr.getCommon().getPathToCommonApi(); final String commonApi = descr.getCommon().getCommonApi().replace('.', '/'); commonPathSet.add(pathTo + "/" + commonApi); } } for (final String pathCommonApi : commonPathSet) { listFiles(fileList, pathCommonApi); } final JavaProjectBuilder builder = new JavaProjectBuilder(); final Element generatedElement = doc.createElement("generatedClasses"); rootElement.appendChild(generatedElement); for (final File file : fileList) { final Element generatedClassElement = doc.createElement("generatedClass"); generatedClassElement.setAttribute("name", file.getName()); generatedElement.appendChild(generatedClassElement); final JavaSource src = builder.addSource(file); final JavaClass class1 = src.getClasses().get(0); generatedClassElement.setAttribute("commonPackage", class1.getPackageName()); final List<JavaAnnotation> annotationList = class1.getAnnotations(); for (JavaAnnotation annotation : annotationList) { final AnnotationValue value = annotation.getProperty("common"); final List<String> commonExtendsList = (List<String>)value.getParameterValue(); for (String commonClass : commonExtendsList) { final Element extendsElement = doc.createElement("commonExtends"); extendsElement.setAttribute("extends", commonClass.replace('"', ' ').trim()); generatedClassElement.appendChild(extendsElement); } } } final Element commonPackagesElement = doc.createElement("commonPackages"); rootElement.appendChild(commonPackagesElement); for (final MetadataDescriptor descr : metadata.getMetadataDescriptorList()) { if (descr.isGenerateCommonClasses() != null && !descr.isGenerateCommonClasses()) { final Element generateElement = doc.createElement("package"); generateElement.setAttribute("packageApi", descr.getPackageApi()); generateElement.setAttribute("generate", Boolean.toString(descr.isGenerateCommonClasses())); commonPackagesElement.appendChild(generateElement); } } final List<String> commonNewFiles = findCommonClasses(metadata); final Element commonNewFilesElement = doc.createElement("commonClasses"); rootElement.appendChild(commonNewFilesElement); for (final String type : commonNewFiles) { final Element commonType = doc.createElement("typeName"); commonType.setAttribute("name", type); commonNewFilesElement.appendChild(commonType); } if (javadocTags != null) { for (final MetadataJavaDoc javaDoc : javadocTags) { final Attr javadocName = doc.createAttribute("tag"); javadocName.setValue(javaDoc.getTag()); final Attr javadocValue = doc.createAttribute("value"); javadocValue.setValue(javaDoc.getValue()); final Element tagElement = doc.createElement("tag"); tagElement.setAttributeNode(javadocName); tagElement.setAttributeNode(javadocValue); javadocsElement.appendChild(tagElement); } } // add packages final Element packages = doc.createElement("packages"); rootElement.appendChild(packages); for (MetadataDescriptor descriptor : metadata.getMetadataDescriptorList()) { final Element packageApi = doc.createElement("api"); final Attr packageApiName = doc.createAttribute("name"); packageApiName.setValue(descriptor.getPackageApi()); packageApi.setAttributeNode(packageApiName); final Attr schemaNameApi = doc.createAttribute("schema"); schemaNameApi.setValue(descriptor.getSchemaName()); packageApi.setAttributeNode(schemaNameApi); final Attr generateClassApi = doc.createAttribute("generateClass"); generateClassApi.setValue(Boolean.toString(descriptor.isGenerateClasses())); packageApi.setAttributeNode(generateClassApi); if (descriptor.getPathToPackageInfoApi() != null) { final Attr pathToPackageInfoApi = doc.createAttribute("packageInfo"); pathToPackageInfoApi.setValue(descriptor.getPathToPackageInfoApi()); packageApi.setAttributeNode(pathToPackageInfoApi); } if (descriptor.getCommonImports() != null) { final Element commonImport = doc.createElement("commonImport"); for (String importDescl : descriptor.getCommonImports()) { final Element importElement = doc.createElement("import"); importElement.setAttribute("package", importDescl); commonImport.appendChild(importElement); } packageApi.appendChild(commonImport); } packages.appendChild(packageApi); } for (MetadataDescriptor descriptor : metadata.getMetadataDescriptorList()) { final Element packageImpl = doc.createElement("impl"); final Attr packageImplName = doc.createAttribute("name"); packageImplName.setValue(descriptor.getPackageImpl()); packageImpl.setAttributeNode(packageImplName); final Attr schemaNameImpl = doc.createAttribute("schema"); schemaNameImpl.setValue(descriptor.getSchemaName()); packageImpl.setAttributeNode(schemaNameImpl); final Attr generateClassImpl = doc.createAttribute("generateClass"); generateClassImpl.setValue(Boolean.toString(descriptor.isGenerateClasses())); packageImpl.setAttributeNode(generateClassImpl); if (descriptor.getPathToPackageInfoImpl() != null) { final Attr pathToPackageInfoImpl = doc.createAttribute("packageInfo"); pathToPackageInfoImpl.setValue(descriptor.getPathToPackageInfoImpl()); packageImpl.setAttributeNode(pathToPackageInfoImpl); } packages.appendChild(packageImpl); } // add datatypes final Element datatypes = doc.createElement("datatypes"); rootElement.appendChild(datatypes); for (MetadataItem metadataType : metadata.getDataTypeList()) { final Element datatype = doc.createElement("datatype"); final Attr attrName = doc.createAttribute("name"); attrName.setValue(metadataType.getName()); datatype.setAttributeNode(attrName); final Attr attrMappedTo = doc.createAttribute("mappedTo"); attrMappedTo.setValue(metadataType.getMappedTo()); datatype.setAttributeNode(attrMappedTo); final Attr attrNamespace = doc.createAttribute("namespace"); attrNamespace.setValue(metadataType.getNamespace()); datatype.setAttributeNode(attrNamespace); final Attr attrSchemaName = doc.createAttribute("schemaName"); attrSchemaName.setValue(metadataType.getSchemaName()); datatype.setAttributeNode(attrSchemaName); datatypes.appendChild(datatype); } final Element enums = doc.createElement("enums"); rootElement.appendChild(enums); for (MetadataEnum metadataEnum : metadata.getEnumList()) { final Element enumElement = doc.createElement("enum"); final Attr attrName = doc.createAttribute("name"); attrName.setValue(metadataEnum.getName()); enumElement.setAttributeNode(attrName); final Attr attrNamespace = doc.createAttribute("namespace"); attrNamespace.setValue(metadataEnum.getNamespace()); enumElement.setAttributeNode(attrNamespace); final Attr attrSchemaName = doc.createAttribute("schemaName"); attrSchemaName.setValue(metadataEnum.getSchemaName()); enumElement.setAttributeNode(attrSchemaName); final Attr attrPackage = doc.createAttribute("package"); attrPackage.setValue(metadataEnum.getPackageApi()); enumElement.setAttributeNode(attrPackage); final Attr attrDocumentation = doc.createAttribute("documentation"); attrDocumentation.setValue(""); enumElement.setAttributeNode(attrDocumentation); for (String value : metadataEnum.getValueList()) { final Element valueElement = doc.createElement("value"); valueElement.setTextContent(value); enumElement.appendChild(valueElement); } enums.appendChild(enumElement); } final Element groups = doc.createElement("groups"); rootElement.appendChild(groups); for (MetadataItem metadataClass : metadata.getGroupList()) { final Element classElement = doc.createElement("class"); final Attr attrName = doc.createAttribute("name"); attrName.setValue(metadataClass.getName()); classElement.setAttributeNode(attrName); final Attr attrNamespace = doc.createAttribute("namespace"); attrNamespace.setValue(metadataClass.getNamespace()); classElement.setAttributeNode(attrNamespace); final Attr attrSchemaName = doc.createAttribute("schemaName"); attrSchemaName.setValue(metadataClass.getSchemaName()); classElement.setAttributeNode(attrSchemaName); final Attr attrPackageApi = doc.createAttribute("package"); attrPackageApi.setValue(metadataClass.getPackageApi()); classElement.setAttributeNode(attrPackageApi); final Attr attrDocumentation = doc.createAttribute("documentation"); attrDocumentation.setValue(""); classElement.setAttributeNode(attrDocumentation); for (MetadataElement element : metadataClass.getElements()) { final Element childElement = doc.createElement("element"); final Attr elName = doc.createAttribute("name"); elName.setValue(element.getName()); childElement.setAttributeNode(elName); final Attr elType = doc.createAttribute("type"); elType.setValue(element.getType()); childElement.setAttributeNode(elType); if (element.getIsAttribute() == true) { final Attr elAttribute = doc.createAttribute("attribute"); elAttribute.setValue(Boolean.toString(element.getIsAttribute())); childElement.setAttributeNode(elAttribute); } if (element.getDefaultValue() != null) { final Attr elAttribute = doc.createAttribute("default"); elAttribute.setValue(element.getDefaultValue()); childElement.setAttributeNode(elAttribute); } if (element.getFixedValue() != null) { final Attr elAttribute = doc.createAttribute("fixed"); elAttribute.setValue(element.getFixedValue()); childElement.setAttributeNode(elAttribute); } if (element.getUse() != null) { final Attr elAttribute = doc.createAttribute("use"); elAttribute.setValue(element.getUse()); childElement.setAttributeNode(elAttribute); } if (element.getMaxOccurs() != null) { final Attr elMaxOccurs = doc.createAttribute("maxOccurs"); elMaxOccurs.setValue(element.getMaxOccurs()); childElement.setAttributeNode(elMaxOccurs); } classElement.appendChild(childElement); } for (MetadataElement element : metadataClass.getReferences()) { final Element childElement = doc.createElement("include"); final Attr elName = doc.createAttribute("name"); elName.setValue(element.getRef()); childElement.setAttributeNode(elName); classElement.appendChild(childElement); } groups.appendChild(classElement); } final Element classes = doc.createElement("classes"); rootElement.appendChild(classes); for (MetadataItem metadataClass : metadata.getClassList()) { final Element classElement = doc.createElement("class"); final Attr attrName = doc.createAttribute("name"); attrName.setValue(metadataClass.getName()); classElement.setAttributeNode(attrName); final Attr attrNamespace = doc.createAttribute("namespace"); attrNamespace.setValue(metadataClass.getNamespace()); classElement.setAttributeNode(attrNamespace); final Attr attrSchemaName = doc.createAttribute("schemaName"); attrSchemaName.setValue(metadataClass.getSchemaName()); classElement.setAttributeNode(attrSchemaName); final Attr attrPackageApi = doc.createAttribute("packageApi"); attrPackageApi.setValue(metadataClass.getPackageApi()); classElement.setAttributeNode(attrPackageApi); final Attr attrPackageImpl = doc.createAttribute("packageImpl"); attrPackageImpl.setValue(metadataClass.getPackageImpl()); classElement.setAttributeNode(attrPackageImpl); final Attr attrDocumentation = doc.createAttribute("documentation"); attrDocumentation.setValue(""); classElement.setAttributeNode(attrDocumentation); for (MetadataElement element : metadataClass.getElements()) { final Element childElement = doc.createElement("element"); final Attr elName = doc.createAttribute("name"); elName.setValue(element.getName()); childElement.setAttributeNode(elName); final Attr elType = doc.createAttribute("type"); elType.setValue(element.getType()); childElement.setAttributeNode(elType); if (element.getMaxOccurs() != null) { final Attr elMaxOccurs = doc.createAttribute("maxOccurs"); elMaxOccurs.setValue(element.getMaxOccurs()); childElement.setAttributeNode(elMaxOccurs); } if (element.getIsAttribute() == true) { final Attr elAttribute = doc.createAttribute("attribute"); elAttribute.setValue(Boolean.toString(element.getIsAttribute())); childElement.setAttributeNode(elAttribute); } if (element.getDefaultValue() != null) { final Attr elAttribute = doc.createAttribute("default"); elAttribute.setValue(element.getDefaultValue()); childElement.setAttributeNode(elAttribute); } if (element.getFixedValue() != null) { final Attr elAttribute = doc.createAttribute("fixed"); elAttribute.setValue(element.getFixedValue()); childElement.setAttributeNode(elAttribute); } if (element.getUse() != null) { final Attr elAttribute = doc.createAttribute("use"); elAttribute.setValue(element.getUse()); childElement.setAttributeNode(elAttribute); } classElement.appendChild(childElement); } for (MetadataElement element : metadataClass.getReferences()) { final Element childElement = doc.createElement("include"); final Attr elName = doc.createAttribute("name"); elName.setValue(element.getRef()); childElement.setAttributeNode(elName); if (element.getMaxOccurs() != null) { final Attr elMaxOccurs = doc.createAttribute("maxOccurs"); elMaxOccurs.setValue(element.getMaxOccurs()); childElement.setAttributeNode(elMaxOccurs); } classElement.appendChild(childElement); } classes.appendChild(classElement); } final Element descriptors = doc.createElement("descriptors"); rootElement.appendChild(descriptors); for (MetadataDescriptor descriptor : metadata.getMetadataDescriptorList()) { if (descriptor.getRootElementName() != null && descriptor.getRootElementType() != null) { final Element descriptorElement = doc.createElement("descriptor"); descriptors.appendChild(descriptorElement); final Attr attrName = doc.createAttribute("name"); attrName.setValue(descriptor.getName()); descriptorElement.setAttributeNode(attrName); final Attr attrSchemaName = doc.createAttribute("schemaName"); attrSchemaName.setValue(descriptor.getSchemaName()); descriptorElement.setAttributeNode(attrSchemaName); final Attr attrPackageApi = doc.createAttribute("packageApi"); attrPackageApi.setValue(descriptor.getPackageApi()); descriptorElement.setAttributeNode(attrPackageApi); final Attr attrPackageImpl = doc.createAttribute("packageImpl"); attrPackageImpl.setValue(descriptor.getPackageImpl()); descriptorElement.setAttributeNode(attrPackageImpl); final Element element = doc.createElement("element"); descriptorElement.appendChild(element); final Attr attElementName = doc.createAttribute("name"); attElementName.setValue(descriptor.getRootElementName()); element.setAttributeNode(attElementName); final Attr attElementType = doc.createAttribute("type"); attElementType.setValue(descriptor.getRootElementType()); element.setAttributeNode(attElementType); final Enumeration<?> em = descriptor.getNamespaces().keys(); while (em.hasMoreElements()) { final String key = (String) em.nextElement(); final String value = (String) descriptor.getNamespaces().get(key); final Attr namespaceAttrName = doc.createAttribute("name"); namespaceAttrName.setValue(key); final Attr namespaceAttrValue = doc.createAttribute("value"); namespaceAttrValue.setValue(value); final Element namespaceElement = doc.createElement("namespace"); namespaceElement.setAttributeNode(namespaceAttrName); namespaceElement.setAttributeNode(namespaceAttrValue); descriptorElement.appendChild(namespaceElement); } if (descriptor.getCommonRef() != null) { final Element commonRefElement = doc.createElement("commonRef"); commonRefElement.setAttribute("refid", descriptor.getCommonRef().getRefid()); descriptorElement.appendChild(commonRefElement); } if (descriptor.getCommon() != null) { final Element commonElement = doc.createElement("common"); commonElement.setAttribute("pathToCommonApi", descriptor.getCommon().getPathToCommonApi()); commonElement.setAttribute("commonDescriptorName", descriptor.getCommon().getCommonDescriptorName()); commonElement.setAttribute("commonApi", descriptor.getCommon().getCommonApi()); commonElement.setAttribute("commonNamespace", descriptor.getCommon().getCommonNamespace()); commonElement.setAttribute("id", descriptor.getCommon().getId()); commonElement.setAttribute("generate", descriptor.getCommon().getGenerate().toString()); if (descriptor.getCommon().getCommonImports() != null) { final Element commonImport = doc.createElement("commonImport"); for (String importDescl : descriptor.getCommon().getCommonImports()) { final Element importElement = doc.createElement("import"); importElement.setAttribute("package", importDescl); commonImport.appendChild(importElement); } commonElement.appendChild(commonImport); } if (descriptor.getCommon().getTypes() != null) { final Element commonTypes = doc.createElement("commonTypes"); for (String type : descriptor.getCommon().getTypes()) { final Element typeElement = doc.createElement("type"); final String[] items = type.split(":", -1); if (items.length == 2) { typeElement.setAttribute("namespace", items[0]); typeElement.setAttribute("name", items[1]); commonTypes.appendChild(typeElement); } } commonElement.appendChild(commonTypes); } if (descriptor.getCommon().getExcludes() != null) { final Element excludeTypes = doc.createElement("commonExcludes"); for (String exclude : descriptor.getCommon().getExcludes()) { final Element excludeElement = doc.createElement("exclude"); final String[] items = exclude.split(":", -1); if (items.length == 2) { excludeElement.setAttribute("namespace", items[0]); excludeElement.setAttribute("name", items[1]); excludeTypes.appendChild(excludeElement); } } commonElement.appendChild(excludeTypes); } descriptorElement.appendChild(commonElement); } } } final TransformerFactory transformerFactory = TransformerFactory.newInstance(); final Transformer transformer = transformerFactory.newTransformer(); final DOMSource source = new DOMSource(doc); final File file = new File(pathToMetadata); final StreamResult result = new StreamResult(file); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); if (log.isLoggable(Level.FINE)) { log.fine("Saved: " + file.getAbsolutePath()); } } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Writes an XML file based on the given meta-data information at the specified location. TODO: a lot of recurring code is here, needs to be refactored. @param metadata @param pathToMetadata
static <T extends Descriptor> T createFromUserView(final Class<T> userViewClass, String descriptorName) throws IllegalArgumentException { // Get the construction information final DescriptorConstructionInfo info = getDescriptorConstructionInfoForUserView(userViewClass); @SuppressWarnings("unchecked") final Class<? extends Descriptor> implClass = (Class<? extends Descriptor>) info.implClass; String name = info.defaultName; if (descriptorName != null) { name = descriptorName; } // Make model class final Descriptor descriptor = createFromImplModelType(implClass, name); // Return return userViewClass.cast(descriptor); }
Creates a new {@link Descriptor} instance of the specified user view type. Will consult a configuration file visible to the {@link Thread} Context {@link ClassLoader} named "META-INF/services/$fullyQualfiedClassName" which should contain a key=value format with the keys {@link DescriptorInstantiator#KEY_IMPL_CLASS_NAME} and {@link DescriptorInstantiator#KEY_MODEL_CLASS_NAME}. The implementation class name must have a constructor accepting an instance of the model class, and the model class must have a no-arg constructor. @param <T> @param userViewClass @param descriptorName The name of the descriptor. If argument is null, the default name will be used. @return @throws IllegalArgumentException If the user view class was not specified
static Descriptor createFromImplModelType(final Class<? extends Descriptor> implClass, String descriptorName) throws IllegalArgumentException { // Precondition checks if (implClass == null) { throw new IllegalArgumentException("implClass must be specified"); } if (descriptorName == null || descriptorName.length() == 0) { throw new IllegalArgumentException("descriptorName must be specified"); } // Get the constructor to use in making the new instance final Constructor<? extends Descriptor> ctor; try { ctor = implClass.getConstructor(String.class); } catch (final NoSuchMethodException nsme) { throw new RuntimeException(implClass + " must contain a constructor with a single String argument"); } // Create a new descriptor instance using the backing model final Descriptor descriptor; try { descriptor = ctor.newInstance(descriptorName); } // Handle all construction errors equally catch (final Exception e) { throw new RuntimeException("Could not create new descriptor instance", e); } // Return return descriptor; }
Creates a {@link Descriptor} instance from the specified implementation class name, also using the specified name @param implClass @param descriptorName @return @throws IllegalArgumentException If either argument is not specified
@SuppressWarnings("unchecked") static <T extends Descriptor> DescriptorImporter<T> createImporterFromUserView(final Class<T> userViewClass, String descriptorName) throws IllegalArgumentException { // Get the construction information final DescriptorConstructionInfo info = getDescriptorConstructionInfoForUserView(userViewClass); // Create an importer final Class<?> implClass = info.implClass; if (!userViewClass.isAssignableFrom(implClass)) { throw new RuntimeException("Configured implementation class for " + userViewClass.getName() + " is not assignable: " + implClass.getName()); } final Class<T> implClassCasted = (Class<T>) implClass; String name = info.defaultName; if (descriptorName != null) { name = descriptorName; } final DescriptorImporter<T> importer; try { importer = (DescriptorImporter<T>) info.importerClass.getConstructor(Class.class, String.class) .newInstance(implClassCasted, name); } catch (Exception e) { throw new RuntimeException("Configured importer for " + userViewClass.getName() + " of type: " + info.importerClass + " could not be created", e); } // Return return importer; }
Creates a new {@link DescriptorImporter} instance of the specified user view type. Will consult a configuration file visible to the {@link Thread} Context {@link ClassLoader} named "META-INF/services/$fullyQualfiedClassName" which should contain a key=value format with the keys {@link DescriptorInstantiator#KEY_IMPL_CLASS_NAME} and {@link DescriptorInstantiator#KEY_MODEL_CLASS_NAME}. The implementation class name must have a constructor accepting an instance of the model class, and the model class must have a no-arg constructor. @param <T> @param userViewClass @param descriptorName The name of the descriptor. If argument is null, the default name will be used. @return @throws IllegalArgumentException If the user view class was not specified
private static DescriptorConstructionInfo getDescriptorConstructionInfoForUserView(final Class<?> userViewClass) throws IllegalArgumentException { // Precondition checks if (userViewClass == null) { throw new IllegalArgumentException("User view class must be specified"); } // Get the configuration from which we'll create new instances final String className = userViewClass.getName(); final String resourceName = MAPPING_LOCATION + className; final ClassLoader tccl = AccessController.doPrivileged(GetTcclAction.INSTANCE); final InputStream resourceStream = tccl.getResourceAsStream(resourceName); if (resourceStream == null) { throw new IllegalArgumentException("No resource " + resourceName + " was found configured for user view class " + userViewClass.getName()); } // Load final Properties props = new Properties(); try { props.load(resourceStream); } catch (final IOException e) { throw new RuntimeException("I/O Problem in reading the properties for " + userViewClass.getName(), e); } final String implClassName = props.getProperty(KEY_IMPL_CLASS_NAME); if (implClassName == null || implClassName.length() == 0) { throw new IllegalStateException("Resource " + resourceName + " for " + userViewClass + " does not contain key " + KEY_IMPL_CLASS_NAME); } final String importerClassName = props.getProperty(KEY_IMPORTER_CLASS_NAME); if (importerClassName == null || importerClassName.length() == 0) { throw new IllegalStateException("Resource " + resourceName + " for " + userViewClass + " does not contain key " + KEY_IMPORTER_CLASS_NAME); } final String defaultName = props.getProperty(KEY_DEFAULT_NAME); if (defaultName == null) { throw new IllegalStateException("Resource " + resourceName + " for " + userViewClass + " does not contain key " + KEY_DEFAULT_NAME); } // Get the construction information final DescriptorConstructionInfo info = new DescriptorConstructionInfo(implClassName, importerClassName, defaultName); // Return return info; }
Obtains the {@link DescriptorConstructionInfo} for the giving end user view, using a configuration file loaded from the TCCL of name "META-INF/services.$fullyQualifiedClassName" having properties as described by {@link DescriptorInstantiator#createFromUserView(Class)}. @param userViewClass @return The construction information needed to create new instances conforming to the user view @throws IllegalArgumentException If the user view was not specified
public static <T> T newInstance(final Class<T> implClass, final Class<?>[] argumentTypes, final Object[] arguments) { if (implClass == null) { throw new IllegalArgumentException("ImplClass must be specified"); } if (argumentTypes == null) { throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments"); } if (arguments == null) { throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments"); } final T obj; try { final Constructor<T> constructor = getConstructor(implClass, argumentTypes); if (!constructor.isAccessible()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { constructor.setAccessible(true); return null; } }); } obj = constructor.newInstance(arguments); } catch (Exception e) { throw new RuntimeException("Could not create new instance of " + implClass, e); } return obj; }
Create a new instance by finding a constructor that matches the argumentTypes signature using the arguments for instantiation. @param implClass Full classname of class to create @param argumentTypes The constructor argument types @param arguments The constructor arguments @return a new instance @throws IllegalArgumentException if className, argumentTypes, or arguments are null @throws RuntimeException if any exceptions during creation @author <a href="mailto:[email protected]">Aslak Knutsen</a> @author <a href="mailto:[email protected]">ALR</a>
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception { HttpServletRequest request = context.getRequest(); Authentication auth = null; // Make sure not to run the logic if there's already an authentication if (SecurityUtils.getAuthentication(request) == null) { String ticket = SecurityUtils.getTicketCookie(request); if (ticket != null) { auth = authenticationManager.getAuthentication(ticket, false); if (auth != null) { // Check to see if profile was updated by another app Long profileLastModified = SecurityUtils.getProfileLastModifiedCookie(request); long currentProfileLastModified = auth.getProfile().getLastModified().getTime(); if (profileLastModified == null || currentProfileLastModified != profileLastModified) { if (profileLastModified == null) { logger.debug("Not profile last modified timestamp specified in request"); } else { logger.debug("The last modified timestamp in request doesn't match the current one"); } auth = authenticationManager.getAuthentication(ticket, true); } } } } if (auth != null) { SecurityUtils.setAuthentication(request, auth); } processorChain.processRequest(context); }
Sets the authentication for the current request. If the {@code profileLastModified} timestamp is in the request, and it doesn't match the one from the current profile, a reload of the profile is forced. @param context the context which holds the current request and other security info pertinent to the request @param processorChain the processor chain, used to call the next processor
public final boolean isItemInsideView(int position) { float x = (getXForItemAtPosition(position) + offsetX); float y = (getYForItemAtPosition(position) + offsetY); float itemSize = getNoxItemSize(); int viewWidth = shapeConfig.getViewWidth(); boolean matchesHorizontally = x + itemSize >= 0 && x <= viewWidth; float viewHeight = shapeConfig.getViewHeight(); boolean matchesVertically = y + itemSize >= 0 && y <= viewHeight; return matchesHorizontally && matchesVertically; }
Returns true if the view should be rendered inside the view window taking into account the offset applied by the scroll effect.
public int getNoxItemHit(float x, float y) { int noxItemPosition = -1; for (int i = 0; i < getNumberOfElements(); i++) { float noxItemX = getXForItemAtPosition(i) + offsetX; float noxItemY = getYForItemAtPosition(i) + offsetY; float itemSize = getNoxItemSize(); boolean matchesHorizontally = x >= noxItemX && x <= noxItemX + itemSize; boolean matchesVertically = y >= noxItemY && y <= noxItemY + itemSize; if (matchesHorizontally && matchesVertically) { noxItemPosition = i; break; } } return noxItemPosition; }
Returns the position of the NoxView if any of the previously configured NoxItem instances is hit. If there is no any NoxItem hit this method returns -1.
protected final void setNoxItemXPosition(int position, float x) { noxItemsXPositions[position] = x; minX = (int) Math.min(x, minX); maxX = (int) Math.max(x, maxX); }
Configures the X position for a given NoxItem indicated with the item position. This method uses two counters to calculate the Shape minimum and maximum X position used to configure the Shape scroll.
protected final void setNoxItemYPosition(int position, float y) { noxItemsYPositions[position] = y; minY = (int) Math.min(y, minY); maxY = (int) Math.max(y, maxY); }
Configures the Y position for a given NoxItem indicated with the item position. This method uses two counters to calculate the Shape minimum and maximum Y position used to configure the Shape scroll.
@Override public T fromStream(final InputStream in, final boolean close) throws IllegalArgumentException, DescriptorImportException { // Precondition check if (in == null) { throw new IllegalArgumentException("InputStream must be specified"); } final Node rootNode = this.getNodeImporter().importAsNode(in, close); // Create the end-user view final Constructor<T> constructor; try { constructor = endUserViewImplType.getConstructor(String.class, Node.class); } catch (final NoSuchMethodException e) { throw new DescriptorImportException("Descriptor impl " + endUserViewImplType.getName() + " does not have a constructor accepting " + String.class.getName() + " and " + Node.class.getName(), e); } final T descriptor; try { descriptor = constructor.newInstance(descriptorName, rootNode); } catch (final Exception e) { throw new DescriptorImportException("Could not create new instance using " + constructor + " with arg: " + rootNode); } // Return return descriptor; }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#fromStream(java.io.InputStream)
public static Optional<Class<?>> getClassWithAnnotation(final Class<?> source, final Class<? extends Annotation> annotationClass) { Class<?> nextSource = source; while (nextSource != Object.class) { if (nextSource.isAnnotationPresent(annotationClass)) { return Optional.of(nextSource); } else { nextSource = nextSource.getSuperclass(); } } return Optional.empty(); }
Class that returns if a class or any subclass is annotated with given annotation. @param source class. @param annotationClass to find. @return Class containing the annotation.
private String removeFinalSlash(String path) { if (path != null && !path.isEmpty() && path.endsWith("/")) { return path.substring(0, path.length() -1); } return path; }
Due a bug in Pact we need to remove final slash character on path
private String getDataType(String[] items) { for (String item : items) { if (XsdDatatypeEnum.ENTITIES.isDataType(item)) { return item; } } return items[0]; }
Returns first data type which is a standard xsd data type. If no such data type found, then the first one will be returned. @param items @return
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception { HttpServletRequest request = context.getRequest(); if (isLoginRequest(request)) { logger.debug("Processing login request"); String[] tenants = tenantsResolver.getTenants(); if (ArrayUtils.isEmpty(tenants)) { throw new IllegalArgumentException("No tenants resolved for authentication"); } String username = getUsername(request); String password = getPassword(request); if (username == null) { username = ""; } if (password == null) { password = ""; } try { logger.debug("Attempting authentication of user '{}' with tenants {}", username, tenants); Authentication auth = authenticationManager.authenticateUser(tenants, username, password); if (getRememberMe(request)) { rememberMeManager.enableRememberMe(auth, context); } else { rememberMeManager.disableRememberMe(context); } onLoginSuccess(context, auth); } catch (AuthenticationException e) { onLoginFailure(context, e); } } else { processorChain.processRequest(context); } }
Checks if the request URL matches the {@code loginUrl} and the HTTP method matches the {@code loginMethod}. If it does, it proceeds to login the user using the username/password specified in the parameters. @param context the context which holds the current request and response @param processorChain the processor chain, used to call the next processor
public Pattern attribute(final String name, final Object value) { return attribute(name, String.valueOf(value)); }
Add or override a named attribute.<br/> <br/> value will be converted to String using String.valueOf(value); @param name The attribute name @param value The given value @return This Node @see #attribute(String, String)
public Pattern attribute(final String name, final String value) { attributes.put(name, value); return this; }
Add or override a named attribute.<br/> @param name The attribute name @param value The given value @return This Node
public boolean matches(final Node node) throws IllegalArgumentException { // Precondition checks if (node == null) { throw new IllegalArgumentException("node must be specified"); } if (!name.equals(node.getName())) { return false; } if ((text != null && node.getText() == null) || (text != null && !text.trim().equals(node.getText().trim()))) { return false; } if (attributes != null) { for (final Map.Entry<String, String> attribute : attributes.entrySet()) { final String attrValue = attribute.getValue(); final String attrName = attribute.getKey(); if (!attrValue.equals(node.getAttribute(attrName))) { return false; } } } return true; }
Returns true if and only if the specified {@link Node} values match the data contained in this {@link Pattern} value object @param node @return @throws IllegalArgumentException If the {@link Node} is not specified
public static String resolveHomeDirectory(String path) { if (path.startsWith("~")) { return path.replace("~", System.getProperty("user.home")); } return path; }
Method that changes any string starting with ~ to user.home property. @param path to change. @return String with ~changed.
public void handle(RequestContext context, AuthenticationException e) throws SecurityProviderException, IOException { saveRequest(context); String loginFormUrl = getLoginFormUrl(); if (StringUtils.isNotEmpty(loginFormUrl)) { RedirectUtils.redirect(context.getRequest(), context.getResponse(), loginFormUrl); } else { sendError(e, context); } }
Saves the current request in the request cache and then redirects to the login form page. @param context the request security context @param e the exception with the reason for requiring authentication
public static void copyPackageInfo(final MetadataParserPath path, final Metadata metadata, final boolean verbose) throws IOException { for (final MetadataDescriptor descriptor : metadata.getMetadataDescriptorList()) { if (descriptor.getPathToPackageInfoApi() != null) { final File sourceFile = new File(descriptor.getPathToPackageInfoApi()); final String destDirectory = path.pathToApi + File.separatorChar + descriptor.getPackageApi().replace('.', '/'); deleteExistingPackageInfo(destDirectory, verbose); copy(sourceFile, destDirectory, verbose); } if (descriptor.getPathToPackageInfoImpl() != null) { final File sourceFile = new File(descriptor.getPathToPackageInfoImpl()); final String destDirectory = path.pathToImpl + File.separatorChar + descriptor.getPackageImpl().replace('.', '/'); deleteExistingPackageInfo(destDirectory, verbose); copy(sourceFile, destDirectory, verbose); } } }
Copies the optional packageInfo files into the packages. @param path @param metadata @throws IOException
public static void copy(final File sourceFile, final String destDirectory, final boolean verbose) throws IOException { String destFileName = PACKAGE_HTML_NAME; if (sourceFile.getName().endsWith("java")) { destFileName = PACKAGE_JAVA_NAME; } final File destFile = new File(destDirectory + File.separatorChar + destFileName); if (verbose) { log.info(String.format("Copying packageInfo from: %s to: %s", sourceFile.getAbsolutePath(), destFile.getAbsolutePath())); } FileUtils.copyFile(sourceFile, destFile, true); }
Copies the given sourceFile into the specified directory. The source file post fix defines which variant of the package info file is created. <p> If the source file ends with <code>.java</code>, then the destination file name is <code>package-info.java</code> otherwise the file name is <code>package.html</code>. @param sourceFile @param destDirectory @param verbose @throws IOException
public static void deleteExistingPackageInfo(final String destDirectory, final boolean verbose) { final File htmlFile = new File(destDirectory + File.separatorChar + PACKAGE_HTML_NAME); final File javaFile = new File(destDirectory + File.separatorChar + PACKAGE_JAVA_NAME); final Boolean isHtmlDeleted = FileUtils.deleteQuietly(htmlFile); final Boolean isJavaDeleted = FileUtils.deleteQuietly(javaFile); if (verbose) { log.info(String.format("File %s deleted: %s", htmlFile.getAbsolutePath(), isHtmlDeleted.toString())); log.info(String.format("File %s deleted: %s", javaFile.getAbsolutePath(), isJavaDeleted.toString())); } }
Deletes package.html or package-info.java from the given directory. @param destDirectory @param verbose
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception { try { processorChain.processRequest(context); } catch (IOException e) { throw e; } catch (Exception e) { SecurityProviderException se = findSecurityException(e); if (se != null) { handleSecurityProviderException(se, context); } else { throw e; } } }
Catches any exception thrown by the processor chain. If the exception is an instance of a {@link SecurityProviderException}, the exception is handled to see if authentication is required ({@link AuthenticationRequiredException}), or if access to the resource is denied ({@link AccessDeniedException}). @param context the context which holds the current request and response @param processorChain the processor chain, used to call the next processor @throws Exception
protected void handleAccessDeniedException(RequestContext context, AccessDeniedException e) throws SecurityProviderException, IOException { Authentication auth = SecurityUtils.getAuthentication(context.getRequest()); // If user is anonymous, authentication is required if (auth == null) { try { // Throw ex just to initialize stack trace throw new AuthenticationRequiredException("Authentication required to access the resource", e); } catch (AuthenticationRequiredException ae) { logger.debug("Authentication is required", ae); authenticationRequiredHandler.handle(context, ae); } } else { logger.debug("Access denied to user '" + auth.getProfile().getUsername() + "'", e); accessDeniedHandler.handle(context, e); } }
Handles the specified {@link AccessDeniedException}, by calling the {@link AccessDeniedHandler}.
@Override public void execute() throws BuildException { if (path == null) throw new BuildException("Path isn't defined"); if (descriptors == null) throw new BuildException("Descriptors isn't defined"); if (descriptors.getData() == null) throw new BuildException("No descriptor defined"); ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { if (classpathRef != null || classpath != null) { org.apache.tools.ant.types.Path p = new org.apache.tools.ant.types.Path(getProject()); if (classpathRef != null) { org.apache.tools.ant.types.Reference reference = new org.apache.tools.ant.types.Reference( getProject(), classpathRef); p.setRefid(reference); } if (classpath != null) { p.append(classpath); } ClassLoader cl = getProject().createClassLoader(oldCl, p); Thread.currentThread().setContextClassLoader(cl); } final List<Descriptor> data = descriptors.getData(); for (Descriptor d : data) { d.applyNamespaces(); } List<Javadoc> javadoc = null; if (javadocs != null) { javadoc = javadocs.getData(); } final MetadataParser metadataParser = new MetadataParser(); metadataParser.parse(path, data, javadoc, verbose); } catch (Throwable t) { throw new BuildException(t.getMessage(), t); } finally { Thread.currentThread().setContextClassLoader(oldCl); } }
Execute Ant task @throws BuildException If an error occurs
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest)request; if (securityEnabled && (includeRequest(httpRequest) || !excludeRequest(httpRequest))) { doFilterInternal((HttpServletRequest)request, (HttpServletResponse)response, chain); } else { chain.doFilter(request, response); } }
If {@code securityEnabled}, passes the request through the chain of {@link RequestSecurityProcessor}s, depending if the request URL matches or not the {@code urlsToInclude} or the {@code urlsToExclude}. The last processor of the chain calls the actual filter chain. @param request @param response @param chain @throws IOException @throws ServletException
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { RequestContext context = RequestContext.getCurrent(); if (context == null) { context = createRequestContext(request, response); } List<RequestSecurityProcessor> finalSecurityProcessors = new ArrayList<>(securityProcessors); finalSecurityProcessors.add(getLastProcessorInChain(chain)); Iterator<RequestSecurityProcessor> processorIter = finalSecurityProcessors.iterator(); RequestSecurityProcessorChain processorChain = new RequestSecurityProcessorChainImpl(processorIter); try { processorChain.processRequest(context); } catch (IOException | ServletException | RuntimeException e) { throw e; } catch (Exception e) { throw new ServletException(e.getMessage(), e); } }
Passes the request through the chain of {@link RequestSecurityProcessor}s. @param request @param response @param chain @throws IOException @throws ServletException
protected boolean excludeRequest(HttpServletRequest request) { if (ArrayUtils.isNotEmpty(urlsToExclude)) { for (String pathPattern : urlsToExclude) { if (pathMatcher.match(pathPattern, HttpUtils.getRequestUriWithoutContextPath(request))) { return true; } } } return false; }
Returns trues if the request should be excluded from processing.
protected boolean includeRequest(HttpServletRequest request) { if (ArrayUtils.isNotEmpty(urlsToInclude)) { for (String pathPattern : urlsToInclude) { if (pathMatcher.match(pathPattern, HttpUtils.getRequestUriWithoutContextPath(request))) { return true; } } } return false; }
Returns trues if the request should be included for processing.
protected RequestContext createRequestContext(HttpServletRequest request, HttpServletResponse response) { return new RequestContext(request, response, getServletContext()); }
Returns a new {@link RequestContext}, using the specified {@link HttpServletRequest} and {@link HttpServletResponse}.
protected RequestSecurityProcessor getLastProcessorInChain(final FilterChain chain) { return new RequestSecurityProcessor() { public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception { chain.doFilter(context.getRequest(), context.getResponse()); } }; }
Returns the last processor of the chain, which should actually call the {@link FilterChain}.
@Override public FilterMutableType getOrCreateFilter() { final List<Node> nodeList = this.getRootNode().get("filter"); if (nodeList.size() > 0) { return createNewFilterViewForModel(nodeList.get(0)); } return createFilter(); }
TODO Add @Override
public static Descriptor createFromImplModelType(final Class<? extends Descriptor> implClass, String descriptorName) throws IllegalArgumentException { return DescriptorInstantiator.createFromImplModelType(implClass, descriptorName); }
Creates a {@link Descriptor} instance from the specified implementation class name, also using the specified name @param implClass @param descriptorName @return @throws IllegalArgumentException If either argument is not specified
public static Pattern[] from(final String queryExpression) throws IllegalArgumentException { if (queryExpression == null) { throw new IllegalArgumentException("Query expression must be specified"); } boolean isAbsolute = queryExpression.startsWith("/"); final Collection<Pattern> patterns = new ArrayList<Pattern>(); final String[] paths = (isAbsolute ? queryExpression.substring(1) : queryExpression).split(PATH_SEPARATOR); for (final String path : paths) { String nameSegment = path.indexOf(ATTR_PATH_SEPERATOR) != -1 ? path.substring(0, path.indexOf(ATTR_PATH_SEPERATOR)) : path; String name = nameSegment.indexOf(ATTR_VALUE_SEPERATOR) != -1 ? nameSegment.substring(0, nameSegment.indexOf(ATTR_VALUE_SEPERATOR)) : nameSegment; String text = nameSegment.indexOf(ATTR_VALUE_SEPERATOR) != -1 ? nameSegment.substring( nameSegment.indexOf(ATTR_VALUE_SEPERATOR) + 1).replaceAll("\\\\", "") : null; String attribute = path.indexOf(ATTR_PATH_SEPERATOR) != -1 ? path.substring( path.indexOf(ATTR_PATH_SEPERATOR) + ATTR_PATH_SEPERATOR.length(), path.length()) : null; String[] attributes = attribute == null ? new String[0] : attribute.split(ATTR_SEPERATOR); Pattern pattern = new Pattern(name); pattern.text(text); for (String attr : attributes) { String[] nameValue = attr.split(ATTR_VALUE_SEPERATOR); if (nameValue.length != 2) { throw new IllegalArgumentException("Attribute without name or value found: " + attr + " in expression: " + queryExpression); } pattern.attribute(nameValue[0], nameValue[1]); } patterns.add(pattern); } return patterns.toArray(ARRAY_CAST); }
Creates a query collection of {@link Pattern}s from the specified {@link String}-formed query expression @param queryExpression @return @throws IllegalArgumentException If the queryExpression is not specified
@Override public List<FILTERTYPE> getAllFilter() { final List<FILTERTYPE> list = new ArrayList<FILTERTYPE>(); final List<Node> nodeList = model.get("filter"); for (final Node node : nodeList) { final FILTERTYPE filter = this.createNewFilterViewForModel(node); list.add(filter); } return list; }
TODO Add @Override
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (noxItemCatalog == null) { wasInvalidatedBefore = false; return; } updateShapeOffset(); for (int i = 0; i < noxItemCatalog.size(); i++) { if (shape.isItemInsideView(i)) { loadNoxItem(i); float left = shape.getXForItemAtPosition(i); float top = shape.getYForItemAtPosition(i); drawNoxItem(canvas, i, left, top); } } canvas.restore(); wasInvalidatedBefore = false; }
Given a List<NoxItem> instances configured previously gets the associated resource to draw the view.
public void showNoxItems(final List<NoxItem> noxItems) { this.post(new Runnable() { @Override public void run() { initializeNoxItemCatalog(noxItems); createShape(); initializeScroller(); refreshView(); } }); }
Configures a of List<NoxItem> instances to draw this items.
public void setShape(Shape shape) { validateShape(shape); this.shape = shape; this.shape.calculate(); initializeScroller(); resetScroll(); }
Changes the Shape used to the one passed as argument. This method will refresh the view.
@Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); boolean clickCaptured = processTouchEvent(event); boolean scrollCaptured = scroller != null && scroller.onTouchEvent(event); boolean singleTapCaptured = getGestureDetectorCompat().onTouchEvent(event); return clickCaptured || scrollCaptured || singleTapCaptured; }
Delegates touch events to the scroller instance initialized previously to implement the scroll effect. If the scroller does not handle the MotionEvent NoxView will check if any NoxItem has been clicked to notify a previously configured OnNoxItemClickListener.
@Override protected void onVisibilityChanged(View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if (changedView != this) { return; } if (visibility == View.VISIBLE) { resume(); } else { pause(); } }
Controls visibility changes to pause or resume this custom view and avoid performance problems.
private void updateShapeOffset() { int offsetX = scroller.getOffsetX(); int offsetY = scroller.getOffsetY(); shape.setOffset(offsetX, offsetY); }
Checks the X and Y scroll offset to update that values into the Shape configured previously.
private void drawNoxItem(Canvas canvas, int position, float left, float top) { if (noxItemCatalog.isBitmapReady(position)) { Bitmap bitmap = noxItemCatalog.getBitmap(position); canvas.drawBitmap(bitmap, left, top, paint); } else if (noxItemCatalog.isDrawableReady(position)) { Drawable drawable = noxItemCatalog.getDrawable(position); drawNoxItemDrawable(canvas, (int) left, (int) top, drawable); } else if (noxItemCatalog.isPlaceholderReady(position)) { Drawable drawable = noxItemCatalog.getPlaceholder(position); drawNoxItemDrawable(canvas, (int) left, (int) top, drawable); } }
Draws a NoxItem during the onDraw method.
private void drawNoxItemDrawable(Canvas canvas, int left, int top, Drawable drawable) { if (drawable != null) { int itemSize = (int) noxConfig.getNoxItemSize(); drawable.setBounds(left, top, left + itemSize, top + itemSize); drawable.draw(canvas); } }
Draws a NoxItem drawable during the onDraw method given a canvas object and all the information needed to draw the Drawable passed as parameter.
private void createShape() { if (shape == null) { float firstItemMargin = noxConfig.getNoxItemMargin(); float firstItemSize = noxConfig.getNoxItemSize(); int viewHeight = getMeasuredHeight(); int viewWidth = getMeasuredWidth(); int numberOfElements = noxItemCatalog.size(); ShapeConfig shapeConfig = new ShapeConfig(numberOfElements, viewWidth, viewHeight, firstItemSize, firstItemMargin); shape = ShapeFactory.getShapeByKey(defaultShapeKey, shapeConfig); } else { shape.setNumberOfElements(noxItemCatalog.size()); } shape.calculate(); }
Initializes a Shape instance given the NoxView configuration provided programmatically or using XML styleable attributes.
private void initializeNoxViewConfig(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { noxConfig = new NoxConfig(); TypedArray attributes = context.getTheme() .obtainStyledAttributes(attrs, R.styleable.nox, defStyleAttr, defStyleRes); initializeNoxItemSize(attributes); initializeNoxItemMargin(attributes); initializeNoxItemPlaceholder(attributes); initializeShapeConfig(attributes); initializeTransformationConfig(attributes); attributes.recycle(); }
Initializes a NoxConfig instance given the NoxView configuration provided programmatically or using XML styleable attributes.
private void initializeNoxItemSize(TypedArray attributes) { float noxItemSizeDefaultValue = getResources().getDimension(R.dimen.default_nox_item_size); float noxItemSize = attributes.getDimension(R.styleable.nox_item_size, noxItemSizeDefaultValue); noxConfig.setNoxItemSize(noxItemSize); }
Configures the nox item default size used in NoxConfig, Shape and NoxItemCatalog to draw nox item instances during the onDraw execution.
private void initializeNoxItemMargin(TypedArray attributes) { float noxItemMarginDefaultValue = getResources().getDimension(R.dimen.default_nox_item_margin); float noxItemMargin = attributes.getDimension(R.styleable.nox_item_margin, noxItemMarginDefaultValue); noxConfig.setNoxItemMargin(noxItemMargin); }
Configures the nox item default margin used in NoxConfig, Shape and NoxItemCatalog to draw nox item instances during the onDraw execution.
private void initializeNoxItemPlaceholder(TypedArray attributes) { Drawable placeholder = attributes.getDrawable(R.styleable.nox_item_placeholder); if (placeholder == null) { placeholder = getContext().getResources().getDrawable(R.drawable.ic_nox); } noxConfig.setPlaceholder(placeholder); }
Configures the placeholder used if there is no another placeholder configured in the NoxItem instances during the onDraw execution.
private void initializeShapeConfig(TypedArray attributes) { defaultShapeKey = attributes.getInteger(R.styleable.nox_shape, ShapeFactory.FIXED_CIRCULAR_SHAPE_KEY); }
Configures the Shape used to show the list of NoxItems.
private void initializeTransformationConfig(TypedArray attributes) { useCircularTransformation = attributes.getBoolean(R.styleable.nox_use_circular_transformation, true); }
Configures the visual transformation applied to the NoxItem resources loaded, images downloaded from the internet and resources loaded from the system.
private GestureDetectorCompat getGestureDetectorCompat() { if (gestureDetector == null) { GestureDetector.OnGestureListener gestureListener = new SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { boolean handled = false; int position = shape.getNoxItemHit(e.getX(), e.getY()); if (position >= 0) { handled = true; NoxItem noxItem = noxItemCatalog.getNoxItem(position); listener.onNoxItemClicked(position, noxItem); } return handled; } }; gestureDetector = new GestureDetectorCompat(getContext(), gestureListener); } return gestureDetector; }
Returns a GestureDetectorCompat lazy instantiated created to handle single tap events and detect if a NoxItem has been clicked to notify the previously configured listener.
@Override public Node importAsNode(final InputStream stream, final boolean close) throws DescriptorImportException { try { // Empty contents? If so, no root Node if (stream.available() == 0) { return null; } final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(stream); final Element element = doc.getDocumentElement(); final Node root = new Node(element.getNodeName()); readRecursive(root, element); return root; } catch (final Exception e) { throw new DescriptorImportException("Could not import XML from stream", e); } finally { if (close) { try { stream.close(); } catch (final IOException ioe) { try { stream.close(); } catch (final IOException i) { log.log(Level.WARNING, "Unclosable stream specified to be closed: {0}", stream); } } } } }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.spi.node.NodeImporter#importAsNode(java.io.InputStream, boolean)
public void traverseAndFilter(final TreeWalker walker, final String indent, final Metadata metadata, final StringBuilder sb) { final Node parend = walker.getCurrentNode(); final boolean isLogged = appendText(indent, (Element) parend, sb); for (final Filter filter : filterList) { if (filter.filter(metadata, walker)) { appendText(" catched by: " + filter.getClass().getSimpleName(), sb); break; } } if (isLogged) { appendText("\n", sb); } for (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) { traverseAndFilter(walker, indent + " ", metadata, sb); } walker.setCurrentNode(parend); }
Traverses the DOM and applies the filters for each visited node. @param walker @param indent @param sb Optional {@link StringBuilder} used to track progress for logging purposes.
private boolean appendText(final String text, final StringBuilder sb) { if (sb != null) { if (text != null && text.indexOf(":annotation") < 0 && text.indexOf(":documentation") < 0) { sb.append(text); return true; } } return false; }
Appends the given text.
private boolean appendText(final String indent, final Element element, final StringBuilder sb) { if (sb != null) { if (element.getTagName().indexOf(":annotation") < 0 && element.getTagName().indexOf(":documentation") < 0) { sb.append(String.format(ELEMENT_LOG, indent, element.getTagName(), element.getAttribute("name"))); return true; } } return false; }
Appends the given element.
@Override public void to(final Node node, final OutputStream out) throws DescriptorExportException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document root = builder.newDocument(); root.setXmlStandalone(true); writeRecursive(root, node); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); StreamResult result = new StreamResult(out); transformer.transform(new DOMSource(root), result); } catch (Exception e) { throw new DescriptorExportException("Could not export Node structure to XML", e); } }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.spi.node.NodeDescriptorExporterImpl#to(org.jboss.shrinkwrap.descriptor.spi.node.Node, java.io.OutputStream)
@Override public ManifestDescriptor fromFile(File file) throws IllegalArgumentException, DescriptorImportException { if (file == null) throw new IllegalArgumentException("File cannot be null"); try { return new ManifestDescriptorImpl(descriptorName, new ManifestModel(file)); } catch (Exception e) { throw new DescriptorImportException(e.getMessage(), e); } }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#fromFile(java.io.File)
@Override public ManifestDescriptor fromStream(InputStream in) throws IllegalArgumentException, DescriptorImportException { return fromStream(in, true); }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#fromStream(java.io.InputStream)
@Override public ManifestDescriptor fromStream(InputStream in, boolean close) throws IllegalArgumentException, DescriptorImportException { if (in == null) throw new IllegalArgumentException("Stream cannot be null"); try { return new ManifestDescriptorImpl(descriptorName, new ManifestModel(in)); } catch (Exception e) { throw new DescriptorImportException(e.getMessage(), e); } finally { if (close) { try { in.close(); } catch (IOException e) { throw new DescriptorImportException("Input stream not closed", e); } } } }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#fromStream(java.io.InputStream, boolean)
@Override @Deprecated public ManifestDescriptor from(String manifest) throws IllegalArgumentException, DescriptorImportException { return fromString(manifest); }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#from(java.lang.String)
@Override public ManifestDescriptor fromString(String manifest) throws IllegalArgumentException, DescriptorImportException { if (manifest == null) throw new IllegalArgumentException("Manifest cannot be null"); InputStream inputStream = new ByteArrayInputStream(manifest.getBytes()); try { return new ManifestDescriptorImpl(descriptorName, new ManifestModel(inputStream)); } catch (IOException e) { throw new DescriptorImportException(e.getMessage(), e); } }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#fromString(java.lang.String)
@Override public ManifestDescriptor fromFile(final String file) throws IllegalArgumentException, DescriptorImportException { return this.fromFile(new File(file)); }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#fromFile(java.lang.String)
public static Map<String, Object> connectionDataToMap(ConnectionData connectionData, TextEncryptor encryptor) throws CryptoException { Map<String, Object> map = new HashMap<>(); map.put("providerUserId", connectionData.getProviderUserId()); map.put("displayName", connectionData.getDisplayName()); map.put("profileUrl", connectionData.getProfileUrl()); map.put("imageUrl", connectionData.getImageUrl()); map.put("accessToken", encrypt(connectionData.getAccessToken(), encryptor)); map.put("secret", encrypt(connectionData.getSecret(), encryptor)); map.put("refreshToken", encrypt(connectionData.getRefreshToken(), encryptor)); map.put("expireTime", connectionData.getExpireTime()); return map; }
Creates a new map from the specified {@link ConnectionData}. Used when connection data needs to be stored in a profile. @param connectionData the connection data to convert @param encryptor the encryptor used to encrypt the accessToken, secret and refreshToken (optional) @return the connection data as a map
public static ConnectionData mapToConnectionData(String providerId, Map<String, Object> map, TextEncryptor encryptor) throws CryptoException { String providerUserId = (String) map.get("providerUserId"); String displayName = (String) map.get("displayName"); String profileUrl = (String) map.get("profileUrl"); String imageUrl = (String) map.get("imageUrl"); String accessToken = decrypt((String)map.get("accessToken"), encryptor); String secret = decrypt((String)map.get("secret"), encryptor); String refreshToken = decrypt((String)map.get("refreshToken"), encryptor); Long expireTime = (Long) map.get("expireTime"); return new ConnectionData(providerId, providerUserId, displayName, profileUrl, imageUrl, accessToken, secret, refreshToken, expireTime); }
Creates a new instance of {@link ConnectionData} from the specified map. Used when connection data needs to be retrieved from a profile. @param providerId the provider ID of the connection (which is not stored in the map) @param map the map to convert @param encryptor the encryptor used to decrypt the accessToken, secret and refreshToken (optional) @return the map as {@link ConnectionData}
public static void addConnectionData(Profile profile, ConnectionData connectionData, TextEncryptor encryptor) throws CryptoException { Map<String, List<Map<String, Object>>> allConnections = profile.getAttribute(CONNECTIONS_ATTRIBUTE_NAME); List<Map<String, Object>> connectionsForProvider = null; if (allConnections == null) { allConnections = new HashMap<>(); profile.setAttribute(CONNECTIONS_ATTRIBUTE_NAME, allConnections); } else { connectionsForProvider = allConnections.get(connectionData.getProviderId()); } if (connectionsForProvider == null) { connectionsForProvider = new ArrayList<>(); allConnections.put(connectionData.getProviderId(), connectionsForProvider); } Map<String, Object> currentConnectionDataMap = null; for (Map<String, Object> connectionDataMap : connectionsForProvider) { if (connectionData.getProviderUserId().equals(connectionDataMap.get("providerUserId"))) { currentConnectionDataMap = connectionDataMap; break; } } if (currentConnectionDataMap != null) { currentConnectionDataMap.putAll(connectionDataToMap(connectionData, encryptor)); } else { connectionsForProvider.add(connectionDataToMap(connectionData, encryptor)); } }
Adds the specified {@link ConnectionData} to the profile. If a connection data with the same user ID already exists, it will be replaced with the new data. @param profile the profile @param connectionData the connection data to add @param encryptor the encryptor used to encrypt the accessToken, secret and refreshToken
public static List<ConnectionData> getConnectionData(Profile profile, String providerId, TextEncryptor encryptor) throws CryptoException { Map<String, List<Map<String, Object>>> allConnections = profile.getAttribute(CONNECTIONS_ATTRIBUTE_NAME); if (MapUtils.isNotEmpty(allConnections)) { List<Map<String, Object>> connectionsForProvider = allConnections.get(providerId); if (CollectionUtils.isNotEmpty(connectionsForProvider)) { List<ConnectionData> connectionDataList = new ArrayList<>(connectionsForProvider.size()); for (Map<String, Object> connectionDataMap : connectionsForProvider) { connectionDataList.add(mapToConnectionData(providerId, connectionDataMap, encryptor)); } return connectionDataList; } } return Collections.emptyList(); }
Returns the list of {@link ConnectionData} associated to the provider ID of the specified profile @param profile the profile that contains the connection data in its attributes @param providerId the provider ID of the connection @param encryptor the encryptor used to decrypt the accessToken, secret and refreshToken @return the list of connection data for the provider, or empty if no connection data was found
public static void removeConnectionData(Profile profile, String providerId) { Map<String, List<Map<String, Object>>> allConnections = profile.getAttribute(CONNECTIONS_ATTRIBUTE_NAME); if (MapUtils.isNotEmpty(allConnections)) { allConnections.remove(providerId); } }
Remove all {@link ConnectionData} associated to the specified provider ID. @param profile the profile where to remove the data from @param providerId the provider ID of the connection
public static void removeConnectionData(String providerId, String providerUserId, Profile profile) { Map<String, List<Map<String, Object>>> allConnections = profile.getAttribute(CONNECTIONS_ATTRIBUTE_NAME); if (MapUtils.isNotEmpty(allConnections)) { List<Map<String, Object>> connectionsForProvider = allConnections.get(providerId); if (CollectionUtils.isNotEmpty(connectionsForProvider)) { for (Iterator<Map<String, Object>> iter = connectionsForProvider.iterator(); iter.hasNext();) { Map<String, Object> connectionDataMap = iter.next(); if (providerUserId.equals(connectionDataMap.get("providerUserId"))) { iter.remove(); } } } } }
Remove the {@link ConnectionData} associated to the provider ID and user ID. @param providerId the provider ID of the connection @param providerUserId the provider user ID @param profile the profile where to remove the data from
public static void addProviderProfileInfo(Profile profile, UserProfile providerProfile) { String email = providerProfile.getEmail(); if (StringUtils.isEmpty(email)) { throw new IllegalStateException("No email included in provider profile"); } String username = providerProfile.getUsername(); if (StringUtils.isEmpty(username)) { username = email; } String firstName = providerProfile.getFirstName(); String lastName = providerProfile.getLastName(); profile.setUsername(username); profile.setEmail(email); profile.setAttribute(FIRST_NAME_ATTRIBUTE_NAME, firstName); profile.setAttribute(LAST_NAME_ATTRIBUTE_NAME, lastName); }
Adds the info from the provider profile to the specified profile. @param profile the target profile @param providerProfile the provider profile where to get the info
public static Profile createProfile(Connection<?> connection) { Profile profile = new Profile(); UserProfile providerProfile = connection.fetchUserProfile(); String email = providerProfile.getEmail(); if (StringUtils.isEmpty(email)) { throw new IllegalStateException("No email included in provider profile"); } String username = providerProfile.getUsername(); if (StringUtils.isEmpty(username)) { username = email; } String firstName = providerProfile.getFirstName(); String lastName = providerProfile.getLastName(); String displayName; if (StringUtils.isNotEmpty(connection.getDisplayName())) { displayName = connection.getDisplayName(); } else { displayName = firstName + " " + lastName; } profile.setUsername(username); profile.setEmail(email); profile.setAttribute(FIRST_NAME_ATTRIBUTE_NAME, firstName); profile.setAttribute(LAST_NAME_ATTRIBUTE_NAME, lastName); profile.setAttribute(DISPLAY_NAME_ATTRIBUTE_NAME, displayName); if (StringUtils.isNotEmpty(connection.getImageUrl())) { profile.setAttribute(AVATAR_LINK_ATTRIBUTE_NAME, connection.getImageUrl()); } return profile; }
Creates a profile from the specified connection. @param connection the connection where to retrieve the profile info from @return the created profile
@Override public void handle(RequestContext context, AccessDeniedException e) throws SecurityProviderException, IOException { saveException(context, e); if (StringUtils.isNotEmpty(getErrorPageUrl())) { forwardToErrorPage(context); } else { sendError(e, context); } }
Forwards to the error page, but if not error page was specified, a 403 error is sent. @param context the request context @param e the exception with the reason of the access deny
@Override public void handle(RequestContext context, AuthenticationException e) throws SecurityProviderException, IOException { String targetUrl = getTargetUrl(); if (StringUtils.isNotEmpty(targetUrl)) { RedirectUtils.redirect(context.getRequest(), context.getResponse(), targetUrl); } else { sendError(e, context); } }
Redirects the response to target URL if target URL is not empty. If not, a 401 UNAUTHORIZED error is sent. @param context the request context @param e the exception that caused the login to fail.
Bitmap getBitmap(int position) { return bitmaps[position] != null ? bitmaps[position].get() : null; }
Returns the bitmap associated to a NoxItem instance given a position or null if the resource wasn't downloaded.
Drawable getPlaceholder(int position) { Drawable placeholder = placeholders[position]; if (placeholder == null && defaultPlaceholder != null) { Drawable clone = defaultPlaceholder.getConstantState().newDrawable(); placeholders[position] = clone; placeholder = clone; } return placeholder; }
Returns the defaultPlaceholder associated to a NoxItem instance given a position or null if the resource wasn't downloaded or previously configured.
void load(int position, boolean useCircularTransformation) { if (isDownloading(position)) { return; } NoxItem noxItem = noxItems.get(position); if ((noxItem.hasUrl() && !isBitmapReady(position)) || noxItem.hasResourceId() && !isDrawableReady(position)) { loading[position] = true; loadNoxItem(position, noxItem, useCircularTransformation); } }
Given a position associated to a NoxItem starts the NoxItem resources download. This load will download the resources associated to the NoxItem only if wasn't previously downloaded or the download is not being performed.
public void recreate() { int newSize = noxItems.size(); WeakReference<Bitmap> newBitmaps[] = new WeakReference[newSize]; Drawable newDrawables[] = new Drawable[newSize]; Drawable newPlaceholders[] = new Drawable[newSize]; boolean newLoadings[] = new boolean[newSize]; ImageLoader.Listener newListeners[] = new ImageLoader.Listener[newSize]; float length = Math.min(bitmaps.length, newSize); for (int i = 0; i < length; i++) { newBitmaps[i] = bitmaps[i]; newDrawables[i] = drawables[i]; newPlaceholders[i] = placeholders[i]; newLoadings[i] = loading[i]; newListeners[i] = listeners[i]; } bitmaps = newBitmaps; drawables = newDrawables; placeholders = newPlaceholders; loading = newLoadings; listeners = newListeners; }
Regenerates all the internal data structures. This method should be called when the number of nox items in the catalog has changed externally.
private void loadNoxItem(final int position, NoxItem noxItem, boolean useCircularTransformation) { imageLoader.load(noxItem.getUrl()) .load(noxItem.getResourceId()) .withPlaceholder(noxItem.getPlaceholderId()) .size(noxItemSize) .useCircularTransformation(useCircularTransformation) .notify(getImageLoaderListener(position)); }
Starts the resource download given a NoxItem instance and a given position.
private ImageLoader.Listener getImageLoaderListener(final int position) { if (listeners[position] == null) { listeners[position] = new NoxItemCatalogImageLoaderListener(position, this); } return listeners[position]; }
Returns the ImageLoader.Listener associated to a NoxItem given a position. If the ImageLoader.Listener wasn't previously created, creates a new instance.
@SuppressWarnings("unchecked") public void parse(final MetadataParserPath path, final List<?> confList, final List<?> javadocTags, final boolean verbose) throws Exception { checkArguments(path, confList); pathToMetadata = createTempFile(verbose); if (log.isLoggable(Level.FINE)) { log.fine("Path to temporary metadata file: " + pathToMetadata); } for (int i = 0; i < confList.size(); i++) { final MetadataParserConfiguration metadataConf = (MetadataParserConfiguration) confList.get(i); metadata.setCurrentNamespace(metadataConf.getNameSpace()); metadata.setCurrentSchmema(metadataConf.getPathToXsd()); metadata.setCurrentPackageApi(metadataConf.getPackageApi()); metadata.setCurrentPackageImpl(metadataConf.getPackageImpl()); final MetadataDescriptor metadataDescriptor = new MetadataDescriptor(metadataConf.getDescriptorName()); metadataDescriptor.setRootElementName(metadataConf.getElementName()); metadataDescriptor.setRootElementType(metadataConf.getElementType()); metadataDescriptor.setSchemaName(metadataConf.getPathToXsd()); metadataDescriptor.setPackageApi(metadataConf.getPackageApi()); metadataDescriptor.setPackageImpl(metadataConf.getPackageImpl()); metadataDescriptor.setNamespace(metadataConf.getNameSpace()); metadataDescriptor.setNamespaces(metadataConf.getNamespaces()); metadataDescriptor.setGenerateClasses(metadataConf.generateClasses); metadataDescriptor.setPathToPackageInfoApi(metadataConf.getPathToPackageInfoApi()); metadataDescriptor.setPathToPackageInfoImpl(metadataConf.getPathToPackageInfoImpl()); metadataDescriptor.setCommon(metadataConf.getCommon()); metadataDescriptor.setCommonRef(metadataConf.getCommonRef()); metadataDescriptor.setGenerateCommonClasses(metadataConf.generateCommonClasses); metadataDescriptor.setCommonImports(metadataConf.getCommonImports()); metadata.getMetadataDescriptorList().add(metadataDescriptor); if (log.isLoggable(Level.FINE)) { log.fine(metadataConf.getPathToXsd()); } if (metadataConf.getPathToXsd().endsWith(".dtd")) { final InputSource in = new InputSource(new FileReader(metadataConf.getPathToXsd())); final MetadataDtdEventListener dtdEventListener = new MetadataDtdEventListener(metadata, verbose); final DTDParser parser = new DTDParser(); parser.setDtdHandler(dtdEventListener); parser.parse(in); } else { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder loader = factory.newDocumentBuilder(); final Document document = loader.parse(metadataConf.getPathToXsd()); if (log.isLoggable(Level.FINE)) { log.fine(document.getDocumentURI()); } final DocumentTraversal traversal = (DocumentTraversal) document; final TreeWalker walker = traversal.createTreeWalker(document.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true); final StringBuilder sb = verbose ? new StringBuilder() : null; filterChain.traverseAndFilter(walker, "", metadata, sb); if (sb != null) { log.info(sb.toString()); } } } /** * Analyze the data types defined in the elements. If an element data types points to a type defined in the data * type section, and the data type is simple type like xsd:string then change the element data type directly * here. */ metadata.preResolveDataTypes(); if (pathToMetadata != null) { new DomWriter().write(metadata, pathToMetadata, (List<MetadataJavaDoc>) javadocTags); } if (verbose) { new MetadataUtil().log(metadata); } if (path.getPathToApi() != null && path.getPathToImpl() != null) { generateCode(path, verbose); PackageInfo.copyPackageInfo(path, metadata, verbose); } }
Parses one or more XSD schemas or DTD and produces java classes based on the parsing results. @param path specifies where to create the interface, implementation and test case java classes. @param confList list <code>MetadataParserConfiguration</code> objects. @param verbose if true, additional parsing information are printed out, otherwise not. @throws Exception
public void generateCode(final MetadataParserPath path, final boolean verbose) throws TransformerException { /** initialize the map which will overwrite global parameters as defined in metadata.xsl/ddJava.xsl */ final Map<String, String> xsltParameters = new HashMap<String, String>(); xsltParameters.put("gOutputFolder", getURIPath(path.getPathToImpl())); xsltParameters.put("gOutputFolderApi", getURIPath(path.getPathToApi())); xsltParameters.put("gOutputFolderTest", getURIPath(path.getPathToTest())); xsltParameters.put("gOutputFolderService", getURIPath(path.getPathToServices())); xsltParameters.put("gVerbose", Boolean.toString(verbose)); final InputStream is = MetadataParser.class.getResourceAsStream("/META-INF/ddJavaAll.xsl"); if (log.isLoggable(Level.FINE)) { log.fine("Stream resource: " + is); } XsltTransformer.simpleTransform(pathToMetadata, is, new File("./tempddJava.xml"), xsltParameters); }
Generates source code by applying the <code>ddJavaAll.xsl</code> XSLT extracted from the resource stream. @throws TransformerException
private String createTempFile(final boolean verbose) throws IOException { final File tempFile = File.createTempFile("tempMetadata", ".xml"); if (!verbose) { tempFile.deleteOnExit(); } return tempFile.getAbsolutePath(); }
Creates a temporary file. @return absolute path of the temporary file. @throws IOException
private void checkArguments(final MetadataParserPath path, final List<?> confList) { if (path == null) { throw new IllegalArgumentException("Invalid configuration. The 'path' element missing!"); } else if (confList == null) { throw new IllegalArgumentException( "Invalid configuration. At least one 'descriptor' element has to be defined!"); } else if (confList.isEmpty()) { throw new IllegalArgumentException( "Invalid configuration. At least one 'descriptor' element has to be defined!"); } }
Validates the given arguments. @param path @param confList
public static List<String> getTenantNames(TenantService tenantService) throws ProfileException { List<Tenant> tenants = tenantService.getAllTenants(); List<String> tenantNames = new ArrayList<>(tenants.size()); if (CollectionUtils.isNotEmpty(tenants)) { for (Tenant tenant : tenants) { tenantNames.add(tenant.getName()); } } return tenantNames; }
Returns a list with the names of all tenants. @param tenantService the service that retrieves the {@link org.craftercms.profile.api.Tenant}s. @return the list of tenant names
public static String getCurrentTenantName() { Profile profile = SecurityUtils.getCurrentProfile(); if (profile != null) { return profile.getTenant(); } else { return null; } }
Returns the current tenant name, which is the tenant of the currently authenticated profile. @return the current tenant name.
public static String getAttributeValue(final Element element, final String name) { final Node node = element.getAttributes().getNamedItem(name); if (node != null) { return node.getNodeValue(); } return null; }
Returns the attribute value for the given attribute name. @param element the w3c dom element. @param name the attribute name @return if present, the the extracted attribute value, otherwise null.
public static Node getNextParentNodeWithAttr(final Node parent, final String attrName) { Node parentNode = parent; Element parendElement = (Element) parentNode; Node valueNode = parendElement.getAttributes().getNamedItem(attrName); while (valueNode == null) { parentNode = parentNode.getParentNode(); if (parentNode != null) { if (parentNode.getNodeType() == Node.ELEMENT_NODE) { parendElement = (Element) parentNode; valueNode = parendElement.getAttributes().getNamedItem(attrName); } } else { break; } } return parendElement; }
Returns the next parent node which has the specific attribute name defined. @param parent the w3c node from which the search will start. @param attrName the attribute name which is searched for. @return a parent node, if the attribute is found, otherwise null.
public static boolean hasChildsOf(final Element parentElement, XsdElementEnum child) { NodeList nodeList = parentElement.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { final Node childNode = nodeList.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE) { final Element childElement = (Element) childNode; if (child.isTagNameEqual(childElement.getTagName())) { return true; } if (childElement.hasChildNodes()) { if (hasChildsOf(childElement, child)) { return true; } } } } return false; }
Checks the existence of a w3c child element. @param parentElement the element from which the search starts. @param child the <code>XsdElementEnum</code> specifying the child element. @return true, if found, otherwise false.
public static boolean hasParentOf(final Element parentElement, XsdElementEnum parentEnum) { Node parent = parentElement.getParentNode(); while (parent != null) { if (parent.getNodeType() == Node.ELEMENT_NODE) { final Element parentElm = (Element) parent; if (parentEnum.isTagNameEqual(parentElm.getTagName())) { return true; } } parent = parent.getParentNode(); } return false; }
Checks for the first parent node occurrence of the a w3c parentEnum element. @param parentElement the element from which the search starts. @param parentEnum the <code>XsdElementEnum</code> specifying the parent element. @return true, if found, otherwise false.
public void log(final Metadata metadata) { final StringBuilder sb = new StringBuilder(); for (final MetadataItem item : metadata.getGroupList()) { sb.append(LINE); sb.append(NEWLINE); sb.append(LINE); sb.append("Group: " + item.getName()); sb.append(NEWLINE); for (MetadataElement element : item.getElements()) { sb.append(" Element : " + element.getName()); sb.append(NEWLINE); sb.append(" Type : " + element.getType()); sb.append(NEWLINE); sb.append(" MinOccurs: " + element.getMinOccurs()); sb.append(NEWLINE); sb.append(" MaxOccurs: " + element.getMaxOccurs()); sb.append(NEWLINE); sb.append(" IsAttr : " + element.getIsAttribute()); sb.append(NEWLINE); sb.append(NEWLINE); } for (MetadataElement element : item.getReferences()) { sb.append(" Ref : " + element.getRef()); sb.append(NEWLINE); } sb.append(NEWLINE); } for (MetadataEnum enumItem : metadata.getEnumList()) { sb.append(LINE); sb.append(NEWLINE); sb.append("Enum: " + enumItem.getName()); sb.append(NEWLINE); for (String enumValue : enumItem.getValueList()) { sb.append(" Value : " + enumValue); sb.append(NEWLINE); } sb.append(NEWLINE); } for (MetadataItem item : metadata.getClassList()) { sb.append(LINE); sb.append(NEWLINE); sb.append("Class: " + item.getName()); sb.append(NEWLINE); for (MetadataElement element : item.getElements()) { sb.append(" Element : " + element.getName()); sb.append(NEWLINE); sb.append(" Type : " + element.getType()); sb.append(NEWLINE); sb.append(" MinOccurs: " + element.getMinOccurs()); sb.append(NEWLINE); sb.append(" MaxOccurs: " + element.getMaxOccurs()); sb.append(NEWLINE); sb.append(" IsAttr : " + element.getIsAttribute()); sb.append(NEWLINE); sb.append(NEWLINE); } for (MetadataElement element : item.getReferences()) { sb.append(" Ref : " + element.getRef()); sb.append(NEWLINE); } sb.append(NEWLINE); } for (MetadataItem dataType : metadata.getDataTypeList()) { sb.append(LINE); sb.append(NEWLINE); sb.append("Name : " + dataType.getName()); sb.append(NEWLINE); sb.append("MappedTo: " + dataType.getMappedTo()); sb.append(NEWLINE); } // Log log.info(sb.toString()); }
Logs out metadata information. @param metadata
void computeScroll() { if (!overScroller.computeScrollOffset()) { isScrollingFast = false; return; } int distanceX = overScroller.getCurrX() - view.getScrollX(); int distanceY = overScroller.getCurrY() - view.getScrollY(); int dX = (int) calculateDx(distanceX); int dY = (int) calculateDy(distanceY); boolean stopScrolling = dX == 0 && dY == 0; if (stopScrolling) { isScrollingFast = false; } view.scrollBy(dX, dY); }
Computes the current scroll using a OverScroller instance and the time lapsed from the previous call. Also controls if the view is performing a fast scroll after a fling gesture.
private GestureDetectorCompat getGestureDetector() { if (gestureDetector == null) { gestureDetector = new GestureDetectorCompat(view.getContext(), gestureListener); } return gestureDetector; }
Returns the GestureDetectorCompat instance where the view should delegate touch events.
private float calculateDx(float distanceX) { int currentX = view.getScrollX(); float nextX = distanceX + currentX; boolean isInsideHorizontally = nextX >= minX && nextX <= maxX; return isInsideHorizontally ? distanceX : 0; }
Returns the distance in the X axes to perform the scroll taking into account the view boundary.