Example usage for java.util Calendar before

List of usage examples for java.util Calendar before

Introduction

In this page you can find the example usage for java.util Calendar before.

Prototype

public boolean before(Object when) 

Source Link

Document

Returns whether this Calendar represents a time before the time represented by the specified Object.

Usage

From source file:com.square.core.service.implementations.PersonneServiceImplementation.java

/**
 * Test si une relation est active ou pas  la date du jour.
 * @param dateDebut date de dbut de la relation
 * @param dateFin date de fin de la relation
 * @return true si la relation est active, false sinon
 *///from w  w w  .j a va2  s  .  c om
private boolean isRelationActive(Calendar dateDebut, Calendar dateFin) {
    final Calendar dateDuJour = Calendar.getInstance();
    final int jour = dateDuJour.get(Calendar.DATE);
    final int mois = dateDuJour.get(Calendar.MONTH);
    final int annee = dateDuJour.get(Calendar.YEAR);
    dateDuJour.clear();
    dateDuJour.set(annee, mois, jour);
    return (dateDebut == null || dateDebut.before(dateDuJour) || dateDebut.equals(dateDuJour))
            && (dateFin == null || dateFin.after(dateDuJour));
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static Object dateDiff(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    if (ArgList.length == 3) {
        try {/*from ww w. j  av  a  2 s  . c  om*/
            if (isNull(ArgList, new int[] { 0, 1, 2 })) {
                return new Double(Double.NaN);
            } else if (isUndefined(ArgList, new int[] { 0, 1, 2 })) {
                return undefinedValue;
            } else {
                java.util.Date dIn1 = (java.util.Date) ArgList[0];
                java.util.Date dIn2 = (java.util.Date) ArgList[1];
                String strType = ((String) ArgList[2]).toLowerCase();
                int iRC = 0;

                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                startDate.setTime(dIn1);
                endDate.setTime(dIn2);

                /*
                 * Changed by: Ingo Klose, SHS VIVEON AG, Date: 27.04.2007
                 *
                 * Calculating time differences using getTimeInMillis() leads to false results when crossing Daylight
                 * Savingstime borders. In order to get correct results the time zone offsets have to be added.
                 *
                 * Fix: 1. calculate correct milli seconds for start and end date 2. replace endDate.getTimeInMillis() with
                 * endL and startDate.getTimeInMillis() with startL
                 */
                long endL = endDate.getTimeInMillis()
                        + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                long startL = startDate.getTimeInMillis()
                        + startDate.getTimeZone().getOffset(startDate.getTimeInMillis());

                if (strType.equals("y")) {
                    return new Double(endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR));
                } else if (strType.equals("m")) {
                    int iMonthsToAdd = (endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR)) * 12;
                    return new Double(
                            (endDate.get(Calendar.MONTH) - startDate.get(Calendar.MONTH)) + iMonthsToAdd);
                } else if (strType.equals("d")) {
                    return new Double(((endL - startL) / 86400000));
                } else if (strType.equals("wd")) {
                    int iOffset = -1;
                    if (endDate.before(startDate)) {
                        iOffset = 1;
                    }
                    while ((iOffset == 1 && endL < startL) || (iOffset == -1 && endL > startL)) {
                        int day = endDate.get(Calendar.DAY_OF_WEEK);
                        if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
                            iRC++;
                        }
                        endDate.add(Calendar.DATE, iOffset);
                        endL = endDate.getTimeInMillis()
                                + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                    }
                    return new Double(iRC);
                } else if (strType.equals("w")) {
                    int iDays = (int) ((endL - startL) / 86400000);
                    return new Double(iDays / 7);
                } else if (strType.equals("ss")) {
                    return new Double(((endL - startL) / 1000));
                } else if (strType.equals("mi")) {
                    return new Double(((endL - startL) / 60000));
                } else if (strType.equals("hh")) {
                    return new Double(((endL - startL) / 3600000));
                } else {
                    return new Double(((endL - startL) / 86400000));
                }
                /*
                 * End Bugfix
                 */
            }
        } catch (Exception e) {
            throw new RuntimeException(e.toString());
        }
    } else {
        throw new RuntimeException("The function call dateDiff requires 3 arguments.");
    }
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static Object dateDiff(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    if (ArgList.length == 3) {
        try {/*ww  w  . j  a v a  2  s  .  c  o  m*/
            if (isNull(ArgList, new int[] { 0, 1, 2 }))
                return new Double(Double.NaN);
            else if (isUndefined(ArgList, new int[] { 0, 1, 2 }))
                return undefinedValue;
            else {
                java.util.Date dIn1 = (java.util.Date) ArgList[0];
                java.util.Date dIn2 = (java.util.Date) ArgList[1];
                String strType = (String) ArgList[2];
                int iRC = 0;

                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                startDate.setTime(dIn1);
                endDate.setTime(dIn2);

                /* Changed by:    Ingo Klose, SHS VIVEON AG,
                 * Date:      27.04.2007
                 *
                 * Calculating time differences using getTimeInMillis() leads to false results
                 * when crossing Daylight Savingstime borders. In order to get correct results
                 * the time zone offsets have to be added.
                 *
                 * Fix:       1.    calculate correct milli seconds for start and end date
                 *             2.    replace endDate.getTimeInMillis() with endL
                 *                and startDate.getTimeInMillis() with startL
                 */
                long endL = endDate.getTimeInMillis()
                        + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                long startL = startDate.getTimeInMillis()
                        + startDate.getTimeZone().getOffset(startDate.getTimeInMillis());

                if (strType.toLowerCase().equals("y")) {
                    return new Double(endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR));
                } else if (strType.toLowerCase().equals("m")) {
                    int iMonthsToAdd = (int) (endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR)) * 12;
                    return new Double(
                            (endDate.get(Calendar.MONTH) - startDate.get(Calendar.MONTH)) + iMonthsToAdd);
                } else if (strType.toLowerCase().equals("d")) {
                    return new Double(((endL - startL) / 86400000));
                } else if (strType.toLowerCase().equals("wd")) {
                    int iOffset = -1;
                    if (endDate.before(startDate))
                        iOffset = 1;
                    while ((iOffset == 1 && endL < startL) || (iOffset == -1 && endL > startL)) {
                        int day = endDate.get(Calendar.DAY_OF_WEEK);
                        if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY))
                            iRC++;
                        endDate.add(Calendar.DATE, iOffset);
                        endL = endDate.getTimeInMillis()
                                + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                    }
                    return new Double(iRC);
                } else if (strType.toLowerCase().equals("w")) {
                    int iDays = (int) ((endL - startL) / 86400000);
                    return new Double(iDays / 7);
                } else if (strType.toLowerCase().equals("ss")) {
                    return new Double(((endL - startL) / 1000));
                } else if (strType.toLowerCase().equals("mi")) {
                    return new Double(((endL - startL) / 60000));
                } else if (strType.toLowerCase().equals("hh")) {
                    return new Double(((endL - startL) / 3600000));
                } else {
                    return new Double(((endL - startL) / 86400000));
                }
                /*
                   * End Bugfix
                 */
            }
        } catch (Exception e) {
            throw new RuntimeException(e.toString());
        }
    } else {
        throw new RuntimeException("The function call dateDiff requires 3 arguments.");
    }
}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static Object dateDiff(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    if (ArgList.length == 3) {
        try {//w w w  . j  a v  a2  s.  c  o  m
            if (isNull(ArgList, new int[] { 0, 1, 2 }))
                return new Double(Double.NaN);
            else if (isUndefined(ArgList, new int[] { 0, 1, 2 }))
                return Context.getUndefinedValue();
            else {
                java.util.Date dIn1 = (java.util.Date) Context.jsToJava(ArgList[0], java.util.Date.class);
                java.util.Date dIn2 = (java.util.Date) Context.jsToJava(ArgList[1], java.util.Date.class);
                String strType = Context.toString(ArgList[2]);
                int iRC = 0;

                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                startDate.setTime(dIn1);
                endDate.setTime(dIn2);

                /* Changed by:    Ingo Klose, SHS VIVEON AG,
                 * Date:      27.04.2007
                 *
                 * Calculating time differences using getTimeInMillis() leads to false results
                 * when crossing Daylight Savingstime borders. In order to get correct results
                 * the time zone offsets have to be added.
                 *
                 * Fix:       1.    calculate correct milli seconds for start and end date
                 *             2.    replace endDate.getTimeInMillis() with endL
                 *                and startDate.getTimeInMillis() with startL
                 */
                long endL = endDate.getTimeInMillis()
                        + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                long startL = startDate.getTimeInMillis()
                        + startDate.getTimeZone().getOffset(startDate.getTimeInMillis());

                if (strType.toLowerCase().equals("y")) {
                    return new Double(endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR));
                } else if (strType.toLowerCase().equals("m")) {
                    int iMonthsToAdd = (int) (endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR)) * 12;
                    return new Double(
                            (endDate.get(Calendar.MONTH) - startDate.get(Calendar.MONTH)) + iMonthsToAdd);
                } else if (strType.toLowerCase().equals("d")) {
                    return new Double(((endL - startL) / 86400000));
                } else if (strType.toLowerCase().equals("wd")) {
                    int iOffset = -1;
                    if (endDate.before(startDate))
                        iOffset = 1;
                    while (endL < startL || endL > startL) {
                        int day = endDate.get(Calendar.DAY_OF_WEEK);
                        if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY))
                            iRC++;
                        endDate.add(Calendar.DATE, iOffset);
                        endL = endDate.getTimeInMillis()
                                + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                    }
                    return new Double(iRC);
                } else if (strType.toLowerCase().equals("w")) {
                    int iDays = (int) ((endL - startL) / 86400000);
                    return new Double(iDays / 7);
                } else if (strType.toLowerCase().equals("ss")) {
                    return new Double(((endL - startL) / 1000));
                } else if (strType.toLowerCase().equals("mi")) {
                    return new Double(((endL - startL) / 60000));
                } else if (strType.toLowerCase().equals("hh")) {
                    return new Double(((endL - startL) / 3600000));
                } else {
                    return new Double(((endL - startL) / 86400000));
                }
                /*
                   * End Bugfix
                 */
            }
        } catch (Exception e) {
            throw Context.reportRuntimeError(e.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call dateDiff requires 3 arguments.");
    }
}

From source file:org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static Object dateDiff(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    if (ArgList.length == 3) {
        try {/*from  w  w w. j a v  a 2 s.co  m*/
            if (isNull(ArgList, new int[] { 0, 1, 2 })) {
                return new Double(Double.NaN);
            } else if (isUndefined(ArgList, new int[] { 0, 1, 2 })) {
                return Context.getUndefinedValue();
            } else {
                java.util.Date dIn1 = (java.util.Date) Context.jsToJava(ArgList[0], java.util.Date.class);
                java.util.Date dIn2 = (java.util.Date) Context.jsToJava(ArgList[1], java.util.Date.class);
                String strType = Context.toString(ArgList[2]).toLowerCase();
                int iRC = 0;

                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                startDate.setTime(dIn1);
                endDate.setTime(dIn2);

                /*
                 * Changed by: Ingo Klose, SHS VIVEON AG, Date: 27.04.2007
                 *
                 * Calculating time differences using getTimeInMillis() leads to false results when crossing Daylight
                 * Savingstime borders. In order to get correct results the time zone offsets have to be added.
                 *
                 * Fix: 1. calculate correct milli seconds for start and end date 2. replace endDate.getTimeInMillis() with
                 * endL and startDate.getTimeInMillis() with startL
                 */
                long endL = endDate.getTimeInMillis()
                        + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                long startL = startDate.getTimeInMillis()
                        + startDate.getTimeZone().getOffset(startDate.getTimeInMillis());

                if (strType.equals("y")) {
                    return new Double(endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR));
                } else if (strType.equals("m")) {
                    int iMonthsToAdd = (endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR)) * 12;
                    return new Double(
                            (endDate.get(Calendar.MONTH) - startDate.get(Calendar.MONTH)) + iMonthsToAdd);
                } else if (strType.equals("d")) {
                    return new Double(((endL - startL) / 86400000));
                } else if (strType.equals("wd")) {
                    int iOffset = -1;
                    if (endDate.before(startDate)) {
                        iOffset = 1;
                    }
                    while ((iOffset == 1 && endL < startL) || (iOffset == -1 && endL > startL)) {
                        int day = endDate.get(Calendar.DAY_OF_WEEK);
                        if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
                            iRC++;
                        }
                        endDate.add(Calendar.DATE, iOffset);
                        endL = endDate.getTimeInMillis()
                                + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                    }
                    return new Double(iRC);
                } else if (strType.equals("w")) {
                    int iDays = (int) ((endL - startL) / 86400000);
                    return new Double(iDays / 7);
                } else if (strType.equals("ss")) {
                    return new Double(((endL - startL) / 1000));
                } else if (strType.equals("mi")) {
                    return new Double(((endL - startL) / 60000));
                } else if (strType.equals("hh")) {
                    return new Double(((endL - startL) / 3600000));
                } else {
                    return new Double(((endL - startL) / 86400000));
                }
                /*
                 * End Bugfix
                 */
            }
        } catch (Exception e) {
            throw Context.reportRuntimeError(e.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call dateDiff requires 3 arguments.");
    }
}

From source file:org.kuali.kfs.module.tem.document.service.impl.TravelDocumentServiceImpl.java

@Override
public Integer calculatePerDiemPercentageFromTimestamp(PerDiemExpense perDiemExpense, Timestamp tripEnd) {
    if (perDiemExpense.getMileageDate() != null) {
        try {/*from   w  w w .j av  a2s  . c  o m*/
            Collection<String> quarterTimes = parameterService.getParameterValuesAsString(
                    TemParameterConstants.TEM_DOCUMENT.class, TravelParameters.QUARTER_DAY_TIME_TABLE);

            // Take date and compare to the quadrant specified.
            Calendar prorateDate = new GregorianCalendar();
            prorateDate.setTime(perDiemExpense.getMileageDate());

            int quadrantIndex = 4;
            for (String qT : quarterTimes) {
                String[] indexTime = qT.split("=");
                String[] hourMinute = indexTime[1].split(":");

                Calendar qtCal = new GregorianCalendar();
                qtCal.setTime(perDiemExpense.getMileageDate());
                qtCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourMinute[0]));
                qtCal.set(Calendar.MINUTE, Integer.parseInt(hourMinute[1]));

                if (prorateDate.equals(qtCal) || prorateDate.before(qtCal)) {
                    quadrantIndex = Integer.parseInt(indexTime[0]);
                    break;
                }
            }

            // Prorate on trip begin. (12:01 AM arrival = 100%, 11:59 PM arrival = 25%)
            if (tripEnd != null && !KfsDateUtils.isSameDay(prorateDate.getTime(), tripEnd)) {
                return 100 - ((quadrantIndex - 1) * TemConstants.QUADRANT_PERCENT_VALUE);
            } else { // Prorate on trip end. (12:01 AM departure = 25%, 11:59 PM arrival = 100%).
                return quadrantIndex * TemConstants.QUADRANT_PERCENT_VALUE;
            }
        } catch (IllegalArgumentException e2) {
            LOG.error("IllegalArgumentException.", e2);
        }
    }

    return 100;
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Assert that the before timestamp is lower than the after timestamp.
 * //from   ww w .j av  a  2 s  . c  om
 * @param before
 *            Timestamp before the event
 * @param after
 *            Timestamp after event
 * @throws Exception
 *             Thrown if the before timestamp is not lower than after.
 */
public static void assertDateBeforeAfter(final String before, final String after) throws Exception {
    Calendar oldModCal = getCalendarFromXmlDateString(before);
    Calendar newModCal = getCalendarFromXmlDateString(after);

    if (!oldModCal.before(newModCal)) {
        fail("Old last modification date is not before new last" + " modification date.");
    }
}

From source file:org.kuali.kfs.module.tem.document.service.impl.TravelDocumentServiceImpl.java

/**
 * @see org.kuali.kfs.module.tem.document.service.TravelDocumentService#updatePerDiemItemsFor(String, List, Integer, Timestamp, Timestamp)
 *///w w w . ja v a2s . c  om
@SuppressWarnings("null")
@Override
public void updatePerDiemItemsFor(final TravelDocument document, final List<PerDiemExpense> perDiemExpenseList,
        final Integer perDiemId, final Timestamp start, final Timestamp end) {
    final String mileageRateExpenseTypeCode = getParameterService().getParameterValueAsString(
            TemParameterConstants.TEM_DOCUMENT.class,
            TemConstants.TravelParameters.PER_DIEM_MILEAGE_RATE_EXPENSE_TYPE_CODE, KFSConstants.EMPTY_STRING);

    // Check for changes on trip begin and trip end.
    // This is necessary to prevent duplication of per diem creation due to timestamp changes.
    boolean datesChanged = false;
    if (perDiemExpenseList != null && !perDiemExpenseList.isEmpty()) {
        Timestamp tempStart = perDiemExpenseList.get(0).getMileageDate();
        Timestamp tempEnd = perDiemExpenseList.get(0).getMileageDate();

        if (perDiemExpenseList.size() > 1) {
            tempEnd = perDiemExpenseList.get(perDiemExpenseList.size() - 1).getMileageDate();
        }

        if (!(tempStart.equals(start) && tempEnd.equals(end))) {
            // the perDiemExpenseList will be cleared once we recreate the table, but we need it for carrying over mileage rates
            datesChanged = true;
        }
    }

    List<PerDiem> perDiemList = new ArrayList<PerDiem>();

    // find a valid per diem for each date.  If per diem is null, make it a custom per diem.
    for (final Timestamp eachTimestamp : dateRange(start, end)) {
        PerDiem perDiem = getPerDiemService().getPerDiem(document.getPrimaryDestinationId(), eachTimestamp,
                document.getEffectiveDateForPerDiem(eachTimestamp));
        if (perDiem == null
                || perDiem.getPrimaryDestinationId() == TemConstants.CUSTOM_PRIMARY_DESTINATION_ID) {
            perDiem = new PerDiem();
            perDiem.setPrimaryDestination(new PrimaryDestination());
            perDiem.getPrimaryDestination().setRegion(new TemRegion());
            perDiem.getPrimaryDestination().getRegion().setTripType(new TripType());
            perDiem.setPrimaryDestinationId(TemConstants.CUSTOM_PRIMARY_DESTINATION_ID);
            perDiem.getPrimaryDestination().getRegion()
                    .setRegionName(document.getPrimaryDestinationCountryState());
            perDiem.getPrimaryDestination().setCounty(document.getPrimaryDestinationCounty());
            perDiem.getPrimaryDestination().getRegion().setTripType(document.getTripType());
            perDiem.getPrimaryDestination().getRegion().setTripTypeCode(document.getTripTypeCode());
            perDiem.getPrimaryDestination().setPrimaryDestinationName(document.getPrimaryDestinationName());
        }
        perDiemList.add(perDiem);
    }

    final Map<Timestamp, PerDiemExpense> perDiemMapped = new HashMap<Timestamp, PerDiemExpense>();

    int diffStartDays = 0;
    if (perDiemExpenseList.size() > 0 && perDiemExpenseList.get(0).getMileageDate() != null && !datesChanged) {
        diffStartDays = dateTimeService.dateDiff(start, perDiemExpenseList.get(0).getMileageDate(), false);
    }

    Calendar endCal = Calendar.getInstance();

    if (end != null) {
        endCal.setTime(end);
        if (!datesChanged) {
            for (final PerDiemExpense perDiemItem : perDiemExpenseList) {
                if (diffStartDays != 0) {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(perDiemItem.getMileageDate());
                    cal.add(Calendar.DATE, -diffStartDays);
                    perDiemItem.setMileageDate(new Timestamp(cal.getTimeInMillis()));
                }

                if (perDiemItem.getMileageDate() != null) {
                    Calendar currCal = Calendar.getInstance();
                    currCal.setTime(perDiemItem.getMileageDate());
                    if (!endCal.before(currCal)) {
                        perDiemMapped.put(perDiemItem.getMileageDate(), perDiemItem);
                    }
                }
            }
        }

        LOG.debug("Iterating over date range from " + start + " to " + end);
        int counter = 0;
        for (final Timestamp someDate : dateRange(start, end)) {
            // Check if a per diem entry exists for this date
            if (!perDiemMapped.containsKey(someDate)) {
                final boolean prorated = shouldProrate(someDate, start, end);
                PerDiemExpense perDiemExpense = createPerDiemItem(document, perDiemList.get(counter), someDate,
                        prorated, mileageRateExpenseTypeCode);
                perDiemExpense.setDocumentNumber(document.getDocumentNumber());
                perDiemMapped.put(someDate, perDiemExpense);
            }
            counter++;
        }
    }

    // Sort the dates and recreate the collection
    perDiemExpenseList.clear();
    for (final Timestamp someDate : new TreeSet<Timestamp>(perDiemMapped.keySet())) {
        LOG.debug("Adding " + perDiemMapped.get(someDate) + " to perdiem list");
        perDiemExpenseList.add(perDiemMapped.get(someDate));
    }
}

From source file:edu.hawaii.soest.kilonalu.ctd.CTDSource.java

/**
 * A method that executes the streaming of data from the source to the RBNB
 * server after all configuration of settings, connections to hosts, and
 * thread initiatizing occurs.  This method contains the detailed code for 
 * streaming the data and interpreting the stream.
 */// www  .  j a  v a  2s .c o m
protected boolean execute() {
    logger.debug("CTDSource.execute() called.");

    // do not execute the stream if there is no connection
    if (!isConnected())
        return false;

    boolean failed = false;

    // test the connection type
    if (this.connectionType.equals("serial")) {

        // create a serial connection to the local serial port
        this.channel = getSerialConnection();

    } else if (this.connectionType.equals("socket")) {

        // otherwise create a TCP or UDP socket connection to the remote host
        this.channel = getSocketConnection();

    } else {
        logger.info("There was an error establishing either a serial or "
                + "socket connection to the instrument.  Please be sure "
                + "the connection type is set to either 'serial' or 'socket'.");
        return false;

    }

    // while data are being sent, read them into the buffer
    try {
        // create four byte placeholders used to evaluate up to a four-byte 
        // window.  The FIFO layout looks like:
        //           -------------------------
        //   in ---> | One | Two |Three|Four |  ---> out
        //           -------------------------
        byte byteOne = 0x00, // set initial placeholder values
                byteTwo = 0x00, byteThree = 0x00, byteFour = 0x00;

        // Create a buffer that will store the sample bytes as they are read
        ByteBuffer sampleBuffer = ByteBuffer.allocate(getBufferSize());

        // Declare sample variables to be used in the response parsing
        byte[] sampleArray;

        // create a byte buffer to store bytes from the TCP stream
        ByteBuffer buffer = ByteBuffer.allocateDirect(getBufferSize());

        // add a channel of data that will be pushed to the server.  
        // Each sample will be sent to the Data Turbine as an rbnb frame.
        ChannelMap rbnbChannelMap = new ChannelMap();

        // while there are bytes to read from the channel ...
        while (this.channel.read(buffer) != -1 || buffer.position() > 0) {

            // prepare the buffer for reading
            buffer.flip();

            // while there are unread bytes in the ByteBuffer
            while (buffer.hasRemaining()) {
                byteOne = buffer.get();
                logger.debug("b1: " + new String(Hex.encodeHex((new byte[] { byteOne }))) + "\t" + "b2: "
                        + new String(Hex.encodeHex((new byte[] { byteTwo }))) + "\t" + "b3: "
                        + new String(Hex.encodeHex((new byte[] { byteThree }))) + "\t" + "b4: "
                        + new String(Hex.encodeHex((new byte[] { byteFour }))) + "\t" + "sample pos: "
                        + sampleBuffer.position() + "\t" + "sample rem: " + sampleBuffer.remaining() + "\t"
                        + "sample cnt: " + sampleByteCount + "\t" + "buffer pos: " + buffer.position() + "\t"
                        + "buffer rem: " + buffer.remaining() + "\t" + "state: " + this.state);

                // Use a State Machine to process the byte stream.
                // Start building an rbnb frame for the entire sample, first by 
                // inserting a timestamp into the channelMap.  This time is merely
                // the time of insert into the data turbine, not the time of
                // observations of the measurements.  That time should be parsed out
                // of the sample in the Sink client code

                switch (this.state) {

                case 0: // wake up the instrument

                    // check for instrument metadata fields
                    if (this.enableSendCommands && !this.hasMetadata) {

                        // wake the instrument with an initial '\r\n' command
                        this.command = this.commandSuffix;
                        this.sentCommand = queryInstrument(this.command);
                        this.sentCommand = queryInstrument(this.command);
                        streamingThread.sleep(2000);

                        this.state = 1;
                        break;

                    } else {

                        this.state = 11;
                        break;

                    }

                case 1: // stop the sampling

                    // be sure the instrument woke (look for S> prompt)
                    //if (byteOne == 0x3E && byteTwo == 0x53 ) {
                    //  
                    //  sampleByteCount = 0;
                    //  sampleBuffer.clear();
                    //  
                    //  // send the stop sampling command
                    this.command = this.commandPrefix + this.stopSamplingCommand + this.commandSuffix;
                    this.sentCommand = queryInstrument(command);

                    sampleBuffer.clear();
                    sampleByteCount = 0;
                    this.state = 2;
                    break;

                //} else {
                //  // handle instrument hardware response
                //  sampleByteCount++; // add the last byte found to the count
                //  
                //  // add the last byte found to the sample buffer
                //  if ( sampleBuffer.remaining() > 0 ) {
                //    sampleBuffer.put(byteOne);
                //  
                //  } else {
                //    sampleBuffer.compact();
                //    sampleBuffer.put(byteOne);
                //    
                //  }                
                //  
                //  break; // continue reading bytes
                //  
                //}

                case 2: // based on outputType, get metadata from the instrument

                    // the response should end in <Executed/>
                    if (byteOne == 0x3E && byteTwo == 0x2F && byteThree == 0x64 && byteFour == 0x65) {

                        sampleBuffer.clear();
                        sampleByteCount = 0;
                        this.samplingIsStopped = true;

                        // for newer firmware CTDs, use xml-based query commands
                        if (getOutputType().equals("xml")) {
                            // create the CTD parser instance used to parse CTD output
                            this.ctdParser = new CTDParser();
                            this.state = 3;
                            break;

                            // otherwise, use text-based query commands
                        } else if (getOutputType().equals("text")) {
                            this.state = 12; // process DS and DCal commands
                            break;

                        } else {

                            logger.info("The CTD output type is not recognized. "
                                    + "Please set the output type to either " + "'xml' or 'text'.");
                            failed = true;
                            this.state = 0;

                            // close the serial or socket channel
                            if (this.channel != null && this.channel.isOpen()) {
                                try {
                                    this.channel.close();

                                } catch (IOException cioe) {
                                    logger.debug("An error occurred trying to close the byte channel. "
                                            + " The error message was: " + cioe.getMessage());
                                    return !failed;

                                }
                            }

                            // disconnect from the RBNB
                            if (isConnected()) {
                                disconnect();
                            }

                            return !failed;

                        }

                    } else {

                        // handle instrument hardware response
                        sampleByteCount++; // add the last byte found to the count

                        // add the last byte found to the sample buffer
                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            sampleBuffer.put(byteOne);

                        }

                        break; // continue reading bytes

                    }

                case 3: // get the instrument status metadata

                    if (!this.ctdParser.getHasStatusMetadata()) {

                        this.command = this.commandPrefix + this.getStatusCommand + this.commandSuffix;
                        this.sentCommand = queryInstrument(command);
                        streamingThread.sleep(5000);
                        this.state = 4;
                        break;

                    } else {

                        // get the configuration metadata
                        this.command = this.commandPrefix + this.getConfigurationCommand + this.commandSuffix;
                        this.sentCommand = queryInstrument(command);
                        streamingThread.sleep(5000);
                        this.state = 5;
                        break;

                    }

                case 4: // handle instrument status response

                    // command response ends with <Executed/> (so find: ed/>)
                    if (byteOne == 0x3E && byteTwo == 0x2F && byteThree == 0x64 && byteFour == 0x65) {

                        // handle instrument status response
                        sampleByteCount++; // add the last byte found to the count

                        // add the last byte found to the sample buffer
                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            sampleBuffer.put(byteOne);

                        }

                        // extract the sampleByteCount length from the sampleBuffer
                        sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        this.responseString = new String(sampleArray, "US-ASCII");

                        // set the CTD metadata
                        int executedIndex = this.responseString.indexOf("<Executed/>");
                        this.responseString = this.responseString.substring(0, executedIndex - 1);

                        this.ctdParser.setMetadata(this.responseString);

                        // reset variables for the next sample
                        sampleBuffer.clear();
                        sampleByteCount = 0;

                        // then get the instrument configuration metadata
                        if (!this.ctdParser.getHasConfigurationMetadata()) {

                            this.command = this.commandPrefix + this.getConfigurationCommand
                                    + this.commandSuffix;
                            this.sentCommand = queryInstrument(command);
                            streamingThread.sleep(5000);
                            this.state = 5;
                            break;

                        } else {

                            // get the calibration metadata
                            this.command = this.commandPrefix + this.getCalibrationCommand + this.commandSuffix;
                            this.sentCommand = queryInstrument(command);
                            streamingThread.sleep(5000);
                            this.state = 6;
                            break;

                        }

                    } else {
                        break; // continue reading bytes

                    }

                case 5: // handle the instrument configuration metadata

                    // command response ends with <Executed/> (so find: ed/>)
                    if (byteOne == 0x3E && byteTwo == 0x2F && byteThree == 0x64 && byteFour == 0x65) {

                        // handle instrument configration response
                        sampleByteCount++; // add the last byte found to the count

                        // add the last byte found to the sample buffer
                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            sampleBuffer.put(byteOne);

                        }

                        // extract the sampleByteCount length from the sampleBuffer
                        sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        this.responseString = new String(sampleArray, "US-ASCII");

                        // set the CTD metadata
                        int executedIndex = this.responseString.indexOf("<Executed/>");
                        this.responseString = this.responseString.substring(0, executedIndex - 1);

                        this.ctdParser.setMetadata(this.responseString);

                        // reset variables for the next sample
                        sampleBuffer.clear();
                        sampleByteCount = 0;

                        // then get the instrument calibration metadata
                        if (!this.ctdParser.getHasCalibrationMetadata()) {

                            this.command = this.commandPrefix + this.getCalibrationCommand + this.commandSuffix;
                            this.sentCommand = queryInstrument(command);
                            streamingThread.sleep(5000);
                            this.state = 6;
                            break;

                        } else {

                            this.command = this.commandPrefix + this.getEventsCommand + this.commandSuffix;
                            this.sentCommand = queryInstrument(command);
                            streamingThread.sleep(5000);
                            this.state = 7;
                            break;

                        }

                    } else {
                        break; // continue reading bytes

                    }

                case 6: // handle the instrument calibration metadata

                    // command response ends with <Executed/> (so find: ed/>)
                    if (byteOne == 0x3E && byteTwo == 0x2F && byteThree == 0x64 && byteFour == 0x65) {

                        // handle instrument calibration response
                        sampleByteCount++; // add the last byte found to the count

                        // add the last byte found to the sample buffer
                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            sampleBuffer.put(byteOne);

                        }

                        // extract the sampleByteCount length from the sampleBuffer
                        sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        this.responseString = new String(sampleArray, "US-ASCII");

                        // set the CTD metadata
                        int executedIndex = this.responseString.indexOf("<Executed/>");
                        this.responseString = this.responseString.substring(0, executedIndex - 1);

                        this.ctdParser.setMetadata(this.responseString);

                        // reset variables for the next sample
                        sampleBuffer.clear();
                        sampleByteCount = 0;

                        // then get the instrument event metadata
                        if (!this.ctdParser.getHasEventMetadata()) {

                            this.command = this.commandPrefix + this.getEventsCommand + this.commandSuffix;
                            this.sentCommand = queryInstrument(command);
                            streamingThread.sleep(5000);
                            this.state = 7;
                            break;

                        } else {

                            this.command = this.commandPrefix + this.getHardwareCommand + this.commandSuffix;
                            this.sentCommand = queryInstrument(command);
                            streamingThread.sleep(5000);
                            this.state = 8;
                            break;

                        }

                    } else {
                        break; // continue reading bytes

                    }

                case 7: // handle instrument event metadata

                    // command response ends with <Executed/> (so find: ed/>)
                    if (byteOne == 0x3E && byteTwo == 0x2F && byteThree == 0x64 && byteFour == 0x65) {

                        // handle instrument events response
                        sampleByteCount++; // add the last byte found to the count

                        // add the last byte found to the sample buffer
                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            sampleBuffer.put(byteOne);

                        }

                        // extract the sampleByteCount length from the sampleBuffer
                        sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        this.responseString = new String(sampleArray, "US-ASCII");

                        // set the CTD metadata
                        int executedIndex = this.responseString.indexOf("<Executed/>");
                        this.responseString = this.responseString.substring(0, executedIndex - 1);

                        this.ctdParser.setMetadata(this.responseString);

                        // reset variables for the next sample
                        sampleBuffer.clear();
                        sampleByteCount = 0;

                        // then get the instrument hardware metadata
                        if (!this.ctdParser.getHasHardwareMetadata()) {

                            this.command = this.commandPrefix + this.getHardwareCommand + this.commandSuffix;
                            this.sentCommand = queryInstrument(command);
                            streamingThread.sleep(5000);
                            this.state = 8;
                            break;

                        } else {

                            this.state = 9;
                            break;

                        }

                    } else {
                        break; // continue reading bytes

                    }

                case 8: // handle the instrument hardware response

                    // command response ends with <Executed/> (so find: ed/>)
                    if (byteOne == 0x3E && byteTwo == 0x2F && byteThree == 0x64 && byteFour == 0x65) {

                        // handle instrument hardware response
                        sampleByteCount++; // add the last byte found to the count

                        // add the last byte found to the sample buffer
                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            sampleBuffer.put(byteOne);

                        }

                        // extract the sampleByteCount length from the sampleBuffer
                        sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        this.responseString = new String(sampleArray, "US-ASCII");

                        // set the CTD metadata
                        int executedIndex = this.responseString.indexOf("<Executed/>");
                        this.responseString = this.responseString.substring(0, executedIndex - 1);

                        this.ctdParser.setMetadata(this.responseString);

                        // reset variables for the next sample
                        sampleBuffer.clear();
                        sampleByteCount = 0;

                        // sync the clock if it is not synced
                        if (!this.clockIsSynced) {

                            this.state = 9;
                            break;

                        } else {
                            this.state = 10;
                            break;

                        }

                    } else {
                        break; // continue reading bytes

                    }

                case 9: // set the instrument clock

                    // is sampling stopped?
                    if (!this.samplingIsStopped) {
                        // wake the instrument with an initial '\r\n' command
                        this.command = this.commandSuffix;
                        this.sentCommand = queryInstrument(this.command);
                        streamingThread.sleep(2000);

                        // then stop the sampling
                        this.command = this.commandPrefix + this.stopSamplingCommand + this.commandSuffix;
                        this.sentCommand = queryInstrument(command);
                        this.samplingIsStopped = true;

                    }

                    // now set the clock
                    if (this.sentCommand) {
                        this.clockSyncDate = new Date();
                        DATE_FORMAT.setTimeZone(TZ);
                        String dateAsString = DATE_FORMAT.format(this.clockSyncDate);

                        this.command = this.commandPrefix + this.setDateTimeCommand + dateAsString
                                + this.commandSuffix;
                        this.sentCommand = queryInstrument(command);
                        streamingThread.sleep(5000);
                        this.clockIsSynced = true;
                        logger.info("The instrument clock has bee synced at " + this.clockSyncDate.toString());
                        this.state = 10;
                        break;

                    } else {

                        break; // try the clock sync again due to failure

                    }

                case 10: // restart the instrument sampling

                    if (this.samplingIsStopped) {

                        this.hasMetadata = true;

                        this.command = this.commandPrefix + this.startSamplingCommand + this.commandSuffix;
                        this.sentCommand = queryInstrument(command);
                        streamingThread.sleep(5000);

                        if (this.sentCommand) {
                            this.state = 11;
                            break;

                        } else {
                            break; // try starting the sampling again due to failure
                        }

                    } else {

                        break;

                    }

                case 11: // read bytes to the next EOL characters

                    // sample line is terminated by \r\n
                    // note bytes are in reverse order in the FIFO window
                    if (byteOne == 0x0A && byteTwo == 0x0D) {

                        sampleByteCount++; // add the last byte found to the count

                        // add the last byte found to the sample buffer
                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            sampleBuffer.put(byteOne);

                        }

                        // extract just the length of the sample bytes out of the
                        // sample buffer, and place it in the channel map as a 
                        // byte array.  Then, send it to the data turbine.
                        sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);

                        this.responseString = new String(sampleArray, "US-ASCII");

                        // test if the sample is not just an instrument message
                        if (this.responseString.matches("^# [0-9].*\r\n")
                                || this.responseString.matches("^#  [0-9].*\r\n")
                                || this.responseString.matches("^ [0-9].*\r\n")) {

                            // add the data observations string to the CTDParser object
                            // and populate the CTDParser data fields
                            //this.ctdParser.setData(this.responseString);
                            //this.ctdParser.parse();

                            // build the channel map with all of the data and metadata channels:                  
                            int channelIndex = rbnbChannelMap.Add(getRBNBChannelName());
                            rbnbChannelMap.PutMime(channelIndex, "text/plain");
                            rbnbChannelMap.PutTimeAuto("server");

                            // add the ASCII sample data field
                            rbnbChannelMap.PutDataAsString(channelIndex, this.responseString);

                            // add other metadata and data fields to the map if metadata was collected
                            if (this.hasMetadata && this.ctdParser != null) {

                                // add the samplingMode field data                                                                                 
                                channelIndex = rbnbChannelMap.Add("samplingMode");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getSamplingMode()); // String

                                // add the temperatureSerialNumber field data                                                                      
                                channelIndex = rbnbChannelMap.Add("temperatureSerialNumber");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getTemperatureSerialNumber()); // String   

                                // add the conductivitySerialNumber field data                                                                     
                                channelIndex = rbnbChannelMap.Add("conductivitySerialNumber");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getConductivitySerialNumber()); // String   

                                // add the mainBatteryVoltage field data                                                                           
                                channelIndex = rbnbChannelMap.Add("mainBatteryVoltage");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getMainBatteryVoltage() }); // double   

                                // add the lithiumBatteryVoltage field data                                                                        
                                channelIndex = rbnbChannelMap.Add("lithiumBatteryVoltage");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getLithiumBatteryVoltage() }); // double   

                                // add the operatingCurrent field data                                                                             
                                channelIndex = rbnbChannelMap.Add("operatingCurrent");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getOperatingCurrent() }); // double   

                                // add the pumpCurrent field data                                                                                  
                                channelIndex = rbnbChannelMap.Add("pumpCurrent");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPumpCurrent() }); // double   

                                // add the channels01ExternalCurrent field data                                                                    
                                channelIndex = rbnbChannelMap.Add("channels01ExternalCurrent");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getChannels01ExternalCurrent() }); // double   

                                // add the channels23ExternalCurrent field data                                                                    
                                channelIndex = rbnbChannelMap.Add("channels23ExternalCurrent");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getChannels23ExternalCurrent() }); // double   

                                // add the loggingStatus field data                                                                                
                                channelIndex = rbnbChannelMap.Add("loggingStatus");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getLoggingStatus()); // String   

                                // add the numberOfScansToAverage field data                                                                       
                                channelIndex = rbnbChannelMap.Add("numberOfScansToAverage");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsInt32(channelIndex,
                                        new int[] { this.ctdParser.getNumberOfScansToAverage() }); // int      

                                // add the numberOfSamples field data                                                                              
                                channelIndex = rbnbChannelMap.Add("numberOfSamples");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsInt32(channelIndex,
                                        new int[] { this.ctdParser.getNumberOfSamples() }); // int      

                                // add the numberOfAvailableSamples field data                                                                     
                                channelIndex = rbnbChannelMap.Add("numberOfAvailableSamples");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsInt32(channelIndex,
                                        new int[] { this.ctdParser.getNumberOfAvailableSamples() }); // int      

                                // add the sampleInterval field data                                                                               
                                channelIndex = rbnbChannelMap.Add("sampleInterval");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsInt32(channelIndex,
                                        new int[] { this.ctdParser.getSampleInterval() }); // int      

                                // add the measurementsPerSample field data                                                                        
                                channelIndex = rbnbChannelMap.Add("measurementsPerSample");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsInt32(channelIndex,
                                        new int[] { this.ctdParser.getMeasurementsPerSample() }); // int      

                                // add the transmitRealtime field data                                                                             
                                channelIndex = rbnbChannelMap.Add("transmitRealtime");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getTransmitRealtime()); // String   

                                // add the numberOfCasts field data                                                                                
                                channelIndex = rbnbChannelMap.Add("numberOfCasts");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsInt32(channelIndex,
                                        new int[] { this.ctdParser.getNumberOfCasts() }); // int      

                                // add the minimumConductivityFrequency field data                                                                 
                                channelIndex = rbnbChannelMap.Add("minimumConductivityFrequency");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsInt32(channelIndex,
                                        new int[] { this.ctdParser.getMinimumConductivityFrequency() }); // int      

                                // add the pumpDelay field data                                                                                    
                                channelIndex = rbnbChannelMap.Add("pumpDelay");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsInt32(channelIndex,
                                        new int[] { this.ctdParser.getPumpDelay() }); // int      

                                // add the automaticLogging field data                                                                             
                                channelIndex = rbnbChannelMap.Add("automaticLogging");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getAutomaticLogging()); // String   

                                // add the ignoreMagneticSwitch field data                                                                         
                                channelIndex = rbnbChannelMap.Add("ignoreMagneticSwitch");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getIgnoreMagneticSwitch()); // String   

                                // add the batteryType field data                                                                                  
                                channelIndex = rbnbChannelMap.Add("batteryType");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getBatteryType()); // String   

                                // add the batteryCutoff field data                                                                                
                                channelIndex = rbnbChannelMap.Add("batteryCutoff");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getBatteryCutoff()); // String   

                                // add the pressureSensorType field data                                                                           
                                channelIndex = rbnbChannelMap.Add("pressureSensorType");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getPressureSensorType()); // String   

                                // add the pressureSensorRange field data                                                                          
                                channelIndex = rbnbChannelMap.Add("pressureSensorRange");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getPressureSensorRange()); // String   

                                // add the sbe38TemperatureSensor field data                                                                       
                                channelIndex = rbnbChannelMap.Add("sbe38TemperatureSensor");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getSbe38TemperatureSensor()); // String   

                                // add the gasTensionDevice field data                                                                             
                                channelIndex = rbnbChannelMap.Add("gasTensionDevice");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getGasTensionDevice()); // String   

                                // add the externalVoltageChannelZero field data                                                                   
                                channelIndex = rbnbChannelMap.Add("externalVoltageChannelZero");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getExternalVoltageChannelZero()); // String   

                                // add the externalVoltageChannelOne field data                                                                    
                                channelIndex = rbnbChannelMap.Add("externalVoltageChannelOne");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getExternalVoltageChannelOne()); // String   

                                // add the externalVoltageChannelTwo field data                                                                    
                                channelIndex = rbnbChannelMap.Add("externalVoltageChannelTwo");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getExternalVoltageChannelTwo()); // String   

                                // add the externalVoltageChannelThree field data                                                                  
                                channelIndex = rbnbChannelMap.Add("externalVoltageChannelThree");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getExternalVoltageChannelThree()); // String   

                                // add the echoCommands field data                                                                                 
                                channelIndex = rbnbChannelMap.Add("echoCommands");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getEchoCommands()); // String   

                                // add the outputFormat field data                                                                                 
                                channelIndex = rbnbChannelMap.Add("outputFormat");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getOutputFormat()); // String   

                                // add the temperatureCalibrationDate field data                                                                   
                                channelIndex = rbnbChannelMap.Add("temperatureCalibrationDate");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getTemperatureCalibrationDate()); // String   

                                // add the temperatureCoefficientTA0 field data                                                                    
                                channelIndex = rbnbChannelMap.Add("temperatureCoefficientTA0");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getTemperatureCoefficientTA0() }); // double   

                                // add the temperatureCoefficientTA1 field data                                                                    
                                channelIndex = rbnbChannelMap.Add("temperatureCoefficientTA1");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getTemperatureCoefficientTA1() }); // double   

                                // add the temperatureCoefficientTA2 field data                                                                    
                                channelIndex = rbnbChannelMap.Add("temperatureCoefficientTA2");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getTemperatureCoefficientTA2() }); // double   

                                // add the temperatureCoefficientTA3 field data                                                                    
                                channelIndex = rbnbChannelMap.Add("temperatureCoefficientTA3");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getTemperatureCoefficientTA3() }); // double   

                                // add the temperatureOffsetCoefficient field data                                                                 
                                channelIndex = rbnbChannelMap.Add("temperatureOffsetCoefficient");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getTemperatureOffsetCoefficient() }); // double   

                                // add the conductivityCalibrationDate field data                                                                  
                                channelIndex = rbnbChannelMap.Add("conductivityCalibrationDate");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getConductivityCalibrationDate()); // String   

                                // add the conductivityCoefficientG field data                                                                     
                                channelIndex = rbnbChannelMap.Add("conductivityCoefficientG");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getConductivityCoefficientG() }); // double   

                                // add the conductivityCoefficientH field data                                                                     
                                channelIndex = rbnbChannelMap.Add("conductivityCoefficientH");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getConductivityCoefficientH() }); // double   

                                // add the conductivityCoefficientI field data                                                                     
                                channelIndex = rbnbChannelMap.Add("conductivityCoefficientI");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getConductivityCoefficientI() }); // double   

                                // add the conductivityCoefficientJ field data                                                                     
                                channelIndex = rbnbChannelMap.Add("conductivityCoefficientJ");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getConductivityCoefficientJ() }); // double   

                                // add the conductivityCoefficientCF0 field data                                                                   
                                channelIndex = rbnbChannelMap.Add("conductivityCoefficientCF0");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getConductivityCoefficientCF0() }); // double   

                                // add the conductivityCoefficientCPCOR field data                                                                 
                                channelIndex = rbnbChannelMap.Add("conductivityCoefficientCPCOR");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getConductivityCoefficientCPCOR() }); // double   

                                // add the conductivityCoefficientCTCOR field data                                                                 
                                channelIndex = rbnbChannelMap.Add("conductivityCoefficientCTCOR");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getConductivityCoefficientCTCOR() }); // double   

                                // add the conductivityCoefficientCSLOPE field data                                                                
                                channelIndex = rbnbChannelMap.Add("conductivityCoefficientCSLOPE");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getConductivityCoefficientCSLOPE() }); // double   

                                // add the pressureSerialNumber field data                                                                         
                                channelIndex = rbnbChannelMap.Add("pressureSerialNumber");
                                rbnbChannelMap.PutMime(channelIndex, "text/plain");
                                rbnbChannelMap.PutDataAsString(channelIndex,
                                        this.ctdParser.getPressureSerialNumber()); // String   

                                // add the pressureCoefficientPA0 field data                                                                       
                                channelIndex = rbnbChannelMap.Add("pressureCoefficientPA0");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureCoefficientPA0() }); // double   

                                // add the pressureCoefficientPA1 field data                                                                       
                                channelIndex = rbnbChannelMap.Add("pressureCoefficientPA1");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureCoefficientPA1() }); // double   

                                // add the pressureCoefficientPA2 field data                                                                       
                                channelIndex = rbnbChannelMap.Add("pressureCoefficientPA2");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureCoefficientPA2() }); // double   

                                // add the pressureCoefficientPTCA0 field data                                                                     
                                channelIndex = rbnbChannelMap.Add("pressureCoefficientPTCA0");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureCoefficientPTCA0() }); // double   

                                // add the pressureCoefficientPTCA1 field data                                                                     
                                channelIndex = rbnbChannelMap.Add("pressureCoefficientPTCA1");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureCoefficientPTCA1() }); // double   

                                // add the pressureCoefficientPTCA2 field data                                                                     
                                channelIndex = rbnbChannelMap.Add("pressureCoefficientPTCA2");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureCoefficientPTCA2() }); // double   

                                // add the pressureCoefficientPTCB0 field data                                                                     
                                channelIndex = rbnbChannelMap.Add("pressureCoefficientPTCB0");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureCoefficientPTCB0() }); // double   

                                // add the pressureCoefficientPTCB1 field data                                                                     
                                channelIndex = rbnbChannelMap.Add("pressureCoefficientPTCB1");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureCoefficientPTCB1() }); // double   

                                // add the pressureCoefficientPTCB2 field data                                                                     
                                channelIndex = rbnbChannelMap.Add("pressureCoefficientPTCB2");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureCoefficientPTCB2() }); // double   

                                // add the pressureCoefficientPTEMPA0 field data                                                                   
                                channelIndex = rbnbChannelMap.Add("pressureCoefficientPTEMPA0");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureCoefficientPTEMPA0() }); // double   

                                // add the pressureCoefficientPTEMPA1 field data                                                                   
                                channelIndex = rbnbChannelMap.Add("pressureCoefficientPTEMPA1");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureCoefficientPTEMPA1() }); // double   

                                // add the pressureCoefficientPTEMPA2 field data                                                                   
                                channelIndex = rbnbChannelMap.Add("pressureCoefficientPTEMPA2");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureCoefficientPTEMPA2() }); // double   

                                // add the pressureOffsetCoefficient field data                                                                    
                                channelIndex = rbnbChannelMap.Add("pressureOffsetCoefficient");
                                rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                                rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                        new double[] { this.ctdParser.getPressureOffsetCoefficient() }); // double   
                            }

                            // send the sample to the data turbine
                            getSource().Flush(rbnbChannelMap);
                            logger.info("Sent sample to the DataTurbine: " + this.responseString);

                            // reset variables for the next sample
                            sampleBuffer.clear();
                            sampleByteCount = 0;
                            channelIndex = 0;
                            rbnbChannelMap.Clear();
                            logger.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap.");

                            // check if the clock needs syncing (daily)
                            if (this.enableSendCommands) {

                                // get the current datetime
                                Calendar currentCalendar = Calendar.getInstance();
                                currentCalendar.setTime(new Date());
                                Calendar lastSyncedCalendar = Calendar.getInstance();
                                lastSyncedCalendar.setTime(this.clockSyncDate);

                                // round the dates to the day
                                currentCalendar.clear(Calendar.MILLISECOND);
                                currentCalendar.clear(Calendar.SECOND);
                                currentCalendar.clear(Calendar.MINUTE);
                                currentCalendar.clear(Calendar.HOUR);

                                lastSyncedCalendar.clear(Calendar.MILLISECOND);
                                lastSyncedCalendar.clear(Calendar.SECOND);
                                lastSyncedCalendar.clear(Calendar.MINUTE);
                                lastSyncedCalendar.clear(Calendar.HOUR);

                                // sync the clock daily
                                if (currentCalendar.before(lastSyncedCalendar)) {
                                    this.state = 8;

                                }
                            }

                            // otherwise stay in state = 11                   
                            break;

                            // the sample looks more like an instrument message, don't flush
                        } else {

                            logger.info("This string does not look like a sample, "
                                    + "and was not sent to the DataTurbine.");
                            logger.info("Skipping sample: " + this.responseString);

                            // reset variables for the next sample
                            sampleBuffer.clear();
                            sampleByteCount = 0;
                            //rbnbChannelMap.Clear();                      
                            logger.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap.");
                            this.state = 11;
                            break;

                        }

                    } else { // not 0x0A0D

                        // still in the middle of the sample, keep adding bytes
                        sampleByteCount++; // add each byte found

                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);
                        } else {
                            sampleBuffer.compact();
                            logger.debug("Compacting sampleBuffer ...");
                            sampleBuffer.put(byteOne);

                        }

                        break;
                    } // end if for 0x0A0D EOL

                case 12: // alternatively use legacy DS and DCal commands

                    if (this.enableSendCommands) {

                        // start by getting the DS status output
                        this.command = this.commandPrefix + this.displayStatusCommand + this.commandSuffix;
                        this.sentCommand = queryInstrument(command);
                        streamingThread.sleep(5000);
                        this.state = 13;
                        break;

                    } else {

                        this.state = 0;
                        break;

                    }

                case 13: // handle the DS command response

                    // command should end with the S> prompt
                    if (byteOne == 0x7E && byteTwo == 0x53) {

                        // handle instrument status response
                        sampleByteCount++; // add the last byte found to the count

                        // add the last byte found to the sample buffer
                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            sampleBuffer.put(byteOne);

                        }

                        // extract the sampleByteCount length from the sampleBuffer
                        sampleArray = new byte[sampleByteCount - 2]; //subtract "S>"
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        this.responseString = new String(sampleArray, "US-ASCII");

                        // reset variables for the next sample
                        sampleBuffer.clear();
                        sampleByteCount = 0;

                        // then get the instrument calibration metadata
                        this.command = this.commandPrefix + this.displayCalibrationCommand + this.commandSuffix;
                        this.sentCommand = queryInstrument(command);
                        streamingThread.sleep(5000);
                        this.state = 14;
                        break;

                    } else {
                        break; // continue reading bytes

                    }

                case 14: // handle the DCal command response

                    // command should end with the S> prompt
                    if (byteOne == 0x7E && byteTwo == 0x53) {

                        // handle instrument status response
                        sampleByteCount++; // add the last byte found to the count

                        // add the last byte found to the sample buffer
                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            sampleBuffer.put(byteOne);

                        }

                        // extract the sampleByteCount length from the sampleBuffer
                        sampleArray = new byte[sampleByteCount - 2]; // subtract "S>"
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);

                        // append the DCal output to the DS output
                        this.responseString = this.responseString.concat(new String(sampleArray, "US-ASCII"));

                        // and add the data delimiter expected in the CTDParser
                        this.responseString = this.responseString.concat("*END*\r\n\r\n");

                        // build the CTDParser object with legacy DS and DCal metadata
                        this.ctdParser = new CTDParser(this.responseString);

                        // reset variables for the next sample
                        sampleBuffer.clear();
                        sampleByteCount = 0;

                        this.state = 9; // set the clock and start sampling
                        break;

                    } else {
                        break; // continue reading bytes

                    }

                } // end switch statement

                // shift the bytes in the FIFO window
                byteFour = byteThree;
                byteThree = byteTwo;
                byteTwo = byteOne;

            } //end while (more unread bytes)

            // prepare the buffer to read in more bytes from the stream
            buffer.compact();

        } // end while (more channel bytes to read)

        this.channel.close();

    } catch (IOException e) {
        // handle exceptions
        // In the event of an i/o exception, log the exception, and allow execute()
        // to return false, which will prompt a retry.
        failed = true;
        this.state = 0;

        // close the serial or socket channel
        if (this.channel != null && this.channel.isOpen()) {
            try {
                this.channel.close();

            } catch (IOException cioe) {
                logger.debug("An error occurred trying to close the byte channel. " + " The error message was: "
                        + cioe.getMessage());

            }
        }

        // disconnect from the RBNB
        if (isConnected()) {
            disconnect();
        }

        e.printStackTrace();
        return !failed;

    } catch (InterruptedException intde) {
        // in the event that the streamingThread is interrupted
        failed = true;
        this.state = 0;

        // close the serial or socket channel
        if (this.channel != null && this.channel.isOpen()) {
            try {
                this.channel.close();

            } catch (IOException cioe) {
                logger.debug("An error occurred trying to close the byte channel. " + " The error message was: "
                        + cioe.getMessage());

            }
        }

        // disconnect from the RBNB
        if (isConnected()) {
            disconnect();
        }

        intde.printStackTrace();
        return !failed;

    } catch (SAPIException sapie) {
        // In the event of an RBNB communication  exception, log the exception, 
        // and allow execute() to return false, which will prompt a retry.
        //this.channel.close();
        failed = true;
        this.state = 0;

        // close the serial or socket channel
        if (this.channel != null && this.channel.isOpen()) {
            try {
                this.channel.close();

            } catch (IOException cioe) {
                logger.debug("An error occurred trying to close the byte channel. " + " The error message was: "
                        + cioe.getMessage());

            }
        }

        // disconnect from the RBNB
        if (isConnected()) {
            disconnect();
        }

        sapie.printStackTrace();
        return !failed;

    } catch (ParseException pe) {
        failed = true;
        this.state = 0;

        // close the serial or socket channel
        if (this.channel != null && this.channel.isOpen()) {
            try {
                this.channel.close();

            } catch (IOException cioe) {
                logger.debug("An error occurred trying to close the byte channel. " + " The error message was: "
                        + cioe.getMessage());

            }
        }

        // disconnect from the RBNB
        if (isConnected()) {
            disconnect();
        }

        logger.info("There was an error parsing the metadata response. " + "The error message was: "
                + pe.getMessage());
        return !failed;

    } finally {

        this.state = 0;

        // close the serial or socket channel
        if (this.channel != null && this.channel.isOpen()) {
            try {
                this.channel.close();

            } catch (IOException cioe) {
                logger.debug("An error occurred trying to close the byte channel. " + " The error message was: "
                        + cioe.getMessage());

            }
        }

    }

    return !failed;
}

From source file:rems.Global.java

public static boolean isTransPrmttd(int accntID, String trnsdate, double amnt, String outptMsg[]) {
    try {//from  w w w .ja  va2  s  .co  m
        //trnsdate = DateTime.ParseExact(
        //trnsdate, "dd-MMM-yyyy HH:mm:ss",
        //System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss");
        //Transaction date must be >= the latest prd start date
        if (accntID <= 0 || trnsdate.equals("")) {
            return false;
        }

        SimpleDateFormat frmtr = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
        SimpleDateFormat frmtr1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat frmtr2 = new SimpleDateFormat("dd-MMM-yyyy");
        SimpleDateFormat frmtr3 = new SimpleDateFormat("dddd");
        Calendar trnsDte = Calendar.getInstance();
        trnsDte.setTime(frmtr.parse(trnsdate));
        Calendar dte1 = Calendar.getInstance();
        dte1.setTime(frmtr.parse(Global.getLtstPrdStrtDate()));
        Calendar dte1Or = Calendar.getInstance();
        dte1Or.setTime(frmtr.parse(Global.getLastPrdClseDate()));
        Calendar dte2 = Calendar.getInstance();
        dte2.setTime(frmtr.parse(Global.getLtstPrdEndDate()));

        if (trnsDte.equals(dte1Or) || trnsDte.before(dte1Or)) {
            outptMsg[0] += "Transaction Date cannot be On or Before " + frmtr.format(dte1Or);
            return false;
        }
        if (trnsDte.before(dte1)) {
            outptMsg[0] += "Transaction Date cannot be before " + frmtr.format(dte1);
            return false;
        }
        if (trnsDte.after(dte2)) {
            outptMsg[0] += "Transaction Date cannot be after " + frmtr.format(dte2);
            return false;
        }
        //Check if trnsDate exists in an Open Period
        long prdHdrID = Global.getPrdHdrID(Global.UsrsOrg_ID);
        //Global.showMsg(Global.Org_iString.valueOf(d) + "-" + prdHdrID.ToString(), 0);
        if (prdHdrID > 0) {
            //Global.showMsg(trnsDte.ToString("yyyy-MM-dd HH:mm:ss") + "-" + prdHdrID.ToString(), 0);
            if (Global.getTrnsDteOpenPrdLnID(prdHdrID, frmtr1.format(trnsDte)) < 0) {
                outptMsg[0] += "Cannot use a Transaction Date (" + frmtr.format(trnsDte)
                        + ") which does not exist in any OPEN period!";
                return false;
            }
            //Check if Date is not in Disallowed Dates
            String noTrnsDatesLov = Global.getGnrlRecNm("accb.accb_periods_hdr", "periods_hdr_id",
                    "no_trns_dates_lov_nm", prdHdrID);
            String noTrnsDayLov = Global.getGnrlRecNm("accb.accb_periods_hdr", "periods_hdr_id",
                    "no_trns_wk_days_lov_nm", prdHdrID);
            //Global.showMsg(noTrnsDatesLov + "-" + noTrnsDayLov + "-" + trnsDte.ToString("dddd").ToUpper() + "-" + trnsDte.ToString("dd-MMM-yyyy").ToUpper(), 0);

            if (!noTrnsDatesLov.equals("")) {
                if (Global.getEnbldPssblValID(frmtr2.format(trnsDte).toUpperCase(),
                        Global.getEnbldLovID(noTrnsDatesLov)) > 0) {
                    outptMsg[0] += "Transactions on this Date (" + frmtr.format(trnsDte)
                            + ") have been banned on this system!";
                    return false;
                }
            }
            //Check if Day of Week is not in Disaalowed days
            if (!noTrnsDatesLov.equals("")) {
                if (Global.getEnbldPssblValID(frmtr3.format(trnsDte).toUpperCase(),
                        Global.getEnbldLovID(noTrnsDayLov)) > 0) {
                    outptMsg[0] += "Transactions on this Day of Week (" + frmtr3.format(trnsDte)
                            + ") have been banned on this system!";
                    return false;
                }
            }
        }

        //Amount must not disobey budget settings on that account
        long actvBdgtID = Global.getActiveBdgtID(Global.UsrsOrg_ID);
        double amntLmt = Global.getAcntsBdgtdAmnt(actvBdgtID, accntID, frmtr.format(trnsDte));

        Calendar bdte1 = Calendar.getInstance();
        bdte1.setTime(frmtr.parse(Global.getAcntsBdgtStrtDte(actvBdgtID, accntID, frmtr.format(trnsDte))));

        Calendar bdte2 = Calendar.getInstance();
        bdte2.setTime(frmtr.parse(Global.getAcntsBdgtEndDte(actvBdgtID, accntID, frmtr.format(trnsDte))));

        double crntBals = Global.getTrnsSum(accntID, frmtr.format(bdte1), frmtr.format(bdte2), "1");

        String actn = Global.getAcntsBdgtLmtActn(actvBdgtID, accntID, trnsdate);

        if ((amnt + crntBals) > amntLmt) {
            if (actn.equals("Disallow")) {
                outptMsg[0] += "This transaction will cause budget on \r\nthe chosen account to be exceeded! ";
                return false;
            } else if (actn.equals("Warn")) {
                outptMsg[0] += "This is just to WARN you that the budget on \r\nthe chosen account will be exceeded!";
                return true;
            } else if (actn.equals("Congratulate")) {
                outptMsg[0] += "This is just to CONGRATULATE you for exceeding the targetted Amount! ";
                return true;
            } else {
                return true;
            }
        }
        return true;
    } catch (Exception ex) {
        outptMsg[0] += Arrays.toString(ex.getStackTrace()) + "\r\n" + ex.getMessage();
        return false;
    }
}