Example usage for java.lang NumberFormatException printStackTrace

List of usage examples for java.lang NumberFormatException printStackTrace

Introduction

In this page you can find the example usage for java.lang NumberFormatException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.capture.CaptureImageRealtime.java

/***********************************************************************************************
 * captureImageRealtime().//from ww  w  .jav  a2s.c  o m
 *
 * @param dao
 * @param commandmessage
 *
 * @return ResponseMessageInterface
 */

public static ResponseMessageInterface doCaptureImageRealtime(final ObservatoryInstrumentDAOInterface dao,
        final CommandMessageInterface commandmessage) {
    final String SOURCE = "CaptureImageRealtime.captureImageRealtime()";
    final int PARAMETER_COUNT = 4;
    final int INDEX_PATHNAME = 0;
    final int INDEX_INTERVAL = 1;
    final int INDEX_PERIOD = 2;
    final int INDEX_UPDATE = 3;
    final CommandType cmdCapture;
    final List<ParameterType> listParameters;
    String strResponseValue;
    final ResponseMessageInterface responseMessage;
    final List<String> errors;
    final boolean boolDebug;

    boolDebug = (LOADER_PROPERTIES.isTimingDebug() || LOADER_PROPERTIES.isMetadataDebug()
            || LOADER_PROPERTIES.isStaribusDebug() || LOADER_PROPERTIES.isStarinetDebug());

    // Initialise
    errors = new ArrayList<String>(10);
    dao.clearEventLogFragment();

    // Get the latest Resources
    dao.readResources();

    // Don't affect the CommandType of the incoming Command
    cmdCapture = (CommandType) commandmessage.getCommandType().copy();

    // We expect four parameters: the pathname, the capture interval, the capture period and the update flag
    listParameters = cmdCapture.getParameterList();

    // Ensure we are dealing with an Ethernet-based instrument
    if ((dao.getHostInstrument() != null) && (dao.getHostInstrument().getInstrument() != null)
            && (dao.getHostInstrument().getInstrument().getController() != null)
            && (dao.getHostInstrument().getInstrument().getController().getIPAddress() != null)
            && (listParameters != null) && (listParameters.size() == PARAMETER_COUNT)
            && (listParameters.get(INDEX_PATHNAME) != null)
            && (SchemaDataType.PATH_NAME
                    .equals(listParameters.get(INDEX_PATHNAME).getInputDataType().getDataTypeName()))
            && (listParameters.get(INDEX_INTERVAL) != null)
            && (SchemaDataType.DECIMAL_INTEGER
                    .equals(listParameters.get(INDEX_INTERVAL).getInputDataType().getDataTypeName()))
            && (listParameters.get(INDEX_PERIOD) != null)
            && (SchemaDataType.DECIMAL_INTEGER
                    .equals(listParameters.get(INDEX_PERIOD).getInputDataType().getDataTypeName()))
            && (listParameters.get(INDEX_UPDATE) != null)
            && (SchemaDataType.BOOLEAN
                    .equals(listParameters.get(INDEX_UPDATE).getInputDataType().getDataTypeName()))
            && (dao.getRemoteDataConnection() != null)) {
        try {
            final String strPathname;
            final String strCaptureInterval;
            final String strCapturePeriod;
            final boolean boolRealtimeUpdate;
            final int intCaptureIntervalSec;
            int intCapturePeriodSec;
            final HttpClient client;
            final HttpMethod method;
            final String strURL;

            strPathname = listParameters.get(INDEX_PATHNAME).getValue();
            strCaptureInterval = listParameters.get(INDEX_INTERVAL).getValue();
            strCapturePeriod = listParameters.get(INDEX_PERIOD).getValue();
            boolRealtimeUpdate = Boolean.parseBoolean(listParameters.get(INDEX_UPDATE).getValue());

            intCaptureIntervalSec = Integer.parseInt(strCaptureInterval);
            intCapturePeriodSec = Integer.parseInt(strCapturePeriod);

            // Check for silly parameter settings
            // CapturePeriod = 0 means run continuously
            if ((intCaptureIntervalSec > 0) && (intCapturePeriodSec >= 0)) {
                final String strPeriod;
                final int intCaptureCountMax;
                final ResponseMessageStatusList listStatusInCaptureLoop;
                boolean boolSuccess;

                if (intCapturePeriodSec == 0) {
                    strPeriod = CaptureCommandHelper.MSG_PERIOD_CONTINUOUS;
                } else {
                    strPeriod = Integer.toString(intCapturePeriodSec);
                }

                // We have all the Parameters, now prepare the HTTP client
                client = new HttpClient();
                client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        new DefaultHttpMethodRetryHandler(1, false));

                // Beware filename part (e.g. IMAGE.JPG) *must* be uppercase!
                // Assume that we are dealing with a valid Ethernet Controller
                strURL = ControlPanelInterface.PREFIX_HTTP + IPVersion.stripTrailingPaddingFromIPAddressAndPort(
                        dao.getHostInstrument().getInstrument().getController().getIPAddress());

                // The DAO HostID contains the Value of Property KEY_DAO_IMAGE_FILENAME
                method = new GetMethod(strURL + "/" + dao.getRemoteDataConnection().getHostname());

                // See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
                // The User-Agent request-header field contains information about the user agent originating the request
                method.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
                // The Referer[sic] request-header field allows the client to specify, for the server's benefit,
                // the address (URI) of the resource from which the Request-URI was obtained
                // (the "referrer", although the header field is misspelled.)
                method.setRequestHeader("Referer", strURL + "/Jview.htm");

                // Log everything we have so far
                SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.INFO,
                        METADATA_TARGET_IMAGE + METADATA_ACTION_CAPTURE + METADATA_PATHNAME + strPathname
                                + TERMINATOR_SPACE + METADATA_INTERVAL + intCaptureIntervalSec
                                + TERMINATOR_SPACE + METADATA_PERIOD + strPeriod + TERMINATOR_SPACE
                                + METADATA_ADDRESS + strURL + "/" + dao.getRemoteDataConnection().getHostname()
                                + TERMINATOR,
                        dao.getLocalHostname(), dao.getObservatoryClock());

                // Correct the CapturePeriod for continuous operation
                if (intCapturePeriodSec == 0) {
                    // Allow about 10 days of operation! (Could be Integer.MAX_VALUE?)
                    intCapturePeriodSec = 1000000;
                }

                intCaptureCountMax = intCapturePeriodSec / intCaptureIntervalSec;
                listStatusInCaptureLoop = ResponseMessageStatus.createResponseMessageStatusList();
                boolSuccess = true;

                // Establish the identity of this Instrument using Metadata
                // from the Framework, Observatory and Observer
                dao.establishDAOIdentityForCapture(DAOCommandHelper.getCommandCategory(cmdCapture), 0, false,
                        null, null);

                for (int intCaptureIndex = 0; ((intCaptureIndex < intCaptureCountMax) && (boolSuccess)
                        && Utilities.executeWorkerCanProceed(dao)); intCaptureIndex++) {
                    final long longTimeStart;
                    final long longTimeFinish;
                    final long longTimeToWait;

                    longTimeStart = dao.getObservatoryClock().getSystemTimeMillis();
                    listStatusInCaptureLoop.clear();

                    try {
                        final int intStatus;
                        final InputStream inputStream;

                        // Now try to get the Image
                        intStatus = client.executeMethod(method);

                        // Check the server status
                        if (intStatus != HttpStatus.SC_OK) {
                            SimpleEventLogUIComponent
                                    .logEvent(dao.getEventLogFragment(), EventStatus.WARNING,
                                            ObservatoryInstrumentDAOInterface.ERROR_HTTP + SPACE
                                                    + method.getStatusLine(),
                                            SOURCE, dao.getObservatoryClock());
                        }

                        // It is vital that the response body is always read,
                        // regardless of the status returned by the server.
                        inputStream = method.getResponseBodyAsStream();

                        if (inputStream != null) {
                            final BufferedImage image;

                            image = ImageIO.read(inputStream);

                            // If we get here, it must have succeeded... (otherwise IOException, ImageFormatException)
                            // Save the image as a timestamped PNG file every time
                            boolSuccess = DataExporter.exportImage(image, strPathname + "/CapturedImage", true,
                                    FileUtilities.png, dao.getEventLogFragment(), dao.getObservatoryClock());

                            // Pass the Image to the DAO, and then to the Instrument and InstrumentPanel
                            if (boolRealtimeUpdate) {
                                dao.setImageData(image);
                                dao.setUnsavedData(true);

                                REGISTRY.getFramework().notifyFrameworkChangedEvent(dao.getHostInstrument());
                                InstrumentHelper.notifyInstrumentChanged(dao.getHostInstrument());
                            }

                            inputStream.close();
                            listStatusInCaptureLoop.add(ResponseMessageStatus.SUCCESS);
                        } else {
                            // No data are available
                            SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING,
                                    ObservatoryInstrumentDAOInterface.ERROR_PARSE_DATA, SOURCE,
                                    dao.getObservatoryClock());
                        }
                    }

                    catch (NumberFormatException exception) {
                        SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL,
                                ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(),
                                SOURCE, dao.getObservatoryClock());
                    }

                    catch (IllegalArgumentException exception) {
                        SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL,
                                ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(),
                                SOURCE, dao.getObservatoryClock());
                    }

                    catch (HttpException exception) {
                        SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING,
                                ObservatoryInstrumentDAOInterface.ERROR_HTTP + exception.getMessage(), SOURCE,
                                dao.getObservatoryClock());
                    }

                    catch (IOException exception) {
                        SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING,
                                ObservatoryInstrumentDAOInterface.ERROR_IO + exception.getMessage(), SOURCE,
                                dao.getObservatoryClock());
                    }

                    // Take account of the time elapsed so far...
                    longTimeFinish = dao.getObservatoryClock().getSystemTimeMillis();
                    longTimeToWait = (intCaptureIntervalSec * ChronosHelper.SECOND_MILLISECONDS)
                            - (longTimeFinish - longTimeStart);

                    if (longTimeToWait > 0) {
                        // Wait for the required time
                        Utilities.safeSleepPollExecuteWorker(longTimeToWait, dao);
                    } else {
                        LOGGER.error(SOURCE + " Invalid capture interval [time_to_wait=" + longTimeToWait
                                + " msec]");
                    }
                }

                // Always release the HttpClient connection
                method.releaseConnection();

                //-----------------------------------------------------------------------------
                // Capture the final Status and ResponseValue (these may show a failure)

                dao.getResponseMessageStatusList().addAll(listStatusInCaptureLoop);

                if (dao.getResponseMessageStatusList().contains(ResponseMessageStatus.SUCCESS)) {
                    strResponseValue = ResponseMessageStatus.SUCCESS.getResponseValue();
                } else {
                    SimpleEventLogUIComponent.logErrors(dao.getEventLogFragment(), EventStatus.FATAL, errors,
                            SOURCE, dao.getObservatoryClock());
                    strResponseValue = ResponseMessageStatus.PREMATURE_TERMINATION.getResponseValue();
                }
            } else {
                throw new IllegalArgumentException(EXCEPTION_PARAMETER_INVALID);
            }
        }

        catch (NumberFormatException exception) {
            SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL,
                    METADATA_EXCEPTION + ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT
                            + exception.getMessage() + TERMINATOR,
                    dao.getLocalHostname(), dao.getObservatoryClock());
            strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue();
            dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER);
        }

        catch (IllegalArgumentException exception) {
            SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL,
                    METADATA_EXCEPTION + ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT
                            + exception.getMessage() + TERMINATOR,
                    dao.getLocalHostname(), dao.getObservatoryClock());
            strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue();
            dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER);
        }

        catch (Exception exception) {
            exception.printStackTrace();
            SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING,
                    METADATA_EXCEPTION + dao.getInstrumentName() + " Generic Exception [exception="
                            + exception.getMessage() + "]" + TERMINATOR,
                    dao.getLocalHostname(), dao.getObservatoryClock());
            strResponseValue = ResponseMessageStatus.INVALID_MESSAGE.getResponseValue();
            dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_MESSAGE);
        }
    } else {
        // Incorrectly configured XML
        strResponseValue = ResponseMessageStatus.INVALID_XML.getResponseValue();
        dao.getResponseMessageStatusList().add(
                DAOCommandHelper.logInvalidXML(dao, SOURCE, METADATA_TARGET_IMAGE, METADATA_ACTION_CAPTURE));
    }

    ObservatoryInstrumentHelper.runGarbageCollector();

    responseMessage = ResponseMessageHelper.createResponseMessage(dao, commandmessage, cmdCapture, null, null,
            strResponseValue);
    return (responseMessage);
}

From source file:com.znsx.cms.web.controller.TmDeviceController.java

@InterfaceDescription(logon = true, method = "Create_Vehicle_Detector", cmd = "2200")
@RequestMapping("/create_vehicle_detector.json")
public void createVehicleDetector(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String name = request.getParameter("name");
    if (StringUtils.isBlank(name)) {
        throw new BusinessException(ErrorCode.PARAMETER_NOT_FOUND, "missing [name]");
    }/*ww  w.ja  va 2 s  .c o m*/
    name = StringUtils.replace(name, " ", "+");
    String standardNumber = request.getParameter("standardNumber");
    if (StringUtils.isBlank(standardNumber)) {
        throw new BusinessException(ErrorCode.PARAMETER_NOT_FOUND, "missing [standardNumber]");
    }

    String dasId = request.getParameter("dasId");
    if (StringUtils.isBlank(dasId)) {
        throw new BusinessException(ErrorCode.PARAMETER_NOT_FOUND, "missing [dasId]");
    }

    String organId = request.getParameter("organId");
    if (StringUtils.isBlank(organId)) {
        throw new BusinessException(ErrorCode.PARAMETER_NOT_FOUND, "missing [organId]");
    }

    Integer period = null;
    String periodString = request.getParameter("period");
    if (StringUtils.isBlank(periodString)) {
        throw new BusinessException(ErrorCode.PARAMETER_NOT_FOUND, "missing [period]");
    } else {
        try {
            period = Integer.parseInt(periodString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.PARAMETER_INVALID,
                    "Parameter period[" + periodString + "] invalid !");
        }

    }

    String stakeNumber = request.getParameter("stakeNumber");
    stakeNumber = StringUtils.replace(stakeNumber, " ", "+");
    String longitude = request.getParameter("longitude");
    String latitude = request.getParameter("latitude");

    Integer sUpLimit = null;
    String sUpLimitString = request.getParameter("sUpLimit");
    if (StringUtils.isNotBlank(sUpLimitString)) {
        try {
            sUpLimit = Integer.parseInt(sUpLimitString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.PARAMETER_INVALID,
                    "Parameter coConctValue[" + sUpLimitString + "] invalid !");
        }
    }

    Integer sLowLimit = null;
    String sLowLimitString = request.getParameter("sLowLimit");
    if (StringUtils.isNotBlank(sLowLimitString)) {
        try {
            sLowLimit = Integer.parseInt(sLowLimitString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.PARAMETER_INVALID,
                    "Parameter visibilityValue[" + sLowLimitString + "] invalid !");
        }
    }

    Integer oUpLimit = null;
    String oUpLimitString = request.getParameter("oUpLimit");
    if (StringUtils.isNotBlank(oUpLimitString)) {
        try {
            oUpLimit = Integer.parseInt(oUpLimitString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.PARAMETER_INVALID,
                    "Parameter visibilityValue[" + oUpLimitString + "] invalid !");
        }
    }

    Integer oLowLimit = null;
    String oLowLimitString = request.getParameter("oLowLimit");
    if (StringUtils.isNotBlank(oLowLimitString)) {
        try {
            oLowLimit = Integer.parseInt(oLowLimitString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.PARAMETER_INVALID,
                    "Parameter visibilityValue[" + oLowLimitString + "] invalid !");
        }
    }

    Integer vUpLimit = null;
    String vUpLimitString = request.getParameter("vUpLimit");
    if (StringUtils.isNotBlank(vUpLimitString)) {
        try {
            vUpLimit = Integer.parseInt(vUpLimitString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.PARAMETER_INVALID,
                    "Parameter visibilityValue[" + vUpLimitString + "] invalid !");
        }
    }

    Integer vLowLimit = null;
    String vLowLimitString = request.getParameter("vLowLimit");
    if (StringUtils.isNotBlank(vLowLimitString)) {
        try {
            vLowLimit = Integer.parseInt(vLowLimitString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.PARAMETER_INVALID,
                    "Parameter visibilityValue[" + vLowLimitString + "] invalid !");
        }
    }

    String note = request.getParameter("note");
    String navigation = request.getParameter("navigation");
    String ip = request.getParameter("ip");
    String port = request.getParameter("port");
    String laneNumber = request.getParameter("laneNumber");
    String reserve = request.getParameter("reserve");
    // License
    License license = licenseManager.getLicense();
    int deviceAmount = Integer.parseInt(license.getDeviceAmount());
    int deviceCount = tmDeviceManager.countDeviceAmount();
    if (deviceCount >= deviceAmount) {
        throw new BusinessException(ErrorCode.DEVICE_AMOUNT_LIMIT, "Device amount over license limit !");
    }

    String id = deviceManager.createVehicleDetector(name, standardNumber, dasId, organId, period, stakeNumber,
            longitude, latitude, sUpLimit, sLowLimit, oUpLimit, oLowLimit, vUpLimit, vLowLimit, note,
            navigation, ip, port, laneNumber, reserve);

    BaseDTO dto = new BaseDTO();
    dto.setCmd("2210");
    dto.setMethod("Create_Weather_Stat");
    dto.setMessage(id + "");

    writePage(response, dto);
}

From source file:org.accada.reader.rprm.core.msg.MessageLayer.java

/**
 * Initializes the messaging layer and starts the reader device.
 *
 * @param reader reference to the ReaderDevice
 *//*from  w w w . j a  va 2 s.  c o m*/
private void initialize() {
    log.debug("**************************************");
    log.debug("* MessageLayer is beeing initialized *");
    log.debug("**************************************");

    readMgmtAgentProperties(MessageLayer.mgmtAgentPropFile, MessageLayer.mgmtAgentDefaultPropFile);

    switch (MessageLayer.mgmtAgentType) {

    case SNMP:

        /*************************
         *   create SNMP agent   *
         *************************/

        String bootCounterFileName = "SnmpAgentBC.cfg";
        String configFileName = "SnmpAgentConfig.cfg";
        File bootCounterFile = new File(bootCounterFileName);
        File configFile = new File(configFileName);

        // delete the old files
        bootCounterFile.delete();
        configFile.delete();

        // create agent
        snmpAgent = SnmpAgent.create(bootCounterFile, configFile, mgmtAgentAddress + "/" + mgmtAgentPort);
        break;

    // case ...:

    }

    /*************************
     *     MessageLayer      *
     *************************/

    String connType;

    // sets the parameters according to the properties file
    try {
        Map serverConns = new HashMap();
        MessageLayerConfiguration conf = MessageLayerConfiguration.getInstance();

        try {
            ConnectionThreadPool.create(conf.getThreadPoolSize());

        } catch (NumberFormatException e) {
            log.error(
                    "Could not interpret the threadPoolSize from the property file. Please ensure to use a correct integer format.");
        }

        if (conf.hasTcpServerConnection()) {
            connType = ServerConnection.TCP_SERVER;
            try {
                int tcpPort = conf.getTcpPort();
                serverConns.put(connType, new Integer(tcpPort));
            } catch (NumberFormatException e) {
                log.error(
                        "Could not interpret the tcpPort from the property file. Please ensure to use a correct integer format.");
            }
        }

        if (conf.hasHttpServerConnection()) {
            connType = ServerConnection.HTTP_SERVER;
            try {
                int httpPort = conf.getHttpPort();
                serverConns.put(connType, new Integer(httpPort));
            } catch (NumberFormatException e) {
                log.error(
                        "Could not interpret the httpPort from the property file. Please ensure to use a correct integer format.");
            }
        }

        try {
            notificationListenTimeout = conf.getNotificationListenTimeout();
        } catch (NumberFormatException e) {
            log.error(
                    "Could not interpret the notificationListenTimeout from the property file. Please ensure to use a correct integer format.");
        }

        // create the message buffer
        log.debug("creating an IncomingMessageBuffer");
        mbuffer = IncomingMessageBuffer.getInstance();

        // create clients
        log.debug("creating Clients");
        clients = Clients.getInstance();

        // create the outgoing message dispatcher
        log.debug("creating an OutgoingMessageDispatcher");
        outDispatcher = OutgoingMessageDispatcher.getInstance();
        outDispatcher.initialize(clients);

        // create and init the service dispatcher
        log.debug("creating a ServiceDispatcher");
        sDispatcher = MessageDispatcher.getInstance(this);
        sDispatcher.initialize(mbuffer, clients, outDispatcher);
        sDispatcher.start();

        log.debug("creating ServiceConnection");
        Iterator iter = serverConns.keySet().iterator();

        while (iter.hasNext()) {
            String cType = (String) iter.next();
            ServerConnection.createServerConnection(cType, ((Integer) serverConns.get(cType)).intValue(),
                    mbuffer);
        }

        ReaderDevice readerDevice = ReaderDevice.getInstance();

        switch (MessageLayer.mgmtAgentType) {

        case SNMP:

            /*************************
             * initialize SNMP agent *
             *************************/

            snmpAgent.init();
            snmpAgent.loadConfig(ImportModes.UPDATE_CREATE);

            // We need to add the alarm channels again because at their
            // creation the SNMP agent was not initialized yet.
            Enumeration<AlarmChannel> alarmChanIter = readerDevice.getAlarmChannels().elements();
            while (alarmChanIter.hasMoreElements()) {
                snmpAgent.addAlarmChannels(new AlarmChannel[] { alarmChanIter.nextElement() });
            }

            snmpAgent.run();
            break;

        // case ...:

        }

        if (mgmtSimulatorStart) {
            MgmtSimulator inst = new MgmtSimulator(readerDevice);
            inst.setVisible(true);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.importers.ImportGOESRealtime.java

/***********************************************************************************************
 * doImportGOESRealtime()./*from ww w.  j a va 2s .c o  m*/
 *
 * @param dao
 * @param commandmessage
 *
 * @return ResponseMessageInterface
 */

public static ResponseMessageInterface doImportGOESRealtime(final ObservatoryInstrumentDAOInterface dao,
        final CommandMessageInterface commandmessage) {
    final String SOURCE = "ImportGOESRealtime.doImportGOESRealtime()";
    final int PARAMETER_COUNT = 5;
    final int INDEX_URL = 0;
    final int INDEX_PATHNAME = 1;
    final int INDEX_INTERVAL = 2;
    final int INDEX_PERIOD = 3;
    final int INDEX_UPDATE = 4;
    final CommandType cmdImport;
    final List<ParameterType> listParameters;
    String strResponseValue;
    final ResponseMessageInterface responseMessage;
    final List<String> errors;
    final boolean boolDebug;

    boolDebug = (LOADER_PROPERTIES.isTimingDebug() || LOADER_PROPERTIES.isMetadataDebug()
            || LOADER_PROPERTIES.isStaribusDebug() || LOADER_PROPERTIES.isStarinetDebug());

    // Initialise
    errors = new ArrayList<String>(10);
    dao.clearEventLogFragment();

    // Get the latest Resources
    dao.readResources();

    // Don't affect the CommandType of the incoming Command
    cmdImport = (CommandType) commandmessage.getCommandType().copy();

    // We expect five parameters: the url, the pathname, the capture interval, the capture period and the update flag
    listParameters = cmdImport.getParameterList();

    if ((dao.getHostInstrument() != null) && (dao.getHostInstrument().getInstrument() != null)
            && (dao.getHostInstrument().getInstrument().getController() != null)
            && (dao.getHostInstrument().getInstrument().getController().getVirtualAddress() != null)
            && (listParameters != null) && (listParameters.size() == PARAMETER_COUNT)
            && (listParameters.get(INDEX_URL) != null)
            && (SchemaDataType.STRING
                    .equals(listParameters.get(INDEX_URL).getInputDataType().getDataTypeName()))
            && (listParameters.get(INDEX_PATHNAME) != null)
            && (SchemaDataType.PATH_NAME
                    .equals(listParameters.get(INDEX_PATHNAME).getInputDataType().getDataTypeName()))
            && (listParameters.get(INDEX_INTERVAL) != null)
            && (SchemaDataType.DECIMAL_INTEGER
                    .equals(listParameters.get(INDEX_INTERVAL).getInputDataType().getDataTypeName()))
            && (listParameters.get(INDEX_PERIOD) != null)
            && (SchemaDataType.DECIMAL_INTEGER
                    .equals(listParameters.get(INDEX_PERIOD).getInputDataType().getDataTypeName()))
            && (listParameters.get(INDEX_UPDATE) != null) && (SchemaDataType.BOOLEAN
                    .equals(listParameters.get(INDEX_UPDATE).getInputDataType().getDataTypeName()))) {
        try {
            final String strURL;
            final String strPathname;
            final String strCaptureInterval;
            final String strCapturePeriod;
            final boolean boolRealtimeUpdate;
            final int intCaptureIntervalSec;
            int intCapturePeriodSec;
            final HttpClient client;
            final HttpMethod method;

            strURL = listParameters.get(INDEX_URL).getValue();
            strPathname = listParameters.get(INDEX_PATHNAME).getValue();
            strCaptureInterval = listParameters.get(INDEX_INTERVAL).getValue();
            strCapturePeriod = listParameters.get(INDEX_PERIOD).getValue();
            boolRealtimeUpdate = Boolean.parseBoolean(listParameters.get(INDEX_UPDATE).getValue());

            intCaptureIntervalSec = Integer.parseInt(strCaptureInterval);
            intCapturePeriodSec = Integer.parseInt(strCapturePeriod);

            // Check for silly parameter settings
            // CapturePeriod = 0 means run continuously
            if ((strURL != null) && (!EMPTY_STRING.equals(strURL.trim())) && (intCaptureIntervalSec > 0)
                    && (intCapturePeriodSec >= 0)) {
                final String strPeriod;
                final int intCaptureCountMax;
                final ResponseMessageStatusList listStatusInCaptureLoop;

                boolean boolSuccess;

                if (intCapturePeriodSec == 0) {
                    strPeriod = CaptureCommandHelper.MSG_PERIOD_CONTINUOUS;
                } else {
                    strPeriod = Integer.toString(intCapturePeriodSec);
                }

                // We have all the Parameters, now prepare the HTTP client
                client = new HttpClient();
                client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        new DefaultHttpMethodRetryHandler(1, false));

                method = new GetMethod(strURL);

                // See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
                // The User-Agent request-header field contains information about the user agent originating the request
                method.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
                // The Referer[sic] request-header field allows the client to specify, for the server's benefit,
                // the address (URI) of the resource from which the Request-URI was obtained
                // (the "referrer", although the header field is misspelled.)
                method.setRequestHeader("Referer", strURL + "/Jview.htm");

                // Log everything we have so far
                SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.INFO,
                        METADATA_TARGET_IMAGE + METADATA_ACTION_IMPORT + METADATA_URL_REQUEST + strURL
                                + TERMINATOR_SPACE + METADATA_PATHNAME + strPathname + TERMINATOR_SPACE
                                + METADATA_INTERVAL + intCaptureIntervalSec + TERMINATOR_SPACE + METADATA_PERIOD
                                + strPeriod + TERMINATOR,
                        dao.getLocalHostname(), dao.getObservatoryClock());

                // Correct the CapturePeriod for continuous operation
                if (intCapturePeriodSec == 0) {
                    // Allow about 10 days of operation! (Could be Integer.MAX_VALUE?)
                    intCapturePeriodSec = 1000000;
                }

                intCaptureCountMax = intCapturePeriodSec / intCaptureIntervalSec;
                boolSuccess = true;

                // Adjust the Timeout for the number of commands expected
                // TODO REVIEW TimeoutHelper.restartDAOTimeoutTimer(dao, intCounter, 0, 0);

                listStatusInCaptureLoop = ResponseMessageStatus.createResponseMessageStatusList();

                for (int intCaptureIndex = 0; ((intCaptureIndex < intCaptureCountMax) && (boolSuccess)
                        && Utilities.executeWorkerCanProceed(dao)); intCaptureIndex++) {
                    final long longTimeStart;
                    final long longTimeFinish;
                    final long longTimeToWait;

                    longTimeStart = dao.getObservatoryClock().getSystemTimeMillis();
                    listStatusInCaptureLoop.clear();

                    try {
                        final int intStatus;
                        final InputStream inputStream;

                        // Now try to get the Image
                        intStatus = client.executeMethod(method);

                        // Check the server status
                        if (intStatus != HttpStatus.SC_OK) {
                            SimpleEventLogUIComponent
                                    .logEvent(dao.getEventLogFragment(), EventStatus.WARNING,
                                            ObservatoryInstrumentDAOInterface.ERROR_HTTP + SPACE
                                                    + method.getStatusLine(),
                                            SOURCE, dao.getObservatoryClock());
                        }

                        // It is vital that the response body is always read,
                        // regardless of the status returned by the server.
                        inputStream = method.getResponseBodyAsStream();

                        if (inputStream != null) {
                            final BufferedImage image;

                            image = ImageIO.read(inputStream);

                            // If we get here, it must have succeeded... (otherwise IOException, ImageFormatException)
                            // Save the image as a timestamped PNG file every time
                            boolSuccess = DataExporter.exportImage(image, strPathname + "/GOES", true,
                                    FileUtilities.png, dao.getEventLogFragment(), dao.getObservatoryClock());

                            // Pass the Image to the DAO, and then to the Instrument and InstrumentPanel
                            if (boolRealtimeUpdate) {
                                dao.setImageData(image);
                                dao.setUnsavedData(true);

                                REGISTRY.getFramework().notifyFrameworkChangedEvent(dao.getHostInstrument());
                                InstrumentHelper.notifyInstrumentChanged(dao.getHostInstrument());
                            }

                            inputStream.close();
                            listStatusInCaptureLoop.add(ResponseMessageStatus.SUCCESS);
                        } else {
                            // No data are available
                            SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING,
                                    ObservatoryInstrumentDAOInterface.ERROR_PARSE_DATA, SOURCE,
                                    dao.getObservatoryClock());
                        }
                    }

                    catch (NumberFormatException exception) {
                        SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL,
                                ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(),
                                SOURCE, dao.getObservatoryClock());
                    }

                    catch (IllegalArgumentException exception) {
                        SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL,
                                ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(),
                                SOURCE, dao.getObservatoryClock());
                    }

                    catch (HttpException exception) {
                        SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING,
                                ObservatoryInstrumentDAOInterface.ERROR_HTTP + exception.getMessage(), SOURCE,
                                dao.getObservatoryClock());
                    }

                    catch (IOException exception) {
                        SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING,
                                ObservatoryInstrumentDAOInterface.ERROR_IO + exception.getMessage(), SOURCE,
                                dao.getObservatoryClock());
                    }

                    // Take account of the time elapsed so far...
                    longTimeFinish = dao.getObservatoryClock().getSystemTimeMillis();
                    longTimeToWait = (intCaptureIntervalSec * ChronosHelper.SECOND_MILLISECONDS)
                            - (longTimeFinish - longTimeStart);

                    if (longTimeToWait > 0) {
                        // Wait for the required time, checking to see if we have been stopped by the User
                        Utilities.safeSleepPollExecuteWorker(longTimeToWait, dao);
                    } else {
                        LOGGER.error(SOURCE + " Invalid capture interval [time_to_wait=" + longTimeToWait
                                + " msec]");
                    }
                }

                // Always release the HttpClient connection
                method.releaseConnection();

                //-----------------------------------------------------------------------------
                // Capture the final Status and ResponseValue (these may show a failure)

                dao.getResponseMessageStatusList().addAll(listStatusInCaptureLoop);

                if (dao.getResponseMessageStatusList().contains(ResponseMessageStatus.SUCCESS)) {
                    strResponseValue = ResponseMessageStatus.SUCCESS.getResponseValue();
                } else {
                    SimpleEventLogUIComponent.logErrors(dao.getEventLogFragment(), EventStatus.FATAL, errors,
                            SOURCE, dao.getObservatoryClock());
                    strResponseValue = ResponseMessageStatus.PREMATURE_TERMINATION.getResponseValue();
                }
            } else {
                throw new IllegalArgumentException(EXCEPTION_PARAMETER_INVALID);
            }
        }

        catch (NumberFormatException exception) {
            SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL,
                    METADATA_EXCEPTION + ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT
                            + exception.getMessage() + TERMINATOR,
                    dao.getLocalHostname(), dao.getObservatoryClock());
            strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue();
            dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER);
        }

        catch (IllegalArgumentException exception) {
            SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL,
                    METADATA_EXCEPTION + ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT
                            + exception.getMessage() + TERMINATOR,
                    dao.getLocalHostname(), dao.getObservatoryClock());
            strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue();
            dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER);
        }

        catch (Exception exception) {
            exception.printStackTrace();
            SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING,
                    METADATA_EXCEPTION + dao.getInstrumentName() + " Generic Exception [exception="
                            + exception.getMessage() + "]" + TERMINATOR,
                    dao.getLocalHostname(), dao.getObservatoryClock());
            strResponseValue = ResponseMessageStatus.INVALID_MESSAGE.getResponseValue();
            dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_MESSAGE);
        }
    } else {
        // Incorrectly configured XML
        strResponseValue = ResponseMessageStatus.INVALID_XML.getResponseValue();
        dao.getResponseMessageStatusList().add(
                DAOCommandHelper.logInvalidXML(dao, SOURCE, METADATA_TARGET_IMAGE, METADATA_ACTION_CAPTURE));
    }

    ObservatoryInstrumentHelper.runGarbageCollector();
    responseMessage = ResponseMessageHelper.createResponseMessage(dao, commandmessage, cmdImport, null, null,
            strResponseValue);
    return (responseMessage);
}

From source file:edu.umass.cs.gnsclient.client.integrationtests.ServerIntegrationTest.java

/**
 * @throws FileNotFoundException//from ww  w. jav  a2s. c om
 * @throws IOException
 * @throws InterruptedException
 */
@Deprecated
public static void setUpBeforeClassOld() throws FileNotFoundException, IOException, InterruptedException {
    /* The waitTillAllServersReady parameter is not needed for
     * single-machine tests as we check the logs explicitly below. It is
     * still useful for distributed tests as there is no intentionally
     * support in gigapaxos' async client to detect if all servrs are up. */
    String waitString = System.getProperty("waitTillAllServersReady");
    if (waitString != null) {
        WAIT_TILL_ALL_SERVERS_READY = Integer.parseInt(waitString);
    }

    // get pattern for log files
    Properties logProps = new Properties();
    logProps.load(new FileInputStream(System.getProperty(DefaultProps.LOGGING_PROPERTIES.key)));
    String logFiles = logProps.getProperty("java.util.logging.FileHandler.pattern");

    if (logFiles != null) {
        logFiles = logFiles.replaceAll("%.*", "").trim() + "*";
    }
    new File(logFiles.replaceFirst("/[^/]*$", "")).mkdirs();

    if (logFiles != null) {
        System.out.print("Deleting log files " + logFiles);
        RunCommand.command("rm -f " + logFiles, ".", false);
        System.out.print(" ...done" + logFiles);
    }

    // start server
    if (System.getProperty("startServer") != null && System.getProperty("startServer").equals("true")) {

        // clear explicitly if gigapaxos
        if (useGPScript()) {

            // forceclear
            String forceClearCmd = System.getProperty(DefaultProps.SERVER_COMMAND.key) + " "
                    + getGigaPaxosOptions() + " forceclear all";
            System.out.println(forceClearCmd);
            RunCommand.command(forceClearCmd, ".");

            /* We need to do this to limit the number of files used by mongo.
             * Otherwise failed runs quickly lead to more failed runs because
             * index files created in previous runs are not removed.
             */
            dropAllDatabases();

            options = getGigaPaxosOptions() + " restart all";
        } else {
            options = SCRIPTS_OPTIONS;
        }

        String startServerCmd = System.getProperty(DefaultProps.SERVER_COMMAND.key) + " " + options;
        System.out.println(startServerCmd);

        // servers are being started here
        if (singleJVM()) {
            startServersSingleJVM();
        } else {
            ArrayList<String> output = RunCommand.command(startServerCmd, ".");

            if (output != null) {
                for (String line : output) {
                    System.out.println(line);
                }
            } else {
                failWithStackTrace("Server command failure: ; aborting all tests.");
            }
        }
    }

    int numServers = PaxosConfig.getActives().size() + ReconfigurationConfig.getReconfigurators().size();

    ArrayList<String> output;
    int numServersUp = 0;
    // a little sleep ensures that there is time for at least one log file to get created
    Thread.sleep(500);
    if (!singleJVM()) {
        do {
            output = RunCommand.command("cat " + logFiles + " | grep -a \"server ready\" | wc -l ", ".", false);
            String temp = output.get(0);
            temp = temp.replaceAll("\\s", "");
            try {
                numServersUp = Integer.parseInt(temp);
            } catch (NumberFormatException e) {
                // can happen if no files have yet gotten created
                System.out.println(e);
            }
            System.out.println(Integer.toString(numServersUp) + " out of " + Integer.toString(numServers)
                    + " servers are ready.");
            Thread.sleep(1000);
        } while (numServersUp < numServers);
    }

    System.out.println("Starting client");

    int numRetries = 2;
    boolean forceCoordinated = true;

    clientCommands = (GNSClientCommands) new GNSClientCommands().setNumRetriesUponTimeout(numRetries)
            .setForceCoordinatedReads(forceCoordinated);

    client = new GNSClient().setNumRetriesUponTimeout(numRetries).setForceCoordinatedReads(forceCoordinated)
            .setForcedTimeout(8000);

    System.out.println("Client created and connected to server.");
    //
    int tries = 5;
    boolean accountCreated = false;

    Thread.sleep(WAIT_TILL_ALL_SERVERS_READY);

    do {
        try {
            System.out.println("Creating account guid: " + (tries - 1) + " attempt remaining.");
            String createdGUID = client.execute(GNSCommand.createAccount(accountAlias)).getResultString();
            Assert.assertEquals(createdGUID, GuidUtils.getGUIDKeys(accountAlias).guid);

            // older code; okay to leave it hanging or to remove
            masterGuid = GuidUtils.lookupOrCreateAccountGuid(clientCommands, accountAlias, PASSWORD, true);
            accountCreated = true;
        } catch (Exception e) {
            e.printStackTrace();
            ThreadUtils.sleep((5 - tries) * 4000);
        }
    } while (!accountCreated && --tries > 0);
    if (accountCreated == false) {
        failWithStackTrace("Failure setting up account guid; aborting all tests.");
    }

}

From source file:edu.hawaii.soest.kilonalu.ctd.SeahorseSource.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.
 *//*from  ww  w.jav a2 s.c o m*/
protected boolean execute() {
    logger.debug("SeahorseSource.execute() called.");
    // do not execute the stream if there is no connection
    if (!isConnected())
        return false;

    boolean failed = false;

    this.socketChannel = getSocketConnection();

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

        // define a byte array that will be used to manipulate the incoming bytes
        byte[] resultArray;
        String resultString;

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

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

        this.rbnbChannelMap = new ChannelMap();
        this.channelIndex = 0;

        // initiate the session with the modem, test if is network registered
        this.command = this.MODEM_COMMAND_PREFIX + this.REGISTRATION_STATUS_COMMAND + this.MODEM_COMMAND_SUFFIX;
        this.sentCommand = queryInstrument(this.command);

        // allow time for the modem to respond
        streamingThread.sleep(this.SLEEP_INTERVAL);

        // while there are bytes to read from the socketChannel ...
        while (socketChannel.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" +
                //             "result pos: "   + resultBuffer.position()                  + "\t" +
                //             "result rem: "   + resultBuffer.remaining()                 + "\t" +
                //             "result cnt: "   + resultByteCount                          + "\t" +
                //             "buffer pos: "   + buffer.position()                        + "\t" +
                //             "buffer rem: "   + buffer.remaining()                       + "\t" +
                //             "state: "        + 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 (state) {

                case 0:

                    // the network registration status should end in OK\r\n
                    // note bytes are in reverse order in the FIFO window
                    if (byteOne == 0x0A && byteTwo == 0x0D && byteThree == 0x4B && byteFour == 0x4F) {

                        logger.debug("Received the registration status result.");

                        this.resultByteCount++; // add the last byte found to the count

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

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

                        }

                        // report the network registration status string
                        resultArray = new byte[this.resultByteCount];
                        resultBuffer.flip();
                        resultBuffer.get(resultArray);
                        resultString = new String(resultArray, "US-ASCII");
                        logger.debug("Network Registration Result: " + resultString.trim());

                        resultBuffer.clear();
                        this.resultByteCount = 0;
                        resultArray = new byte[0];
                        resultString = "";
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;

                        // send a request for the signal strength
                        this.command = this.MODEM_COMMAND_PREFIX + this.SIGNAL_STRENGTH_COMMAND
                                + this.MODEM_COMMAND_SUFFIX;
                        this.sentCommand = queryInstrument(this.command);
                        // allow time for the modem to respond
                        streamingThread.sleep(this.SLEEP_INTERVAL);

                        state = 1;
                        break;

                    } else {
                        this.resultByteCount++; // add the last byte found to the count

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

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

                        }

                        break;
                    }

                case 1: // report the signal strength of the Iridium modem

                    // the signal strength status should end in OK\r\n
                    // note bytes are in reverse order in the FIFO window
                    if (byteOne == 0x0A && byteTwo == 0x0D && byteThree == 0x4B && byteFour == 0x4F) {

                        logger.debug("Received the signal strength result.");

                        this.resultByteCount++; // add the last byte found to the count

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

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

                        }

                        // report the signal strength status string
                        resultArray = new byte[this.resultByteCount];
                        resultBuffer.flip();
                        resultBuffer.get(resultArray);
                        resultString = new String(resultArray, "US-ASCII");
                        logger.debug("Signal Strength Result: " + resultString.trim());

                        int signalStrengthIndex = resultString.indexOf(this.SIGNAL_STRENGTH) + 5;

                        int signalStrength = new Integer(
                                resultString.substring(signalStrengthIndex, signalStrengthIndex + 1))
                                        .intValue();

                        // test if the signal strength is above the threshold
                        if (signalStrength > SIGNAL_THRESHOLD) {

                            resultBuffer.clear();
                            this.resultByteCount = 0;
                            resultArray = new byte[0];
                            resultString = "";
                            byteOne = 0x00;
                            byteTwo = 0x00;
                            byteThree = 0x00;
                            byteFour = 0x00;

                            state = 2;
                            break;

                            // the signal strength is too low, check again
                        } else {

                            resultBuffer.clear();
                            this.resultByteCount = 0;
                            resultArray = new byte[0];
                            resultString = "";
                            byteOne = 0x00;
                            byteTwo = 0x00;
                            byteThree = 0x00;
                            byteFour = 0x00;

                            // resend a request for the signal strength
                            this.command = this.MODEM_COMMAND_PREFIX + this.SIGNAL_STRENGTH_COMMAND
                                    + this.MODEM_COMMAND_SUFFIX;
                            this.sentCommand = queryInstrument(this.command);
                            // allow time for the modem to respond
                            streamingThread.sleep(this.SLEEP_INTERVAL);

                            state = 1;
                            break;

                        }

                    } else {

                        // still in the middle of the result, keep adding bytes
                        this.resultByteCount++; // add each byte found

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

                        }

                        break;
                    }

                case 2: // handle the RING command from the instrument

                    // listen for the RING command 
                    // note bytes are in reverse order in the FIFO window
                    if (byteOne == 0x47 && byteTwo == 0x4E && byteThree == 0x49 && byteFour == 0x52) {

                        logger.debug("Received the RING command.");

                        this.resultByteCount++; // add the last byte found to the count

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

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

                        }

                        resultBuffer.clear();
                        this.resultByteCount = 0;
                        resultArray = new byte[0];
                        resultString = "";
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;

                        // answer the call
                        this.command = this.MODEM_COMMAND_PREFIX + this.ANSWER_COMMAND
                                + this.MODEM_COMMAND_SUFFIX;
                        this.sentCommand = queryInstrument(this.command);
                        // allow time for the modem to respond
                        streamingThread.sleep(this.SLEEP_INTERVAL);

                        state = 3;
                        break;

                    } else {

                        // still in the middle of the result, keep adding bytes
                        this.resultByteCount++; // add each byte found

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

                        }

                        break;

                    }

                case 3: // acknowledge the connection

                    // the ready status string should end in READY\r
                    // note bytes are in reverse order in the FIFO window
                    if (byteOne == 0x0D && byteTwo == 0x59 && byteThree == 0x44 && byteFour == 0x41) {

                        logger.debug("Received the ready status result.");

                        this.resultByteCount++; // add the last byte found to the count

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

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

                        }

                        // report the connect rate and ready status string
                        resultArray = new byte[this.resultByteCount];
                        resultBuffer.flip();
                        resultBuffer.get(resultArray);
                        resultString = new String(resultArray, "US-ASCII");

                        // test the connect rate
                        logger.debug("Result from ATA: " + resultString);

                        if (resultString.indexOf(this.CONNECT_RATE) > 0) {
                            logger.debug("Connect Rate Result: " + this.CONNECT_RATE);

                            // test the ready status
                            if (resultString.indexOf(this.READY_STATUS) > 0) {
                                logger.debug("Connect Rate Result: " + this.READY_STATUS);

                                resultBuffer.clear();
                                this.resultByteCount = 0;
                                resultArray = new byte[0];
                                resultString = "";
                                byteOne = 0x00;
                                byteTwo = 0x00;
                                byteThree = 0x00;
                                byteFour = 0x00;

                                // acknowledge the ready status
                                this.command = this.ACKNOWLEDGE_COMMAND + this.MODEM_COMMAND_SUFFIX;
                                this.sentCommand = queryInstrument(this.command);

                                // allow time for the modem to receive the ACK
                                streamingThread.sleep(this.SLEEP_INTERVAL);

                                // query the instrument id
                                this.command = this.ID_COMMAND + this.MODEM_COMMAND_SUFFIX;
                                this.sentCommand = queryInstrument(this.command);

                                // allow time for the modem to respond
                                streamingThread.sleep(this.SLEEP_INTERVAL);

                                state = 4;
                                break;

                            } else {
                                logger.debug("The ready status differs from: " + this.READY_STATUS);

                                // throw an exception here?
                                break;
                            }

                        } else {
                            logger.debug("The connect rate differs from: " + this.CONNECT_RATE);

                            // throw an exception here?
                            break;
                        }

                    } else {

                        // still in the middle of the result, keep adding bytes
                        this.resultByteCount++; // add each byte found

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

                        }

                        break;

                    }

                case 4: // get the instrument id

                    // the instrument ID string should end in \r
                    if (byteOne == 0x0D) {

                        logger.debug("Received the instrument ID result.");

                        this.resultByteCount++; // add the last byte found to the count

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

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

                        }

                        // report the instrument ID string
                        resultArray = new byte[this.resultByteCount];
                        resultBuffer.flip();
                        resultBuffer.get(resultArray);
                        resultString = new String(resultArray, "US-ASCII");
                        logger.debug("Seahorse Instrument ID: " + resultString.trim());

                        // set the platformID variable
                        this.platformID = resultString.substring(0, resultString.length() - 1);

                        resultBuffer.clear();
                        this.resultByteCount = 0;
                        resultArray = new byte[0];
                        resultString = "";
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;

                        // query the battery voltage
                        this.command = this.BATTERY_VOLTAGE_COMMAND + this.MODEM_COMMAND_SUFFIX;
                        this.sentCommand = queryInstrument(this.command);

                        // allow time for the modem to respond
                        streamingThread.sleep(this.SLEEP_INTERVAL);

                        state = 5;
                        break;

                    } else {

                        // still in the middle of the result, keep adding bytes
                        this.resultByteCount++; // add each byte found

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

                        }

                        break;

                    }

                case 5: // get the seahorse battery voltage

                    // the battery voltage string should end in \r
                    if (byteOne == 0x0D) {

                        logger.debug("Received the instrument battery voltage result.");

                        this.resultByteCount++; // add the last byte found to the count

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

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

                        }

                        // report the battery voltage string
                        resultArray = new byte[this.resultByteCount];
                        resultBuffer.flip();
                        resultBuffer.get(resultArray);
                        resultString = new String(resultArray, "US-ASCII");
                        logger.debug("Seahorse Battery Voltage: " + resultString.trim());

                        resultBuffer.clear();
                        this.resultByteCount = 0;
                        resultArray = new byte[0];
                        resultString = "";
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;

                        // query the GPS location
                        this.command = this.GPRMC_COMMAND + this.MODEM_COMMAND_SUFFIX;
                        this.sentCommand = queryInstrument(this.command);

                        // allow time for the modem to respond
                        streamingThread.sleep(this.SLEEP_INTERVAL);

                        state = 6;
                        break;

                    } else {

                        // still in the middle of the result, keep adding bytes
                        this.resultByteCount++; // add each byte found

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

                        }

                        break;

                    }

                case 6:

                    // the GPRMC string should end in END\r
                    // note bytes are in reverse order in the FIFO window
                    if (byteOne == 0x0D && byteTwo == 0x44 && byteThree == 0x4E && byteFour == 0x45) {

                        logger.debug("Received the GPRMS result.");

                        this.resultByteCount++; // add the last byte found to the count

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

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

                        }

                        // report the GPRMC string
                        resultArray = new byte[this.resultByteCount];
                        resultBuffer.flip();
                        resultBuffer.get(resultArray);
                        resultString = new String(resultArray, "US-ASCII");
                        logger.debug("Seahorse GPRMC string: " + resultString.trim());

                        resultBuffer.clear();
                        this.resultByteCount = 0;
                        resultArray = new byte[0];
                        resultString = "";
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;

                        // query the file name for transfer
                        this.command = this.FILENAME_COMMAND + this.MODEM_COMMAND_SUFFIX;
                        this.sentCommand = queryInstrument(this.command);

                        // allow time for the modem to respond
                        streamingThread.sleep(this.SLEEP_INTERVAL);

                        state = 7;
                        break;

                    } else {

                        // still in the middle of the result, keep adding bytes
                        this.resultByteCount++; // add each byte found

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

                        }

                        break;

                    }

                case 7:

                    // the file name string should end in .Z\r
                    // note bytes are in reverse order in the FIFO window
                    if (byteOne == 0x0D && byteTwo == 0x5A && byteThree == 0x2E) {

                        logger.debug("Received the file name result.");

                        this.resultByteCount++; // add the last byte found to the count

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

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

                        }

                        // report the file name string
                        resultArray = new byte[this.resultByteCount];
                        resultBuffer.flip();
                        resultBuffer.get(resultArray);
                        resultString = new String(resultArray, "US-ASCII");
                        logger.debug("File name result: " + resultString.trim());

                        resultString = resultString.trim();
                        int fileNameIndex = resultString.indexOf(this.FILENAME_PREFIX);

                        //extract just the filename from the result (excise the "FILE=")
                        this.fileNameToDownload = resultString.substring(
                                (fileNameIndex + (this.FILENAME_PREFIX).length()), resultString.length());

                        logger.debug("File name to download: " + this.fileNameToDownload);

                        // test to see if the GFN command returns FILES=NONE
                        if (!(resultString.indexOf(this.END_OF_FILES) > 0)) {

                            // there is a file to download. parse the file name,
                            // get the number of blocks to transfer
                            this.command = this.NUMBER_OF_BLOCKS_COMMAND + this.MODEM_COMMAND_SUFFIX;
                            this.sentCommand = queryInstrument(this.command);

                            // allow time for the modem to respond
                            streamingThread.sleep(this.SLEEP_INTERVAL);

                            resultBuffer.clear();
                            this.resultByteCount = 0;
                            resultArray = new byte[0];
                            resultString = "";
                            byteOne = 0x00;
                            byteTwo = 0x00;
                            byteThree = 0x00;
                            byteFour = 0x00;

                            state = 8;
                            break;

                        } else {

                            // We have downloaded all files. Parse the data string,
                            // build the channel map, and flush the data to the Dataturbine
                            // by iterating through the data matrix.  The metadata and
                            // ASCII data strings are flushed once with the first matrix
                            // row.

                            // Parse the data file, not the cast file.
                            try {

                                // parse the CTD data file
                                this.ctdParser = new CTDParser(this.dataFileString);

                                // convert the raw frequencies and voltages to engineering
                                // units and return the data as a matrix
                                CTDConverter ctdConverter = new CTDConverter(this.ctdParser);
                                ctdConverter.convert();
                                RealMatrix convertedDataMatrix = ctdConverter.getConvertedDataValuesMatrix();

                                // Register the data and metadata channels;
                                failed = register();

                                if (!failed) {
                                    // format the first sample date and use it as the first insert
                                    // date.  Add the sampleInterval on each iteration to insert
                                    // subsequent data rows.  Sample interval is by default 
                                    // 4 scans/second for the CTD.
                                    DATE_FORMAT.setTimeZone(TZ);
                                    this.sampleDateTime = Calendar.getInstance();
                                    this.sampleDateTime
                                            .setTime(DATE_FORMAT.parse(ctdParser.getFirstSampleTime()));

                                    for (int row = 0; row < convertedDataMatrix.getRowDimension(); row++) {

                                        // Only insert the metadata fields and full ASCII text strings
                                        // with the first row of data
                                        if (row == 0) {
                                            // Add the samplingMode data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("samplingMode");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getSamplingMode());

                                            // Add the firstSampleTime data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("firstSampleTime");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getFirstSampleTime());

                                            // Add the fileName data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("fileName");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getFileName());

                                            // Add the temperatureSerialNumber data to the channel map
                                            this.channelIndex = this.rbnbChannelMap
                                                    .Add("temperatureSerialNumber");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getTemperatureSerialNumber());

                                            // Add the conductivitySerialNumber data to the channel map
                                            this.channelIndex = this.rbnbChannelMap
                                                    .Add("conductivitySerialNumber");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getConductivitySerialNumber());

                                            // Add the systemUpLoadTime data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("systemUpLoadTime");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getSystemUpLoadTime());

                                            // Add the cruiseInformation data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("cruiseInformation");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getCruiseInformation());

                                            // Add the stationInformation data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("stationInformation");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getStationInformation());

                                            // Add the shipInformation data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("shipInformation");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getShipInformation());

                                            // Add the chiefScientist data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("chiefScientist");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getChiefScientist());

                                            // Add the organization data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("organization");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getOrganization());

                                            // Add the areaOfOperation data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("areaOfOperation");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getAreaOfOperation());

                                            // Add the instrumentPackage data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("instrumentPackage");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getInstrumentPackage());

                                            // Add the mooringNumber data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("mooringNumber");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getMooringNumber());

                                            // Add the instrumentLatitude data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("instrumentLatitude");
                                            this.rbnbChannelMap.PutMime(this.channelIndex,
                                                    "application/octet-stream");
                                            this.rbnbChannelMap.PutDataAsFloat64(this.channelIndex,
                                                    new double[] { this.ctdParser.getInstrumentLatitude() });

                                            // Add the instrumentLongitude data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("instrumentLongitude");
                                            this.rbnbChannelMap.PutMime(this.channelIndex,
                                                    "application/octet-stream");
                                            this.rbnbChannelMap.PutDataAsFloat64(this.channelIndex,
                                                    new double[] { this.ctdParser.getInstrumentLongitude() });

                                            // Add the depthSounding data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("depthSounding");
                                            this.rbnbChannelMap.PutMime(this.channelIndex,
                                                    "application/octet-stream");
                                            this.rbnbChannelMap.PutDataAsFloat64(this.channelIndex,
                                                    new double[] { this.ctdParser.getDepthSounding() });

                                            // Add the profileNumber data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("profileNumber");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getProfileNumber());

                                            // Add the profileDirection data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("profileDirection");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getProfileDirection());

                                            // Add the deploymentNotes data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("deploymentNotes");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getDeploymentNotes());

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

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

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

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

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

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

                                            // Add the loggingStatus data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("loggingStatus");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getLoggingStatus());

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

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

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

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

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

                                            // Add the transmitRealtime data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("transmitRealtime");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getTransmitRealtime());

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

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

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

                                            // Add the automaticLogging data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("automaticLogging");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getAutomaticLogging());

                                            // Add the ignoreMagneticSwitch data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("ignoreMagneticSwitch");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getIgnoreMagneticSwitch());

                                            // Add the batteryType data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("batteryType");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getBatteryType());

                                            // Add the batteryCutoff data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("batteryCutoff");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getBatteryCutoff());

                                            // Add the pressureSensorType data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("pressureSensorType");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getPressureSensorType());

                                            // Add the pressureSensorRange data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("pressureSensorRange");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getPressureSensorRange());

                                            // Add the sbe38TemperatureSensor data to the channel map
                                            this.channelIndex = this.rbnbChannelMap
                                                    .Add("sbe38TemperatureSensor");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getSbe38TemperatureSensor());

                                            // Add the gasTensionDevice data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("gasTensionDevice");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getGasTensionDevice());

                                            // Add the externalVoltageChannelZero data to the channel map
                                            this.channelIndex = this.rbnbChannelMap
                                                    .Add("externalVoltageChannelZero");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getExternalVoltageChannelZero());

                                            // Add the externalVoltageChannelOne data to the channel map
                                            this.channelIndex = this.rbnbChannelMap
                                                    .Add("externalVoltageChannelOne");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getExternalVoltageChannelOne());

                                            // Add the externalVoltageChannelTwo data to the channel map
                                            this.channelIndex = this.rbnbChannelMap
                                                    .Add("externalVoltageChannelTwo");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getExternalVoltageChannelTwo());

                                            // Add the externalVoltageChannelThree data to the channel map
                                            this.channelIndex = this.rbnbChannelMap
                                                    .Add("externalVoltageChannelThree");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getExternalVoltageChannelThree());

                                            // Add the echoCommands data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("echoCommands");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getEchoCommands());

                                            // Add the outputFormat data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("outputFormat");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getOutputFormat());

                                            // Add the temperatureCalibrationDate data to the channel map
                                            this.channelIndex = this.rbnbChannelMap
                                                    .Add("temperatureCalibrationDate");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getTemperatureCalibrationDate());

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

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

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

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

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

                                            // Add the conductivityCalibrationDate data to the channel map
                                            this.channelIndex = this.rbnbChannelMap
                                                    .Add("conductivityCalibrationDate");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getConductivityCalibrationDate());

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

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

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

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

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

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

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

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

                                            // Add the pressureSerialNumber data to the channel map
                                            this.channelIndex = this.rbnbChannelMap.Add("pressureSerialNumber");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.ctdParser.getPressureSerialNumber());

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

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

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

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

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

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

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

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

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

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

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

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

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

                                            // Insert the file into the channel map. 
                                            this.channelIndex = this.rbnbChannelMap.Add(this.rbnbChannelName);
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.dataFileString);

                                            this.channelIndex = this.rbnbChannelMap.Add("ASCIICastData");
                                            this.rbnbChannelMap.PutMime(this.channelIndex, "text/plain");
                                            this.rbnbChannelMap.PutDataAsString(this.channelIndex,
                                                    this.castFileString);

                                        }

                                        // Add in the matrix data row to the map here
                                        List<String> variableNames = ctdParser.getDataVariableNames();
                                        List<String> variableUnits = ctdParser.getDataVariableUnits();

                                        // iterate through the variable names and add them to
                                        // the channel map.
                                        for (int variableIndex = 0; variableIndex < variableNames
                                                .size(); variableIndex++) {

                                            //  Add the variable name to the channel map
                                            this.channelIndex = this.rbnbChannelMap
                                                    .Add(variableNames.get(variableIndex));
                                            // The matrix is a double array, so set the data type below
                                            this.rbnbChannelMap.PutMime(this.channelIndex,
                                                    "application/octet-stream");
                                            // add the data to the map from the [row,column] of the
                                            // matrix (row is from the outer for loop)
                                            this.rbnbChannelMap.PutDataAsFloat64(this.channelIndex,
                                                    new double[] {
                                                            convertedDataMatrix.getEntry(row, variableIndex) });

                                        }

                                        // Flush the channel map to the RBNB
                                        double sampleTimeAsSecondsSinceEpoch = (double) (this.sampleDateTime
                                                .getTimeInMillis() / 1000);
                                        this.rbnbChannelMap.PutTime(sampleTimeAsSecondsSinceEpoch, 0d);
                                        getSource().Flush(this.rbnbChannelMap);

                                        logger.info("Flushed data to the DataTurbine.");
                                        this.rbnbChannelMap.Clear();

                                        // samples are taken 4x per second, so increment the
                                        // sample time by 250 milliseconds for the next insert                     
                                        this.sampleDateTime.add(Calendar.MILLISECOND, 250);

                                    } // end for loop 

                                } //  end if !failed

                            } catch (Exception e) {
                                logger.debug("Failed to parse the CTD data file: " + e.getMessage());

                            }

                            // there are no more files to read. close the Tx session.
                            this.command = this.CLOSE_TRANSFER_SESSION_COMMAND + this.MODEM_COMMAND_SUFFIX;
                            this.sentCommand = queryInstrument(this.command);

                            // allow time for the modem to respond
                            streamingThread.sleep(this.SLEEP_INTERVAL);

                            // clean up
                            resultBuffer.clear();
                            this.resultByteCount = 0;
                            resultArray = new byte[0];
                            resultString = "";
                            byteOne = 0x00;
                            byteTwo = 0x00;
                            byteThree = 0x00;
                            byteFour = 0x00;

                            state = 10;
                            break;

                        }

                    } else {

                        // still in the middle of the result, keep adding bytes
                        this.resultByteCount++; // add each byte found

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

                        }

                        break;

                    }

                case 8:

                    // the number of blocks string should end in \r
                    if (byteOne == 0x0D) {

                        logger.debug("Received the number of blocks result.");

                        this.resultByteCount++; // add the last byte found to the count

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

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

                        }

                        // report the number of blocks string
                        resultArray = new byte[this.resultByteCount];
                        resultBuffer.flip();
                        resultBuffer.get(resultArray);
                        resultString = new String(resultArray, "US-ASCII");
                        logger.debug("Number of bytes reported: " + resultString.trim());

                        int numberOfBlocksIndex = resultString.indexOf(this.BLOCKSIZE_PREFIX);

                        // If 'BLOCKSIZE=' is not found, set the index to 0
                        if (numberOfBlocksIndex == -1) {
                            numberOfBlocksIndex = 0;

                        }

                        resultString = resultString.substring(
                                (numberOfBlocksIndex + (this.BLOCKSIZE_PREFIX).length()),
                                resultString.length());

                        // convert the string to an integer
                        try {
                            this.numberOfBlocks = new Integer(resultString.trim()).intValue();
                            logger.debug("Number of bytes to download: " + this.numberOfBlocks);

                        } catch (java.lang.NumberFormatException nfe) {
                            failed = true;
                            nfe.printStackTrace();
                            logger.debug("Failed to convert returned string value "
                                    + "to an integer value.  The returned string is: " + this.numberOfBlocks);

                        }

                        // test to see if the GNB command returns DONE\r
                        if (!(resultString.indexOf(this.TRANSFER_COMPLETE) > 0)) {

                            // there are bytes to transfer. send the transfer command

                            this.command = this.TRANSFER_BLOCKS_COMMAND + this.MODEM_COMMAND_SUFFIX;
                            this.sentCommand = queryInstrument(this.command);

                            // allow time for the modem to respond
                            streamingThread.sleep(this.SLEEP_INTERVAL);

                            //resultBuffer.clear(); dont clear the buffer
                            this.resultByteCount = 0;
                            resultArray = new byte[0];
                            resultString = "";
                            byteOne = 0x00;
                            byteTwo = 0x00;
                            byteThree = 0x00;
                            byteFour = 0x00;

                            state = 9;
                            break;

                        } else {

                            // there are no more bytes to transfer.  

                            // Decompress the file, which is under zlib compression.  
                            Inflater inflater = new Inflater();
                            inflater.setInput(resultBuffer.array());
                            byte[] output = new byte[resultBuffer.capacity()];

                            int numDecompressed = inflater.inflate(output);

                            // set the appropriate string variable
                            if (this.fileNameToDownload.indexOf(DATA_FILE_PREFIX) > 0) {
                                this.dataFileString = new String(output);

                                //report the file contents to the log
                                logger.debug("File " + this.fileNameToDownload + ": ");
                                logger.debug(this.dataFileString);

                            } else {
                                this.castFileString = new String(output);

                                //report the file contents to the log
                                logger.debug("File " + this.fileNameToDownload + ": ");
                                logger.debug(this.castFileString);

                            }

                            // Ask for the next file.
                            this.command = this.FILENAME_COMMAND + this.MODEM_COMMAND_SUFFIX;
                            this.sentCommand = queryInstrument(this.command);

                            // allow time for the modem to respond
                            streamingThread.sleep(this.SLEEP_INTERVAL);

                            //resultBuffer.clear(); dont clear the buffer
                            this.resultByteCount = 0;
                            resultArray = new byte[0];
                            resultString = "";
                            byteOne = 0x00;
                            byteTwo = 0x00;
                            byteThree = 0x00;
                            byteFour = 0x00;

                            state = 7; //back to the file name state
                            break;

                        }

                    } else {

                        // still in the middle of the result, keep adding bytes
                        this.resultByteCount++; // add each byte found

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

                        }

                        break;

                    }

                case 9:

                    // transfer up to the reported number of bytes
                    if (this.resultByteCount == this.numberOfBlocks) {

                        // we have downloaded the reported bytes. get the next section.
                        // get the number of blocks to transfer
                        this.command = this.NUMBER_OF_BLOCKS_COMMAND + this.MODEM_COMMAND_SUFFIX;
                        this.sentCommand = queryInstrument(this.command);

                        // allow time for the modem to respond
                        streamingThread.sleep(this.SLEEP_INTERVAL);

                        //resultBuffer.clear();
                        this.resultByteCount = 0;
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;

                        state = 8;
                        break;

                    } else {

                        // still in the middle of the result, keep adding bytes
                        this.resultByteCount++; // add each byte found

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

                        }

                        break;

                    }

                case 10:

                    // the response from the modem should end in BYE\r
                    // note bytes are in reverse order in the FIFO window
                    if (byteOne == 0x0D && byteTwo == 0x45 && byteThree == 0x59 && byteFour == 0x42) {

                        logger.debug("Received the BYE command.");

                        // continue to disconnect. send the escape sequence
                        this.command = this.ESCAPE_SEQUENCE_COMMAND + this.MODEM_COMMAND_SUFFIX;
                        this.sentCommand = queryInstrument(this.command);

                        // allow time for the modem to respond
                        streamingThread.sleep(this.SLEEP_INTERVAL);

                        resultBuffer.clear();
                        this.resultByteCount = 0;
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;

                        state = 11;
                        break;

                    } else {

                        // still in the middle of the result, keep adding bytes
                        this.resultByteCount++; // add each byte found

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

                        }

                        break;

                    }

                case 11:

                    // the response from the modem should end in OK\r\n
                    // note bytes are in reverse order in the FIFO window
                    if (byteOne == 0x0D && byteTwo == 0x0A && byteThree == 0x4B && byteFour == 0x4F) {

                        // now hang up.
                        this.command = this.MODEM_COMMAND_PREFIX + this.HANGUP_COMMAND
                                + this.MODEM_COMMAND_SUFFIX;
                        this.sentCommand = queryInstrument(this.command);

                        // allow time for the modem to respond
                        streamingThread.sleep(this.SLEEP_INTERVAL);

                        resultBuffer.clear();
                        this.resultByteCount = 0;
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;

                        state = 12;
                        break;

                    } else {

                        // still in the middle of the result, keep adding bytes
                        this.resultByteCount++; // add each byte found

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

                        }

                        break;

                    }

                case 12:

                    // the response from the modem should end in OK\r\n
                    // note bytes are in reverse order in the FIFO window
                    if (byteOne == 0x0D && byteTwo == 0x0A && byteThree == 0x4B && byteFour == 0x4F) {

                        // we are done. re-test if is network registered
                        this.command = this.MODEM_COMMAND_PREFIX + this.REGISTRATION_STATUS_COMMAND
                                + this.MODEM_COMMAND_SUFFIX;
                        this.sentCommand = queryInstrument(this.command);

                        // allow time for the modem to respond
                        streamingThread.sleep(this.SLEEP_INTERVAL);

                        resultBuffer.clear();
                        this.resultByteCount = 0;
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;

                        state = 0;
                        break;

                    } else {

                        // still in the middle of the result, keep adding bytes
                        this.resultByteCount++; // add each byte found

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

                        }

                        break;

                    }

                } // 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 socketChannel bytes to read)
        socketChannel.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;
        e.printStackTrace();
        return !failed;

    } catch (java.lang.InterruptedException ine) {
        failed = true;
        ine.printStackTrace();
        return !failed;

    } catch (java.util.zip.DataFormatException dfe) {
        failed = true;
        dfe.printStackTrace();
        return !failed;
    }

    return !failed;
}

From source file:com.idega.builder.business.BuilderLogic.java

/**
 * Returns the current IBPageID that the user has requested
 *//*from   w  ww .j  a  v  a  2  s  . co m*/
public int getCurrentIBPageID(IWContext iwc) {
    String theReturn = getCurrentIBPage(iwc);
    if (theReturn == null) {
        return -1;
    }
    try {
        return Integer.parseInt(theReturn);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    return -1;
}

From source file:com.idega.builder.business.BuilderLogic.java

public Collection<PageTreeNode> getTopLevelPages(IWContext iwc) {
    Collection<PageTreeNode> coll = DomainTree.getDomainTree(iwc).getPagesNode().getChildren();

    List<PageTreeNode> unsortedNodes = new ArrayList<PageTreeNode>(coll);
    List<PageTreeNode> sortedNodes = new ArrayList<PageTreeNode>();
    List<PageTreeNode> nodesLeft = new ArrayList<PageTreeNode>();

    try {//from ww w.  j  a va  2 s. c  om
        for (int i = 0; i < coll.size(); i++) {
            sortedNodes.add(null);
        }

        for (int i = 0; i < unsortedNodes.size(); i++) {
            PageTreeNode node = unsortedNodes.get(i);
            //         if (node.getOrder() > 0){
            if ((node.getOrder() > 0) && (node.getOrder() <= sortedNodes.size())) {
                if (sortedNodes.get(node.getOrder() - 1) == null) {
                    sortedNodes.set(node.getOrder() - 1, node);
                } else {
                    nodesLeft.add(node);
                    unsortedNodes.set(i, null);
                }
            } else {
                nodesLeft.add(node);
                unsortedNodes.set(i, null);
            }
        }
        int nodesLeftIndex = 0;
        if (!nodesLeft.isEmpty()) {
            for (int i = 0; i < sortedNodes.size(); i++) {
                if (sortedNodes.get(i) == null) {
                    PageTreeNode node = nodesLeft.get(nodesLeftIndex);
                    node.setOrder(i + 1);
                    sortedNodes.set(i, node);
                    nodesLeftIndex++;
                    if (Integer.parseInt(node.getId()) > -1) {
                        ICPage page = getICPage(node.getId());
                        if (page != null) {
                            page.setTreeOrder(i + 1);
                            page.store();
                        }
                    }
                }
            }
        }
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return coll;
    } catch (IDOStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return coll;
    }

    return sortedNodes;
}

From source file:cheladocs.controlo.DocumentoServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/pdf; application/msword; application/excel");

    String comando = request.getParameter("comando");

    if (comando == null) {
        comando = "principal";
    }/*from ww w  .  j a  v  a  2s . co m*/

    DocumentoDAO documentoDAO;
    Documento documento = new Documento();

    if (comando == null || !comando.equalsIgnoreCase("principal")) {
        try {
            idDocumento = request.getParameter("numero_protocolo");
            if (idDocumento != null) {
                documento.setNumeroProtocolo(Integer.parseInt(idDocumento));
            }

        } catch (NumberFormatException ex) {
            System.err.println("Erro ao converter dado: " + ex.getMessage());
        }
    }

    try {

        documentoDAO = new DocumentoDAO();

        if (comando.equalsIgnoreCase("guardar")) {

            documento.getRequerente().setIdRequerente(Integer.parseInt(request.getParameter("requerente")));
            documento.setDataEntrada(Date.valueOf(request.getParameter("data_entrada")));
            documento.setOrigem(request.getParameter("origem_documento"));
            documento.setDescricaoAssunto(request.getParameter("descricao_assunto"));
            documento.getNaturezaAssunto()
                    .setIdNaturezaAssunto(Integer.parseInt(request.getParameter("natureza_assunto")));
            documento.getTipoExpediente()
                    .setIdTipoExpediente(Integer.parseInt(request.getParameter("tipo_expediente")));
            Part ficheiro = request.getPart("ficheiro");
            if (ficheiro != null) {
                byte[] ficheiroDados = IOUtils.toByteArray(ficheiro.getInputStream());
                documento.setConteudoDocumento(ficheiroDados);
                documento.setUrlFicheiroDocumento(ficheiro.getSubmittedFileName());
                doUpload(ficheiro, request);
            }
            documentoDAO.save(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("editar")) {

            documento.setNumeroProtocolo(Integer.parseInt(request.getParameter("requerente")));

            documento.getRequerente().setIdRequerente(Integer.parseInt(request.getParameter("requerente")));
            documento.setDataEntrada(Date.valueOf(request.getParameter("data_entrada")));
            documento.setOrigem(request.getParameter("origem_documento"));
            documento.setDescricaoAssunto(request.getParameter("descricao_assunto"));
            documento.getNaturezaAssunto()
                    .setIdNaturezaAssunto(Integer.parseInt(request.getParameter("natureza_assunto")));
            documento.getTipoExpediente()
                    .setIdTipoExpediente(Integer.parseInt(request.getParameter("tipo_expediente")));
            Part ficheiro = request.getPart("ficheiro");
            if (ficheiro != null) {
                byte[] ficheiroDados = IOUtils.toByteArray(ficheiro.getInputStream());
                documento.setConteudoDocumento(ficheiroDados);
                documento.setUrlFicheiroDocumento(ficheiro.getSubmittedFileName());
                doUpload(ficheiro, request);
            }

            documentoDAO.update(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("eliminar")) {
            documentoDAO.delete(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("prepara_editar")) {
            documento = documentoDAO.findById(documento.getNumeroProtocolo());
            request.setAttribute("documento", documento);

            RequestDispatcher rd = request.getRequestDispatcher("paginas/documento_editar.jsp");
            rd.forward(request, response);
        } else if (comando.equalsIgnoreCase("listar")) {

            response.sendRedirect("paginas/gerir_documento.jsp");
        } else if (comando.equalsIgnoreCase("imprimir_todos") || comando.equalsIgnoreCase("imprimir_by_id")) {
            ReporteUtil reporte = new ReporteUtil();
            File caminhoRelatorio = null;
            HashMap hashMap = new HashMap();

            if (comando.equalsIgnoreCase("imprimir_todos")) {
                caminhoRelatorio = new File(getServletConfig().getServletContext()
                        .getRealPath("/WEB-INF/relatorios/DocumentoListar.jasper"));
                reporte.geraRelatorio(caminhoRelatorio.getPath(), hashMap, response);
            } else {
                hashMap.put("codigo_documento", Integer.parseInt(idDocumento));
                caminhoRelatorio = new File(getServletConfig().getServletContext()
                        .getRealPath("/WEB-INF/relatorios/Ficha_Documento.jasper"));
                reporte.geraRelatorio(caminhoRelatorio.getPath(), hashMap, response);
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:org.cytoscape.app.internal.net.WebQuerier.java

public Set<WebApp> getAllApps() {
    // If we have a cached result from the previous query, use that one
    if (this.appsByUrl.get(currentAppStoreUrl) != null) {
        return this.appsByUrl.get(currentAppStoreUrl);
    }//from ww w  .  ja va 2s.co  m

    DebugHelper.print("Obtaining apps from app store..");

    Set<WebApp> result = new HashSet<WebApp>();

    String jsonResult = null;
    try {
        // Obtain information about the app from the website
        jsonResult = query(currentAppStoreUrl + "backend/all_apps");

        if (appManager != null && appManager.getAppManagerDialog() != null) {
            appManager.getAppManagerDialog().hideNetworkError();
        }

        // Parse the JSON result
        JSONArray jsonArray = new JSONArray(jsonResult);
        JSONObject jsonObject = null;
        String keyName;

        for (int index = 0; index < jsonArray.length(); index++) {
            jsonObject = jsonArray.getJSONObject(index);

            WebApp webApp = new WebApp();

            keyName = "fullname";
            if (jsonObject.has(keyName)) {
                webApp.setName(jsonObject.get(keyName).toString());
                webApp.setFullName(jsonObject.get(keyName).toString());
            } else {
                continue;
            }

            keyName = "icon_url";
            if (jsonObject.has(keyName)) {
                webApp.setIconUrl(jsonObject.get(keyName).toString());
            }

            keyName = "page_url";
            if (jsonObject.has(keyName)) {
                webApp.setPageUrl(currentAppStoreUrl.substring(0, currentAppStoreUrl.length() - 1)
                        + jsonObject.get(keyName).toString());
            }

            keyName = "description";
            if (jsonObject.has(keyName)) {
                webApp.setDescription(jsonObject.get(keyName).toString());
            }

            keyName = "downloads";
            if (jsonObject.has(keyName)) {
                try {
                    webApp.setDownloadCount(Integer.parseInt(jsonObject.get(keyName).toString()));
                } catch (NumberFormatException e) {
                }
            }

            keyName = "stars_percentage";
            if (jsonObject.has(keyName)) {
                try {
                    webApp.setStarsPercentage(Integer.parseInt(jsonObject.get(keyName).toString()));
                } catch (NumberFormatException e) {
                }
            }

            keyName = "votes";
            if (jsonObject.has(keyName)) {
                try {
                    webApp.setVotes(Integer.parseInt(jsonObject.get(keyName).toString()));
                } catch (NumberFormatException e) {
                }
            }

            keyName = "citation";
            if (jsonObject.has(keyName)) {
                webApp.setCitation(jsonObject.get(keyName).toString());
            }

            try {
                List<WebApp.Release> releases = new LinkedList<WebApp.Release>();

                if (jsonObject.has("releases")) {
                    JSONArray jsonReleases = jsonObject.getJSONArray("releases");
                    JSONObject jsonRelease;
                    boolean isCompatible = true;

                    for (int releaseIndex = 0; releaseIndex < jsonReleases.length(); releaseIndex++) {
                        jsonRelease = jsonReleases.getJSONObject(releaseIndex);

                        WebApp.Release release = new WebApp.Release();

                        release.setBaseUrl(currentAppStoreUrl);
                        release.setRelativeUrl(jsonRelease.optString("release_download_url"));
                        release.setReleaseDate(jsonRelease.optString("created_iso"));
                        release.setReleaseVersion(jsonRelease.optString("version"));
                        release.setSha512Checksum(jsonRelease.optString("hexchecksum"));

                        keyName = "works_with";
                        if (jsonRelease.has(keyName)) {
                            release.setCompatibleCytoscapeVersions(jsonRelease.get(keyName).toString());
                            isCompatible = release.isCompatible(cyVersion);
                        }

                        if (isCompatible)
                            releases.add(release);
                    }

                    // Sort releases by version number
                    Collections.sort(releases, new Comparator<WebApp.Release>() {

                        @Override
                        public int compare(Release first, Release second) {
                            return compareVersions(second.getReleaseVersion(), first.getReleaseVersion());
                        }

                    });
                }

                webApp.setReleases(releases);
            } catch (JSONException e) {
                logger.warn(
                        "Error obtaining releases for app: " + webApp.getFullName() + ", " + e.getMessage());
            }

            // DebugHelper.print("Obtaining ImageIcon: " + iconUrlPrefix + webApp.getIconUrl());
            // webApp.setImageIcon(new ImageIcon(new URL(iconUrlPrefix + webApp.getIconUrl())));

            // Check the app for compatible releases
            List<WebApp.Release> compatibleReleases = getCompatibleReleases(webApp);

            // Only add this app if it has compatible releases
            if (compatibleReleases.size() > 0) {
                // Obtain tags associated with this app
                processAppTags(webApp, jsonObject);

                result.add(webApp);
            }
        }

    } catch (final IOException e) {
        if (appManager != null && appManager.getAppManagerDialog() != null) {
            appManager.getAppManagerDialog().showNetworkError();
        }
        e.printStackTrace();
        result = null;
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        DebugHelper.print("Error parsing JSON: " + e.getMessage());
        e.printStackTrace();
    }

    //DebugHelper.print(result.size() + " apps found from web store.");

    // Cache the result of this query
    this.appsByUrl.put(currentAppStoreUrl, result);
    return result;
}