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:edu.uga.cs.fluxbuster.db.PostgresDBInterface.java

/**
 * @see edu.uga.cs.fluxbuster.db.DBInterface#storeClusters(java.util.List, java.lang.String, java.util.Date)
 *///  w  ww. j a  va  2 s. c  om
@Override
public void storeClusters(List<DomainCluster> clusters, String sensorname, Date logdate) {

    String logDateTable = dateFormatTable.format(logdate);

    Connection con = null;
    PreparedStatement domainsInsertStmt = null;
    PreparedStatement domainsSelectStmt = null;
    PreparedStatement clustersInsertStmt = null;
    PreparedStatement resolvedIPSInsertStmt = null;
    PreparedStatement clusterResolvedIPSInsertStmt = null;
    PreparedStatement clusterFeatureVectorsInsertStmt = null;

    try {
        con = this.getConnection();
        domainsInsertStmt = con
                .prepareStatement("INSERT INTO domains_" + logDateTable + " VALUES(DEFAULT, ?, ?, ?)");
        domainsSelectStmt = con
                .prepareStatement("SELECT domain_id FROM domains_" + logDateTable + " WHERE domain_name = ?");
        clustersInsertStmt = con
                .prepareStatement("INSERT INTO clusters_" + logDateTable + " VALUES " + "(?, ?, ?, ?)");
        resolvedIPSInsertStmt = con
                .prepareStatement("INSERT INTO resolved_ips_" + logDateTable + " VALUES " + "( ?, ?, inet(?))");
        clusterResolvedIPSInsertStmt = con.prepareStatement(
                "INSERT INTO cluster_resolved_ips_" + logDateTable + " VALUES " + "( ?, ?, ?, inet(?))");
        clusterFeatureVectorsInsertStmt = con.prepareStatement("INSERT INTO cluster_feature_vectors_"
                + logDateTable + "(cluster_id, sensor_name, log_date, network_cardinality, ip_diversity, "
                + "number_of_domains, ttl_per_domain, ip_growth_ratio, queries_per_domain, avg_last_growth_ratio_single_entry, "
                + "avg_last_growth_ratio_entries, avg_last_growth_prefix_ratio_entries, last_growth_ratio_cluster,"
                + "last_growth_prefix_ratio_cluster) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        int clusterId = 1;
        for (DomainCluster cluster : clusters) {
            for (CandidateFluxDomain candidateDomain : cluster.getCandidateDomains()) {
                String domainName = filterChars(candidateDomain.getDomainName());
                String domainNameRev = DomainNameUtils.reverseDomainName(domainName);
                String secondLevelDomainName = DomainNameUtils.extractEffective2LD(domainName);
                String secondLevelDomainNameRev = null;
                if (secondLevelDomainName != null) {
                    secondLevelDomainNameRev = DomainNameUtils.reverseDomainName(secondLevelDomainName);
                } else {
                    secondLevelDomainNameRev = DomainNameUtils.reverseDomainName(domainName);
                }

                domainsInsertStmt.setString(1, domainNameRev);
                domainsInsertStmt.setDate(2, new java.sql.Date(logdate.getTime()));
                domainsInsertStmt.setString(3, secondLevelDomainNameRev);
                executePreparedStatementNoResult(con, domainsInsertStmt);

                domainsSelectStmt.setString(1, domainNameRev);
                ResultSet rs = this.executePreparedStatementWithResult(con, domainsSelectStmt);

                try {
                    if (rs.next()) {
                        int domainId = rs.getInt(1);

                        clustersInsertStmt.setInt(1, clusterId);
                        clustersInsertStmt.setInt(2, domainId);
                        clustersInsertStmt.setString(3, sensorname);
                        clustersInsertStmt.setDate(4, new java.sql.Date(logdate.getTime()));

                        this.executePreparedStatementNoResult(con, clustersInsertStmt);

                        for (InetAddress resolvedIP : candidateDomain.getIps()) {
                            resolvedIPSInsertStmt.setInt(1, domainId);
                            resolvedIPSInsertStmt.setDate(2, new java.sql.Date(logdate.getTime()));
                            resolvedIPSInsertStmt.setString(3, resolvedIP.getHostAddress());

                            this.executePreparedStatementNoResult(con, resolvedIPSInsertStmt);

                        }
                    }
                } catch (SQLException ex) {
                    if (log.isErrorEnabled()) {
                        log.error("", ex);
                    }
                } finally {
                    rs.close();
                }
            }

            /*String nickname = getNicknames((List<String>)cluster.getDomains());
            insertQuery = "INSERT INTO cluster_nicknames_"+ logDateTable +" VALUES" +
             "("+clusterId+", '"+sensorname+"', '"+logDateStr+"', '"+nickname+"')";
                    
            performInsertQuery(insertQuery, clusterNicknamesCreateQuery);*/

            for (InetAddress resolvedIP : cluster.getIps()) {
                clusterResolvedIPSInsertStmt.setInt(1, clusterId);
                clusterResolvedIPSInsertStmt.setString(2, sensorname);
                clusterResolvedIPSInsertStmt.setDate(3, new java.sql.Date(logdate.getTime()));
                clusterResolvedIPSInsertStmt.setString(4, resolvedIP.getHostAddress());

                this.executePreparedStatementNoResult(con, clusterResolvedIPSInsertStmt);
            }

            clusterFeatureVectorsInsertStmt.setInt(1, clusterId);
            clusterFeatureVectorsInsertStmt.setString(2, sensorname);
            clusterFeatureVectorsInsertStmt.setDate(3, new java.sql.Date(logdate.getTime()));
            clusterFeatureVectorsInsertStmt.setInt(4, cluster.getIps().size());
            clusterFeatureVectorsInsertStmt.setDouble(5, cluster.getIpDiversity());
            clusterFeatureVectorsInsertStmt.setInt(6, cluster.getDomains().size());
            clusterFeatureVectorsInsertStmt.setDouble(7, cluster.getAvgTTLPerDomain());
            clusterFeatureVectorsInsertStmt.setDouble(8, cluster.getIpGrowthRatio());
            clusterFeatureVectorsInsertStmt.setDouble(9, cluster.getQueriesPerDomain());

            Double temp = cluster.getAvgLastGrowthRatioSingleEntry();
            if (temp == null) {
                clusterFeatureVectorsInsertStmt.setNull(10, java.sql.Types.REAL);
            } else {
                clusterFeatureVectorsInsertStmt.setDouble(10, temp);
            }

            temp = cluster.getAvgLastGrowthRatioEntries();
            if (temp == null) {
                clusterFeatureVectorsInsertStmt.setNull(11, java.sql.Types.REAL);
            } else {
                clusterFeatureVectorsInsertStmt.setDouble(11, temp);
            }

            temp = cluster.getAvgLastGrowthPrefixRatioEntries();
            if (temp == null) {
                clusterFeatureVectorsInsertStmt.setNull(12, java.sql.Types.REAL);
            } else {
                clusterFeatureVectorsInsertStmt.setDouble(12, temp);
            }

            temp = cluster.getLastGrowthRatioCluster();
            if (temp == null) {
                clusterFeatureVectorsInsertStmt.setNull(13, java.sql.Types.REAL);
            } else {
                clusterFeatureVectorsInsertStmt.setDouble(13, temp);
            }

            temp = cluster.getLastGrowthPrefixRatioCluster();
            if (temp == null) {
                clusterFeatureVectorsInsertStmt.setNull(14, java.sql.Types.REAL);
            } else {
                clusterFeatureVectorsInsertStmt.setDouble(14, temp);
            }

            this.executePreparedStatementNoResult(con, clusterFeatureVectorsInsertStmt);

            clusterId++;
        }
    } catch (SQLException e) {
        if (log.isErrorEnabled()) {
            log.error("", e);
        }
    } finally {
        try {
            if (domainsInsertStmt != null && !domainsInsertStmt.isClosed()) {
                domainsInsertStmt.close();
            }
            if (domainsSelectStmt != null && !domainsSelectStmt.isClosed()) {
                domainsSelectStmt.close();
            }
            if (clustersInsertStmt != null && !clustersInsertStmt.isClosed()) {
                clustersInsertStmt.close();
            }
            if (resolvedIPSInsertStmt != null && !resolvedIPSInsertStmt.isClosed()) {
                resolvedIPSInsertStmt.close();
            }
            if (clusterResolvedIPSInsertStmt != null && !clusterResolvedIPSInsertStmt.isClosed()) {
                clusterResolvedIPSInsertStmt.close();
            }
            if (clusterFeatureVectorsInsertStmt != null && !clusterFeatureVectorsInsertStmt.isClosed()) {
                clusterFeatureVectorsInsertStmt.close();
            }
            if (con != null && !con.isClosed()) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

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

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

    /*if (SystemStateManager.getCurrentState() != SystemStateManager.STATUS_NORMAL) {
    return mapping.findForward(LOCKED_FORWARD);
    }*//*from  w w w . j a  v a  2s  .com*/

    HttpSession session = request.getSession();
    Locale sessionLocale = (Locale) request.getAttribute("sessionLocale");
    String sessionLocaleString = null;
    if ((sessionLocale.getLanguage() != null)
            && ((sessionLocale.getCountry() != null) && (!sessionLocale.getCountry().equals("")))) {
        sessionLocaleString = sessionLocale.getLanguage() + "_" + sessionLocale.getCountry();
    } else if (sessionLocale.getLanguage() != null) {
        sessionLocaleString = sessionLocale.getLanguage();
    }
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    Connection conn = null;
    BaseEncounter encounter = null;
    Map encMap = null;
    Long formId = null;
    SessionSubject sessionPatient = null;
    Long patientId = null;
    //Long eventId = null;
    String eventUuid = null;
    Form encounterForm = null;
    String formName = null;
    if (mapping.getParameter() != null && !mapping.getParameter().equals("")) {
        formName = mapping.getParameter().trim();
        formId = (Long) DynaSiteObjects.getFormNameMap().get(formName);
    } else {
        if (request.getParameter("formId") != null) {
            formId = Long.decode(request.getParameter("formId"));
        } else if (request.getAttribute("formId") != null) {
            formId = Long.decode(request.getAttribute("formId").toString());
        }
        //formId = request.getAttribute("id").toString();
    }

    if (request.getParameter("patientId") != null) {
        patientId = Long.decode(request.getParameter("patientId"));
    } else if (request.getAttribute("patientId") != null) {
        patientId = Long.decode(request.getAttribute("patientId").toString());
    }

    try {
        sessionPatient = (SessionSubject) SessionUtil.getInstance(session).getSessionPatient();
        //eventId = sessionPatient.getCurrentEventId();
        eventUuid = sessionPatient.getCurrentEventUuid();
    } catch (SessionUtil.AttributeNotFoundException e) {
        log.error("Unable to get TimsSessionSubject");
    }

    if (patientId == null) {
        try {
            patientId = sessionPatient.getId();
        } catch (Exception e) {
            log.error("Unable to get TimsSessionSubject field");
        }
    }

    // sometimes the user can click link to create a new event and then click elsewhere.
    if (eventUuid == null) {
        String forwardString = "/listEvents.do?patientId=" + patientId;
        ActionForward forwardForm = new ActionForward(forwardString);
        forwardForm.setRedirect(true);
        return forwardForm;
    }

    encounterForm = ((Form) DynaSiteObjects.getForms().get(formId));
    try {
        conn = DatabaseUtils.getZEPRSConnection(username);

        // populate the records for this class
        List chartItems = new ArrayList();
        String classname = StringManipulation.fixClassname(encounterForm.getName());
        Class clazz = Class.forName(Constants.getDynasiteFormsPackage() + "." + classname);
        try {
            ArrayList moreItems = (ArrayList) EncountersDAO.getAllOrderBy(conn, patientId, eventUuid,
                    "SQL_RETRIEVE_UUID" + formId, clazz, "date_visit DESC");
            chartItems.addAll(moreItems);
        } catch (IOException e) {
            request.setAttribute("exception", e);
            return mapping.findForward("error");
        } catch (ServletException e) {
            request.setAttribute("exception", e);
            return mapping.findForward("error");
        } catch (SQLException e) {
            request.setAttribute("exception", e);
            return mapping.findForward("error");
        }

        // DAR-specific:
        if (formName.equals("PatientCondition")) {
            String bmiCalc = Constants.getProperties("bmi.calculate", Constants.getAPP_PROPERTIES());
            if (bmiCalc != null && bmiCalc.equals("true")) {
                for (int i = 0; i < chartItems.size(); i++) {
                    PatientCondition pc = (PatientCondition) chartItems.get(i);
                    Float weight = pc.getWeight();
                    Float height = pc.getHeight();
                    if ((weight != null) && ((height != null) && (height != 0))) {
                        Float bmi = HealthCalcUtils.bmiCalc(weight, height);
                        pc.setBmi_calculated(bmi);
                    }
                }
            }
        }

        // Attach a map of encounter values that has enumerations already resolved.
        MessageResources messageResources = getResources(request, encounterForm.getClassname() + "Messages");
        String messageKey = encounterForm.getClassname() + "Messages";
        ReloadablePropertyMessageResources messages = (ReloadablePropertyMessageResources) request
                .getAttribute(messageKey);
        //ZcorePropertyMessageResources sMessages = (ZcorePropertyMessageResources) messages;
        HashMap messageResourcesMap = messages.getMessages();
        HashMap localeMap = messages.getLocales();
        if (localeMap.get(sessionLocale.toString()) == null) {
            messages.loadLocale(sessionLocale.toString());
        }

        // Attach a map of encounter values that has enumerations already resolved.
        Form encForm = (Form) DynaSiteObjects.getForms().get(encounterForm.getId());
        for (int i = 0; i < chartItems.size(); i++) {
            encounter = (EncounterData) chartItems.get(i);
            encMap = PatientRecordUtils.getEncounterMap(encForm, encounter, "fieldId");
            encounter.setEncounterMap(encMap);
            if (messageResourcesMap != null) {
                encounter.setMessageResourcesMap(messageResourcesMap);
            }
        }
        if (chartItems.size() > 0) {
            request.setAttribute("chartItems", chartItems);
            request.setAttribute("formId", encounterForm.getId());
            // loading of body onload DWRUtil.useLoadingMessage()
            request.setAttribute("dwr", 1);
        }

        // Process the dynamic dropdown lists.
        HashMap listMap = new HashMap();
        Form inlineForm = null;
        for (Iterator iterator = encounterForm.getPageItems().iterator(); iterator.hasNext();) {
            PageItem pageItem = (PageItem) iterator.next();
            FormField formField = pageItem.getForm_field();
            String identifier = formField.getIdentifier();

            if (pageItem.getInputType().equals("dropdown") || pageItem.getInputType().equals("dropdown-add-one")
                    || pageItem.getInputType().equals("dropdown_site")) {
                List list = WidgetUtils.getList(conn, pageItem.getDropdownTable(), pageItem.getDropdownColumn(),
                        pageItem.getDropdownConstraint(), pageItem.getDropdownOrderByClause(),
                        DropdownItem.class, pageItem.getFkIdentifier());
                listMap.put(pageItem.getId(), list);
                if (pageItem.getInputType().equals("dropdown-add-one")) {
                    String classNameString = StringManipulation.fixClassname(pageItem.getDropdownTable());
                    Long inlineFormId = (Long) DynaSiteObjects.getFormNameMap().get(classNameString);
                    inlineForm = ((Form) DynaSiteObjects.getForms().get(new Long(inlineFormId)));
                    // Create a list of fieldnames for inline forms.
                    ArrayList<String> inlineFields = new ArrayList<String>();
                    for (Iterator iterator2 = inlineForm.getPageItems().iterator(); iterator2.hasNext();) {
                        PageItem pageItem2 = (PageItem) iterator2.next();
                        if (pageItem2.getForm_field().isEnabled() == true
                                && !pageItem2.getForm_field().getType().equals("Display")) {
                            inlineFields.add(pageItem2.getForm_field().getIdentifier());
                        }
                    }
                    request.setAttribute("inlineForm_" + identifier, inlineForm);
                    request.setAttribute("inlineFields_" + identifier, inlineFields);
                    // loading of body onload DWRUtil.useLoadingMessage()
                    request.setAttribute("dwr", 1);
                }
            }
        }
        request.setAttribute("listMap", listMap);
        request.setAttribute("encounterForm", encounterForm);

        // Keep this block at the end - it sets sessionPatient to null in certain circumstances.
        // Set the tasklist for particular circumstances. First check if the form requires a patient or if "id" is in the reqiest.
        if ((encounterForm.isRequirePatient() || ((request.getParameter("id") != null)))) {
            // we don't need the tasklist if we're just editing a form or it's in unassigned flow
            Long unassigned = new Long("100");
            if (request.getParameter("id") == null) {
                if (!encounterForm.getFlow().getId().equals(unassigned)) {
                    // moved code for form 66 below.
                }
            }
            Boolean status = Boolean.valueOf(true);
            List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status,
                    sessionPatient);
            request.setAttribute("activeProblems", activeProblems);
            // now get inactive problems
            status = Boolean.valueOf(false);
            List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid,
                    status, sessionPatient);
            request.setAttribute("inactiveProblems", inactiveProblems);
            // Display task list if editing form 1.
        } else if ((encounterForm.getId().intValue() == 1) & (patientId != null)) {
            Boolean status = Boolean.valueOf(true);
            List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status,
                    sessionPatient);
            request.setAttribute("activeProblems", activeProblems);
            // now get inactive problems
            status = Boolean.valueOf(false);
            List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid,
                    status, sessionPatient);
            request.setAttribute("inactiveProblems", inactiveProblems);
            // otherwise reset sessionPatient
        } else {
            SessionUtil.getInstance(session).setSessionPatient(null);
        }

    } catch (ServletException e) {
        log.error(e);
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }

    encounterForm = null;

    return mapping.findForward("success");

}

From source file:sce.RESTCheckSLAJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    Connection conn = null;
    try {//from w w  w . ja v a2 s  .  c  o  m
        //required parameters #url, #slaId, #slaTimestamp
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String url1 = jobDataMap.getString("#url"); // e.g. http://kb-read:icaro@192.168.0.106:8080/IcaroKB/sparql
        if (url1 == null) {
            throw new JobExecutionException("#url parameter must be not null");
        }
        String slaId = jobDataMap.getString("#slaId");
        if (slaId == null) {
            throw new JobExecutionException("#slaId parameter must be not null");
        }
        String slaTimestamp = jobDataMap.getString("#slaTimestamp"); // e.g. 2014-09-10T16:30:00
        //if timestamp is not defined, use current
        if (slaTimestamp == null) {
            //throw new JobExecutionException("#slaTimestamp parameter must be not null");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            slaTimestamp = sdf.format(new Date());
        }
        //first SPARQL query to retrieve services, metrics and thresholds in the SLA
        String url = url1 + "?query=" + URLEncoder.encode(getSPARQLQuery(slaId), "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");
        int bindings = list.size();
        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 v = (String) ((HashMap<String, Object>) o.get("v")).get("value");
            String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value");
            String p = (String) ((HashMap<String, Object>) o.get("p")).get("value");
            String callUrl = (String) ((HashMap<String, Object>) o.get("act")).get("value");
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value");
            lst.add(new String[] { mn, v, sm, p, callUrl, bc });
        }

        //second SPARQL query to retrieve alerts for SLA
        url = url1 + "?query=" + URLEncoder.encode(getAlertsForSLA(lst, slaTimestamp), "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");
        //ArrayList<String[]> lst1 = new ArrayList<>();
        //int counter = 0;
        String vv_temp;
        String result = "";

        //LOAD QUARTZ PROPERTIES
        Properties prop = new Properties();
        prop.load(this.getClass().getResourceAsStream("quartz.properties"));

        //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);

        //Hashmap to store callUrls to be called in case of alarm
        HashMap<String, Integer> callUrlMap = new HashMap<>();

        // JSON to be sent to the SM
        JSONArray jsonArray = new JSONArray();
        boolean notify = false; // whether notify the SM or not

        // Business Configuration
        String bc = "";

        for (Object obj : list1) {
            //JSON to insert into database
            //JSONArray jsonArray = new JSONArray();
            boolean alarm; //set to true if there is an alarm on sla

            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String y = (String) ((HashMap<String, Object>) o.get("y")).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 mt = (String) ((HashMap<String, Object>) o.get("mt")).get("value"); //timestamp
            //String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value");
            String vm = (String) ((HashMap<String, Object>) o.get("vm")).get("value"); //virtual_machine
            String vmn = (String) ((HashMap<String, Object>) o.get("vmn")).get("value"); //virtual_machine_name
            String hm = o.get("hm") != null ? (String) ((HashMap<String, Object>) o.get("hm")).get("value")
                    : ""; //host_machine
            //String na = (String) ((HashMap<String, Object>) o.get("na")).get("value");
            //String ip = (String) ((HashMap<String, Object>) o.get("ip")).get("value");
            String v = (String) ((HashMap<String, Object>) o.get("v")).get("value"); //threshold
            String p = (String) ((HashMap<String, Object>) o.get("p")).get("value"); //relation (<,>,=)
            vv_temp = (String) ((HashMap<String, Object>) o.get("vv")).get("value"); //value
            String callUrl = (String) ((HashMap<String, Object>) o.get("callUrl")).get("value"); //call url
            bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value"); //business configuration

            /*JSONObject object = new JSONObject();
             object.put("metric", y);
             object.put("metric_name", mn);
             object.put("metric_unit", mu);
             object.put("timestamp", mt);
             //object.put("service", sm);
             object.put("virtual_machine", vm);
             object.put("virtual_machine_name", vmn);
             object.put("host_machine", hm);
             object.put("value", vv_temp);
             object.put("relation", getProperty(p));
             object.put("threshold", v);
             jsonArray.add(object);*/
            //CHECK IF THE SLA IS VIOLATED
            alarm = checkSLA(Double.parseDouble(vv_temp), Double.parseDouble(v), p);

            // if alarm is true, then put the callUrl in a HashMap
            // and build the json object to be added to the json array to be sent to the SM
            if (alarm) {
                callUrlMap.put(callUrl, 1);

                notify = true;
                JSONObject object = new JSONObject();
                object.put("sla", slaId);
                object.put("metric", y);
                object.put("metric_name", mn);
                object.put("metric_unit", mu);
                object.put("metric_timestamp", mt);
                object.put("virtual_machine", vm);
                object.put("virtual_machine_name", vmn);
                object.put("host_machine", hm);
                object.put("value", vv_temp);
                object.put("relation", p.substring(p.lastIndexOf("#") + 1));
                object.put("threshold", v);
                object.put("call_url", callUrl);
                jsonArray.add(object);
            }

            //INSERT THE DATA INTO DATABASE
            PreparedStatement preparedStatement = conn.prepareStatement(
                    "INSERT INTO quartz.QRTZ_SPARQL (timestamp, sla, alarm, metric, metric_name, metric_unit, metric_timestamp, virtual_machine, virtual_machine_name, host_machine, value, relation, threshold, call_url, business_configuration) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE timestamp=?");
            preparedStatement.setString(1, timestamp); // date
            preparedStatement.setString(2, slaId); // sla
            preparedStatement.setInt(3, alarm ? 1 : 0); // alarm
            preparedStatement.setString(4, y); // metric
            preparedStatement.setString(5, mn); // metric_name
            preparedStatement.setString(6, mu); // metric_unit
            preparedStatement.setString(7, mt); // metric_timestamp (e.g., 2014-12-01T16:14:00)
            preparedStatement.setString(8, vm); // virtual_machine
            preparedStatement.setString(9, vmn); // virtual_machine_name
            preparedStatement.setString(10, hm); // host_machine
            preparedStatement.setString(11, vv_temp); // value
            preparedStatement.setString(12, p.substring(p.lastIndexOf("#") + 1)); //relation (e.g., http://www.cloudicaro.it/cloud_ontology/core#hasMetricValueLessThan)
            preparedStatement.setString(13, v); // threshold
            preparedStatement.setString(14, callUrl); // callUrl
            preparedStatement.setString(15, bc); // business configuration
            preparedStatement.setString(16, timestamp); // date
            preparedStatement.executeUpdate();
            preparedStatement.close();

            //lst1.add(new String[]{y, mt, vv_temp});
            result += "\nService Metric: " + y + "\n";
            result += "\nMetric Name: " + mn + "\n";
            result += "\nMetric Unit: " + mu + "\n";
            result += "Timestamp: " + mt + "\n";
            //result += "Service: " + sm + "\n";
            result += "Virtual Machine: " + vm + "\n";
            result += "Virtual Machine Name: " + vmn + "\n";
            result += "Host Machine: " + hm + "\n";
            //result += "Network Adapter: " + na + "\n";
            //result += "IP: " + ip + "\n";
            result += "Value" + (counter + 1) + ": " + vv_temp + "\n";
            result += "Threshold: " + getProperty(lst.get(counter)[3]) + " " + lst.get(counter)[1] + "\n";
            result += "Call Url: " + callUrl + "\n";
            result += "Business Configuration: " + bc + "\n";

            counter++;
        }

        // if the notify is true, then send the JSON to the SM
        if (notify) {
            JSONObject object = new JSONObject();
            object.put("metric", jsonArray);
            object.put("business_configuration", bc);
            object.put("timestamp", timestamp);
            object.put("sla", slaId);
            sendPostRequest(object.toJSONString());
        }

        //call the callUrls in the HashMap
        Iterator it = callUrlMap.entrySet().iterator();
        while (it.hasNext()) {
            try {
                Map.Entry pairs = (Map.Entry) it.next();
                URL u_callUrl = new URL((String) pairs.getKey());
                //get user credentials from URL, if present
                final String usernamePasswordCallUrl = u_callUrl.getUserInfo();
                //set the basic authentication credentials for the connection
                if (usernamePasswordCallUrl != null) {
                    Authenticator.setDefault(new Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(usernamePasswordCallUrl.split(":")[0],
                                    usernamePasswordCallUrl.split(":")[1].toCharArray());
                        }
                    });
                }
                //call the callUrl
                URLConnection connection = u_callUrl.openConnection();
                getUrlContents(connection);
            } catch (Exception e) {
            }
            it.remove(); // avoids a ConcurrentModificationException

        }

        //clean the callUrl map
        callUrlMap.clear();

        //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.rti.zcore.dar.remote.StockEncounter.java

/**
 * This is only for editing patient dispensary items
 * @param inputType//  w ww .ja va2  s  . c o  m
 * @param value
 * @param pageItemId
 * @param formId
 * @param encounterId
 * @param widgetType  - "Form" or "Chart"
 * @param bridgeId - if the record is a patient bridge table
 * @return updated value
 */
public static String update(String inputType, String value, Long pageItemId, Long formId, Long encounterId,
        String widgetType, Long displayField, Long bridgeId, String currentFieldNameIdentifier) {
    String result = "";
    WebContext exec = WebContextFactory.get();
    String username = null;
    try {
        username = exec.getHttpServletRequest().getUserPrincipal().getName();
    } catch (NullPointerException e) {
        // unit testing - it's ok...
        username = "demo";
    }
    Connection conn = null;
    HttpSession session = null;
    try {
        conn = DatabaseUtils.getZEPRSConnection(username);
        SessionUtil zeprsSession = null;
        try {
            session = exec.getSession();
            zeprsSession = (SessionUtil) session.getAttribute("zeprs_session");
        } catch (Exception e) {
            // unit testing - it's ok...
        }
        Long patientId = null;
        Long eventId = null;
        Long siteId = null;
        String documentId = null;

        if (displayField == null) {
            displayField = encounterId;
        }

        PageItem pageItem = (PageItem) DynaSiteObjects.getPageItems().get(pageItemId);
        FormField formField = pageItem.getForm_field();
        Long formFieldId = formField.getId();

        if (widgetType.equals("Form")) {
            documentId = String.valueOf(formFieldId);
        } else if (widgetType.equals("Chart")) {
            documentId = String.valueOf(encounterId) + "." + String.valueOf(formFieldId);
        }
        if (pageItemId == 3861) {
            documentId = String.valueOf(encounterId) + "." + String.valueOf(displayField);
        }

        Form encounterForm = (Form) DynaSiteObjects.getForms().get(formId);
        if (encounterForm.getFormTypeId() == 6) { // patient bridge table form
            documentId = currentFieldNameIdentifier + String.valueOf(formFieldId);
        }

        SessionSubject sessionPatient = null; // sessionPatient used for rule processing in EncountersDAO.update
        if (zeprsSession != null) {
            try {
                sessionPatient = (SessionSubject) zeprsSession.getSessionPatient();
                patientId = zeprsSession.getSessionPatient().getId();
                eventId = zeprsSession.getSessionPatient().getCurrentEventId();
                ClientSettings clientSettings = zeprsSession.getClientSettings();
                siteId = clientSettings.getSiteId();
            } catch (SessionUtil.AttributeNotFoundException e) {
                log.error("inputType: " + inputType + " value: " + value + " pageItemId: " + pageItemId
                        + " formId: " + formId + " encounterId: " + encounterId);
                return documentId + "="
                        + "Error: your session may have expired. Please refresh this page or login again.";
            } catch (NullPointerException e) {
                // it's ok - testing
                patientId = new Long("44");
                eventId = new Long("38");
                siteId = new Long("1");
            }
        } else {
            log.error("inputType: " + inputType + " value: " + value + " pageItemId: " + pageItemId
                    + " formId: " + formId + " encounterId: " + encounterId);
            return documentId + "="
                    + "Error: your session may have expired. Please refresh this page or login again.";
        }

        Form form = (Form) DynaSiteObjects.getForms().get(formId);

        EncounterData encounter = null;
        String className = Constants.getDynasiteFormsPackage() + "."
                + StringManipulation.fixClassname(form.getName());
        Class clazz = null;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            log.error(e);
        }
        try {
            encounter = (EncounterData) clazz.newInstance();
        } catch (InstantiationException e) {
            log.error(e);
        } catch (IllegalAccessException e) {
            log.error(e);
        }

        try {
            encounter = (EncounterData) EncountersDAO.getOne(conn, encounterId, "SQL_RETRIEVEID" + formId,
                    clazz);
        } catch (IOException e) {
            log.error(e);
        } catch (ServletException e) {
            log.error(e);
        } catch (SQLException e) {
            log.error(e);
        } catch (ObjectNotFoundException e) {
            log.error(e);
        }

        // extra validation for stock.

        Long itemId = null;
        String dataType = formField.getType();
        Integer intValue = null;
        if (dataType.equals("Integer")) {
            try {
                intValue = Integer.valueOf(value);
            } catch (NumberFormatException e) {
                try {
                    throw new PersistenceException(
                            "This input field requires an integer value (e.g.: 55). You entered : " + value, e,
                            false);
                } catch (PersistenceException e1) {
                    result = documentId + "=" + "Error:" + e.getMessage();
                }
            }
        }

        if (formField.getIdentifier().equals("dispensed")) {
            String itemIdStr = null;
            String dispensedStr = null;
            Long originallyDispensed = null;
            try {
                itemIdStr = BeanUtils.getProperty(encounter, "item_id");
                dispensedStr = BeanUtils.getProperty(encounter, "dispensed");
            } catch (IllegalAccessException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (InvocationTargetException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (NoSuchMethodException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            if (itemIdStr != null) {
                itemId = Long.valueOf(itemIdStr);
                originallyDispensed = Long.valueOf(dispensedStr);
                if (DynaSiteObjects.getStatusMap().get("balanceMap") != null) {
                    HashMap<Long, StockReport> balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects
                            .getStatusMap().get("balanceMap");
                    StockReport stockReport = balanceMap.get(itemId);
                    if (stockReport != null) {
                        Integer balance = stockReport.getBalanceBF();
                        if (balance <= 0) {
                            result = documentId
                                    + "=Error: This item is out of stock. Cannot proceed with this update. Current balance: "
                                    + balance;
                            return result;
                        } else if ((balance + originallyDispensed) - intValue < 0) { // add the originallyDispensed value back to the balanace, and then subtract the new dispensed value.
                            result = documentId
                                    + "=Error: This update would create a negative stock balanace Please reduce the amount dispensed. Current balance: "
                                    + balance;
                            return result;
                        }
                    }
                }
            }
        } else if (formField.getIdentifier().equals("item_id")) {
            result = documentId
                    + "=Error: You may not change the stock item. Either delete this record or set the Quantity dispensed for this item to zero (0) and create a new record (Dispensing link -> \"Create New Dispensing record\" link).";
            return result;
        }

        Timestamp lastModified = null;
        if (value != null) {
            try {
                EncountersDAO.update(conn, value, pageItemId, formId, encounterId, siteId, username, patientId,
                        eventId, sessionPatient, lastModified, bridgeId, currentFieldNameIdentifier, null,
                        session);
                if (formField.getIdentifier().equals("dispensed")) {
                    if ((itemId != null) && (DynaSiteObjects.getStatusMap().get("balanceMap") != null)) {
                        HashMap<Long, StockReport> balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects
                                .getStatusMap().get("balanceMap");
                        StockReport stockReport = balanceMap.get(itemId);
                        if (stockReport != null) {
                            if (intValue != null) {
                                StockControl tempStockControl = InventoryDAO.getCurrentStockBalance(conn,
                                        itemId, null);
                                Integer currentBalance = tempStockControl.getBalance();
                                //Integer currentBalance = balanceBF - intValue;
                                stockReport.setBalanceBF(currentBalance);
                                stockReport.setOnHand(currentBalance);
                                balanceMap.put(itemId, stockReport);
                            }
                        }
                    }
                }
            } catch (SQLException e) {
                log.error(e);
            } catch (ServletException e) {
                log.error(e);
            } catch (PersistenceException e) {
                result = documentId + "=" + "Error:" + e.getMessage();
            } catch (ObjectNotFoundException e) {
                log.error(e);
            } catch (ClassNotFoundException e) {
                log.error(e);
            } catch (IOException e) {
                result = documentId + "=" + "Error:" + e.getMessage();
                log.error(e);
            }

            if (result.equals("")) {
                if (value.equals("")) {
                    result = documentId + "=" + value;
                } else {
                    if (inputType.equals("select") || inputType.equals("select-dwr")
                            || inputType.equals("multiselect_item")) {
                        FieldEnumeration fieldEnum = (FieldEnumeration) DynaSiteObjects.getFieldEnumerations()
                                .get(Long.valueOf(value));
                        switch (formFieldId.intValue()) {
                        default:
                            result = documentId + "=" + fieldEnum.getEnumeration();
                            break;
                        }
                    } else if (inputType.equals("lab_results")) {
                        FieldEnumeration fieldEnum = (FieldEnumeration) DynaSiteObjects.getFieldEnumerations()
                                .get(Long.valueOf(value));
                        result = documentId + "=" + fieldEnum.getEnumeration();
                    } else if (inputType.equals("currentMedicine")) {
                        // Drugs drug = DrugsDAO.getOne(Long.valueOf(value));
                        Drugs drug = null;
                        try {
                            drug = (Drugs) DynaSiteObjects.getDrugMap().get(Long.valueOf(value));
                            result = documentId + "=" + drug.getName();
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        if (drug == null) {
                            result = documentId + "=" + value;
                        }
                    } else if (inputType.equals("Yes/No")) {
                        if (value.equals("1")) {
                            value = "Yes";
                        } else if (value.equals("0")) {
                            value = "No";
                        }
                        result = documentId + "=" + value;
                    } else if (inputType.equals("checkbox")) {
                        if (value.equals("true")) {
                            value = "Yes";
                        } else if (value.equals("1")) {
                            value = "Yes";
                        } else if (value.equals("on")) {
                            value = "Yes";
                        } else if (value.equals("false")) {
                            value = "";
                        } else if (value.equals("0")) {
                            value = "";
                        } else if (value.equals("off")) {
                            value = "";
                        }
                        result = documentId + "=" + value;
                    } else if (inputType.equals("checkbox_dwr")) {
                        if (value.equals("true")) {
                            value = "Yes";
                        } else if (value.equals("on")) {
                            value = "Yes";
                        } else if (value.equals("false")) {
                            value = "";
                        } else if (value.equals("off")) {
                            value = "";
                        }
                        result = documentId + "=" + value;
                    } else if (inputType.equals("sex")) {
                        if (value.equals("1")) {
                            value = "Female";
                        } else if (value.equals("2")) {
                            value = "Male";
                        }
                        result = documentId + "=" + value;
                    } else if (inputType.equals("ega")) {
                        int valueInt = new Integer(value);
                        int days = valueInt % 7;
                        int weeks = valueInt / 7;
                        value = weeks + ", " + days + "/7";
                        result = documentId + "=" + value;
                    } else if (pageItem.getInputType().equals("sites")
                            || pageItem.getInputType().equals("sites_not_selected")) {
                        Long thisSite = new Long(value);
                        Site site = (Site) DynaSiteObjects.getClinicMap().get(thisSite);
                        value = site.getName();
                        result = documentId + "=" + value;
                    } else if (inputType.equals("text") & displayField.intValue() != formFieldId.intValue()) {
                        // used in Lab form chart to share two fields in one cell.
                        /*if (displayField != 0) {
                        documentId = String.valueOf(encounterId) + "." + String.valueOf(displayField);
                        }*/
                        result = documentId + "=" + value;
                        //} else if (inputType.equals("dropdown") & currentFieldNameIdentifier != null) {
                    } else if (inputType.equals("dropdown") || inputType.equals("dropdown-add-one")
                            || inputType.equals("dropdown_site")) {
                        //Integer id = Integer.valueOf(value);
                        String uuidValue = null;
                        Integer id = null;
                        if (pageItem.getFkIdentifier() != null && pageItem.getFkIdentifier().equals("uuid")) {
                            uuidValue = value;
                        } else {
                            id = Integer.valueOf(value);
                        }
                        DropdownItem item = null;
                        try {
                            item = WidgetUtils.getDropdownItem(conn, pageItem.getDropdownTable(),
                                    pageItem.getDropdownColumn(), id, null, pageItem.getFkIdentifier(),
                                    uuidValue);
                        } catch (ObjectNotFoundException e) {
                            log.debug("value for Dropdown item not found:" + e);
                        } catch (SQLException e) {
                            log.debug("value for Dropdown item not found:" + e);
                        }
                        if (item != null) {
                            value = item.getDropdownValue();
                            result = documentId + "=" + value;
                        } else {
                            value = "Unable to fetch updated value.";
                            result = documentId + "=" + value;
                        }
                    } else {
                        result = documentId + "=" + value;
                    }
                }
            }
        } else {
            result = documentId + "=" + "Error: No value entered.";
        }
    } catch (ServletException e) {
        log.error(e);
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
                conn = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return result;
}

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

/**
 * Special handling for form id 170 - user info form.
 *///from ww w  .j  a  v  a 2  s.co m
protected ActionForward doExecute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession();
    Site site = SessionUtil.getInstance(session).getClientSettings().getSite();
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    Connection conn = null;

    Long encounterId = null;
    String userrecord = null;
    Long patientId = null;
    Long formId = null;
    String formName = null;
    Integer deps = null;
    String forwardString = null; // Pass forward if you want to override the forward.
    if (request.getParameter("formId") != null) {
        formId = Long.valueOf(request.getParameter("formId"));
        formName = DynaSiteObjects.getFormIdClassNameMap().get(formId);
    }
    //formId = (Long) DynaSiteObjects.getFormNameMap().get(formName);
    if (request.getParameter("encounterId") != null) {
        //if (formName.equals("UserInfo")) {
        //   userrecord = String.valueOf(request.getParameter("encounterId"));
        //} else {
        encounterId = Long.valueOf(request.getParameter("encounterId"));
        //}
    }
    if (request.getParameter("patientId") != null) {
        patientId = Long.valueOf(request.getParameter("patientId"));
    }

    if (request.getParameter("deps") != null) {
        deps = Integer.valueOf(request.getParameter("deps"));
    }
    if (request.getParameter("forward") != null) {
        forwardString = String.valueOf(request.getParameter("forward"));
    }

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

    try {
        conn = DatabaseUtils.getZEPRSConnection(Constants.DATABASE_ADMIN_USERNAME);
        //if ((encounterId != null && formId != null) || formId == 170) {
        if (encounterId != null) {
            EncounterData encounter = null;
            try {
                //if (formName.equals("UserInfo")) {
                //   PatientRecordUtils.deleteUser(conn, userrecord);
                //} else {
                // If this is a MenuItem, save the MenuItem list to xml and refresh DynasiteObjects
                formName = form.getClassname();
                if (!formName.equals("MenuItem")) {
                    try {
                        encounter = (EncounterData) EncountersDAO.getOneById(conn, encounterId);
                    } catch (ObjectNotFoundException e) {
                        // it's ok - may be an admin record.
                    }
                    String eventUuid = null;
                    if (encounter != null) {
                        if (patientId == null) {
                            patientId = encounter.getPatientId();
                        } else {
                            if (encounter.getPatientId() == null) {
                                // this is an admin form - probably a relationship.
                                encounter.setPatientId(patientId);
                            }
                        }

                        //Long eventId = encounter.getEventId();
                        eventUuid = encounter.getEventUuid();
                        formId = encounter.getFormId();
                        // this could be an admin record, which is will not have patientId or pregnancyId
                        if (patientId != null) {
                            //PatientStatusReport psr = PatientStatusDAO.getOne(conn, patientId);
                            Patient patient = PatientDAO.getOne(conn, patientId);
                            //Long currentFlowEncounterId = patient.getCurrentFlowEncounterId();
                            String currentFlowEncounterUuid = patient.getCurrentFlowEncounterUuid();
                            if (formId.longValue() == 1) {
                                String message = "You may not delete the patient registration record. "
                                        + "Delete the whole patient record instead by clicking the \"Delete Patient\" link\n"
                                        + "on the Demographics page.";
                                request.setAttribute("exception", message);
                                return mapping.findForward("error");
                            }
                            List outcomes = OutcomeDAO.getAllforEncounter(conn, encounterId);

                            if (outcomes.size() > 0) {
                                if (deps != null && deps.intValue() == 1) {
                                    for (int i = 0; i < outcomes.size(); i++) {
                                        OutcomeImpl outcome = (OutcomeImpl) outcomes.get(i);
                                        OutcomeDAO.deleteOne(conn, outcome.getId());
                                    }
                                } else {
                                    String url = "/" + Constants.APP_NAME
                                            + "/admin/deleteEncounter.do;jsessionid=" + session.getId()
                                            + "?encounterId=" + encounterId + "&formId=" + formName + "&deps=1";
                                    String message = "<p>This record has system-generated problems.  "
                                            + "Are you sure you want to delete it?.</p>" + "<p><a href=\"" + url
                                            + "\">Delete</a></p>";
                                    request.setAttribute("exception", message);
                                    return mapping.findForward("error");
                                }
                            }

                            // Test to see if you are deleting the most recent encounter.
                            //if (encounterId.longValue() == currentFlowEncounterId.longValue()) {
                            if (encounter.getUuid().equals(currentFlowEncounterUuid)) {
                                // Find the previous encounter
                                EncounterData encounterData = EncountersDAO.getPreviousEncounter(conn,
                                        patientId, eventUuid, encounterId);
                                Long prevEncId = encounterData.getId();
                                if (prevEncId != null) {
                                    // re-assign values in patient status
                                    Long currentFlowId = encounterData.getFlowId();
                                    Map queries = QueryLoader.instance()
                                            .load("/" + Constants.SQL_PATIENT_PROPERTIES);
                                    String sqlUpdateStatus = (String) queries.get("SQL_MODIFY_STATUS");
                                    EncounterData vo = new EncounterData(); // dummy EncounterData is OK.
                                    vo.setUuid(encounterData.getUuid());
                                    PatientStatusDAO.updatePatientStatus(conn, vo, currentFlowId, prevEncId,
                                            username, site.getId(), patientId, sqlUpdateStatus);
                                } else {
                                    String message = "Unable to delete this record - please contact the system administrator. ";
                                    request.setAttribute("exception", message);
                                    return mapping.findForward("error");
                                }
                            }
                        }
                    }

                    EncounterData vo = new EncounterData(); // dummy EncounterData is OK.
                    vo.setPatientId(patientId);
                    //vo.setEventId(eventId);
                    vo.setEventUuid(eventUuid);

                    // DAR-specific code for stock and regimen-related forms - deletes only its associated table record
                    if (formId == 128 || formId == 129 || formId == 130 || formId == 131 || formId == 181) {
                        deleteFromSingleTable(site, username, conn, encounterId, formId, encounter);
                    } else {
                        try {
                            PatientRecordUtils.deleteEncounter(conn, formId, encounterId, username, site, vo,
                                    null);
                        } catch (Exception e) {
                            request.setAttribute("exception", e);
                            return mapping.findForward("error");
                        }
                    }

                } else {
                    // If this is a MenuItem, save the MenuItem list to xml and refresh DynasiteObjects
                    ArrayList<MenuItem> menuItemList = DynaSiteObjects.getMenuItemList();
                    int index = 0;
                    for (MenuItem menuItem : menuItemList) {
                        if (encounterId.intValue() == menuItem.getId().intValue()) {
                            index = menuItemList.indexOf(menuItem);
                            //EncounterData encounterMenuItem = (EncounterData) EncountersDAO.getOne(conn, encounterId, "SQL_RETRIEVE_ONE_ADMIN" + formId, MenuItem.class);
                            //MenuItem menuItem = (MenuItem) encounterMenuItem;
                            String templateKey = menuItem.getTemplateKey();

                            //ignore property files for spacer deletion
                            if (templateKey != null) {
                                Boolean dev = DynaSiteObjects.getDev();
                                String pathName = null;
                                String deployPathname = null;

                                if (dev == true) {
                                    pathName = Constants.DEV_RESOURCES_PATH;
                                    deployPathname = Constants.DYNASITE_RESOURCES_PATH;
                                } else {
                                    pathName = Constants.DYNASITE_RESOURCES_PATH;
                                }

                                SortedProperties properties = null;
                                ApplicationDefinition applicationDefinition = DynaSiteObjects
                                        .getApplicationDefinition();
                                ArrayList<String> localeList = applicationDefinition.getLocalList();
                                ;
                                //loop through all property fields and delete this property
                                if (applicationDefinition != null) {
                                    localeList = applicationDefinition.getLocalList();
                                    properties = new SortedProperties();
                                    for (String locale : localeList) {
                                        try {
                                            properties.load(
                                                    new FileInputStream(pathName + Constants.MENU_ITEM_FILENAME
                                                            + "_" + locale + ".properties"));
                                            properties.remove(templateKey);
                                            properties.store(
                                                    new FileOutputStream(pathName + Constants.MENU_ITEM_FILENAME
                                                            + "_" + locale + ".properties"),
                                                    "Deletion by admin");
                                            properties.clear();
                                        } catch (Exception e) {
                                        }
                                    }
                                    properties.clear();
                                    String defaultLocale = applicationDefinition.getDefaultLocale();
                                    if (defaultLocale != null) {
                                        try {
                                            properties.load(
                                                    new FileInputStream(pathName + Constants.MENU_ITEM_FILENAME
                                                            + "_" + defaultLocale + ".properties"));
                                            properties.remove(templateKey);
                                            properties.store(
                                                    new FileOutputStream(pathName + Constants.MENU_ITEM_FILENAME
                                                            + "_" + defaultLocale + ".properties"),
                                                    "Deletion by admin");
                                            properties.clear();
                                        } catch (FileNotFoundException e) {
                                            // not created yet.
                                        }
                                    }
                                    properties.clear();
                                    properties.load(new FileInputStream(
                                            pathName + Constants.MENU_ITEM_FILENAME + ".properties"));
                                    properties.remove(templateKey);
                                    properties.store(
                                            new FileOutputStream(
                                                    pathName + Constants.MENU_ITEM_FILENAME + ".properties"),
                                            "Deletion by admin");
                                    properties.clear();
                                }

                                //Properties properties = new Properties();
                                String selectedLocale = (String) request.getAttribute("defaultLocale");

                                boolean isDefaultLocale = false;
                                try {
                                    properties.load(new FileInputStream(pathName + Constants.MENU_ITEM_FILENAME
                                            + "_" + selectedLocale + ".properties"));
                                    //isDefaultLocale = true;
                                } catch (FileNotFoundException e) {
                                    try {
                                        properties.load(new FileInputStream(
                                                pathName + Constants.MENU_ITEM_FILENAME + ".properties"));
                                    } catch (FileNotFoundException e1) {
                                        e.printStackTrace();
                                    }
                                }
                                properties.remove(templateKey);
                                properties.store(new FileOutputStream(pathName + Constants.MENU_ITEM_FILENAME
                                        + (isDefaultLocale ? "_" + selectedLocale : "") + ".properties"),
                                        "New Entry");

                                // copy to tomcat as well if in dev mode
                                if (dev) {
                                    for (String locale : localeList) {
                                        try {
                                            FileUtils.copyQuick(
                                                    pathName + Constants.MENU_ITEM_FILENAME + "_" + locale
                                                            + ".properties",
                                                    deployPathname + Constants.MENU_ITEM_FILENAME + "_" + locale
                                                            + ".properties");
                                        } catch (Exception e) {
                                        }
                                        try {
                                            FileUtils.copyQuick(
                                                    pathName + Constants.MENU_ITEM_FILENAME + ".properties",
                                                    deployPathname + Constants.MENU_ITEM_FILENAME
                                                            + ".properties");
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    menuItemList.remove(index);
                    DisplayOrderComparator doc = new DisplayOrderComparator();
                    Collections.sort(menuItemList, doc);
                    DynasiteUtils.refreshMenuItemList();
                }
                //}

                // part of reload prevention scheme:
                resetToken(request);
                StrutsUtils.removeFormBean(mapping, request);
                // return mapping.findForward("patientHome");
                ActionForward forwardForm = null;
                if (forwardString != null) {
                    forwardForm = new ActionForward(forwardString);
                    forwardForm.setRedirect(true);
                } else {
                    forwardForm = StrutsUtils.getActionForward("deleteEncounter", patientId, form);
                }
                return forwardForm;
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ObjectNotFoundException e) {
                // already deleted or missing - simply send back to home.
                return mapping.findForward("home");
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        request.setAttribute("exception", e);
        return mapping.findForward("error");
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
    return mapping.findForward("success");
}

From source file:com.viettel.logistic.wms.service.StockImportServiceImpl.java

@Override
public ResultDTO importStockCust(StockTransDTO stockTransDTO, List<StockTransDetailDTO> lstStockTransDetailDTO,
        List<StockTransSerialDTO> lstStockTransSerialDTO) {
    String stockTransDetailId;//from   w  w  w  .java2s  . co  m
    List<StockTransSerialDTO> filterListStockTransSerialDTO;
    String stockTransCode;
    String stockTransSEQ;
    ResultDTO resultDTO = new ResultDTO();
    resultDTO.setMessage(ParamUtils.SUCCESS);
    Map<String, GoodsDTO> mapGoodsDTO;
    Map<String, GoodsDTO> mapGoodsCode2DTO;
    //
    Double indexInsertSuccess = 0D;
    //
    int insertSuccess = 0;
    int insertFail = 0;
    Double amountIssue;
    //
    String stockTransId = "";
    String sysdate;
    //
    Session session;
    Transaction transaction;
    Connection connection = null;
    session = sessionFactory.openSession();
    transaction = session.getTransaction();
    transaction.begin();
    //
    sysdate = stockGoodsBusiness.getSysDate(formatDate);
    GoodsDTO goodsDTO;
    //du lieu cho dong bo bccs
    String previousOrderActionStatus = null;
    /*
     duyot: cap nhat 27/08: dong bo bccs
     - cap nhat partner id
     - cap nhat cac truong trong serial neu la tu kh vtt (id = 1)
     - Khoi tao list NHAP - NHAP DIEU CHUYEN
     */
    //DuyOT
    OrderActionDTO orderActionDTO = null;
    OrdersDTO orders = null;
    try {
        //---------------------------------------------------------------------
        //1. KHOI TAO CONNECTION
        //-------------------------------------------------------------------    
        SessionFactory sessionFactoryBatch = session.getSessionFactory();
        connection = sessionFactoryBatch.getSessionFactoryOptions().getServiceRegistry()
                .getService(ConnectionProvider.class).getConnection();
        connection.setAutoCommit(false);
        //-------------------------------------------------------------------
        //KIEM TRA LENH DA DUOC NHAP HAY CHUA
        //1. KIEM TRA TRANG THAI LENH
        String orderIdList = stockTransDTO.getOrderIdList();
        if (!StringUtils.isStringNullOrEmpty(orderIdList)) {//NEU LA NHAP THEO YC -> CHECK
            orders = WSOrders.findOrderById(orderIdList);
            if (orders == null) {//KHONG TIM DUOC YC HOP LE
                resultDTO.setMessage(ParamUtils.ERROR_MESSAGE.ORDER_NOT_FOUND);
                resultDTO.setKey(ParamUtils.ERROR_MESSAGE.ORDER_NOT_FOUND);
                rollback(session, transaction, connection);
                return resultDTO;
            }
            //LAY THONG TIN LENH
            List<ConditionBean> lstConditionBeanUpdateOrders = new ArrayList<>();
            lstConditionBeanUpdateOrders.add(new ConditionBean("orderIdList", ParamUtils.NAME_EQUAL,
                    orders.getOrderId(), ParamUtils.TYPE_STRING));
            try {
                orderActionDTO = WSOrderAction.getListOrderActionByCondition(lstConditionBeanUpdateOrders, 0,
                        Integer.MAX_VALUE, "", "id").get(0);
            } catch (Exception ex) {
            }
            if (orderActionDTO == null) {//KHONG TIM DUOC YC HOP LE
                resultDTO.setMessage(ParamUtils.ERROR_MESSAGE.ORDER_NOT_FOUND);
                resultDTO.setKey(ParamUtils.ERROR_MESSAGE.ORDER_NOT_FOUND);
                rollback(session, transaction, connection);
                return resultDTO;
            }
            //kiem tra co ai dang cung nhap k
            //                if (lstCurrentOrderActionID.contains(orderActionDTO.getId())) {
            //                    resultDTO.setMessage(ParamUtils.ERROR_MESSAGE.SESSION_CONFLIC);
            //                    resultDTO.setKey(ParamUtils.ERROR_MESSAGE.SESSION_CONFLIC);
            //                    return resultDTO;
            //                } else {//them vao current process
            //                    lstCurrentOrderActionID.add(orderActionDTO.getId());
            //                }

            if (orderActionDTO.getStatus().equalsIgnoreCase("3")) {//NEU TRANG THAI LENH = 3 -> DA NHAP -> THONG BAO LENH DA THUC NHAP
                resultDTO.setMessage(ParamUtils.ERROR_MESSAGE.ORDER_ACTION_UPDATED);
                resultDTO.setKey(ParamUtils.ERROR_MESSAGE.ORDER_ACTION_UPDATED);
                return resultDTO;
            }

            previousOrderActionStatus = orderActionDTO.getStatus();
            String updateMessage = updateOrderAndOrderAction(orders, orderActionDTO);

            if (!updateMessage.equalsIgnoreCase(ParamUtils.SUCCESS)) {//NEU THONG TIN CAP NHAT LOI -> ROLLBACK
                resultDTO.setMessage(ParamUtils.FAIL);
                resultDTO.setKey(ParamUtils.ERROR_MESSAGE.UPDATE_ORDER_ACTION_FAIL);
                rollBackOrderAndOrderAction(orders, orderActionDTO, previousOrderActionStatus);
                rollback(session, transaction, connection);
                removeLock(orderActionDTO);
                return resultDTO;
            }
        }
        //
        if (!DataUtil.isListNullOrEmpty(lstStockTransDetailDTO)) {
            //INSERT GIAO DICH STOCK_TRANS
            stockTransSEQ = stockTransBusiness.getSequence("STOCK_TRANS_SEQ");
            stockTransCode = ParamUtils.CODE_IMPORT_STOCK + stockTransSEQ;
            stockTransDTO.setStockTransCode(stockTransCode);
            stockTransDTO.setCreateDatetime(sysdate);
            stockTransDTO.setStockTransDate(sysdate);
            stockTransDTO.setStockTransId(stockTransSEQ);
            resultDTO = commonBusinessInterface.insertStockTrans(stockTransDTO, connection);
            stockTransId = stockTransDTO.getStockTransId();
            stockTransDTO.setStockTransId(stockTransId);
            if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                removeLock(orderActionDTO);
                rollback(session, transaction, connection);
                rollBackOrderAndOrderAction(orders, orderActionDTO, previousOrderActionStatus);
                return resultDTO;
            }
            //DAY VAO MAP DANH SACH HANG HOA
            String goodsIdList = getGoodsIdList(lstStockTransDetailDTO);
            List<ConditionBean> lstConditionBean = new ArrayList<>();
            lstConditionBean.add(new ConditionBean("custId", ParamUtils.OP_EQUAL, stockTransDTO.getCustId(),
                    ParamUtils.TYPE_NUMBER));
            lstConditionBean
                    .add(new ConditionBean("goodsId", ParamUtils.OP_IN, goodsIdList, ParamUtils.TYPE_NUMBER));
            List<GoodsDTO> lstGoodsDTO = goodsBusiness.searchByConditionBean(lstConditionBean, 0,
                    Integer.MAX_VALUE, "", "code");
            mapGoodsDTO = DataUtil.putGoodsToMap(lstGoodsDTO);
            //LOOP: CHI TIET CHO TUNG MAT HANG
            boolean firstWrong = false;
            Double pre = 0D;
            for (StockTransDetailDTO stockTransDetailDTO : lstStockTransDetailDTO) {
                //lay seq
                String stockTransDetailSEQ = stockTransDetailBusiness.getSequence("STOCK_TRANS_DETAIL_SEQ");
                stockTransDetailDTO.setStockTransId(stockTransId);
                stockTransDetailDTO.setStockTransDetailId(stockTransDetailSEQ);
                stockTransDetailDTO.setStockTransDate(sysdate);
                stockTransDetailDTO.setCreateDatetime(sysdate);
                goodsDTO = mapGoodsDTO.get(stockTransDetailDTO.getGoodsId());
                if (goodsDTO == null) {
                    rollback(session, transaction, connection);
                    resultDTO.setMessage(ParamUtils.FAIL);
                    resultDTO.setKey(ParamUtils.GOODS_IS_NOT_EXIST);
                    removeLock(orderActionDTO);
                    rollBackOrderAndOrderAction(orders, orderActionDTO, previousOrderActionStatus);
                    return resultDTO;
                }
                //INSERT CHI TIET GIAO DICH KHO STOCK_TRANS_DETAIL
                stockTransDetailDTO.setGoodsCode(goodsDTO.getCode());
                stockTransDetailDTO.setGoodsName(goodsDTO.getName());
                stockTransDetailDTO.setGoodsIsSerial(goodsDTO.getIsSerial());
                stockTransDetailDTO.setGoodsIsSerialStrip(goodsDTO.getIsSerialStrip());
                //------
                resultDTO = commonBusinessInterface.insertStockTransDetail(stockTransDetailDTO, connection);
                //-------------
                stockTransDetailId = stockTransDetailSEQ;
                //
                if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                    rollback(session, transaction, connection);
                    resultDTO.setMessage(ParamUtils.FAIL);
                    resultDTO.setKey(ParamUtils.SYSTEM_OR_DATA_ERROR);
                    removeLock(orderActionDTO);
                    rollBackOrderAndOrderAction(orders, orderActionDTO, previousOrderActionStatus);
                    return resultDTO;
                }
                //MAT HANG K THEO SERIAL
                if (!stockTransDetailDTO.getGoodsIsSerial().equals(Constants.IS_SERIAL)) {
                    //Cap nhat mat hang theo so luong STOCK_GOODS
                    resultDTO = importStockGoods(stockTransDTO, stockTransDetailDTO, session,
                            ParamUtils.GOODS_IMPORT_STATUS.IMPORTED);
                    if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                        rollback(session, transaction, connection);
                        removeLock(orderActionDTO);
                        rollBackOrderAndOrderAction(orders, orderActionDTO, previousOrderActionStatus);
                        return resultDTO;
                    }
                    //Cap nhat so luong tong cong STOCK_GOODS_TOTAL
                    resultDTO = importStockGoodsTotal(stockTransDTO, stockTransDetailDTO, session);
                    if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                        rollback(session, transaction, connection);
                        removeLock(orderActionDTO);
                        rollBackOrderAndOrderAction(orders, orderActionDTO, previousOrderActionStatus);
                        return resultDTO;
                    }
                } else //MAT HANG QUAN LY THEO SERIAL
                {
                    //LAY RA DANH SACH SERIAL CUA HANG HOA TUONG UNG
                    filterListStockTransSerialDTO = filterStockTransSerialDTO(
                            stockTransDetailDTO.getTmpStockTransDetailId(), lstStockTransSerialDTO);
                    if (filterListStockTransSerialDTO == null || filterListStockTransSerialDTO.size() < 1) {
                        resultDTO.setMessage(ParamUtils.FAIL);
                        resultDTO.setKey(ParamUtils.SYSTEM_OR_DATA_ERROR);
                        rollback(session, transaction, connection);
                        removeLock(orderActionDTO);
                        rollBackOrderAndOrderAction(orders, orderActionDTO, previousOrderActionStatus);
                        return resultDTO;
                    }
                    //Insert giao dich chi tiet serial
                    //khoi tao list serial duoc nhap kho cho mat hang nay
                    for (StockTransSerialDTO stockTransSerialDTO : filterListStockTransSerialDTO) {
                        //Cap nhat Id giao dich, ID chi tiet giao dichj
                        stockTransSerialDTO.setStockTransId(stockTransId);
                        stockTransSerialDTO.setStockTransDetailId(stockTransDetailId);
                        stockTransSerialDTO.setStockTransDate(sysdate);
                        stockTransSerialDTO.setCreateDatetime(sysdate);
                        stockTransSerialDTO.setGoodsCode(goodsDTO.getCode());
                        stockTransSerialDTO.setGoodsName(goodsDTO.getName());
                    }
                    //Insert batch VAO KHO STOCK_GOODS_SERIAL
                    resultDTO = importStockGoodsListSerial(stockTransDTO,
                            (StockTransDetailDTO) DataUtil.cloneObject(stockTransDetailDTO),
                            filterListStockTransSerialDTO, session, connection,
                            ParamUtils.GOODS_IMPORT_STATUS.IMPORTED);
                    insertSuccess = resultDTO.getQuantitySucc();
                    insertFail = resultDTO.getQuantityFail();
                    //amountIssue = resultDTO.getAmountIssue();

                    //kiem tra so luong thanh cong cua hang hoa
                    if (stockTransDetailDTO.getGoodsIsSerialStrip().equals(Constants.IS_SERIAL_STRIP)) {
                        amountIssue = resultDTO.getAmountIssue();
                    } else {
                        if ((insertFail != 0 && !firstWrong) || (insertFail == 0)) {
                            indexInsertSuccess = Double.parseDouble(insertSuccess + "");
                            pre = Double.parseDouble(insertFail + "");
                            firstWrong = true;
                        } else if (insertFail != 0 && firstWrong) {
                            indexInsertSuccess = insertSuccess + pre;
                            pre = Double.parseDouble(insertFail + "");
                        }
                        amountIssue = indexInsertSuccess;
                    }
                    //DUA VAO THONG TIN GIAO DICH: STOCK_TRANS_SERIAL

                    if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                        rollback(session, transaction, connection);
                        removeLock(orderActionDTO);
                        rollBackOrderAndOrderAction(orders, orderActionDTO, previousOrderActionStatus);
                        return resultDTO;
                    }
                    //END FOR FILTER LIST
                    //CAP NHAT LAI STOCK_TRANS_DETAIL VOI SO LUONG INSERT THANH CONG
                    int isUpdate = stockGoodsSerialBusiness2.updateStockTransDetail(stockTransDetailId,
                            amountIssue, connection);
                    //neu update khong thanh cong
                    if (isUpdate < 1) {
                        resultDTO.setMessage(ParamUtils.FAIL);
                        resultDTO.setKey("UPDATE_STOCK_TRANS_DETAIL_ERROR");
                        rollback(session, transaction, connection);
                        removeLock(orderActionDTO);
                        rollBackOrderAndOrderAction(orders, orderActionDTO, previousOrderActionStatus);
                        return resultDTO;
                    }
                    //

                    stockTransDetailDTO.setAmountReal(amountIssue.toString().replace(".0", ""));
                    //CAP NHAT SO LUONG TONG CONG CUA HANG HOA
                    resultDTO = importStockGoodsTotal(stockTransDTO, stockTransDetailDTO, session);
                    if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                        rollback(session, transaction, connection);
                        removeLock(orderActionDTO);
                        rollBackOrderAndOrderAction(orders, orderActionDTO, previousOrderActionStatus);
                        return resultDTO;
                    }
                }
            }
        }
        //neu hoan toan k co loi -> commit
        commit(session, transaction, connection);

    } catch (Exception e) {
        rollback(session, transaction, connection);
        Logger.getLogger(StockImportServiceImpl.class.getName()).log(Level.SEVERE, null, e);
        resultDTO.setMessage(e.getMessage());
        resultDTO.setKey(ParamUtils.SYSTEM_OR_DATA_ERROR);
        rollBackOrderAndOrderAction(orders, orderActionDTO, previousOrderActionStatus);
        removeLock(orderActionDTO);
        return resultDTO;
    } finally {
        try {
            if (session.isOpen()) {
                session.close();
            }
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(StockImportServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //
    resultDTO.setQuantitySucc(insertSuccess);
    resultDTO.setQuantityFail(insertFail);
    resultDTO.setId(stockTransId);
    removeLock(orderActionDTO);
    return resultDTO;
}

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

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

    //      Extract attributes we will need
    HttpSession session = request.getSession();
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    Form encounterForm;//from  w w w. j a  va  2  s  .c om
    BaseEncounter encounter = null;
    Map encMap = null;
    Long formId = null;
    Long patientId = null;
    Long eventId = null;
    String constraintClause = null;
    Long constraintLong = null;
    String detailName = null;
    BaseSessionSubject sessionPatient = null;
    Integer maxRows = 0;
    Integer offset = 0;
    Integer prevRows = 0;
    Integer nextRows = 0;
    Connection conn = null;
    String className = null;
    try {
        conn = DatabaseUtils.getZEPRSConnection(username);
        if (request.getParameter("formId") != null) {
            formId = Long.decode(request.getParameter("formId"));
        } else if (request.getAttribute("formId") != null) {
            formId = Long.decode(request.getAttribute("formId").toString());
        }
        if (request.getParameter("className") != null) {
            className = request.getParameter("className");
            formId = (Long) DynaSiteObjects.getFormNameMap().get(className);
        } else if (request.getAttribute("className") != null) {
            className = (String) request.getAttribute("className");
            formId = (Long) DynaSiteObjects.getFormNameMap().get(className);
        }
        if (request.getParameter("constraintClause") != null) {
            constraintClause = request.getParameter("constraintClause");
        } else if (request.getAttribute("constraintClause") != null) {
            constraintClause = request.getAttribute("constraintClause").toString();
        }
        if (request.getParameter("constraintLong") != null) {
            constraintLong = Long.decode(request.getParameter("constraintLong"));
        } else if (request.getAttribute("constraintLong") != null) {
            constraintLong = Long.decode(request.getAttribute("constraintLong").toString());
        }
        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 {
            if (formId != null) {
                switch (formId.intValue()) {
                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;
                }
            } 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 (mapping.getParameter() != null && !mapping.getParameter().equals("")) {
            String formName = mapping.getParameter();
            formId = (Long) DynaSiteObjects.getFormNameMap().get(formName);
        }
        // Admin pages usually do not have a sessionPatient. This is a hack to use code that uses sessionPatient.
        sessionPatient = new TimsSessionSubject();
        SessionUtil.getInstance(session).setSessionPatient(sessionPatient);

        encounterForm = ((Form) DynaSiteObjects.getForms().get(new Long(formId)));
        Long formTypeId = encounterForm.getFormTypeId();
        // populate the records for this class
        List items = null;
        if (className != null && className.equals("MenuItem")) {
            items = DynaSiteObjects.getMenuItemList(); //must be sorted
        } else {
            String classname = StringManipulation.fixClassname(encounterForm.getName());
            Class clazz = null;
            try {
                clazz = Class.forName(Constants.getDynasiteFormsPackage() + "." + classname);
            } catch (ClassNotFoundException e1) {
                if (classname.equals("UserInfo")) {
                    clazz = Class.forName("org.rti.zcore." + classname);
                }
            }

            try {
                String orderBy = "id DESC";
                switch (formTypeId.intValue()) {
                case 5: // admin
                    if (constraintLong != null) {
                        /*if (formId == 161) { // stock
                           // Get the item - form 131
                           Class clazz = Class.forName(DynaSiteObjects.getDynasiteFormsPackage() + ".Item");
                           Item stockItem = (Item) EncountersDAO.getOne(conn, constraintLong, "SQL_RETRIEVE_ONE_ADMIN131", clazz);
                           detailName = stockItem.getField2153();
                           request.setAttribute("detailName", detailName);
                        }*/
                        //String orderBy = "id DESC";
                        items = EncountersDAO.getAllConstraintOrderBy(conn, formId,
                                "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, constraintClause, constraintLong,
                                orderBy);
                    } else {
                        if (formId == 161) { // stock
                            //items = EncountersDAO.getAll(conn, formId, "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, maxRows, offset, "id DESC");
                            if (maxRows == 0) {
                                items = EncountersDAO.getAllOrderBy(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, orderBy);
                            } else {
                                items = EncountersDAO.getAll(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset,
                                        orderBy);
                            }
                        } else if (formId == 128) { // regimen groups
                            //items = EncountersDAO.getAll(conn, formId, "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset, "name ");
                            if (maxRows == 0) {
                                items = EncountersDAO.getAllOrderBy(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, "name ");
                            } else {
                                items = EncountersDAO.getAll(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset,
                                        "name ");
                            }
                        } else if (formId == 129) { // regimen
                            //items = EncountersDAO.getAll(conn, formId, "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset, "code ");
                            if (maxRows == 0) {
                                items = EncountersDAO.getAllOrderBy(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, "code ");
                            } else {
                                items = EncountersDAO.getAll(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset,
                                        "code ");
                            }
                        } else if (formId == 130) { // item groups
                            //items = EncountersDAO.getAll(conn, formId, "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset, "name ");
                            if (maxRows == 0) {
                                items = EncountersDAO.getAllOrderBy(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, "name ");
                            } else {
                                items = EncountersDAO.getAll(conn, formId,
                                        "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset,
                                        "name ");
                            }
                        } else {
                            if (className != null && className.equals("MenuItem")) {
                                items = DynaSiteObjects.getMenuItemList(); //must be sorted
                            } else {
                                if (formId == 181) {
                                    orderBy = "regimen_id DESC";
                                    if (maxRows == 0) {
                                        //items = EncountersDAO.getAllOrderBy(conn, formId, "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, orderBy);
                                        String sql = "SELECT rb.id, rb.regimen_id AS regimen_id, item_id AS item_id, r.code "
                                                + "FROM regimen_item_bridge rb, regimen r "
                                                + "WHERE rb.regimen_id = r.id ORDER BY r.code ASC";
                                        ArrayList values = new ArrayList();
                                        items = DatabaseUtils.getList(conn, clazz, sql, values);
                                    } else {
                                        items = EncountersDAO.getAll(conn, formId,
                                                "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset,
                                                orderBy);
                                    }
                                } else {
                                    if (maxRows == 0) {
                                        items = EncountersDAO.getAllOrderBy(conn, formId,
                                                "SQL_RETRIEVE_ALL_ADMIN" + formId, clazz, orderBy);
                                    } else {
                                        items = EncountersDAO.getAll(conn, formId,
                                                "SQL_RETRIEVE_ALL_ADMIN_PAGER" + formId, clazz, maxRows, offset,
                                                orderBy);
                                    }
                                }
                            }
                        }
                    }
                    break;
                case 8: // list - for patients
                    items = EncountersDAO.getAll(conn, formId, "SQL_RETRIEVEALL" + formId, clazz, maxRows,
                            offset);
                    break;
                default:
                    items = EncountersDAO.getAll(conn, formId, "SQL_RETRIEVE_ALL" + formId, clazz, maxRows,
                            offset);
                    break;
                }
            } catch (IOException e) {
                request.setAttribute("exception", e);
                return mapping.findForward("error");
            } catch (ServletException e) {
                request.setAttribute("exception", e);
                return mapping.findForward("error");
            } catch (SQLException e) {
                request.setAttribute("exception", e);
                return mapping.findForward("error");
            }
        }

        if (maxRows == 0) {
            request.setAttribute("noNavigationWidget", "1");
        } else {
            request.setAttribute("maxRows", maxRows);
            nextRows = offset + maxRows;
            if (items.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);
        }
        // Attach a map of encounter values that has enumerations already resolved.
        Form encForm = (Form) DynaSiteObjects.getForms().get(encounterForm.getId());
        for (int i = 0; i < items.size(); i++) {
            encounter = (EncounterData) items.get(i);
            // Form encForm = (Form) DynaSiteObjects.getForms().get(encounter.getFormId());
            encMap = PatientRecordUtils.getEncounterMap(encForm, encounter, "fieldId");

            encounter.setEncounterMap(encMap);
        }
        if (items.size() > 0) {
            request.setAttribute("chartItems", items);
            request.setAttribute("formId", encounterForm.getId());
            // loading of body onload DWRUtil.useLoadingMessage()
            request.setAttribute("dwr", 1);
        }

        // Process the dynamic dropdown lists.
        HashMap listMap = new HashMap();
        Form inlineForm = null;
        HashMap<Long, StockReport> balanceMap = null;
        if (DynaSiteObjects.getStatusMap().get("balanceMap") != null) {
            balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects.getStatusMap().get("balanceMap");
        }
        for (Iterator iterator = encounterForm.getPageItems().iterator(); iterator.hasNext();) {
            PageItem pageItem = (PageItem) iterator.next();
            FormField formField = pageItem.getForm_field();
            String identifier = formField.getIdentifier();

            if (pageItem.getInputType().equals("dropdown") || pageItem.getInputType().equals("dropdown-add-one")
                    || pageItem.getInputType().equals("dropdown_site")) {
                String dropdownConstraint = null;
                String pageItemDropdownConstraint = pageItem.getDropdownConstraint();
                if (pageItemDropdownConstraint != null && pageItemDropdownConstraint.endsWith("'siteAbbrev'")) {
                    String siteAbbrev = SessionUtil.getInstance(session).getClientSettings().getSite()
                            .getAbbreviation();
                    dropdownConstraint = pageItemDropdownConstraint.replace("'siteAbbrev'",
                            "'" + siteAbbrev + "'");
                } else {
                    dropdownConstraint = pageItemDropdownConstraint;
                }
                List<DropdownItem> list = WidgetUtils.getList(conn, pageItem.getDropdownTable(),
                        pageItem.getDropdownColumn(), dropdownConstraint, pageItem.getDropdownOrderByClause(),
                        DropdownItem.class, pageItem.getFkIdentifier());
                String formName = encForm.getClassname();
                if (formName.equals("StockControl")) {
                    for (DropdownItem dropdownItem : list) {
                        if (balanceMap != null) {
                            String itemIdStr = dropdownItem.getDropdownId();
                            Long itemId = Long.valueOf(itemIdStr);
                            StockReport stockReport = balanceMap.get(itemId);
                            Integer balance = 0;
                            if (stockReport != null) {
                                balance = stockReport.getBalanceBF();
                                String label = dropdownItem.getDropdownValue();
                                if (balance <= 0) {
                                    String value = dropdownItem.getDropdownValue();
                                    dropdownItem
                                            .setDropdownValue(value + " ** Out of Stock ** Bal: " + balance);
                                } else {
                                    dropdownItem.setDropdownValue(label + " Bal: " + balance);
                                }
                            }
                        }
                    }
                }
                listMap.put(pageItem.getId(), list);
                if (pageItem.getInputType().equals("dropdown-add-one")) {
                    String classNameString = StringManipulation.fixClassname(pageItem.getDropdownTable());
                    Long inlineFormId = (Long) DynaSiteObjects.getFormNameMap().get(classNameString);
                    inlineForm = ((Form) DynaSiteObjects.getForms().get(new Long(inlineFormId)));
                    // Create a list of fieldnames for inline forms.
                    ArrayList<String> inlineFields = new ArrayList<String>();
                    for (Iterator iterator2 = inlineForm.getPageItems().iterator(); iterator2.hasNext();) {
                        PageItem pageItem2 = (PageItem) iterator2.next();
                        if (pageItem2.getForm_field().isEnabled() == true
                                && !pageItem2.getForm_field().getType().equals("Display")) {
                            inlineFields.add(pageItem2.getForm_field().getIdentifier());
                        }
                    }
                    request.setAttribute("inlineForm_" + identifier, inlineForm);
                    request.setAttribute("inlineFields_" + identifier, inlineFields);
                    // loading of body onload DWRUtil.useLoadingMessage()
                    request.setAttribute("dwr", 1);
                }
            }
        }

        request.setAttribute("listMap", listMap);

        request.setAttribute("encounterForm", encounterForm);

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

        if (Constants.STOCK_PROBLEMS_ENABLED != null && Constants.STOCK_PROBLEMS_ENABLED.equals("true")) {
            //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);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
    return mapping.findForward("success");
}

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

/**
 * Create record from form.//from www  .j a  v a  2 s.  c o m
 *
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return ActionForward
 * @throws Exception
 */
public ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    HttpSession session = request.getSession();
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    DynaValidatorForm dynaForm = null;
    int formId = 0;
    String formName = mapping.getParameter().trim();
    Long formIdL = (Long) DynaSiteObjects.getFormNameMap().get(formName);
    formId = formIdL.intValue();
    ActionMessages errors = new ActionMessages();

    SessionSubject sessionPatient = null;
    Long patientId = null;
    String eventUuid = null;

    dynaForm = (DynaValidatorForm) form;
    Site site = SessionUtil.getInstance(session).getClientSettings().getSite();
    Long siteId = site.getId();

    // Get a form and flow from the formDef; add them to the encounter
    Form formDef = (Form) DynaSiteObjects.getForms().get(new Long(formId));
    Long formTypeId = formDef.getFormTypeId();
    //FormType formType = formDef.getFormType();
    EncounterData vo = null;
    Connection conn = null;
    try {
        conn = DatabaseUtils.getZEPRSConnection(username);
        if (formDef.isRequireReauth()) {
            try {
                AuthManager.confirmIdentity(conn, request, user.getName(), request.getParameter("password"));
            } catch (UserUnauthorizedException e) {
                errors.add("errors", new ActionMessage("errors.userunauthorized"));
                saveErrors(request, errors);
                try {
                    String forwardName = (String) DynaSiteObjects.getFormNames().get(formName);
                    if (forwardName == null) {
                        return mapping.getInputForward();
                    } else {
                        if (forwardName.equals("demographics")) {
                            return mapping.getInputForward();
                        } else {
                            return mapping.findForward(forwardName + "Error");
                        }
                    }
                } catch (Exception e1) {
                    return mapping.getInputForward();
                }
            }
        }

        if (formName.equals("PatientRegistration")) {
            //ActionMessages errors = new ActionMessages();
            // check if there is a duplicate id
            Object item = dynaForm.get("patient_id_number");
            if (item != null) {
                String zeprsId = (String) item;
                Boolean status = PatientDAO.checkPatientId(conn, zeprsId);
                if (status == Boolean.FALSE) {
                    errors.add("errors", new ActionMessage("errors.duplicateId", zeprsId));
                }
            }
        }

        if (formName.equals("UserInfo")) {
            //ActionMessages errors = new ActionMessages();
            // check if password at least 8 chars
            Object item = dynaForm.get("password");
            if (item != null) {
                String password = (String) item;
                if (password.length() < 8) {
                    errors.add("errors", new ActionMessage("errors.password"));
                }
            }

            // Check for duplicate username
            if (dynaForm.get("username") != null) {
                String searchUsername = (String) dynaForm.get("username");
                Object userObject;
                try {
                    userObject = UserDAO.getUser(conn, searchUsername);
                    errors.add("errors", new ActionMessage("errors.duplicate.username", searchUsername));
                } catch (ObjectNotFoundException e) {
                    // It's ok - there should not be a user.
                }
            }
        }

        //resolve the patientId - it has been either pushed via the request or gathered from the sessionPatient
        if (!formName.equals("PatientRegistration") && formTypeId != 5 && formTypeId != 9) {
            sessionPatient = (SessionSubject) SessionUtil.getInstance(session).getSessionPatient();
            patientId = sessionPatient.getId();
        }

        Long encounterId = null;
        try {
            encounterId = (Long) dynaForm.get("id");
        } catch (IllegalArgumentException e) {
            if (request.getParameter("id") != null) {
                if (!request.getParameter("id").equals("")) {
                    encounterId = Long.valueOf(request.getParameter("id"));
                }
            }
        }

        Map dynaMap = dynaForm.getMap();
        Set encSet = dynaMap.entrySet();
        boolean emptyForm = true;
        //boolean futureDateVisit = false;
        for (Iterator iterator = encSet.iterator(); iterator.hasNext();) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = (String) entry.getKey();
            String value = null;
            try {
                value = (String) entry.getValue();
            } catch (ClassCastException e) {
                if (entry.getValue().getClass().equals("Integer.class")) {
                    Integer valueInt = (Integer) entry.getValue();
                    value = valueInt.toString();
                }
            }

            if ((key.equals("date_visit")) || (key.equals("date_of_record"))) {
                Date dateVisit = Date.valueOf(value);
                Date now = DateUtils.getNow();
                if (dateVisit.getTime() > now.getTime()) {
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
                            Constants.DATE_FORMAT_EXCEL_SHORT);
                    sdf.setTimeZone(TimeZone.getDefault());
                    Date valueDate = Date.valueOf(value);
                    String formattedDate = sdf.format(valueDate.getTime());
                    errors.add("errors", new ActionMessage("errors.invalid.dateVisit.future", formattedDate));
                    saveErrors(request, errors);
                }
            } else {
                if (!value.equals("")) {
                    emptyForm = false;
                }
            }
        }

        if (emptyForm) {
            if (formId == 132) {
                errors.add("errors", new ActionMessage("errors.dispensing.emptyForm"));
            } else {
                errors.add("errors", new ActionMessage("errors.emptyForm"));
            }
            saveErrors(request, errors);
        }

        if (errors.size() > 0) {
            saveErrors(request, errors);
            try {
                String specialFormName = (String) DynaSiteObjects.getFormNames().get("form" + formId);
                if (specialFormName == null) {
                    return mapping.getInputForward();
                } else {
                    if (specialFormName.equals("demographics")) {
                        return mapping.getInputForward();
                    } else {
                        return mapping.findForward(formName + "Error");
                    }
                }
            } catch (Exception e1) {
                return mapping.getInputForward();
            }
        }

        if (formId == 132) { // Patient Dispensary
            //ActionMessages errors = new ActionMessages();
            // loop through the bridge table records
            int recordsPerEncounter = formDef.getRecordsPerEncounter();
            for (int j = 1; j < recordsPerEncounter; j++) {
                String itemIdFieldName = "PBF" + j + "_item_id";
                String quantityDispensedFieldName = "PBF" + j + "_dispensed";
                // get the item_id
                Long itemId = null;
                Integer quantityDispensed = 0;
                if (!dynaForm.getMap().get(itemIdFieldName).equals("")) {
                    itemId = Long.valueOf((String) dynaForm.getMap().get(itemIdFieldName));
                }
                if (!dynaForm.getMap().get(quantityDispensedFieldName).equals("")) {
                    quantityDispensed = Integer
                            .valueOf((String) dynaForm.getMap().get(quantityDispensedFieldName));
                }
                Integer currentBalance = 0;
                Integer possiblebalance = 0;
                if (itemId != null) {
                    if (DynaSiteObjects.getStatusMap().get("balanceMap") != null) {
                        HashMap<Long, StockReport> balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects
                                .getStatusMap().get("balanceMap");
                        StockReport stockReport = balanceMap.get(itemId);
                        //tempStockControl = InventoryDAO.getCurrentStockBalance(conn, itemId, siteId.intValue());
                        if (stockReport != null) {
                            currentBalance = stockReport.getBalanceBF();
                        }
                        possiblebalance = currentBalance - quantityDispensed;
                        dynaForm.getMap().put("balance", possiblebalance);
                    }
                    processBalanceMessages(conn, errors, itemId, currentBalance, possiblebalance, true);
                }
            }
            if (errors.size() > 0) {
                saveErrors(request, errors);
                try {
                    String specialFormName = (String) DynaSiteObjects.getFormNames().get("form" + formId);
                    if (specialFormName == null) {
                        return mapping.getInputForward();
                    } else {
                        if (specialFormName.equals("demographics")) {
                            return mapping.getInputForward();
                        } else {
                            return mapping.findForward(formName + "Error");
                        }
                    }
                } catch (Exception e1) {
                    return mapping.getInputForward();
                }
            }
        }

        if (formId == 161) { // stock_control
            Integer value = 0;
            Integer balance = 0;
            Integer tempStockControlBalance = 0;
            Long itemId = null;
            // get the item_id
            if (!dynaForm.getMap().get("item_id").equals("")) {
                itemId = Long.valueOf((String) dynaForm.getMap().get("item_id"));
            }

            if (DynaSiteObjects.getStatusMap().get("balanceMap") != null) {
                HashMap<Long, StockReport> balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects
                        .getStatusMap().get("balanceMap");
                StockReport stockReport = balanceMap.get(itemId);
                //tempStockControl = InventoryDAO.getCurrentStockBalance(conn, itemId, siteId.intValue());
                if (stockReport != null) {
                    tempStockControlBalance = stockReport.getBalanceBF();
                }
            }
            // set the last_patient_item_id hidden field
            //dynaForm.getMap().put("last_patient_item_id", tempStockControl.getLast_patient_item_id());
            // change the current stock balance based on the fields in this submission
            if (!dynaForm.getMap().get("type_of_change").equals("")) {
                Integer typeOfStock = Integer.valueOf((String) dynaForm.getMap().get("type_of_change"));
                if (!dynaForm.getMap().get("change_value").equals("")) {
                    value = Integer.valueOf((String) dynaForm.getMap().get("change_value"));
                }
                switch (typeOfStock) {
                // Received
                case 3263:
                    balance = tempStockControlBalance + value;
                    break;
                // Issued
                case 3264:
                    balance = tempStockControlBalance - value;
                    break;
                // Losses
                case 3265:
                    balance = tempStockControlBalance - value;
                    break;
                // Pos. Adjust.
                case 3266:
                    balance = tempStockControlBalance + value;
                    break;
                // Neg. Adjust
                case 3267:
                    balance = tempStockControlBalance - value;
                    break;
                default:
                    balance = value;
                    break;
                }
            } else {
                balance = value;
            }

            processBalanceMessages(conn, errors, itemId, tempStockControlBalance, balance, false);

            if (errors.size() > 0) {
                saveErrors(request, errors);
                try {
                    String specialFormName = (String) DynaSiteObjects.getFormNames().get("form" + formId);
                    if (specialFormName == null) {
                        return mapping.getInputForward();
                    } else {
                        if (specialFormName.equals("demographics")) {
                            return mapping.getInputForward();
                        } else {
                            return mapping.findForward(formName + "Error");
                        }
                    }
                } catch (Exception e1) {
                    return mapping.getInputForward();
                }
            }

            // set the balance hidden field
            dynaForm.getMap().put("balance", balance);

            // reset the lowStockItems
            /*if (Constants.LOW_STOCK_WARNING_QUANTITY != null) {
               List<Task> lowStockItems = null;
               if (DynaSiteObjects.getStatusMap().get("lowStockItems") != null) {
                  lowStockItems = (List<Task>) DynaSiteObjects.getStatusMap().get("lowStockItems");
               }
               if (lowStockItems != null) {
                  int i = 0;
                  int itemToRemove = 0;
                  for (Task lowStockTask : lowStockItems) {
             i++;
             Long lowStockItemId = lowStockTask.getId();
             if (itemId.intValue() == lowStockItemId.intValue()) {
                itemToRemove = i;
                break;
             }
                  }
                  if (itemToRemove > 0) {
             lowStockItems.remove(i-1);
                  }
               }
            }*/
        }

        // We need to calculate tempStockControl's balance field a couple of times.
        StockControl tempStockControl = null;
        Map formData = dynaForm.getMap();
        try {
            if (formId == 128 || formId == 129 || formId == 130 || formId == 131 || formId == 181) {
                vo = DarFormDAO.saveForm(conn, formDef, String.valueOf(formId), patientId, formData,
                        encounterId, siteId, username, sessionPatient);
            } else {
                vo = PopulatePatientRecord.saveForm(conn, formDef, String.valueOf(formId), patientId, formData,
                        encounterId, siteId, username, sessionPatient);
            }
            if (formId == 161) {
                StockControl sc = (StockControl) vo;
                Long itemId = sc.getItem_id();
                StockControlDAO.prepareStockforAlertList(conn, sc, null, itemId);
            }
            if (formId == 132) { // Patient Dispensary
                // we're processing this item here because we don't really need to do it in EncounterProcessor,
                // but we do need the id of the recently-saved record.
                // loop through the bridge table records
                int recordsPerEncounter = formDef.getRecordsPerEncounter();
                for (int j = 1; j < recordsPerEncounter; j++) {
                    String itemIdFieldName = "PBF" + j + "_item_id";
                    String quantityDispensedFieldName = "PBF" + j + "_dispensed";
                    // get the item_id
                    Long itemId = null;
                    Integer quantityDispensed = null;
                    if (!formData.get(itemIdFieldName).equals("")) {
                        itemId = Long.valueOf((String) formData.get(itemIdFieldName));
                    }
                    if (!formData.get(quantityDispensedFieldName).equals("")) {
                        quantityDispensed = Integer.valueOf((String) formData.get(quantityDispensedFieldName));
                    }
                    if (itemId != null) {
                        //if (tempStockControl == null) {
                        tempStockControl = InventoryDAO.getCurrentStockBalance(conn, itemId, null);
                        //}
                        Integer currentBalance = tempStockControl.getBalance();

                        HashMap<Long, StockReport> balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects
                                .getStatusMap().get("balanceMap");
                        StockReport stockReport = balanceMap.get(itemId);
                        if (stockReport != null) {
                            stockReport.setBalanceBF(currentBalance);
                            stockReport.setOnHand(currentBalance);
                            balanceMap.put(itemId, stockReport);
                        }
                        Integer lowStockWarning = Integer.valueOf(Constants.LOW_STOCK_WARNING_QUANTITY);
                        //Integer possiblebalance = currentBalance - quantityDispensed;
                        if (currentBalance <= 0) {
                            // first check if the most recent record for this item is an out-of-stock warning = 3279
                            try {
                                StockControl outOfStock = InventoryDAO.getMostRecentOutOfStock(conn, itemId,
                                        null);
                                // if record exists, we're ok
                            } catch (ObjectNotFoundException e) {
                                try {
                                    Date visitDateD = null;
                                    if (formData != null) {
                                        //String formName = StringManipulation.fixClassname(formDef.getName());
                                        visitDateD = DateUtils.getVisitDate(formData, formName);
                                    } else {
                                        visitDateD = DateUtils.getNow();
                                    }
                                    InventoryDAO.createOutOfStockRecord(conn, formDef, String.valueOf(formId),
                                            patientId, siteId, username, sessionPatient, vo, itemId,
                                            quantityDispensed, visitDateD);
                                } catch (Exception e2) {
                                    log.error(e2);
                                }
                            }
                        }
                    }
                }
                // refreshes the StockAlertList.
                StockControlDAO.setStockAlertList(conn, null);
            }
        } catch (Exception e) {
            log.debug("formData: " + formData);
            log.error(
                    "Error saving record - formId: " + formId + ", patientId: " + patientId + ", encounterId: "
                            + encounterId + ", siteId: " + siteId + ", username: " + username + " Error: " + e);
            if (sessionPatient == null) {
                log.error("Error saving record - null sessionPatient");
            }
            e.printStackTrace();
            if (!conn.isClosed()) {
                conn.close();
                conn = null;
            }
            request.setAttribute("exception", e);
            return mapping.findForward("error");
        }

        String menuItemText = null;
        if (formName.equals("MenuItem")) {
            menuItemText = StringManipulation.escapeString(dynaForm.get("textLink").toString());
            menuItemText = StringManipulation.fixFirstDigit(menuItemText);
            dynaForm.set("templateKey", Constants.MENUITEM_PROPERTY_PREFIX + "." + menuItemText);
        }

        //Forms that don't require patient(including admin forms) don't need the session refreshed since they aren't patient oriented
        // Submitting the PatientRegistration form does need the TimsSessionSubject initialised.
        if (formDef.isRequirePatient() == true || formName.equals("PatientRegistration")
                || formName.equals("PerpetratorDemographics")) {
            try {
                SessionPatientDAO.updateSessionPatient(conn, vo.getPatientId(), vo.getEventUuid(), session);
                // re-initialize a few vars
                sessionPatient = (SessionSubject) SessionUtil.getInstance(session).getSessionPatient();
                eventUuid = sessionPatient.getCurrentEventUuid();
                patientId = sessionPatient.getId();
            } catch (ObjectNotFoundException e) {
                // clear out session patient - it's null
                SessionUtil.getInstance(session).setSessionPatient(null);
            }
        }
        // Reset form
        form.reset(mapping, request);
        StrutsUtils.removeFormBean(mapping, request);
    } catch (ServletException e) {
        log.error(e);
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }

    /**
     * Forwards section - send user to the next form
     */

    return createForward(request, mapping, patientId, eventUuid, dynaForm, session, formId, vo);
}

From source file:com.viettel.logistic.wms.service.StockImportServiceImpl.java

@Override
public ResultDTO synImportStockCust(StockTransDTO stockTransDTO) {
    //Do KPI//w w w  .j  a va 2  s  .c  o m
    KpiLogDTO synKpiLog = new KpiLogDTO();
    String sStartTime = DateUtil.sysdateString();
    String functionCode;
    String reason;
    String strResult = "";
    String descr;
    String transactionCode = null;
    synKpiLog.setStartTime(sStartTime);
    synKpiLog.setCreateDatetime(sStartTime);
    //Ket thuc khoi tao doi tuong do kpi
    String stockTransDetailId;
    List<StockTransSerialDTO> filterListStockTransSerialDTO;
    String stockTransCode;
    String stockTransSEQ;
    ResultDTO resultDTO = new ResultDTO();
    resultDTO.setMessage(ParamUtils.SUCCESS);
    Map<String, GoodsDTO> mapGoodsDTO;

    int insertSuccess = 0;
    int insertFail = 0;
    Double amountIssue;
    //
    String stockTransId = "";
    String sysdate;
    //INIT TRANSACTION
    Session session;
    Transaction transaction;
    Connection connection = null;
    session = sessionFactory.openSession();
    transaction = session.getTransaction();
    transaction.begin();
    //
    sysdate = stockGoodsBusiness.getSysDate(formatDate);
    GoodsDTO goodsDTO;
    //du lieu cho dong bo bccs
    OrdersDTO ordersDTO = null;
    long startTime = System.currentTimeMillis();
    long time;
    //=====================================        
    List<StockTransDetailDTO> lstStockTransDetail = new ArrayList<>();
    List<StockTransDetailDTO> lstStockTransDetailDTOsImportAndUpdate = new ArrayList<>();
    //DUYOT: 27/01/2016: loc ra danh sach hang kit
    for (StockTransDetailDTO i : stockTransDTO.getLstStockTransDetailDTO()) {
        //Neu TH nhap kit --> se truyen vao transfersGoodsCode la code cua hang hoa sim--> Thuc hien xuat sim va nhap kit
        if (!DataUtil.isStringNullOrEmpty(i.getTransfersGoodsCode())) {
            lstStockTransDetailDTOsImportAndUpdate.add(i);
        } else {
            lstStockTransDetail.add(i);
        }
    }

    //DUYOT: 28/01/2016: check lai trang thai cua yeu cau - lenh---------------------
    //CHECK THONG TIN YEU CAU - LENH CO TRANG THAI HOP LE-------------------
    String orderIdList = stockTransDTO.getOrderIdList();
    if (orderIdList == null || orderIdList.equals("")) {
        resultDTO.setMessage(ParamUtils.FAIL);
        resultDTO.setKey(ParamUtils.ERROR_MESSAGE.ORDER_IE);
        return resultDTO;
    }
    try {
        ordersDTO = WSOrders.findOrderById(orderIdList);
    } catch (Exception ex) {
        Logger.getLogger(StockImportServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (ordersDTO != null && ORDER_STATUS_IMPORTED_EXPORTED.equalsIgnoreCase(ordersDTO.getOrderStatus())) {
        resultDTO.setMessage(ParamUtils.FAIL);
        resultDTO.setKey(ParamUtils.ERROR_MESSAGE.ORDER_IE);
        return resultDTO;
    }
    //---------------------------------------------------------------------------------
    //
    functionCode = "CREATE_BILL_IMPORT_LOG";
    if (ordersDTO != null) {
        transactionCode = ordersDTO.getOrderCode();
    }
    try {
        //-------------------------------------------------------------------  
        //1. KHOI TAO CONNECTION
        //-------------------------------------------------------------------    
        SessionFactory sessionFactoryBatch = session.getSessionFactory();
        connection = sessionFactoryBatch.getSessionFactoryOptions().getServiceRegistry()
                .getService(ConnectionProvider.class).getConnection();
        connection.setAutoCommit(false);
        //-------------------------------------------------------------------
        //THUC HIEN GIAO DICH THU HOI DOI VOI HANG KIT ( XUAT SIM -> NHAP KIT)-----------------
        if (!DataUtil.isListNullOrEmpty(lstStockTransDetailDTOsImportAndUpdate)) {
            System.out.println("LOG: BAT DAU THUC HIEN DONG BO NHAP KIT");
            StockTransDTO exportStockTransDTO = (StockTransDTO) DataUtil.cloneObject(stockTransDTO);
            exportStockTransDTO.setStockTransStatus(ParamUtils.TRANS_STATUS.WAITING_IMPORT);
            //duyot 27/01/2016
            //tao danh sach serial cho tat cat hang hoa -> loc sau
            List<StockTransSerialDTO> lstStockTransSerialDTO = new ArrayList<>();
            int countTemp = 0;
            for (StockTransDetailDTO i : lstStockTransDetailDTOsImportAndUpdate) {
                //set lai lst temp de filter
                String temp = countTemp + "";
                i.setTmpStockTransDetailId(temp);
                //
                List<StockTransSerialDTO> lstSerialInDetail = i.getLstStockTransSerialDTO();
                for (StockTransSerialDTO j : lstSerialInDetail) {
                    j.setTmpStockTransDetailId(temp);
                    lstStockTransSerialDTO.add(j);
                }
                //                    lstStockTransSerialDTO.addAll(lstSerialInDetail);
                countTemp++;
            }
            //
            exportStockTransDTO.setStockTransType("2");
            exportStockTransDTO.setStockTransId(null);
            //Lay danh sach goods code tu transfersGoodsCode
            String goodsCodeList = getGoodsCodeList(lstStockTransDetailDTOsImportAndUpdate);
            List<ConditionBean> lstConditionBean = new ArrayList<>();
            lstConditionBean.add(new ConditionBean("custId", ParamUtils.OP_EQUAL, stockTransDTO.getCustId(),
                    ParamUtils.TYPE_NUMBER));
            lstConditionBean
                    .add(new ConditionBean("code", ParamUtils.OP_IN, goodsCodeList, ParamUtils.TYPE_STRING));
            List<GoodsDTO> lstGoodsDTO = goodsBusiness.searchByConditionBean(lstConditionBean, 0,
                    Integer.MAX_VALUE, "", "code");
            //DAY VAO MAP DANH SACH HANG HOA
            Map<String, GoodsDTO> mapGoodsCode2DTO = DataUtil.putGoodsCodeToMap(lstGoodsDTO);
            ResultDTO result;
            // Map giua hang da xuat -> danh sach stock_goods cua hang do
            Map<String, List<StockGoods>> mapStockgoods = new HashMap<>();
            Map<String, List<StockGoodsSerialStrip>> mapSerialTrip = new HashMap<>();
            //Danh sach sim trang se xuat kho
            List<StockTransDetailDTO> lstExportDetail = DataUtil
                    .cloneList(lstStockTransDetailDTOsImportAndUpdate);
            GoodsDTO goods;
            for (StockTransDetailDTO o : lstExportDetail) {
                goods = mapGoodsCode2DTO.get(o.getTransfersGoodsCode());
                o.setGoodsCode(goods.getCode());
                o.setGoodsId(goods.getGoodsId());
                o.setGoodsName(goods.getName());
            }
            //1--> BEGIN TRANS
            /*
            - khi da xuat hang -> dua ra map hang da ban cho phan nhap
            */
            //-->2 THUC HIEN GIAO DICH XUAT MAT HANG SIM TRANG
            result = exportStockGoodsTransfer(exportStockTransDTO, lstExportDetail,
                    DataUtil.cloneList(lstStockTransSerialDTO), session, transaction, mapStockgoods,
                    mapSerialTrip);
            if (!result.getMessage().equals(ParamUtils.SUCCESS)) {
                return result;
            }
            //-->3 THUC HIEN GIAO DICH NHAP KIT DUOC XUAT TU SIM TRANG
            //1. Cap nhat vao transaction
            //set fromstocktransid
            stockTransDTO.setFromStockTransId(result.getId());
            //
            List<GoodsInTicketDTO> lstGoods = new ArrayList<>();
            stockTransDTO.setStockTransStatus(ParamUtils.TRANS_STATUS.WAITING_IMPORT);
            result = importStockGoodsTransfer(stockTransDTO, lstStockTransDetailDTOsImportAndUpdate,
                    lstExportDetail, DataUtil.cloneList(lstStockTransSerialDTO),
                    DataUtil.cloneList(lstStockTransSerialDTO), session, transaction, mapStockgoods,
                    mapSerialTrip, lstGoods);
            if (!result.getMessage().equals(ParamUtils.SUCCESS)) {
                return result;
            }
            stockTransId = result.getId();
        }
        //END QUYENDM: KET THUC NHAP KIT-------------------------------------------------------------
        //Ghi log ra file KPI        
        String synSys = Constants.TYPE_ORDERS_BCCS.equalsIgnoreCase(ordersDTO.getSourceOrder()) ? "BCCS"
                : "KTTS";
        String description = "Viet phieu nhap dong bo " + synSys + "| YC: " + orderIdList;
        System.out.println(DateUtil.sysdateString() + " | " + description);
        //DOI VOI HANG HOA KHONG PHAI LA HANG KIT---------------------------------------------------
        if (!DataUtil.isListNullOrEmpty(lstStockTransDetail)) {
            //Kiem tra xem giao dich nhap thu hoi hay nhap moi
            if (ordersDTO.getInputType() != null && !ordersDTO.getInputType().equalsIgnoreCase("1")) {
                //Begin - ThienNG1 - NEU LA GIAO DICH THU HOI
                //                    resultDTO = reSyncImportRecovered(stockTransDTO, Constants.STATUS_SERIAL_WAIT_STOCK, session, transaction);
                //Begin - QuyenDM 20160413 - VIET LAI GIAO DICH THU HOI
                //----------------------------------------
                //1. KHOI TAO CONNECTION                    
                resultDTO = reSyncImportRecovered(stockTransDTO, Constants.STATUS_SERIAL_WAIT_STOCK, connection,
                        session);
                if (!resultDTO.getMessage().equalsIgnoreCase(ParamUtils.SUCCESS)) {
                    rollback(session, transaction, connection);
                    return resultDTO;
                }

                //End - QuyenDM 20160413 - VIET LAI GIAO DICH THU HOI
            } else {
                //NEU LA NHAP HANG BT
                //INSERT GIAO DICH STOCK_TRANS
                stockTransSEQ = stockTransBusiness.getSequence("STOCK_TRANS_SEQ");
                stockTransCode = ParamUtils.CODE_IMPORT_STOCK + stockTransSEQ;
                stockTransDTO.setStockTransCode(stockTransCode);
                stockTransDTO.setCreateDatetime(sysdate);
                stockTransDTO.setStockTransDate(sysdate);
                stockTransDTO.setStockTransId(stockTransSEQ);
                //                    resultDTO = stockTransBusiness.createObjectSession(stockTransDTO, session);
                resultDTO = commonBusinessInterface.insertStockTrans(stockTransDTO, connection);

                stockTransId = stockTransDTO.getStockTransId();
                stockTransDTO.setStockTransId(stockTransId);
                if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                    rollback(session, transaction, connection);
                    return resultDTO;
                }
                //DAY VAO MAP DANH SACH HANG HOA
                String goodsIdList = getGoodsIdList(lstStockTransDetail);
                List<ConditionBean> lstConditionBean = new ArrayList<>();
                lstConditionBean.add(new ConditionBean("custId", ParamUtils.OP_EQUAL, stockTransDTO.getCustId(),
                        ParamUtils.TYPE_NUMBER));
                lstConditionBean.add(
                        new ConditionBean("goodsId", ParamUtils.OP_IN, goodsIdList, ParamUtils.TYPE_NUMBER));
                List<GoodsDTO> lstGoodsDTO = goodsBusiness.searchByConditionBean(lstConditionBean, 0,
                        Integer.MAX_VALUE, "", "code");
                mapGoodsDTO = DataUtil.putGoodsToMap(lstGoodsDTO);
                //LOOP: CHI TIET CHO TUNG MAT HANG
                for (StockTransDetailDTO stockTransDetailDTO : lstStockTransDetail) {
                    //lay seq
                    String stockTransDetailSEQ = stockTransDetailBusiness.getSequence("STOCK_TRANS_DETAIL_SEQ");
                    stockTransDetailDTO.setStockTransId(stockTransId);
                    stockTransDetailDTO.setStockTransDetailId(stockTransDetailSEQ);
                    stockTransDetailDTO.setStockTransDate(sysdate);
                    stockTransDetailDTO.setCreateDatetime(sysdate);
                    goodsDTO = mapGoodsDTO.get(stockTransDetailDTO.getGoodsId());
                    if (goodsDTO == null) {
                        rollback(session, transaction, connection);
                        resultDTO.setMessage(ParamUtils.GOODS_IS_NOT_EXIST);
                        resultDTO.setKey(ParamUtils.GOODS_IS_NOT_EXIST);
                        return resultDTO;
                    }
                    //INSERT CHI TIET GIAO DICH KHO STOCK_TRANS_DETAIL
                    stockTransDetailDTO.setGoodsCode(goodsDTO.getCode());
                    stockTransDetailDTO.setGoodsName(goodsDTO.getName());
                    stockTransDetailDTO.setGoodsIsSerial(goodsDTO.getIsSerial());
                    stockTransDetailDTO.setGoodsIsSerialStrip(goodsDTO.getIsSerialStrip());
                    //------
                    resultDTO = commonBusinessInterface.insertStockTransDetail(stockTransDetailDTO, connection);
                    //-------------
                    stockTransDetailDTO.setStockTransDetailId(stockTransDetailSEQ);
                    stockTransDetailId = stockTransDetailSEQ;
                    //
                    if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                        rollback(session, transaction, connection);
                        resultDTO.setMessage(Constants.ERROR_MESSAGE.INSERT_STOCK_TRANS_DETAIL_ERROR);
                        resultDTO.setKey(Constants.ERROR_MESSAGE.INSERT_STOCK_TRANS_DETAIL_ERROR);
                        return resultDTO;
                    }
                    //MAT HANG K THEO SERIAL
                    if (!stockTransDetailDTO.getGoodsIsSerial().equals(Constants.IS_SERIAL)) {
                        //Cap nhat mat hang theo so luong STOCK_GOODS
                        resultDTO = importStockGoods(stockTransDTO, stockTransDetailDTO, session,
                                ParamUtils.GOODS_IMPORT_STATUS.WAITING_IMPORT);
                        if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                            rollback(session, transaction, connection);
                            return resultDTO;
                        }
                    } else //MAT HANG QUAN LY THEO SERIAL
                    {
                        //LAY RA DANH SACH SERIAL CUA HANG HOA TUONG UNG
                        filterListStockTransSerialDTO = stockTransDetailDTO.getLstStockTransSerialDTO();
                        if (filterListStockTransSerialDTO == null || filterListStockTransSerialDTO.size() < 1) {
                            resultDTO.setMessage(ParamUtils.FAIL);
                            resultDTO.setKey(ParamUtils.SYSTEM_OR_DATA_ERROR);
                            rollback(session, transaction, connection);
                            return resultDTO;
                        }
                        //Insert giao dich chi tiet serial
                        amountIssue = 0D;
                        //khoi tao list serial duoc nhap kho cho mat hang nay
                        for (StockTransSerialDTO stockTransSerialDTO : filterListStockTransSerialDTO) {
                            //Cap nhat Id giao dich, ID chi tiet giao dichj
                            stockTransSerialDTO.setStockTransId(stockTransId);
                            stockTransSerialDTO.setStockTransDetailId(stockTransDetailId);
                            stockTransSerialDTO.setStockTransDate(sysdate);
                            stockTransSerialDTO.setCreateDatetime(sysdate);
                            stockTransSerialDTO.setGoodsCode(goodsDTO.getCode());
                            stockTransSerialDTO.setGoodsName(goodsDTO.getName());
                        }
                        //Insert batch VAO KHO STOCK_GOODS_SERIAL
                        resultDTO = importStockGoodsListSerial(stockTransDTO, stockTransDetailDTO,
                                filterListStockTransSerialDTO, session, connection,
                                ParamUtils.GOODS_IMPORT_STATUS.WAITING_IMPORT);
                        insertSuccess = insertSuccess + resultDTO.getQuantitySucc();
                        insertFail = insertFail + resultDTO.getQuantityFail();
                        amountIssue = resultDTO.getAmountIssue();
                        //

                        if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                            rollback(session, transaction, connection);
                            return resultDTO;
                        }
                        //KIEM TRA SO LUONG UPDATE SERIAL -> NEU CO LOI -> DAU RA THONG BAO
                        if (insertFail > 0) {
                            resultDTO.setQuantitySucc(insertSuccess);
                            resultDTO.setQuantityFail(insertFail);
                            resultDTO.setId(stockTransId);
                            resultDTO.setMessage(Constants.ERROR_MESSAGE.IS_OVERLAP);
                            rollback(session, transaction, connection);
                            return resultDTO;
                        }
                        //END FOR FILTER LIST
                        //CAP NHAT LAI STOCK_TRANS_DETAIL VOI SO LUONG INSERT THANH CONG
                        stockTransDetailDTO.setAmountReal(amountIssue.toString().replace(".0", ""));
                        int isUpdate = stockGoodsSerialBusiness2.updateStockTransDetail(stockTransDetailId,
                                amountIssue, connection);
                        //neu update khong thanh cong
                        if (isUpdate < 1) {
                            resultDTO.setMessage(ParamUtils.FAIL);
                            resultDTO.setKey("UPDATE_STOCK_TRANS_DETAIL_ERROR");
                            rollback(session, transaction, connection);
                            return resultDTO;
                        }
                    }
                } //KET THUC NHAP HANG BT
                  //
            } //KET THUC NHHAP K PHAI KIT
        }
        //DUYOT: KET THUC: GOI HAM DONG BO--------------------------------------
        /*
             duyot: dong bo sang bccs: gui thong tin thuc nhap
             1. lay ra thong tin nhap kho theo format: billstock-listgoods-list serial
             2. goi sang service bccs
             3. check ket qua tra ve
             */
        resultDTO = getListOrdersTicket(stockTransDTO, ordersDTO, connection, session);
        if (!ParamUtils.SUCCESS.equals(resultDTO.getMessage())) {
            rollback(session, transaction, connection);
            //                    resultDTO.setMessage(ParamUtils.FAIL);
            resultDTO.setKey(ParamUtils.ERROR_MESSAGE.SYNC_FAIL);
            return resultDTO;
        }
        //neu hoan toan k co loi -> commit
        commit(session, transaction, connection);

    } catch (Exception e) {
        rollback(session, transaction, connection);
        Logger.getLogger(StockImportServiceImpl.class.getName()).log(Level.SEVERE, null, e);
        resultDTO.setMessage(e.getMessage());
        resultDTO.setKey(ParamUtils.SYSTEM_OR_DATA_ERROR);
        return resultDTO;
    } finally {
        time = System.currentTimeMillis() - startTime;
        //Ghi ra file KPI.log
        if (resultDTO.getMessage() != null) {
            strResult = resultDTO.getMessage().equalsIgnoreCase(null) ? resultDTO.getKey()
                    : resultDTO.getMessage();
        }
        //Ghi ra file Catalina.out  
        //Ghi log ra file KPI        
        synKpiLog.setFunctionCode(functionCode);
        synKpiLog.setTransactionCode(transactionCode);
        descr = "Tong thoi gian viet phieu nhap " + transactionCode + " : " + time;
        System.out.println(descr);
        KPILogger.createLogs(descr);
        if (!strResult.equalsIgnoreCase(ParamUtils.SUCCESS)) {
            reason = resultDTO.getMessage();
            synKpiLog.setReason(reason);
            synKpiLog.setStockTransStatus(SYN_FAIL);
        } else {
            synKpiLog.setStockTransStatus(SYN_SUCC);
        }
        synKpiLog.setEndTime(DateUtil.sysdateString());
        synKpiLog.setDuration(String.valueOf(time));
        synKpiLog.setDescription("Tao phieu nhap dong bo tren HT LOG");
        //Ghi ra bang kpi_log
        kpiLogBusiness.createKpiLog(synKpiLog);
        try {
            if (session.isOpen()) {
                session.close();
            }
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(StockImportServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //
    resultDTO.setQuantitySucc(insertSuccess);
    resultDTO.setQuantityFail(insertFail);
    resultDTO.setId(stockTransId);

    return resultDTO;

}

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

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

    /*if (SystemStateManager.getCurrentState() != SystemStateManager.STATUS_NORMAL) {
    return mapping.findForward(LOCKED_FORWARD);
    }*///from w  ww  .  j  a  va2s.co m

    HttpSession session = request.getSession();
    Principal user = request.getUserPrincipal();
    Locale locale = getLocale(request);
    Locale sessionLocale = (Locale) request.getAttribute("sessionLocale");
    String sessionLocaleString = null;
    if ((sessionLocale.getLanguage() != null)
            && ((sessionLocale.getCountry() != null) && (!sessionLocale.getCountry().equals("")))) {
        sessionLocaleString = sessionLocale.getLanguage() + "_" + sessionLocale.getCountry();
    } else if (sessionLocale.getLanguage() != null) {
        sessionLocaleString = sessionLocale.getLanguage();
    }
    String username = user.getName();
    Connection conn = null;
    Form encounterForm;
    BaseEncounter encounter = null;
    Map encMap = null;
    try {
        conn = DatabaseUtils.getZEPRSConnection(username);

        String formName = null;
        String encounterIdString = "";

        if (mapping.getParameter() != null && !mapping.getParameter().equals("")) {
            formName = mapping.getParameter();
            if (request.getAttribute("encounterId") != null) {
                encounterIdString = request.getAttribute("encounterId").toString();
            }
        } else {
            formName = request.getAttribute("id").toString();
        }

        // Sometimes encounterId is sent in url
        if (request.getParameter("encounterId") != null) {
            encounterIdString = request.getParameter("encounterId").toString();
        }

        DarSessionSubject sessionPatient = null;
        Long patientId = null;
        //Long eventId = null;
        String eventUuid = null;

        if (request.getParameter("next") != null) {
            String next = request.getParameter("next");
            request.setAttribute("next", next);
        }

        String fixName = StringManipulation.fixClassname(formName);
        Long formId = (Long) DynaSiteObjects.getFormNameMap().get(fixName);
        encounterForm = ((Form) DynaSiteObjects.getForms().get(new Long(formId)));

        String siteId = "";
        try {
            siteId = SessionUtil.getInstance(session).getClientSettings().getSiteId().toString();
        } catch (SessionUtil.AttributeNotFoundException e) {
            // it's ok - we're in admin mode.
        }

        if (!formName.equals("PatientRegistration") && !formName.equals("PerpetratorDemographics")
                && encounterForm.getFormTypeId() != 5) {
            try {
                sessionPatient = (DarSessionSubject) SessionUtil.getInstance(session).getSessionPatient();
                patientId = sessionPatient.getId();
                //eventId = sessionPatient.getCurrentEventId();
                eventUuid = sessionPatient.getCurrentEventUuid();
            } catch (SessionUtil.AttributeNotFoundException e) {
                log.error("Unable to get SessionSubject for " + formName);
            }
        } else {
            if (request.getParameter("patientId") != null) {
                patientId = Long.valueOf(request.getParameter("patientId"));
                try {
                    sessionPatient = (DarSessionSubject) SessionUtil.getInstance(session).getSessionPatient();
                } catch (SessionUtil.AttributeNotFoundException e) {
                    log.error("Unable to get TimsSessionSubject");
                }
                //eventId = sessionPatient.getCurrentEventId();
                eventUuid = sessionPatient.getCurrentEventUuid();
            }
        }

        HashMap visiblePageItems = new HashMap();
        if (request.getParameter("id") != null) {
            encounterIdString = request.getParameter("id");
        }
        boolean drugList = false;

        String newform = "";
        if (request.getAttribute("newform") != null) {
            newform = (String) request.getAttribute("newform");
        }

        // Editing a form?
        if (!encounterIdString.equals("")) {
            Long encounterId = new Long(encounterIdString);
            String className = Constants.getDynasiteFormsPackage() + "."
                    + StringManipulation.fixClassname(encounterForm.getName());
            Class clazz = null;
            try {
                clazz = Class.forName(className);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            if (encounterForm.getFormTypeId() == 6) { // patient bridge table form
                encounter = PatientBridgeTableDAO.getEncounter(conn, encounterForm, formId, encounterId, clazz);
                Long encSiteId = encounter.getSiteId();
                if (encSiteId != null) {
                    Site site = (Site) DynaSiteObjects.getClinicMap().get(encSiteId);
                    if (site != null) {
                        encounter.setSiteName(site.getName());
                    }
                }
            } else {
                try {
                    encounter = populateEncounterI18n(request, sessionLocale, sessionLocaleString, conn,
                            encounterForm, formId, encounterId, clazz);
                    encMap = PatientRecordUtils.getEncounterMap(encounterForm, encounter, "fieldId");
                    encounter.setEncounterMap(encMap);
                } catch (ObjectNotFoundException e) {
                    String errorMessage = "<p>An error has occurred. The system was unable to retrieve the requested record. "
                            + "Please press the \"Back\" button and try another link.</p>"
                            + "<p>This error has been logged by the system.</p>";
                    String logMessage = errorMessage + "\n * Code is from FormDisplayAction."
                            + "\n * Debug: encounterId: " + encounterId + ", class: " + clazz + "Error: " + e;
                    log.error(logMessage);
                    log.error(e);
                    request.setAttribute("exception", errorMessage);
                    return mapping.findForward("error");
                }

                DynaValidatorForm dynaForm = (DynaValidatorForm) form;
                // used to store values used in multiselect tag
                HashMap multiValues = new HashMap();

                // Section Map is used to reveal hidden fields that have values
                // Should reveal all values in case user needs to enter data for one of the hidden fields
                Map formSection = (Map) DynaSiteObjects.getFormSections().get(encounterForm.getId());
                Map formDependencies = (Map) DynaSiteObjects.getFormDependencies().get(encounterForm.getId());
                Map collapsingSections = (Map) DynaSiteObjects.getCollapsingSections()
                        .get(encounterForm.getId());
                Map collapsingDependencies = (Map) DynaSiteObjects.getCollapsingDependencies()
                        .get(encounterForm.getId());
                // Loop through the pageItems and use the encounterMap to identify the pageItems that have values
                // If it has a value, use the sectionMap to make that section visible.
                Long section = null;
                Long collapsingTableId = null;
                // Set newPageItems = new TreeSet(new DisplayOrderComparator());
                for (Iterator iterator = encounterForm.getPageItems().iterator(); iterator.hasNext();) {
                    PageItem pageItem = (PageItem) iterator.next();
                    // createPageItem(pageItem);
                    String value = null;
                    Long collapsingSectionId = null;
                    if (pageItem.getForm_field().isEnabled() == true) {
                        // Find which section the field is in
                        try {
                            section = (Long) formDependencies.get(pageItem.getForm_field().getId());
                        } catch (Exception e) {
                            // it's ok
                        }
                        // Is it in a collapsingSection?
                        try {
                            collapsingSectionId = (Long) collapsingDependencies
                                    .get(pageItem.getForm_field().getId());
                            if (collapsingSectionId != null) {
                                ArrayList collapsingSection = (ArrayList) collapsingSections
                                        .get(collapsingSectionId);
                                //the table that is dependent upon the collapsing table if the second item in the list.
                                collapsingTableId = (Long) collapsingSection.get(1);
                            }
                            // collapsingTableId = (Long) formDependencies.get(collapsingSection);
                        } catch (Exception e) {
                            // it's ok
                        }

                        String fieldName = null;
                        FormField formField = pageItem.getForm_field();
                        /*Long currentId = formField.getId();
                        if (formField.getImportId() != null) {
                           currentId = formField.getImportId();
                        }
                        if (formField.getImportId() != null) {
                        fieldName = "field" + currentId;
                        } else {*/
                        //fieldName = StringManipulation.firstCharToLowerCase(formField.getStarSchemaName());
                        fieldName = formField.getIdentifier();
                        //}
                        value = (String) encMap.get(fieldName);
                        // value = BeanUtils.getProperty(encounter, "field" + pageItem.getForm_field().getId());
                        // Do not need to set property  if it's null
                        if (value != null) {
                            if (!pageItem.getForm_field().getType().equals("Display")) {
                                dynaForm.set(fieldName, value);
                            }
                            // Use the sectionMap to make that section visible if necessary.
                            if ((!pageItem.isVisible()) & (section != null)) {
                                // pageItem.setVisible(true);
                                visiblePageItems.put("pageItem" + pageItem.getId(), "visible");
                            }
                            // Use the sectionMap to make that collapsingSection visible if necessary.
                            if (collapsingTableId != null) {
                                visiblePageItems.put("pageItem" + collapsingTableId, "visible");
                            }

                            // also set its sister fields in the section to true
                            // loop through the formSection, matching the masterId
                            List deps = (List) formSection.get(section);
                            if (deps != null) {
                                for (int i = 0; i < deps.size(); i++) {
                                    Long depId = (Long) deps.get(i);
                                    PageItem depPageItem = (PageItem) DynaSiteObjects.getPageItems().get(depId);
                                    // depPageItem.setVisible(true);
                                    visiblePageItems.put("pageItem" + pageItem.getId(), "visible");
                                }
                            }

                        }

                        // Make all hidden fields visible
                        if (!pageItem.isVisible()) {
                            // pageItem.setVisible(true);
                            visiblePageItems.put("pageItem" + pageItem.getId(), "visible");
                        }

                        if (pageItem.getInputType().equals("druglist")) {
                            drugList = true;
                        }

                        if (pageItem.getInputType().equals("multiselect_enum")) {
                            List masterList = new ArrayList();
                            //multiValues.put(currentId, masterList);
                            multiValues.put(fieldName, masterList);
                        }

                        // populate the multiHelper array
                        // each field in which the multiselect widget stores data has the multiselect widget field id in the
                        // visibleDependencies1 property

                        if (pageItem.getInputType().equals("multiselect_item")) {
                            List itemList = null;
                            String visDeps1 = pageItem.getVisibleDependencies1();
                            if (visDeps1 != null) {
                                try {
                                    itemList = (List) multiValues.get(new Long(visDeps1));
                                } catch (NullPointerException e) {
                                    e.printStackTrace(); // multiselect_enum not exist, or out of order.
                                }
                            } else {
                                String error = "multiselect widget setup error - select the widget id for this field's visible deps1.";
                                log.error(error);
                                request.setAttribute("exception", error);
                                return mapping.findForward("error");
                            }

                            value = BeanUtils.getProperty(encounter, fieldName);
                            if (value != null) {
                                //multifields.append(value+ ",");
                                itemList.add(value);
                                //multiValues.put(pageItem.getVisibleDependencies1(), itemList);
                            }
                        }
                    }
                }
                request.setAttribute("multiValues", multiValues);
            }

            request.setAttribute(SUBJECT_KEY, encounter);

            Date dateVisit = encounter.getDateVisit();
            request.setAttribute("dateVisit", dateVisit);
            // used for remote widgets
            request.setAttribute("className", className);
            // loading of body onload DWRUtil.useLoadingMessage()
            request.setAttribute("dwr", 1);
        } else {
            if (sessionPatient != null && sessionPatient.getDead() != null
                    && sessionPatient.getDead().equals(Boolean.TRUE)) {
                String forwardString = null;
                if (sessionPatient != null) {
                    //Long flowId = sessionPatient.getCurrentFlowId();
                    Long flowId = encounterForm.getFlowId();
                    if (flowId.intValue() == 2) {
                        forwardString = "/PatientItem/list.do";
                    } else {
                        forwardString = "/patientTask.do?flowId=" + flowId.toString();
                    }
                } else {
                    forwardString = "/home.do";
                }
                ActionForward forwardForm = null;
                forwardForm = new ActionForward(forwardString);
                forwardForm.setRedirect(true);
                return forwardForm;
            }
        }

        if (visiblePageItems.size() > 0) {
            request.setAttribute("visiblePageItems", visiblePageItems);
        }

        request.setAttribute("encounterForm", encounterForm);

        List drugs = DynaSiteObjects.getDrugs();
        request.setAttribute("drugs", drugs);

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

        String patientSiteId = SessionUtil.getInstance(session).getClientSettings().getSiteId().toString();
        Site site = (Site) DynaSiteObjects.getClinicMap().get(new Long(patientSiteId));
        Integer siteTypeId = site.getSiteTypeId();
        String siteAlphaId = site.getSiteAlphaId().substring(0, 2);
        String clinicId = site.getSiteAlphaId().substring(2, 3);
        request.setAttribute("siteAlphaId", siteAlphaId);
        request.setAttribute("clinicId", clinicId);
        request.setAttribute("siteTypeId", siteTypeId);
        request.setAttribute("patientSiteId", patientSiteId);

        if ((encounterIdString.equals(""))) {
            // See if this form has 1 MaxSubmissions
            int maxSubmissions = encounterForm.getMaxSubmissions();
            Boolean startNewEvent = encounterForm.getStartNewEvent();
            if (maxSubmissions == 1) {
                if (startNewEvent != null && startNewEvent == true) {
                    // start a new Event
                } else {
                    EncounterData encounterOneOnly = null;
                    try {
                        encounterOneOnly = (EncounterData) EncountersDAO.getId(conn, patientId, eventUuid,
                                new Long(formId));
                        Long encounterId = encounterOneOnly.getId();
                        ActionForward forwardForm = null;
                        forwardForm = new ActionForward(
                                "/viewEncounter.do?patientId=" + patientId + "&id=" + encounterId);
                        forwardForm.setRedirect(true);
                        return forwardForm;
                        // send to the record view of this form.
                    } catch (ObjectNotFoundException e1) {
                        // it's ok - form not submitted yet.
                    }
                }
            }

            // patient registration needs sex to be pre-filled to female
            if (encounterForm.getId().intValue() == 1) {
                DynaValidatorForm dynaForm = (DynaValidatorForm) form;
                dynaForm.set("sex", "1");
            }
        }

        List yearList = DateUtils.getYearList();
        request.setAttribute("yearList", yearList);

        // Process the dynamic dropdown lists.
        HashMap listMap = new HashMap();
        Form inlineForm = null;
        for (Iterator iterator = encounterForm.getPageItems().iterator(); iterator.hasNext();) {
            PageItem pageItem = (PageItem) iterator.next();
            FormField formField = pageItem.getForm_field();
            String identifier = formField.getIdentifier();

            if (pageItem.getInputType().equals("dropdown") || pageItem.getInputType().equals("dropdown-add-one")
                    || pageItem.getInputType().equals("dropdown_site")) {
                List list = WidgetUtils.getList(conn, pageItem.getDropdownTable(), pageItem.getDropdownColumn(),
                        pageItem.getDropdownConstraint(), pageItem.getDropdownOrderByClause(),
                        DropdownItem.class, pageItem.getFkIdentifier());
                // Process PatientItem later.
                if (!formName.equals("PatientItem")) {
                    listMap.put(pageItem.getId(), list);
                }
                if (pageItem.getInputType().equals("dropdown-add-one")) {
                    String classNameString = StringManipulation.fixClassname(pageItem.getDropdownTable());
                    Long inlineFormId = (Long) DynaSiteObjects.getFormNameMap().get(classNameString);
                    inlineForm = ((Form) DynaSiteObjects.getForms().get(new Long(inlineFormId)));
                    // Create a list of fieldnames for inline forms.
                    ArrayList<String> inlineFields = new ArrayList<String>();
                    for (Iterator iterator2 = inlineForm.getPageItems().iterator(); iterator2.hasNext();) {
                        PageItem pageItem2 = (PageItem) iterator2.next();
                        if (pageItem2.getForm_field().isEnabled() == true
                                && !pageItem2.getForm_field().getType().equals("Display")) {
                            inlineFields.add(pageItem2.getForm_field().getIdentifier());
                        }
                    }
                    request.setAttribute("inlineForm_" + identifier, inlineForm);
                    request.setAttribute("inlineFields_" + identifier, inlineFields);
                    // loading of body onload DWRUtil.useLoadingMessage()
                    request.setAttribute("dwr", 1);
                }
            }
        }
        // For DAR/ART care form 132
        if (formName.equals("PatientItem")) {
            // Fetch the patient's regimen.
            Long regimenId = sessionPatient.getRegimenId();
            String regimenName = sessionPatient.getRegimenName();
            List<PatientItem> items = RegimenUtils.getAllItemsForRegimen(conn, regimenId);
            // now construct a list of items for the dropdown.
            // We'll replace the one that was just created.
            HashMap<Long, StockReport> balanceMap = null;
            if (DynaSiteObjects.getStatusMap().get("balanceMap") != null) {
                balanceMap = (HashMap<Long, StockReport>) DynaSiteObjects.getStatusMap().get("balanceMap");
            }
            List list = new ArrayList();
            for (PatientItem regimenItem_bridge : items) {
                Long itemId = regimenItem_bridge.getItem_id();
                DropdownItem item = null;
                try {
                    item = RegimenUtils.getItemForRegimen(conn, itemId);
                    //StockControl tempStockControl = InventoryDAO.getCurrentStockBalance(conn, itemId, Integer.valueOf(siteId));
                    if (balanceMap != null) {
                        StockReport stockReport = balanceMap.get(itemId);
                        Integer balance = 0;
                        if (stockReport != null) {
                            balance = stockReport.getBalanceBF();
                        }
                        if (balance <= 0) {
                            /*String value = item.getDropdownValue();
                            item.setDropdownValue(value + " ** Out of Stock ** Bal: " + balance);*/
                        } else {
                            String value = item.getDropdownValue();
                            item.setDropdownValue(value + " Bal: " + balance);
                            list.add(item);
                        }
                    }
                } catch (Exception e) {
                    log.debug("Unable to fetch item for regimen: " + regimenName + " regimenId: " + regimenId
                            + " itemId: " + itemId);
                }
            }
            if (sessionPatient.getChild() != null && sessionPatient.getChild() == true) {
                List<DropdownItem> paedsItems = RegimenUtils.getPaediatricSingleDrugItems(conn);
                for (DropdownItem dropdownItem : paedsItems) {
                    StockReport stockReport = balanceMap.get(Long.valueOf(dropdownItem.getDropdownId()));
                    Integer balance = 0;
                    if (stockReport != null) {
                        balance = stockReport.getBalanceBF();
                    }
                    if (balance <= 0) {
                    } else {
                        String value = dropdownItem.getDropdownValue();
                        dropdownItem.setDropdownValue(value + " Bal: " + balance);
                        list.add(dropdownItem);
                    }
                }
            }
            List<DropdownItem> otherItems = RegimenUtils.getOtherDropdownItems(conn);
            for (DropdownItem dropdownItem : otherItems) {
                StockReport stockReport = balanceMap.get(Long.valueOf(dropdownItem.getDropdownId()));
                Integer balance = 0;
                if (stockReport != null) {
                    balance = stockReport.getBalanceBF();
                }
                if (balance <= 0) {
                } else {
                    String value = dropdownItem.getDropdownValue();
                    dropdownItem.setDropdownValue(value + " Bal: " + balance);
                    list.add(dropdownItem);
                }
            }
            //list.addAll(otherItems);
            if (list.size() > 0) {
                listMap.put(Long.valueOf(4376), list);
            }
        }
        request.setAttribute("listMap", listMap);

        if (encounterForm.getRecordsPerEncounter() != null && encounterForm.getRecordsPerEncounter() > 0) {
            if (encounterForm.getResizedForPatientBridge() == null) {
                FormUtils.createBridgeTablePageItems(encounterForm);
            }
        }

        if (sessionPatient != null && sessionPatient.getPatientType() == 2) {
            List<Patient> clientList = RelationshipDAO.getRelationshipToUuid2(conn, sessionPatient);
            request.setAttribute("relationshipList", clientList);
        }

        // Keep this block at the end - it sets sessionPatient to null in certain circumstances.
        // Set the tasklist for particular circumstances. First check if the form requires a patient or if "id" is in the reqiest.
        if ((encounterForm.isRequirePatient() || ((request.getParameter("id") != null)))) {
            // we don't need the tasklist if we're just editing a form or it's in unassigned flow
            Long unassigned = new Long("100");
            if (request.getParameter("id") == null) {
                if (!encounterForm.getFlow().getId().equals(unassigned)) {
                    // moved code for form 66 below.
                }
            }
            Boolean status = Boolean.valueOf(true);
            /*if (eventUuid == null) {
            return mapping.findForward("home");
            }*/
            List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status,
                    sessionPatient);
            request.setAttribute("activeProblems", activeProblems);
            // now get inactive problems
            status = Boolean.valueOf(false);
            List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid,
                    status, sessionPatient);
            request.setAttribute("inactiveProblems", inactiveProblems);
            // Display task list if editing form 1.
        } else if ((encounterForm.getId().intValue() == 1) & (patientId != null)) {
            Boolean status = Boolean.valueOf(true);
            List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status,
                    sessionPatient);
            request.setAttribute("activeProblems", activeProblems);
            // now get inactive problems
            status = Boolean.valueOf(false);
            List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid,
                    status, sessionPatient);
            request.setAttribute("inactiveProblems", inactiveProblems);
        } else if ((formName.equals("PerpetratorDemographics")) & (patientId != null)) {
            Boolean status = Boolean.valueOf(true);
            List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status,
                    sessionPatient);
            request.setAttribute("activeProblems", activeProblems);
            // now get inactive problems
            status = Boolean.valueOf(false);
            List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid,
                    status, sessionPatient);
            request.setAttribute("inactiveProblems", inactiveProblems);
            // otherwise reset sessionPatient
        } else {
            SessionUtil.getInstance(session).setSessionPatient(null);
        }

    } catch (ServletException e) {
        log.error(e);
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }

    encounterForm = null;

    return mapping.findForward("success");

}