Example usage for javax.xml.transform Templates newTransformer

List of usage examples for javax.xml.transform Templates newTransformer

Introduction

In this page you can find the example usage for javax.xml.transform Templates newTransformer.

Prototype

Transformer newTransformer() throws TransformerConfigurationException;

Source Link

Document

Create a new transformation context for this Templates object.

Usage

From source file:org.mule.tools.schemadocs.SchemaDocsMain.java

protected void processSchema(InputStream xslSource, OutputStream out)
        throws TransformerException, IOException, ParserConfigurationException {
    TransformerFactory factory = TransformerFactory.newInstance();
    Templates template = factory.newTemplates(new StreamSource(xslSource));
    Transformer xformer = template.newTransformer();
    Iterator urls = listSchema2().iterator();
    while (urls.hasNext()) {
        URL url = (URL) urls.next();
        String tag = tagFromFileName(url.getFile());
        logger.info(tag + " : " + url);
        xformer.setParameter(TAG, tag);/*  w ww  . j a  va 2  s.c  om*/
        Source source = new StreamSource(url.openStream());
        xformer.transform(source, new StreamResult(out));
        //            xformer.transform(source, new StreamResult(System.out));
        out.flush();
    }
}

From source file:org.mycore.common.content.MCRVFSContentTest.java

/**
 * Test method for {@link org.mycore.common.content.MCRContent#getSource()}.
 * @throws IOException //from   w w w  .  j  a  va 2  s.  co  m
 * @throws TransformerException 
 */
@Test
public final void testGetSource() throws IOException, TransformerException {
    CommonVFSResolver resolver = new CommonVFSResolver(fileObject);
    assertFalse("File is open", resolver.isContentOpen());
    //identity transformation
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    StreamResult result = new StreamResult(System.out);
    transformer.transform(resolver.resolve("test://test", null), result);
    assertFalse("File is open after identity transformation", resolver.isContentOpen());
    //simple transformation
    URL xslURL = MCRVFSContentTest.class.getResource(TEST_BASE + "test.xsl");
    URL xmlURL = MCRVFSContentTest.class.getResource(TEST_BASE + "test.xml");
    Source xsl = new StreamSource(xslURL.toString());
    Source xml = new StreamSource(xmlURL.toString());
    transformer = TransformerFactory.newInstance().newTransformer(xsl);
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setURIResolver(resolver);
    transformer.transform(xml, result);
    assertFalse("File is open after simple transformation", resolver.isContentOpen());
    //cacheable transformation
    Templates templates = TransformerFactory.newInstance().newTemplates(xsl);
    transformer = templates.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setURIResolver(resolver);
    transformer.transform(xml, result);
    assertFalse("File is open after cacheable transformation", resolver.isContentOpen());
}

From source file:org.openehealth.ipf.commons.xml.XsltTransmogrifier.java

private void doZap(Source source, Result result, Object... params) {
    if (params.length == 0) {
        throw new IllegalArgumentException("Expected XSL location in first parameter");
    }//  ww w.  j av  a2 s.  c  om
    try {
        Templates template = template(params);
        Transformer transformer = template.newTransformer();
        transformer.setURIResolver(resolver);
        setXsltParameters(transformer, staticParams);
        setXsltParameters(transformer, parameters(params));
        transformer.transform(source, result);
    } catch (TransformerException e) {
        throw new RuntimeException("XSLT processing failed", e);
    }

}

From source file:org.openrepose.commons.utils.transform.xslt.XsltTransformConstruction.java

public ObjectPool<Transformer> generateXsltResourcePool(final Templates transformationTemplates) {
    return new SoftReferenceObjectPool<>(new BasePoolableObjectFactory<Transformer>() {

        @Override//from  ww w .j  av  a2 s .  c  o m
        public Transformer makeObject() {
            try {
                return transformationTemplates.newTransformer();
            } catch (TransformerConfigurationException configurationException) {
                throw new XsltTransformationException(
                        "Failed to generate XSLT transformer. Reason: " + configurationException.getMessage(),
                        configurationException);
            }
        }
    });
}

From source file:org.pentaho.di.job.entries.xslt.JobEntryXSLT.java

private boolean processOneXMLFile(String xmlfilename, String xslfilename, String outputfilename, Result result,
        Job parentJob) {/*w w  w.  j  ava 2 s. c  o  m*/
    boolean retval = false;
    FileObject xmlfile = null;
    FileObject xslfile = null;
    FileObject outputfile = null;

    try {
        xmlfile = KettleVFS.getFileObject(xmlfilename, this);
        xslfile = KettleVFS.getFileObject(xslfilename, this);
        outputfile = KettleVFS.getFileObject(outputfilename, this);

        if (xmlfile.exists() && xslfile.exists()) {
            if (outputfile.exists() && iffileexists == 2) {
                // Output file exists
                // User want to fail
                logError(BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists1.Label") + outputfilename
                        + BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists2.Label"));
                return retval;

            } else if (outputfile.exists() && iffileexists == 1) {
                // Do nothing
                if (log.isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists1.Label") + outputfilename
                            + BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists2.Label"));
                }
                retval = true;
                return retval;

            } else {
                if (outputfile.exists() && iffileexists == 0) {
                    // the output file exists and user want to create new one with unique name
                    // Format Date

                    // Try to clean filename (without wildcard)
                    String wildcard = outputfilename.substring(outputfilename.length() - 4,
                            outputfilename.length());
                    if (wildcard.substring(0, 1).equals(".")) {
                        // Find wildcard
                        outputfilename = outputfilename.substring(0, outputfilename.length() - 4) + "_"
                                + StringUtil.getFormattedDateTimeNow(true) + wildcard;
                    } else {
                        // did not find wildcard
                        outputfilename = outputfilename + "_" + StringUtil.getFormattedDateTimeNow(true);
                    }
                    if (log.isDebug()) {
                        logDebug(BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists1.Label")
                                + outputfilename
                                + BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists2.Label"));
                        logDebug(BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileNameChange1.Label")
                                + outputfilename
                                + BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileNameChange2.Label"));
                    }
                }

                // Create transformer factory
                TransformerFactory factory = TransformerFactory.newInstance();

                if (xsltfactory.equals(FACTORY_SAXON)) {
                    // Set the TransformerFactory to the SAXON implementation.
                    factory = new net.sf.saxon.TransformerFactoryImpl();
                }

                if (log.isDetailed()) {
                    log.logDetailed(BaseMessages.getString(PKG, "JobEntryXSL.Log.TransformerFactoryInfos"),
                            BaseMessages.getString(PKG, "JobEntryXSL.Log.TransformerFactory",
                                    factory.getClass().getName()));
                }

                InputStream xslInputStream = KettleVFS.getInputStream(xslfile);
                InputStream xmlInputStream = KettleVFS.getInputStream(xmlfile);
                OutputStream os = null;
                try {
                    // Use the factory to create a template containing the xsl file
                    Templates template = factory.newTemplates(new StreamSource(xslInputStream));

                    // Use the template to create a transformer
                    Transformer xformer = template.newTransformer();

                    if (log.isDetailed()) {
                        log.logDetailed(BaseMessages.getString(PKG, "JobEntryXSL.Log.TransformerClassInfos"),
                                BaseMessages.getString(PKG, "JobEntryXSL.Log.TransformerClass",
                                        xformer.getClass().getName()));
                    }

                    // Do we need to set output properties?
                    if (setOutputProperties) {
                        xformer.setOutputProperties(outputProperties);
                    }

                    // Do we need to pass parameters?
                    if (useParameters) {
                        for (int i = 0; i < nrParams; i++) {
                            xformer.setParameter(nameOfParams[i], valueOfParams[i]);
                        }
                    }

                    // Prepare the input and output files
                    Source source = new StreamSource(xmlInputStream);
                    os = KettleVFS.getOutputStream(outputfile, false);
                    StreamResult resultat = new StreamResult(os);

                    // Apply the xsl file to the source file and write the result to the output file
                    xformer.transform(source, resultat);

                    if (isAddFileToResult()) {
                        // Add output filename to output files
                        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                                KettleVFS.getFileObject(outputfilename, this), parentJob.getJobname(),
                                toString());
                        result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                    }

                    // Everything is OK
                    retval = true;
                } finally {
                    try {
                        xslInputStream.close();
                    } catch (IOException ignored) {
                        // ignore IO Exception on close
                    }
                    try {
                        xmlInputStream.close();
                    } catch (IOException ignored) {
                        // ignore IO Exception on close
                    }
                    try {
                        if (os != null) {
                            os.close();
                        }
                    } catch (IOException ignored) {
                        // ignore IO Exception on close
                    }
                }
            }
        } else {

            if (!xmlfile.exists()) {
                logError(BaseMessages.getString(PKG, "JobEntryXSLT.FileDoesNotExist1.Label") + xmlfilename
                        + BaseMessages.getString(PKG, "JobEntryXSLT.FileDoesNotExist2.Label"));
            }
            if (!xslfile.exists()) {
                logError(BaseMessages.getString(PKG, "JobEntryXSLT.FileDoesNotExist1.Label") + xmlfilename
                        + BaseMessages.getString(PKG, "JobEntryXSLT.FileDoesNotExist2.Label"));
            }
        }
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLST.Label")
                + BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLSTXML1.Label") + xmlfilename
                + BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLSTXML2.Label")
                + BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLSTXSL1.Label") + xslfilename
                + BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLSTXSL2.Label") + e.getMessage());
    } finally {
        try {
            if (xmlfile != null) {
                xmlfile.close();
            }

            if (xslfile != null) {
                xslfile.close();
            }
            if (outputfile != null) {
                outputfile.close();
            }
        } catch (IOException e) {
            logError("Unable to close file", e);
        }
    }

    return retval;
}

From source file:org.rdswitchboard.importers.browser.s3.App.java

public static void main(String[] args) {
    try {//  ww w. j a v  a 2s.  c o m
        if (args.length == 0 || StringUtils.isNullOrEmpty(args[0]))
            throw new Exception("Please provide properties file");

        String propertiesFile = args[0];
        Properties properties = new Properties();
        try (InputStream in = new FileInputStream(propertiesFile)) {
            properties.load(in);
        }

        String source = properties.getProperty("data.source.id");

        if (StringUtils.isNullOrEmpty(source))
            throw new IllegalArgumentException("Source can not be empty");

        System.out.println("Source: " + source);

        String baseUrl = properties.getProperty("base.url");

        if (StringUtils.isNullOrEmpty(baseUrl))
            throw new IllegalArgumentException("Base URL can not be empty");

        System.out.println("Base URL: " + baseUrl);

        String sessionId = properties.getProperty("session.id");

        if (StringUtils.isNullOrEmpty(sessionId))
            throw new IllegalArgumentException("Session Id can not be empty");

        System.out.println("Session Id: " + sessionId);

        String accessKey = properties.getProperty("aws.access.key");
        String secretKey = properties.getProperty("aws.secret.key");

        String bucket = properties.getProperty("s3.bucket");

        if (StringUtils.isNullOrEmpty(bucket))
            throw new IllegalArgumentException("AWS S3 Bucket can not be empty");

        System.out.println("S3 Bucket: " + bucket);

        String prefix = properties.getProperty("s3.prefix");

        if (StringUtils.isNullOrEmpty(prefix))
            throw new IllegalArgumentException("AWS S3 Prefix can not be empty");

        System.out.println("S3 Prefix: " + prefix);

        String crosswalk = properties.getProperty("crosswalk");
        Templates template = null;

        if (!StringUtils.isNullOrEmpty(crosswalk)) {
            System.out.println("Crosswalk: " + crosswalk);

            template = TransformerFactory.newInstance()
                    .newTemplates(new StreamSource(new FileInputStream(crosswalk)));
        }

        ObjectMapper mapper = new ObjectMapper();

        Client client = Client.create();
        Cookie cookie = new Cookie("PHPSESSID", properties.getProperty("session"));

        AmazonS3 s3client;

        if (!StringUtils.isNullOrEmpty(accessKey) && !StringUtils.isNullOrEmpty(secretKey)) {
            System.out.println(
                    "Connecting to AWS via Access and Secret Keys. This is not safe practice, consider to use IAM Role instead.");

            AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
            s3client = new AmazonS3Client(awsCredentials);
        } else {
            System.out.println("Connecting to AWS via Instance Profile Credentials");

            s3client = new AmazonS3Client(new InstanceProfileCredentialsProvider());
        }

        //String file = "rda/rif/class:collection/54800.xml";

        ListObjectsRequest listObjectsRequest;
        ObjectListing objectListing;

        String file = prefix + "/latest.txt";
        S3Object object = s3client.getObject(new GetObjectRequest(bucket, file));

        String latest;
        try (InputStream txt = object.getObjectContent()) {
            latest = prefix + "/" + IOUtils.toString(txt, StandardCharsets.UTF_8).trim() + "/";
        }

        System.out.println("S3 Repository: " + latest);

        listObjectsRequest = new ListObjectsRequest().withBucketName(bucket).withPrefix(latest);
        do {
            objectListing = s3client.listObjects(listObjectsRequest);
            for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {

                file = objectSummary.getKey();

                System.out.println("Processing file: " + file);

                object = s3client.getObject(new GetObjectRequest(bucket, file));
                String xml = null;

                if (null != template) {
                    Source reader = new StreamSource(object.getObjectContent());
                    StringWriter writer = new StringWriter();

                    Transformer transformer = template.newTransformer();
                    transformer.transform(reader, new StreamResult(writer));

                    xml = writer.toString();
                } else {
                    InputStream is = object.getObjectContent();

                    xml = IOUtils.toString(is, ENCODING);
                }

                URL url = new URL(baseUrl + "/registry/import/import_s3/");

                StringBuilder sb = new StringBuilder();
                addParam(sb, "id", source);
                addParam(sb, "xml", xml);

                //System.out.println(sb.toString());

                WebResource webResource = client.resource(url.toString());
                ClientResponse response = webResource
                        .header("User-Agent",
                                "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0")
                        .accept(MediaType.APPLICATION_JSON, "*/*").acceptLanguage("en-US", "en")
                        .type(MediaType.APPLICATION_FORM_URLENCODED).cookie(cookie)
                        .post(ClientResponse.class, sb.toString());

                if (response.getStatus() != 200) {
                    throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
                }

                String output = response.getEntity(String.class);

                Result result = mapper.readValue(output, Result.class);

                if (!result.getStatus().equals("OK")) {
                    System.err.println(result.getMessage());

                    break;
                } else
                    System.out.println(result.getMessage());
            }
            listObjectsRequest.setMarker(objectListing.getNextMarker());
        } while (objectListing.isTruncated());

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

From source file:org.sakaiproject.portal.xsltcharon.impl.XsltRenderEngine.java

public Transformer getTransformer(XsltRenderContext xrc) {
    try {/*from  ww  w .j  av a 2 s .c o  m*/
        Templates templates = null;
        boolean skin = false;

        if (xrc.getAlternateTemplate() != null) {
            templates = getTemplates().get(xrc.getAlternateTemplate());
        }

        // test seperately in case the param wasnt' correct
        if (templates == null) {
            templates = getSkinTemplates(xrc);
            skin = true;
        }

        if (templates == null) {
            templates = getDefaultTemplates();
            skin = false;
        }

        Transformer trans = templates.newTransformer();
        trans.setURIResolver(getServletResolver(skin));
        return trans;
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:sdf_manager.ExporterSiteHTML.java

/**
 *
 * @return/*from w w w . j  av a  2s.c o  m*/
 */
public Document processDatabase() {
    OutputStream os = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        SDF_Util.getProperties();
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();

        Iterator itrSites = this.sitecodes.iterator();
        int flush = 0;
        ExporterSiteHTML.log.info("Parsing sitecodes...");

        Document doc = docBuilder.newDocument();
        Element sdfs = doc.createElement("sdfs");
        doc.appendChild(sdfs);

        while (itrSites.hasNext()) {
            Element sdf = doc.createElement("sdf");
            Element siteIdentification = doc.createElement("siteIdentification");

            Site site = (Site) session.get(Site.class, (String) itrSites.next()); // results.get(i);

            siteIdentification.appendChild(doc.createElement("siteType"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteType(), "siteType")));
            siteIdentification.appendChild(doc.createElement("siteCode"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteCode().toUpperCase(), "siteCode")));
            ExporterSiteHTML.log.info("Parsing sitecode:::" + site.getSiteCode());
            siteIdentification.appendChild(doc.createElement("siteName"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteName(), "siteName")));

            if (site.getSiteCompDate() != null) {
                siteIdentification.appendChild(doc.createElement("compilationDate"))
                        .appendChild(doc.createTextNode(
                                fmt(SDF_Util.getFormatDateToXML(site.getSiteCompDate()), "compilationDate")));
            }

            if (site.getSiteUpdateDate() != null) {
                siteIdentification.appendChild(doc.createElement("updateDate")).appendChild(doc.createTextNode(
                        fmt(SDF_Util.getFormatDateToXML(site.getSiteUpdateDate()), "updateDate")));
            }

            Resp resp = site.getResp();
            if (resp != null) {

                Element respNode = doc.createElement("respondent");
                respNode.appendChild(doc.createElement("name"))
                        .appendChild(doc.createTextNode(fmt(resp.getRespName(), "respName")));
                if (resp.getRespAddressArea() != null && !resp.getRespAddressArea().equals("")) {

                    Element addresElem = doc.createElement("address");

                    // THE NAME DOES NOT MATCH THEIR RESPECTIVES
                    addresElem.appendChild(doc.createElement("adminUnit"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespAdminUnit(), "adminUnit")));
                    addresElem.appendChild(doc.createElement("thoroughfare"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespLocatorName(), "locatorName")));
                    addresElem.appendChild(doc.createElement("locatorDesignator"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespThoroughFare(), "thoroughfare")));
                    addresElem.appendChild(doc.createElement("postCode"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespAddressArea(), "addressArea")));
                    addresElem.appendChild(doc.createElement("postName"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespPostName(), "postName")));
                    addresElem.appendChild(doc.createElement("addressArea"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespPostCode(), "postCode")));
                    addresElem.appendChild(doc.createElement("locatorName")).appendChild(
                            doc.createTextNode(fmt(resp.getRespLocatorDesig(), "locatorDesignator")));
                    respNode.appendChild(addresElem);

                } else {
                    Element addresElem = doc.createElement("address");
                    addresElem.appendChild(doc.createElement("addressArea"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespAddress(), "addressArea")));
                    respNode.appendChild(addresElem);
                }

                respNode.appendChild(doc.createElement("email"))
                        .appendChild(doc.createTextNode(fmt(resp.getRespEmail(), "respEmail")));
                siteIdentification.appendChild(respNode);
            }

            if (SDF_ManagerApp.isEmeraldMode()) {
                XmlGenerationUtils.appendDateElement(site.getSiteProposedAsciDate(), siteIdentification,
                        "asciProposalDate", doc);
                if (site.getSiteProposedAsciDate() == null) {
                    XmlGenerationUtils.appendDateElement(XmlGenerationUtils.nullDate(), siteIdentification,
                            "asciProposalDate", doc);
                }
                XmlGenerationUtils.appendDateElement(site.getSiteConfirmedCandidateAsciDate(),
                        siteIdentification, "asciConfirmedCandidateDate", doc);
                XmlGenerationUtils.appendDateElement(site.getSiteConfirmedAsciDate(), siteIdentification,
                        "asciConfirmationDate", doc);
                XmlGenerationUtils.appendDateElement(site.getSiteDesignatedAsciDate(), siteIdentification,
                        "asciDesignationDate", doc);

                siteIdentification.appendChild(doc.createElement("asciLegalReference"))
                        .appendChild(doc.createTextNode(fmt(site.getSiteAsciLegalRef(), "asciLegalReference")));

            } else {

                if (site.getSiteSpaDate() != null) {
                    siteIdentification.appendChild(doc.createElement("spaClassificationDate")).appendChild(
                            doc.createTextNode(fmt(SDF_Util.getFormatDateToXML(site.getSiteSpaDate()),
                                    "spaClassificationDate")));
                } else {
                    siteIdentification.appendChild(doc.createElement("spaClassificationDate"))
                            .appendChild(doc.createTextNode(fmt("0000-00", "spaClassificationDate")));
                }

                siteIdentification.appendChild(doc.createElement("spaLegalReference"))
                        .appendChild(doc.createTextNode(fmt(site.getSiteSpaLegalRef(), "spaLegalReference")));

                if (site.getSiteSciPropDate() != null) {
                    siteIdentification.appendChild(doc.createElement("sciProposalDate")).appendChild(
                            doc.createTextNode(fmt(SDF_Util.getFormatDateToXML(site.getSiteSciPropDate()),
                                    "sciProposalDate")));
                }

                if (site.getSiteSciConfDate() != null) {
                    siteIdentification.appendChild(doc.createElement("sciConfirmationDate")).appendChild(
                            doc.createTextNode(fmt(SDF_Util.getFormatDateToXML(site.getSiteSciConfDate()),
                                    "sciConfirmationDate")));
                }

                if (site.getSiteSacDate() != null) {
                    siteIdentification.appendChild(doc.createElement("sacDesignationDate")).appendChild(
                            doc.createTextNode(fmt(SDF_Util.getFormatDateToXML(site.getSiteSacDate()),
                                    "sacDesignationDate")));
                }

                siteIdentification.appendChild(doc.createElement("sacLegalReference"))
                        .appendChild(doc.createTextNode(fmt(site.getSiteSacLegalRef(), "sacLegalReference")));

            }
            siteIdentification.appendChild(doc.createElement("explanations"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteExplanations(), "explanations")));
            sdf.appendChild(siteIdentification);

            /**************LOCATION***************/

            Element location = doc.createElement("siteLocation");
            location.appendChild(doc.createElement("longitude"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteLongitude(), "longitude")));
            location.appendChild(doc.createElement("latitude"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteLatitude(), "latitude")));
            location.appendChild(doc.createElement("area"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteArea(), "area")));
            location.appendChild(doc.createElement("marineAreaPercentage"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteMarineArea(), "marineArea")));
            location.appendChild(doc.createElement("siteLength"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteLength(), "siteLength")));

            /*regions*/
            Element regions = doc.createElement("adminRegions");
            Set siteRegions = site.getRegions();
            Iterator itr = siteRegions.iterator();
            while (itr.hasNext()) {
                Region r = (Region) itr.next();
                Element rElem = doc.createElement("region");
                rElem.appendChild(doc.createElement("code"))
                        .appendChild(doc.createTextNode(fmt(r.getRegionCode(), "regionCode")));
                //descomentado--> adaptar nuevo xml
                rElem.appendChild(doc.createElement("name"))
                        .appendChild(doc.createTextNode(fmt(r.getRegionName(), "regionName")));
                regions.appendChild(rElem);
            }
            //adaptacion al nuevo xml
            location.appendChild(regions);

            /*bioregions*/
            Element biogeoRegions = doc.createElement("biogeoRegions");
            Set siteBioRegions = site.getSiteBiogeos();
            if (!(siteBioRegions.isEmpty())) {
                Iterator itbr = siteBioRegions.iterator();
                while (itbr.hasNext()) {
                    SiteBiogeo s = (SiteBiogeo) itbr.next();
                    Element biogeoElement = doc.createElement("biogeoRegions");
                    Biogeo b = s.getBiogeo();
                    //this XMl doesn't need validate, so it's better to use bioregion name instead bioregion code
                    biogeoElement.appendChild(doc.createElement("code"))
                            .appendChild(doc.createTextNode(fmt(b.getBiogeoName(), "bioRegionCode")));
                    biogeoElement.appendChild(doc.createElement("percentage"))
                            .appendChild(doc.createTextNode(fmt(s.getBiogeoPercent(), "biogeoPercent")));
                    location.appendChild(biogeoElement);
                }

            }

            sdf.appendChild(location);

            /********ECOLOGICAL INFORMATION***********/
            //adptacion nuevo XML
            Element ecologicalInformation = doc.createElement("ecologicalInformation");

            /************HABITATS****************/
            Element habitatsTypes = doc.createElement("habitatTypes");

            Set siteHabs = site.getHabitats();
            itr = siteHabs.iterator();
            while (itr.hasNext()) {
                Habitat h = (Habitat) itr.next();
                Element hElem = doc.createElement("habitatType");
                hElem.appendChild(doc.createElement("code"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatCode(), "habitatCode")));
                hElem.appendChild(doc.createElement("priorityFormOfHabitatType")).appendChild(
                        doc.createTextNode(fmt(toBoolean(h.getHabitatPriority()), "habitatPriority")));
                hElem.appendChild(doc.createElement("nonPresenceInSite"))
                        .appendChild(doc.createTextNode(fmt(toBoolean(h.getHabitatNp()), "habitatNp")));
                hElem.appendChild(doc.createElement("coveredArea"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatCoverHa(), "habitatCover")));
                hElem.appendChild(doc.createElement("caves"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatCaves(), "habitatCaves")));

                hElem.appendChild(doc.createElement("observationDataQuality"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatDataQuality(), "habitatDataQuality")));
                hElem.appendChild(doc.createElement("representativity")).appendChild(
                        doc.createTextNode(fmt(h.getHabitatRepresentativity(), "habitatRepresentativity")));
                hElem.appendChild(doc.createElement("relativeSurface"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatRelativeSurface(), "relativeSurface")));
                hElem.appendChild(doc.createElement("conservation")).appendChild(
                        doc.createTextNode(fmt(h.getHabitatConservation(), "habitatConservation")));
                hElem.appendChild(doc.createElement("global"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatGlobal(), "habitatGlobal")));

                habitatsTypes.appendChild(hElem);

            }
            ecologicalInformation.appendChild(habitatsTypes);

            /************SPECIES****************/
            Element specieses = doc.createElement("species");
            Set siteSpecies = site.getSpecieses();
            itr = siteSpecies.iterator();
            while (itr.hasNext()) {

                Species s = (Species) itr.next();
                Element sElem = doc.createElement("speciesPopulation");
                sElem.appendChild(doc.createElement("speciesGroup"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesGroup(), "speciesGroup")));
                sElem.appendChild(doc.createElement("speciesCode"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesCode(), "speciesCode")));
                sElem.appendChild(doc.createElement("scientificName"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesName(), "speciesName")));

                sElem.appendChild(doc.createElement("sensitiveInfo")).appendChild(
                        doc.createTextNode(fmt(toBoolean(s.getSpeciesSensitive()), "speciesSensitive")));
                sElem.appendChild(doc.createElement("nonPresenceInSite"))
                        .appendChild(doc.createTextNode(fmt(toBoolean(s.getSpeciesNp()), "speciesNP")));
                sElem.appendChild(doc.createElement("populationType"))
                        .appendChild(doc.createTextNode(fmtToLowerCase(s.getSpeciesType(), "speciesType")));

                Element popElem = doc.createElement("populationSize");
                popElem.appendChild(doc.createElement("lowerBound"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesSizeMin(), "speciesSizeMin")));
                popElem.appendChild(doc.createElement("upperBound"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesSizeMax(), "speciesSizeMax")));
                popElem.appendChild(doc.createElement("countingUnit"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesUnit(), "speciesUnit")));
                sElem.appendChild(popElem);

                if (s.getSpeciesCategory() != null) {
                    if (!("").equals(s.getSpeciesCategory().toString())) {
                        sElem.appendChild(doc.createElement("abundanceCategory")).appendChild(
                                doc.createTextNode(fmtToUpperCase(s.getSpeciesCategory(), "speciesCategory")));
                    }
                }

                sElem.appendChild(doc.createElement("dataQuality"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesDataQuality(), "speciesQuality")));
                // sElem.appendChild(doc.createElement("observationDataQuality")).appendChild(doc.createTextNode(fmt(s.getSpeciesDataQuality(), "speciesQuality")));
                sElem.appendChild(doc.createElement("population"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesPopulation(), "speciesPopulation")));
                sElem.appendChild(doc.createElement("conservation")).appendChild(
                        doc.createTextNode(fmt(s.getSpeciesConservation(), "speciesConservation")));

                sElem.appendChild(doc.createElement("isolation"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesIsolation(), "speciesIsolation")));
                sElem.appendChild(doc.createElement("global"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesGlobal(), "speciesGlobal")));

                specieses.appendChild(sElem);
            }

            siteSpecies = site.getOtherSpecieses();
            itr = siteSpecies.iterator();
            while (itr.hasNext()) {

                OtherSpecies s = (OtherSpecies) itr.next();
                Element sElem = doc.createElement("speciesPopulation");

                sElem.appendChild(doc.createElement("speciesGroup"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesGroup(), "ospeciesGroup")));
                sElem.appendChild(doc.createElement("speciesCode"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesCode(), "ospeciesCode")));
                sElem.appendChild(doc.createElement("scientificName"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesName(), "ospeciesName")));
                sElem.appendChild(doc.createElement("sensitiveInfo")).appendChild(
                        doc.createTextNode(fmt(toBoolean(s.getOtherSpeciesSensitive()), "ospeciesSensitive")));

                if (s.getOtherSpeciesNp() != null) {
                    if (!(("").equals(s.getOtherSpeciesNp().toString()))) {
                        sElem.appendChild(doc.createElement("nonPresenceInSite")).appendChild(
                                doc.createTextNode(fmt(toBoolean(s.getOtherSpeciesNp()), "ospeciesNP")));
                    }
                }

                Element popElem = doc.createElement("populationSize");
                popElem.appendChild(doc.createElement("lowerBound"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesSizeMin(), "speciesSizeMin")));
                popElem.appendChild(doc.createElement("upperBound"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesSizeMax(), "speciesSizeMax")));
                popElem.appendChild(doc.createElement("countingUnit"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesUnit(), "speciesUnit")));
                sElem.appendChild(popElem);
                if (s.getOtherSpeciesCategory() != null) {
                    if (!(("").equals(s.getOtherSpeciesCategory().toString()))) {
                        sElem.appendChild(doc.createElement("abundanceCategory")).appendChild(
                                doc.createTextNode(fmt(s.getOtherSpeciesCategory(), "ospeciesCategory")));
                    }

                }

                //modificar porque es un tree primero es motivations y despues el nodo motivation (solo en el caso que haya motivations es other species en caso contrario
                //es species
                if (s.getOtherSpeciesMotivation() != null && !(("").equals(s.getOtherSpeciesMotivation()))) {
                    Element sElemMot = doc.createElement("motivations");

                    String strMotivation = s.getOtherSpeciesMotivation();
                    StringTokenizer st2 = new StringTokenizer(strMotivation, ",");

                    while (st2.hasMoreElements()) {
                        String mot = (String) st2.nextElement();
                        sElemMot.appendChild(doc.createElement("motivation"))
                                .appendChild(doc.createTextNode(fmt(mot, "ospeciesMotivation")));
                        sElem.appendChild(sElemMot);
                    }
                }

                specieses.appendChild(sElem);
            }
            ecologicalInformation.appendChild(specieses);

            sdf.appendChild(ecologicalInformation);

            /**************DESCRIPTION***********************/
            Element description = doc.createElement("siteDescription");
            Set classes = site.getHabitatClasses();
            itr = classes.iterator();

            while (itr.hasNext()) {
                HabitatClass h = (HabitatClass) itr.next();
                Element cElem = doc.createElement("habitatClass");
                cElem.appendChild(doc.createElement("code"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatClassCode(), "habitatClassCode")));
                cElem.appendChild(doc.createElement("coveragePercentage"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatClassCover(), "habitatClassCover")));
                description.appendChild(cElem);
            }

            description.appendChild(doc.createElement("otherSiteCharacteristics")).appendChild(
                    doc.createTextNode(fmt(site.getSiteCharacteristics(), "otherSiteCharacteristics")));
            description.appendChild(doc.createElement("qualityAndImportance"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteQuality(), "qualityAndImportance")));
            Element impacts = doc.createElement("impacts");
            Set siteImpacts = site.getImpacts();
            itr = siteImpacts.iterator();

            while (itr.hasNext()) {

                Element iElem = doc.createElement("impact");
                Impact im = (Impact) itr.next();
                iElem.appendChild(doc.createElement("code"))
                        .appendChild(doc.createTextNode(fmt(im.getImpactCode(), "impactCode")));

                iElem.appendChild(doc.createElement("rank"))
                        .appendChild(doc.createTextNode(fmt(im.getImpactRank(), "impactRank")));

                if (im.getImpactPollutionCode() != null) {
                    if (!("").equals(im.getImpactPollutionCode().toString())) {
                        iElem.appendChild(doc.createElement("pollutionCode")).appendChild(
                                doc.createTextNode(fmt(im.getImpactPollutionCode(), "impactPollution")));
                    }

                }

                iElem.appendChild(doc.createElement("occurrence"))
                        .appendChild(doc.createTextNode(fmt(im.getImpactOccurrence(), "impactOccurrece")));

                String impacType = "";
                if (im.getImpactType() != null) {
                    if (("P").equals(im.getImpactType().toString())) {
                        impacType = "Positive";
                    } else {
                        impacType = "Negative";
                    }
                }
                iElem.appendChild(doc.createElement("natureOfImpact"))
                        .appendChild(doc.createTextNode(fmt(impacType, "natureOfImpact")));
                impacts.appendChild(iElem);
            }

            description.appendChild(impacts);

            Element ownership = doc.createElement("ownership");
            Set owners = site.getSiteOwnerships();
            itr = owners.iterator();
            while (itr.hasNext()) {
                SiteOwnership o = (SiteOwnership) itr.next();
                Ownership o2 = o.getOwnership();
                Element oElem = doc.createElement("ownershipPart");
                oElem.appendChild(doc.createElement("ownershiptype"))
                        .appendChild(doc.createTextNode(fmt(o2.getOwnershipCode(), "ownershipType")));
                oElem.appendChild(doc.createElement("percent"))
                        .appendChild(doc.createTextNode(fmt(o.getOwnershipPercent(), "ownershipPercent")));
                ownership.appendChild(oElem);
            }

            description.appendChild(ownership);

            Element documentation = doc.createElement("documentation");
            Doc docObj = site.getDoc();
            if (docObj != null) {

                documentation.appendChild(doc.createElement("description"))
                        .appendChild(doc.createTextNode(fmt(docObj.getDocDescription(), "docDescription")));
                Set docLinks = docObj.getDocLinks();
                itr = docLinks.iterator();
                Element links = doc.createElement("links");
                while (itr.hasNext()) {
                    DocLink docLink = (DocLink) itr.next();
                    links.appendChild(doc.createElement("link"))
                            .appendChild(doc.createTextNode(fmt(docLink.getDocLinkUrl(), "linkURL")));
                }
                documentation.appendChild(links);
                description.appendChild(documentation);
            }
            sdf.appendChild(description);

            /********PROTECTION**********/
            Element protection = doc.createElement("siteProtection");

            Element natDesigs = doc.createElement("nationalDesignations");
            Set dsigs = site.getNationalDtypes();
            itr = dsigs.iterator();
            while (itr.hasNext()) {
                NationalDtype dtype = (NationalDtype) itr.next();
                Element nElem = doc.createElement("nationalDesignation");
                nElem.appendChild(doc.createElement("designationCode"))
                        .appendChild(doc.createTextNode(fmt(dtype.getNationalDtypeCode(), "dtypecode")));
                nElem.appendChild(doc.createElement("cover"))
                        .appendChild(doc.createTextNode(fmt(dtype.getNationalDtypeCover(), "dtypecover")));
                natDesigs.appendChild(nElem);
            }
            protection.appendChild(natDesigs);

            Set rels = site.getSiteRelations();
            if (!rels.isEmpty()) {
                Element relations = doc.createElement("relations");
                Element nationalRelations = doc.createElement("nationalRelationships");
                Element internationalRelations = doc.createElement("internationalRelationships");

                itr = rels.iterator();
                while (itr.hasNext()) {

                    SiteRelation rel = (SiteRelation) itr.next();
                    Element rElem;
                    Character scope = rel.getSiteRelationScope();

                    if (("N").equals(scope.toString())) {
                        rElem = doc.createElement("nationalRelationship");
                        rElem.appendChild(doc.createElement("designationCode")).appendChild(
                                doc.createTextNode(fmt(rel.getSiteRelationCode(), "relationCode")));
                        nationalRelations.appendChild(rElem);
                    } else if (("I").equals(scope.toString())) {
                        rElem = doc.createElement("internationalRelationship");
                        rElem.appendChild(doc.createElement("convention")).appendChild(
                                doc.createTextNode(fmt(rel.getSiteRelationConvention(), "relationConvention")));
                        internationalRelations.appendChild(rElem);
                    } else {
                        //                            log("Relation type undefined, ignoring relation: " + scope.toString());
                        continue;
                    }
                    rElem.appendChild(doc.createElement("siteName")).appendChild(
                            doc.createTextNode(fmt(rel.getSiteRelationSitename(), "relationSite")));
                    rElem.appendChild(doc.createElement("type"))
                            .appendChild(doc.createTextNode(fmt(rel.getSiteRelationType(), "relationType")));
                    rElem.appendChild(doc.createElement("cover"))
                            .appendChild(doc.createTextNode(fmt(rel.getSiteRelationCover(), "relationCover")));
                }
                relations.appendChild(nationalRelations);
                relations.appendChild(internationalRelations);

                protection.appendChild(relations);
            }

            protection.appendChild(doc.createElement("siteDesignationAdditional"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteDesignation(), "siteDesignation")));
            sdf.appendChild(protection);

            /******************MANAGEMENT************************/

            Element mgmtElem = doc.createElement("siteManagement");
            Mgmt mgmt = site.getMgmt();
            if (mgmt != null) {
                // Management Body
                Set bodies = mgmt.getMgmtBodies();
                itr = bodies.iterator();
                Element bodiesElem = doc.createElement("managementBodies");
                while (itr.hasNext()) {

                    MgmtBody bodyObj = (MgmtBody) itr.next();
                    Element bElem = doc.createElement("managementBody");
                    bElem.appendChild(doc.createElement("organisation"))
                            .appendChild(doc.createTextNode(fmt(bodyObj.getMgmtBodyOrg(), "mgmtBodyOrg")));
                    //if el campo addressunestructured esta vacio entonces addres es un tipo complejo (implementar) en caso contrario
                    if (bodyObj.getMgmtBodyAddressArea() != null
                            && !bodyObj.getMgmtBodyAddressArea().equals("")) {
                        Element addresElem = doc.createElement("address");

                        addresElem.appendChild(doc.createElement("adminUnit")).appendChild(
                                doc.createTextNode(fmt(bodyObj.getMgmtBodyAdminUnit(), "adminUnit") + "  "));
                        addresElem.appendChild(doc.createElement("locatorDesignator")).appendChild(doc
                                .createTextNode(fmt(bodyObj.getMgmtBodyThroughFare(), "thoroughfare") + "  "));
                        addresElem.appendChild(doc.createElement("locatorName")).appendChild(doc.createTextNode(
                                fmt(bodyObj.getMgmtBodyLocatorDesignator(), "locatorDesignator") + "  "));
                        addresElem.appendChild(doc.createElement("addressArea")).appendChild(
                                doc.createTextNode(fmt(bodyObj.getMgmtBodyPostCode(), "postCode") + "  "));
                        addresElem.appendChild(doc.createElement("postName")).appendChild(
                                doc.createTextNode(fmt(bodyObj.getMgmtBodyPostName(), "postName") + "  "));
                        addresElem.appendChild(doc.createElement("postCode")).appendChild(doc
                                .createTextNode(fmt(bodyObj.getMgmtBodyAddressArea(), "addressArea") + "  "));
                        addresElem.appendChild(doc.createElement("thoroughfare")).appendChild(doc
                                .createTextNode(fmt(bodyObj.getMgmtBodyLocatorName(), "locatorName") + "  "));

                        bElem.appendChild(addresElem);
                    } else {
                        Element addresElem = doc.createElement("address");
                        addresElem.appendChild(doc.createElement("addressArea")).appendChild(
                                doc.createTextNode(fmt(bodyObj.getMgmtBodyAddress(), "addressArea")));
                        bElem.appendChild(addresElem);
                    }

                    bElem.appendChild(doc.createElement("email"))
                            .appendChild(doc.createTextNode(fmt(bodyObj.getMgmtBodyEmail(), "mgmtBodyMail")));
                    bodiesElem.appendChild(bElem);
                }
                mgmtElem.appendChild(bodiesElem);

                // Management Plan

                Character status = mgmt.getMgmtStatus();
                Element mgmtExists = (Element) mgmtElem.appendChild(doc.createElement("exists"));
                if (status != null) {
                    mgmtExists
                            .appendChild(doc.createTextNode(fmt(Character.toUpperCase(status), "mgmtExists")));
                }
                Set plans = mgmt.getMgmtPlans();
                itr = plans.iterator();
                Element plansElem = doc.createElement("managementPlans");
                plansElem.appendChild(mgmtExists);
                while (itr.hasNext()) {
                    MgmtPlan planObj = (MgmtPlan) itr.next();
                    Element pElem = doc.createElement("managementPlan");
                    pElem.appendChild(doc.createElement("name"))
                            .appendChild(doc.createTextNode(fmt(planObj.getMgmtPlanName(), "mgmtPlanName")));
                    pElem.appendChild(doc.createElement("url"))
                            .appendChild(doc.createTextNode(fmt(planObj.getMgmtPlanUrl(), "mgmtPlanUrl")));
                    plansElem.appendChild(pElem);
                }
                mgmtElem.appendChild(plansElem);

                mgmtElem.appendChild(doc.createElement("conservationMeasures")).appendChild(
                        doc.createTextNode(fmt(mgmt.getMgmtConservMeasures(), "conservationMeasures")));
            }
            sdf.appendChild(mgmtElem);

            Map map = site.getMap();
            Element mapElem = doc.createElement("map");
            if (map != null) {
                mapElem.appendChild(doc.createElement("InspireID"))
                        .appendChild(doc.createTextNode(fmt(map.getMapInspire(), "mapInspireID")));

                Boolean bMap;
                if (map.getMapPdf() != null && map.getMapPdf().equals(Short.valueOf("1"))) {
                    bMap = true;
                } else {
                    bMap = false;
                }
                mapElem.appendChild(doc.createElement("pdfProvided"))
                        .appendChild(doc.createTextNode(fmt(bMap, "mapPDF")));
                mapElem.appendChild(doc.createElement("mapReference"))
                        .appendChild(doc.createTextNode(fmt(map.getMapReference(), "mapRef")));
            }
            sdf.appendChild(mapElem);

            if (flush++ % 100 == 0) {
                session.clear();
            }
            sdfs.appendChild(sdf);
        }

        //All the data is stored in the node instead of the document.
        Source source = new DOMSource(doc);

        // File file = new File(this.fileName);
        File file = new File("xsl" + File.separator + this.siteCode + ".html");

        Result result = new StreamResult(file.toURI().getPath());

        TransformerFactory tFactory = TransformerFactory.newInstance();
        String xslFileName = SDF_ManagerApp.isEmeraldMode() ? "EmeraldSiteXSL.xsl" : "SiteXSL.xsl";

        Source xsl = new StreamSource("." + File.separator + "xsl" + File.separator + xslFileName);
        Templates template = tFactory.newTemplates(xsl);
        Transformer transformer = template.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS,
                "siteName name otherSiteCharacteristics"
                        + " qualityAndImportance selectiveBasis derogationJustification comments "
                        + "location licensedJustification licensingAuthority licenseValidFrom licenseValidUntil otherType "
                        + "method activity reason");

        transformer.transform(source, result);

        String pdfPath = new File("").getAbsolutePath() + File.separator + "xsl" + File.separator
                + this.siteCode + ".pdf";
        // File inputFile = new File(this.fileName);
        File inputFile = new File("xsl" + File.separator + this.siteCode + ".html");
        os = new FileOutputStream(new File(pdfPath));

        ITextRenderer renderer = new ITextRenderer();
        FontFactory.register("resources/fonts");

        renderer.setDocument(inputFile);
        renderer.layout();
        renderer.createPDF(os);

        Desktop desktop = null;
        // Before more Desktop API is used, first check
        // whether the API is supported by this particular
        // virtual machine (VM) on this particular host.
        if (Desktop.isDesktopSupported()) {
            desktop = Desktop.getDesktop();
            Desktop.getDesktop().open(file);
        }
        return null;
    } catch (TransformerConfigurationException e) {
        ExporterSiteHTML.log
                .error("A TransformerConfigurationException has occurred in processDatabase. Error Message:::"
                        + e.getMessage());
        return null;
    } catch (TransformerException e) {
        ExporterSiteHTML.log.error(
                "A TransformerException has occurred in processDatabase. Error Message:::" + e.getMessage());
        return null;
    } catch (FileNotFoundException e) {
        ExporterSiteHTML.log.error(
                "A FileNotFoundException has occurred in processDatabase. Error Message:::" + e.getMessage());
        return null;
    } catch (IOException e) {
        ExporterSiteHTML.log
                .error("An IOException has occurred in processDatabase. Error Message:::" + e.getMessage());
        return null;
    } catch (Exception e) {
        ExporterSiteHTML.log.error(
                "A general exception has occurred in processDatabase. Error Message:::" + e.getMessage());
        return null;
    } finally {
        IOUtils.closeQuietly(os);
        session.close();
    }

}

From source file:sdf_manager.GenerateSitePDF.java

/**
 *
 * @return//from   w  w w.ja v a  2 s .  co m
 */
public Document processDatabase() {
    OutputStream os = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Iterator itrSites = this.sitecodes.iterator();
        int flush = 0;

        Document doc = docBuilder.newDocument();
        Element sdfs = doc.createElement("sdfs");
        doc.appendChild(sdfs);

        while (itrSites.hasNext()) {
            Element sdf = doc.createElement("sdf");
            Element siteIdentification = doc.createElement("siteIdentification");

            Site site = (Site) session.get(Site.class, (String) itrSites.next()); // results.get(i);

            siteIdentification.appendChild(doc.createElement("siteType"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteType(), "siteType")));
            siteIdentification.appendChild(doc.createElement("siteCode"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteCode(), "siteCode")));
            GenerateSitePDF.log.info("Parsing sitecode:::" + site.getSiteCode());
            siteIdentification.appendChild(doc.createElement("siteName"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteName(), "siteName")));

            if (site.getSiteCompDate() != null && !(("").equals(site.getSiteCompDate()))) {
                siteIdentification.appendChild(doc.createElement("compilationDate"))
                        .appendChild(doc.createTextNode(
                                fmt(SDF_Util.getFormatDateToXML(site.getSiteCompDate()), "compilationDate")));
            }

            if (site.getSiteUpdateDate() != null && !(("").equals(site.getSiteUpdateDate()))) {
                siteIdentification.appendChild(doc.createElement("updateDate")).appendChild(doc.createTextNode(
                        fmt(SDF_Util.getFormatDateToXML(site.getSiteUpdateDate()), "updateDate")));
            }

            Resp resp = site.getResp();
            if (resp != null) {
                Element respNode = doc.createElement("respondent");
                respNode.appendChild(doc.createElement("name"))
                        .appendChild(doc.createTextNode(fmt(resp.getRespName(), "respName")));

                if (resp.getRespAddressArea() != null && !resp.getRespAddressArea().equals("")) {
                    Element addresElem = doc.createElement("address");

                    addresElem.appendChild(doc.createElement("adminUnit"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespAdminUnit(), "adminUnit")));
                    addresElem.appendChild(doc.createElement("thoroughfare"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespLocatorName(), "locatorName")));
                    addresElem.appendChild(doc.createElement("locatorDesignator"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespThoroughFare(), "thoroughfare")));
                    addresElem.appendChild(doc.createElement("postCode"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespAddressArea(), "addressArea")));
                    addresElem.appendChild(doc.createElement("postName"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespPostName(), "postName")));
                    addresElem.appendChild(doc.createElement("addressArea"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespPostCode(), "postCode")));
                    addresElem.appendChild(doc.createElement("locatorName")).appendChild(
                            doc.createTextNode(fmt(resp.getRespLocatorDesig(), "locatorDesignator")));
                    respNode.appendChild(addresElem);
                } else {
                    Element addresElem = doc.createElement("address");
                    addresElem.appendChild(doc.createElement("addressArea"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespAddress(), "addressArea")));
                    respNode.appendChild(addresElem);
                    // respNode.appendChild(doc.createElement("addressUnstructured")).appendChild(doc.createTextNode(fmt(resp.getRespAddress(), "respAddress")));
                }

                respNode.appendChild(doc.createElement("email"))
                        .appendChild(doc.createTextNode(fmt(resp.getRespEmail(), "respEmail")));
                siteIdentification.appendChild(respNode);
            }

            if (SDF_ManagerApp.isEmeraldMode()) {
                XmlGenerationUtils.appendDateElement(site.getSiteProposedAsciDate(), siteIdentification,
                        "asciProposalDate", doc);
                if (site.getSiteProposedAsciDate() == null) {
                    XmlGenerationUtils.appendDateElement(XmlGenerationUtils.nullDate(), siteIdentification,
                            "asciProposalDate", doc);
                }
                XmlGenerationUtils.appendDateElement(site.getSiteConfirmedCandidateAsciDate(),
                        siteIdentification, "asciConfirmedCandidateDate", doc);
                XmlGenerationUtils.appendDateElement(site.getSiteConfirmedAsciDate(), siteIdentification,
                        "asciConfirmationDate", doc);
                XmlGenerationUtils.appendDateElement(site.getSiteDesignatedAsciDate(), siteIdentification,
                        "asciDesignationDate", doc);

                siteIdentification.appendChild(doc.createElement("asciLegalReference"))
                        .appendChild(doc.createTextNode(fmt(site.getSiteAsciLegalRef(), "asciLegalReference")));

            } else {
                if (site.getSiteSpaDate() != null) {
                    siteIdentification.appendChild(doc.createElement("spaClassificationDate")).appendChild(
                            doc.createTextNode(fmt(SDF_Util.getFormatDateToXML(site.getSiteSpaDate()),
                                    "spaClassificationDate")));
                } else {
                    siteIdentification.appendChild(doc.createElement("spaClassificationDate"))
                            .appendChild(doc.createTextNode(fmt("0000-00", "spaClassificationDate")));
                }

                siteIdentification.appendChild(doc.createElement("spaLegalReference"))
                        .appendChild(doc.createTextNode(fmt(site.getSiteSpaLegalRef(), "spaLegalReference")));

                if (site.getSiteSciPropDate() != null) {
                    siteIdentification.appendChild(doc.createElement("sciProposalDate")).appendChild(
                            doc.createTextNode(fmt(SDF_Util.getFormatDateToXML(site.getSiteSciPropDate()),
                                    "sciProposalDate")));
                }

                if (site.getSiteSciConfDate() != null) {
                    siteIdentification.appendChild(doc.createElement("sciConfirmationDate")).appendChild(
                            doc.createTextNode(fmt(SDF_Util.getFormatDateToXML(site.getSiteSciConfDate()),
                                    "sciConfirmationDate")));
                }

                if (site.getSiteSacDate() != null) {
                    siteIdentification.appendChild(doc.createElement("sacDesignationDate")).appendChild(
                            doc.createTextNode(fmt(SDF_Util.getFormatDateToXML(site.getSiteSacDate()),
                                    "sacDesignationDate")));
                }

                siteIdentification.appendChild(doc.createElement("sacLegalReference"))
                        .appendChild(doc.createTextNode(fmt(site.getSiteSacLegalRef(), "sacLegalReference")));
            }
            siteIdentification.appendChild(doc.createElement("explanations"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteExplanations(), "explanations")));
            sdf.appendChild(siteIdentification);

            /**************LOCATION***************/
            Element location = doc.createElement("siteLocation");
            location.appendChild(doc.createElement("longitude"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteLongitude(), "longitude")));
            location.appendChild(doc.createElement("latitude"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteLatitude(), "latitude")));
            location.appendChild(doc.createElement("area"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteArea(), "area")));
            location.appendChild(doc.createElement("marineAreaPercentage"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteMarineArea(), "marineArea")));
            location.appendChild(doc.createElement("siteLength"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteLength(), "siteLength")));

            /*regions*/
            Element regions = doc.createElement("adminRegions");
            Set siteRegions = site.getRegions();
            Iterator itr = siteRegions.iterator();
            while (itr.hasNext()) {
                Region r = (Region) itr.next();
                Element rElem = doc.createElement("region");
                rElem.appendChild(doc.createElement("code"))
                        .appendChild(doc.createTextNode(fmt(r.getRegionCode(), "regionCode")));
                //descomentado--> adaptar nuevo xml
                rElem.appendChild(doc.createElement("name"))
                        .appendChild(doc.createTextNode(fmt(r.getRegionName(), "regionName")));
                regions.appendChild(rElem);
            }
            //adaptacion al nuevo xml
            location.appendChild(regions);

            /*bioregions*/
            Element biogeoRegions = doc.createElement("biogeoRegions");
            Set siteBioRegions = site.getSiteBiogeos();
            if (!(siteBioRegions.isEmpty())) {
                Iterator itbr = siteBioRegions.iterator();
                while (itbr.hasNext()) {
                    SiteBiogeo s = (SiteBiogeo) itbr.next();

                    Element biogeoElement = doc.createElement("biogeoRegions");
                    Biogeo b = s.getBiogeo();
                    //this XMl doesn't need validate, so it's better to use bioregion name instead bioregion code
                    biogeoElement.appendChild(doc.createElement("code"))
                            .appendChild(doc.createTextNode(fmt(b.getBiogeoName(), "bioRegionCode")));
                    biogeoElement.appendChild(doc.createElement("percentage"))
                            .appendChild(doc.createTextNode(fmt(s.getBiogeoPercent(), "biogeoPercent")));
                    location.appendChild(biogeoElement);
                }
            }

            sdf.appendChild(location);

            /********ECOLOGICAL INFORMATION***********/
            //adptacion nuevo XML
            Element ecologicalInformation = doc.createElement("ecologicalInformation");

            /************HABITATS****************/
            Element habitatsTypes = doc.createElement("habitatTypes");

            Set siteHabs = site.getHabitats();
            itr = siteHabs.iterator();
            while (itr.hasNext()) {
                Habitat h = (Habitat) itr.next();
                Element hElem = doc.createElement("habitatType");
                hElem.appendChild(doc.createElement("code"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatCode(), "habitatCode")));
                hElem.appendChild(doc.createElement("priorityFormOfHabitatType")).appendChild(
                        doc.createTextNode(fmt(toBoolean(h.getHabitatPriority()), "habitatPriority")));
                hElem.appendChild(doc.createElement("nonPresenceInSite"))
                        .appendChild(doc.createTextNode(fmt(toBoolean(h.getHabitatNp()), "habitatNp")));
                hElem.appendChild(doc.createElement("coveredArea"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatCoverHa(), "habitatCover")));
                hElem.appendChild(doc.createElement("caves"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatCaves(), "habitatCaves")));

                hElem.appendChild(doc.createElement("observationDataQuality"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatDataQuality(), "habitatDataQuality")));
                hElem.appendChild(doc.createElement("representativity")).appendChild(
                        doc.createTextNode(fmt(h.getHabitatRepresentativity(), "habitatRepresentativity")));
                hElem.appendChild(doc.createElement("relativeSurface"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatRelativeSurface(), "relativeSurface")));
                hElem.appendChild(doc.createElement("conservation")).appendChild(
                        doc.createTextNode(fmt(h.getHabitatConservation(), "habitatConservation")));
                hElem.appendChild(doc.createElement("global"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatGlobal(), "habitatGlobal")));

                habitatsTypes.appendChild(hElem);
            }
            ecologicalInformation.appendChild(habitatsTypes);

            /************SPECIES****************/
            Element specieses = doc.createElement("species");
            Set siteSpecies = site.getSpecieses();
            itr = siteSpecies.iterator();
            while (itr.hasNext()) {
                Species s = (Species) itr.next();
                Element sElem = doc.createElement("speciesPopulation");
                sElem.appendChild(doc.createElement("speciesGroup"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesGroup(), "speciesGroup")));
                sElem.appendChild(doc.createElement("speciesCode"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesCode(), "speciesCode")));
                sElem.appendChild(doc.createElement("scientificName"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesName(), "speciesName")));

                sElem.appendChild(doc.createElement("sensitiveInfo")).appendChild(
                        doc.createTextNode(fmt(toBoolean(s.getSpeciesSensitive()), "speciesSensitive")));
                sElem.appendChild(doc.createElement("nonPresenceInSite"))
                        .appendChild(doc.createTextNode(fmt(toBoolean(s.getSpeciesNp()), "speciesNP")));
                sElem.appendChild(doc.createElement("populationType"))
                        .appendChild(doc.createTextNode(fmtToLowerCase(s.getSpeciesType(), "speciesType")));

                Element popElem = doc.createElement("populationSize");
                popElem.appendChild(doc.createElement("lowerBound"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesSizeMin(), "speciesSizeMin")));
                popElem.appendChild(doc.createElement("upperBound"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesSizeMax(), "speciesSizeMax")));
                popElem.appendChild(doc.createElement("countingUnit"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesUnit(), "speciesUnit")));
                sElem.appendChild(popElem);

                if (s.getSpeciesCategory() != null) {
                    if (!("").equals(s.getSpeciesCategory().toString())) {
                        sElem.appendChild(doc.createElement("abundanceCategory")).appendChild(
                                doc.createTextNode(fmtToUpperCase(s.getSpeciesCategory(), "speciesCategory")));
                    }
                }

                sElem.appendChild(doc.createElement("dataQuality"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesDataQuality(), "speciesQuality")));
                // sElem.appendChild(doc.createElement("observationDataQuality")).appendChild(doc.createTextNode(fmt(s.getSpeciesDataQuality(), "speciesQuality")));
                sElem.appendChild(doc.createElement("population"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesPopulation(), "speciesPopulation")));
                sElem.appendChild(doc.createElement("conservation")).appendChild(
                        doc.createTextNode(fmt(s.getSpeciesConservation(), "speciesConservation")));

                sElem.appendChild(doc.createElement("isolation"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesIsolation(), "speciesIsolation")));
                sElem.appendChild(doc.createElement("global"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesGlobal(), "speciesGlobal")));

                specieses.appendChild(sElem);
            }

            siteSpecies = site.getOtherSpecieses();
            itr = siteSpecies.iterator();
            while (itr.hasNext()) {
                OtherSpecies s = (OtherSpecies) itr.next();
                Element sElem = doc.createElement("speciesPopulation");

                sElem.appendChild(doc.createElement("speciesGroup"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesGroup(), "ospeciesGroup")));
                sElem.appendChild(doc.createElement("speciesCode"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesCode(), "ospeciesCode")));
                sElem.appendChild(doc.createElement("scientificName"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesName(), "ospeciesName")));
                sElem.appendChild(doc.createElement("sensitiveInfo")).appendChild(
                        doc.createTextNode(fmt(toBoolean(s.getOtherSpeciesSensitive()), "ospeciesSensitive")));

                if (s.getOtherSpeciesNp() != null) {
                    if (!("").equals(s.getOtherSpeciesNp().toString())) {
                        sElem.appendChild(doc.createElement("nonPresenceInSite")).appendChild(
                                doc.createTextNode(fmt(toBoolean(s.getOtherSpeciesNp()), "ospeciesNP")));
                    }
                }

                Element popElem = doc.createElement("populationSize");
                popElem.appendChild(doc.createElement("lowerBound"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesSizeMin(), "speciesSizeMin")));
                popElem.appendChild(doc.createElement("upperBound"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesSizeMax(), "speciesSizeMax")));
                popElem.appendChild(doc.createElement("countingUnit"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesUnit(), "speciesUnit")));
                sElem.appendChild(popElem);
                if (s.getOtherSpeciesCategory() != null) {
                    if (!("").equals(s.getOtherSpeciesCategory().toString())) {
                        sElem.appendChild(doc.createElement("abundanceCategory")).appendChild(
                                doc.createTextNode(fmt(s.getOtherSpeciesCategory(), "ospeciesCategory")));
                    }
                }

                //modificar porque es un tree primero es motivations y despues el nodo motivation (solo en el caso que haya motivations es other species en caso contrario
                //es species
                if (s.getOtherSpeciesMotivation() != null && !(("").equals(s.getOtherSpeciesMotivation()))) {
                    Element sElemMot = doc.createElement("motivations");

                    String strMotivation = s.getOtherSpeciesMotivation();
                    StringTokenizer st2 = new StringTokenizer(strMotivation, ",");

                    while (st2.hasMoreElements()) {
                        String mot = (String) st2.nextElement();
                        sElemMot.appendChild(doc.createElement("motivation"))
                                .appendChild(doc.createTextNode(fmt(mot, "ospeciesMotivation")));
                        sElem.appendChild(sElemMot);
                    }
                }

                specieses.appendChild(sElem);
            }

            ecologicalInformation.appendChild(specieses);

            sdf.appendChild(ecologicalInformation);

            /**************DESCRIPTION***********************/
            Element description = doc.createElement("siteDescription");
            Set classes = site.getHabitatClasses();
            itr = classes.iterator();
            while (itr.hasNext()) {
                HabitatClass h = (HabitatClass) itr.next();
                Element cElem = doc.createElement("habitatClass");
                cElem.appendChild(doc.createElement("code"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatClassCode(), "habitatClassCode")));
                cElem.appendChild(doc.createElement("coveragePercentage"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatClassCover(), "habitatClassCover")));
                description.appendChild(cElem);
            }
            description.appendChild(doc.createElement("otherSiteCharacteristics")).appendChild(
                    doc.createTextNode(fmt(site.getSiteCharacteristics(), "otherSiteCharacteristics")));
            description.appendChild(doc.createElement("qualityAndImportance"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteQuality(), "qualityAndImportance")));
            Element impacts = doc.createElement("impacts");
            Set siteImpacts = site.getImpacts();
            itr = siteImpacts.iterator();
            while (itr.hasNext()) {
                Element iElem = doc.createElement("impact");
                Impact im = (Impact) itr.next();
                iElem.appendChild(doc.createElement("code"))
                        .appendChild(doc.createTextNode(fmt(im.getImpactCode(), "impactCode")));

                iElem.appendChild(doc.createElement("rank"))
                        .appendChild(doc.createTextNode(fmt(im.getImpactRank(), "impactRank")));

                if (im.getImpactPollutionCode() != null) {
                    if (!("").equals(im.getImpactPollutionCode().toString())) {
                        iElem.appendChild(doc.createElement("pollutionCode")).appendChild(
                                doc.createTextNode(fmt(im.getImpactPollutionCode(), "impactPollution")));
                    }
                }

                iElem.appendChild(doc.createElement("occurrence"))
                        .appendChild(doc.createTextNode(fmt(im.getImpactOccurrence(), "impactOccurrece")));

                String impacType = "";
                if (im.getImpactType() != null) {
                    if (("P").equals(im.getImpactType().toString())) {
                        impacType = "Positive";
                    } else {
                        impacType = "Negative";
                    }
                }

                iElem.appendChild(doc.createElement("natureOfImpact"))
                        .appendChild(doc.createTextNode(fmt(impacType, "natureOfImpact")));
                impacts.appendChild(iElem);
            }

            description.appendChild(impacts);

            Element ownership = doc.createElement("ownership");
            Set owners = site.getSiteOwnerships();
            itr = owners.iterator();
            while (itr.hasNext()) {
                SiteOwnership o = (SiteOwnership) itr.next();
                Ownership o2 = o.getOwnership();
                Element oElem = doc.createElement("ownershipPart");
                //oElem.appendChild(doc.createElement("ownershiptype")).appendChild(doc.createTextNode(fmt(o2.getOwnershipType(), "ownershipType")));
                oElem.appendChild(doc.createElement("ownershiptype"))
                        .appendChild(doc.createTextNode(fmt(o2.getOwnershipCode(), "ownershipType")));
                oElem.appendChild(doc.createElement("percent"))
                        .appendChild(doc.createTextNode(fmt(o.getOwnershipPercent(), "ownershipPercent")));
                ownership.appendChild(oElem);
            }

            description.appendChild(ownership);

            Element documentation = doc.createElement("documentation");
            Doc docObj = site.getDoc();
            if (docObj != null) {
                documentation.appendChild(doc.createElement("description"))
                        .appendChild(doc.createTextNode(fmt(docObj.getDocDescription(), "docDescription")));
                Set docLinks = docObj.getDocLinks();
                itr = docLinks.iterator();
                Element links = doc.createElement("links");
                while (itr.hasNext()) {
                    DocLink docLink = (DocLink) itr.next();
                    links.appendChild(doc.createElement("link"))
                            .appendChild(doc.createTextNode(fmt(docLink.getDocLinkUrl(), "linkURL")));
                }
                documentation.appendChild(links);
                description.appendChild(documentation);
            }
            sdf.appendChild(description);

            /********PROTECTION**********/
            Element protection = doc.createElement("siteProtection");

            Element natDesigs = doc.createElement("nationalDesignations");
            Set dsigs = site.getNationalDtypes();
            itr = dsigs.iterator();
            while (itr.hasNext()) {
                NationalDtype dtype = (NationalDtype) itr.next();
                Element nElem = doc.createElement("nationalDesignation");
                nElem.appendChild(doc.createElement("designationCode"))
                        .appendChild(doc.createTextNode(fmt(dtype.getNationalDtypeCode(), "dtypecode")));
                nElem.appendChild(doc.createElement("cover"))
                        .appendChild(doc.createTextNode(fmt(dtype.getNationalDtypeCover(), "dtypecover")));
                natDesigs.appendChild(nElem);
            }
            protection.appendChild(natDesigs);

            Set rels = site.getSiteRelations();
            if (!rels.isEmpty()) {
                Element relations = doc.createElement("relations");
                Element nationalRelations = doc.createElement("nationalRelationships");
                Element internationalRelations = doc.createElement("internationalRelationships");

                itr = rels.iterator();
                while (itr.hasNext()) {
                    SiteRelation rel = (SiteRelation) itr.next();
                    Element rElem;
                    Character scope = rel.getSiteRelationScope();
                    if (Character.toLowerCase(scope) == 'n') {
                        rElem = doc.createElement("nationalRelationship");
                        rElem.appendChild(doc.createElement("designationCode")).appendChild(
                                doc.createTextNode(fmt(rel.getSiteRelationCode(), "relationCode")));
                        nationalRelations.appendChild(rElem);
                    } else if (Character.toLowerCase(scope) == 'i') {
                        rElem = doc.createElement("internationalRelationship");
                        rElem.appendChild(doc.createElement("convention")).appendChild(
                                doc.createTextNode(fmt(rel.getSiteRelationConvention(), "relationConvention")));
                        internationalRelations.appendChild(rElem);
                    } else {
                        //                            log("Relation type undefined, ignoring relation: " + scope.toString());
                        continue;
                    }
                    rElem.appendChild(doc.createElement("siteName")).appendChild(
                            doc.createTextNode(fmt(rel.getSiteRelationSitename(), "relationSite")));
                    rElem.appendChild(doc.createElement("type"))
                            .appendChild(doc.createTextNode(fmt(rel.getSiteRelationType(), "relationType")));
                    rElem.appendChild(doc.createElement("cover"))
                            .appendChild(doc.createTextNode(fmt(rel.getSiteRelationCover(), "relationCover")));
                }
                relations.appendChild(nationalRelations);
                relations.appendChild(internationalRelations);

                protection.appendChild(relations);
            }

            protection.appendChild(doc.createElement("siteDesignationAdditional"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteDesignation(), "siteDesignation")));
            sdf.appendChild(protection);

            /******************MANAGEMENT************************/
            Element mgmtElem = doc.createElement("siteManagement");
            Mgmt mgmt = site.getMgmt();
            if (mgmt != null) {
                /***Mangement Body**/
                Set bodies = mgmt.getMgmtBodies();
                itr = bodies.iterator();
                Element bodiesElem = doc.createElement("managementBodies");
                while (itr.hasNext()) {
                    MgmtBody bodyObj = (MgmtBody) itr.next();
                    Element bElem = doc.createElement("managementBody");
                    bElem.appendChild(doc.createElement("organisation"))
                            .appendChild(doc.createTextNode(fmt(bodyObj.getMgmtBodyOrg(), "mgmtBodyOrg")));
                    //if el campo addressunestructured esta vacio entonces addres es un tipo complejo (implementar) en caso contrario
                    //if (resp.getRespAddressArea() != null && !!resp.getRespAddressArea().equals("")) {
                    if (bodyObj.getMgmtBodyAddressArea() != null
                            && !bodyObj.getMgmtBodyAddressArea().equals("")) {
                        Element addresElem = doc.createElement("address");

                        addresElem.appendChild(doc.createElement("adminUnit")).appendChild(
                                doc.createTextNode(fmt(bodyObj.getMgmtBodyAdminUnit(), "adminUnit") + "  "));
                        addresElem.appendChild(doc.createElement("locatorDesignator")).appendChild(doc
                                .createTextNode(fmt(bodyObj.getMgmtBodyThroughFare(), "thoroughfare") + "  "));
                        addresElem.appendChild(doc.createElement("locatorName")).appendChild(doc.createTextNode(
                                fmt(bodyObj.getMgmtBodyLocatorDesignator(), "locatorDesignator") + "  "));
                        addresElem.appendChild(doc.createElement("addressArea")).appendChild(
                                doc.createTextNode(fmt(bodyObj.getMgmtBodyPostCode(), "postCode") + "  "));
                        addresElem.appendChild(doc.createElement("postName")).appendChild(
                                doc.createTextNode(fmt(bodyObj.getMgmtBodyPostName(), "postName") + "  "));
                        addresElem.appendChild(doc.createElement("postCode")).appendChild(doc
                                .createTextNode(fmt(bodyObj.getMgmtBodyAddressArea(), "addressArea") + "  "));
                        addresElem.appendChild(doc.createElement("thoroughfare")).appendChild(doc
                                .createTextNode(fmt(bodyObj.getMgmtBodyLocatorName(), "locatorName") + "  "));
                        bElem.appendChild(addresElem);

                    } else {
                        Element addresElem = doc.createElement("address");
                        addresElem.appendChild(doc.createElement("addressArea")).appendChild(
                                doc.createTextNode(fmt(bodyObj.getMgmtBodyAddress(), "addressArea")));
                        bElem.appendChild(addresElem);
                    }

                    bElem.appendChild(doc.createElement("email"))
                            .appendChild(doc.createTextNode(fmt(bodyObj.getMgmtBodyEmail(), "mgmtBodyMail")));
                    bodiesElem.appendChild(bElem);
                }
                mgmtElem.appendChild(bodiesElem);

                /***Mangement Plan**/
                Character status = mgmt.getMgmtStatus();
                Element mgmtExists = (Element) mgmtElem.appendChild(doc.createElement("exists"));
                if (status != null) {
                    mgmtExists
                            .appendChild(doc.createTextNode(fmt(Character.toUpperCase(status), "mgmtExists")));
                }
                Set plans = mgmt.getMgmtPlans();
                itr = plans.iterator();
                Element plansElem = doc.createElement("managementPlans");
                plansElem.appendChild(mgmtExists);
                while (itr.hasNext()) {
                    MgmtPlan planObj = (MgmtPlan) itr.next();
                    Element pElem = doc.createElement("managementPlan");
                    pElem.appendChild(doc.createElement("name"))
                            .appendChild(doc.createTextNode(fmt(planObj.getMgmtPlanName(), "mgmtPlanName")));
                    pElem.appendChild(doc.createElement("url"))
                            .appendChild(doc.createTextNode(fmt(planObj.getMgmtPlanUrl(), "mgmtPlanUrl")));
                    plansElem.appendChild(pElem);
                }
                mgmtElem.appendChild(plansElem);

                mgmtElem.appendChild(doc.createElement("conservationMeasures")).appendChild(
                        doc.createTextNode(fmt(mgmt.getMgmtConservMeasures(), "conservationMeasures")));
            }
            sdf.appendChild(mgmtElem);

            Map map = site.getMap();
            Element mapElem = doc.createElement("map");
            if (map != null) {
                mapElem.appendChild(doc.createElement("InspireID"))
                        .appendChild(doc.createTextNode(fmt(map.getMapInspire(), "mapInspireID")));

                Boolean bMap;
                if (map.getMapPdf() != null && map.getMapPdf().equals(Short.valueOf("1"))) {
                    bMap = true;
                } else {
                    bMap = false;
                }

                mapElem.appendChild(doc.createElement("pdfProvided"))
                        .appendChild(doc.createTextNode(fmt(bMap, "mapPDF")));
                mapElem.appendChild(doc.createElement("mapReference"))
                        .appendChild(doc.createTextNode(fmt(map.getMapReference(), "mapRef")));
            }
            sdf.appendChild(mapElem);

            if (flush++ % 100 == 0) {
                session.clear();
            }
            sdfs.appendChild(sdf);
        }

        //All the data is stored in the node instead of the document.
        Source source = new DOMSource(doc);

        File file = new File(new File("").getAbsolutePath() + File.separator + "xsl" + File.separator + "Site_"
                + this.siteCode + ".html");
        Result result = new StreamResult(file.toURI().getPath());

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Source xsl;
        if (SDF_ManagerApp.isEmeraldMode()) {
            xsl = new StreamSource(new File("").getAbsolutePath() + File.separator + "xsl" + File.separator
                    + "EmeraldSiteXSL.xsl");
        } else {
            xsl = new StreamSource(
                    new File("").getAbsolutePath() + File.separator + "xsl" + File.separator + "SiteXSL.xsl");
        }

        Templates template = tFactory.newTemplates(xsl);
        Transformer transformer = template.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS,
                "siteName name otherSiteCharacteristics"
                        + " qualityAndImportance selectiveBasis derogationJustification comments "
                        + "location licensedJustification licensingAuthority licenseValidFrom licenseValidUntil otherType "
                        + "method activity reason");

        transformer.transform(source, result);
        String pdfPath = this.filePath + "\\Site_" + this.siteCode + ".pdf";

        os = new FileOutputStream(new File(pdfPath));

        ITextRenderer renderer = new ITextRenderer();
        FontFactory.registerDirectory("resources/fonts");

        renderer.setDocument(file);
        renderer.layout();
        renderer.createPDF(os);

        return null;
    } catch (TransformerConfigurationException e) {
        //e.printStackTrace();
        GenerateSitePDF.log
                .error("A TransformerConfigurationException has occurred in processDatabase. Error Message:::"
                        + e.getMessage());
        return null;
    } catch (TransformerException e) {
        //e.printStackTrace();
        GenerateSitePDF.log.error(
                "A TransformerException has occurred in processDatabase. Error Message:::" + e.getMessage());
        return null;
    } catch (FileNotFoundException e) {
        GenerateSitePDF.log.error(
                "A FileNotFoundException has occurred in processDatabase. Error Message:::" + e.getMessage());
        //e.printStackTrace();
        return null;
    } catch (IOException e) {
        GenerateSitePDF.log
                .error("An IOException has occurred in processDatabase. Error Message:::" + e.getMessage());
        //e.printStackTrace();
        return null;
    } catch (Exception e) {
        //e.printStackTrace();
        GenerateSitePDF.log.error(
                "A general exception has occurred in processDatabase. Error Message:::" + e.getMessage());
        return null;
    } finally {
        IOUtils.closeQuietly(os);
        session.close();
    }

}

From source file:servlet.PdfServlet1.java

/**
 * Processes requests for both HTTP// w  ww  .  j a v a2s .  c  o  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    MyQuery mq = new MyQuery();

    ServletContext webApp = this.getServletContext();

    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();

        FopFactory fopFactory = FopFactory.newInstance();

        //Setup a buffer to obtain the content length
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        Templates templates = tFactory.newTemplates(new StreamSource(webApp.getRealPath(XSLT_PATH)));
        // Create a transformer
        Transformer transformer = templates.newTransformer();

        // Get concrete implementation
        DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
        // Need a parser that support namespaces
        dFactory.setNamespaceAware(true);
        // Create the parser
        DocumentBuilder parser = dFactory.newDocumentBuilder();
        // Parse the XML document
        InputSource is = new InputSource(new StringReader(mq.getStarsBis()));
        // Parse the XML document

        Document doc = parser.parse(is);

        //Setup FOP
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

        //Make sure the XSL transformation's result is piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        //Setup input
        Source src = new DOMSource(doc);

        //Start the transformation and rendering process
        transformer.transform(src, res);

        //Prepare response
        response.setContentType("application/pdf");
        response.setContentLength(out.size());

        //Send content to Browser
        response.getOutputStream().write(out.toByteArray());
        response.getOutputStream().flush();
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}