Search in sources :

Example 16 with Document

use of org.jdom.Document in project ACS by ACS-Community.

the class FiltersVector method loadFilters.

/**
	 * Load filters 
	 * In case of errors an exception is thrown
	 * 
	 * @param f The xml file to parse (java.io.File) 
	 * @param eraseFilters If true existing filters will be deleted before loading
	 * @param fileName Is the name of the file (it is usually null and the name is
	 *                 read from the parameter f. However when this method is called
	 *                 recursively we need to pass the name because the file we're reading
	 *                 is a temporary file (generated by converting the original file)
	 * @throws <code>Exception</code> In case of error loading the filters
	 */
public void loadFilters(File f, boolean eraseFilters, String fileName) throws Exception {
    Document doc;
    FileInputStream fStream;
    fStream = new FileInputStream(f);
    JAXPDOMAdapter adapter = new JAXPDOMAdapter();
    DOMBuilder builder = new DOMBuilder();
    doc = builder.build(adapter.getDocument(fStream, false));
    Element root = doc.getRootElement();
    if (root.getName().compareToIgnoreCase("FILTER_LIST") != 0 && root.getName().compareToIgnoreCase("FILTERS") != 0) {
        // We show a message to the user and abort
        throw new Exception("Wrong xml file: the root is " + root.getName() + " instead of FILTER_LIST");
    } else if (root.getName().compareToIgnoreCase("FILTER_LIST") == 0) {
        // The file is an old version (show a message to the user to explain what's
        // happening and how to avoid this message appears again in future
        System.err.println("The format of this filter file is deprecated. \nSave the filters to avoid this message appears in future.");
        // Convert the format of the file
        File newFormatFile = convertOldFilterFile(f);
        if (newFormatFile == null) {
            // Something went wrong while converting: abort
            throw new Exception("Error converting the file to the new format");
        } else {
            // Recursively call loadFilters but now the file has
            // the new format
            loadFilters(newFormatFile, eraseFilters, f.getAbsolutePath());
            return;
        }
    }
    Element filtersElement = root.getChild("FILTER_LIST");
    // No filters defined
    if (filtersElement == null)
        return;
    List children = filtersElement.getChildren("FILTER");
    // Check if the vector has elements
    if (children == null || children.size() == 0) {
        return;
    }
    if (eraseFilters) {
        // The user whish to substitute the existing filters
        // with those he's loading
        clear();
    }
    // Read all the filters from the file
    Iterator it = children.iterator();
    while (it.hasNext()) {
        // Temporary Strings to store values read from the file
        String lethalStr = null;
        String notStr = null;
        String minStr = null;
        String maxStr = null;
        String exactStr = null;
        String wcharStr = null;
        String fieldStr = null;
        Boolean enabled = null;
        Element element = (Element) it.next();
        String type = element.getAttributeValue("type");
        Constraint constraint = Constraint.fromName(type);
        Element lethalElement = element.getChild("LETHAL");
        if (lethalElement != null) {
            lethalStr = lethalElement.getText();
        }
        Element notElement = element.getChild("APPLYNOT");
        if (notElement != null) {
            notStr = notElement.getText();
        }
        Element minElement = element.getChild("MIN");
        String minType = null;
        if (minElement != null) {
            minStr = minElement.getText();
            minType = minElement.getAttributeValue("class");
        }
        Element maxElement = element.getChild("MAX");
        String maxType = null;
        if (maxElement != null) {
            maxStr = maxElement.getText();
            maxType = maxElement.getAttributeValue("class");
        }
        Element exactElement = element.getChild("EXACT");
        String exactType = null;
        if (exactElement != null) {
            exactStr = exactElement.getText();
            exactType = exactElement.getAttributeValue("class");
        }
        Element wcharElement = element.getChild("WILDCHAR");
        if (wcharElement != null) {
            wcharStr = wcharElement.getText();
        }
        Element fieldElement = element.getChild("FIELD");
        if (fieldElement != null) {
            fieldStr = fieldElement.getText();
        }
        // Build the Field.
        LogField field = LogField.fromName(fieldStr);
        if (field == null) {
            // Ooops the field has not been found
            // Check if this String contains an Integer representing the
            // position of this field in the enum LogField (it was in the old format)
            Integer i = Integer.parseInt(fieldStr);
            field = LogField.values()[i];
        }
        Element enabledElement = element.getChild("ENABLED");
        if (enabledElement != null) {
            enabled = new Boolean(enabledElement.getText());
        } else {
            // Tag not found: enable the filter per default
            enabled = Boolean.TRUE;
        }
        // Build the filter
        Filter filter = Filter.buildFilter(constraint, field, lethalStr, notStr, minStr, minType, maxStr, maxType, exactStr, exactType, wcharStr);
        // bulidFilter throws an exception but ner return a null filter
        if (filter == null) {
            throw new IllegalStateException("The filter should not be null");
        }
        addFilter(filter, enabled);
    }
}
Also used : Constraint(com.cosylab.logging.engine.Filter.Constraint) Element(org.jdom.Element) Document(org.jdom.Document) LogField(com.cosylab.logging.engine.log.LogField) FileInputStream(java.io.FileInputStream) DOMBuilder(org.jdom.input.DOMBuilder) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) JAXPDOMAdapter(org.jdom.adapters.JAXPDOMAdapter) Iterator(java.util.Iterator) List(java.util.List) File(java.io.File)

Example 17 with Document

use of org.jdom.Document in project gora by apache.

the class CassandraMappingManager method loadConfiguration.

/**
   * Primary class for loading Cassandra configuration from the 'MAPPING_FILE'.
   * 
   * @throws JDOMException
   * @throws IOException
   */
@SuppressWarnings("unchecked")
public void loadConfiguration() throws JDOMException, IOException {
    SAXBuilder saxBuilder = new SAXBuilder();
    // get mapping file
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(MAPPING_FILE);
    if (inputStream == null) {
        LOG.warn("Mapping file '" + MAPPING_FILE + "' could not be found!");
        throw new IOException("Mapping file '" + MAPPING_FILE + "' could not be found!");
    }
    Document document = saxBuilder.build(inputStream);
    if (document == null) {
        LOG.warn("Mapping file '" + MAPPING_FILE + "' could not be found!");
        throw new IOException("Mapping file '" + MAPPING_FILE + "' could not be found!");
    }
    Element root = document.getRootElement();
    // find cassandra keyspace element
    List<Element> keyspaces = root.getChildren(KEYSPACE_ELEMENT);
    if (keyspaces == null || keyspaces.size() == 0) {
        LOG.error("Error locating Cassandra Keyspace element!");
    } else {
        for (Element keyspace : keyspaces) {
            // log name, cluster and host for given keyspace(s)
            String keyspaceName = keyspace.getAttributeValue(NAME_ATTRIBUTE);
            String clusterName = keyspace.getAttributeValue(CLUSTER_ATTRIBUTE);
            String hostName = keyspace.getAttributeValue(HOST_ATTRIBUTE);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Located Cassandra Keyspace: '" + keyspaceName + "' in cluster '" + clusterName + "' on host '" + hostName + "'.");
            }
            if (keyspaceName == null) {
                LOG.error("Error locating Cassandra Keyspace name attribute!");
                continue;
            }
            keyspaceMap.put(keyspaceName, keyspace);
        }
    }
    // load column definitions    
    List<Element> mappings = root.getChildren(MAPPING_ELEMENT);
    if (mappings == null || mappings.size() == 0) {
        LOG.error("Error locating Cassandra Mapping class element!");
    } else {
        for (Element mapping : mappings) {
            // associate persistent and class names for keyspace(s)
            String className = mapping.getAttributeValue(NAME_ATTRIBUTE);
            String keyClassName = mapping.getAttributeValue(KEYCLASS_ATTRIBUTE);
            String keyspaceName = mapping.getAttributeValue(KEYSPACE_ELEMENT);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Located Cassandra Mapping: keyClass: '" + keyClassName + "' in storage class '" + className + "' for Keyspace '" + keyspaceName + "'.");
            }
            if (className == null) {
                LOG.error("Error locating Cassandra Mapping class name attribute!");
                continue;
            }
            mappingMap.put(className, mapping);
        }
    }
}
Also used : SAXBuilder(org.jdom.input.SAXBuilder) InputStream(java.io.InputStream) Element(org.jdom.Element) IOException(java.io.IOException) Document(org.jdom.Document)

Example 18 with Document

use of org.jdom.Document in project gora by apache.

the class MongoMappingBuilder method fromFile.

/**
   * Load the {@link org.apache.gora.mongodb.store.MongoMapping} from a file
   * passed in parameter.
   * 
   * @param uri
   *          path to the file holding the mapping
   * @throws java.io.IOException
   */
protected void fromFile(String uri) throws IOException {
    try {
        SAXBuilder saxBuilder = new SAXBuilder();
        InputStream is = getClass().getResourceAsStream(uri);
        if (is == null) {
            String msg = "Unable to load the mapping from resource '" + uri + "' as it does not appear to exist! " + "Trying local file.";
            MongoStore.LOG.warn(msg);
            is = new FileInputStream(uri);
        }
        Document doc = saxBuilder.build(is);
        Element root = doc.getRootElement();
        // No need to use documents descriptions for now...
        // Extract class descriptions
        @SuppressWarnings("unchecked") List<Element> classElements = root.getChildren(TAG_CLASS);
        for (Element classElement : classElements) {
            final Class<T> persistentClass = dataStore.getPersistentClass();
            final Class<K> keyClass = dataStore.getKeyClass();
            if (haveKeyClass(keyClass, classElement) && havePersistentClass(persistentClass, classElement)) {
                loadPersistentClass(classElement, persistentClass);
                // only need that
                break;
            }
        }
    } catch (IOException ex) {
        MongoStore.LOG.error(ex.getMessage());
        MongoStore.LOG.error(ex.getStackTrace().toString());
        throw ex;
    } catch (Exception ex) {
        MongoStore.LOG.error(ex.getMessage());
        MongoStore.LOG.error(ex.getStackTrace().toString());
        throw new IOException(ex);
    }
}
Also used : SAXBuilder(org.jdom.input.SAXBuilder) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Element(org.jdom.Element) IOException(java.io.IOException) Document(org.jdom.Document) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException)

Example 19 with Document

use of org.jdom.Document in project gora by apache.

the class HBaseStore method readMapping.

@SuppressWarnings("unchecked")
private HBaseMapping readMapping(String filename) throws IOException {
    HBaseMappingBuilder mappingBuilder = new HBaseMappingBuilder();
    try {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(getClass().getClassLoader().getResourceAsStream(filename));
        Element root = doc.getRootElement();
        List<Element> tableElements = root.getChildren("table");
        for (Element tableElement : tableElements) {
            String tableName = tableElement.getAttributeValue("name");
            List<Element> fieldElements = tableElement.getChildren("family");
            for (Element fieldElement : fieldElements) {
                String familyName = fieldElement.getAttributeValue("name");
                String compression = fieldElement.getAttributeValue("compression");
                String blockCache = fieldElement.getAttributeValue("blockCache");
                String blockSize = fieldElement.getAttributeValue("blockSize");
                String bloomFilter = fieldElement.getAttributeValue("bloomFilter");
                String maxVersions = fieldElement.getAttributeValue("maxVersions");
                String timeToLive = fieldElement.getAttributeValue("timeToLive");
                String inMemory = fieldElement.getAttributeValue("inMemory");
                mappingBuilder.addFamilyProps(tableName, familyName, compression, blockCache, blockSize, bloomFilter, maxVersions, timeToLive, inMemory);
            }
        }
        List<Element> classElements = root.getChildren("class");
        boolean keyClassMatches = false;
        for (Element classElement : classElements) {
            if (classElement.getAttributeValue("keyClass").equals(keyClass.getCanonicalName()) && classElement.getAttributeValue("name").equals(persistentClass.getCanonicalName())) {
                LOG.debug("Keyclass and nameclass match.");
                keyClassMatches = true;
                String tableNameFromMapping = classElement.getAttributeValue("table");
                String tableName = getSchemaName(tableNameFromMapping, persistentClass);
                //tableNameFromMapping could be null here
                if (!tableName.equals(tableNameFromMapping)) {
                    //TODO this might not be the desired behavior as the user might have actually made a mistake.
                    LOG.warn("Mismatching schema's names. Mappingfile schema: '{}'. PersistentClass schema's name: '{}'. Assuming they are the same.", tableNameFromMapping, tableName);
                    if (tableNameFromMapping != null) {
                        mappingBuilder.renameTable(tableNameFromMapping, tableName);
                    }
                }
                mappingBuilder.setTableName(tableName);
                List<Element> fields = classElement.getChildren("field");
                for (Element field : fields) {
                    String fieldName = field.getAttributeValue("name");
                    String family = field.getAttributeValue("family");
                    String qualifier = field.getAttributeValue("qualifier");
                    mappingBuilder.addField(fieldName, family, qualifier);
                    mappingBuilder.addColumnFamily(tableName, family);
                }
                //do not continue on other class definitions
                break;
            }
        }
        if (!keyClassMatches)
            LOG.error("KeyClass in gora-hbase-mapping is not the same as the one in the databean.");
    } catch (MalformedURLException ex) {
        LOG.error("Error while trying to read the mapping file {}. " + "Expected to be in the classpath " + "(ClassLoader#getResource(java.lang.String)).", filename);
        LOG.error("Actual classpath = {}", Arrays.asList(((URLClassLoader) getClass().getClassLoader()).getURLs()));
        throw ex;
    } catch (IOException ex) {
        LOG.error(ex.getMessage(), ex);
        throw ex;
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);
        throw new IOException(ex);
    }
    return mappingBuilder.build();
}
Also used : SAXBuilder(org.jdom.input.SAXBuilder) MalformedURLException(java.net.MalformedURLException) Element(org.jdom.Element) IOException(java.io.IOException) HBaseMappingBuilder(org.apache.gora.hbase.store.HBaseMapping.HBaseMappingBuilder) Document(org.jdom.Document) FileNotFoundException(java.io.FileNotFoundException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Example 20 with Document

use of org.jdom.Document in project gora by apache.

the class GoraDynamoDBCompiler method readMapping.

/**
   * Reads the schema file and converts it into a data structure to be used
   * @param pMapFile
   *          schema file to be mapped into a table
   * @return
   * @throws IOException
   */
@SuppressWarnings("unchecked")
private DynamoDBMapping readMapping(File pMapFile) throws IOException {
    DynamoDBMappingBuilder mappingBuilder = new DynamoDBMappingBuilder();
    try {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(pMapFile);
        if (doc == null || doc.getRootElement() == null)
            throw new GoraException("Unable to load " + MAPPING_FILE + ". Please check its existance!");
        Element root = doc.getRootElement();
        List<Element> tableElements = root.getChildren("table");
        boolean keys = false;
        for (Element tableElement : tableElements) {
            String tableName = tableElement.getAttributeValue("name");
            long readCapacUnits = Long.parseLong(tableElement.getAttributeValue("readcunit"));
            long writeCapacUnits = Long.parseLong(tableElement.getAttributeValue("writecunit"));
            this.packageName = tableElement.getAttributeValue("package");
            mappingBuilder.setProvisionedThroughput(tableName, readCapacUnits, writeCapacUnits);
            log.debug("Table properties have been set for name, package and provisioned throughput.");
            // Retrieving attributes
            List<Element> fieldElements = tableElement.getChildren("attribute");
            for (Element fieldElement : fieldElements) {
                String key = fieldElement.getAttributeValue("key");
                String attributeName = fieldElement.getAttributeValue("name");
                String attributeType = fieldElement.getAttributeValue("type");
                mappingBuilder.addAttribute(tableName, attributeName, attributeType);
                // Retrieving key's features
                if (key != null) {
                    mappingBuilder.setKeySchema(tableName, attributeName, key);
                    keys = true;
                }
            }
            log.debug("Attributes for table '{}' have been read.", tableName);
            if (!keys)
                log.warn("Keys for table '{}' have NOT been set.", tableName);
        }
    } catch (IOException ex) {
        log.error("Error while performing xml mapping.", ex.getMessage());
        throw new RuntimeException(ex);
    } catch (Exception ex) {
        log.error("An error occured whilst reading the xml mapping file!", ex.getMessage());
        throw new IOException(ex);
    }
    return mappingBuilder.build();
}
Also used : SAXBuilder(org.jdom.input.SAXBuilder) GoraException(org.apache.gora.util.GoraException) KeySchemaElement(com.amazonaws.services.dynamodbv2.model.KeySchemaElement) Element(org.jdom.Element) DynamoDBMappingBuilder(org.apache.gora.dynamodb.store.DynamoDBMapping.DynamoDBMappingBuilder) IOException(java.io.IOException) Document(org.jdom.Document) IOException(java.io.IOException) GoraException(org.apache.gora.util.GoraException)

Aggregations

Document (org.jdom.Document)90 Element (org.jdom.Element)67 IOException (java.io.IOException)40 SAXBuilder (org.jdom.input.SAXBuilder)40 JDOMException (org.jdom.JDOMException)24 File (java.io.File)16 XMLOutputter (org.jdom.output.XMLOutputter)16 ArrayList (java.util.ArrayList)13 List (java.util.List)12 StringReader (java.io.StringReader)10 XPath (org.jdom.xpath.XPath)10 Format (org.jdom.output.Format)9 StringWriter (java.io.StringWriter)8 InputStream (java.io.InputStream)7 NotNull (org.jetbrains.annotations.NotNull)7 Nullable (org.jetbrains.annotations.Nullable)7 Writer (java.io.Writer)5 URL (java.net.URL)5 JDOMUtil.loadDocument (com.intellij.openapi.util.JDOMUtil.loadDocument)4 VirtualFile (com.intellij.openapi.vfs.VirtualFile)4