Example usage for java.sql Date valueOf

List of usage examples for java.sql Date valueOf

Introduction

In this page you can find the example usage for java.sql Date valueOf.

Prototype

@SuppressWarnings("deprecation")
public static Date valueOf(LocalDate date) 

Source Link

Document

Obtains an instance of Date from a LocalDate object with the same year, month and day of month value as the given LocalDate .

Usage

From source file:org.apache.ignite.internal.processors.query.h2.database.InlineIndexHelperTest.java

/** */
public void testDate() throws Exception {
    testPutGet(ValueDate.get(Date.valueOf("2017-02-20")), ValueDate.get(Date.valueOf("2017-02-21")),
            ValueDate.get(Date.valueOf("2017-02-19")));
}

From source file:za.co.neilson.sqlite.orm.android.demo.MainActivity.java

public static void insertDemo(Context context, TextView textView) {
    StringBuilder stringBuilder = new StringBuilder();
    CarDatabaseModel carDatabaseModel = null;
    try {/*from  w  w w  .  java  2  s. co  m*/
        carDatabaseModel = getCarDatabaseModel(context);

        Car honda = new Car();
        honda.setMake("Honda");
        honda.setModel("Jazz");
        honda.setRegistered(true);
        honda.setRegistration("RG23BTGP");
        honda.setMileage(55673);
        honda.setManufacturedDate(Date.valueOf("2013-12-03"));

        honda.setWheels(new ArrayList<Wheel>(4));
        for (int w = 0; w < 4; w++) {
            Wheel wheel = new Wheel();
            wheel.setSize(16);
            honda.getWheels().add(wheel);
        }

        /*
         * Inserting the honda will automatically insert it's wheels!
         * 
         * Using insertAndReturnUpdated() means that after the honda and
         * it's wheels are inserted, the honda will be updated by a fresh
         * select on the database. As the Wheel's foreign key specifies the
         * Car classes Collection<Wheel> wheels property as the parent
         * reference, the honda's Wheels will also be updated including the
         * wheelIds that were assigned by SQLite when they were inserted
         * into the database
         */
        honda = carDatabaseModel.getObjectModel(Car.class).insertAndReturnUpdated(honda);

        /*
         * When we inserted the Honda into the database, the Wheels were
         * inserted as well and SQLite automatically assigned each wheel a
         * new wheelId as the wheelId was created as an auto-incrementing
         * primary key.
         * 
         * Since we used the insertAndReturnUpdated() method to insert the
         * Honda, it and its wheels were inserted and then updated from the
         * database including the newly assigned wheelIds. had we just used
         * the insert() method, all the wheelIds would still be 0.
         */
        ObjectModel<WheelNut, ?, ?> wheelNutModel = carDatabaseModel.getObjectModel(WheelNut.class);

        for (Wheel wheel : honda.getWheels()) {
            for (int i = 0; i < 5; i++) {
                WheelNut wheelNut = new WheelNut();
                wheelNut.setWheelId(wheel.getWheelId());
                wheelNut.setThingaMaJigger(new ThingaMaJigger(Status.CHARGED));
                wheelNutModel.insert(wheelNut);
            }
        }

        /*
         * For the sake of this demonstration let's close our database
         * connection and dispose our models to prove that the records were
         * persisted.
         */
        carDatabaseModel.disconnect();
        carDatabaseModel = null;
        wheelNutModel = null;
        System.gc();

        /*
         * Now lets get the Honda from the database and display the results.
         * Getting the Honda will automatically get it's wheels due to the
         * relationship we created between the two but we'll need to get
         * each wheel's wheel nuts manually
         */
        carDatabaseModel = getCarDatabaseModel(context);
        honda = carDatabaseModel.getObjectModel(Car.class).getFirst("registration = ?", "RG23BTGP");
        stringBuilder.append(String.valueOf(honda) + "\n");

        wheelNutModel = carDatabaseModel.getObjectModel(WheelNut.class);
        for (Wheel wheel : honda.getWheels()) {
            System.out.println(wheel);
            for (WheelNut wheelNut : wheelNutModel.getAll("wheelId = ?", wheel.getWheelId())) {
                System.out.println(wheelNut);
            }
        }

    } catch (ClassNotFoundException | NoSuchFieldException | SQLException e) {
        Log.e(MainActivity.class.getName(), e.getMessage(), e);
    } finally {
        if (carDatabaseModel != null) {
            // Disconnect the DatabaseModel's connection to the SQLite
            // database
            carDatabaseModel.disconnect();
            // Make the DatabaseModel eligible for garbage collection
            carDatabaseModel = null;
        }
    }
    textView.setText(stringBuilder.toString());
}

From source file:net.niyonkuru.koodroid.ui.OverviewFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (!data.moveToFirst())
        return;//ww w  . j  a  va 2  s.c  o  m

    int id = loader.getId();

    switch (id) {
    case SUBSCRIBER_TOKEN: {
        mSubscriberName.setText(data.getString(SubscribersQuery.FULL_NAME));
        break;
    }
    case BILL_TOKEN: {
        mBillTotal.setText(formatMoney(data.getString(BillsQuery.TOTAL)));
        mBillPastDueBalance.setText(formatMoney(data.getString(BillsQuery.PAST_DUE_BALANCE)));
        mBillCurrentBalance.setText(formatMoney(data.getString(BillsQuery.CURRENT_CHARGES)));

        if (!data.isNull(BillsQuery.DUE_DATE)) {
            mBillDueDate.setTag(Date.valueOf(data.getString(BillsQuery.DUE_DATE)));
        }
        mBillUpdateTime.setTag(Timestamp.valueOf(data.getString(BillsQuery.UPDATED)));
        break;
    }
    case TAB_TOKEN: {
        mTabBalance.setText(formatMoney(data.getString(TabsQuery.BALANCE)));
        mTabUpdateTime.setTag(Timestamp.valueOf(data.getString(TabsQuery.UPDATED)));
        break;
    }
    }

    updateTimestamps();
}

From source file:org.apache.nifi.processors.orc.PutORCTest.java

@Test
public void testWriteORCWithAvroLogicalTypes() throws IOException, InitializationException {
    final String avroSchema = IOUtils.toString(
            new FileInputStream("src/test/resources/user_logical_types.avsc"), StandardCharsets.UTF_8);
    schema = new Schema.Parser().parse(avroSchema);
    Calendar now = Calendar.getInstance();
    LocalTime nowTime = LocalTime.now();
    LocalDateTime nowDateTime = LocalDateTime.now();
    LocalDate epoch = LocalDate.ofEpochDay(0);
    LocalDate nowDate = LocalDate.now();

    final int timeMillis = nowTime.get(ChronoField.MILLI_OF_DAY);
    final Timestamp timestampMillis = Timestamp.valueOf(nowDateTime);
    final Date dt = Date.valueOf(nowDate);
    final double dec = 1234.56;

    configure(proc, 10, (numUsers, readerFactory) -> {
        for (int i = 0; i < numUsers; i++) {
            readerFactory.addRecord(i, timeMillis, timestampMillis, dt, dec);
        }/*from w  w  w .  j  ava2s.c om*/
        return null;
    });

    final String filename = "testORCWithDefaults-" + System.currentTimeMillis();

    final Map<String, String> flowFileAttributes = new HashMap<>();
    flowFileAttributes.put(CoreAttributes.FILENAME.key(), filename);

    testRunner.setProperty(PutORC.HIVE_TABLE_NAME, "myTable");

    testRunner.enqueue("trigger", flowFileAttributes);
    testRunner.run();
    testRunner.assertAllFlowFilesTransferred(PutORC.REL_SUCCESS, 1);

    final Path orcFile = new Path(DIRECTORY + "/" + filename);

    // verify the successful flow file has the expected attributes
    final MockFlowFile mockFlowFile = testRunner.getFlowFilesForRelationship(PutORC.REL_SUCCESS).get(0);
    mockFlowFile.assertAttributeEquals(PutORC.ABSOLUTE_HDFS_PATH_ATTRIBUTE, orcFile.getParent().toString());
    mockFlowFile.assertAttributeEquals(CoreAttributes.FILENAME.key(), filename);
    mockFlowFile.assertAttributeEquals(PutORC.RECORD_COUNT_ATTR, "10");
    // DDL will be created with field names normalized (lowercased, e.g.) for Hive by default
    mockFlowFile.assertAttributeEquals(PutORC.HIVE_DDL_ATTRIBUTE,
            "CREATE EXTERNAL TABLE IF NOT EXISTS `myTable` (`id` INT, `timemillis` INT, `timestampmillis` TIMESTAMP, `dt` DATE, `dec` DOUBLE) STORED AS ORC");

    // verify we generated a provenance event
    final List<ProvenanceEventRecord> provEvents = testRunner.getProvenanceEvents();
    assertEquals(1, provEvents.size());

    // verify it was a SEND event with the correct URI
    final ProvenanceEventRecord provEvent = provEvents.get(0);
    assertEquals(ProvenanceEventType.SEND, provEvent.getEventType());
    // If it runs with a real HDFS, the protocol will be "hdfs://", but with a local filesystem, just assert the filename.
    Assert.assertTrue(provEvent.getTransitUri().endsWith(DIRECTORY + "/" + filename));

    // verify the content of the ORC file by reading it back in
    verifyORCUsers(orcFile, 10, (x, currUser) -> {
        assertEquals((int) currUser, ((IntWritable) x.get(0)).get());
        assertEquals(timeMillis, ((IntWritable) x.get(1)).get());
        assertEquals(timestampMillis, ((TimestampWritableV2) x.get(2)).getTimestamp().toSqlTimestamp());
        final DateFormat noTimeOfDayDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        noTimeOfDayDateFormat.setTimeZone(TimeZone.getTimeZone("gmt"));
        assertEquals(noTimeOfDayDateFormat.format(dt), ((DateWritableV2) x.get(3)).get().toString());
        assertEquals(dec, ((DoubleWritable) x.get(4)).get(), Double.MIN_VALUE);
        return null;
    });

    // verify we don't have the temp dot file after success
    final File tempOrcFile = new File(DIRECTORY + "/." + filename);
    Assert.assertFalse(tempOrcFile.exists());

    // verify we DO have the CRC file after success
    final File crcAvroORCFile = new File(DIRECTORY + "/." + filename + ".crc");
    Assert.assertTrue(crcAvroORCFile.exists());
}

From source file:com.wso2telco.dep.reportingservice.northbound.NbHostObjectUtils.java

/**
 * Checks if is subscription valid for month.
 *
 * @param subAPI the sub api/*  w w w  .  ja  v  a  2  s.  co  m*/
 * @param year the year
 * @param month the month
 * @return true, if is subscription valid for month
 * @throws Exception 
 */
private static boolean isSubscriptionValidForMonth(SubscribedAPI subAPI, String year, String month)
        throws Exception {
    BillingDAO billingDAO = new BillingDAO();
    java.util.Date createdTime = billingDAO.getSubscriptionCreatedTime(subAPI.getApplication().getId(),
            subAPI.getApiId());
    Date reportDate = Date.valueOf(year + "-" + month + "-01");
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(reportDate);

    // compare created time with 1st day of next month
    calendar.add(Calendar.MONTH, 1);
    calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
    if (createdTime != null) {
        return createdTime.before(calendar.getTime());
    } else {
        return false;
    }

}

From source file:org.everit.jira.hr.admin.SchemeUsersComponent.java

private void processEdit(final HttpServletRequest req, final HttpServletResponse resp) {
    long recordId = Long.parseLong(req.getParameter("record-id"));
    long schemeId = Long.parseLong(req.getParameter("schemeId"));
    String userName = req.getParameter("user");
    Date startDate = Date.valueOf(req.getParameter("start-date"));
    Date endDate = Date.valueOf(req.getParameter("end-date"));
    Date endDateExcluded = DateUtil.addDays(endDate, 1);

    Long userId = getUserId(userName);
    if (userId == null) {
        renderAlert("User does not exist", "error", resp);
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;//w  w  w . java2s.  c  o m
    }

    if (startDate.compareTo(endDate) > 0) {
        renderAlert("Start date must not be after end date", "error", resp);
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    Set<String> schemeNamesWithOverlappingTimeRange = getSchemeNamesWithOverlappingTimeRange(userId, startDate,
            endDateExcluded, recordId);

    if (!schemeNamesWithOverlappingTimeRange.isEmpty()) {
        renderAlert(
                "The user is assigned overlapping with the specified date range to the"
                        + " following scheme(s): " + schemeNamesWithOverlappingTimeRange.toString(),
                "error", resp);
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    update(recordId, schemeId, userId, startDate, endDateExcluded);

    try (PartialResponseBuilder prb = new PartialResponseBuilder(resp)) {
        renderAlertOnPrb("Updating user successful", "info", prb, resp.getLocale());
        prb.replace("#scheme-user-table", render(req, resp.getLocale(), "scheme-user-table"));
    }
}

From source file:com.linkedin.databus2.producers.gg.GGEventGenerationFactory.java

public static long ggDateStringToLong(String value) throws DatabusException {
    Pattern _pattern = Pattern.compile("(\\d{4}-\\d{2}-\\d{2}).*");
    Matcher matcher = _pattern.matcher(value);
    if (!matcher.matches() || matcher.groupCount() != 1) {
        throw new DatabusException("The date format is not as expected, cannot proceed!");
    }//  ww w .j  av a2s.c o  m
    String dateFormatString = matcher.group(1);
    long dateLong = Date.valueOf(dateFormatString).getTime();
    return dateLong;
}

From source file:org.apache.hawq.pxf.plugins.hive.HiveResolver.java

void initPartitionFields() {
    partitionFields = new LinkedList<>();
    if (partitionKeys.equals(HiveDataFragmenter.HIVE_NO_PART_TBL)) {
        return;// w w w  .  ja  v  a 2  s.c o m
    }

    String[] partitionLevels = partitionKeys.split(HiveDataFragmenter.HIVE_PARTITIONS_DELIM);
    for (String partLevel : partitionLevels) {
        String[] levelKey = partLevel.split(HiveDataFragmenter.HIVE_1_PART_DELIM);
        String type = levelKey[1];
        String val = levelKey[2];
        DataType convertedType;
        Object convertedValue = null;
        boolean isDefaultPartition = false;

        LOG.debug("Partition type: " + type + ", value: " + val);
        // check if value is default partition
        isDefaultPartition = isDefaultPartition(type, val);
        // ignore the type's parameters
        String typeName = type.replaceAll("\\(.*\\)", "");

        switch (typeName) {
        case serdeConstants.STRING_TYPE_NAME:
            convertedType = TEXT;
            convertedValue = isDefaultPartition ? null : val;
            break;
        case serdeConstants.BOOLEAN_TYPE_NAME:
            convertedType = BOOLEAN;
            convertedValue = isDefaultPartition ? null : Boolean.valueOf(val);
            break;
        case serdeConstants.TINYINT_TYPE_NAME:
        case serdeConstants.SMALLINT_TYPE_NAME:
            convertedType = SMALLINT;
            convertedValue = isDefaultPartition ? null : Short.parseShort(val);
            break;
        case serdeConstants.INT_TYPE_NAME:
            convertedType = INTEGER;
            convertedValue = isDefaultPartition ? null : Integer.parseInt(val);
            break;
        case serdeConstants.BIGINT_TYPE_NAME:
            convertedType = BIGINT;
            convertedValue = isDefaultPartition ? null : Long.parseLong(val);
            break;
        case serdeConstants.FLOAT_TYPE_NAME:
            convertedType = REAL;
            convertedValue = isDefaultPartition ? null : Float.parseFloat(val);
            break;
        case serdeConstants.DOUBLE_TYPE_NAME:
            convertedType = FLOAT8;
            convertedValue = isDefaultPartition ? null : Double.parseDouble(val);
            break;
        case serdeConstants.TIMESTAMP_TYPE_NAME:
            convertedType = TIMESTAMP;
            convertedValue = isDefaultPartition ? null : Timestamp.valueOf(val);
            break;
        case serdeConstants.DATE_TYPE_NAME:
            convertedType = DATE;
            convertedValue = isDefaultPartition ? null : Date.valueOf(val);
            break;
        case serdeConstants.DECIMAL_TYPE_NAME:
            convertedType = NUMERIC;
            convertedValue = isDefaultPartition ? null : HiveDecimal.create(val).bigDecimalValue().toString();
            break;
        case serdeConstants.VARCHAR_TYPE_NAME:
            convertedType = VARCHAR;
            convertedValue = isDefaultPartition ? null : val;
            break;
        case serdeConstants.CHAR_TYPE_NAME:
            convertedType = BPCHAR;
            convertedValue = isDefaultPartition ? null : val;
            break;
        case serdeConstants.BINARY_TYPE_NAME:
            convertedType = BYTEA;
            convertedValue = isDefaultPartition ? null : val.getBytes();
            break;
        default:
            throw new UnsupportedTypeException("Unsupported partition type: " + type);
        }
        addOneFieldToRecord(partitionFields, convertedType, convertedValue);
    }
}

From source file:HotelManagerImplTest.java

private Date date(String date) {
    return Date.valueOf(date);
}

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

/**
 * Create record from form./* w  w w  .j  av a2  s.  c om*/
 *
 * @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);
}