Search in sources :

Example 76 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project mycore by MyCoRe-Org.

the class MCRXSLTransformer method getTransformHandlerList.

protected LinkedList<TransformerHandler> getTransformHandlerList(MCRParameterCollector parameterCollector) throws TransformerConfigurationException, SAXException, ParserConfigurationException {
    checkTemplateUptodate();
    LinkedList<TransformerHandler> xslSteps = new LinkedList<>();
    // every transformhandler shares the same ErrorListener instance
    MCRErrorListener errorListener = MCRErrorListener.getInstance();
    for (Templates template : templates) {
        TransformerHandler handler = tFactory.newTransformerHandler(template);
        parameterCollector.setParametersTo(handler.getTransformer());
        handler.getTransformer().setErrorListener(errorListener);
        if (TRACE_LISTENER_ENABLED) {
            TransformerImpl transformer = (TransformerImpl) handler.getTransformer();
            TraceManager traceManager = transformer.getTraceManager();
            try {
                traceManager.addTraceListener(TRACE_LISTENER);
            } catch (TooManyListenersException e) {
                LOGGER.warn("Could not add MCRTraceListener.", e);
            }
        }
        if (!xslSteps.isEmpty()) {
            Result result = new SAXResult(handler);
            xslSteps.getLast().setResult(result);
        }
        xslSteps.add(handler);
    }
    return xslSteps;
}
Also used : TransformerImpl(org.apache.xalan.transformer.TransformerImpl) TransformerHandler(javax.xml.transform.sax.TransformerHandler) TooManyListenersException(java.util.TooManyListenersException) MCRErrorListener(org.mycore.common.xsl.MCRErrorListener) SAXResult(javax.xml.transform.sax.SAXResult) Templates(javax.xml.transform.Templates) TraceManager(org.apache.xalan.trace.TraceManager) LinkedList(java.util.LinkedList) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult)

Example 77 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project mycore by MyCoRe-Org.

the class MCRXSLTransformer method transform.

@Override
public MCRContent transform(MCRContent source, MCRParameterCollector parameter) throws IOException {
    try {
        LinkedList<TransformerHandler> transformHandlerList = getTransformHandlerList(parameter);
        XMLReader reader = getXMLReader(transformHandlerList);
        TransformerHandler lastTransformerHandler = transformHandlerList.getLast();
        return transform(source, reader, lastTransformerHandler, parameter);
    } catch (TransformerException | SAXException | ParserConfigurationException e) {
        throw new IOException(e);
    }
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) IOException(java.io.IOException) XMLReader(org.xml.sax.XMLReader) TransformerException(javax.xml.transform.TransformerException) SAXException(org.xml.sax.SAXException)

Example 78 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project mycore by MyCoRe-Org.

the class MCRXSL2JAXBTransformer method getJAXBObject.

public T getJAXBObject(MCRContent source, MCRParameterCollector parameter) throws TransformerConfigurationException, SAXException, JAXBException, IOException, ParserConfigurationException {
    LinkedList<TransformerHandler> transformHandlerList = getTransformHandlerList(parameter);
    XMLReader reader = getXMLReader(transformHandlerList);
    TransformerHandler lastTransformerHandler = transformHandlerList.getLast();
    return getJAXBObject(source, reader, lastTransformerHandler);
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) XMLReader(org.xml.sax.XMLReader)

Example 79 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project lar_361 by comitsrl.

the class LCO_DianExportXML method doIt.

// prepare
/**
 * 	Process
 *	@return message
 *	@throws Exception
 */
protected String doIt() throws Exception {
    /**
     * Parametros
     *			-> IsAttachXML
     *			-> Path/Directory
     *			-  Validar XML --Flag
     *			Para XML Header
     *			    Genere el nombre del archivo de acuerdo a la resolucion
     *			    Escribir encabezado
     *			    Para cada Send Line del XML Header
     *			        Para Campo
     *			            Escriba campo
     *			        Fin Campo
     *			    Fin Para
     *			    Cerrrar Archivo
     *			    Si IsAttachXML
     *			        Anexar el archivo XML al XML Header (probar con Archivador
     *			a ver si funciona, si no con Attachment)
     *			        NOTA: ¿Que hacer si ya hay un archivo previo generado?
     *			Verificar si el archivador es read-only, y si podria renombrar
     *			un archivo previo generado para añadirle un sufijo _old_yyyymmdd
     *			Fin XML Header
     */
    OutputStream mmDocStream = null;
    X_LCO_DIAN_XML_Header xmlheader = new X_LCO_DIAN_XML_Header(getCtx(), p_LCO_DIAN_XML_Header_ID, get_TrxName());
    X_LCO_DIAN_SendSchedule sendScheduleProcess = new X_LCO_DIAN_SendSchedule(getCtx(), xmlheader.getLCO_DIAN_SendSchedule_ID(), get_TrxName());
    if (sendScheduleProcess.getLCO_DIAN_SendSchedule_ID() <= 0)
        throw new AdempiereUserError("@No@ @LCO_DIAN_SendSchedule@");
    if (sendScheduleProcess.getLCO_DIAN_Format_ID() <= 0)
        throw new AdempiereUserError("@No@ @LCO_DIAN_Format@");
    MLCODIANFormat format = new MLCODIANFormat(getCtx(), sendScheduleProcess.getLCO_DIAN_Format_ID(), get_TrxName());
    X_LCO_DIAN_XMLPrintLabel labelDet = new X_LCO_DIAN_XMLPrintLabel(getCtx(), format.getLCO_DIAN_XMLPrintLabel_ID(), get_TrxName());
    String printLbDet = labelDet.getValue();
    /**
     *Dmuisca_ccmmmmmvvaaaacccccccc.xml
     *		   cc : Concepto (Inserción = 01, Reemplazo = 02)
     *		   mmmmm : Formato (Retenciones en la fuente practicadas = 01002)
     *		   vv : Versión del formato (Versión = 07).
     *		   aaaa : Año de envío.
     *		   cccccccc : Consecutivo de envío por año.
     */
    String xmlFileName = "Dmuisca_" + String.format("%2s", sendScheduleProcess.getSendConceptCode()).replace(" ", "0") + String.format("%5s", format.getValue()).replace(" ", "0") + String.format("%2s", format.getVersionNo()).replace(" ", "0") + String.format("%tY", sendScheduleProcess.getSendDate()) + String.format("%08d", xmlheader.getSequence()) + ".xml";
    if (folder.equals(""))
        throw new AdempiereUserError("Folder is mandatory");
    // crea los directorios para los archivos xml
    (new File(folder + File.separator + "XMLGenerated" + File.separator)).mkdirs();
    // ruta completa del archivo xml
    String file_name = folder + File.separator + "XMLGenerated" + File.separator + xmlFileName;
    // Stream para el documento xml
    mmDocStream = new FileOutputStream(file_name, false);
    StreamResult streamResult_menu = new StreamResult(new OutputStreamWriter(mmDocStream, "ISO-8859-1"));
    SAXTransformerFactory tf_menu = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    try {
        tf_menu.setAttribute("indent-number", new Integer(0));
    } catch (Exception e) {
    // swallow
    }
    TransformerHandler mmDoc = tf_menu.newTransformerHandler();
    Transformer serializer_menu = mmDoc.getTransformer();
    serializer_menu.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    try {
        serializer_menu.setOutputProperty(OutputKeys.INDENT, "yes");
    } catch (Exception e) {
    // swallow
    }
    mmDoc.setResult(streamResult_menu);
    mmDoc.startDocument();
    AttributesImpl atts = new AttributesImpl();
    // XML Header
    // Para XML Header
    atts.clear();
    // xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../xsd/1002.xsd"
    atts.addAttribute("", "", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
    atts.addAttribute("", "", "xsi:noNamespaceSchemaLocation", "CDATA", "../xsd/" + format.getValue() + ".xsd");
    mmDoc.startElement("", "", "mas", atts);
    atts.clear();
    mmDoc.startElement("", "", "Cab", atts);
    // Escribir encabezado
    // Año de envío,int4,Formato AAAA
    addHeaderElement(mmDoc, "Ano", String.format("%tY", sendScheduleProcess.getSendDate()), atts);
    // Concepto ,int2 , 1= Inserción 2= Reemplazo
    addHeaderElement(mmDoc, "CodCpt", sendScheduleProcess.getSendConceptCode(), atts);
    // Código del formato ,int5 ,Retenciones en la fuente practicadas = 1002
    addHeaderElement(mmDoc, "Formato", format.getValue(), atts);
    // Versión del formato ,int2 ,Versión = 7
    addHeaderElement(mmDoc, "Version", format.getVersionNo(), atts);
    /**
     *Número de envío ,int8
     *		   Debe ser un número consecutivo por año para todos los formatos que el remitente envíe a la DIAN
     *		   Consecutivo de envío por año.*
     */
    addHeaderElement(mmDoc, "NumEnvio", "" + xmlheader.getSequence(), atts);
    // Fecha de envío,datetime19 ,Debe ser la fecha calendario. Formato AAAA-MM-DDTHH:MM:SS
    addHeaderElement(mmDoc, "FecEnvio", String.format("%1$tFT%1$tT", sendScheduleProcess.getSendDate()), atts);
    // Fecha Inicial ,date10 ,Debe ser la fecha calendario.Los registros corresponden mínimo esta fecha inicial. Formato AAAA-MM-DD
    addHeaderElement(mmDoc, "FecInicial", String.format("%1$tF", sendScheduleProcess.getStartDate()), atts);
    // Fecha Final ,date10 ,Debe ser la fecha calendario.Los registros corresponden máximo a esta fecha final. Formato AAAA-MM-DD
    addHeaderElement(mmDoc, "FecFinal", String.format("%1$tF", sendScheduleProcess.getEndDate()), atts);
    // Valor Total , double20
    // Corresponde a la sumatoria de la casilla vret (Valor de la Retención en la fuente practicada) de los registros reportados.
    addHeaderElement(mmDoc, "ValorTotal", String.format("%.0f", xmlheader.getCumulatedAmt()), atts);
    // Cantidad de registros ,int4 ,Se enviarán archivos con máximo 5000 registros (*).
    // Cantidad de registros reportados en el contenido.
    addHeaderElement(mmDoc, "CantReg", String.format("%.0f", xmlheader.getRecordsQty()), atts);
    mmDoc.endElement("", "", "Cab");
    X_LCO_DIAN_FieldFormat[] fieldFormats = format.getFields();
    // body
    atts.clear();
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    String sqlschline = "SELECT * FROM LCO_DIAN_SendScheduleLine WHERE LCO_DIAN_XML_Header_ID =? ORDER BY LCO_DIAN_SendScheduleLine_ID";
    try {
        pstmt = DB.prepareStatement(sqlschline, get_TrxName());
        pstmt.setInt(1, p_LCO_DIAN_XML_Header_ID);
        rs = pstmt.executeQuery();
        // Para cada Send Line del XML Header
        while (rs.next()) {
            X_LCO_DIAN_SendScheduleLine dssl = new X_LCO_DIAN_SendScheduleLine(getCtx(), rs, get_TrxName());
            int line_id = dssl.getLCO_DIAN_SendScheduleLine_ID();
            MLCODIANConcept concept = new MLCODIANConcept(getCtx(), dssl.getLCO_DIAN_Concept_ID(), get_TrxName());
            MBPartner bp = null;
            MBPartnerLocation bpl = null;
            MLocation loc = null;
            boolean isColombia = true;
            boolean isDetailedNames = false;
            if (dssl.getC_BPartner_ID() > 0) {
                bp = new MBPartner(getCtx(), dssl.getC_BPartner_ID(), get_TrxName());
                bpl = bp.getLocation(dssl.getC_BPartner_Location_ID());
                loc = bpl.getLocation(false);
                isColombia = (loc.getC_Country_ID() == 156);
                /* HARDCODED = Colombia C_Country_ID */
                isDetailedNames = (Boolean) bp.get_Value("IsDetailedNames");
            }
            // Para Campo
            for (X_LCO_DIAN_FieldFormat fieldFormat : fieldFormats) {
                X_LCO_DIAN_XMLPrintLabel label = new X_LCO_DIAN_XMLPrintLabel(getCtx(), fieldFormat.getLCO_DIAN_XMLPrintLabel_ID(), get_TrxName());
                String printLb = label.getValue();
                // Condicion de error
                if (bp == null && (printLb.equals("tdoc") || printLb.equals("nid") || printLb.equals("dv") || printLb.equals("apl1") || printLb.equals("apl2") || printLb.equals("nom1") || printLb.equals("nom2") || printLb.equals("raz") || printLb.equals("dir") || printLb.equals("dpto") || printLb.equals("mun") || printLb.equals("pais"))) {
                    throw new AdempiereUserError(printLb + " cannot be used without BP detail");
                }
                if (printLb.equals("cpt")) {
                    // Concepto ( Siempre debe diligenciarse )
                    add_Attribute(atts, printLb, concept.getValue(), line_id, true);
                } else if (printLb.equals("tdoc")) {
                    // Tipo de Documento ( Siempre debe diligenciarse )
                    add_Attribute(atts, printLb, getTdoc(dssl.getC_BPartner_ID()), line_id, true);
                } else if (printLb.equals("nid")) {
                    // Número de Identificación ( Siempre debe diligenciarse )
                    add_Attribute(atts, printLb, bp.getTaxID(), line_id, true);
                } else if (printLb.equals("dv")) {
                    // Digito de Verificación ( Si se conoce debe diligenciarse)
                    add_Attribute(atts, printLb, (String) bp.get_Value("TaxIdDigit"), line_id, false);
                } else if (printLb.equals("apl1")) {
                    // En caso de ser una Persona Natural siempre debe diligenciarse.
                    if (isDetailedNames) {
                        add_Attribute(atts, printLb, (String) bp.get_Value("LastName1"), line_id, isDetailedNames);
                    }
                } else if (printLb.equals("apl2")) {
                    // En caso de ser una Persona Natural y si se conoce debe diligenciarse.
                    if (isDetailedNames) {
                        String aux = (String) bp.get_Value("LastName2");
                        if (aux != null && aux.length() > 0)
                            add_Attribute(atts, printLb, aux, line_id, false);
                    }
                } else if (printLb.equals("nom1")) {
                    // En caso de ser una Persona Natural siempre debe diligenciarse.
                    if (isDetailedNames) {
                        add_Attribute(atts, printLb, (String) bp.get_Value("FirstName1"), line_id, isDetailedNames);
                    }
                } else if (printLb.equals("nom2")) {
                    // En caso de ser una Persona Natural y si se conoce debe diligenciarse.
                    if (isDetailedNames) {
                        String aux = (String) bp.get_Value("FirstName2");
                        if (aux != null && aux.length() > 0)
                            add_Attribute(atts, printLb, aux, line_id, false);
                    }
                } else if (printLb.equals("raz")) {
                    // En caso de ser una Persona Jurídica siempre debe diligenciarse.
                    if (!isDetailedNames) {
                        add_Attribute(atts, printLb, bp.getName(), line_id, !isDetailedNames);
                    }
                } else if (printLb.equals("dir")) {
                    // Dirección
                    // En caso que el País de residencia sea Colombia siempre debe diligenciarse
                    add_Attribute(atts, printLb, loc.getAddress1(), line_id, isColombia);
                } else if (printLb.equals("dpto")) {
                    // Código del Departamento
                    // Código DANE Numérico, debe incluir los ceros a la izquierda. En caso que el País de residencia sea Colombia siempre debe diligenciarse
                    add_Attribute(atts, printLb, getDpto(loc.getC_Region_ID()), line_id, isColombia);
                } else if (printLb.equals("mun")) {
                    // Código del Municipio
                    // Código DANE Numérico, debe incluir los ceros a la izquierda. En caso que el País de residencia sea Colombia siempre debe diligenciarse
                    add_Attribute(atts, printLb, getMun(loc.getC_City_ID()), line_id, isColombia);
                } else if (printLb.equals("pais")) {
                    // País de Residencia o domicilio
                    // Siempre debe diligenciarse
                    add_Attribute(atts, printLb, getPais(loc.getC_Country_ID()), line_id, true);
                } else {
                    // Fin de las 13 columnas hardcoded
                    // Label de una columna calculada
                    int col = fieldFormat.getCalcColumnPosition();
                    if (col < 1 || col > 10)
                        throw new AdempiereUserError(label + " col not valid (" + col + ") in line " + line_id);
                    BigDecimal amt = (BigDecimal) dssl.get_Value("FieldAmt" + col);
                    if (amt == null)
                        amt = Env.ZERO;
                    // TODO: Aplicar fieldFormat.getFieldPrintFormat
                    add_Attribute(atts, printLb, String.format("%.0f", amt), line_id, true);
                }
            }
            mmDoc.startElement("", "", printLbDet, atts);
            mmDoc.endElement("", "", printLbDet);
            atts.clear();
        }
    } catch (SQLException e) {
        log.log(Level.SEVERE, sqlschline, e);
        throw e;
    } finally {
        DB.close(rs, pstmt);
        rs = null;
        pstmt = null;
    }
    mmDoc.endElement("", "", "mas");
    mmDoc.endDocument();
    if (mmDocStream != null) {
        try {
            mmDocStream.close();
        } catch (Exception e) {
        }
    }
    if (isAttachXML) {
        int AD_Table_ID = MTable.getTable_ID(X_LCO_DIAN_XML_Header.Table_Name);
        // if one attach is found , it means that a xml file was attached before
        MAttachment attach = MAttachment.get(getCtx(), AD_Table_ID, xmlheader.getLCO_DIAN_XML_Header_ID());
        // no se encontro archivo previo
        if (attach == null) {
            attach = new MAttachment(getCtx(), AD_Table_ID, xmlheader.getLCO_DIAN_XML_Header_ID(), get_TrxName());
            attach.addEntry(new File(file_name));
            attach.save();
        } else {
            // se encontro un archivo adjunto previamente
            // toma el index  del penultimo archivo y lo renombra
            // REVIEWME
            int index = (attach.getEntryCount() - 1);
            MAttachmentEntry entry = attach.getEntry(index);
            String renamed = folder + File.separator + entry.getName().substring(0, entry.getName().length() - 4) + "_old_" + getDateTime() + ".xml";
            entry.setName(renamed);
            attach.save();
            // agrega el nuevo archivo ya q el anterior ha sido renombrado
            attach.addEntry(new File(file_name));
            attach.save();
        }
    // DB.getSQLValue(get_TrxName(),"SELECT AD_Attachment_ID FROM AD_Attachment WHERE AD_Table_ID=? AND Record_ID=?",AD_Table_ID)
    }
    return "@LCO_FileGenerated@ -> " + file_name;
}
Also used : X_LCO_DIAN_XML_Header(org.globalqss.model.X_LCO_DIAN_XML_Header) TransformerHandler(javax.xml.transform.sax.TransformerHandler) MAttachment(org.compiere.model.MAttachment) Transformer(javax.xml.transform.Transformer) SQLException(java.sql.SQLException) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) MBPartnerLocation(org.compiere.model.MBPartnerLocation) X_LCO_DIAN_FieldFormat(org.globalqss.model.X_LCO_DIAN_FieldFormat) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ResultSet(java.sql.ResultSet) MLocation(org.compiere.model.MLocation) MLCODIANFormat(org.globalqss.model.MLCODIANFormat) AdempiereUserError(org.compiere.util.AdempiereUserError) X_LCO_DIAN_XMLPrintLabel(org.globalqss.model.X_LCO_DIAN_XMLPrintLabel) MLCODIANConcept(org.globalqss.model.MLCODIANConcept) StreamResult(javax.xml.transform.stream.StreamResult) MAttachmentEntry(org.compiere.model.MAttachmentEntry) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) X_LCO_DIAN_SendScheduleLine(org.globalqss.model.X_LCO_DIAN_SendScheduleLine) PreparedStatement(java.sql.PreparedStatement) MBPartner(org.compiere.model.MBPartner) SQLException(java.sql.SQLException) BigDecimal(java.math.BigDecimal) FileOutputStream(java.io.FileOutputStream) X_LCO_DIAN_SendSchedule(org.globalqss.model.X_LCO_DIAN_SendSchedule) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File)

Example 80 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project ant-ivy by apache.

the class BundleRepoTest method testXMLSerialisation.

@Test
public void testXMLSerialisation() throws SAXException, IOException {
    FSManifestIterable it = new FSManifestIterable(bundlerepo);
    BundleRepoDescriptor repo = new BundleRepoDescriptor(bundlerepo.toURI(), ExecutionEnvironmentProfileProvider.getInstance());
    repo.populate(it.iterator());
    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler hd;
    try {
        hd = tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        throw new BuildException("Sax configuration error: " + e.getMessage(), e);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    StreamResult stream = new StreamResult(out);
    hd.setResult(stream);
    OBRXMLWriter.writeManifests(it, hd, false);
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    BundleRepoDescriptor repo2 = OBRXMLParser.parse(bundlerepo.toURI(), in);
    assertEquals(repo, repo2);
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayInputStream(java.io.ByteArrayInputStream) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) BuildException(org.apache.tools.ant.BuildException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Test(org.junit.Test)

Aggregations

TransformerHandler (javax.xml.transform.sax.TransformerHandler)84 StreamResult (javax.xml.transform.stream.StreamResult)57 SAXTransformerFactory (javax.xml.transform.sax.SAXTransformerFactory)51 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)33 Transformer (javax.xml.transform.Transformer)29 IOException (java.io.IOException)23 SAXException (org.xml.sax.SAXException)22 AttributesImpl (org.xml.sax.helpers.AttributesImpl)17 StringWriter (java.io.StringWriter)13 SAXResult (javax.xml.transform.sax.SAXResult)13 File (java.io.File)11 XMLReader (org.xml.sax.XMLReader)11 FileOutputStream (java.io.FileOutputStream)10 Test (org.junit.Test)10 InputStream (java.io.InputStream)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 OutputStream (java.io.OutputStream)8 ContentHandler (org.xml.sax.ContentHandler)8 InputSource (org.xml.sax.InputSource)8 Metadata (org.apache.tika.metadata.Metadata)7