Example usage for java.util StringTokenizer hasMoreElements

List of usage examples for java.util StringTokenizer hasMoreElements

Introduction

In this page you can find the example usage for java.util StringTokenizer hasMoreElements.

Prototype

public boolean hasMoreElements() 

Source Link

Document

Returns the same value as the hasMoreTokens method.

Usage

From source file:com.servoy.j2db.util.Utils.java

public static String[] getTokenElements(String value, String delim, boolean trim) {
    if (value == null) {
        return new String[] {};
    }// w w  w  .  ja v  a  2  s . c  om

    List<String> lst = new ArrayList<String>();
    StringTokenizer tokemizer = new StringTokenizer(value, delim);
    while (tokemizer.hasMoreElements()) {
        String token = tokemizer.nextToken();
        if (trim) {
            lst.add(token.trim());
        } else {
            lst.add(token);
        }
    }
    return lst.toArray(new String[lst.size()]);
}

From source file:sdf_manager.GenerateSitePDF.java

/**
 *
 * @return/*from  w  w w.java 2s .  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:com.sun.socialsite.pojos.Profile.java

/**
 * Updates property values in a property holder: a display section, a
 * property object or a property object collection.
 *
 * @param instancePath   Full path of the property holder instance
 * @param updatedValues  JSON object with updated name/values
 * @param holder         Property holder definition
 * @param deletes        List of objects deleted from collections
 *//*from  ww  w.ja  va  2s  .  c  o  m*/
private void updatePropertyHolder(String instancePath, JSONObject updatedValues,
        ProfileDefinition.PropertyDefinitionHolder holder, Profile.VisibilityType visibility,
        DeleteMap deletes) {

    ProfileManager mgr = Factory.getSocialSite().getProfileManager();

    // process the properties defined in the holder
    boolean haveDeletes = false;
    for (ProfileDefinition.PropertyDefinition propDef : holder.getPropertyDefinitions()) {
        String fullPropertyName = instancePath + "_" + propDef.getShortName();
        ProfileProperty profileProp = getProperty(fullPropertyName);
        String incomingPropValue = null;
        try {
            try {
                if ("stringarray".equals(propDef.getType())) {
                    incomingPropValue = (String) updatedValues.get(fullPropertyName);
                    JSONArray ja = new JSONArray();
                    StringTokenizer toker = new StringTokenizer(incomingPropValue, "\n");
                    while (toker.hasMoreElements()) {
                        ja.put(toker.nextToken());
                    }
                    incomingPropValue = ja.toString();
                } else if ("boolean".equals(propDef.getType())) {
                    if (updatedValues.getBoolean(fullPropertyName)) {
                        incomingPropValue = "true";
                    } else {
                        incomingPropValue = "false";
                    }
                } else {
                    incomingPropValue = (String) updatedValues.get(fullPropertyName);
                }
            } catch (Exception ex) {
                log.error("ERROR reading incoming property: " + fullPropertyName, ex);
            }

            if (incomingPropValue == null) {
                continue;
            }
            log.debug("Processing property [" + fullPropertyName + "]");
            log.debug("    Request value is [" + incomingPropValue + "]");

            if (profileProp == null) {
                // If a property is not found, then create it based on its
                // porperty definition, effectively creating all user properties
                // the first time that the user edits his/her properties.
                log.debug("    New property");
                profileProp = new ProfileProperty();
                profileProp.setType(propDef.getType());
                profileProp.setName(fullPropertyName);
                profileProp.setValue("dummy");
                profileProp.setNameKey(propDef.getNamekey());
                profileProp.setVisibility(visibility);
                profileProp.setVisibilityLevel(1);
                profileProp.setCreated(new Date());
                profileProp.setUpdated(new Date());
                mgr.saveProfileProperty(profileProp);
                addProfileProp(profileProp);
            } else {
                log.debug("    Existing property");
            }

            // some special treatment for booleans
            if (profileProp.getValue() != null
                    && (profileProp.getValue().equals("true") || profileProp.getValue().equals("false"))) {

                if (incomingPropValue == null || !incomingPropValue.equals("true")) {
                    incomingPropValue = "false";
                } else {
                    incomingPropValue = "true";
                }
            }

            // only work on props that were submitted with the request
            if (incomingPropValue != null) {
                log.debug("Setting new value for [" + fullPropertyName + "]");
                profileProp.setValue(incomingPropValue.trim());
                if (holder instanceof ProfileDefinition.PropertyObjectCollectionDefinition
                        && DELETE_FLAG.equals(profileProp.getValue())) {
                    haveDeletes = true;
                }
            }
        } catch (Exception ex) {
            log.error("Failed to set property: " + fullPropertyName, ex);
        }
    }

    if (haveDeletes) {
        deletes.put((ProfileDefinition.PropertyObjectCollectionDefinition) holder, instancePath);
    }

    // process the property objects defined in the holder
    for (ProfileDefinition.PropertyObjectDefinition objectDef : holder.getPropertyObjectDefinitions()) {

        // check to see if any properties are children of this object
        String fullObjectName = instancePath + "_" + objectDef.getShortName();
        String[] names = JSONObject.getNames(updatedValues);
        for (int i = 0; i < names.length; i++) {
            if (names[i].startsWith(fullObjectName)) {
                updatePropertyHolder(fullObjectName, updatedValues, objectDef, visibility, deletes);
            }
        }
    }

    // and finally, process the property object collections defined in the holder
    for (ProfileDefinition.PropertyObjectCollectionDefinition collectionDef : holder
            .getPropertyObjectCollectionDefinitions()) {

        // determine if collection is an OpenSocial ListField
        // assume it is if it has value, type and primary fields
        boolean listField = false;
        Map<String, ProfileDefinition.PropertyDefinition> propDefMap = new HashMap<String, ProfileDefinition.PropertyDefinition>();
        for (ProfileDefinition.PropertyDefinition propDef : collectionDef.getPropertyDefinitions()) {
            propDefMap.put(propDef.getShortName(), propDef);
        }
        if (propDefMap.get("value") != null && propDefMap.get("type") != null
                && propDefMap.get("primary") != null) {
            listField = true;
        }

        // process collection defs of this type
        for (int poi = 1; poi < COLLECTION_MAX; poi++) {
            String fullCollectionName = instancePath + "_"
                    + collectionDef.getShortName().replace("{n}", Integer.toString(poi));
            String[] names = JSONObject.getNames(updatedValues);
            for (int i = 0; i < names.length; i++) {
                if (names[i].startsWith(fullCollectionName)) {
                    updatePropertyHolder(fullCollectionName, updatedValues, collectionDef, visibility, deletes);
                }
            }
        }

        // special handling for ListFields: ensure no more than one primary
        int listCount = 0;
        boolean gotPrimary = false;
        if (listField)
            for (int poi = 1; poi < COLLECTION_MAX; poi++) {
                listCount++;
                String fullCollectionName = instancePath + "_"
                        + collectionDef.getShortName().replace("{n}", Integer.toString(poi));
                String primaryPropName = fullCollectionName + "_primary";
                ProfileProperty primaryProp = getProperty(primaryPropName);
                if (!gotPrimary && primaryProp != null && "true".equals(primaryProp.getValue())) {
                    // good, we have a primary
                    gotPrimary = true;
                } else if (gotPrimary && primaryProp != null && "true".equals(primaryProp.getValue())) {
                    // sorry, already got a primary
                    primaryProp.setValue("false");
                }
            }

        // special handling for ListFields: ensure at least one primary
        if (!gotPrimary && listCount > 0) {
            // no primary, so use first item
            String fullCollectionName = instancePath + "_" + collectionDef.getShortName().replace("{n}", "1");
            String primaryPropName = fullCollectionName + "_primary";
            ProfileProperty primaryProp = getProperty(primaryPropName);
            if (primaryProp != null) {
                primaryProp.setValue("true");
            }
        }
    }
}

From source file:com.impetus.kundera.query.KunderaQuery.java

/**
 * Parses the ordering @See Order By Clause.
 * /*from   www .  jav a  2  s  . co  m*/
 * @param ordering
 *            the ordering
 */
private void parseOrdering(String ordering) {
    final String comma = ",";
    final String space = " ";

    StringTokenizer tokenizer = new StringTokenizer(ordering, comma);

    sortOrders = new ArrayList<KunderaQuery.SortOrdering>();
    while (tokenizer.hasMoreTokens()) {
        String order = (String) tokenizer.nextElement();
        StringTokenizer token = new StringTokenizer(order, space);
        SortOrder orderType = SortOrder.ASC;

        String colName = (String) token.nextElement();
        while (token.hasMoreElements()) {
            String nextOrder = (String) token.nextElement();

            // more spaces given.
            if (StringUtils.isNotBlank(nextOrder)) {
                try {
                    orderType = SortOrder.valueOf(nextOrder.toUpperCase());
                } catch (IllegalArgumentException e) {
                    logger.error("Error while parsing order by clause:");
                    throw new JPQLParseException("Invalid sort order provided:" + nextOrder);
                }
            }
        }
        sortOrders.add(new SortOrdering(colName, orderType));
    }
}

From source file:sdf_manager.ExporterSiteHTML.java

/**
 *
 * @return/*  w  ww  .j av a 2 s .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:org.specrunner.parameters.core.AccessFactoryImpl.java

@Override
public Object getProperty(Object source, String str) throws PluginException {
    Object bean = source;/*from w ww .  j  av a  2  s  . c o  m*/
    IFeatureManager fm = SRServices.getFeatureManager();
    Boolean acceptNullPath = (Boolean) fm.get(FEATURE_PROPERTY_ACCEPT_NULL_PATH,
            DEFAULT_PROPERTY_ACCEPT_NULL_PATH);
    Boolean invalidPathAsNull = (Boolean) fm.get(FEATURE_PROPERTY_INVALID_PATH_AS_NULL,
            DEFAULT_PROPERTY_INVALID_PATH_AS_NULL);
    try {
        StringTokenizer st = new StringTokenizer(str, ".");
        StringBuilder path = new StringBuilder();
        if (UtilLog.LOG.isInfoEnabled()) {
            UtilLog.LOG.info("Searching '" + str + "' on " + source);
        }
        while (bean != null && st.hasMoreTokens()) {
            String part = st.nextToken();
            IAccess access = newAccess(bean, part);
            if (UtilLog.LOG.isInfoEnabled()) {
                UtilLog.LOG.info("Part '" + part + "', bean='" + bean + "'("
                        + (bean != null ? bean.getClass() : "null") + ") access='" + access + "'");
            }
            if ((access == null || !access.hasFeature()) && invalidPathAsNull) {
                bean = null;
                break;
            }
            path.append(path.length() > 0 ? "." : "");
            path.append(part);
            if (access == null && !invalidPathAsNull) {
                StringBuilder sb = new StringBuilder(
                        "Invalid property '" + part + "' in path:'" + path + "' of property '" + str + "'.");
                PluginException tmp = new PluginException(sb.toString());
                tmp.printStackTrace();
                throw tmp;
            }
            bean = access.get(bean, part);
            if (UtilLog.LOG.isInfoEnabled()) {
                UtilLog.LOG.info("Bean '" + path + "' = '" + bean + "'");
            }
            if (bean == null && !acceptNullPath && st.hasMoreElements()) {
                PluginException tmp = new PluginException(
                        "Invalid null value for part '" + path + "' of property '" + str + "'.");
                tmp.printStackTrace();
                throw tmp;
            }
        }
        return bean;
    } catch (PluginException e) {
        throw e;
    } catch (Exception e) {
        throw new PluginException(e);
    }
}

From source file:nl.nn.adapterframework.http.HttpSender.java

public String sendMessageWithTimeoutGuarded(String correlationID, String message,
        ParameterResolutionContext prc) throws SenderException, TimeOutException {
    ParameterValueList pvl = null;/*w  w w .j a  va 2  s  . c om*/
    try {
        if (prc != null && paramList != null) {
            pvl = prc.getValues(paramList);
        }
    } catch (ParameterException e) {
        throw new SenderException(
                getLogPrefix() + "Sender [" + getName() + "] caught exception evaluating parameters", e);
    }
    URI uri;
    HttpMethod httpmethod;
    HostConfiguration hostconfiguration = new HostConfiguration(hostconfigurationBase);
    try {
        if (urlParameter != null) {
            String url = (String) pvl.getParameterValue(getUrlParam()).getValue();
            uri = getURI(url);
        } else {
            uri = staticUri;
        }

        Map<String, String> headersParamsMap = new HashMap<String, String>();
        if (headersParams != null) {
            StringTokenizer st = new StringTokenizer(headersParams, ",");
            while (st.hasMoreElements()) {
                headersParamsMap.put(st.nextToken(), null);
            }
        }

        if (!isParamsInUrl()) {
            httpmethod = getPostMethodWithParamsInBody(uri, message, pvl, headersParamsMap, prc);
        } else {
            httpmethod = getMethod(uri, message, pvl, headersParamsMap);
            if (!"POST".equals(getMethodType()) && !"PUT".equals(getMethodType())
                    && !"REPORT".equals(getMethodType())) {
                httpmethod.setFollowRedirects(isFollowRedirects());
            }
        }

        int port = getPort(uri);

        if (socketfactory != null && "https".equals(uri.getScheme())) {
            Protocol authhttps = new Protocol(uri.getScheme(), socketfactory, port);
            hostconfiguration.setHost(uri.getHost(), port, authhttps);
        } else {
            hostconfiguration.setHost(uri.getHost(), port, uri.getScheme());
        }
        log.info(getLogPrefix() + "configured httpclient for host [" + hostconfiguration.getHostURL() + "]");

        if (credentials != null) {
            httpState.setCredentials(null, uri.getHost(), credentials);
        }
    } catch (URIException e) {
        throw new SenderException(e);
    }

    String result = null;
    int statusCode = -1;
    int count = getMaxExecuteRetries();
    String msg = null;
    while (count-- >= 0 && statusCode == -1) {
        try {
            if (log.isDebugEnabled())
                log.debug(getLogPrefix() + "executing method");
            statusCode = httpclient.executeMethod(hostconfiguration, httpmethod, httpState);
            if (log.isDebugEnabled())
                log.debug(getLogPrefix() + "executed method");

            if (statusCode != HttpServletResponse.SC_OK) {
                StatusLine statusline = httpmethod.getStatusLine();
                if (statusline != null) {
                    log.warn(getLogPrefix() + "status [" + statusline.toString() + "]");
                } else {
                    log.warn(getLogPrefix() + "no statusline found");
                }
            } else {
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "status [" + statusCode + "]");
            }
            HttpServletResponse response = null;
            if (isStreamResultToServlet()) {
                response = (HttpServletResponse) prc.getSession().get("restListenerServletResponse");
            }
            String fileName = null;
            if (StringUtils.isNotEmpty(getStreamResultToFileNameSessionKey())) {
                fileName = (String) prc.getSession().get(getStreamResultToFileNameSessionKey());
            }
            result = extractResult(httpmethod, prc, response, fileName);
            if (log.isDebugEnabled())
                log.debug(getLogPrefix() + "retrieved result [" + result + "]");
        } catch (HttpException e) {
            Throwable throwable = e.getCause();
            String cause = null;
            if (throwable != null) {
                cause = throwable.toString();
            }
            msg = e.getMessage();
            log.warn(getLogPrefix() + "httpException with message [" + msg + "] and cause [" + cause
                    + "], executeRetries left [" + count + "]");
        } catch (IOException e) {
            httpmethod.abort();
            if (e instanceof SocketTimeoutException) {
                throw new TimeOutException(e);
            }
            throw new SenderException(e);
        } finally {
            // In case of storeResultAsStreamInSessionKey release connection
            // is done by ReleaseConnectionAfterReadInputStream.
            if (StringUtils.isEmpty(getStoreResultAsStreamInSessionKey())) {
                httpmethod.releaseConnection();
            }
        }
    }

    if (statusCode == -1) {
        if (StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) {
            //java.net.SocketTimeoutException: Read timed out
            throw new TimeOutException("Failed to recover from timeout exception");
        }
        throw new SenderException("Failed to recover from exception");
    }

    if (isXhtml() && StringUtils.isNotEmpty(result)) {
        result = XmlUtils.skipDocTypeDeclaration(result.trim());
        if (result.startsWith("<html>") || result.startsWith("<html ")) {
            CleanerProperties props = new CleanerProperties();
            HtmlCleaner cleaner = new HtmlCleaner(props);
            TagNode tagNode = cleaner.clean(result);
            result = new SimpleXmlSerializer(props).getXmlAsString(tagNode);

            if (transformerPool != null) {
                log.debug(getLogPrefix() + " transforming result [" + result + "]");
                ParameterResolutionContext prc_xslt = new ParameterResolutionContext(result, null, true, true);
                try {
                    result = transformerPool.transform(prc_xslt.getInputSource(), null);
                } catch (Exception e) {
                    throw new SenderException("Exception on transforming input", e);
                }
            }
        }
    }
    return result;
}

From source file:org.cloudifysource.esc.driver.provisioning.openstack.OpenStackCloudifyDriver.java

@Override
protected void initDeployer(final Cloud cloud) {
    final ComputeTemplate cloudTemplate;
    if (this.management) {
        final String managementMachineTemplate = cloud.getConfiguration().getManagementMachineTemplate();
        cloudTemplate = cloud.getCloudCompute().getTemplates().get(managementMachineTemplate);
        if (cloudTemplate == null) {
            throw new IllegalStateException("Management compute template with name <"
                    + managementMachineTemplate + "> could not be found.");
        }/*from   ww  w . j  a  va  2s  . co  m*/
    } else {
        cloudTemplate = cloud.getCloudCompute().getTemplates().get(cloudTemplateName);
        if (cloudTemplate == null) {
            throw new IllegalStateException(
                    "Template with name <" + cloudTemplateName + "> could not be found.");
        }
    }

    String endpoint = null;
    final Map<String, Object> overrides = cloudTemplate.getOverrides();
    if (overrides != null && !overrides.isEmpty()) {
        endpoint = (String) overrides.get(OPENSTACK_ENDPOINT);
    }

    final String networkApiVersion = (String) cloudTemplate.getOptions().get(OPT_NETWORK_API_VERSION);
    final String networkServiceName = (String) cloudTemplate.getOptions().get(OPT_NETWORK_SERVICE_NAME);
    final String computeServiceName = (String) cloudTemplate.getOptions().get(OPT_COMPUTE_SERVICE_NAME);

    final String cloudImageId = cloudTemplate.getImageId();
    final String region = cloudImageId.split("/")[0];

    final String cloudUser = cloud.getUser().getUser();
    final String password = cloud.getUser().getApiKey();

    if (cloudUser == null || password == null) {
        throw new IllegalStateException("Cloud user or password not found");
    }

    final StringTokenizer st = new StringTokenizer(cloudUser, ":");
    final String tenant = st.hasMoreElements() ? (String) st.nextToken() : null;
    final String username = st.hasMoreElements() ? (String) st.nextToken() : null;

    try {
        this.computeApi = new OpenStackComputeClient(endpoint, username, password, tenant, region,
                computeServiceName);
        this.networkApi = new OpenStackNetworkClient(endpoint, username, password, tenant, region,
                networkServiceName, networkApiVersion);

    } catch (OpenstackJsonSerializationException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.schemaspy.Config.java

/**
 * Specifies connection properties to use in the format:
 * <code>key1\=value1;key2\=value2</code><br>
 * user (from -u) and password (from -p) will be passed in the
 * connection properties if specified.<p>
 * This is an alternative form of passing connection properties than by file
 * (see {@link #setConnectionPropertiesFile(String)})
 *
 * @param properties//from   w  w w  .  jav  a  2  s  . c om
 */
public void setConnectionProperties(String properties) {
    userConnectionProperties = new Properties();

    StringTokenizer tokenizer = new StringTokenizer(properties, ";");
    while (tokenizer.hasMoreElements()) {
        String pair = tokenizer.nextToken();
        int index = pair.indexOf(ESCAPED_EQUALS);
        if (index != -1) {
            String key = pair.substring(0, index);
            String value = pair.substring(index + ESCAPED_EQUALS.length());
            userConnectionProperties.put(key, value);
        }
    }
}

From source file:com.pureinfo.studio.db.txt2SRM.impl.SchoolSCITxtImportRunner.java

/**
 * return sql states if no properties set return null
 * //from w  w w.  j  a v  a  2  s.  c o m
 * @param _sNewObj
 * @param _sStrSQL
 * @param _sIsToTemp
 */
private String getSqlStrBuffer(DolphinObject _newObj, String _sStrSQL, boolean _bIsToTemp) {
    StringBuffer sbuff = null;
    boolean bStringProperty;

    if (_sStrSQL.length() > 0) {
        StringTokenizer st = new StringTokenizer(_sStrSQL, ",", false);
        // if (_bIsToTemp) {
        // sbuff = new StringBuffer("select * from {this}0 where ");
        // }
        // else {
        // sbuff = new StringBuffer("select * from {this} where ");
        // }
        sbuff = new StringBuffer();
        try {
            String sValueWhole, sValue, sTableRowValue;
            while (st.hasMoreElements()) {
                sValueWhole = (String) st.nextElement();

                sValue = sValueWhole.substring(0, sValueWhole.indexOf("-"));
                sTableRowValue = sValueWhole.substring(sValueWhole.indexOf("-") + 1);
                if (_newObj.getProperty(sValue) != null) {

                    bStringProperty = _newObj.getProperty(sValue) instanceof String
                            || _newObj.getProperty(sValue) instanceof Date;
                    if ((bStringProperty && _newObj.getPropertyAsString(sValue).trim().length() > 0)
                            || (!bStringProperty)) {
                        if (sbuff.length() > 0) {
                            sbuff.append(" and ");
                        }
                        sbuff.append(sTableRowValue);
                        sbuff.append('=');
                        if (bStringProperty)
                            sbuff.append('\'');

                        String sPropertyValue = _newObj.getPropertyAsString(sValue);
                        sPropertyValue = StrUtil.escapeEncode(sPropertyValue);
                        sPropertyValue = StrUtil.sqlEncode(sPropertyValue);
                        sPropertyValue = removeBlank(sPropertyValue);

                        sbuff.append(sPropertyValue);
                        if (bStringProperty)
                            sbuff.append('\'');
                    }
                }
            }

            return sbuff.length() > 0 ? sbuff.toString() : null;
        } finally {
            sbuff.setLength(0);
        }
    }
    return null;
}