Example usage for org.jdom2 Element getChild

List of usage examples for org.jdom2 Element getChild

Introduction

In this page you can find the example usage for org.jdom2 Element getChild.

Prototype

public Element getChild(final String cname, final Namespace ns) 

Source Link

Document

This returns the first child element within this element with the given local name and belonging to the given namespace.

Usage

From source file:ca.nrc.cadc.vosi.Availability.java

License:Open Source License

public AvailabilityStatus fromXmlDocument(Document doc) throws ParseException {
    Namespace vosi = Namespace.getNamespace("vosi", VOSI.AVAILABILITY_NS_URI);
    Element availability = doc.getRootElement();
    if (!availability.getName().equals("availability"))
        throw new IllegalArgumentException("missing root element 'availability'");

    Element elemAvailable = availability.getChild("available", vosi);
    if (elemAvailable == null)
        throw new IllegalArgumentException("missing element 'available'");
    boolean available = elemAvailable.getText().equalsIgnoreCase("true");

    DateFormat df = DateUtil.getDateFormat(DateUtil.IVOA_DATE_FORMAT, DateUtil.UTC);

    Element elemUpSince = availability.getChild("upSince", vosi);
    Element elemDownAt = availability.getChild("downAt", vosi);
    Element elemBackAt = availability.getChild("backAt", vosi);
    Element elemNote = availability.getChild("note", vosi);

    Date upSince = null;/* w w  w .  ja v a2 s  .co m*/
    Date downAt = null;
    Date backAt = null;
    String note = null;

    if (elemUpSince != null)
        upSince = df.parse(elemUpSince.getText());
    if (elemDownAt != null)
        downAt = df.parse(elemDownAt.getText());
    if (elemBackAt != null)
        backAt = df.parse(elemBackAt.getText());
    if (elemNote != null)
        note = elemNote.getText();

    return new AvailabilityStatus(available, upSince, downAt, backAt, note);
}

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/*w  w  w . j  av  a 2  s  . co m*/
*/
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

private boolean validateSchema(Element schema, Namespace ns, String pathToWorkDir) {
    int onWork = 41;
    boolean valid = true;
    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()) {
        List<Element> tables = schema.getChild("tables", ns).getChildren("table", ns);
        for (Element table : tables) {
            valid = valid && validateTable(table, ns, pathToWorkDir, schemaPath);
            if (onWork == 41) {
                onWork = 2;/* w  w  w .  ja  v  a  2 s.c o  m*/
                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;
            }
        }
    } else {
        valid = false;
        if (schemaPath.exists()) {
            getMessageService().logError(
                    getTextResourceService().getText(MESSAGE_XML_MODUL_D_SIARD) + getTextResourceService()
                            .getText(MESSAGE_XML_D_INVALID_FOLDER, "content", schemaPath.getName()));
        } else {
            getMessageService().logError(
                    getTextResourceService().getText(MESSAGE_XML_MODUL_D_SIARD) + getTextResourceService()
                            .getText(MESSAGE_XML_D_MISSING_FOLDER, "content", schemaPath.getName()));
        }
    }
    return valid;
}

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

License:Open Source License

private boolean validateTable(Element table, Namespace ns, String pathToWorkDir, File schemaPath) {
    boolean valid = true;
    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());
        valid = valid && validateFile(tableXml, tablePath);
        File tableXsd = new File(new StringBuilder(tablePath.getAbsolutePath()).append(File.separator)
                .append(tableFolder.getText() + ".xsd").toString());
        valid = valid && validateFile(tableXsd, tablePath);
    } else {//from ww  w . j a  v a2 s .  c  om
        valid = false;
        if (tablePath.exists()) {
            getMessageService().logError(
                    getTextResourceService().getText(MESSAGE_XML_MODUL_D_SIARD) + getTextResourceService()
                            .getText(MESSAGE_XML_D_INVALID_FOLDER, schemaPath.getName(), tablePath.getName()));
        } else {
            getMessageService().logError(
                    getTextResourceService().getText(MESSAGE_XML_MODUL_D_SIARD) + getTextResourceService()
                            .getText(MESSAGE_XML_D_MISSING_FOLDER, schemaPath.getName(), tablePath.getName()));
        }
    }
    return valid;
}

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

License:Open Source License

private boolean validateColumnOccurrence(ValidationContext validationContext) throws Exception {
    int onWork = 41;
    boolean validTable;
    boolean validDatabase;
    Properties properties = validationContext.getValidationProperties();
    List<SiardTable> siardTables = validationContext.getSiardTables();
    StringBuilder namesOfInvalidTables = new StringBuilder();
    StringBuilder namesOfInvalidColumns = new StringBuilder();
    validDatabase = true;/*from   ww  w . j av  a2s .c  om*/
    // Iterate over the SIARD tables and verify the nullable attribute
    for (SiardTable siardTable : siardTables) {
        String nullable = new String();
        String minOccurs = new String();
        validTable = true;
        // Number of attributes in metadata.xml
        int metadataXMLColumnsCount = siardTable.getMetadataXMLElements().size();
        // Number of attributes in schema.xsd
        int tableXSDColumnsCount = siardTable.getTableXSDElements().size();
        /* Counter. In order to prevent indexOutOfBorder errors columnsCounter is assigned to the
         * smaller number of columns */
        int columnCount = (metadataXMLColumnsCount >= tableXSDColumnsCount) ? tableXSDColumnsCount
                : metadataXMLColumnsCount;
        // Element/Attributes of the actual SIARD table
        List<Element> xmlElements = siardTable.getMetadataXMLElements();
        // Elements/Attributes of the according XML schema
        List<Element> xsdElements = siardTable.getTableXSDElements();
        Namespace xmlNamespace = validationContext.getXmlNamespace();
        for (int i = 0; i < columnCount; i++) {
            // Actual Element of the metadata.xml
            Element xmlElement = xmlElements.get(i);
            // Actual Element of the according XML schema
            Element xsdElement = xsdElements.get(i);
            String nullableElementDescription = properties
                    .getProperty("module.e.siard.metadata.xml.nullable.element.name");
            String minuOccursAttributeDescription = properties
                    .getProperty("module.e.siard.table.xsd.attribute.minOccurs.name");
            String nameAttributeDescription = properties.getProperty("module.e.siard.table.xsd.attribute.name");
            // Value of the nullable Element in metadata.xml
            nullable = xmlElement.getChild(nullableElementDescription, xmlNamespace).getValue();
            // Value of the minOccurs attribute in the according XML schema
            minOccurs = xsdElement.getAttributeValue(minuOccursAttributeDescription);
            // If the nullable Element is set to true and the minOccurs attribute is null
            if (nullable.equalsIgnoreCase("true") && minOccurs == null) {
                validTable = false;
                validDatabase = false;
                namesOfInvalidColumns.append((namesOfInvalidColumns.length() > 0) ? ", " : "");
                namesOfInvalidColumns.append(xsdElement.getAttributeValue(nameAttributeDescription));
                // If the nullable Element is set to true and the minOccurs attribute is set to zero
            } else if (nullable.equalsIgnoreCase("true") && minOccurs.equalsIgnoreCase("0")) {
            } else if (nullable.equalsIgnoreCase("false") && minOccurs == null) {
            } else if (nullable.equalsIgnoreCase("false") && minOccurs.equalsIgnoreCase("0")) {
                validTable = false;
                validDatabase = false;
                namesOfInvalidColumns.append((namesOfInvalidColumns.length() > 0) ? ", " : "");
                namesOfInvalidColumns.append(xsdElement.getAttributeValue(nameAttributeDescription));
            }
        }
        if (validTable == false) {
            namesOfInvalidTables.append((namesOfInvalidTables.length() > 0) ? ", " : "");
            namesOfInvalidTables.append(siardTable.getTableName());
            namesOfInvalidTables.append(properties.getProperty("module.e.siard.table.xsd.file.extension"));
            namesOfInvalidTables.append("(");
            namesOfInvalidTables.append(namesOfInvalidColumns);
            namesOfInvalidTables.append(")");
            namesOfInvalidColumns = null;
            namesOfInvalidColumns = new StringBuilder();
        }
        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;
        }
    }
    // Writing back error log
    this.setIncongruentColumnOccurrence(namesOfInvalidTables);
    return validDatabase;
}

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

License:Open Source License

private boolean validateColumnType(ValidationContext validationContext) throws Exception {
    int onWork = 41;
    boolean validTable;
    boolean validDatabase;
    Properties properties = validationContext.getValidationProperties();
    List<SiardTable> siardTables = validationContext.getSiardTables();
    StringBuilder namesOfInvalidTables = new StringBuilder();
    StringBuilder namesOfInvalidColumns = new StringBuilder();
    // List of all XML column elements to verify the allover sequence
    List<String> xmlElementSequence = new ArrayList<String>();
    // List of all XSD column elements
    List<String> xsdElementSequence = new ArrayList<String>();
    // Iterate over the SIARD tables and verify the column types
    validDatabase = true;//from  w  ww  .  j a  v a 2  s. co  m
    for (SiardTable siardTable : siardTables) {
        // Elements of the actual SIARD table
        List<Element> xmlElements = siardTable.getMetadataXMLElements();
        // Elements of the according XML schema
        List<Element> xsdElements = siardTable.getTableXSDElements();
        // Number of attributes in metadata.xml
        int metadataXMLColumnsCount = xmlElements.size();
        // Number of attributes in schema.xsd
        int tableXSDColumnsCount = xsdElements.size();
        /* Counter. In order to prevent indexOutOfBorder errors columnsCounter is assigned to the
         * smaller number of columns */
        int columnCount = (metadataXMLColumnsCount >= tableXSDColumnsCount) ? tableXSDColumnsCount
                : metadataXMLColumnsCount;
        validTable = true;
        // Verify whether the number of column elements in XML and XSD are equal
        for (int i = 0; i < columnCount; i++) {
            Element xmlElement = xmlElements.get(i);
            Element xsdElement = xsdElements.get(i);
            // Retrieve the Elements name
            String xmlTypeElementName = properties.getProperty("module.e.siard.metadata.xml.type.element.name");
            String xsdTypeAttribute = properties.getProperty("module.e.siard.table.xsd.type.attribute.name");
            String xsdAttribute = properties.getProperty("module.e.siard.table.xsd.attribute.name");
            String columnName = xsdElement.getAttributeValue(xsdAttribute);
            // Retrieve the original column type from metadata.xml
            String leftSide = xmlElement.getChild(xmlTypeElementName, validationContext.getXmlNamespace())
                    .getValue();
            // Retrieve the original column type from table.xsd
            String rightSide = xsdElement.getAttributeValue(xsdTypeAttribute);
            String delimiter = properties
                    .getProperty("module.e.attribute.type.validator.original.type.delimiter");
            // Trim the column types - eliminates the brackets and specific numeric parameters
            String trimmedExpectedType = trimLeftSideType(leftSide, delimiter);
            // Designing expected column type in table.xsd, called "rightSide"
            String expectedType = properties.getProperty(trimmedExpectedType);
            // In case the expected type does not exist
            if (expectedType == null) {
                expectedType = properties.getProperty("module.e.type.validator.unknown.type");
                validTable = false;
                validDatabase = false;
                namesOfInvalidColumns.append((namesOfInvalidColumns.length() > 0) ? ", " : "");
                namesOfInvalidColumns.append(columnName + "{" + expectedType + "}");
            } else if (!expectedType.equalsIgnoreCase(rightSide) && expectedType != null) {
                validTable = false;
                validDatabase = false;
                namesOfInvalidColumns.append((namesOfInvalidColumns.length() > 0) ? ", " : "");
                namesOfInvalidColumns.append(columnName);
            }
            // Convey the column types for the all over sequence test [E.4]
            xmlElementSequence.add(expectedType);
            xsdElementSequence.add(rightSide);
        }
        if (validTable == false) {
            namesOfInvalidTables.append((namesOfInvalidTables.length() > 0) ? ", " : "");
            namesOfInvalidTables.append(siardTable.getTableName());
            namesOfInvalidTables.append(properties.getProperty("module.e.siard.table.xsd.file.extension"));
            namesOfInvalidTables.append("(");
            namesOfInvalidTables.append(namesOfInvalidColumns);
            namesOfInvalidTables.append(")");
            namesOfInvalidColumns = null;
            namesOfInvalidColumns = new StringBuilder();
        }
        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;
        }
    }
    this.setIncongruentColumnType(namesOfInvalidTables);
    // Save the allover column elements for [E.4]
    validationContext.setXmlElementsSequence(xmlElementSequence);
    validationContext.setXsdElementsSequence(xsdElementSequence);
    this.setValidationContext(validationContext);
    // Return the current validation state
    return validDatabase;
}

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();//from ww w .j  av a  2 s . c om
            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

private boolean validateSchema(Element schema, Namespace ns, String pathToWorkDir) {
    int onWork = 41;
    boolean valid = true;
    boolean validT = true;
    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()) {
        List<Element> tables = schema.getChild("tables", ns).getChildren("table", ns);
        for (Element table : tables) {
            // Valid = True ansonsten validiert er nicht
            validT = true;// w ww . j a v  a 2  s . c  o  m
            validT = validT && validateTable(table, ns, pathToWorkDir, schemaPath);
            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;
            }
            // Validierungsergebnis in valid speichern
            valid = valid && validT;
        }
    } else {
        valid = false;
    }
    valid = valid && validT;
    return valid;
}

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

License:Open Source License

private boolean validateTable(Element table, Namespace ns, String pathToWorkDir, File schemaPath) {
    boolean valid = true;
    boolean validR = true;
    Element tableFolder = table.getChild("folder", ns);
    Element tablerows = table.getChild("rows", ns);
    int rowmax = Integer.parseInt(tablerows.getText());

    File tablePath = new File(new StringBuilder(schemaPath.getAbsolutePath()).append(File.separator)
            .append(tableFolder.getText()).toString());
    File tableXsd = new File(new StringBuilder(tablePath.getAbsolutePath()).append(File.separator)
            .append(tableFolder.getText() + ".xsd").toString());
    validR = validateRow(tableXsd, rowmax);
    valid = valid && validR;/*from   w  w w  . ja  va  2 s . c o m*/

    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  .j a v a 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;
}