Example usage for org.jdom2.input SAXBuilder build

List of usage examples for org.jdom2.input SAXBuilder build

Introduction

In this page you can find the example usage for org.jdom2.input SAXBuilder build.

Prototype

@Override
public Document build(final String systemId) throws JDOMException, IOException 

Source Link

Document

This builds a document from the supplied URI.

Usage

From source file:de.sub.goobi.helper.HelperSchritte.java

License:Open Source License

public static void extractMetadata(Path metadataFile, Map<String, List<String>> metadataPairs) {
    SAXBuilder builder = new SAXBuilder();
    Document doc;/*w ww  . j  a v  a  2s  .  co  m*/
    try {
        doc = builder.build(metadataFile.toString());
    } catch (JDOMException | IOException e1) {
        return;
    }
    Element root = doc.getRootElement();
    try {
        Element goobi = root.getChildren("dmdSec", mets).get(0).getChild("mdWrap", mets)
                .getChild("xmlData", mets).getChild("mods", mods).getChild("extension", mods)
                .getChild("goobi", goobiNamespace);
        List<Element> metadataList = goobi.getChildren();
        addMetadata(metadataList, metadataPairs);
        for (Element el : root.getChildren("dmdSec", mets)) {
            if (el.getAttributeValue("ID").equals("DMDPHYS_0000")) {
                Element phys = el.getChild("mdWrap", mets).getChild("xmlData", mets).getChild("mods", mods)
                        .getChild("extension", mods).getChild("goobi", goobiNamespace);
                List<Element> physList = phys.getChildren();
                addMetadata(physList, metadataPairs);
            }
        }
        // create field for "DocStruct"
        String docType = root.getChildren("structMap", mets).get(0).getChild("div", mets)
                .getAttributeValue("TYPE");
        metadataPairs.put("DocStruct", Collections.singletonList(docType));

    } catch (Exception e) {
        logger.error(e);
        logger.error("Cannot extract metadata from " + metadataFile.toString());
    }
}

From source file:de.sub.goobi.helper.tasks.ProcessSwapInTask.java

License:Open Source License

/**
 * Aufruf als Thread ================================================================
 *///  w  ww.java  2s.c o m
@SuppressWarnings("deprecation")
@Override
public void run() {
    setStatusProgress(5);
    String swapPath = null;
    //      ProzessDAO dao = new ProzessDAO();
    String processDirectory = "";

    if (ConfigurationHelper.getInstance().isUseSwapping()) {
        swapPath = ConfigurationHelper.getInstance().getSwapPath();
    } else {
        setStatusMessage("swapping not activated");
        setStatusProgress(-1);
        return;
    }
    if (swapPath == null || swapPath.length() == 0) {
        setStatusMessage("no swappingPath defined");
        setStatusProgress(-1);
        return;
    }
    Path swapFile = Paths.get(swapPath);
    if (!StorageProvider.getInstance().isFileExists(swapFile)) {
        setStatusMessage("Swap folder does not exist or is not mounted");
        setStatusProgress(-1);
        return;
    }
    try {
        processDirectory = getProzess().getProcessDataDirectoryIgnoreSwapping();
        // TODO: Don't catch Exception (the super class)
    } catch (Exception e) {
        logger.warn("Exception:", e);
        setStatusMessage(
                "Error while getting process data folder: " + e.getClass().getName() + " - " + e.getMessage());
        setStatusProgress(-1);
        return;
    }

    Path fileIn = Paths.get(processDirectory);
    Path fileOut = Paths.get(swapPath + getProzess().getId() + FileSystems.getDefault().getSeparator());

    if (!StorageProvider.getInstance().isFileExists(fileOut)) {
        setStatusMessage(getProzess().getTitel() + ": swappingOutTarget does not exist");
        setStatusProgress(-1);
        return;
    }
    if (!StorageProvider.getInstance().isFileExists(fileIn)) {
        setStatusMessage(getProzess().getTitel() + ": process data folder does not exist");
        setStatusProgress(-1);
        return;
    }

    SAXBuilder builder = new SAXBuilder();
    Document docOld;
    try {
        Path swapLogFile = Paths.get(processDirectory, "swapped.xml");
        docOld = builder.build(swapLogFile.toFile());
        // TODO: Don't catch Exception (the super class)
    } catch (Exception e) {
        logger.warn("Exception:", e);
        setStatusMessage("Error while reading swapped.xml in process data folder: " + e.getClass().getName()
                + " - " + e.getMessage());
        setStatusProgress(-1);
        return;
    }

    /*
     * --------------------- alte Checksummen in HashMap schreiben -------------------
     */
    setStatusMessage("reading checksums");
    Element rootOld = docOld.getRootElement();

    HashMap<String, String> crcMap = new HashMap<String, String>();

    // TODO: Don't use Iterators
    for (Iterator<Element> it = rootOld.getChildren("file").iterator(); it.hasNext();) {
        Element el = it.next();
        crcMap.put(el.getAttribute("path").getValue(), el.getAttribute("crc32").getValue());
    }
    StorageProvider.getInstance().deleteDataInDir(fileIn);

    /*
     * --------------------- Dateien kopieren und Checksummen ermitteln -------------------
     */
    Document doc = new Document();
    Element root = new Element("goobiArchive");
    doc.setRootElement(root);

    /*
     * --------------------- Verzeichnisse und Dateien kopieren und anschliessend den Ordner leeren -------------------
     */
    setStatusProgress(50);
    try {
        setStatusMessage("copying process files");
        Helper.copyDirectoryWithCrc32Check(fileOut, fileIn, swapPath.length(), root);
    } catch (IOException e) {
        logger.warn("IOException:", e);
        setStatusMessage("IOException in copyDirectory: " + e.getMessage());
        setStatusProgress(-1);
        return;
    }
    setStatusProgress(80);

    /*
     * --------------------- Checksummen vergleichen -------------------
     */
    setStatusMessage("checking checksums");
    // TODO: Don't use Iterators
    for (Iterator<Element> it = root.getChildren("file").iterator(); it.hasNext();) {
        Element el = it.next();
        String newPath = el.getAttribute("path").getValue();
        String newCrc = el.getAttribute("crc32").getValue();
        if (crcMap.containsKey(newPath)) {
            if (!crcMap.get(newPath).equals(newCrc)) {
                setLongMessage(getLongMessage() + "File " + newPath + " has different checksum<br/>");
            }
            crcMap.remove(newPath);
        }
    }

    setStatusProgress(85);
    /*
     * --------------------- prfen, ob noch Dateien fehlen -------------------
     */
    setStatusMessage("checking missing files");
    if (crcMap.size() > 0) {
        for (String myFile : crcMap.keySet()) {
            setLongMessage(getLongMessage() + "File " + myFile + " is missing<br/>");
        }
    }

    setStatusProgress(90);

    /* in Prozess speichern */
    StorageProvider.getInstance().deleteDir(fileOut);
    try {
        setStatusMessage("saving process");
        Process myProzess = ProcessManager.getProcessById(getProzess().getId());
        myProzess.setSwappedOutGui(false);
        ProcessManager.saveProcess(myProzess);
    } catch (DAOException e) {
        setStatusMessage("DAOException while saving process: " + e.getMessage());
        logger.warn("DAOException:", e);
        setStatusProgress(-1);
        return;
    }
    setStatusMessage("done");

    setStatusProgress(100);
}

From source file:de.tsystems.mms.apm.performancesignature.viewer.rest.DashboardXMLReader.java

License:Apache License

private static Document useSAXParser(final String xml) throws JDOMException, IOException {
    SAXBuilder saxBuilder = new SAXBuilder();
    return saxBuilder.build(new StringReader(xml));
}

From source file:de.unirostock.sems.cbarchive.web.dataholder.XmlTreeMetaObjectDataholder.java

License:Open Source License

public void setXmlString(String xmlString) {

    try {/*from  ww w . j  a  v  a2  s  .  com*/
        SAXBuilder builder = new SAXBuilder();
        Document doc = (Document) builder.build(new ByteArrayInputStream(xmlString.getBytes()));
        xmlTree = doc.getRootElement().clone();

        exceptionMessage = null;
    } catch (JDOMException | IOException e) {
        LOGGER.error(e, "Cannot transform String to Xml Element");
        xmlTree = null;
        exceptionMessage = e.getMessage();
    }

}

From source file:delfos.configfile.rs.single.DatasetConfigurationFileParser.java

License:Open Source License

/**
 * Mtodo para recuperar los objetos que se deben usar segn los parmetros que dicta el fichero de configuracin
 * indicado. Como se devuelven mltiples valores y java no permite la devolucin de mltiples valores en una
 * funcin, se ha creado un objeto para almacenarlos.
 *
 * @param configFile Ruta del fichero de configuracin.
 * @return Devuelve un objeto que contiene los parmetros necesarios para definir completamente un sistema de
 * recomendacin.//  w w w. ja v a  2s  . c o m
 * @throws JDOMException Si el archivo de configuracin no tiene la estructura de objetos JDOM esperada, es decir,
 * no se reconoce el formato del archivo.
 * @throws CannotLoadContentDataset Si no se puede cargar el dataset de contenido.
 * @throws CannotLoadRatingsDataset Si no se puede cargar el dataset de valoraciones.
 * @throws FileNotFoundException Si el archivo indicado no existe.
 */
public static DatasetConfiguration loadDatasetLoaderFromConfigFile(File configFile)
        throws JDOMException, CannotLoadContentDataset, CannotLoadRatingsDataset, FileNotFoundException {
    SAXBuilder builder = new SAXBuilder();
    Document doc = null;
    try {
        doc = builder.build(configFile);
    } catch (IOException ex) {
        Global.showError(ex);
        ERROR_CODES.CANNOT_LOAD_CONFIG_FILE.exit(ex);
        throw new IllegalStateException(ex);
    }

    Element config = doc.getRootElement();
    Element datasetLoaderElement = config.getChild(DatasetLoaderXML.ELEMENT_NAME);
    DatasetLoader<? extends Rating> datasetLoader = DatasetLoaderXML.getDatasetLoader(datasetLoaderElement);

    return new DatasetConfiguration(datasetLoader);
}

From source file:delfos.configfile.rs.single.RecommenderSystemConfigurationFileParser.java

License:Open Source License

private static RecommenderSystemConfiguration loadConfigFileWithExceptions(String configFilePath)
        throws JDOMException, FileNotFoundException {

    Global.showMessageTimestamped("Loading config file " + configFilePath);
    SAXBuilder builder = new SAXBuilder();
    Document doc = null;//from  ww w.j  a  va 2s .c  o  m

    File configFile = new File(configFilePath);
    try {
        doc = builder.build(configFile);
    } catch (IOException ex) {
        Global.showError(ex);
        ERROR_CODES.CANNOT_LOAD_CONFIG_FILE.exit(ex);
        throw new IllegalStateException(ex);
    }

    Element config = doc.getRootElement();

    Element rs = config.getChild(RecommenderSystemXML.ELEMENT_NAME);
    GenericRecommenderSystem<Object> recommender = RecommenderSystemXML.getRecommenderSystem(rs);

    Element datasetLoaderElement = config.getChild(DatasetLoaderXML.ELEMENT_NAME);
    DatasetLoader<? extends Rating> datasetLoader = DatasetLoaderXML.getDatasetLoader(datasetLoaderElement);

    Element relevanceCriteriaElement = config.getChild(RelevanceCriteriaXML.ELEMENT_NAME);
    RelevanceCriteria relevanceCriteria = RelevanceCriteriaXML.getRelevanceCriteria(relevanceCriteriaElement);

    //Persistence Method
    Element persistenceMethodElement = config.getChild(PersistenceMethodXML.PERSISTENCE_METHOD_ELEMENT);
    PersistenceMethod persistenceMethod = PersistenceMethodXML.getPersistenceMethod(persistenceMethodElement);

    //Obtiene el mtodo para devolver las recomendaciones.
    RecommendationsOutputMethod recommdendationsOutputMethod;
    {
        Element recommdendationsOutputMethodElement = config
                .getChild(RecommdendationsOutputMethodXML.RECOMMENDATIONS_OUTPUT_METHOD_ELEMENT_NAME);
        if (recommdendationsOutputMethodElement == null) {
            Global.showWarning(
                    "This configuration file is old, update to the new version which includes recommendations output management.");
            Global.showWarning("Using default RecommendationsOutputMethod --> "
                    + RecommendationsOutputStandardXML.class.getName());
            recommdendationsOutputMethod = new RecommendationsOutputStandardXML();
        } else {
            recommdendationsOutputMethod = RecommdendationsOutputMethodXML
                    .getRecommdendationsOutputMethod(recommdendationsOutputMethodElement);
        }
        if (Global.isVerboseAnnoying()) {
            Global.showInfoMessage("Recommendation output method loaded: "
                    + recommdendationsOutputMethod.getNameWithParameters() + "\n");
        }
    }

    //Obtiene el mtodo para calcular los items candidatos a recomendacin.
    RecommendationCandidatesSelector recommendationCandidatesSelector;
    {
        Element recommendationCandidatesSelectorElement = config
                .getChild(RecommendationCandidatesSelectorXML.RECOMMENDATION_CANDIDATE_SELECTOR_ELEMENT_NAME);
        if (recommendationCandidatesSelectorElement == null) {
            Global.showWarning(
                    "This configuration file is old, update to the new version which includes recommendation candidates selector.");
            Global.showWarning("Using default RecommendationCandidatesSelector --> "
                    + RecommendationCandidatesSelector.defaultValue.getClass().getName());
            recommendationCandidatesSelector = RecommendationCandidatesSelector.defaultValue;
        } else {
            recommendationCandidatesSelector = RecommendationCandidatesSelectorXML
                    .getRecommendationsCandidatesSelector(recommendationCandidatesSelectorElement);
        }
        if (Global.isVerboseAnnoying()) {
            Global.showInfoMessage("Recommendation output method loaded: "
                    + recommdendationsOutputMethod.getNameWithParameters() + "\n");
        }
    }

    if (config.getChild("NUMBER_OF_RECOMMENDATIONS") != null) {
        Global.showWarning(
                "Deprecated RecommenderSystem Configuration element: _Number of recommendations. Use RecommendationOutputMethod parameter NUMBER_OF_RECOMMENDATIONS instead.");
    }

    RecommenderSystemConfiguration ret = new RecommenderSystemConfiguration(recommender, datasetLoader,
            persistenceMethod, recommendationCandidatesSelector, recommdendationsOutputMethod,
            relevanceCriteria);
    Global.showMessageTimestamped("Loaded config file " + configFilePath);

    return ret;

}

From source file:delfos.configuration.ConfigurationScope.java

License:Open Source License

protected void loadConfigurationScope() {
    if (document == null) {
        File configurationFile = ConfigurationManager.getConfigurationFile(this);
        SAXBuilder builder = new SAXBuilder();
        try {/*  w  w w .  j a v a2  s.  c  om*/
            document = builder.build(configurationFile);
        } catch (JDOMException | IOException ex) {
            Global.showWarning("Cannot load xml from " + configurationFile.getAbsolutePath());

            if (configurationFile.exists()) {
                File erroneousFile = new File(
                        configurationFile.getParentFile().getAbsolutePath() + "cannot-parse.xml");
                configurationFile.renameTo(erroneousFile);
            }

            document = new Document(new Element(scopeName));
        }
    }
}

From source file:delfos.configuration.scopes.ConfiguredDatasetsScope.java

License:Open Source License

private synchronized Collection<ConfiguredDataset> loadConfiguredDatasets() {
    File fileOfConfiguredDatasets = ConfigurationManager.getConfigurationFile(this);

    Collection<ConfiguredDataset> configuredDatasets = new ArrayList<>();

    if (!fileOfConfiguredDatasets.exists()) {
        Global.showWarning("The configured datasets file for this machine does not exists-");
        Global.showWarning("\tFile '" + fileOfConfiguredDatasets.getAbsolutePath() + "': not found.");
        Global.showWarning("The configured datasets file for this machine does not exists.");
        saveConfigurationScope();/*from  ww  w . j a  v  a2 s  .c om*/
    } else {
        if (Global.isVerboseAnnoying()) {
            Global.showInfoMessage("Loading configured datasets from file '"
                    + fileOfConfiguredDatasets.getAbsolutePath() + "'\n");
        }
        try {
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(fileOfConfiguredDatasets);

            Element rootElement = doc.getRootElement();
            if (!rootElement.getName().equals(CONFIGURED_DATASETS_ROOT_ELEMENT_NAME)) {
                IllegalArgumentException ex = new IllegalArgumentException(
                        "The XML does not contains the configured datasets.");
                ERROR_CODES.CANNOT_READ_CONFIGURED_DATASETS_FILE.exit(ex);
            }

            for (Element configuredDataset : rootElement.getChildren(CONFIGURED_DATASET_ELEMENT_NAME)) {
                String name = configuredDataset.getAttributeValue(CONFIGURED_DATASET_ELEMENT_NAME_ATTRIBUTE);
                String description = configuredDataset
                        .getAttributeValue(CONFIGURED_DATASET_ELEMENT_DESCRIPTION_ATTRIBUTE);
                Element datasetLoaderElement = configuredDataset.getChild(DatasetLoaderXML.ELEMENT_NAME);

                if (datasetLoaderElement == null) {
                    IllegalStateException ex = new IllegalStateException(
                            "Cannot retrieve configured dataset loader '" + name + "'");
                    ERROR_CODES.CANNOT_READ_CONFIGURED_DATASETS_FILE.exit(ex);
                }

                DatasetLoader<? extends Rating> datasetLoader = DatasetLoaderXML
                        .getDatasetLoader(datasetLoaderElement);

                if (Global.isVerboseAnnoying()) {
                    Global.showInfoMessage("\tConfigured dataset '" + name + "' loaded.\n");
                }

                configuredDatasets.add(new ConfiguredDataset(name, description, datasetLoader));

            }
            if (configuredDatasets.isEmpty()) {
                Global.showWarning("No configured datasets found, check configuration file.");
            }
        } catch (JDOMException | IOException ex) {
            ERROR_CODES.CANNOT_READ_CONFIGURED_DATASETS_FILE.exit(ex);
        }
    }

    return configuredDatasets;
}

From source file:delfos.group.grs.consensus.ConsensusOfIndividualRecommendationsToXML.java

License:Open Source License

public static ConsensusOutputModel readConsensusOutputXML(File consensusIntputXML)
        throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(consensusIntputXML);

    Element root = doc.getRootElement();
    if (!root.getName().equals(CONSENSUS_OUTPUT_ROOT_NAME)) {
        throw new IllegalArgumentException(
                "The XML does not contains a Case Study (" + consensusIntputXML.getAbsolutePath() + ")");
    }/*from www .j a  v a 2 s  .c o m*/

    Element consensus = root.getChild(CONSENSUS_OUTPUT_CONSENSUS_ELEMENT_NAME);

    int round = Integer.parseInt(consensus.getAttributeValue(CONSENSUS_OUTPUT_CONSENSUS_ATTRIBUTE_ROUND));
    double consensusDegree = Double
            .parseDouble(consensus.getAttributeValue(CONSENSUS_OUTPUT_CONSENSUS_ATTRIBUTE_CONSENSUS_DEGREE));

    Collection<Recommendation> consensusRecommendations = new ArrayList<>();

    for (Element alternative : consensus.getChildren(CONSENSUS_OUTPUT_ALTERNATVE_ELEMENT_NAME)) {
        int idItem = Integer
                .parseInt(alternative.getAttributeValue(CONSENSUS_OUTPUT_ALTERNATVE_ATTRIBUTE_ID_ITEM));
        double rank = Double
                .parseDouble(alternative.getAttributeValue(CONSENSUS_OUTPUT_ALTERNATVE_ATTRIBUTE_RANK));

        double preference = 1 / rank;
        consensusRecommendations.add(new Recommendation(idItem, preference));
    }

    return new ConsensusOutputModel(consensusDegree, round, consensusRecommendations);
}

From source file:delfos.group.io.xml.casestudy.GroupCaseStudyXML.java

License:Open Source License

/**
 * Carga la descripcin de un caso de estudio para sistemas de recomendacin
 * para grupos./* ww  w .  ja  v  a 2  s . com*/
 *
 * @param file Archivo donde se encuentra almacenado el caso de estudio.
 * @return Caso de estudio recuperado del archivo.
 * @throws org.jdom2.JDOMException Cuando se intenta cargar un xml que no
 * tiene la estructura esperada. Chequear si esta desfasada la versin.
 * @throws IOException Cuando no se puede leer el archivo indicado o existe
 * algun fallo de conversin de datos al leer el contenido del mismo.
 */
public static GroupCaseStudyConfiguration loadGroupCaseDescription(File file)
        throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();

    Document doc = builder.build(file);
    Element caseStudy = doc.getRootElement();
    if (!caseStudy.getName().equals(CASE_ROOT_ELEMENT_NAME)) {
        throw new IllegalArgumentException("The XML does not contains a Case Study.");
    }
    GroupRecommenderSystem<Object, Object> groupRecommenderSystem = GroupRecommenderSystemXML
            .getGroupRecommenderSystem(caseStudy.getChild(GroupRecommenderSystemXML.ELEMENT_NAME));

    GroupFormationTechnique groupFormationTechnique = GroupFormationTechniqueXML
            .getGroupFormationTechnique(caseStudy.getChild(GroupFormationTechniqueXML.ELEMENT_NAME));
    ValidationTechnique validationTechnique = ValidationTechniqueXML
            .getValidationTechnique(caseStudy.getChild(ValidationTechniqueXML.ELEMENT_NAME));
    GroupPredictionProtocol groupPredictionProtocol = GroupPredictionProtocolXML
            .getGroupPredictionProtocol(caseStudy.getChild(GroupPredictionProtocolXML.ELEMENT_NAME));
    RelevanceCriteria relevanceCriteria = RelevanceCriteriaXML
            .getRelevanceCriteria(caseStudy.getChild(RelevanceCriteriaXML.ELEMENT_NAME));

    DatasetLoader<? extends Rating> datasetLoader = DatasetLoaderXML
            .getDatasetLoader(caseStudy.getChild(DatasetLoaderXML.ELEMENT_NAME));

    long seed = Long.parseLong(caseStudy.getAttributeValue(SeedHolder.SEED.getName()));
    int numExecutions = Integer.parseInt(caseStudy.getAttributeValue(NUM_EXEC_ATTRIBUTE_NAME));
    String caseStudyAlias = caseStudy.getAttributeValue(ParameterOwner.ALIAS.getName());

    return new GroupCaseStudyConfiguration(groupRecommenderSystem, datasetLoader, groupFormationTechnique,
            validationTechnique, groupPredictionProtocol, relevanceCriteria, caseStudyAlias, numExecutions,
            seed, null);
}