Example usage for java.util StringTokenizer nextElement

List of usage examples for java.util StringTokenizer nextElement

Introduction

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

Prototype

public Object nextElement() 

Source Link

Document

Returns the same value as the nextToken method, except that its declared return value is Object rather than String .

Usage

From source file:com.sshtools.j2ssh.SftpClient.java

/**
 * <p>/*from   ww  w  . java2  s . com*/
 * Create a directory or set of directories. This method will not fail even
 * if the directories exist. It is advisable to test whether the directory
 * exists before attempting an operation by using the <code>stat</code>
 * method to return the directories attributes.
 * </p>
 *
 * @param dir the path of directories to create.
 */
public void mkdirs(String dir) {
    StringTokenizer tokens = new StringTokenizer(dir, "/");
    String path = dir.startsWith("/") ? "/" : "";

    while (tokens.hasMoreElements()) {
        path += (String) tokens.nextElement();

        try {
            stat(path);
        } catch (IOException ex) {
            try {
                mkdir(path);
            } catch (IOException ex2) {
            }
        }

        path += "/";
    }
}

From source file:org.trafodion.dtm.TmAuditTlog.java

public boolean deleteAgedEntries(final long lvAsn) throws IOException {
    if (LOG.isTraceEnabled())
        LOG.trace("deleteAgedEntries start:  Entries older than " + lvAsn + " will be removed");
    HTableInterface deleteTable;// w  w  w. ja va 2  s. co m
    for (int i = 0; i < tlogNumLogs; i++) {
        String lv_tLogName = new String(TLOG_TABLE_NAME + "_LOG_" + Integer.toHexString(i));
        //         Connection deleteConnection = ConnectionFactory.createConnection(this.config);

        HConnection deleteConnection = HConnectionManager.createConnection(this.config);

        deleteTable = deleteConnection.getTable(TableName.valueOf(lv_tLogName));
        try {
            Scan s = new Scan();
            s.setCaching(100);
            s.setCacheBlocks(false);
            ArrayList<Delete> deleteList = new ArrayList<Delete>();
            ResultScanner ss = deleteTable.getScanner(s);

            try {
                for (Result r : ss) {
                    for (Cell cell : r.rawCells()) {
                        String valueString = new String(CellUtil.cloneValue(cell));
                        StringTokenizer st = new StringTokenizer(valueString, ",");
                        if (st.hasMoreElements()) {
                            String asnToken = st.nextElement().toString();
                            String transidToken = st.nextElement().toString();
                            String stateToken = st.nextElement().toString();
                            if ((Long.parseLong(asnToken) < lvAsn) && (stateToken.equals("FORGOTTEN"))) {
                                String rowKey = new String(r.getRow());
                                Delete del = new Delete(r.getRow());
                                if (LOG.isTraceEnabled())
                                    LOG.trace("adding transid: " + transidToken + " to delete list");
                                deleteList.add(del);
                            } else if ((Long.parseLong(asnToken) < lvAsn)
                                    && (stateToken.equals("COMMITTED") || stateToken.equals("ABORTED"))) {
                                if (ageCommitted) {
                                    String rowKey = new String(r.getRow());
                                    Delete del = new Delete(r.getRow());
                                    if (LOG.isTraceEnabled())
                                        LOG.trace("adding transid: " + transidToken + " to delete list");
                                    deleteList.add(del);
                                } else {
                                    String key = new String(r.getRow());
                                    Get get = new Get(r.getRow());
                                    get.setMaxVersions(versions); // will return last n versions of row
                                    Result lvResult = deleteTable.get(get);
                                    // byte[] b = lvResult.getValue(TLOG_FAMILY, ASN_STATE);  // returns current version of value
                                    List<Cell> list = lvResult.getColumnCells(TLOG_FAMILY, ASN_STATE); // returns all versions of this column
                                    for (Cell element : list) {
                                        String value = new String(CellUtil.cloneValue(element));
                                        StringTokenizer stok = new StringTokenizer(value, ",");
                                        if (stok.hasMoreElements()) {
                                            if (LOG.isTraceEnabled())
                                                LOG.trace("Performing secondary search on (" + transidToken
                                                        + ")");
                                            asnToken = stok.nextElement().toString();
                                            transidToken = stok.nextElement().toString();
                                            stateToken = stok.nextElement().toString();
                                            if ((Long.parseLong(asnToken) < lvAsn)
                                                    && (stateToken.equals("FORGOTTEN"))) {
                                                Delete del = new Delete(r.getRow());
                                                if (LOG.isTraceEnabled())
                                                    LOG.trace("Secondary search found new delete - adding ("
                                                            + transidToken + ") with asn: " + asnToken
                                                            + " to delete list");
                                                deleteList.add(del);
                                                break;
                                            } else {
                                                if (LOG.isTraceEnabled())
                                                    LOG.trace("Secondary search skipping entry with asn: "
                                                            + asnToken + ", state: " + stateToken
                                                            + ", transid: " + transidToken);
                                            }
                                        }
                                    }
                                }
                            } else {
                                if (LOG.isTraceEnabled())
                                    LOG.trace("deleteAgedEntries skipping asn: " + asnToken + ", transid: "
                                            + transidToken + ", state: " + stateToken);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                LOG.error("deleteAgedEntries Exception getting results for table index " + i + "; " + e);
                throw new RuntimeException(e);
            } finally {
                ss.close();
            }
            if (LOG.isTraceEnabled())
                LOG.trace("attempting to delete list with " + deleteList.size() + " elements");
            try {
                deleteTable.delete(deleteList);
            } catch (IOException e) {
                LOG.error("deleteAgedEntries Exception deleting from table index " + i + "; " + e);
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            LOG.error("deleteAgedEntries IOException setting up scan on table index " + i);
            e.printStackTrace();
        } finally {
            try {
                deleteTable.close();
                deleteConnection.close();
            } catch (IOException e) {
                LOG.error("deleteAgedEntries IOException closing table or connection for table index " + i);
                e.printStackTrace();
            }
        }
    }
    if (LOG.isTraceEnabled())
        LOG.trace("deleteAgedEntries - exit");
    return true;
}

From source file:org.trafodion.dtm.TmAuditTlog.java

public void getTransactionState(TransactionState ts) throws IOException {
    if (LOG.isTraceEnabled())
        LOG.trace("getTransactionState start; transid: " + ts.getTransactionId());

    // This request might be for a transaction not originating on this node, so we need to open
    // the appropriate Tlog
    HTableInterface unknownTransactionTable;
    long lvTransid = ts.getTransactionId();
    int lv_ownerNid = (int) (lvTransid >> 32);
    int lv_lockIndex = (int) (lvTransid & tLogHashKey);
    String lv_tLogName = new String(
            "TRAFODION._DTM_.TLOG" + String.valueOf(lv_ownerNid) + "_LOG_" + Integer.toHexString(lv_lockIndex));
    HConnection unknownTableConnection = HConnectionManager.createConnection(this.config);
    unknownTransactionTable = unknownTableConnection.getTable(TableName.valueOf(lv_tLogName));

    try {// www .j  ava2  s .co  m
        String transidString = new String(String.valueOf(lvTransid));
        Get g;
        long key = (((lvTransid & tLogHashKey) << tLogHashShiftFactor) + (lvTransid & 0xFFFFFFFF));
        if (LOG.isTraceEnabled())
            LOG.trace("key: " + key + ", hexkey: " + Long.toHexString(key) + ", transid: " + lvTransid);
        g = new Get(Bytes.toBytes(key));
        TransState lvTxState = TransState.STATE_NOTX;
        String stateString = "";
        String transidToken = "";
        try {
            Result r = unknownTransactionTable.get(g);
            if (r == null) {
                if (LOG.isTraceEnabled())
                    LOG.trace("getTransactionState: tLog result is null: " + transidString);
            }
            if (r.isEmpty()) {
                if (LOG.isTraceEnabled())
                    LOG.trace("getTransactionState: tLog empty result: " + transidString);
            }
            byte[] value = r.getValue(TLOG_FAMILY, ASN_STATE);
            if (value == null) {
                ts.setStatus(TransState.STATE_NOTX);
                if (LOG.isTraceEnabled())
                    LOG.trace("getTransactionState: tLog value is null: " + transidString);
                return;
            }
            if (value.length == 0) {
                ts.setStatus(TransState.STATE_NOTX);
                if (LOG.isTraceEnabled())
                    LOG.trace("getTransactionState: tLog transaction not found: " + transidString);
                return;
            }
            ts.clearParticipatingRegions();
            String recordString = new String(Bytes.toString(value));
            StringTokenizer st = new StringTokenizer(recordString, ",");
            if (st.hasMoreElements()) {
                String asnToken = st.nextElement().toString();
                transidToken = st.nextElement().toString();
                stateString = st.nextElement().toString();
                if (LOG.isTraceEnabled())
                    LOG.trace("getTransactionState: transaction: " + transidToken + " stateString is: "
                            + stateString);
            }
            if (stateString.compareTo("COMMITTED") == 0) {
                lvTxState = TransState.STATE_COMMITTED;
            } else if (stateString.compareTo("ABORTED") == 0) {
                lvTxState = TransState.STATE_ABORTED;
            } else if (stateString.compareTo("ACTIVE") == 0) {
                lvTxState = TransState.STATE_ACTIVE;
            } else if (stateString.compareTo("PREPARED") == 0) {
                lvTxState = TransState.STATE_PREPARED;
            } else if (stateString.compareTo("NOTX") == 0) {
                lvTxState = TransState.STATE_NOTX;
            } else if (stateString.compareTo("FORGOTTEN") == 0) {
                // Need to get the previous state record so we know how to drive the regions
                String keyS = new String(r.getRow());
                Get get = new Get(r.getRow());
                get.setMaxVersions(versions); // will return last n versions of row
                Result lvResult = unknownTransactionTable.get(get);
                // byte[] b = lvResult.getValue(TLOG_FAMILY, ASN_STATE);  // returns current version of value
                List<Cell> list = lvResult.getColumnCells(TLOG_FAMILY, ASN_STATE); // returns all versions of this column
                for (Cell element : list) {
                    String stringValue = new String(CellUtil.cloneValue(element));
                    st = new StringTokenizer(stringValue, ",");
                    if (st.hasMoreElements()) {
                        if (LOG.isTraceEnabled())
                            LOG.trace("Performing secondary search on (" + transidToken + ")");
                        String asnToken = st.nextElement().toString();
                        transidToken = st.nextElement().toString();
                        String stateToken = st.nextElement().toString();
                        if ((stateToken.compareTo("COMMITTED") == 0)
                                || (stateToken.compareTo("ABORTED") == 0)) {
                            String rowKey = new String(r.getRow());
                            if (LOG.isTraceEnabled())
                                LOG.trace("Secondary search found record for (" + transidToken
                                        + ") with state: " + stateToken);
                            lvTxState = (stateToken.compareTo("COMMITTED") == 0) ? TransState.STATE_COMMITTED
                                    : TransState.STATE_ABORTED;
                            break;
                        } else {
                            if (LOG.isTraceEnabled())
                                LOG.trace("Secondary search skipping entry for (" + transidToken
                                        + ") with state: " + stateToken);
                        }
                    }
                }
            } else if (stateString.compareTo("ABORTING") == 0) {
                lvTxState = TransState.STATE_ABORTING;
            } else if (stateString.compareTo("COMMITTING") == 0) {
                lvTxState = TransState.STATE_COMMITTING;
            } else if (stateString.compareTo("PREPARING") == 0) {
                lvTxState = TransState.STATE_PREPARING;
            } else if (stateString.compareTo("FORGETTING") == 0) {
                lvTxState = TransState.STATE_FORGETTING;
            } else if (stateString.compareTo("FORGETTING_HEUR") == 0) {
                lvTxState = TransState.STATE_FORGETTING_HEUR;
            } else if (stateString.compareTo("BEGINNING") == 0) {
                lvTxState = TransState.STATE_BEGINNING;
            } else if (stateString.compareTo("HUNGCOMMITTED") == 0) {
                lvTxState = TransState.STATE_HUNGCOMMITTED;
            } else if (stateString.compareTo("HUNGABORTED") == 0) {
                lvTxState = TransState.STATE_HUNGABORTED;
            } else if (stateString.compareTo("IDLE") == 0) {
                lvTxState = TransState.STATE_IDLE;
            } else if (stateString.compareTo("FORGOTTEN_HEUR") == 0) {
                lvTxState = TransState.STATE_FORGOTTEN_HEUR;
            } else if (stateString.compareTo("ABORTING_PART2") == 0) {
                lvTxState = TransState.STATE_ABORTING_PART2;
            } else if (stateString.compareTo("TERMINATING") == 0) {
                lvTxState = TransState.STATE_TERMINATING;
            } else {
                lvTxState = TransState.STATE_BAD;
            }

            // get past the filler
            st.nextElement();

            // Load the TransactionState object up with regions
            while (st.hasMoreElements()) {
                String tableNameToken = st.nextToken();
                HTable table = new HTable(config, tableNameToken);
                NavigableMap<HRegionInfo, ServerName> regions = table.getRegionLocations();
                Iterator<Map.Entry<HRegionInfo, ServerName>> it = regions.entrySet().iterator();
                while (it.hasNext()) { // iterate entries.
                    NavigableMap.Entry<HRegionInfo, ServerName> pairs = it.next();
                    HRegionInfo regionKey = pairs.getKey();
                    if (LOG.isTraceEnabled())
                        LOG.trace("getTransactionState: transaction: " + transidToken + " adding region: "
                                + regionKey.getRegionNameAsString());
                    ServerName serverValue = regions.get(regionKey);
                    String hostAndPort = new String(serverValue.getHostAndPort());
                    StringTokenizer tok = new StringTokenizer(hostAndPort, ":");
                    String hostName = new String(tok.nextElement().toString());
                    int portNumber = Integer.parseInt(tok.nextElement().toString());
                    TransactionRegionLocation loc = new TransactionRegionLocation(regionKey, serverValue);
                    ts.addRegion(loc);
                }
            }
            ts.setStatus(lvTxState);

            if (LOG.isTraceEnabled())
                LOG.trace("getTransactionState: returning transid: " + ts.getTransactionId() + " state: "
                        + lvTxState);
        } catch (Exception e) {
            LOG.error("getTransactionState Exception " + Arrays.toString(e.getStackTrace()));
            throw e;
        }
    } catch (Exception e2) {
        LOG.error("getTransactionState Exception2 " + e2);
        e2.printStackTrace();
    }
    if (LOG.isTraceEnabled())
        LOG.trace("getTransactionState end transid: " + ts.getTransactionId());
    return;
}

From source file:org.kchine.rpf.db.DBLayer.java

public void applyDBScript(InputStream scriptInputStream)
        throws RemoteException, NotBoundException, AccessException {
    Statement stmt = null;//  w w  w. ja  v  a2  s .com
    ResultSet rset = null;
    try {
        checkConnection();
        stmt = _connection.createStatement();

        BufferedReader br = new BufferedReader(new InputStreamReader(scriptInputStream));
        String line = null;
        StringBuffer sbuffer = new StringBuffer();
        try {
            while ((line = br.readLine()) != null) {
                sbuffer.append(line.trim());
                sbuffer.append(" ");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        StringTokenizer st = new StringTokenizer(replaceCode(sbuffer.toString()), ";");
        while (st.hasMoreElements()) {
            String statmentStr = ((String) st.nextElement()).trim();
            if (statmentStr.equals(""))
                continue;

            System.out.println("<" + statmentStr + ">");

            try {
                if (statmentStr.trim().equalsIgnoreCase("commit")) {
                    _connection.commit();
                } else {
                    stmt.execute(statmentStr);
                }
                System.out.println("OK");
            } catch (SQLException sqle) {
                if (statmentStr.toUpperCase().startsWith("DROP")) {
                    System.out.println("NOK / " + statmentStr + " Failed ");
                } else {
                    sqle.printStackTrace();
                }
            }

        }
    } catch (SQLException sqle) {

        if (isNoConnectionError(sqle) && canReconnect()) {
            applyDBScript(scriptInputStream);
        } else {
            throw new RemoteException("", (sqle));
        }

    } finally {
        if (stmt != null)
            try {
                stmt.close();
            } catch (Exception e) {
                throw new RemoteException("", (e));
            }
        if (rset != null)
            try {
                stmt.close();
            } catch (Exception e) {
                throw new RemoteException("", (e));
            }
    }
}

From source file:org.apache.jmeter.JMeter.java

private void runNonGui(String testFile, String logFile, boolean remoteStart, String remote_hosts_string,
        boolean generateReportDashboard) {
    try {/* ww w .j a v a  2  s.c o  m*/
        File f = new File(testFile);
        if (!f.exists() || !f.isFile()) {
            println("Could not open " + testFile);
            return;
        }
        FileServer.getFileServer().setBaseForScript(f);

        HashTree tree = SaveService.loadTree(f);

        @SuppressWarnings("deprecation") // Deliberate use of deprecated ctor
        JMeterTreeModel treeModel = new JMeterTreeModel(new Object());// Create non-GUI version to avoid headless problems
        JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot();
        treeModel.addSubTree(tree, root);

        // Hack to resolve ModuleControllers in non GUI mode
        SearchByClass<ReplaceableController> replaceableControllers = new SearchByClass<>(
                ReplaceableController.class);
        tree.traverse(replaceableControllers);
        Collection<ReplaceableController> replaceableControllersRes = replaceableControllers.getSearchResults();
        for (ReplaceableController replaceableController : replaceableControllersRes) {
            replaceableController.resolveReplacementSubTree(root);
        }

        // Remove the disabled items
        // For GUI runs this is done in Start.java
        convertSubTree(tree);

        Summariser summer = null;
        String summariserName = JMeterUtils.getPropDefault("summariser.name", "");//$NON-NLS-1$
        if (summariserName.length() > 0) {
            log.info("Creating summariser <" + summariserName + ">");
            println("Creating summariser <" + summariserName + ">");
            summer = new Summariser(summariserName);
        }
        ReportGenerator reportGenerator = null;
        if (logFile != null) {
            ResultCollector logger = new ResultCollector(summer);
            logger.setFilename(logFile);
            tree.add(tree.getArray()[0], logger);
            if (generateReportDashboard) {
                reportGenerator = new ReportGenerator(logFile, logger);
            }
        } else {
            // only add Summariser if it can not be shared with the ResultCollector
            if (summer != null) {
                tree.add(tree.getArray()[0], summer);
            }
        }
        // Used for remote notification of threads start/stop,see BUG 54152
        // Summariser uses this feature to compute correctly number of threads 
        // when NON GUI mode is used
        tree.add(tree.getArray()[0], new RemoteThreadsListenerTestElement());

        List<JMeterEngine> engines = new LinkedList<>();
        tree.add(tree.getArray()[0],
                new ListenToTest(parent, (remoteStart && remoteStop) ? engines : null, reportGenerator));
        println("Created the tree successfully using " + testFile);
        if (!remoteStart) {
            JMeterEngine engine = new StandardJMeterEngine();
            engine.configure(tree);
            long now = System.currentTimeMillis();
            println("Starting the test @ " + new Date(now) + " (" + now + ")");
            engine.runTest();
            engines.add(engine);
        } else {
            java.util.StringTokenizer st = new java.util.StringTokenizer(remote_hosts_string, ",");//$NON-NLS-1$
            List<String> hosts = new LinkedList<>();
            while (st.hasMoreElements()) {
                hosts.add((String) st.nextElement());
            }

            DistributedRunner distributedRunner = new DistributedRunner(this.remoteProps);
            distributedRunner.setStdout(System.out);
            distributedRunner.setStdErr(System.err);
            distributedRunner.init(hosts, tree);
            engines.addAll(distributedRunner.getEngines());
            distributedRunner.start();
        }
        startUdpDdaemon(engines);
    } catch (Exception e) {
        System.out.println("Error in NonGUIDriver " + e.toString());
        log.error("Error in NonGUIDriver", e);
    }
}

From source file:us.mn.state.health.lims.result.action.ResultsEntryUpdateAction.java

protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // this is used if user has clicked notes icon and decides to update
    // (all results get updated, but we need to know which results to
    // display notes for)
    String notesAnalyteId = (String) request.getParameter("analyteId");
    String notesRefId = null;/*from   ww  w .j  a  v a  2s.c  om*/

    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");
    request.setAttribute(PREVIOUS_DISABLED, "true");
    request.setAttribute(NEXT_DISABLED, "true");
    String refId = null;

    if (request.getAttribute(NOTES_REFID) != null) {
        refId = (String) request.getAttribute(NOTES_REFID);
    }

    //bugzilla 2227
    String amendedAnalysisId = null;
    if (request.getParameter(ANALYSIS_ID) != null) {
        amendedAnalysisId = (String) request.getParameter(ANALYSIS_ID);
    }

    BaseActionForm dynaForm = (BaseActionForm) form;

    String accessionNumber = (String) dynaForm.get("accessionNumber");
    String[] selectedTestResultIds = (String[]) dynaForm.get("selectedTestResultIds");
    String[] resultValueN = (String[]) dynaForm.get("resultValueN");
    String[] selectedResultIsReportableFlags = (String[]) dynaForm.get("selectedResultIsReportableFlags");
    List testTestAnalytes = (List) dynaForm.get("testTestAnalytes");
    String addedReflexTestIds = (String) dynaForm.get("addedReflexTestIds");
    String addedReflexTestParentResultIds = (String) dynaForm.get("addedReflexTestParentResultIds");
    // bugzilla 1882
    String addedReflexTestParentAnalyteIds = (String) dynaForm.get("addedReflexTestParentAnalyteIds");
    String addedReflexTestParentAnalysisIds = (String) dynaForm.get("addedReflexTestParentAnalysisIds");
    String[] selectedTestIsReportableFlags = (String[]) dynaForm.get("selectedTestIsReportableFlags");

    String domain = (String) dynaForm.get("domain");
    //bugzilla 2254
    String hasNewUnsatisfactoryResult = (String) dynaForm.get("hasNewUnsatisfactoryResult");

    //bugzilla 1798: if coming from popup to link a parent test - this will have information
    String linkedParentInformationString = (String) dynaForm.get("linkedParentInformationString");

    //bugzilla 1798: if User has clicked UNLINK FROM PARENT this string will have information
    String unlinkedParentInformationString = (String) dynaForm.get("unlinkedParentInformationString");

    int pageResultCounter = 0;
    for (int j = 0; j < testTestAnalytes.size(); j++) {
        Test_TestAnalyte testTestAnalyte = (Test_TestAnalyte) testTestAnalytes.get(j);
        TestAnalyte_TestResults[] testAnalyteTestResults = (TestAnalyte_TestResults[]) testTestAnalyte
                .getTestAnalyteTestResults();

        // remove the testresultid added by default for those numeric types
        for (int i = 0; i < testAnalyteTestResults.length; i++) {
            TestAnalyte_TestResults taTr = (TestAnalyte_TestResults) testAnalyteTestResults[i];
            List testResults = taTr.getTestResults();
            //bugzila 1908 fixing a bug where null and size not checked (this was found while testing 1908)
            if (testResults != null && testResults.size() > 0) {
                TestResult testresult = (TestResult) testResults.get(0);
                //bugzilla 2220 - Added titer type results to this logic (numeric and titer are in one category)
                if (testresult.getTestResultType()
                        .equalsIgnoreCase(SystemConfiguration.getInstance().getNumericType())
                        || testresult.getTestResultType()
                                .equalsIgnoreCase(SystemConfiguration.getInstance().getTiterType())) {
                    if (StringUtil.isNullorNill(resultValueN[pageResultCounter])) {
                        selectedTestResultIds[pageResultCounter] = "";
                    }

                }
            }
            pageResultCounter++;
        }
    }

    // server side validation of accessionNumber
    // validate on server-side sample accession number

    ActionMessages errors = null;

    try {
        errors = new ActionMessages();
        errors = validateAll(request, errors, dynaForm);
        // System.out.println("Just validated accessionNumber");
    } catch (Exception e) {
        //bugzilla 2154
        LogEvent.logError("ResultsEntryUpdateAction", "performAction()", e.toString());
        ActionError error = new ActionError("errors.ValidationException", null, null);
        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
    }
    if (errors != null && errors.size() > 0) {
        saveErrors(request, errors);
        //bugzilla 2361
        if (domain.equals(SystemConfiguration.getInstance().getHumanDomain())) {
            return mapping.findForward(FWD_FAIL_HUMAN);
        } else {
            return mapping.findForward(FWD_FAIL);
        }
    }

    // initialize the form
    dynaForm.initialize(mapping);

    // 1926 get sysUserId from login module
    UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA);
    String sysUserId = String.valueOf(usd.getSystemUserId());

    Date today = Calendar.getInstance().getTime();
    Locale locale = (Locale) request.getSession().getAttribute("org.apache.struts.action.LOCALE");

    String dateAsText = DateUtil.formatDateAsText(today, locale);

    org.hibernate.Transaction tx = HibernateUtil.getSession().beginTransaction();

    if (!StringUtil.isNullorNill(accessionNumber)) {

        ResultDAO resultDAO = new ResultDAOImpl();
        TestResultDAO testResultDAO = new TestResultDAOImpl();
        AnalysisDAO analysisDAO = new AnalysisDAOImpl();
        TestDAO testDAO = new TestDAOImpl();
        NoteDAO noteDAO = new NoteDAOImpl();
        TestAnalyteDAO testAnalyteDAO = new TestAnalyteDAOImpl();
        SampleDAO sampleDAO = new SampleDAOImpl();
        DictionaryDAO dictDAO = new DictionaryDAOImpl();

        try {
            //bugzilla 1798 (added functionality to link a parent test to child test)
            //parse data from popup (link test) for subsequent update of child analysis
            String childAnalysisId = "";
            Analysis linkedParentAnalysis = new Analysis();
            Result linkedParentResult = new Result();
            if (!StringUtil.isNullorNill(linkedParentInformationString)) {

                String idSeparator = SystemConfiguration.getInstance().getDefaultIdSeparator();
                StringTokenizer st = new StringTokenizer(linkedParentInformationString, idSeparator);
                String parentAnalysisId = "";
                String parentResultId = "";

                List listOfIds = new ArrayList();
                while (st.hasMoreElements()) {
                    String id = (String) st.nextElement();
                    listOfIds.add(id);
                }

                //see resultsEntryLinkChildTestToParentTestResultPopup.jsp
                childAnalysisId = (String) listOfIds.get(0);
                parentAnalysisId = (String) listOfIds.get(1);
                parentResultId = (String) listOfIds.get(2);

                linkedParentAnalysis.setId(parentAnalysisId);
                linkedParentResult.setId(parentResultId);

                analysisDAO.getData(linkedParentAnalysis);
                resultDAO.getData(linkedParentResult);

            }
            //end 1798

            Sample sample = new Sample();
            sample.setAccessionNumber(accessionNumber);
            sample = sampleDAO.getSampleByAccessionNumber(accessionNumber);

            int pageResultIndex = 0;

            // pre-process the reflex tests
            List listOfTestsThatTriggeredReflex = new ArrayList();
            List listOfTestResultsThatTriggeredReflex = new ArrayList();
            // bugzilla 1882
            List listOfAnalytesThatTriggeredReflex = new ArrayList();
            List listOfAnalysesThatTriggeredReflex = new ArrayList();
            List listOfResultsThatTriggeredReflex = new ArrayList();
            List listOfAddedTests = new ArrayList();
            if (!StringUtil.isNullorNill(addedReflexTestIds)
                    && !StringUtil.isNullorNill(addedReflexTestParentResultIds)) {
                String idSeparator = SystemConfiguration.getInstance().getDefaultIdSeparator();

                // populate list of parent results
                StringTokenizer parentResultTokenizer = new StringTokenizer(addedReflexTestParentResultIds,
                        idSeparator);
                while (parentResultTokenizer.hasMoreElements()) {
                    String testResultId = (String) parentResultTokenizer.nextElement();
                    TestResult testResult = new TestResult();
                    testResult.setId(testResultId);
                    testResultDAO.getData(testResult);
                    listOfTestResultsThatTriggeredReflex.add(testResult);
                    String testId = testResult.getTest().getId();
                    listOfTestsThatTriggeredReflex.add(testId);
                }

                StringTokenizer addedTestTokenizer = new StringTokenizer(addedReflexTestIds, idSeparator);

                while (addedTestTokenizer.hasMoreElements()) {
                    String testId = (String) addedTestTokenizer.nextElement();
                    // System.out
                    // .println("This is a addedTestToken " + testId);
                    Test test = new Test();
                    test.setId(testId);
                    testDAO.getData(test);
                    listOfAddedTests.add(test);
                }

                // bugzilla 1882 populate list of parent analytes
                StringTokenizer parentAnalyteTokenizer = new StringTokenizer(addedReflexTestParentAnalyteIds,
                        idSeparator);
                while (parentAnalyteTokenizer.hasMoreElements()) {
                    String testAnalyteId = (String) parentAnalyteTokenizer.nextElement();
                    TestAnalyte testAnalyte = new TestAnalyte();
                    testAnalyte.setId(testAnalyteId);
                    testAnalyteDAO.getData(testAnalyte);
                    listOfAnalytesThatTriggeredReflex.add(testAnalyte);
                }

                // bugzilla 1882 populate list of parent analyses
                StringTokenizer parentAnalysisTokenizer = new StringTokenizer(addedReflexTestParentAnalysisIds,
                        idSeparator);
                while (parentAnalysisTokenizer.hasMoreElements()) {
                    String analysisId2 = (String) parentAnalysisTokenizer.nextElement();
                    Analysis analysis2 = new Analysis();
                    analysis2.setId(analysisId2);
                    listOfAnalysesThatTriggeredReflex.add(analysis2);
                }

            }

            for (int x = 0; x < testTestAnalytes.size(); x++) {
                Test_TestAnalyte test_testAnalyte = (Test_TestAnalyte) testTestAnalytes.get(x);
                TestAnalyte_TestResults[] testAnalyteTestResults = (TestAnalyte_TestResults[]) test_testAnalyte
                        .getTestAnalyteTestResults();

                Analysis analysis = test_testAnalyte.getAnalysis();

                //bugzilla 1942 (if results for all REQUIRED test analytes have been entered then results entry is considered complete)
                boolean areResultsForRequiredTestAnalytesEntered = true;
                //bugzilla 1942 completedDate on analysis should only be update if 
                //              results entry is completed = areResultsForRequiredTestAnalytesEntered is true
                //              AND if at least one result has changed
                boolean atLeastOneRequiredResultHasChanged = false;

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

                    TestAnalyte_TestResults taTr = (TestAnalyte_TestResults) testAnalyteTestResults[i];

                    String selectedTestResultId = taTr.getSelectedTestResultId();
                    TestAnalyte ta = taTr.getTestAnalyte();

                    Result result = new Result();
                    Result[] resultsFromTestTestAnalyte = test_testAnalyte.getResults();

                    for (int j = 0; j < resultsFromTestTestAnalyte.length; j++) {
                        Result res = (Result) resultsFromTestTestAnalyte[j];
                        if (res != null && !StringUtil.isNullorNill(res.getId())) {
                            if (res.getAnalyte().getId().equals(ta.getAnalyte().getId())) {
                                result = res;
                                break;
                            }
                        }
                    }
                    // bugzilla 1926
                    result.setSysUserId(sysUserId);

                    //bugzilla 1942
                    boolean noResult = true;
                    if (!StringUtil.isNullorNill(selectedTestResultId)) {
                        if (!StringUtil.isNullorNill(selectedTestResultIds[pageResultIndex])) {
                            noResult = false;
                            TestResult tr = new TestResult();
                            tr.setId(selectedTestResultIds[pageResultIndex]);
                            testResultDAO.getData(tr);

                            //bugzilla 1942: find out if required results have changed on this test (needed to determine whether to update completed date)
                            if (result.getIsReportable() != null && result.getIsReportable().equals(YES)) {
                                if (result.getTestResult() != null
                                        && !StringUtil.isNullorNill(result.getTestResult().getValue())) {
                                    String oldResult = result.getTestResult().getValue();
                                    if (!oldResult.equals(tr.getValue())) {
                                        atLeastOneRequiredResultHasChanged = true;
                                    }
                                }
                            }

                            // update existing selection
                            result.setTestResult(tr);

                            if (tr.getTestResultType()
                                    .equalsIgnoreCase(SystemConfiguration.getInstance().getNumericType())) {
                                result.setValue(resultValueN[pageResultIndex]);
                            } else if (tr.getTestResultType()
                                    .equalsIgnoreCase(SystemConfiguration.getInstance().getTiterType())) {

                                String setTiter = "1:" + resultValueN[pageResultIndex];
                                result.setValue(setTiter);
                            } else {
                                result.setValue(tr.getValue());
                                //bugzilla 2028 check for UNSATISFACTORY dictionary type results
                                // get from dictionary
                                Dictionary dictionary = new Dictionary();
                                dictionary.setId(result.getValue());
                                dictDAO.getData(dictionary);
                            }

                            result.setAnalysis(analysis);

                            result.setIsReportable(selectedResultIsReportableFlags[pageResultIndex]);
                            if (!StringUtil.isNullorNill(notesAnalyteId)) {
                                if (result.getAnalyte().getId().equals(notesAnalyteId)) {
                                    notesRefId = result.getId();
                                }
                            }

                            resultDAO.updateData(result);

                        } else {
                            // bugzilla 1942: delete existing result
                            List results = new ArrayList();
                            //bugzilla 1942 check if result has notes - THEN DON'T ALLOW DELETE (per Christina/Nancy)
                            Note note = new Note();
                            List notesByResult = new ArrayList();
                            //bugzilla 2571 go through ReferenceTablesDAO to get reference tables info
                            ReferenceTables referenceTables = new ReferenceTables();
                            referenceTables
                                    .setId(SystemConfiguration.getInstance().getResultReferenceTableId());
                            //bugzilla 2571 go through ReferenceTablesDAO to get reference tables info
                            note.setReferenceTables(referenceTables);
                            note.setReferenceId(result.getId());
                            notesByResult = noteDAO.getAllNotesByRefIdRefTable(note);

                            //bugzilla 1798
                            List childAnalysesByResult = new ArrayList();
                            childAnalysesByResult = analysisDAO.getAllChildAnalysesByResult(result);

                            if (notesByResult != null && notesByResult.size() > 0) {
                                Exception e = new LIMSCannotDeleteDependentRecordExistsException(
                                        "Cannot delete - dependent record exists for " + result.getId());

                                throw new LIMSRuntimeException("Error in Result updateData()", e);
                            }
                            //bugzilla 1798
                            else if (childAnalysesByResult != null && childAnalysesByResult.size() > 0) {
                                Exception e = new LIMSCannotDeleteDependentRecordExistsException(
                                        "Cannot delete - dependent record exists for " + result.getId());

                                throw new LIMSRuntimeException("Error in Result updateData()", e);
                            } else {
                                results.add(result);
                                resultDAO.deleteData(results);
                            }
                        }
                    } else {
                        if (!StringUtil.isNullorNill(selectedTestResultIds[pageResultIndex])) {
                            // insert new result
                            noResult = false;
                            TestResult tr = new TestResult();
                            tr.setId(selectedTestResultIds[pageResultIndex]);
                            testResultDAO.getData(tr);

                            // insert
                            Analyte analyte = ta.getAnalyte();
                            result.setAnalyte(analyte);
                            result.setAnalysis(analysis);

                            result.setTestResult(tr);
                            if (tr.getTestResultType()
                                    .equalsIgnoreCase(SystemConfiguration.getInstance().getNumericType())) {
                                result.setValue(resultValueN[pageResultIndex]);
                            } else if (tr.getTestResultType()
                                    .equalsIgnoreCase(SystemConfiguration.getInstance().getTiterType())) {

                                String setTiter = "1:" + resultValueN[pageResultIndex];
                                result.setValue(setTiter);
                            } else {
                                result.setValue(tr.getValue());
                                //bugzilla 2028 check for UNSATISFACTORY dictionary type results
                                // get from dictionary
                                Dictionary dictionary = new Dictionary();
                                dictionary.setId(result.getValue());
                                dictDAO.getData(dictionary);
                            }

                            result.setResultType(tr.getTestResultType());
                            result.setIsReportable(selectedResultIsReportableFlags[pageResultIndex]);
                            result.setSortOrder(ta.getSortOrder());

                            //bugzilla 1942: find out if required results have changed on this test (needed to determine whether to update completed date)
                            //this result has changed for sure
                            if (ta.getIsReportable() != null && ta.getIsReportable().equals(YES)) {
                                atLeastOneRequiredResultHasChanged = true;
                            }
                            resultDAO.insertData(result);

                            // need to add this new result to
                            // test_testAnalyte
                            // for display on right side of screen after
                            // update
                            // on route to notes popup
                            resultsFromTestTestAnalyte[i] = result;
                            test_testAnalyte.setResults(resultsFromTestTestAnalyte);

                            if (!StringUtil.isNullorNill(notesAnalyteId)) {
                                if (result.getAnalyte().getId().equals(notesAnalyteId)) {
                                    notesRefId = result.getId();
                                }
                            }
                        } else {
                            // do nothing
                        }
                    }

                    //bugzilla 1942 (if results for all REQUIRED test analytes have been entered then results entry is considered complete)
                    //  per Christina - all reportable results must have a value for a test otherwise results entry is not completed
                    //  need to check test_analyte for isReportable flag if there is NO result record
                    if (noResult && !StringUtil.isNullorNill(ta.getIsReportable())
                            && ta.getIsReportable().equals(YES)) {
                        areResultsForRequiredTestAnalytesEntered = false;
                    }

                    // if this is analyte that notes icon was selected for
                    // then
                    // set the result id (IActionConstants.NOTES_REFID) in
                    // the
                    // request
                    // this can be used in NotesPopupAction
                    pageResultIndex++;
                }
                // bugzilla 1926
                analysis.setSysUserId(sysUserId);

                analysis.setIsReportable(selectedTestIsReportableFlags[x]);

                //bugzilla 1942 (if results for all REQUIRED test analytes have been entered then results entry is considered complete)
                if (areResultsForRequiredTestAnalytesEntered) {
                    //bugzilla 1967 only if not already released
                    //bugzilla 1942 AND if at least one result has changed
                    if (!analysis.getStatus()
                            .equals(SystemConfiguration.getInstance().getAnalysisStatusReleased())
                            && atLeastOneRequiredResultHasChanged) {
                        analysis.setStatus(
                                SystemConfiguration.getInstance().getAnalysisStatusResultCompleted());
                        analysis.setCompletedDateForDisplay(dateAsText);
                    }
                } else {
                    analysis.setStatus(SystemConfiguration.getInstance().getAnalysisStatusAssigned());
                    analysis.setCompletedDateForDisplay(null);
                }

                //bugzilla 1798 also update parent analysis/parent result if link was requested for this analysis
                //link
                if (!StringUtil.isNullorNill(linkedParentInformationString)
                        && childAnalysisId.equals(analysis.getId())) {
                    analysis.setParentAnalysis(linkedParentAnalysis);
                    analysis.setParentResult(linkedParentResult);
                }
                //unlink
                if (!StringUtil.isNullorNill(unlinkedParentInformationString)
                        && unlinkedParentInformationString.equals(analysis.getId())) {
                    analysis.setParentAnalysis(null);
                    analysis.setParentResult(null);
                }

                analysisDAO.updateData(analysis);

            }

            // bugzilla 1882
            if (listOfAnalytesThatTriggeredReflex.size() > 0) {
                //create listOfResultsThatTriggeredReflex from analysis/analyte
                for (int i = 0; i < listOfAnalysesThatTriggeredReflex.size(); i++) {

                    Analysis analysisThatTriggered = (Analysis) listOfAnalysesThatTriggeredReflex.get(i);
                    TestAnalyte analyteThatTriggered = (TestAnalyte) listOfAnalytesThatTriggeredReflex.get(i);
                    Result result = new Result();
                    resultDAO.getResultByAnalysisAndAnalyte(result, analysisThatTriggered,
                            analyteThatTriggered);
                    listOfResultsThatTriggeredReflex.add(result);
                }
                // Are there any added tests (reflex tests)
                for (int i = 0; i < listOfAnalytesThatTriggeredReflex.size(); i++) {

                    Analysis analysisThatTriggered = (Analysis) listOfAnalysesThatTriggeredReflex.get(i);
                    analysisDAO.getData(analysisThatTriggered);
                    TestAnalyte analyteThatTriggered = (TestAnalyte) listOfAnalytesThatTriggeredReflex.get(i);
                    Result result = (Result) listOfResultsThatTriggeredReflex.get(i);
                    Test test = (Test) listOfAddedTests.get(i);
                    Analysis newAnalysis = new Analysis();
                    // TODO: need to populate this with actual data!!!
                    newAnalysis.setAnalysisType("TEST");
                    newAnalysis.setSampleItem(analysisThatTriggered.getSampleItem());
                    newAnalysis.setTest(test);
                    newAnalysis.setTestSection(test.getTestSection());
                    newAnalysis.setStatus(SystemConfiguration.getInstance().getAnalysisStatusAssigned());

                    newAnalysis.setParentAnalysis(analysisThatTriggered);
                    newAnalysis.setParentResult(result);
                    newAnalysis.setIsReportable(test.getIsReportable());
                    // bugzilla 1926
                    newAnalysis.setSysUserId(sysUserId);
                    //bugzilla 2064
                    newAnalysis.setRevision(SystemConfiguration.getInstance().getAnalysisDefaultRevision());
                    //bugzilla 2013 added duplicateCheck parameter
                    analysisDAO.insertData(newAnalysis, false);
                }
            }

            tx.commit();

            // bugzilla 1703: introducing a confirmation message after
            // updates and inserts have succeeded!
            errors = new ActionMessages();
            ActionError error = null;
            error = new ActionError("resultsentry.confirmupdate.message", null, null);
            errors.add(ActionMessages.GLOBAL_MESSAGE, error);
            saveErrors(request, errors);
            request.setAttribute(Globals.ERROR_KEY, errors);
            // end bugzilla 1703

        } catch (LIMSRuntimeException lre) {
            //bugzilla 2154
            LogEvent.logError("ResultsEntryUpdateAction", "performAction()", lre.toString());
            tx.rollback();

            errors = new ActionMessages();
            ActionError error = null;
            if (lre.getException() instanceof org.hibernate.StaleObjectStateException) {

                error = new ActionError("errors.OptimisticLockException", null, null);
            } else if (lre.getException() instanceof LIMSCannotDeleteDependentRecordExistsException) {
                error = new ActionError("resultsentry.changetonoresult.error", null, null);
            } else {
                error = new ActionError("errors.UpdateException", null, null);
            }
            errors.add(ActionMessages.GLOBAL_MESSAGE, error);
            saveErrors(request, errors);
            request.setAttribute(Globals.ERROR_KEY, errors);
            // bugzilla 1485
            // request.setAttribute(IActionConstants.ALLOW_EDITS_KEY,
            // "false");

            //bugzilla 2361
            if (domain.equals(SystemConfiguration.getInstance().getHumanDomain())) {
                forward = FWD_FAIL_HUMAN;
            } else {
                forward = FWD_FAIL;
            }

        } finally {
            HibernateUtil.closeSession();
        }

    }

    PropertyUtils.setProperty(dynaForm, "accessionNumber", accessionNumber);
    PropertyUtils.setProperty(dynaForm, "selectedTestResultIds", selectedTestResultIds);
    PropertyUtils.setProperty(dynaForm, "resultValueN", resultValueN);
    PropertyUtils.setProperty(dynaForm, "selectedResultIsReportableFlags", selectedResultIsReportableFlags);
    PropertyUtils.setProperty(dynaForm, "selectedTestIsReportableFlags", selectedTestIsReportableFlags);

    PropertyUtils.setProperty(dynaForm, "domain", domain);
    PropertyUtils.setProperty(dynaForm, "testTestAnalytes", testTestAnalytes);

    if (!StringUtil.isNullorNill(notesAnalyteId)) {
        request.setAttribute(NOTES_REFID, notesRefId);
        request.setAttribute(NOTES_REFTABLE, SystemConfiguration.getInstance().getResultReferenceTableId());
    } else {
        request.setAttribute(NOTES_REFID, refId);
        request.setAttribute(NOTES_REFTABLE, SystemConfiguration.getInstance().getResultReferenceTableId());
    }

    //bugzilla 2311
    //bugzilla 2361
    if (!forward.equals(FWD_FAIL) && !forward.equals(FWD_FAIL_HUMAN)) {
        //bugzilla 2028 Qa Events - if any of the results are UNSATISFACTORY then route to QAEvents Entry
        //bugzilla 2227 - don't route to qa events if Note or Amend were clicked
        //bugzilla 2254
        if (hasNewUnsatisfactoryResult.equals(TRUE) && !mapping.getPath().contains("Note")
                && !mapping.getPath().contains("Amend")) {
            forward = FWD_SUCCESS_QA_EVENTS_ENTRY;
            return getForward(mapping.findForward(forward), accessionNumber);
        }

        //bugzilla 2227
        if (!StringUtil.isNullorNill(amendedAnalysisId)) {
            return getForward(mapping.findForward(forward), accessionNumber, amendedAnalysisId);
        }
    }

    return mapping.findForward(forward);
}

From source file:com.irets.datadownloader.SearchPropertyServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
    long reqInputArrivalTime = System.currentTimeMillis();
    Date resultdate = new Date(reqInputArrivalTime);
    System.out.println("Calling Me @:" + sdf.format(resultdate) + ", from: " + request.getRemoteAddr()
            + ", with url> " + request.getRequestURL() + "?" + request.getQueryString());

    long startTime = reqInputArrivalTime;

    WebApplicationContext wac = WebApplicationContextUtils
            .getRequiredWebApplicationContext(getServletContext());
    SearchService propServices = this.getSearchService(wac);
    propServices.setContextPath(this.getUrl3(request));
    //propServices.setServer(this.getServer(request));
    Filter filer = new Filter();
    ArrayList<FilterItem> filterItemArrayList = new ArrayList<FilterItem>(1);
    ArrayList<FilterItem> exactFilterItemArrayList = new ArrayList<FilterItem>(1);
    ArrayList<FilterItem> multipleFilterItemArrayList = new ArrayList<FilterItem>(1);
    ArrayList<String> keywordArrayList = new ArrayList<String>(1);
    Vector<SimpleRange> rangeVector = new Vector<SimpleRange>(1);
    GeoParameter geoParam = null;/*w w w . j ava  2 s .  co  m*/
    //        SimpleRange aRange = new SimpleRange("price_list",null,50000);
    //        filer.setRanges(new SimpleRange[]{aRange});
    int start = 0;
    int limit = -1;
    //        if(request.getParameter("ListingId") != null){
    //           FilterItem filterItem = new FilterItem();
    //            filterItem.setField("number_MLS");
    //            filterItem.setValue(request.getParameter("ListingId"));
    //            filterItemArrayList.add(filterItem);
    //        }
    if (request.getParameter("ListPrice") != null) {
        SimpleRange aRange;
        String listPrice = request.getParameter("ListPrice");
        System.out.println("List price is " + listPrice);
        String min = "";
        String max = "";
        if (!listPrice.equalsIgnoreCase("No Min-No Max")) {
            if (listPrice.indexOf(":") != -1) {
                //                 System.out.println("listPrice : -->>"+listPrice);
                min = listPrice.substring(0, listPrice.indexOf(":"));
                max = listPrice.substring(listPrice.indexOf(":") + 1, listPrice.length());
                aRange = new SimpleRange("price_list", min, max);
            } else if (listPrice.endsWith("+")) {
                //                 System.out.println("listPrice +-->>"+listPrice);
                min = listPrice.substring(0, listPrice.indexOf("+"));
                aRange = new SimpleRange("price_list", min, null);
            } else if (listPrice.endsWith("-")) {
                //                 System.out.println("listPrice - -->>"+listPrice);
                max = listPrice.substring(0, listPrice.indexOf("-"));
                aRange = new SimpleRange("price_list", null, max);
            } else if (listPrice.length() > 0) { // Exact match....
                min = listPrice.substring(0, listPrice.length());
                max = min;
                aRange = new SimpleRange("price_list", min, max);
            } else {
                aRange = new SimpleRange("price_list", null, null);
            }

            rangeVector.add(aRange);
        }
    }

    if (request.getParameter("Bedrooms") != null) {
        SimpleRange aRange;
        String bedrooms = request.getParameter("Bedrooms");
        String min = "";
        String max = "";
        if (!bedrooms.equalsIgnoreCase("No Min-No Max")) {
            if (bedrooms.indexOf(":") != -1) {
                //                 System.out.println("Bedrooms: -->>"+bedrooms);
                min = bedrooms.substring(0, bedrooms.indexOf(":"));
                max = bedrooms.substring(bedrooms.indexOf(":") + 1, bedrooms.length());
                aRange = new SimpleRange("number_beds_Total", min, max);
            } else if (bedrooms.endsWith("+")) {
                //                 System.out.println("Bedrooms+ -->>"+bedrooms);
                min = bedrooms.substring(0, bedrooms.indexOf("+"));
                aRange = new SimpleRange("number_beds_Total", min, null);
            } else if (bedrooms.endsWith("-")) {
                //                 System.out.println("Bedrooms- -->>"+bedrooms);
                max = bedrooms.substring(0, bedrooms.indexOf("-"));
                aRange = new SimpleRange("number_beds_Total", null, max);
            } else if (bedrooms.length() > 0) { // Exact match....
                min = bedrooms.substring(0, bedrooms.length());
                max = min;
                aRange = new SimpleRange("number_beds_Total", min, max);
            } else {
                aRange = new SimpleRange("number_beds_Total", null, null);
            }
            rangeVector.add(aRange);
        }
    }
    if (request.getParameter("FullBathrooms") != null) {
        SimpleRange aRange;
        String fullBath = request.getParameter("FullBathrooms");
        String min = "";
        String max = "";
        if (!fullBath.equalsIgnoreCase("No Min-No Max")) {
            if (fullBath.indexOf(":") != -1) {
                //                 System.out.println("FullBathrooms: -->>"+fullBath);
                min = fullBath.substring(0, fullBath.indexOf(":"));
                max = fullBath.substring(fullBath.indexOf(":") + 1, fullBath.length());
                aRange = new SimpleRange("number_baths_Full", min, max);
            } else if (fullBath.endsWith("+")) {
                //                 System.out.println("FullBathrooms+ -->>"+fullBath);
                min = fullBath.substring(0, fullBath.indexOf("+"));
                aRange = new SimpleRange("number_baths_Full", min, null);
            } else if (fullBath.endsWith("-")) {
                //                 System.out.println("FullBathrooms- -->>"+fullBath);
                max = fullBath.substring(0, fullBath.indexOf("-"));
                aRange = new SimpleRange("number_baths_Full", null, max);
            } else if (fullBath.length() > 0) {
                min = fullBath.substring(0, fullBath.length());
                max = min;
                aRange = new SimpleRange("number_baths_Full", min, max);
            } else {
                aRange = new SimpleRange("number_baths_Full", null, null);
            }
            rangeVector.add(aRange);
        }
    }

    if (request.getParameter("SqFt") != null) {
        SimpleRange aRange;
        String sqFt = request.getParameter("SqFt");
        String min = "";
        String max = "";
        if (!sqFt.equalsIgnoreCase("No Min-No Max")) {
            if (sqFt.indexOf(":") != -1) {
                //                 System.out.println("SqFt: -->>"+sqFt);
                min = sqFt.substring(0, sqFt.indexOf(":"));
                max = sqFt.substring(sqFt.indexOf(":") + 1, sqFt.length());
                aRange = new SimpleRange("sqft_Structure", min, max);
            } else if (sqFt.endsWith("+")) {
                //                 System.out.println("SqFt+ -->>"+sqFt);
                min = sqFt.substring(0, sqFt.indexOf("+"));
                aRange = new SimpleRange("sqft_Structure", min, null);
            } else if (sqFt.endsWith("-")) {
                //                 System.out.println("SqFt- -->>"+sqFt);
                max = sqFt.substring(0, sqFt.indexOf("-"));
                aRange = new SimpleRange("sqft_Structure", null, max);
            } else if (sqFt.length() > 0) {
                min = sqFt.substring(0, sqFt.length());
                max = min;
                aRange = new SimpleRange("sqft_Structure", min, max);
            } else {
                aRange = new SimpleRange("sqft_Structure", null, null);
            }
            rangeVector.add(aRange);
        }
    }

    // Date range for the property.
    if (request.getParameter("Age") != null) {
        SimpleRange aRange;
        String age = request.getParameter("Age");
        String min = "";
        String max = "";
        if (!age.equalsIgnoreCase("No Min-No Max")) {
            if (age.indexOf(":") != -1) {
                System.out.println("age: -->>" + age);
                min = age.substring(0, age.indexOf(":"));
                max = age.substring(age.indexOf(":") + 1, age.length());
                aRange = new SimpleRange("date_Listing_Modification", min, max);
            } else if (age.endsWith("+")) {
                //                 System.out.println("SqFt+ -->>"+sqFt);
                min = age.substring(0, age.indexOf("+"));
                aRange = new SimpleRange("date_Listing_Modification", min, null);
            } else if (age.endsWith("-")) {
                //                 System.out.println("SqFt- -->>"+sqFt);
                max = age.substring(0, age.indexOf("-"));
                aRange = new SimpleRange("date_Listing_Modification", null, max);
            } else if (age.length() > 0) {
                min = age.substring(0, age.length());
                max = min;
                aRange = new SimpleRange("date_Listing_Modification", min, max);
            } else {
                aRange = new SimpleRange("date_Listing_Modification", null, null);
            }
            System.out.println("Range is " + aRange.getMinValue() + ", " + aRange.getMaxValue());
            rangeVector.add(aRange);
        }
    }

    // Range for Longitude
    if (request.getParameter("Longitude") != null) {
        SimpleRange aRange;
        String longitude = request.getParameter("Longitude");
        System.out.println("Longitude is " + longitude);
        String min = "";
        String max = "";
        if (longitude.indexOf(":") != -1) {
            min = longitude.substring(0, longitude.indexOf(":"));
            max = longitude.substring(longitude.indexOf(":") + 1, longitude.length());
            aRange = new SimpleRange("_long", min, max);
        } else {
            aRange = new SimpleRange("_long", null, null);
        }
        rangeVector.add(aRange);
    }

    // Range for Latitude
    if (request.getParameter("Latitude") != null) {
        SimpleRange aRange;
        String latitude = request.getParameter("Latitude");
        System.out.println("Latitude is " + latitude);
        String min = "";
        String max = "";
        if (latitude.indexOf(":") != -1) {
            min = latitude.substring(0, latitude.indexOf(":"));
            max = latitude.substring(latitude.indexOf(":") + 1, latitude.length());
            aRange = new SimpleRange("lat", min, max);
        } else {
            aRange = new SimpleRange("lat", null, null);
        }
        rangeVector.add(aRange);
    }

    // Near by homes
    // Format required is Latitude,Longitude,distance
    if (request.getParameter("NBH") != null) {
        String nbh = request.getParameter("NBH");
        String[] s = nbh.split(",");
        if (s.length == 3) {
            Float f = Float.valueOf(s[2]);
            if (f >= 10) // 10 miles radius max
                s[2] = "10";
            else if (f < 0) // if negative distance
                s[2] = "1";
            geoParam = new GeoParameter(s[0], s[1], s[2]);
        }
    } else {
        // City and Zip are optional if NBH is provided.
        if (request.getParameter("Zip") != null) {
            FilterItem filterItem = new FilterItem();
            filterItem.setField("zipCode");
            // remove the space first
            String inZipcode = request.getParameter("Zip");
            StringBuffer zipBuffer = new StringBuffer();
            if (inZipcode.indexOf(",") > -1) {
                StringTokenizer sToken = new StringTokenizer(inZipcode, ",");
                while (sToken.hasMoreElements()) {
                    String object = (String) sToken.nextElement();
                    zipBuffer.append("'");
                    zipBuffer.append(object);
                    zipBuffer.append("'");
                    if (sToken.countTokens() > 0)
                        zipBuffer.append(",");
                }
            } else {
                zipBuffer.append("'");
                zipBuffer.append(inZipcode);
                zipBuffer.append("'");
            }

            //System.out.println(zipBuffer.toString());
            filterItem.setValue(zipBuffer.toString());
            multipleFilterItemArrayList.add(filterItem);

        }

        if (request.getParameter("City") != null) {
            FilterItem filterItem = new FilterItem();
            filterItem.setField("name_City");

            String cityList = request.getParameter("City");
            StringBuffer cityMod = new StringBuffer();
            if (cityList.indexOf(",") > -1) {
                StringTokenizer sToken = new StringTokenizer(cityList, ",");
                while (sToken.hasMoreElements()) {
                    String object = (String) sToken.nextElement();
                    cityMod.append("'");
                    cityMod.append(getCity(object));
                    cityMod.append("'");
                    if (sToken.countTokens() > 0)
                        cityMod.append(",");
                }
            } else {
                cityMod.append("'");
                cityMod.append(getCity(cityList));
                cityMod.append("'");
            }

            filterItem.setValue(cityMod.toString());
            multipleFilterItemArrayList.add(filterItem);
        }
    }

    // Status of property, link Active or Pending
    // For backward compatibility, Status=A. we added extra checks
    // for Status=ACTIVE or PENDING
    /*
     * if(request.getParameter("Status") != null &&
      (request.getParameter("Status").equalsIgnoreCase("ACTIVE")||
      request.getParameter("Status").equalsIgnoreCase("PENDING"))){
       FilterItem filterItem = new FilterItem();
    filterItem.setField("status_Listing");
    filterItem.setValue(request.getParameter("Status"));
    if (request.getParameter("Status").equalsIgnoreCase("PENDING")){
       filterItem.setValue(propServices.getPendingStatus());
    }           
    filterItemArrayList.add(filterItem);
    }
    */
    if (request.getParameter("Status") != null && (request.getParameter("Status").equalsIgnoreCase("ACTIVE")
            || request.getParameter("Status").equalsIgnoreCase("PENDING"))) {
        FilterItem filterItem = new FilterItem();
        filterItem.setField("status_Listing");
        StringBuffer statusMod = new StringBuffer();
        String statusList = null;
        if (request.getParameter("Status").equalsIgnoreCase("ACTIVE")) {
            statusList = propServices.getActiveStatus();
        } else if (request.getParameter("Status").equalsIgnoreCase("PENDING")) {
            statusList = propServices.getPendingStatus();
        }
        if (statusList.indexOf(",") > -1) {
            StringTokenizer sToken = new StringTokenizer(statusList, ",");
            while (sToken.hasMoreElements()) {
                String object = (String) sToken.nextElement();
                statusMod.append("'");
                statusMod.append(object);
                statusMod.append("'");
                if (sToken.countTokens() > 0)
                    statusMod.append(",");
            }
        } else {
            statusMod.append("'");
            statusMod.append(statusList);
            statusMod.append("'");
        }
        System.out.println("Status query..: " + statusMod.toString());
        filterItem.setValue(statusMod.toString());
        multipleFilterItemArrayList.add(filterItem);
    }

    if (request.getParameter("ListingId") != null) {
        FilterItem filterItem = new FilterItem();
        filterItem.setField("number_MLS");
        String listingId = request.getParameter("ListingId");
        String mlsNumberPrefix = propServices.getMlsNumberPrefix();
        StringBuffer listingIdList = new StringBuffer();
        if (listingId.indexOf(",") > -1) {
            StringTokenizer sToken = new StringTokenizer(listingId, ",");
            while (sToken.hasMoreElements()) {
                String object = (String) sToken.nextElement();
                if ((mlsNumberPrefix != null) && (!mlsNumberPrefix.equals(""))
                        && (!object.contains(mlsNumberPrefix))) {
                    listingIdList.append("'" + mlsNumberPrefix);
                } else {
                    listingIdList.append("'");
                }
                listingIdList.append(object);
                listingIdList.append("'");
                if (sToken.countTokens() > 0)
                    listingIdList.append(",");
            }
        } else {
            if ((mlsNumberPrefix != null) && (!mlsNumberPrefix.equals(""))
                    && (!listingId.contains(mlsNumberPrefix)))
                listingIdList.append("'" + mlsNumberPrefix);
            else
                listingIdList.append("'");
            listingIdList.append(listingId);
            listingIdList.append("'");
        }

        filterItem.setValue(listingIdList.toString());
        multipleFilterItemArrayList.add(filterItem);
        //System.out.println("got listing id "+ request.getParameter("ListingId"));
    }

    if (request.getParameter("ListingAgentLic") != null) {
        FilterItem filterItem = new FilterItem();
        filterItem.setField("listing_license_number");
        String listingId = request.getParameter("ListingAgentLic");

        if (listingId.indexOf(",") > -1) {
            StringTokenizer sToken = new StringTokenizer(listingId, ",");
            while (sToken.hasMoreElements()) {
                keywordArrayList.add((String) sToken.nextElement());
            }
        } else {
            keywordArrayList.add(listingId);
        }
        //System.out.println("got listing agent lic "+ request.getParameter("ListingAgentLic"));

    }

    if (request.getParameter("offset") != null) {
        start = Integer.parseInt(request.getParameter("offset"));
    }
    if (request.getParameter("limit") != null) {
        limit = Integer.parseInt(request.getParameter("limit"));
    }
    String sort = request.getParameter("sort");
    if (sort != null) {
        if (sort.equalsIgnoreCase("City")) {
            sort = "name_City";
        } else if (sort.equalsIgnoreCase("YearBuilt")) {
            sort = "year_Built";
        } else if (sort.equalsIgnoreCase("ListPrice")) {
            sort = "price_List";
        } else if (sort.equalsIgnoreCase("Sqft")) {
            sort = "sqft_Structure";
        } else if (sort.equalsIgnoreCase("LotSqFt")) {
            sort = "Size_Lot";
        } else if (sort.equalsIgnoreCase("Type")) {
            sort = "";
        } else if (sort.equalsIgnoreCase("Bedrooms")) {
            sort = "number_beds_Total";
        } else if (sort.equalsIgnoreCase("FullBathrooms")) {
            sort = "number_baths_Full";
        } else if (sort.equalsIgnoreCase("ExteriorFeatures")) {
            sort = "type_Property";
        } else if (sort.equalsIgnoreCase("none")) {
            sort = null;
        }
    }

    String sort_direction = request.getParameter("sort_direction");
    if (sort_direction != null) {
        if (sort_direction.equalsIgnoreCase("none")) {
            sort_direction = null;
        } else if (sort_direction.equalsIgnoreCase("ASC")) {
            sort_direction = "asc";
        } else {
            sort_direction = "desc";
        }

    } else { //{TOD: why do we need this??
        if (request.getParameter("ListingAgentLic") != null) {
            sort = "price_List";
            sort_direction = "desc"; // with agent listing, they want desc
        } else {
            sort_direction = "asc"; // default sorting order
        }

    }

    // Type of property, link Single Family, Townhouse, Condominium
    if (request.getParameter("ExteriorFeatures") != null) {
        String param = request.getParameter("ExteriorFeatures");
        FilterItem filterItem = new FilterItem();
        filterItem.setField("type_Property");
        List<ExteriorFeaturesData> extFeatureData = propServices.getExtFeaturesData();
        // Getting ExFeatures list from properties files
        if (extFeatureData != null) {
            System.out.println("Exterior Features param is " + param);
            for (ExteriorFeaturesData efd : extFeatureData) {
                if (efd.getName().equalsIgnoreCase(param)) {
                    filterItem.setValue(efd.getInSearchFields());
                    break;
                }
            }
            if (filterItem.getValue() != null) {
                System.out.println("Exterior Features value " + filterItem.getValue());
                multipleFilterItemArrayList.add(filterItem);
            }
        } else {// Getting ExFeatures list from DB                        
            filterItem.setValue(param);
            System.out.println("Exterior Features (single) " + filterItem.getValue());
            filterItemArrayList.add(filterItem);
        }

    }

    // Adding the search parameter for Full Address
    if (request.getParameter("FullAddress") != null) {
        FilterItem filterItem = new FilterItem();
        filterItem.setField("address_Filtered");
        filterItem.setValue(request.getParameter("FullAddress"));
        filterItemArrayList.add(filterItem);
    }

    boolean returnOpenHouseData = false;
    if (request.getParameter("OpenHouse") != null) {
        if (request.getParameter("OpenHouse").equals("1")) {
            returnOpenHouseData = true;
        }
    }

    // Put the keyword search (using it for license id)
    String[] filterArrayKeyword = new String[keywordArrayList.size()];
    filterArrayKeyword = keywordArrayList.toArray(filterArrayKeyword);
    filer.setKeywords(filterArrayKeyword);

    // Put range in the filter
    SimpleRange[] sRangeArray = new SimpleRange[rangeVector.size()];
    sRangeArray = rangeVector.toArray(sRangeArray);
    filer.setRanges(sRangeArray);

    // Put single value item in the filter with '%value%'
    FilterItem[] filterArray = new FilterItem[filterItemArrayList.size()];
    filterArray = filterItemArrayList.toArray(filterArray);
    filer.setFilters(filterArray);

    // Put single value item in the filter, with exact search with 'value'
    FilterItem[] exactFilterArray = new FilterItem[exactFilterItemArrayList.size()];
    exactFilterArray = exactFilterItemArrayList.toArray(exactFilterArray);
    filer.setExactFilters(exactFilterArray);

    // Put the multiple values (',' separated) item in the filter.
    FilterItem[] filterItemA = new FilterItem[multipleFilterItemArrayList.size()];
    filterItemA = multipleFilterItemArrayList.toArray(filterItemA);
    filer.setSearchForFieldItems(filterItemA);

    //System.out.println("time in making query:"+(new Date().getTime()-startTime)+" msecs");   
    //System.out.println("limit " + request.getParameter("limit") + ", offset " + 
    //      request.getParameter("offset") +", sort " + sort + ", sort direction "+ sort_direction);

    Object returnObj = null;
    startTime = new Date().getTime();

    // Create a Timer and a TimerTask
    Timer timer = new Timer();
    TimerTask task = new SearchPropertyTimerTask(request, response, this.getOutputType());

    // Set timer for 30 sec, method takes args in milliseconds.
    timer.schedule(task, 30 * 1000);
    boolean timedoutResponse = true;// Default is timed out response.

    try {
        /* for testing of timer functionality.
        try {
         Thread.sleep(10000);
        } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }*/

        Properties prop = propServices.searchForProperties(start, limit, sort, sort_direction, filer, geoParam,
                returnOpenHouseData);
        prop.setElapsedTime(BigInteger.valueOf(System.currentTimeMillis() - reqInputArrivalTime));

        if (this.getOutputType().equalsIgnoreCase("json")) {
            returnObj = getJSONReturnObj(prop);
        } else {
            returnObj = prop;
        }
    } catch (LargeResultSetException e) {
        Errors errors = new Errors();
        com.irets.generated.Error error = new com.irets.generated.Error();
        error.setCode(e.getErrorCode());
        error.setDescription(e.getMessage());
        errors.getError().add(error);
        errors.setTotalcount(BigInteger.valueOf(e.getTotalCount()));
        errors.setElapsedtime(BigInteger.valueOf(System.currentTimeMillis() - reqInputArrivalTime));
        returnObj = errors;
        System.out.println(e.getMessage());
    } finally {
        if (task.cancel()) {
            timedoutResponse = false;// No timeout, send normal response.             
        }
    }

    System.out.println("time in database call:" + (new Date().getTime() - startTime) + " msecs");

    //startTime = new Date().getTime();
    //GSONHelper.serializeToJSON(prop, response.getOutputStream());
    if (!timedoutResponse) {
        if (this.getOutputType().equalsIgnoreCase("json")) {
            response.setContentType("application/json");
            JacksonJSONHelper.serializeToJSON(returnObj, response.getOutputStream(), response);
        } else {
            response.setContentType("text/xml");
            JAXBHelper.serializeToXML(returnObj, response.getOutputStream());
        }
    }
    //System.out.println("time in making output:"+(new Date().getTime()-startTime)+" msecs");
    System.out.println("Done!!!! elapsed time: " + (System.currentTimeMillis() - reqInputArrivalTime));
}

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

/**
 * Parses the ordering @See Order By Clause.
 * /*www .  ja va  2 s .  c  o  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.GenerateSitePDF.java

/**
 *
 * @return//from   w w w.jav  a2s.  c  om
 */
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:sdf_manager.ExporterSiteHTML.java

/**
 *
 * @return/*from  www  .j av a  2 s .co 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();
    }

}