Example usage for org.jdom2.input SAXBuilder SAXBuilder

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

Introduction

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

Prototype

public SAXBuilder() 

Source Link

Document

Creates a new JAXP-based SAXBuilder.

Usage

From source file:cager.parser.test.SimpleTest3.java

License:Open Source License

private Element inicializaKDM(String segmentName) {

    // Creamos el builder basado en SAX
    SAXBuilder builder = new SAXBuilder();

    //Namespace xmi = Namespace.getNamespace("xmi", "http://www.omg.org/XMI");
    Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    Namespace action = Namespace.getNamespace("action", "http://kdm.omg.org/action");
    Namespace code = Namespace.getNamespace("code", "http://kdm.omg.org/code");
    Namespace kdm = Namespace.getNamespace("kdm", "http://kdm.omg.org/kdm");
    Namespace source = Namespace.getNamespace("source", "http://kdm.omg.org/source");

    Element segmento = new Element("Segment", kdm);
    segmento.addNamespaceDeclaration(xmi);
    segmento.addNamespaceDeclaration(xsi);
    segmento.addNamespaceDeclaration(action);
    segmento.addNamespaceDeclaration(code);
    segmento.addNamespaceDeclaration(kdm);
    segmento.addNamespaceDeclaration(source);

    segmento.setAttribute("name", segmentName.substring(0, segmentName.indexOf('.')));

    Element modelo = new Element("model");
    modelo.setAttribute("id", "id.0", xmi);
    idCount++;/*from   w  w w . j a  v  a2s  .co m*/
    modelo.setAttribute("name", segmentName.substring(0, segmentName.indexOf('.')));
    modelo.setAttribute("type", "code:CodeModel", xmi);

    Element codeElement = new Element("codeElement");
    codeElement.setAttribute("id", "id.1", xmi);
    idCount++;
    codeElement.setAttribute("name", segmentName);
    codeElement.setAttribute("type", "code:CompilationUnit", xmi);

    modelo.addContent(codeElement);

    elementoTipos = inicializaDataTypes();

    modelo.addContent(elementoTipos);

    segmento.addContent(modelo);

    return segmento;
}

From source file:cager.parser.test.SimpleTest3.java

License:Open Source License

private Element inicializaDataTypes() {

    // Creamos el builder basado en SAX
    SAXBuilder builder = new SAXBuilder();

    //Namespace xmi = Namespace.getNamespace("xmi", "http://www.omg.org/XMI");
    Namespace code = Namespace.getNamespace("code", "http://kdm.omg.org/code");

    Element model = new Element("model");
    model.setAttribute("id", "id." + idCount, xmi);
    model.setAttribute("type", "code:CodeModel", xmi);
    idCount++;// ww  w  .j  av  a 2 s.c om

    Element codeElementP = new Element("codeElement");
    codeElementP.setAttribute("id", "id." + idCount, xmi);
    codeElementP.setAttribute("type", "code:LanguageUnit", xmi);
    idCount++;

    Element codeElementI = new Element("codeElement");

    for (int i = 0; i < dataTypes.length; i++) {

        codeElementI = new Element("codeElement");
        codeElementI.setAttribute("id", "id." + idCount, xmi);
        if (dataTypes[i].equals("Double") || dataTypes[i].equals("Long") || dataTypes[i].equals("Short")) {
            codeElementI.setAttribute("type", "code:DecimalType", xmi);
        } else if (dataTypes[i].equals("Byte")) {
            codeElementI.setAttribute("type", "code:OctetType", xmi);
        } else {
            codeElementI.setAttribute("type", "code:" + dataTypes[i] + "Type", xmi);
        }

        codeElementI.setAttribute("name", dataTypes[i]);

        if (!hsmLanguajeUnitDataType.containsKey(dataTypes[i])) {
            hsmLanguajeUnitDataType.put(dataTypes[i], idCount);
        }

        idCount++;

        codeElementP.addContent(codeElementI);

    }

    //model.addContent(codeElementP);      

    return codeElementP;

}

From source file:centroinfantil.PasoLista.java

License:Open Source License

/**
 *
 * @return//from w w w  .jav  a 2s. co  m
 */
static public ArrayList<ArrayList<String>> cargarXml() {
    //Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File("historial.xml");
    ArrayList<ArrayList<String>> salida = new ArrayList<>();

    try {
        ArrayList<String> nino = new ArrayList<>();
        String cadena;

        //Se crea el documento a traves del archivo
        Document document = (Document) builder.build(xmlFile);

        //Se obtiene la raiz 'tables'
        Element rootNode = document.getRootElement();

        //Se obtiene la lista de hijos de la raiz 'tables'
        List list = rootNode.getChildren("child");

        System.out.println(list.size());
        //Se recorre la lista de hijos de 'tables'
        for (int i = 0; i < list.size(); i++) {
            //Se obtiene el elemento 'tabla'
            Element tabla = (Element) list.get(i);

            //Se obtiene la lista de hijos del tag 'tabla'
            List lista_campos = tabla.getChildren();

            //Se recorre la lista de campos
            for (int j = 0; j < lista_campos.size() - 1; j++) {
                //Se obtiene el elemento 'campo'
                Element campo = (Element) lista_campos.get(j);
                cadena = campo.getText();
                nino.add(cadena);
            }

            Element campo = (Element) lista_campos.get(lista_campos.size() - 1);
            nino.add(campo.getChildTextTrim("fecha"));
            nino.add(campo.getChildTextTrim("sala"));
            nino.add(campo.getChildTextTrim("camara"));
            nino.add(campo.getChildTextTrim("posicionX"));
            nino.add(campo.getChildTextTrim("posicionY"));

            salida.add(nino);
        }
    } catch (IOException | JDOMException io) {
        System.out.println(io.getMessage());
    }
    return salida;
}

From source file:cfdi.clases.UtilidadesArchivoCfdi.java

License:Open Source License

/**
* Proceso de parseo del XML al objeto estructura layout
* El objeto layout es el que se pasa como parametro al reporte
* 
* @param rutaArchivo ruta donde se va a colocar el archivo
* @param nombreArchivo nombre del archivo a exportar
* @param showLog guardar informacin del inicio y finilizacion del proceso de exportacin
* @return EstructuraLayout/*www .j  av  a2s .c  om*/
*/
public EstructuraLayout parseLayout(String rutaArchivo, String nombreArchivo, boolean showLog) {
    EstructuraLayout layout = null;
    if (showLog)
        logger.log(Level.INFO, "Inicia parse {0}", nombreArchivo);
    try {
        File archivo;
        archivo = new File(rutaArchivo + nombreArchivo);
        SAXBuilder constructorSAX = new SAXBuilder();
        try {
            layout = new EstructuraLayout();
            layout.setRutaArchivo(rutaArchivo);
            layout.setNombreArchivo(nombreArchivo);
            Document documento = (Document) constructorSAX.build(archivo);
            layout.setVersion(documento.getRootElement().getAttribute("version") != null
                    ? documento.getRootElement().getAttribute("version").getValue()
                    : (documento.getRootElement().getAttribute("Version") != null
                            ? documento.getRootElement().getAttribute("Version").getValue()
                            : ""));
            layout.setSerie(documento.getRootElement().getAttribute("serie") != null
                    ? documento.getRootElement().getAttribute("serie").getValue()
                    : (documento.getRootElement().getAttribute("Serie") != null
                            ? documento.getRootElement().getAttribute("Serie").getValue()
                            : ""));
            layout.setFolio(documento.getRootElement().getAttribute("folio") != null
                    ? documento.getRootElement().getAttribute("folio").getValue()
                    : (documento.getRootElement().getAttribute("Folio") != null
                            ? documento.getRootElement().getAttribute("Folio").getValue()
                            : ""));
            layout.setFecha(documento.getRootElement().getAttribute("fecha") != null
                    ? documento.getRootElement().getAttribute("fecha").getValue()
                    : (documento.getRootElement().getAttribute("Fecha") != null
                            ? documento.getRootElement().getAttribute("Fecha").getValue()
                            : ""));
            layout.setSello(documento.getRootElement().getAttribute("sello") != null
                    ? documento.getRootElement().getAttribute("sello").getValue()
                    : (documento.getRootElement().getAttribute("Sello") != null
                            ? documento.getRootElement().getAttribute("Sello").getValue()
                            : ""));
            layout.setFormaPago(documento.getRootElement().getAttribute("formaDePago") != null
                    ? documento.getRootElement().getAttribute("formaDePago").getValue()
                    : (documento.getRootElement().getAttribute("FormaDePago") != null
                            ? documento.getRootElement().getAttribute("FormaDePago").getValue()
                            : ""));
            layout.setNoCertificado(documento.getRootElement().getAttribute("noCertificado") != null
                    ? documento.getRootElement().getAttribute("noCertificado").getValue()
                    : (documento.getRootElement().getAttribute("NoCertificado") != null
                            ? documento.getRootElement().getAttribute("NoCertificado").getValue()
                            : ""));
            layout.setCertificado(documento.getRootElement().getAttribute("certificado") != null
                    ? documento.getRootElement().getAttribute("certificado").getValue()
                    : (documento.getRootElement().getAttribute("Certificado") != null
                            ? documento.getRootElement().getAttribute("Certificado").getValue()
                            : ""));
            layout.setSubtotal(documento.getRootElement().getAttribute("subTotal") != null
                    ? documento.getRootElement().getAttribute("subTotal").getValue()
                    : (documento.getRootElement().getAttribute("SubTotal") != null
                            ? documento.getRootElement().getAttribute("SubTotal").getValue()
                            : ""));
            layout.setImporteLetras(NumberToLetterConvert
                    .convertNumberToLetter(documento.getRootElement().getAttribute("total") != null
                            ? documento.getRootElement().getAttribute("total").getValue()
                            : (documento.getRootElement().getAttribute("Total") != null
                                    ? documento.getRootElement().getAttribute("Total").getValue()
                                    : "")));
            layout.setTotal(documento.getRootElement().getAttribute("total") != null
                    ? documento.getRootElement().getAttribute("total").getValue()
                    : (documento.getRootElement().getAttribute("Total") != null
                            ? documento.getRootElement().getAttribute("Total").getValue()
                            : ""));
            layout.setDescuento(documento.getRootElement().getAttribute("descuento") != null
                    ? documento.getRootElement().getAttribute("descuento").getValue()
                    : (documento.getRootElement().getAttribute("Descuento") != null
                            ? documento.getRootElement().getAttribute("Descuento").getValue()
                            : ""));
            layout.setMotivoDescuento(documento.getRootElement().getAttribute("motivoDescuento") != null
                    ? documento.getRootElement().getAttribute("motivoDescuento").getValue()
                    : (documento.getRootElement().getAttribute("MotivoDescuento") != null
                            ? documento.getRootElement().getAttribute("MotivoDescuento").getValue()
                            : ""));
            layout.setTipoCambio(documento.getRootElement().getAttribute("TipoCambio") != null
                    ? documento.getRootElement().getAttribute("TipoCambio").getValue()
                    : (documento.getRootElement().getAttribute("tipoCambio") != null
                            ? documento.getRootElement().getAttribute("tipoCambio").getValue()
                            : ""));
            layout.setMoneda(documento.getRootElement().getAttribute("Moneda") != null
                    ? documento.getRootElement().getAttribute("Moneda").getValue()
                    : (documento.getRootElement().getAttribute("moneda") != null
                            ? documento.getRootElement().getAttribute("moneda").getValue()
                            : ""));
            layout.setMetodoPago(documento.getRootElement().getAttribute("metodoDePago") != null
                    ? documento.getRootElement().getAttribute("metodoDePago").getValue()
                    : (documento.getRootElement().getAttribute("MetodoDePago") != null
                            ? documento.getRootElement().getAttribute("MetodoDePago").getValue()
                            : ""));
            layout.setTipodeComprobante(documento.getRootElement().getAttribute("tipoDeComprobante") != null
                    ? documento.getRootElement().getAttribute("tipoDeComprobante").getValue()
                    : (documento.getRootElement().getAttribute("TipoDeComprobante") != null
                            ? documento.getRootElement().getAttribute("TipoDeComprobante").getValue()
                            : ""));
            layout.setLugarExpedicion(documento.getRootElement().getAttribute("LugarExpedicion") != null
                    ? documento.getRootElement().getAttribute("LugarExpedicion").getValue()
                    : (documento.getRootElement().getAttribute("lugarExpedicion") != null
                            ? documento.getRootElement().getAttribute("lugarExpedicion").getValue()
                            : ""));
            layout.setNumCtaPago(documento.getRootElement().getAttribute("NumCtaPago") != null
                    ? documento.getRootElement().getAttribute("NumCtaPago").getValue()
                    : (documento.getRootElement().getAttribute("numCtaPago") != null
                            ? documento.getRootElement().getAttribute("numCtaPago").getValue()
                            : ""));
            layout.setCondicionesDePago(documento.getRootElement().getAttribute("condicionesDePago") != null
                    ? documento.getRootElement().getAttribute("condicionesDePago").getValue()
                    : (documento.getRootElement().getAttribute("CondicionesDePago") != null
                            ? documento.getRootElement().getAttribute("CondicionesDePago").getValue()
                            : ""));
            Element emisor = documento.getRootElement().getChild("Emisor",
                    Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
            layout.setRFC(emisor.getAttribute("rfc") != null ? emisor.getAttribute("rfc").getValue()
                    : (emisor.getAttribute("Rfc") != null ? emisor.getAttribute("Rfc").getValue() : ""));
            Element domicilioEmisor = emisor.getChild("DomicilioFiscal",
                    Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
            if (domicilioEmisor != null) {
                layout.setCp_df(domicilioEmisor.getAttribute("codigoPostal") != null
                        ? domicilioEmisor.getAttribute("codigoPostal").getValue()
                        : (domicilioEmisor.getAttribute("CodigoPostal") != null
                                ? domicilioEmisor.getAttribute("CodigoPostal").getValue()
                                : ""));
                layout.setPais_df(domicilioEmisor.getAttribute("pais") != null
                        ? domicilioEmisor.getAttribute("pais").getValue()
                        : (domicilioEmisor.getAttribute("Pais") != null
                                ? domicilioEmisor.getAttribute("Pais").getValue()
                                : ""));
                layout.setEstado_df(domicilioEmisor.getAttribute("estado") != null
                        ? domicilioEmisor.getAttribute("estado").getValue()
                        : (domicilioEmisor.getAttribute("Estado") != null
                                ? domicilioEmisor.getAttribute("Estado").getValue()
                                : ""));
                layout.setMunicipio_df(domicilioEmisor.getAttribute("municipio") != null
                        ? domicilioEmisor.getAttribute("municipio").getValue()
                        : (domicilioEmisor.getAttribute("Municipio") != null
                                ? domicilioEmisor.getAttribute("Municipio").getValue()
                                : ""));
                layout.setColonia_df(domicilioEmisor.getAttribute("colonia") != null
                        ? domicilioEmisor.getAttribute("colonia").getValue()
                        : (domicilioEmisor.getAttribute("Colonia") != null
                                ? domicilioEmisor.getAttribute("Colonia").getValue()
                                : ""));
                layout.setNoInterior_df(domicilioEmisor.getAttribute("noInterior") != null
                        ? domicilioEmisor.getAttribute("noInterior").getValue()
                        : (domicilioEmisor.getAttribute("NoInterior") != null
                                ? domicilioEmisor.getAttribute("NoInterior").getValue()
                                : ""));
                layout.setNoExterior_df(domicilioEmisor.getAttribute("noExterior") != null
                        ? domicilioEmisor.getAttribute("noExterior").getValue()
                        : (domicilioEmisor.getAttribute("NoExterior") != null
                                ? domicilioEmisor.getAttribute("NoExterior").getValue()
                                : ""));
                layout.setCalle_df(domicilioEmisor.getAttribute("calle") != null
                        ? domicilioEmisor.getAttribute("calle").getValue()
                        : (domicilioEmisor.getAttribute("Calle") != null
                                ? domicilioEmisor.getAttribute("Calle").getValue()
                                : ""));
                layout.setColonia_df(domicilioEmisor.getAttribute("localidad") != null
                        ? domicilioEmisor.getAttribute("localidad").getValue()
                        : (domicilioEmisor.getAttribute("Localidad") != null
                                ? domicilioEmisor.getAttribute("Localidad").getValue()
                                : ""));
            }
            Element expedidoEn = emisor.getChild("ExpedidoEn",
                    Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
            if (expedidoEn != null) {
                layout.setCp(expedidoEn.getAttribute("codigoPostal") != null
                        ? expedidoEn.getAttribute("codigoPostal").getValue()
                        : (expedidoEn.getAttribute("CodigoPostal") != null
                                ? expedidoEn.getAttribute("CodigoPostal").getValue()
                                : ""));
                layout.setPais(
                        expedidoEn.getAttribute("pais") != null ? expedidoEn.getAttribute("pais").getValue()
                                : (expedidoEn.getAttribute("Pais") != null
                                        ? expedidoEn.getAttribute("Pais").getValue()
                                        : ""));
                layout.setEstado(
                        expedidoEn.getAttribute("estado") != null ? expedidoEn.getAttribute("estado").getValue()
                                : (expedidoEn.getAttribute("Estado") != null
                                        ? expedidoEn.getAttribute("Estado").getValue()
                                        : ""));
                layout.setMunicipio(expedidoEn.getAttribute("municipio") != null
                        ? expedidoEn.getAttribute("municipio").getValue()
                        : (expedidoEn.getAttribute("Municipio") != null
                                ? expedidoEn.getAttribute("Municipio").getValue()
                                : ""));
                layout.setColonia(expedidoEn.getAttribute("colonia") != null
                        ? expedidoEn.getAttribute("colonia").getValue()
                        : (expedidoEn.getAttribute("Colonia") != null
                                ? expedidoEn.getAttribute("Colonia").getValue()
                                : ""));
                layout.setNoInterior(expedidoEn.getAttribute("noInterior") != null
                        ? expedidoEn.getAttribute("noInterior").getValue()
                        : (expedidoEn.getAttribute("NoInterior") != null
                                ? expedidoEn.getAttribute("NoInterior").getValue()
                                : ""));
                layout.setNoExterior(expedidoEn.getAttribute("noExterior") != null
                        ? expedidoEn.getAttribute("noExterior").getValue()
                        : (expedidoEn.getAttribute("NoExterior") != null
                                ? expedidoEn.getAttribute("NoExterior").getValue()
                                : ""));
                layout.setCalle(
                        expedidoEn.getAttribute("calle") != null ? expedidoEn.getAttribute("calle").getValue()
                                : (expedidoEn.getAttribute("Calle") != null
                                        ? expedidoEn.getAttribute("Calle").getValue()
                                        : ""));
            }
            Element regimenFiscal = emisor.getChild("RegimenFiscal",
                    Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
            if (regimenFiscal != null) {
                layout.setRegimenFiscal(regimenFiscal.getAttribute("Regimen") != null
                        ? regimenFiscal.getAttribute("Regimen").getValue()
                        : (regimenFiscal.getAttribute("regimen") != null
                                ? regimenFiscal.getAttribute("regimen").getValue()
                                : ""));
            }
            layout.setNombreEmisor(emisor.getAttribute("nombre") != null
                    ? emisor.getAttribute("nombre").getValue()
                    : (emisor.getAttribute("Nombre") != null ? emisor.getAttribute("Nombre").getValue() : ""));
            Element receptor = documento.getRootElement().getChild("Receptor",
                    Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
            layout.setNombreReceptor(
                    receptor.getAttribute("nombre") != null ? receptor.getAttribute("nombre").getValue()
                            : (receptor.getAttribute("Nombre") != null
                                    ? receptor.getAttribute("Nombre").getValue()
                                    : ""));
            layout.setRfcReceptor(receptor.getAttribute("rfc") != null ? receptor.getAttribute("rfc").getValue()
                    : (receptor.getAttribute("Rfc") != null ? receptor.getAttribute("Rfc").getValue() : ""));
            Element domicilioReceptor = receptor.getChild("Domicilio",
                    Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
            if (domicilioReceptor != null) {
                layout.setCpReceptor(domicilioReceptor.getAttribute("codigoPostal") != null
                        ? domicilioReceptor.getAttribute("codigoPostal").getValue()
                        : (domicilioReceptor.getAttribute("CodigoPostal") != null
                                ? domicilioReceptor.getAttribute("CodigoPostal").getValue()
                                : ""));
                layout.setPaisReceptor(domicilioReceptor.getAttribute("pais") != null
                        ? domicilioReceptor.getAttribute("pais").getValue()
                        : (domicilioReceptor.getAttribute("Pais") != null
                                ? domicilioReceptor.getAttribute("Pais").getValue()
                                : ""));
                layout.setEstadoReceptor(domicilioReceptor.getAttribute("estado") != null
                        ? domicilioReceptor.getAttribute("estado").getValue()
                        : (domicilioReceptor.getAttribute("Estado") != null
                                ? domicilioReceptor.getAttribute("Estado").getValue()
                                : ""));
                layout.setMunicipioReceptor(domicilioReceptor.getAttribute("municipio") != null
                        ? domicilioReceptor.getAttribute("municipio").getValue()
                        : (domicilioReceptor.getAttribute("Municipio") != null
                                ? domicilioReceptor.getAttribute("Municipio").getValue()
                                : ""));
                layout.setColoniaReceptor(domicilioReceptor.getAttribute("colonia") != null
                        ? domicilioReceptor.getAttribute("colonia").getValue()
                        : (domicilioReceptor.getAttribute("Colonia") != null
                                ? domicilioReceptor.getAttribute("Colonia").getValue()
                                : ""));
                layout.setNoInteriorReceptor(domicilioReceptor.getAttribute("noInterior") != null
                        ? domicilioReceptor.getAttribute("noInterior").getValue()
                        : (domicilioReceptor.getAttribute("NoInterior") != null
                                ? domicilioReceptor.getAttribute("NoInterior").getValue()
                                : ""));
                layout.setNoExteriorReceptor(domicilioReceptor.getAttribute("noExterior") != null
                        ? domicilioReceptor.getAttribute("noExterior").getValue()
                        : (domicilioReceptor.getAttribute("NoExterior") != null
                                ? domicilioReceptor.getAttribute("NoExterior").getValue()
                                : ""));
                layout.setCalleReceptor(domicilioReceptor.getAttribute("calle") != null
                        ? domicilioReceptor.getAttribute("calle").getValue()
                        : (domicilioReceptor.getAttribute("Calle") != null
                                ? domicilioReceptor.getAttribute("Calle").getValue()
                                : ""));
            }
            Element impuestos = documento.getRootElement().getChild("Impuestos",
                    Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
            if (impuestos != null) {
                layout.setRetenidos(impuestos.getAttribute("totalImpuestosRetenidos") != null
                        ? impuestos.getAttribute("totalImpuestosRetenidos").getValue()
                        : (impuestos.getAttribute("TotalImpuestosRetenidos") != null
                                ? impuestos.getAttribute("TotalImpuestosRetenidos").getValue()
                                : ""));
                layout.setTrasladados(impuestos.getAttribute("totalImpuestosTrasladados") != null
                        ? impuestos.getAttribute("totalImpuestosTrasladados").getValue()
                        : (impuestos.getAttribute("TotalImpuestosTrasladados") != null
                                ? impuestos.getAttribute("TotalImpuestosTrasladados").getValue()
                                : ""));
                Element retenciones = impuestos.getChild("Retenciones",
                        Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
                if (retenciones != null) {
                    Element retencion = retenciones.getChild("Retencion",
                            Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
                    layout.setImpuestoRetenido(retencion.getAttribute("impuesto") != null
                            ? retencion.getAttribute("impuesto").getValue()
                            : (retencion.getAttribute("Impuesto") != null
                                    ? retencion.getAttribute("Impuesto").getValue()
                                    : ""));
                    layout.setImporteRetenido(retencion.getAttribute("importe") != null
                            ? retencion.getAttribute("importe").getValue()
                            : (retencion.getAttribute("Importe") != null
                                    ? retencion.getAttribute("Importe").getValue()
                                    : ""));
                }
                Element trasladados = impuestos.getChild("Trasladados",
                        Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
                if (trasladados != null) {
                    Element trasladado = trasladados.getChild("Trasladado",
                            Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
                    layout.setImpuestoTrasladado(trasladado.getAttribute("impuesto") != null
                            ? trasladado.getAttribute("impuesto").getValue()
                            : (trasladado.getAttribute("Impuesto") != null
                                    ? trasladado.getAttribute("Impuesto").getValue()
                                    : ""));
                    layout.setImporteTrasladado(trasladado.getAttribute("importe") != null
                            ? trasladado.getAttribute("importe").getValue()
                            : (trasladado.getAttribute("Importe") != null
                                    ? trasladado.getAttribute("Importe").getValue()
                                    : ""));
                    layout.setTasaTrasladado(
                            trasladado.getAttribute("tasa") != null ? trasladado.getAttribute("tasa").getValue()
                                    : (trasladado.getAttribute("Tasa") != null
                                            ? trasladado.getAttribute("Tasa").getValue()
                                            : ""));
                }
            } else {
                layout.setRetenidos("");
                layout.setTrasladados("");
                layout.setImpuestoRetenido("");
                layout.setImporteRetenido("");
                layout.setImpuestoTrasladado("");
                layout.setImporteTrasladado("");
                layout.setTasaTrasladado("");
            }
            Element complemento = documento.getRootElement().getChild("Complemento",
                    Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
            Element nomina = complemento.getChild("Nomina",
                    Namespace.getNamespace("nomina", "http://www.sat.gob.mx/nomina"));

            Element conceptos = documento.getRootElement().getChild("Conceptos",
                    Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));

            if (nomina != null) {
                Element concepto = conceptos.getChild("Concepto",
                        Namespace.getNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"));
                if (concepto != null) {
                    layout.setImporte(concepto.getAttribute("importe") != null
                            ? concepto.getAttribute("importe").getValue()
                            : (concepto.getAttribute("Importe") != null
                                    ? concepto.getAttribute("Importe").getValue()
                                    : ""));
                    layout.setValorUnitario(concepto.getAttribute("valorUnitario") != null
                            ? concepto.getAttribute("valorUnitario").getValue()
                            : (concepto.getAttribute("ValorUnitario") != null
                                    ? concepto.getAttribute("ValorUnitario").getValue()
                                    : ""));
                    layout.setDescripcion(concepto.getAttribute("descripcion") != null
                            ? concepto.getAttribute("descripcion").getValue()
                            : (concepto.getAttribute("Descripcion") != null
                                    ? concepto.getAttribute("Descripcion").getValue()
                                    : ""));
                    layout.setUnidad(
                            concepto.getAttribute("unidad") != null ? concepto.getAttribute("unidad").getValue()
                                    : (concepto.getAttribute("Unidad") != null
                                            ? concepto.getAttribute("Unidad").getValue()
                                            : ""));
                    layout.setCantidad(concepto.getAttribute("cantidad") != null
                            ? concepto.getAttribute("cantidad").getValue()
                            : (concepto.getAttribute("Cantidad") != null
                                    ? concepto.getAttribute("Cantidad").getValue()
                                    : ""));
                }
                layout.setComprobanteTipo("NOMINA");
                layout.setPuesto(
                        nomina.getAttribute("Puesto") != null ? nomina.getAttribute("Puesto").getValue()
                                : (nomina.getAttribute("puesto") != null
                                        ? nomina.getAttribute("puesto").getValue()
                                        : ""));
                layout.setFechaInicioRelLaboral(nomina.getAttribute("FechaInicioRelLaboral") != null
                        ? nomina.getAttribute("FechaInicioRelLaboral").getValue()
                        : (nomina.getAttribute("fechaInicioRelLaboral") != null
                                ? nomina.getAttribute("fechaInicioRelLaboral").getValue()
                                : ""));
                layout.setClabe(nomina.getAttribute("CLABE") != null ? nomina.getAttribute("CLABE").getValue()
                        : (nomina.getAttribute("clabe") != null ? nomina.getAttribute("clabe").getValue()
                                : ""));
                layout.setBanco(nomina.getAttribute("Banco") != null ? nomina.getAttribute("Banco").getValue()
                        : (nomina.getAttribute("banco") != null ? nomina.getAttribute("banco").getValue()
                                : ""));
                layout.setTipoContrato(nomina.getAttribute("TipoContrato") != null
                        ? nomina.getAttribute("TipoContrato").getValue()
                        : (nomina.getAttribute("tipoContrato") != null
                                ? nomina.getAttribute("tipoContrato").getValue()
                                : ""));
                layout.setRiesgoPuesto(nomina.getAttribute("RiesgoPuesto") != null
                        ? nomina.getAttribute("RiesgoPuesto").getValue()
                        : (nomina.getAttribute("riesgoPuesto") != null
                                ? nomina.getAttribute("riesgoPuesto").getValue()
                                : ""));
                layout.setSalarioDiarioIntegrado(nomina.getAttribute("SalarioDiarioIntegrado") != null
                        ? nomina.getAttribute("SalarioDiarioIntegrado").getValue()
                        : (nomina.getAttribute("salarioDiarioIntegrado") != null
                                ? nomina.getAttribute("salarioDiarioIntegrado").getValue()
                                : ""));
                layout.setSalarioBaseCotApor(nomina.getAttribute("SalarioBaseCotApor") != null
                        ? nomina.getAttribute("SalarioBaseCotApor").getValue()
                        : (nomina.getAttribute("salarioBaseCotApor") != null
                                ? nomina.getAttribute("salarioBaseCotApor").getValue()
                                : ""));
                layout.setTipoJornada(nomina.getAttribute("TipoJornada") != null
                        ? nomina.getAttribute("TipoJornada").getValue()
                        : (nomina.getAttribute("tipoJornada") != null
                                ? nomina.getAttribute("tipoJornada").getValue()
                                : ""));
                layout.setPeriodicidadPago(nomina.getAttribute("PeriodicidadPago") != null
                        ? nomina.getAttribute("PeriodicidadPago").getValue()
                        : (nomina.getAttribute("periodicidadPago") != null
                                ? nomina.getAttribute("periodicidadPago").getValue()
                                : ""));
                layout.setCurp(nomina.getAttribute("CURP") != null ? nomina.getAttribute("CURP").getValue()
                        : (nomina.getAttribute("curp") != null ? nomina.getAttribute("curp").getValue() : ""));
                layout.setTipoRegimen(nomina.getAttribute("TipoRegimen") != null
                        ? nomina.getAttribute("TipoRegimen").getValue()
                        : (nomina.getAttribute("tipoRegimen") != null
                                ? nomina.getAttribute("tipoRegimen").getValue()
                                : ""));
                layout.setNumEmpleado(nomina.getAttribute("NumEmpleado") != null
                        ? nomina.getAttribute("NumEmpleado").getValue()
                        : (nomina.getAttribute("numEmpleado") != null
                                ? nomina.getAttribute("numEmpleado").getValue()
                                : ""));
                layout.setVersionN(
                        nomina.getAttribute("Version") != null ? nomina.getAttribute("Version").getValue()
                                : (nomina.getAttribute("version") != null
                                        ? nomina.getAttribute("version").getValue()
                                        : ""));
                layout.setRegistroPatronal(nomina.getAttribute("RegistroPatronal") != null
                        ? nomina.getAttribute("RegistroPatronal").getValue()
                        : (nomina.getAttribute("registroPatronal") != null
                                ? nomina.getAttribute("registroPatronal").getValue()
                                : ""));
                layout.setNss(nomina.getAttribute("NumSeguridadSocial") != null
                        ? nomina.getAttribute("NumSeguridadSocial").getValue()
                        : (nomina.getAttribute("numSeguridadSocial") != null
                                ? nomina.getAttribute("numSeguridadSocial").getValue()
                                : ""));
                layout.setNumDiasPagados(nomina.getAttribute("NumDiasPagados") != null
                        ? nomina.getAttribute("NumDiasPagados").getValue()
                        : (nomina.getAttribute("numDiasPagados") != null
                                ? nomina.getAttribute("numDiasPagados").getValue()
                                : ""));
                layout.setDepartamento(nomina.getAttribute("Departamento") != null
                        ? nomina.getAttribute("Departamento").getValue()
                        : (nomina.getAttribute("departamento") != null
                                ? nomina.getAttribute("departamento").getValue()
                                : ""));
                layout.setFechaFinalPago(nomina.getAttribute("FechaFinalPago") != null
                        ? nomina.getAttribute("FechaFinalPago").getValue()
                        : (nomina.getAttribute("fechaFinalPago") != null
                                ? nomina.getAttribute("fechaFinalPago").getValue()
                                : ""));
                layout.setFechaPago(
                        nomina.getAttribute("FechaPago") != null ? nomina.getAttribute("FechaPago").getValue()
                                : (nomina.getAttribute("fechaPago") != null
                                        ? nomina.getAttribute("fechaPago").getValue()
                                        : ""));
                layout.setFechaInicialPago(nomina.getAttribute("FechaInicialPago") != null
                        ? nomina.getAttribute("FechaInicialPago").getValue()
                        : (nomina.getAttribute("fechaInicialPago") != null
                                ? nomina.getAttribute("fechaInicialPago").getValue()
                                : ""));
                Element persepciones = nomina.getChild("Percepciones",
                        Namespace.getNamespace("nomina", "http://www.sat.gob.mx/nomina"));

                if (persepciones != null) {
                    layout.setTotalExentoP(persepciones.getAttribute("TotalExento") != null
                            ? persepciones.getAttribute("TotalExento").getValue()
                            : (persepciones.getAttribute("totalExento") != null
                                    ? persepciones.getAttribute("totalExento").getValue()
                                    : ""));
                    layout.setTotalGravadoP(persepciones.getAttribute("TotalGravado") != null
                            ? persepciones.getAttribute("TotalGravado").getValue()
                            : (persepciones.getAttribute("totalGravado") != null
                                    ? persepciones.getAttribute("totalGravado").getValue()
                                    : ""));
                    for (Element persepcion : persepciones.getChildren()) {
                        NominaDetalle nominaDetalle = new NominaDetalle();
                        nominaDetalle.setTipo(persepcion.getAttribute("TipoPercepcion") != null
                                ? persepcion.getAttribute("TipoPercepcion").getValue()
                                : (persepcion.getAttribute("tipoPercepcion") != null
                                        ? persepcion.getAttribute("tipoPercepcion").getValue()
                                        : ""));
                        nominaDetalle.setConcepto(persepcion.getAttribute("Concepto") != null
                                ? persepcion.getAttribute("Concepto").getValue()
                                : (persepcion.getAttribute("concepto") != null
                                        ? persepcion.getAttribute("concepto").getValue()
                                        : ""));
                        nominaDetalle.setClave(persepcion.getAttribute("Clave") != null
                                ? persepcion.getAttribute("Clave").getValue()
                                : (persepcion.getAttribute("clave") != null
                                        ? persepcion.getAttribute("clave").getValue()
                                        : ""));
                        nominaDetalle.setImporteGravado(persepcion.getAttribute("ImporteGravado") != null
                                ? persepcion.getAttribute("ImporteGravado").getValue()
                                : (persepcion.getAttribute("importeGravado") != null
                                        ? persepcion.getAttribute("importeGravado").getValue()
                                        : ""));
                        nominaDetalle.setImporteExento(persepcion.getAttribute("ImporteExento") != null
                                ? persepcion.getAttribute("ImporteExento").getValue()
                                : (persepcion.getAttribute("importeExento") != null
                                        ? persepcion.getAttribute("importeExento").getValue()
                                        : ""));
                        nominaDetalle.setTipoConcepto("1");
                        layout.addNominaDetalle(nominaDetalle);
                    }
                }
                Element deducciones = nomina.getChild("Deducciones",
                        Namespace.getNamespace("nomina", "http://www.sat.gob.mx/nomina"));
                if (deducciones != null) {
                    layout.setTotalExentoD(deducciones.getAttribute("TotalExento") != null
                            ? deducciones.getAttribute("TotalExento").getValue()
                            : (deducciones.getAttribute("totalExento") != null
                                    ? deducciones.getAttribute("totalExento").getValue()
                                    : ""));
                    layout.setTotalGravadoD(deducciones.getAttribute("TotalGravado") != null
                            ? deducciones.getAttribute("TotalGravado").getValue()
                            : (deducciones.getAttribute("totalGravado") != null
                                    ? deducciones.getAttribute("totalGravado").getValue()
                                    : ""));
                    for (Element deduccion : deducciones.getChildren()) {
                        NominaDetalle nominaDetalle = new NominaDetalle();
                        nominaDetalle.setTipo(deduccion.getAttribute("TipoDeduccion") != null
                                ? deduccion.getAttribute("TipoDeduccion").getValue()
                                : (deduccion.getAttribute("tipoDeduccion") != null
                                        ? deduccion.getAttribute("tipoDeduccion").getValue()
                                        : ""));
                        nominaDetalle.setConcepto(deduccion.getAttribute("Concepto") != null
                                ? deduccion.getAttribute("Concepto").getValue()
                                : (deduccion.getAttribute("concepto") != null
                                        ? deduccion.getAttribute("concepto").getValue()
                                        : ""));
                        nominaDetalle.setClave(deduccion.getAttribute("Clave") != null
                                ? deduccion.getAttribute("Clave").getValue()
                                : (deduccion.getAttribute("clave") != null
                                        ? deduccion.getAttribute("clave").getValue()
                                        : ""));
                        nominaDetalle.setImporteGravado(deduccion.getAttribute("ImporteGravado") != null
                                ? deduccion.getAttribute("ImporteGravado").getValue()
                                : (deduccion.getAttribute("importeGravado") != null
                                        ? deduccion.getAttribute("importeGravado").getValue()
                                        : ""));
                        nominaDetalle.setImporteExento(deduccion.getAttribute("ImporteExento") != null
                                ? deduccion.getAttribute("ImporteExento").getValue()
                                : (deduccion.getAttribute("importeExento") != null
                                        ? deduccion.getAttribute("importeExento").getValue()
                                        : ""));
                        nominaDetalle.setTipoConcepto("2");
                        layout.addNominaDetalle(nominaDetalle);
                    }
                }
            } else {
                layout.setComprobanteTipo("FACTURA");
                for (Element concepto : conceptos.getChildren()) {
                    IngresoDetalle ingresoDetalle = new IngresoDetalle();

                    ingresoDetalle.setImporte(concepto.getAttribute("importe") != null
                            ? concepto.getAttribute("importe").getValue()
                            : (concepto.getAttribute("importe") != null
                                    ? concepto.getAttribute("importe").getValue()
                                    : ""));
                    ingresoDetalle.setValorUnitario(concepto.getAttribute("valorUnitario") != null
                            ? concepto.getAttribute("valorUnitario").getValue()
                            : (concepto.getAttribute("valorUnitario") != null
                                    ? concepto.getAttribute("valorUnitario").getValue()
                                    : ""));
                    ingresoDetalle.setDescripcion(concepto.getAttribute("descripcion") != null
                            ? concepto.getAttribute("descripcion").getValue()
                            : (concepto.getAttribute("descripcion") != null
                                    ? concepto.getAttribute("descripcion").getValue()
                                    : ""));
                    ingresoDetalle.setUnidad(
                            concepto.getAttribute("unidad") != null ? concepto.getAttribute("unidad").getValue()
                                    : (concepto.getAttribute("unidad") != null
                                            ? concepto.getAttribute("unidad").getValue()
                                            : ""));
                    ingresoDetalle.setCantidad(concepto.getAttribute("cantidad") != null
                            ? concepto.getAttribute("cantidad").getValue()
                            : (concepto.getAttribute("cantidad") != null
                                    ? concepto.getAttribute("cantidad").getValue()
                                    : ""));
                    layout.addIngresoDetalle(ingresoDetalle);
                }
            }
            Element timbreFiscal = complemento.getChild("TimbreFiscalDigital",
                    Namespace.getNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital"));
            if (timbreFiscal != null) {
                layout.setUuid(
                        timbreFiscal.getAttribute("UUID") != null ? timbreFiscal.getAttribute("UUID").getValue()
                                : (timbreFiscal.getAttribute("Uuid") != null
                                        ? timbreFiscal.getAttribute("Uuid").getValue()
                                        : ""));
                layout.setFechaTimbrado(timbreFiscal.getAttribute("FechaTimbrado") != null
                        ? timbreFiscal.getAttribute("FechaTimbrado").getValue()
                        : (timbreFiscal.getAttribute("fechaTimbrado") != null
                                ? timbreFiscal.getAttribute("fechaTimbrado").getValue()
                                : ""));
                layout.setSelloCfd(timbreFiscal.getAttribute("selloCFD") != null
                        ? timbreFiscal.getAttribute("selloCFD").getValue()
                        : (timbreFiscal.getAttribute("SelloCFD") != null
                                ? timbreFiscal.getAttribute("SelloCFD").getValue()
                                : ""));
                layout.setNoCertificadoSat(timbreFiscal.getAttribute("noCertificadoSAT") != null
                        ? timbreFiscal.getAttribute("noCertificadoSAT").getValue()
                        : (timbreFiscal.getAttribute("NoCertificadoSAT") != null
                                ? timbreFiscal.getAttribute("NoCertificadoSAT").getValue()
                                : ""));
                layout.setSelloSat(timbreFiscal.getAttribute("selloSAT") != null
                        ? timbreFiscal.getAttribute("selloSAT").getValue()
                        : (timbreFiscal.getAttribute("SelloSAT") != null
                                ? timbreFiscal.getAttribute("SelloSAT").getValue()
                                : ""));
            }

            layout.setCadenaOriginal(
                    "||" + layout.getVersion() + "|" + layout.getUuid() + "|" + layout.getFechaTimbrado() + "|"
                            + layout.getSelloCfd() + "|" + layout.getNoCertificadoSat() + "||");
        } catch (JDOMException e) {
            logger.log(Level.SEVERE, "{0}: {1}", new Object[] { nombreArchivo, e.getMessage() });
            layout = null;
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "{0}: {1}", new Object[] { nombreArchivo, e.getMessage() });
        layout = null;
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "{0}: {1}", new Object[] { nombreArchivo, ex.getMessage() });
        layout = null;
    }
    if (showLog)
        logger.log(Level.INFO, "Fin parse ");
    return layout;
}

From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationDstructureModuleImpl.java

License:Open Source License

@Override
public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationDstructureException {
    // Ausgabe SIARD-Modul Ersichtlich das KOST-Val arbeitet
    System.out.print("D   ");
    System.out.print("\r");
    int onWork = 41;

    boolean valid = true;
    try {//from ww w. ja v a  2  s .com
        /* Extract the metadata.xml from the temporare work folder and build a jdom document */
        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        pathToWorkDir = pathToWorkDir + File.separator + "SIARD";
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());
        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each schema and table entry verify existence in temporary
         * extracted structure */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");
        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            valid = validateSchema(schema, ns, pathToWorkDir);
            if (onWork == 41) {
                onWork = 2;
                System.out.print("D-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("D\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("D|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("D/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, ioe.getMessage() + " (IOException)"));
    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (JDOMException)"));
    }

    return valid;
}

From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationEcolumnModuleImpl.java

License:Open Source License

private boolean prepareXMLAccess(ValidationContext validationContext)
        throws JDOMException, IOException, Exception {
    boolean successfullyCommitted = false;
    Properties properties = validationContext.getValidationProperties();
    File metadataXML = validationContext.getMetadataXML();
    InputStream inputStream = new FileInputStream(metadataXML);
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(inputStream);
    // Assigning JDOM Document to the validation context
    validationContext.setMetadataXMLDocument(document);
    String xmlPrefix = properties.getProperty("module.e.metadata.xml.prefix");
    String xsdPrefix = properties.getProperty("module.e.table.xsd.prefix");
    // Setting the namespaces to access metadata.xml and the different table.xsd
    Element rootElement = document.getRootElement();
    String namespaceURI = rootElement.getNamespaceURI();
    Namespace xmlNamespace = Namespace.getNamespace(xmlPrefix, namespaceURI);
    Namespace xsdNamespace = Namespace.getNamespace(xsdPrefix, namespaceURI);
    // Assigning prefix to the validation context
    validationContext.setXmlPrefix(xmlPrefix);
    validationContext.setXsdPrefix(xsdPrefix);
    // Assigning namespace info to the validation context
    validationContext.setXmlNamespace(xmlNamespace);
    validationContext.setXsdNamespace(xsdNamespace);
    if (validationContext.getXmlNamespace() != null && validationContext.getXsdNamespace() != null
            && validationContext.getXmlPrefix() != null && validationContext.getXsdPrefix() != null
            && validationContext.getMetadataXMLDocument() != null
            && validationContext.getValidationProperties() != null) {
        this.setValidationContext(validationContext);
        successfullyCommitted = true;/*from  ww  w. j  a v  a  2  s .co  m*/
    } else {
        successfullyCommitted = false;
        this.setValidationContext(null);
        throw new Exception();
    }
    return successfullyCommitted;
}

From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationEcolumnModuleImpl.java

License:Open Source License

private boolean prepareValidationData(ValidationContext validationContext)
        throws JDOMException, IOException, Exception {
    int onWork = 41;
    boolean successfullyCommitted = false;
    Properties properties = validationContext.getValidationProperties();
    // Gets the tables to be validated
    List<SiardTable> siardTables = new ArrayList<SiardTable>();
    Document document = validationContext.getMetadataXMLDocument();
    Element rootElement = document.getRootElement();
    String workingDirectory = validationContext.getConfigurationService().getPathToWorkDir();
    String siardSchemasElementsName = properties.getProperty("module.e.siard.metadata.xml.schemas.name");
    // Gets the list of <schemas> elements from metadata.xml
    List<Element> siardSchemasElements = rootElement.getChildren(siardSchemasElementsName,
            validationContext.getXmlNamespace());
    for (Element siardSchemasElement : siardSchemasElements) {
        // Gets the list of <schema> elements from metadata.xml
        List<Element> siardSchemaElements = siardSchemasElement.getChildren(
                properties.getProperty("module.e.siard.metadata.xml.schema.name"),
                validationContext.getXmlNamespace());
        // Iterating over all <schema> elements
        for (Element siardSchemaElement : siardSchemaElements) {
            String schemaFolderName = siardSchemaElement
                    .getChild(properties.getProperty("module.e.siard.metadata.xml.schema.folder.name"),
                            validationContext.getXmlNamespace())
                    .getValue();/*  w ww  .  j ava2 s  . c o m*/
            Element siardTablesElement = siardSchemaElement.getChild(
                    properties.getProperty("module.e.siard.metadata.xml.tables.name"),
                    validationContext.getXmlNamespace());
            List<Element> siardTableElements = siardTablesElement.getChildren(
                    properties.getProperty("module.e.siard.metadata.xml.table.name"),
                    validationContext.getXmlNamespace());
            // Iterating over all containing table elements
            for (Element siardTableElement : siardTableElements) {
                Element siardColumnsElement = siardTableElement.getChild(
                        properties.getProperty("module.e.siard.metadata.xml.columns.name"),
                        validationContext.getXmlNamespace());
                List<Element> siardColumnElements = siardColumnsElement.getChildren(
                        properties.getProperty("module.e.siard.metadata.xml.column.name"),
                        validationContext.getXmlNamespace());
                String tableName = siardTableElement
                        .getChild(properties.getProperty("module.e.siard.metadata.xml.table.folder.name"),
                                validationContext.getXmlNamespace())
                        .getValue();
                SiardTable siardTable = new SiardTable();
                siardTable.setMetadataXMLElements(siardColumnElements);
                siardTable.setTableName(tableName);
                String siardTableFolderName = siardTableElement
                        .getChild(properties.getProperty("module.e.siard.metadata.xml.table.folder.name"),
                                validationContext.getXmlNamespace())
                        .getValue();
                StringBuilder pathToTableSchema = new StringBuilder();
                // Preparing access to the according XML schema file
                pathToTableSchema.append(workingDirectory);
                pathToTableSchema.append(File.separator);
                pathToTableSchema.append(properties.getProperty("module.e.siard.path.to.content"));
                pathToTableSchema.append(File.separator);
                pathToTableSchema.append(schemaFolderName.replaceAll(" ", ""));
                pathToTableSchema.append(File.separator);
                pathToTableSchema.append(siardTableFolderName.replaceAll(" ", ""));
                pathToTableSchema.append(File.separator);
                pathToTableSchema.append(siardTableFolderName.replaceAll(" ", ""));
                pathToTableSchema.append(properties.getProperty("module.e.siard.table.xsd.file.extension"));
                // Retrieve the according XML schema
                File tableSchema = validationContext.getSiardFiles().get(pathToTableSchema.toString());
                SAXBuilder builder = new SAXBuilder();
                Document tableSchemaDocument = builder.build(tableSchema);
                Element tableSchemaRootElement = tableSchemaDocument.getRootElement();
                Namespace namespace = tableSchemaRootElement.getNamespace();
                // Getting the tags from XML schema to be validated
                Element tableSchemaComplexType = tableSchemaRootElement
                        .getChild(properties.getProperty("module.e.siard.table.xsd.complexType"), namespace);
                Element tableSchemaComplexTypeSequence = tableSchemaComplexType
                        .getChild(properties.getProperty("module.e.siard.table.xsd.sequence"), namespace);
                List<Element> tableSchemaComplexTypeElements = tableSchemaComplexTypeSequence
                        .getChildren(properties.getProperty("module.e.siard.table.xsd.element"), namespace);
                siardTable.setTableXSDElements(tableSchemaComplexTypeElements);
                siardTables.add(siardTable);
                // Writing back the List off all SIARD tables to the validation context
                validationContext.setSiardTables(siardTables);
            }
        }
        if (onWork == 41) {
            onWork = 2;
            System.out.print("E-   ");
            System.out.print("\r");
        } else if (onWork == 11) {
            onWork = 12;
            System.out.print("E\\   ");
            System.out.print("\r");
        } else if (onWork == 21) {
            onWork = 22;
            System.out.print("E|   ");
            System.out.print("\r");
        } else if (onWork == 31) {
            onWork = 32;
            System.out.print("E/   ");
            System.out.print("\r");
        } else {
            onWork = onWork + 1;
        }
    }
    if (validationContext.getSiardTables().size() > 0) {
        this.setValidationContext(validationContext);
        successfullyCommitted = true;
    } else {
        this.setValidationContext(null);
        successfullyCommitted = false;
        throw new Exception();
    }
    return successfullyCommitted;
}

From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationFrowModuleImpl.java

License:Open Source License

@Override
public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationFrowException {
    // Ausgabe SIARD-Modul Ersichtlich das KOST-Val arbeitet
    System.out.print("F   ");
    System.out.print("\r");
    int onWork = 41;

    boolean valid = true;
    try {/*  ww  w .  j  a va  2  s .co m*/
        /* Extract the metadata.xml from the temporare work folder and build a jdom document */
        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        pathToWorkDir = pathToWorkDir + File.separator + "SIARD";
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());
        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each schema and table entry verify existence in temporary
         * extracted structure and compare the rownumber */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");
        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            valid = validateSchema(schema, ns, pathToWorkDir);
            if (onWork == 41) {
                onWork = 2;
                System.out.print("F-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("F\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("F|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("F/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, ioe.getMessage() + " (IOException)"));
    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (JDOMException)"));
    }

    return valid;
}

From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationGtableModuleImpl.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from w w  w.  ja  va 2s .c o m
public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationGtableException {
    // Ausgabe SIARD-Modul Ersichtlich das KOST-Val arbeitet
    System.out.print("G   ");
    System.out.print("\r");
    int onWork = 41;

    boolean valid = true;
    try {
        /* Extract the metadata.xml from the temporare work folder and build a jdom document */

        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        pathToWorkDir = pathToWorkDir + File.separator + "SIARD";
        /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
         * entsprechenden Modul die property anzugeben: <property name="configurationService"
         * ref="configurationService" /> */
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());

        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        // declare ArrayLists
        List listSchemas = new ArrayList();
        List listTables = new ArrayList();
        List listColumns = new ArrayList();

        /* read the document and for each schema and table entry verify existence in temporary
         * extracted structure */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");

        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            String schemaName = schema.getChild("name", ns).getText();

            String lsSch = (new StringBuilder().append(schemaName).toString());

            // select table elements and loop
            List<Element> tables = schema.getChild("tables", ns).getChildren("table", ns);
            for (Element table : tables) {
                String tableName = table.getChild("name", ns).getText();

                // Concatenate schema and table
                String lsTab = (new StringBuilder().append(schemaName).append(" / ").append(tableName)
                        .toString());

                // select column elements and loop
                List<Element> columns = table.getChild("columns", ns).getChildren("column", ns);
                for (Element column : columns) {
                    String columnName = column.getChild("name", ns).getText();

                    // Concatenate schema, table and column
                    String lsCol = (new StringBuilder().append(schemaName).append(" / ").append(tableName)
                            .append(" / ").append(columnName).toString());
                    listColumns.add(lsCol);
                    // concatenating Strings
                }
                listTables.add(lsTab);
                // concatenating Strings (table names)
                if (onWork == 41) {
                    onWork = 2;
                    System.out.print("G-   ");
                    System.out.print("\r");
                } else if (onWork == 11) {
                    onWork = 12;
                    System.out.print("G\\   ");
                    System.out.print("\r");
                } else if (onWork == 21) {
                    onWork = 22;
                    System.out.print("G|   ");
                    System.out.print("\r");
                } else if (onWork == 31) {
                    onWork = 32;
                    System.out.print("G/   ");
                    System.out.print("\r");
                } else {
                    onWork = onWork + 1;
                }
            }
            listSchemas.add(lsSch);
            // concatenating Strings (schema names)
        }
        HashSet hashSchemas = new HashSet(); // check for duplicate schemas
        for (Object value : listSchemas)
            if (!hashSchemas.add(value)) {
                valid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_SIARD)
                        + getTextResourceService().getText(MESSAGE_XML_G_DUPLICATE_SCHEMA, value));
            }
        HashSet hashTables = new HashSet(); // check for duplicate tables
        for (Object value : listTables)
            if (!hashTables.add(value)) {
                valid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_SIARD)
                        + getTextResourceService().getText(MESSAGE_XML_G_DUPLICATE_TABLE, value));
            }
        HashSet hashColumns = new HashSet(); // check for duplicate columns
        for (Object value : listColumns)
            if (!hashColumns.add(value)) {
                valid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_SIARD)
                        + getTextResourceService().getText(MESSAGE_XML_G_DUPLICATE_COLUMN, value));
            }

    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, ioe.getMessage() + " (IOException)"));

    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (JDOMException)"));
        return valid;
    }
    return valid;
}

From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationHcontentModuleImpl.java

License:Open Source License

@Override
public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationHcontentException {
    // Ausgabe SIARD-Modul Ersichtlich das KOST-Val arbeitet
    System.out.print("H   ");
    System.out.print("\r");
    int onWork = 41;

    boolean valid = true;
    try {//from   w w  w.j  a v  a2 s  .  c  o m
        /* Extract the metadata.xml from the temporary work folder and build a jdom document */
        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        pathToWorkDir = pathToWorkDir + File.separator + "SIARD";
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());
        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each schema and table entry verify existence in temporary
         * extracted structure */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");
        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            Element schemaFolder = schema.getChild("folder", ns);
            File schemaPath = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("content")
                    .append(File.separator).append(schemaFolder.getText()).toString());
            if (schemaPath.isDirectory()) {
                Element[] tables = schema.getChild("tables", ns).getChildren("table", ns)
                        .toArray(new Element[0]);
                for (Element table : tables) {
                    Element tableFolder = table.getChild("folder", ns);
                    File tablePath = new File(new StringBuilder(schemaPath.getAbsolutePath())
                            .append(File.separator).append(tableFolder.getText()).toString());
                    if (tablePath.isDirectory()) {
                        File tableXml = new File(new StringBuilder(tablePath.getAbsolutePath())
                                .append(File.separator).append(tableFolder.getText() + ".xml").toString());
                        File tableXsd = new File(new StringBuilder(tablePath.getAbsolutePath())
                                .append(File.separator).append(tableFolder.getText() + ".xsd").toString());
                        // TODO: hier erfolgt die Validerung
                        if (verifyRowCount(tableXml, tableXsd)) {

                            // valid = validate1( tableXml, tableXsd ) && valid;

                            // xmllint via cmd
                            // resources\xmllint\xmllint --noout --stream --schema tableXsd tableXml
                            try {
                                // Pfad zum Programm xmllint existiert die Dateien?
                                String pathToxmllintExe = "resources" + File.separator + "xmllint"
                                        + File.separator + "xmllint.exe";
                                String pathToxmllintDll1 = "resources" + File.separator + "xmllint"
                                        + File.separator + "iconv.dll";
                                String pathToxmllintDll2 = "resources" + File.separator + "xmllint"
                                        + File.separator + "libxml2.dll";
                                String pathToxmllintDll3 = "resources" + File.separator + "xmllint"
                                        + File.separator + "zlib1.dll";

                                File fpathToxmllintExe = new File(pathToxmllintExe);
                                File fpathToxmllintDll1 = new File(pathToxmllintDll1);
                                File fpathToxmllintDll2 = new File(pathToxmllintDll2);
                                File fpathToxmllintDll3 = new File(pathToxmllintDll3);
                                if (!fpathToxmllintExe.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT1_MISSING));
                                    valid = false;
                                } else if (!fpathToxmllintDll1.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT2_MISSING));
                                    valid = false;
                                } else if (!fpathToxmllintDll2.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT3_MISSING));
                                    valid = false;
                                } else if (!fpathToxmllintDll3.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT4_MISSING));
                                    valid = false;
                                } else {

                                    StringBuffer command = new StringBuffer("resources" + File.separator
                                            + "xmllint" + File.separator + "xmllint ");
                                    command.append("--noout --stream ");
                                    command.append(" --schema ");
                                    command.append(" ");
                                    command.append("\"");
                                    command.append(tableXsd.getAbsolutePath());
                                    command.append("\"");
                                    command.append(" ");
                                    command.append("\"");
                                    command.append(tableXml.getAbsolutePath());
                                    command.append("\"");

                                    Process proc = null;
                                    Runtime rt = null;

                                    try {
                                        File outTableXml = new File(pathToWorkDir + File.separator + "SIARD_H_"
                                                + tableXml.getName() + ".txt");

                                        Util.switchOffConsoleToTxt(outTableXml);

                                        rt = Runtime.getRuntime();
                                        proc = rt.exec(command.toString().split(" "));
                                        // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden
                                        // ist!

                                        // Fehleroutput holen

                                        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(),
                                                "ERROR-" + tableXml.getName());

                                        // Output holen
                                        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(),
                                                "OUTPUT-" + tableXml.getName());

                                        // Threads starten
                                        errorGobbler.start();
                                        outputGobbler.start();

                                        // Warte, bis wget fertig ist 0 = Alles io
                                        int exitStatus = proc.waitFor();

                                        // 200ms warten bis die Konsole umgeschaltet wird, damit wirklich alles im
                                        // file landet
                                        Thread.sleep(200);
                                        Util.switchOnConsole();

                                        if (0 != exitStatus) {
                                            // message.xml.h.invalid.xml = <Message>{0} ist invalid zu
                                            // {1}</Message></Error>
                                            getMessageService().logError(
                                                    getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                                                            + getTextResourceService().getText(
                                                                    MESSAGE_XML_H_INVALID_XML,
                                                                    tableXml.getName(), tableXsd.getName()));
                                            valid = false;

                                            // Fehlermeldung aus outTableXml auslesen

                                            BufferedReader br = new BufferedReader(new FileReader(outTableXml));
                                            try {
                                                String line = br.readLine();
                                                String linePrev = null;
                                                /* Fehlermeldungen holen, ausser die letzte, die besagt, dass es invalide
                                                 * ist (wurde bereits oben in D, F,E ausgegeben */
                                                while (line != null) {
                                                    if (linePrev != null) {
                                                        getMessageService().logError(getTextResourceService()
                                                                .getText(MESSAGE_XML_MODUL_H_SIARD)
                                                                + getTextResourceService().getText(
                                                                        MESSAGE_XML_H_INVALID_ERROR, linePrev));
                                                    }
                                                    linePrev = line;
                                                    line = br.readLine();
                                                }
                                            } finally {
                                                br.close();

                                                /* Konsole zuerst einmal noch umleiten und die Streams beenden, damit die
                                                 * dateien gelscht werden knnen */
                                                Util.switchOffConsoleToTxtClose(outTableXml);
                                                System.out.println(" . ");
                                                Util.switchOnConsole();
                                                Util.deleteFile(outTableXml);

                                            }
                                        } else {
                                            /* Konsole zuerst einmal noch umleiten und die Streams beenden, damit die
                                             * dateien gelscht werden knnen */
                                            Util.switchOffConsoleToTxtClose(outTableXml);
                                            System.out.println(" . ");
                                            Util.switchOnConsole();
                                            Util.deleteFile(outTableXml);

                                        }
                                        /* Konsole zuerst einmal noch umleiten und die Streams beenden, damit die
                                         * dateien gelscht werden knnen */
                                        Util.switchOffConsoleToTxtClose(outTableXml);
                                        System.out.println(" . ");
                                        Util.switchOnConsole();
                                        Util.deleteFile(outTableXml);

                                    } catch (Exception e) {
                                        getMessageService().logError(
                                                getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                                                        + getTextResourceService().getText(ERROR_XML_UNKNOWN,
                                                                e.getMessage()));
                                        return false;
                                    } finally {
                                        if (proc != null) {
                                            closeQuietly(proc.getOutputStream());
                                            closeQuietly(proc.getInputStream());
                                            closeQuietly(proc.getErrorStream());
                                        }
                                    }
                                }
                            } finally {
                            }
                        }
                    }
                    if (onWork == 41) {
                        onWork = 2;
                        System.out.print("H-   ");
                        System.out.print("\r");
                    } else if (onWork == 11) {
                        onWork = 12;
                        System.out.print("H\\   ");
                        System.out.print("\r");
                    } else if (onWork == 21) {
                        onWork = 22;
                        System.out.print("H|   ");
                        System.out.print("\r");
                    } else if (onWork == 31) {
                        onWork = 32;
                        System.out.print("H/   ");
                        System.out.print("\r");
                    } else {
                        onWork = onWork + 1;
                    }
                }
            }
            if (onWork == 41) {
                onWork = 2;
                System.out.print("H-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("H\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("H|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("H/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, ioe.getMessage() + " (IOException)"));
    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (JDOMException)"));
    } catch (SAXException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (SAXException)"));
    }

    return valid;
}