Example usage for org.jdom2 Document getRootElement

List of usage examples for org.jdom2 Document getRootElement

Introduction

In this page you can find the example usage for org.jdom2 Document getRootElement.

Prototype

public Element getRootElement() 

Source Link

Document

This will return the root Element for this Document

Usage

From source file:fr.paris.lutece.plugins.dila.service.impl.DilaBatchXMLService.java

License:Open Source License

@Override
public XmlDTO buildDocument(File file, AudienceCategoryEnum typeXML) throws JDOMException, IOException {
    XmlDTO dilaXml = new XmlDTO();
    dilaXml.setIdAudience(typeXML.getId());

    // Convert file to document object
    Document document = _saxBuilder.build(file);

    // Get root/*from   w  w  w  .  j  a va 2s  .c om*/
    Element root = document.getRootElement();

    // Get attribute ID
    Attribute rootAttrId = root.getAttribute(ATTRIBUTE_ID);

    if (rootAttrId != null) {
        String strId = rootAttrId.getValue();
        dilaXml.setIdXml(strId);
    }

    // Get title
    Element title = root.getChild(CHILD_TITLE, NAMESPACE_DC);

    if (title != null) {
        String strTitle = title.getTextTrim();
        dilaXml.setTitle(strTitle);
    }

    // Get type
    Element type = root.getChild(CHILD_TYPE, NAMESPACE_DC);

    if (type != null) {
        if (file.getName().startsWith("R")) {
            dilaXml.setResourceType(RESSOURCE_TYPE);
        } else {
            String strType = type.getTextTrim();
            dilaXml.setResourceType(strType);
        }
    }

    // Get breadcrumb
    Element rootBreadcrumb = root.getChild(CHILD_BREADCRUMB);

    if (rootBreadcrumb != null) {
        List<Element> listBreadcrumb = rootBreadcrumb.getChildren();

        if (CollectionUtils.isNotEmpty(listBreadcrumb)) {
            List<String> listBreadcrumbId = new ArrayList<String>(listBreadcrumb.size());

            for (Element elementBreadcrumb : listBreadcrumb) {
                listBreadcrumbId.add(elementBreadcrumb.getAttributeValue(ATTRIBUTE_ID));
            }

            String strBreadcrumb = StringUtils.join(listBreadcrumbId, ";");
            dilaXml.setBreadCrumb(strBreadcrumb);
        }
    }

    return dilaXml;
}

From source file:fr.rt.acy.locapic.gps.TrackService.java

License:Open Source License

/**
 * Methode qui ajoute la localisation a partir de l'element JDOM passe en parametre
 * Utilise les attributs de classe FILE_DIRECTORY et FILE_NAME comme chemin pour le fichier a reecrire
 * @param loc - Element JDOM representant la nouvelle position
 * @return true/*from  www  .  jav a 2 s .c  o  m*/
 */
public boolean addLocation(Element loc) {
    // Parsing
    SAXBuilder saxBuilder = new SAXBuilder();
    Document document = new Document(new Element("temp"));
    try {
        // On creer un nouveau document JDOM a partir du fichier GPX
        if (!FILE_EXT)
            document = saxBuilder.build(openFileInput(FILE_NAME));
        else
            document = saxBuilder.build(new FileInputStream(new File(EXT_FILES_DIR + FILE_NAME)));

        // On recupere la racine du document
        Element racine = document.getRootElement();
        // A partir de la racine, on recupere les tracks (<trk>)
        List<Element> trkList = racine.getChildren("trk", ns);
        // A partir de la derniere track, on recupere les segments de track (<trkseg>)
        List<Element> trksegList = trkList.get(trkList.size() - 1).getChildren("trkseg", ns);
        // On recupere le dernier segment de track (de la derniere track donc)
        Element trkseg = trksegList.get(trksegList.size() - 1);
        // On y ajoute la nouvelle position (Element loc)
        trkseg.addContent(loc);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
    // Partie enregistrement dans le Fichier
    XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
    //Log.d(TAG, "addLocation : FILE_EXT = "+FILE_EXT);
    try {
        if (!FILE_EXT)
            xmlOutput.output(document, openFileOutput(FILE_NAME, MODE_WORLD_READABLE));
        else
            xmlOutput.output(document, new FileOutputStream(EXT_FILES_DIR + FILE_NAME));
    } catch (FileNotFoundException e) {
        Log.e(TAG, e.toString());
    } catch (IOException ioe) {
        Log.e(TAG, ioe.toString());
    }

    return true;
}

From source file:geosolutions.zoom.system.XMLConfiguration.java

public boolean readXmlParametrosSystem(String path) {
    File file = new File(path + "/config.xml");
    SAXBuilder sAXBuilder = new SAXBuilder();
    if (file.exists()) {
        Cripto cripto = new Cripto();
        try {/*  ww  w  . j a  v a  2 s . c  o  m*/
            Document documento = sAXBuilder.build(file);
            Element root = documento.getRootElement();
            /**------------------servidor---------------------------*/
            Element nodoServidor = root.getChild("servidor");
            //hijos
            ParametrosSystem.setDriverPostgres(nodoServidor.getChild("driver").getText());
            ParametrosSystem.setUrlPostgres(nodoServidor.getChild("url").getText());
            ParametrosSystem.setIpServidor(nodoServidor.getChild("ip_servidor").getText());
            ParametrosSystem.setBaseDatos(nodoServidor.getChild("db").getText());
            ParametrosSystem.setNombrePcServidor(nodoServidor.getChild("nombre_servidor").getText());
            ParametrosSystem.setPuertoPostgres(nodoServidor.getChild("puerto").getText());
            ParametrosSystem.setUsuarioPostgres(nodoServidor.getChild("usuario").getText());
            ParametrosSystem.setPasswordPostgres(nodoServidor.getChild("password").getText());
            ParametrosSystem.setNickSistema(nodoServidor.getChild("nick").getText());

            /**------------------ciente---------------------------*/
            Element nodoCliente = root.getChild("cliente");
            //hijos
            ParametrosSystem.setIpCliente(nodoCliente.getChild("ip_cliente").getText());
            ParametrosSystem.setNombrePcCliente(nodoCliente.getChild("nombre_cliente").getText());

            /**------------------otro servidor---------------------------*/
            Element nodoOtrosServidor = root.getChild("otro_servidor");
            //hijos
            ParametrosSystem.setOtroIpServidor(nodoOtrosServidor.getChild("otro_ip_servidor").getText());
            ParametrosSystem.setOtroPuertoPostgres(nodoOtrosServidor.getChild("otro_puerto").getText());
            ParametrosSystem.setOtroDB(nodoOtrosServidor.getChild("otro_db").getText());

            /**------------------otros---------------------------*/
            Element nodoOtros = root.getChild("otros");
            //hijos
            ParametrosSystem.setEsServidor(nodoOtros.getChild("es_servidor").getText());
            ParametrosSystem.setInterrupcion(nodoOtros.getChild("interrupcion").getText());
            ParametrosSystem.setHoraCierrePlanilla(nodoOtros.getChild("hora_cierre_planilla").getText());
            ParametrosSystem.setEsAutorizado(nodoOtros.getChild("es_autorizado_backup").getText());
            /**------------------otros---------------------------*/
            Element nodoPath = root.getChild("path");
            //hijos
            ParametrosSystem.setPathReport(nodoPath.getChild("path_reporte").getText());
            ParametrosSystem.setPathPgDumpPostgres(nodoPath.getChild("path_pg_dump").getText());
            ParametrosSystem.setPathBackup(nodoPath.getChild("path_backup").getText());

            return true;
        } catch (JDOMException ex) {
            Logger.getLogger(XMLConfiguration.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (IOException ex) {
            Logger.getLogger(XMLConfiguration.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    } else {
        return false;
    }
}

From source file:gestetu05.Client.java

static void LireXML(String NomFichier) {
    Element racine = new Element("repertoire");
    Document document = new Document(racine);

    //On cre une instance de SAXBuilder
    SAXBuilder sxb = new SAXBuilder();
    try {//from  w w w  .j a v  a2s  .c o m
        //On cre un nouveau document JDOM avec en argument le fichier XML
        //Le parsing est termin ;)
        document = sxb.build(new File(NomFichier));
    } catch (JDOMException | IOException e) {
    }

    //On initialise un nouvel lment racine avec l'lment racine du document.
    racine = document.getRootElement();
    //On cre une List contenant tous les noeuds "utilisateur" de l'Element racine
    List listUtilisateurs = racine.getChildren("utilisateur");
    //On cre un Iterator sur notre liste
    Iterator i = listUtilisateurs.iterator();
    System.out.println("--------------------Fil d'actualit--------------------");
    while (i.hasNext()) {
        //On recre l'Element courant  chaque tour de boucle afin de
        //pouvoir utiliser les mthodes propres aux Element comme :
        //slectionner un nud fils, modifier du texte, etc...
        Element courant = (Element) i.next();
        //On affiche le nom de llment courant
        System.out.println("L'utilisateur " + courant.getChild("nom").getText());
        System.out.println(" est " + courant.getChild("Profession").getText());

    }
}

From source file:gestetu05.Client.java

static void ChercherInformation(String NomFichier, String recherche) {
    Element racine = new Element("repertoire");
    Document document = new Document(racine);
    //On cre une instance de SAXBuilder
    SAXBuilder sxb = new SAXBuilder();
    try {/*from w  ww  .  j ava2 s . c  o  m*/
        //On cre un nouveau document JDOM avec en argument le fichier XML
        //Le parsing est termin ;)
        document = sxb.build(new File(NomFichier));
    } catch (JDOMException | IOException e) {
    }

    //On initialise un nouvel lment racine avec l'lment racine du document.
    racine = document.getRootElement();
    //On cre une List contenant tous les noeuds "utilisateur" de l'Element racine
    List listUtilisateurs = racine.getChildren("utilisateur");
    //On cre un Iterator sur notre liste
    Iterator i = listUtilisateurs.iterator();
    System.out.println("Rsultat de la recherche:\n");
    while (i.hasNext()) {
        //On recre l'Element courant  chaque tour de boucle afin de
        //pouvoir utiliser les mthodes propres aux Element comme :
        //slectionner un nud fils, modifier du texte, etc...
        Element courant = (Element) i.next();
        //On affiche le nom de llment courant
        if (courant.getChild("nom").getText().equals(recherche)
                || courant.getChild("Profession").getText().equals(recherche)) {
            System.out.println("Nom:" + courant.getChild("nom").getText());
            System.out.println("Profession:" + courant.getChild("Profession").getText() + "\n");
        }

    }
}

From source file:gestores.IOMapeadorURLs.java

public static MapeadorDeURLs importarMapeadorSAX(String URL) {
    MapeadorDeURLs mapeador = new MapeadorDeURLs();

    SAXBuilder builder = new SAXBuilder();

    File file = new File(URL);

    try {/* w w w.  j  av  a 2 s. c  om*/
        Document document = builder.build(file);

        Element rootNode = document.getRootElement();

        List<Element> lista = rootNode.getChildren(Configuracion.marcaMapeoMapeador);

        for (Element elemento : lista) {
            String URLMapeada = elemento.getChildText(Configuracion.marcaURLMapeador);
            int map = Integer.parseInt(elemento.getChildText(Configuracion.marcaMappingMapeador));

            mapeador.agregarURL(URLMapeada, map);
        }
    } catch (Exception e) {
        System.out.println("Error al intentar leer el mapeador desde la URL: " + URL);
        e.printStackTrace();
        return null;
    }

    return mapeador;
}

From source file:gestores.IOVocabularioGeneral.java

private static ArrayList<EntradaVocabularioGeneral> importarEntradasDeVocabularioSAX(String URL) {
    ArrayList<EntradaVocabularioGeneral> entradas = new ArrayList<>();

    SAXBuilder builder = new SAXBuilder();

    File file = new File(URL);

    try {/* w  ww. j a  va 2s  . c  o  m*/
        Document document = builder.build(file);

        Element rootNode = document.getRootElement();

        List<Element> lista = rootNode.getChildren(Configuracion.marcaEntradaVocabulario);

        for (Element elemento : lista) {

            EntradaVocabularioGeneral entrada = new EntradaVocabularioGeneral();
            entrada.setDocumentosEnQueAparece(
                    Integer.parseInt(elemento.getChildText(Configuracion.marcaCantidadDocumentosVocabulario)));
            entrada.setFrecuencia(
                    Integer.parseInt(elemento.getChildText(Configuracion.marcaFrecuenciaVocabulario)));
            entrada.setFrecuenciaMaxima(
                    Integer.parseInt(elemento.getChildText(Configuracion.marcaFrecuenciaMaximaVocabulario)));
            entrada.setPalabra((elemento.getChildText(Configuracion.marcaPalabraVocabulario)));

            entradas.add(entrada);
        }
    } catch (Exception e) {
        System.out.println("Error al intentar leer el vocabulario desde la URL: " + URL);
        e.printStackTrace();
        return new ArrayList<>();
    }

    return entradas;
}

From source file:gov.nasa.jpl.mudrod.main.MudrodEngine.java

License:Apache License

/**
 * Load the configuration provided at <a href=
 * "https://github.com/mudrod/mudrod/blob/master/core/src/main/resources/config.xml">config.xml</a>.
 *
 * @return a populated {@link java.util.Properties} object.
 *///  w ww . j a v a2s .c  o m
public Properties loadConfig() {
    SAXBuilder saxBuilder = new SAXBuilder();

    InputStream configStream = locateConfig();

    Document document;
    try {
        document = saxBuilder.build(configStream);
        Element rootNode = document.getRootElement();
        List<Element> paraList = rootNode.getChildren("para");

        for (int i = 0; i < paraList.size(); i++) {
            Element paraNode = paraList.get(i);
            String attributeName = paraNode.getAttributeValue("name");
            if (MudrodConstants.SVM_SGD_MODEL.equals(attributeName)) {
                props.put(attributeName, decompressSVMWithSGDModel(paraNode.getTextTrim()));
            } else {
                props.put(attributeName, paraNode.getTextTrim());
            }
        }
    } catch (JDOMException | IOException e) {
        LOG.error("Exception whilst retrieving or processing XML contained within 'config.xml'!", e);
    }
    return getConfig();

}

From source file:gov.nih.nci.restgen.codegen.RESTfulResourceGenerator.java

License:BSD License

private String generateMethodEJB(String resourceName, Method method, String methodName, StringTemplate template)
        throws GeneratorException {
    Implementation impl = method.getImplementation();

    template.setAttribute("MethodName", methodName);
    template.setAttribute("ResourceName", resourceName);

    JarFile jarFile = null;/*w  w  w  .j a  v  a2  s.com*/
    org.jdom2.Document doc = null;
    try {
        jarFile = new JarFile(context.getMapping().getOptions().getEjbLocation());
        JarEntry jarEntry = jarFile.getJarEntry("META-INF/ejb-jar.xml");
        if (jarEntry != null) {
            InputStream is = jarFile.getInputStream(jarEntry);
            SAXBuilder sax = new SAXBuilder();
            doc = sax.build(is);

        } else
            throw new GeneratorException("Invalid EJB JAR path. Unable to load ejb-jar.xml");
    } catch (IOException e) {
        throw new GeneratorException("Failed to load EJB JAR. ", e);
    } catch (JDOMException e) {
        throw new GeneratorException("Failed to load EJB JAR ejb-jar.xml ", e);
    }

    org.jdom2.Element root = doc.getRootElement();

    org.jdom2.Element eBeans = root.getChild("enterprise-beans", root.getNamespace());
    List<org.jdom2.Element> sessionBeans = eBeans.getChildren("session", root.getNamespace());
    String ejbHomeName = null;
    String ejbRemoteName = null;

    boolean foundService = false;
    for (org.jdom2.Element sessionBean : sessionBeans) {
        org.jdom2.Element ejbName = sessionBean.getChild("ejb-name", root.getNamespace());

        if (ejbName.getValue().equals(impl.getName())) {
            foundService = true;
            org.jdom2.Element ejbHome = sessionBean.getChild("home", root.getNamespace());
            ejbHomeName = ejbHome.getValue();
            org.jdom2.Element ejbRemote = sessionBean.getChild("remote", root.getNamespace());
            ejbRemoteName = ejbRemote.getValue();
            break;
        }
    }

    if (!foundService)
        throw new GeneratorException("Unable to find EJB from ejb-jar.xml for " + impl.getName());

    String returnType = getOperationReturnType(impl);
    if (!returnType.equals("void")) {
        template.setAttribute("ReturnTypeNotVoid", true);
        template.setAttribute("PostReturnType", returnType);
        template.setAttribute("PutReturnType", returnType);
        template.setAttribute("DeleteReturnType", returnType);
    } else {
        template.setAttribute("ReturnTypeResponse", true);
        template.setAttribute("PostReturnType", "Response");
        template.setAttribute("PutReturnType", "Response");
        template.setAttribute("DeleteReturnType", "Response");

    }

    template.setAttribute("ReturnType", returnType);
    String pathParamPath = getOperationPath(impl, method.getName());
    if (pathParamPath != null) {
        template.setAttribute("PathParamPath", "@Path(\"" + pathParamPath + "\")");
        template.setAttribute("PathParamPathShort", pathParamPath);
    }

    template.setAttribute("PathParam", getOperationPathParams(method, impl));
    template.setAttribute("HomeInterface", ejbHomeName);
    template.setAttribute("RemoteInterface", ejbRemoteName);
    template.setAttribute("OperationName", impl.getOperation().getName());
    String operationParams = getOperationParams(impl);
    //if (operationParams != null)
    //   operationParams = operationParams + ", ";
    template.setAttribute("OperationParameters", operationParams);
    template.setAttribute("RequestType", getRequestTypes(impl));
    template.setAttribute("OperationParamNames", getOperationParams(impl));

    if (impl.getClientType().equals(Implementation.EJB_REMOTE)) {
        String jndiPath = impl.getJndiProperties();
        String fileName = jndiPath.substring(jndiPath.lastIndexOf(File.separator) + 1);
        template.setAttribute("JNDIProperties", fileName);
    }
    template.setAttribute("JNDIName", impl.getJndiName());
    return template.toString();
}

From source file:gov.nih.nci.restgen.util.RESTContentHandler.java

License:BSD License

private <T> void marshallTypeCollection(List<T> value, Class<T> clzz, OutputStreamWriter os) {
    try {// ww w .j  a  v  a 2 s.  c o m
        if (value == null || value.size() == 0)
            return;

        Object obj = value.get(0);
        String className = obj.getClass().getName();
        String qName = obj.getClass().getName();
        if (clzz.getName().indexOf(".") > 0) {
            String temp = obj.getClass().getName().substring(obj.getClass().getName().lastIndexOf(".") + 1);
            qName = (temp.charAt(0) + "").toLowerCase() + temp.substring(1, temp.length());
        }
        String collectionName = className.substring(className.lastIndexOf(".") + 1) + "s";
        org.jdom2.Element httpQuery = new org.jdom2.Element(collectionName, "");

        Iterator iterator = value.iterator();
        JAXBContext jc = JAXBContext.newInstance(obj.getClass().getPackage().getName());
        Marshaller u = jc.createMarshaller();
        u.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
        StringWriter strWriter = null;
        Reader in = null;

        try {
            while (iterator.hasNext()) {
                Object objValue = iterator.next();
                strWriter = new StringWriter();
                u.marshal(new JAXBElement(new QName(qName), obj.getClass(), objValue), strWriter);
                in = new StringReader(strWriter.toString());
                org.jdom2.input.SAXBuilder builder = new org.jdom2.input.SAXBuilder();
                org.jdom2.Document doc = builder.build(in);
                org.jdom2.Element rootEle = (org.jdom2.Element) doc.getRootElement().clone();
                httpQuery.addContent(rootEle);
                strWriter.flush();
                in.close();
                strWriter.close();
            }
        } catch (JDOMException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        org.jdom2.Document xmlDoc = new org.jdom2.Document(httpQuery);
        org.jdom2.output.XMLOutputter outputter = new org.jdom2.output.XMLOutputter();
        try {
            outputter.output(xmlDoc, os);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } catch (JAXBException e) {
        e.printStackTrace();
    }
}