Example usage for java.sql Connection isClosed

List of usage examples for java.sql Connection isClosed

Introduction

In this page you can find the example usage for java.sql Connection isClosed.

Prototype

boolean isClosed() throws SQLException;

Source Link

Document

Retrieves whether this Connection object has been closed.

Usage

From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java

public int update(final boolean autoCommit, final boolean failOnError, final boolean failOnDrops,
        final boolean failOnSequenceCreate, final int commitRate, final ISqlResultsListener resultsListener,
        final ISqlStatementSource source) {
    return execute(new IConnectionCallback<Integer>() {
        @SuppressWarnings("resource")
        public Integer execute(Connection con) throws SQLException {
            int totalUpdateCount = 0;
            boolean oldAutoCommitSetting = con.getAutoCommit();
            Statement stmt = null;
            try {
                con.setAutoCommit(autoCommit);
                stmt = con.createStatement();
                int statementCount = 0;
                for (String statement = source.readSqlStatement(); statement != null; statement = source
                        .readSqlStatement()) {
                    logSql(statement, null);
                    try {
                        boolean hasResults = stmt.execute(statement);
                        int updateCount = stmt.getUpdateCount();
                        totalUpdateCount += updateCount;
                        int rowsRetrieved = 0;
                        if (hasResults) {
                            ResultSet rs = null;
                            try {
                                rs = stmt.getResultSet();
                                while (rs.next()) {
                                    rowsRetrieved++;
                                }/*from   w  w w.  j a v a  2s  .c o  m*/
                            } finally {
                                close(rs);
                            }
                        }
                        if (resultsListener != null) {
                            resultsListener.sqlApplied(statement, updateCount, rowsRetrieved, statementCount);
                        }
                        statementCount++;
                        if (statementCount % commitRate == 0 && !autoCommit) {
                            con.commit();
                        }
                    } catch (SQLException ex) {
                        boolean isDrop = statement.toLowerCase().trim().startsWith("drop");
                        boolean isSequenceCreate = statement.toLowerCase().trim().startsWith("create sequence");
                        if (resultsListener != null) {
                            resultsListener.sqlErrored(statement, translate(statement, ex), statementCount,
                                    isDrop, isSequenceCreate);
                        }

                        if ((isDrop && !failOnDrops) || (isSequenceCreate && !failOnSequenceCreate)) {
                            log.debug("{}.  Failed to execute: {}", ex.getMessage(), statement);
                        } else {
                            log.warn("{}.  Failed to execute: {}", ex.getMessage(), statement);
                            if (failOnError) {
                                throw ex;
                            }
                        }

                    }
                }

                if (!autoCommit) {
                    con.commit();
                }
                return totalUpdateCount;
            } catch (SQLException ex) {
                if (!autoCommit) {
                    con.rollback();
                }
                throw ex;
            } finally {
                close(stmt);
                if (!con.isClosed()) {
                    con.setAutoCommit(oldAutoCommitSetting);
                }
            }
        }
    });
}

From source file:com.belle.yitiansystem.merchant.service.impl.MerchantsService.java

/**
 * ?//from   ww w.  ja v  a  2 s.c  om
 * 
 * @param conn
 * @param pstmt
 * @param rs
 */
private void close(Connection conn, Statement pstmt, ResultSet rs) {
    try {
        if (rs != null) {
            rs.close();
            rs = null;
        }

        if (pstmt != null) {
            pstmt.close();
            pstmt = null;
        }
        if (conn != null) {
            if (!conn.isClosed()) {
                conn.close();
            }
            conn = null;
        }
    } catch (Exception e) {
        // TODO: handle exception
        logger.error("?!", e);
    }
}

From source file:cz.incad.kramerius.processes.impl.DatabaseProcessManager.java

@Override
public void deleteBatchLongRunningProcess(LRProcess longRunningProcess) {

    Connection connection = null;
    try {/* ww w  .ja  v a2s  .  c om*/
        connection = connectionProvider.get();
        if (connection == null)
            throw new NotReadyException("connection not ready");

        if (longRunningProcess.getProcessState().equals(States.RUNNING)) {
            throw new ProcessManagerException(
                    "cannot delete process with state '" + longRunningProcess.getProcessState() + "'");
        }

        List<JDBCCommand> commands = new ArrayList<JDBCCommand>();

        final String token = longRunningProcess.getGroupToken();
        final List<LRProcess> childSubprecesses = getLongRunningProcessesByGroupToken(token);

        final int id = ProcessDatabaseUtils.getProcessId(longRunningProcess, connection);
        commands.add(new JDBCCommand() {

            @Override
            public Object executeJDBCCommand(Connection con) throws SQLException {
                PreparedStatement prepareStatement = con
                        .prepareStatement("delete from PROCESS_2_TOKEN where process_id = ?");
                prepareStatement.setInt(1, id);
                return prepareStatement.executeUpdate();
            }
        });

        for (final LRProcess lrProcess : childSubprecesses) {
            if (lrProcess.getAuthToken() != null) {
                commands.add(new JDBCCommand() {

                    @Override
                    public Object executeJDBCCommand(Connection con) throws SQLException {
                        PreparedStatement prepareStatement = con
                                .prepareStatement("delete from PROCESS_2_TOKEN where auth_token = ?");
                        prepareStatement.setString(1, lrProcess.getAuthToken());
                        return prepareStatement.executeUpdate();
                    }
                });

            }
        }

        commands.add(new JDBCCommand() {

            @Override
            public Object executeJDBCCommand(Connection con) throws SQLException {
                PreparedStatement prepareStatement = con
                        .prepareStatement("delete from PROCESS_2_TOKEN where auth_token = ?");
                prepareStatement.setString(1, token);
                return prepareStatement.executeUpdate();
            }
        });

        commands.add(new JDBCCommand() {

            @Override
            public Object executeJDBCCommand(Connection con) throws SQLException {
                PreparedStatement prepareStatement = con
                        .prepareStatement("delete from PROCESSES where token = ?");
                prepareStatement.setString(1, token);
                return prepareStatement.executeUpdate();
            }
        });

        JDBCTransactionTemplate.Callbacks callbacks = new JDBCTransactionTemplate.Callbacks() {

            @Override
            public void rollbacked() {
                // do nothing
            }

            @Override
            public void commited() {
                for (int i = 0; i < childSubprecesses.size(); i++) {
                    LRProcess child = childSubprecesses.get(i);
                    File chWDir = child.processWorkingDirectory();
                    try {
                        FileUtils.deleteDirectory(chWDir);
                    } catch (IOException e) {
                        LOGGER.log(Level.SEVERE, e.getMessage(), e);
                    }
                }
            }
        };

        new JDBCTransactionTemplate(connection, true).updateWithTransaction(callbacks,
                (JDBCCommand[]) commands.toArray(new JDBCCommand[commands.size()]));
    } catch (SQLException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        throw new ProcessManagerException(e);
    } finally {
        try {
            if (connection != null && (!connection.isClosed())) {
                DatabaseUtils.tryClose(connection);
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ProcessManagerException(e);
        }
    }
}

From source file:org.rti.zcore.dar.struts.action.HomeAction.java

/**
 * Build the ZEPRS home page, incorporating the search interface/results
 * if it's a report-only user, send to reports
 * otherwise, send to permissions page.//from w  ww. j  a  v a 2s .  c o  m
 *
 * @param mapping  The ActionMapping used to select this instance
 * @param form     The optional ActionForm bean for this request (if any)
 * @param request  The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return Action to forward to
 * @throws Exception if an input/output error or servlet exception occurs
 */
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession();
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    Integer maxRows = 0;
    Integer offset = 0;
    Integer prevRows = 0;
    Integer nextRows = 0;
    Connection conn = null;
    try {
        conn = DatabaseUtils.getZEPRSConnection(username);
        if (request.isUserInRole("VIEW_INDIVIDUAL_PATIENT_RECORDS")
                || request.isUserInRole("CREATE_NEW_PATIENTS_AND_SEARCH")) {
            String searchStringRequest = request.getParameter("search_string");
            String firstSurname = request.getParameter("first_surname"); // used in a-z search
            String labour = request.getParameter("labour"); // used in a-z search
            String searchType = "keyword";
            String searchString = "";
            if (searchStringRequest == null) {
                searchString = "";
            } else {
                searchString = searchStringRequest.trim().toLowerCase();
            }
            if (firstSurname != null && !firstSurname.equals("")) {
                searchType = "firstSurname";
                searchString = firstSurname;
                request.setAttribute("firstSurname", firstSurname);
            }
            request.setAttribute("searchString", searchString);
            String patientSiteId = SessionUtil.getInstance(session).getClientSettings().getSiteId().toString();
            request.setAttribute("patientSiteId", patientSiteId);

            String site = request.getParameter("site");
            request.setAttribute("site", site);
            if (site != null) {
                if (site.equals("")) {
                    site = patientSiteId;
                }
            }
            if (request.getParameter("maxRows") != null) {
                maxRows = Integer.decode(request.getParameter("maxRows"));
            } else if (request.getAttribute("maxRows") != null) {
                maxRows = Integer.decode(request.getAttribute("maxRows").toString());
            } else {
                maxRows = 20;
            }
            if (request.getParameter("offset") != null) {
                offset = Integer.decode(request.getParameter("offset"));
            } else if (request.getAttribute("offset") != null) {
                offset = Integer.decode(request.getAttribute("offset").toString());
            }
            if (request.getParameter("prevRows") != null) {
                prevRows = Integer.decode(request.getParameter("prevRows"));
                offset = prevRows;
            } else if (request.getAttribute("prevRows") != null) {
                prevRows = Integer.decode(request.getAttribute("prevRows").toString());
                offset = prevRows;
            }
            if (request.getParameter("nextRows") != null) {
                nextRows = Integer.decode(request.getParameter("nextRows"));
            } else if (request.getAttribute("nextRows") != null) {
                nextRows = Integer.decode(request.getAttribute("nextRows").toString());
            }
            if (site == null) {
                site = patientSiteId;
            }
            List results = null;
            results = PatientSearchDAO.getResults(conn, site, searchString, offset, maxRows, searchType, 0,
                    username);
            request.setAttribute("results", results);

            request.setAttribute("maxRows", maxRows);
            nextRows = offset + maxRows;
            if (results.size() < maxRows) {
                if (offset == 0) {
                    request.setAttribute("noNavigationWidget", "1");
                }
            } else {
                request.setAttribute("offset", nextRows);
            }

            if (offset - maxRows >= 0) {
                prevRows = offset - maxRows;
                request.setAttribute("prevRows", prevRows);
            }
            request.setAttribute("nextRows", nextRows);
            SessionUtil.getInstance(session).setSessionPatient(null);

            List sites = null;
            sites = DynaSiteObjects.getClinics();//
            request.setAttribute("sites", sites);

            if (SessionUtil.getInstance(request.getSession()).isClientConfigured()) {
                String sitename = SessionUtil.getInstance(session).getClientSettings().getSite().getName();
                request.setAttribute("sitename", sitename);
            } else {
                request.setAttribute("sitename", "Configure PC: ");
            }
            String fullname = null;
            try {
                fullname = SessionUtil.getInstance(session).getFullname();
            } catch (SessionUtil.AttributeNotFoundException e) {
                // ok
            }
            //List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn);
            //List<Task> stockAlertList = PatientRecordUtils.getStockAlerts();
            List<Task> stockAlertList = null;
            if (DynaSiteObjects.getStatusMap().get("stockAlertList") != null) {
                stockAlertList = (List<Task>) DynaSiteObjects.getStatusMap().get("stockAlertList");
            }
            request.setAttribute("activeProblems", stockAlertList);
            request.setAttribute("fullname", fullname);
            if (conn != null && !conn.isClosed()) {
                conn.close();
                conn = null;
            }
            return mapping.findForward("success");
        } else if (request.isUserInRole("VIEW_SELECTED_REPORTS_AND_VIEW_STATISTICAL_SUMMARIES")) {
            if (conn != null && !conn.isClosed()) {
                conn.close();
                conn = null;
            }
            return mapping.findForward("reports");
        } else if (request.isUserInRole("CREATE_MEDICAL_STAFF_IDS_AND_PASSWORDS_FOR_MEDICAL_STAFF")) {
            if (conn != null && !conn.isClosed()) {
                conn.close();
                conn = null;
            }

            // Create user accounts
            ActionForward fwd = mapping.findForward("admin/records/list");
            String path = fwd.getPath();
            path += "?formId=";
            path += "170";
            return new ActionForward(path);
        }
    } catch (ServletException e) {
        log.error(e);
        request.setAttribute("exception",
                "There is an error generating the Search Results for the Home page. Please stand by - the system may be undergoing maintenance.");
        return mapping.findForward("error");
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
            conn = null;
        }

    }

    return mapping.findForward("noPermissions");
}

From source file:org.lockss.subscription.SubscriptionManager.java

/**
 * Adds subscriptions to the system.//from  w  ww.  java  2  s  . com
 * 
 * @param subscriptions
 *          A Collection<Subscription> with the subscriptions to be added.
 * @param status
 *          A SubscriptionOperationStatus where to return the status of the
 *          operation.
 */
public void addSubscriptions(Collection<Subscription> subscriptions, SubscriptionOperationStatus status) {
    final String DEBUG_HEADER = "addSubscriptions(): ";
    if (log.isDebug2()) {
        if (subscriptions != null) {
            log.debug2(DEBUG_HEADER + "subscriptions.size() = " + subscriptions.size());
        } else {
            log.debug2(DEBUG_HEADER + "subscriptions is null");
        }
    }

    // Force a re-calculation of the relative weights of the repositories.
    repositories = null;

    Connection conn = null;

    try {
        // Get a connection to the database.
        conn = dbManager.getConnection();
    } catch (DbException dbe) {
        log.error(CANNOT_CONNECT_TO_DB_ERROR_MESSAGE, dbe);

        for (Subscription subscription : subscriptions) {
            status.addStatusEntry(subscription.getPublication().getPublicationName(), false, dbe.getMessage(),
                    null);
        }

        if (log.isDebug2())
            log.debug(DEBUG_HEADER + "Done.");
        return;
    }

    BatchAuStatus bas;

    try {
        // Loop through all the subscriptions.
        for (Subscription subscription : subscriptions) {
            if (log.isDebug3())
                log.debug3(DEBUG_HEADER + "subscription = " + subscription);

            try {
                // Persist the subscription in the database.
                persistSubscription(conn, subscription);

                List<BibliographicPeriod> subscribedRanges = subscription.getSubscribedRanges();
                if (log.isDebug3())
                    log.debug3(DEBUG_HEADER + "subscribedRanges = " + subscribedRanges);

                // Check whether the added subscription may imply the configuration of
                // some archival unit.
                if (subscribedRanges != null && subscribedRanges.size() > 0
                        && (subscribedRanges.size() > 1 || !subscribedRanges.iterator().next().isEmpty())) {
                    // Yes: Configure the archival units that correspond to this
                    // subscription.
                    bas = configureAus(conn, subscription);
                } else {
                    bas = null;
                }

                DbManager.commitOrRollback(conn, log);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), bas);
            } catch (IllegalStateException ise) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot add subscription " + subscription, ise);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        ise.getMessage(), null);
            } catch (IOException ioe) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot add subscription " + subscription, ioe);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        ioe.getMessage(), null);
            } catch (DbException dbe) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot add subscription " + subscription, dbe);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        dbe.getMessage(), null);
            } catch (SubscriptionException se) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot add subscription " + subscription, se);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        se.getMessage(), null);
            }
        }
    } finally {
        DbManager.safeRollbackAndClose(conn);
    }

    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "Done.");
}

From source file:org.lockss.subscription.SubscriptionManager.java

/**
 * Updates existing subscriptions.//from   www  .ja  va2 s . co m
 * 
 * @param subscriptions
 *          A Collection<Subscription> with the subscriptions to be updated.
 * @param status
 *          A SubscriptionOperationStatus where to return the status of the
 *          operation.
 */
public void updateSubscriptions(Collection<Subscription> subscriptions, SubscriptionOperationStatus status) {
    final String DEBUG_HEADER = "updateSubscriptions(): ";
    if (log.isDebug2()) {
        if (subscriptions != null) {
            log.debug2(DEBUG_HEADER + "subscriptions.size() = " + subscriptions.size());
        } else {
            log.debug2(DEBUG_HEADER + "subscriptions is null");
        }
    }

    // Force a re-calculation of the relative weights of the repositories.
    repositories = null;

    Connection conn = null;

    try {
        // Get a connection to the database.
        conn = dbManager.getConnection();
    } catch (DbException dbe) {
        log.error(CANNOT_CONNECT_TO_DB_ERROR_MESSAGE, dbe);

        for (Subscription subscription : subscriptions) {
            status.addStatusEntry(subscription.getPublication().getPublicationName(), false, dbe.getMessage(),
                    null);
        }

        if (log.isDebug2())
            log.debug(DEBUG_HEADER + "Done.");
        return;
    }

    BatchAuStatus bas;

    try {
        // Loop through all the subscriptions.
        for (Subscription subscription : subscriptions) {
            if (log.isDebug3())
                log.debug3(DEBUG_HEADER + "subscription = " + subscription);

            try {
                // Update the subscription in the database.
                updateSubscription(conn, subscription);

                List<BibliographicPeriod> subscribedRanges = subscription.getSubscribedRanges();
                if (log.isDebug3())
                    log.debug3(DEBUG_HEADER + "subscribedRanges = " + subscribedRanges);

                // Check whether the updated subscription may imply the configuration
                // of some archival unit.
                if (subscribedRanges != null && subscribedRanges.size() > 0
                        && (subscribedRanges.size() > 1 || !subscribedRanges.iterator().next().isEmpty())) {
                    // Yes: Configure the archival units that correspond to this
                    // subscription.
                    bas = configureAus(conn, subscription);
                } else {
                    bas = null;
                }

                DbManager.commitOrRollback(conn, log);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), bas);
            } catch (IllegalStateException ise) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot update subscription " + subscription, ise);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        ise.getMessage(), null);
            } catch (IOException ioe) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot update subscription " + subscription, ioe);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        ioe.getMessage(), null);
            } catch (DbException dbe) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot update subscription " + subscription, dbe);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        dbe.getMessage(), null);
            } catch (SubscriptionException se) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot update subscription " + subscription, se);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        se.getMessage(), null);
            }
        }
    } finally {
        DbManager.safeRollbackAndClose(conn);
    }

    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "Done.");
}

From source file:org.rti.zcore.dar.struts.action.FormAction.java

/**
 * Check formId to see what is the next form to be served.
 *
 * @param request/* w w  w  . j  ava  2 s .  co m*/
 * @param mapping
 * @param patientId
 * @param eventUuid
 * @param dynaForm
 * @param session
 * @param formId
 * @param vo Useful when you need to pass the encounterId in the url parameters
 * @return the next page/form
 */
private ActionForward createForward(HttpServletRequest request, ActionMapping mapping, Long patientId,
        String eventUuid, DynaValidatorForm dynaForm, HttpSession session, int formId, EncounterData vo) {
    BaseSessionSubject sessionPatient = null;
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    String formName = mapping.getParameter().trim();
    Connection conn = null;
    Form nextForm = new Form();

    Integer maxRows = 0;
    if (request.getParameter("maxRows") != null) {
        maxRows = Integer.decode(request.getParameter("maxRows"));
    } else if (request.getAttribute("maxRows") != null) {
        maxRows = Integer.decode(request.getAttribute("maxRows").toString());
    } else {
        switch (formId) {
        case 128:
            maxRows = 0;
            break;
        case 129:
            maxRows = 0;
            break;
        case 130:
            maxRows = 0;
            break;
        case 131:
            maxRows = 0;
            break;
        case 181:
            maxRows = 0;
            break;

        default:
            maxRows = 20;
            break;
        }
    }

    try {
        conn = DatabaseUtils.getZEPRSConnection(username);
        try {
            sessionPatient = SessionUtil.getInstance(session).getSessionPatient();
        } catch (SessionUtil.AttributeNotFoundException e) {
            //log.error("Unable to get TimsSessionSubject");
        }

        Form form = (Form) DynaSiteObjects.getForms().get(Long.valueOf(formId));
        Long formTypeId = form.getFormTypeId();

        // part of reload prevention scheme:
        resetToken(request);
        dynaForm.reset(mapping, request);
        StrutsUtils.removeFormBean(mapping, request);

        ActionForward forwardForm = null;
        String forwardString = null;
        switch (formId) {
        case 1: // Patient Registration
            forwardString = "/ArtRegimen/new.do?patientId=" + patientId.toString();
            break;
        case 137: // ART Regimen
            forwardString = "/PatientItem/new.do?patientId=" + patientId.toString();
            break;
        case 132: // Dispensary
            //forwardString = "/patientTask.do?flowId=" + flowId.toString();
            forwardString = "/Appointment/new.do?patientId=" + patientId.toString();
            //forwardString = "/chart.do?patientId=" + patientId.toString() + "&formId=" + formId;
            break;
        /*case 136:
          forwardString = "/chart.do?patientId=" + patientId.toString() + "&formId=" + formId;
           break;*/
        case 136: // PatientCondition
            forwardString = "/PatientCondition/new.do?patientId=" + patientId.toString();
            break;
        case 179: // Appt
            if (Constants.APPOINTMENT_COUNT_THRESHOLD != null) {
                Appointment appt = (Appointment) vo;
                Date apptDate = appt.getAppointment_date();
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
                        org.rti.zcore.Constants.DATE_FORMAT_SHORT);
                sdf.setTimeZone(TimeZone.getDefault());
                String apptDateStr = sdf.format(appt.getAppointment_date().getTime());

                ResultSet rs = null;
                Integer countAppts = 0;
                String warningMessage = "";
                try {
                    String sql = "SELECT COUNT(encounter.id) AS countAppts " + "FROM encounter, appointment "
                            + "WHERE appointment.id=encounter.id " + "AND appointment_date = ? ";
                    PreparedStatement ps = conn.prepareStatement(sql);
                    ps.setDate(1, apptDate);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        countAppts = rs.getInt("countAppts");
                    }
                } catch (Exception ex) {
                    log.error(ex);
                }
                Integer apptCountThreshold = Integer.valueOf(Constants.APPOINTMENT_COUNT_THRESHOLD);
                if (countAppts != null && countAppts > 0) {
                    Integer warningThreshold = apptCountThreshold - 10;
                    if ((countAppts >= warningThreshold) && (countAppts < apptCountThreshold)) {
                        warningMessage = "Warning: Approaching Threshold of " + apptCountThreshold
                                + " Appointments";
                    } else if (countAppts >= apptCountThreshold) {
                        warningMessage = "Warning: Passed Threshold of " + apptCountThreshold
                                + " Appointments.";
                    }
                    forwardString = "/Appointment/new.do?patientId=" + patientId.toString() + "&warningMessage="
                            + warningMessage + "&countAppts=" + countAppts + "&apptDate=" + apptDateStr;
                } else {
                    forwardString = "/Appointment/new.do?patientId=" + patientId.toString() + "&countAppts="
                            + countAppts + "&apptDate=" + apptDateStr;
                }
            } else {
                forwardString = "/Appointment/new.do?patientId=" + patientId.toString();
            }
            break;
        case 180: // Appt
            forwardString = "/PatientStatus_changes/new.do?patientId=" + patientId.toString();
            break;

        default:
            switch (formTypeId.intValue()) {
            case 5: // admin
                forwardString = "/admin/records/list.do?formId=" + formId + "&maxRows=" + maxRows;
                break;
            case 7: // charts
                forwardString = "/chart.do?id=" + formId;
                break;
            case 8: // lists
                forwardString = "/recordList.do?formId=" + formId + "&patientId=" + patientId.toString();
                break;
            default:
                if (sessionPatient != null) {
                    Long flowId = sessionPatient.getCurrentFlowId();
                    forwardString = "/patientTask.do?flowId=" + flowId.toString();
                } else {
                    forwardString = "/home.do";
                }
                break;
            }
            break;
        }
        forwardForm = new ActionForward(forwardString);
        forwardForm.setRedirect(true);
        return forwardForm;
    } catch (ServletException e) {
        log.error(e);
    } finally {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException e) {
            log.error(e);
        }
    }

    return (new ActionForward(mapping.getInput()));
}

From source file:sce.LoggingJobHistoryPluginCustom.java

public void logToDatabase(Object args[], String message, boolean updateStatus, String progress)
        throws SQLException {
    Connection conn = null;
    PreparedStatement preparedStatement = null;
    PreparedStatement preparedStatementStatusUpdate = null;
    PreparedStatement preparedStatementStatusInsert = null;
    Statement stmt = null; //statement for opening TRANSACTION
    try {//from ww  w  . j  a v a2  s . com
        conn = dataSource.getConnection();
        stmt = conn.createStatement();
        stmt.executeQuery("START TRANSACTION"); //START TRANSACTION
        // conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);

        //if progress value is not null, then include it in the insert/update query
        if (progress != null) {
            preparedStatement = conn.prepareStatement(
                    "INSERT INTO quartz.QRTZ_LOGS (FIRE_INSTANCE_ID, JOB_NAME, JOB_GROUP, JOB_DATA, DATE, TRIGGER_NAME, TRIGGER_GROUP, PREV_FIRE_TIME, NEXT_FIRE_TIME, REFIRE_COUNT, RESULT, SCHEDULER_INSTANCE_ID, SCHEDULER_NAME, IP_ADDRESS, STATUS, LOGGER, LEVEL, MESSAGE, PROGRESS) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            preparedStatementStatusUpdate = conn.prepareStatement(
                    "UPDATE quartz.QRTZ_STATUS SET JOB_NAME = ?, JOB_GROUP = ?, JOB_DATA = ?, DATE = ?, TRIGGER_NAME = ?, TRIGGER_GROUP = ?, PREV_FIRE_TIME = ?, NEXT_FIRE_TIME = ?, REFIRE_COUNT = ?, RESULT = ?, SCHEDULER_INSTANCE_ID = ?, SCHEDULER_NAME = ?, IP_ADDRESS = ?, STATUS = ?, LOGGER = ?, LEVEL = ?, MESSAGE = ?, PROGRESS = ? WHERE FIRE_INSTANCE_ID = ?");
            preparedStatementStatusInsert = conn.prepareStatement(
                    "INSERT INTO quartz.QRTZ_STATUS (FIRE_INSTANCE_ID, JOB_NAME, JOB_GROUP, JOB_DATA, DATE, TRIGGER_NAME, TRIGGER_GROUP, PREV_FIRE_TIME, NEXT_FIRE_TIME, REFIRE_COUNT, RESULT, SCHEDULER_INSTANCE_ID, SCHEDULER_NAME, IP_ADDRESS, STATUS, LOGGER, LEVEL, MESSAGE, PROGRESS) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE DATE = values(DATE), JOB_NAME = values(JOB_NAME), JOB_GROUP = values(JOB_GROUP), JOB_DATA = values(JOB_DATA), TRIGGER_NAME = values(TRIGGER_NAME), TRIGGER_GROUP = values(TRIGGER_GROUP), PREV_FIRE_TIME = values(PREV_FIRE_TIME), NEXT_FIRE_TIME = values(NEXT_FIRE_TIME), REFIRE_COUNT = values(REFIRE_COUNT), RESULT = values(RESULT), SCHEDULER_INSTANCE_ID = values(SCHEDULER_INSTANCE_ID), SCHEDULER_NAME = values(SCHEDULER_NAME), IP_ADDRESS = values(IP_ADDRESS), STATUS = values(STATUS), LOGGER = values(LOGGER), LEVEL = values(LEVEL), MESSAGE = values(MESSAGE), PROGRESS = values(PROGRESS)");
        } else {
            preparedStatement = conn.prepareStatement(
                    "INSERT INTO quartz.QRTZ_LOGS (FIRE_INSTANCE_ID, JOB_NAME, JOB_GROUP, JOB_DATA, DATE, TRIGGER_NAME, TRIGGER_GROUP, PREV_FIRE_TIME, NEXT_FIRE_TIME, REFIRE_COUNT, RESULT, SCHEDULER_INSTANCE_ID, SCHEDULER_NAME, IP_ADDRESS, STATUS, LOGGER, LEVEL, MESSAGE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            preparedStatementStatusUpdate = conn.prepareStatement(
                    "UPDATE quartz.QRTZ_STATUS SET JOB_NAME = ?, JOB_GROUP = ?, JOB_DATA = ?, DATE = ?, TRIGGER_NAME = ?, TRIGGER_GROUP = ?, PREV_FIRE_TIME = ?, NEXT_FIRE_TIME = ?, REFIRE_COUNT = ?, RESULT = ?, SCHEDULER_INSTANCE_ID = ?, SCHEDULER_NAME = ?, IP_ADDRESS = ?, STATUS = ?, LOGGER = ?, LEVEL = ?, MESSAGE = ? WHERE FIRE_INSTANCE_ID = ?");
            preparedStatementStatusInsert = conn.prepareStatement(
                    "INSERT INTO quartz.QRTZ_STATUS (FIRE_INSTANCE_ID, JOB_NAME, JOB_GROUP, JOB_DATA, DATE, TRIGGER_NAME, TRIGGER_GROUP, PREV_FIRE_TIME, NEXT_FIRE_TIME, REFIRE_COUNT, RESULT, SCHEDULER_INSTANCE_ID, SCHEDULER_NAME, IP_ADDRESS, STATUS, LOGGER, LEVEL, MESSAGE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE DATE = values(DATE), JOB_NAME = values(JOB_NAME), JOB_GROUP = values(JOB_GROUP), JOB_DATA = values(JOB_DATA), TRIGGER_NAME = values(TRIGGER_NAME), TRIGGER_GROUP = values(TRIGGER_GROUP), PREV_FIRE_TIME = values(PREV_FIRE_TIME), NEXT_FIRE_TIME = values(NEXT_FIRE_TIME), REFIRE_COUNT = values(REFIRE_COUNT), RESULT = values(RESULT), SCHEDULER_INSTANCE_ID = values(SCHEDULER_INSTANCE_ID), SCHEDULER_NAME = values(SCHEDULER_NAME), IP_ADDRESS = values(IP_ADDRESS), STATUS = values(STATUS), LOGGER = values(LOGGER), LEVEL = values(LEVEL), MESSAGE = values(MESSAGE)");
        }
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof String) {
                preparedStatement.setString(i + 1, (String) args[i]);
                preparedStatementStatusInsert.setString(i + 1, (String) args[i]);
            } else if (args[i] instanceof Date) {
                preparedStatement.setTimestamp(i + 1, new java.sql.Timestamp(((Date) args[i]).getTime()));
                preparedStatementStatusInsert.setTimestamp(i + 1,
                        new java.sql.Timestamp(((Date) args[i]).getTime()));
            }
            //skip the first args element (FIRE_INSTANCE_ID) for the preparedStatementStatusUpdate, to be set below
            if (i + 1 < args.length && args[i + 1] instanceof String) {
                preparedStatementStatusUpdate.setString(i + 1, (String) args[i + 1]);
            } else if (i + 1 < args.length && args[i + 1] instanceof Date) {
                preparedStatementStatusUpdate.setTimestamp(i + 1,
                        new java.sql.Timestamp(((Date) args[i + 1]).getTime()));
            }
        }
        preparedStatementStatusUpdate.setString(args.length, message);
        if (progress != null) {
            preparedStatementStatusUpdate.setString(args.length + 1, progress);
            preparedStatementStatusUpdate.setString(args.length + 2, (String) args[0]); //SET "WHERE FIRE_INSTANCE_ID = ?" IN THE preparedStatementStatusUpdate

            preparedStatement.setString(args.length + 1, message);
            preparedStatement.setString(args.length + 2, progress);

            preparedStatementStatusInsert.setString(args.length + 1, message);
            preparedStatementStatusInsert.setString(args.length + 2, progress);
        } else {
            preparedStatementStatusUpdate.setString(args.length + 1, (String) args[0]); //SET "WHERE FIRE_INSTANCE_ID = ?" IN THE preparedStatementStatusUpdate
            preparedStatement.setString(args.length + 1, message);
            preparedStatementStatusInsert.setString(args.length + 1, message);
        }

        preparedStatement.executeUpdate();
        if (updateStatus) {
            int rows = preparedStatementStatusUpdate.executeUpdate(); //UPDATE
            //IF UPDATE ON QRTZ_STATUS RETURNS 0 ROWS THEN INSERT
            if (rows == 0) {
                preparedStatementStatusInsert.executeUpdate(); //INSERT
            }
        }
        stmt.executeQuery("COMMIT"); //COMMIT TRANSACTION
    } catch (SQLException e) {
        if (stmt != null) {
            stmt.executeQuery("ROLLBACK"); //ROLLBACK TRANSACTION
        }
        e.printStackTrace();
        throw new SQLException(e);
    } finally {
        if (preparedStatement != null) {
            preparedStatement.close();
        }
        if (preparedStatementStatusUpdate != null) {
            preparedStatementStatusUpdate.close();
        }
        if (preparedStatementStatusInsert != null) {
            preparedStatementStatusInsert.close();
        }
        if (!conn.isClosed()) {
            conn.close();
        }
    }
}

From source file:sce.RESTAppMetricJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    Connection conn = null;
    try {//from w ww  .  ja  v a 2 s  . c  o m
        String url1 = prop.getProperty("kb_url");
        //required parameters #url
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String callUrl = jobDataMap.getString("#url"); // url to call when passing result data from SPARQL query
        if (callUrl == null) {
            throw new JobExecutionException("#url parameter must be not null");
        }
        String timeout = jobDataMap.getString("#timeout"); // timeout in ms to use when calling the #url
        if (timeout == null) {
            timeout = "5000";
        }

        //first SPARQL query to retrieve application related metrics and business configurations
        String url = url1 + "?query=" + URLEncoder.encode(getSPARQLQuery(), "UTF-8");
        URL u = new URL(url);
        final String usernamePassword = u.getUserInfo();
        if (usernamePassword != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(usernamePassword.split(":")[0],
                            usernamePassword.split(":")[1].toCharArray());
                }
            });
        }
        this.urlConnection = u.openConnection();
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json");
        HashMap<String, Object> res = new ObjectMapper().readValue(urlConnection.getInputStream(),
                HashMap.class);
        HashMap<String, Object> r = (HashMap<String, Object>) res.get("results");
        ArrayList<Object> list = (ArrayList<Object>) r.get("bindings");
        ArrayList<String[]> lst = new ArrayList<>();
        for (Object obj : list) {
            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value");
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value");
            lst.add(new String[] { mn, bc });
        }

        //second SPARQL query to retrieve alerts for SLA
        url = url1 + "?query=" + URLEncoder.encode(getValuesForMetrics(lst), "UTF-8");
        u = new URL(url);
        //java.io.FileWriter fstream = new java.io.FileWriter("/var/www/html/sce/log.txt", false);
        //java.io.BufferedWriter out = new java.io.BufferedWriter(fstream);
        //out.write(getAlertsForSLA(lst, slaTimestamp));
        //out.close();
        this.urlConnection = u.openConnection();
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json");

        //format the result
        HashMap<String, Object> alerts = new ObjectMapper().readValue(urlConnection.getInputStream(),
                HashMap.class);
        HashMap<String, Object> r1 = (HashMap<String, Object>) alerts.get("results");
        ArrayList<Object> list1 = (ArrayList<Object>) r1.get("bindings");
        String result = "";

        //MYSQL CONNECTION
        conn = Main.getConnection();
        // conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); // use for transactions and at the end call conn.commit() conn.close()
        int counter = 0;

        //SET timestamp FOR MYSQL ROW
        Date dt = new java.util.Date();
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = sdf.format(dt);

        // JSON to be sent to the SM
        JSONArray jsonArray = new JSONArray();

        for (Object obj : list1) {
            //JSON to insert into database
            //JSONArray jsonArray = new JSONArray();
            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value"); //metric
            String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value"); //metric_name
            String mu = (String) ((HashMap<String, Object>) o.get("mu")).get("value"); //metric_unit
            String v = (String) ((HashMap<String, Object>) o.get("v")).get("value"); //value
            String mt = (String) ((HashMap<String, Object>) o.get("mt")).get("value"); //metric_timestamp
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value"); //business_configuration

            // add these metric value to the json array
            JSONObject object = new JSONObject();
            object.put("business_configuration", bc);
            object.put("metric", sm);
            object.put("metric_name", mn);
            object.put("metric_unit", mu);
            object.put("value", v);
            object.put("metric_timestamp", mt);
            jsonArray.add(object);

            //INSERT THE DATA INTO DATABASE
            PreparedStatement preparedStatement = conn.prepareStatement(
                    "INSERT INTO quartz.QRTZ_APP_METRICS (timestamp, metric, metric_name, metric_unit, value, metric_timestamp, business_configuration) VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE timestamp=?");
            preparedStatement.setString(1, timestamp); // date
            preparedStatement.setString(2, sm); // metric
            preparedStatement.setString(3, mn); // metric_name
            preparedStatement.setString(4, mu); // metric_unit
            preparedStatement.setString(5, v); // value
            preparedStatement.setString(6, mt); // metric_timestamp (e.g., 2014-12-01T16:14:00)
            preparedStatement.setString(7, bc); // business_configuration 
            preparedStatement.setString(8, timestamp); // date
            preparedStatement.executeUpdate();
            preparedStatement.close();

            result += "\nService Metric: " + sm + "\n";
            result += "\nMetric Name: " + mn + "\n";
            result += "\nMetric Unit: " + mu + "\n";
            result += "Timestamp: " + mt + "\n";
            result += "Business Configuration: " + bc + "\n";
            result += "Value" + (counter + 1) + ": " + v + "\n";
            result += "Call Url: " + callUrl + "\n";

            counter++;
        }

        // send the JSON to the CM
        URL tmp_u = new URL(callUrl);
        final String usr_pwd = tmp_u.getUserInfo();
        String usr = null;
        String pwd = null;
        if (usr_pwd != null) {
            usr = usr_pwd.split(":")[0];
            pwd = usr_pwd.split(":")[1];
        }
        sendPostRequest(jsonArray.toJSONString(), callUrl, usr, pwd, Integer.parseInt(timeout));

        //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener)
        context.setResult(result);

        if (jobDataMap.containsKey("#notificationEmail")) {
            sendEmail(context, jobDataMap.getString("#notificationEmail"));
        }
        jobChain(context);
    } catch (MalformedURLException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (IOException | SQLException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (!conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.zaproxy.zap.extension.callgraph.CallGraphFrame.java

/**
 * sets up the graph by retrieving the nodes and edges from the history table in the database
 *
 * @param urlPattern//  www.j a  v a2  s.  com
 * @throws SQLException
 */
private void setupGraph(Pattern urlPattern) throws SQLException {
    Connection conn = null;
    Statement st = null;
    ResultSet rs = null;
    Map<String, String> schemaAuthorityToColor = new HashMap<String, String>();
    // use some web safe colours. Currently, there are 24 colours.
    String[] colors = { "#FFFF00", "#FFCC00", "#FF9900", "#FF6600", "#FF3300", "#CCFF00", "#CCCC00", "#CC9900",
            "#CC6600", "#99FF00", "#999900", "#996600", "#CCFFCC", "#CCCCCC", "#99CCCC", "#9999CC", "#9966CC",
            "#66FFCC", "#6699CC", "#6666CC", "#33FFCC", "#33CCCC", "#3399CC", "#00FFCC" };
    int colorsUsed = 0;
    try {
        // Create a pattern for the specified

        // get a new connection to the database to query it, since the existing database classes
        // do not cater for
        // ad-hoc queries on the table
        /*
         * TODO Add-ons should NOT make their own connections to the db any more - the db layer is plugable
         * so could be implemented in a completely different way
         * TODO: how? There is currently no API to do this.
         */
        // Note: the db is a singleton instance, so do *not* close it!!
        Database db = Model.getSingleton().getDb();
        if (!(db instanceof ParosDatabase)) {
            throw new InvalidParameterException(db.getClass().getCanonicalName());
        }

        conn = ((ParosDatabaseServer) db.getDatabaseServer()).getNewConnection();

        // we begin adding stuff to the graph, so begin a "transaction" on it.
        // we will close this after we add all the vertexes and edges to the graph
        graph.getModel().beginUpdate();

        // prepare to add the vertices to the graph
        // this must include all URLs references as vertices, even if those URLs did not feature
        // in the history table in their own right

        // include entries of type 1 (proxied), 2 (spidered), 10 (Ajax spidered) from the
        // history
        st = conn.createStatement();
        rs = st.executeQuery(
                "select distinct URI from HISTORY where histtype in (1,2,10) union distinct select distinct  RIGHT(REGEXP_SUBSTRING (REQHEADER, 'Referer:.+') , LENGTH(REGEXP_SUBSTRING (REQHEADER, 'Referer:.+'))-LENGTH('Referer: ')) from HISTORY where REQHEADER like '%Referer%' and histtype in (1,2,10) order by 1");
        for (; rs.next();) {
            String url = rs.getString(1);

            // remove urls that do not match the pattern specified (all sites / one site)
            Matcher urlmatcher = urlPattern.matcher(url);
            if (urlmatcher.find()) {
                // addVertex(url , url);
                try {
                    URI uri = new URI(url, false);
                    String schemaAuthority = uri.getScheme() + "://" + uri.getAuthority();
                    String path = uri.getPathQuery();
                    if (path == null)
                        path = "/";
                    String color = schemaAuthorityToColor.get(schemaAuthority);
                    if (color == null) {
                        // not found already.. so assign this scheme and authority a color.
                        if (colorsUsed >= colors.length) {
                            throw new Exception("Too many scheme/authority combinations. Ne need more colours");
                        }
                        color = colors[colorsUsed++];
                        schemaAuthorityToColor.put(schemaAuthority, color);
                    }
                    addVertex(path, url, "fillColor=" + color);
                } catch (Exception e) {
                    log.error("Error graphing node for URL " + url, e);
                }
            } else {
                if (log.isDebugEnabled())
                    log.debug("URL " + url + " does not match the specified pattern " + urlPattern
                            + ", so not adding it as a vertex");
            }
        }
        // close the resultset and statement
        rs.close();
        st.close();

        // set up the edges in the graph
        st = conn.createStatement();
        rs = st.executeQuery(
                "select distinct RIGHT(REGEXP_SUBSTRING (REQHEADER, 'Referer:.+') , LENGTH(REGEXP_SUBSTRING (REQHEADER, 'Referer:.+'))-LENGTH('Referer: ')), URI from HISTORY where REQHEADER like '%Referer%' and histtype in (1,2,10) order by 2");

        mxGraphModel graphmodel = (mxGraphModel) graph.getModel();
        for (; rs.next();) {
            String predecessor = rs.getString(1);
            String url = rs.getString(2);

            // now trim back all urls from the base url
            // Matcher predecessorurlmatcher = urlpattern.matcher(predecessor);
            // if (predecessorurlmatcher.find()) {
            //   predecessor =  predecessorurlmatcher.group(1);
            //   }
            // Matcher urlmatcher = urlpattern.matcher(url);
            // if (urlmatcher.find()) {
            //   url =  urlmatcher.group(1);
            //   }

            // remove urls that do not match the pattern specified (all sites / one site)
            Matcher urlmatcher1 = urlPattern.matcher(predecessor);
            if (!urlmatcher1.find()) {
                if (log.isDebugEnabled())
                    log.debug("Predecessor URL " + predecessor + " does not match the specified pattern "
                            + urlPattern + ", so not adding it as a vertex");
                continue; // to the next iteration
            }
            Matcher urlmatcher2 = urlPattern.matcher(url);
            if (!urlmatcher2.find()) {
                if (log.isDebugEnabled())
                    log.debug("URL " + url + " does not match the specified pattern " + urlPattern
                            + ", so not adding it as a vertex");
                continue; // to the next iteration
            }

            // check that we have added the url as a vertex in its own right.. definitely should
            // have happened..
            mxCell predecessorVertex = (mxCell) graphmodel.getCell(predecessor);
            mxCell postdecessorVertex = (mxCell) graphmodel.getCell(url);
            if (predecessorVertex == null || postdecessorVertex == null) {
                log.warn("Could not find graph node for " + predecessor + " or for " + url + ". Ignoring it.");
                continue;
            }
            // add the edge (ie, add the dependency between 2 URLs)
            graph.insertEdge(parent, predecessorVertex.getId() + "-->" + postdecessorVertex.getId(), null,
                    predecessorVertex, postdecessorVertex);
        }

        // once all the vertices and edges are drawn, look for root nodes (nodes with no
        // incoming edges)
        // we will display the full URl for these, rather than just the path, to aid viewing the
        // graph
        Object[] vertices = graph.getChildVertices(graph.getDefaultParent());
        for (Object vertex : vertices) {
            Object[] incomingEdgesForVertex = graph.getIncomingEdges(vertex);
            if (incomingEdgesForVertex == null
                    || (incomingEdgesForVertex != null && incomingEdgesForVertex.length == 0)) {
                // it's a root node. Set it's value (displayed label) to the same as it's id
                // (the full URL)
                mxCell vertextCasted = (mxCell) vertex;
                vertextCasted.setValue(vertextCasted.getId());

                // now sort out the text metrics for the vertex, since the size of the displayed
                // text has been changed
                Dimension textsize = this.getTextDimension((String) vertextCasted.getValue(), this.fontmetrics);
                mxGeometry cellGeometry = vertextCasted.getGeometry();
                cellGeometry.setHeight(textsize.getHeight());
                cellGeometry.setWidth(textsize.getWidth());
                vertextCasted.setGeometry(cellGeometry);
            }
        }
    } catch (SQLException e) {
        log.error("Error trying to setup the graph", e);
        throw e;
    } finally {

        if (rs != null && !rs.isClosed())
            rs.close();
        if (st != null && !st.isClosed())
            st.close();
        if (conn != null && !conn.isClosed())
            conn.close();
        // mark the "transaction" on the graph as complete
        graph.getModel().endUpdate();
    }
}