Example usage for java.nio ByteBuffer allocateDirect

List of usage examples for java.nio ByteBuffer allocateDirect

Introduction

In this page you can find the example usage for java.nio ByteBuffer allocateDirect.

Prototype

public static ByteBuffer allocateDirect(int capacity) 

Source Link

Document

Creates a direct byte buffer based on a newly allocated memory block.

Usage

From source file:org.apache.hadoop.crypto.CryptoStreamsTestBase.java

/** Test byte buffer read with different buffer size. */
@Test(timeout = 120000)// ww  w  .  ja  v  a  2s.c  o m
public void testByteBufferRead() throws Exception {
    OutputStream out = getOutputStream(defaultBufferSize);
    writeData(out);

    // Default buffer size, initial buffer position is 0
    InputStream in = getInputStream(defaultBufferSize);
    ByteBuffer buf = ByteBuffer.allocate(dataLen + 100);
    byteBufferReadCheck(in, buf, 0);
    in.close();

    // Default buffer size, initial buffer position is not 0
    in = getInputStream(defaultBufferSize);
    buf.clear();
    byteBufferReadCheck(in, buf, 11);
    in.close();

    // Small buffer size, initial buffer position is 0
    in = getInputStream(smallBufferSize);
    buf.clear();
    byteBufferReadCheck(in, buf, 0);
    in.close();

    // Small buffer size, initial buffer position is not 0
    in = getInputStream(smallBufferSize);
    buf.clear();
    byteBufferReadCheck(in, buf, 11);
    in.close();

    // Direct buffer, default buffer size, initial buffer position is 0
    in = getInputStream(defaultBufferSize);
    buf = ByteBuffer.allocateDirect(dataLen + 100);
    byteBufferReadCheck(in, buf, 0);
    in.close();

    // Direct buffer, default buffer size, initial buffer position is not 0
    in = getInputStream(defaultBufferSize);
    buf.clear();
    byteBufferReadCheck(in, buf, 11);
    in.close();

    // Direct buffer, small buffer size, initial buffer position is 0
    in = getInputStream(smallBufferSize);
    buf.clear();
    byteBufferReadCheck(in, buf, 0);
    in.close();

    // Direct buffer, small buffer size, initial buffer position is not 0
    in = getInputStream(smallBufferSize);
    buf.clear();
    byteBufferReadCheck(in, buf, 11);
    in.close();
}

From source file:x10.x10rt.yarn.ApplicationMaster.java

protected void handleX10() {
    // handle X10 place requests
    Iterator<SelectionKey> events = null;
    while (running) {
        try {/*  ww w.ja va  2s  .c o m*/
            SelectionKey key;
            // check for previously unhandled events
            if (events != null && events.hasNext()) {
                key = events.next();
                events.remove();
            } else if (selector.select() == 0) // check for new events
                continue; // nothing to process, go back and block on select again
            else { // select returned some events
                events = selector.selectedKeys().iterator();
                key = events.next();
                events.remove();
            }

            // process the selectionkey
            if (key.isAcceptable()) {
                LOG.info("New connection from X10 detected");
                // accept any connections on the server socket, and look for things to read from it
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);
            }
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();

                ByteBuffer incomingMsg;
                if (pendingReads.containsKey(sc))
                    incomingMsg = pendingReads.remove(sc);
                else
                    incomingMsg = ByteBuffer.allocateDirect(headerLength).order(ByteOrder.nativeOrder());

                LOG.info("Reading message from X10");
                try {
                    if (sc.read(incomingMsg) == -1) {
                        // socket closed
                        sc.close();
                        key.cancel();
                        pendingReads.remove(sc);
                    } else if (incomingMsg.hasRemaining()) {
                        LOG.info("Message header partially read. " + incomingMsg.remaining()
                                + " bytes remaining");
                        pendingReads.put(sc, incomingMsg);
                    } else { // buffer is full
                        if (incomingMsg.capacity() == headerLength) {
                            // check to see if there is a body associated with this message header
                            int datalen = incomingMsg.getInt(headerLength - 4);
                            //System.err.println("Byte order is "+incomingMsg.order()+" datalen="+datalen);
                            if (datalen == 0)
                                processMessage(incomingMsg, sc);
                            else { // create a larger array to hold the header+body
                                ByteBuffer newBuffer = ByteBuffer.allocateDirect(headerLength + datalen)
                                        .order(ByteOrder.nativeOrder());
                                incomingMsg.rewind();
                                newBuffer.put(incomingMsg);
                                incomingMsg = newBuffer;
                                sc.read(incomingMsg); // read in the body, if available
                                if (incomingMsg.hasRemaining()) {
                                    LOG.info("Message partially read. " + incomingMsg.remaining()
                                            + " bytes remaining");
                                    pendingReads.put(sc, incomingMsg);
                                } else
                                    processMessage(incomingMsg, sc);
                            }
                        }
                    }
                } catch (IOException e) {
                    LOG.warn("Error reading in message from socket channel", e);
                }
            }
        } catch (IOException e) {
            LOG.warn("Error handling X10 links", e);
        }
    }
}

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * Configures all the needed components, but does not actually start the server.
 * @param config   Contains all information needed to fully wire up the http, https, and httpclient components of this reverse proxy.
 * @throws Exception   Yeah, a lot can go wrong here, but at least it will be caught immediately :-)
 *//*from  w w  w  .j a  v  a  2s . c  o  m*/
public void config(HierarchicalConfiguration config) throws Exception {
    List<HierarchicalConfiguration> lconf;
    HttpAsyncRequester executor = null;
    BasicNIOConnPool connPool = null;
    ObjectPool<ByteBuffer> byteBufferPool = null;
    LinkedHashMap<String, TargetDescriptor> mappings = null;
    ConcurrentMap<String, HttpHost> hosts = null;

    handlerRegistry = new UriHttpAsyncRequestHandlerMapper();

    // Initialize the keystore (if one was specified)
    KeyStore keystore = null;
    char[] keypass = null;
    String keystoreUri = config.getString("keystore");
    if ((keystoreUri != null) && (keystoreUri.trim().length() > 0)) {
        Path keystorePath = Utils.MakePath(keystoreUri);
        if (!Files.exists(keystorePath))
            throw new ConfigurationException("Keystore does not exist.");
        if (Files.isDirectory(keystorePath))
            throw new ConfigurationException("Keystore is not a file");
        String storepass = config.getString("storepass");
        if ((storepass != null) && "null".equals(storepass))
            storepass = null;
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream keyStoreStream = Files.newInputStream(keystorePath)) {
            keystore.load(keyStoreStream, storepass == null ? null : storepass.trim().toCharArray());
        } catch (IOException ex) {
            Logger.error("Unable to load https server keystore from " + keystoreUri);
            return;
        }
        keypass = config.getString("keypass").trim().toCharArray();
    }

    // Wire up the listening reactor
    lconf = config.configurationsAt("server");
    if ((lconf == null) || (lconf.size() != 1))
        throw new ConfigurationException("One (and only one) server configuration element is allowed.");
    else {
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("server[@cpu]", 0.667)));
        builder.setSoTimeout(config.getInt("server[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("server[@soLinger]", -1));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        builder.setSelectInterval(100);

        IOReactorConfig rconfig = builder.build();
        Logger.info("Configuring server with options: " + rconfig.toString());
        listeningReactor = new DefaultListeningIOReactor(rconfig);

        lconf = config.configurationsAt("server.listen");
        InetSocketAddress addr;
        boolean hasNonWildcardSecure = false;
        LinkedHashMap<SocketAddress, SSLContext> addrSSLContext = new LinkedHashMap<SocketAddress, SSLContext>();
        if ((lconf == null) || (lconf.size() == 0)) {
            addr = new InetSocketAddress("127.0.0.1", 8080);
            ListenerEndpoint ep = listeningReactor.listen(addr);
            Logger.warn("Configured " + ep.getAddress());
        } else {
            TrustManager[] trustManagers = null;
            KeyManagerFactory kmf = null;
            // Create all the specified listeners.
            for (HierarchicalConfiguration hc : lconf) {
                String addrStr = hc.getString("[@address]");
                if ((addrStr == null) || (addrStr.length() == 0))
                    addrStr = "0.0.0.0";
                String alias = hc.getString("[@alias]");
                int port = hc.getInt("[@port]", alias != null ? 443 : 80);
                addr = new InetSocketAddress(addrStr, port);
                ListenerEndpoint ep = listeningReactor.listen(addr);
                String protocol = hc.containsKey("[@protocol]") ? hc.getString("[@protocol]") : null;
                Boolean secure = hc.containsKey("[@secure]") ? hc.getBoolean("[@secure]") : null;
                if ((alias != null) && (secure == null))
                    secure = true;
                if ((protocol != null) && (secure == null))
                    secure = true;
                if ((secure != null) && secure) {
                    if (protocol == null)
                        protocol = "TLS";
                    if (keystore == null)
                        throw new ConfigurationException(
                                "An https listening socket was requested, but no keystore was specified.");
                    if (kmf == null) {
                        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                        kmf.init(keystore, keypass);
                    }
                    // Are we going to trust all clients or just specific ones?
                    if (hc.getBoolean("[@trustAny]", true))
                        trustManagers = new TrustManager[] { new X509TrustAllManager() };
                    else {
                        TrustManagerFactory instance = TrustManagerFactory
                                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                        instance.init(keystore);
                        trustManagers = instance.getTrustManagers();
                    }
                    KeyManager[] keyManagers = kmf.getKeyManagers();
                    if (alias != null)
                        for (int i = 0; i < keyManagers.length; i++) {
                            if (keyManagers[i] instanceof X509ExtendedKeyManager)
                                keyManagers[i] = new PokerFaceKeyManager(alias,
                                        (X509ExtendedKeyManager) keyManagers[i]);
                        }
                    SSLContext sslCtx = SSLContext.getInstance(protocol);
                    sslCtx.init(keyManagers, trustManagers, new SecureRandom());
                    if (addr.getAddress().isAnyLocalAddress()) {
                        // This little optimization helps us respond faster for every connection as we don't have to extrapolate a local connection address to wild card.
                        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                                .hasMoreElements();) {
                            NetworkInterface intf = en.nextElement();
                            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                    .hasMoreElements();) {
                                addr = new InetSocketAddress(enumIpAddr.nextElement(), port);
                                addrSSLContext.put(addr, sslCtx);
                            }
                        }
                    } else {
                        addrSSLContext.put(addr, sslCtx);
                        hasNonWildcardSecure = true;
                    }
                }
                Logger.warn("Configured " + (alias == null ? "" : (protocol + " on")) + ep.getAddress());
            }
        }
        // We will need an HTTP protocol processor for the incoming connections
        String serverAgent = config.getString("server.serverAgent", "PokerFace/" + Utils.Version);
        HttpProcessor inhttpproc = new ImmutableHttpProcessor(
                new HttpResponseInterceptor[] { new ResponseDateInterceptor(), new ResponseServer(serverAgent),
                        new ResponseContent(), new ResponseConnControl() });
        HttpAsyncService serviceHandler = new HttpAsyncService(inhttpproc, new DefaultConnectionReuseStrategy(),
                null, handlerRegistry, null) {
            public void exception(final NHttpServerConnection conn, final Exception cause) {
                Logger.warn(cause.getMessage());
                super.exception(conn, cause);
            }
        };
        if (addrSSLContext.size() > 0) {
            final SSLContext defaultCtx = addrSSLContext.values().iterator().next();
            final Map<SocketAddress, SSLContext> sslMap;
            if ((!hasNonWildcardSecure) || (addrSSLContext.size() == 1))
                sslMap = null;
            else
                sslMap = addrSSLContext;
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler,
                    new SSLNHttpServerConnectionFactory(defaultCtx, null, ConnectionConfig.DEFAULT) {
                        protected SSLIOSession createSSLIOSession(IOSession iosession, SSLContext sslcontext,
                                SSLSetupHandler sslHandler) {
                            SSLIOSession retVal;
                            SSLContext sktCtx = sslcontext;
                            if (sslMap != null) {
                                SocketAddress la = iosession.getLocalAddress();
                                if (la != null) {
                                    sktCtx = sslMap.get(la);
                                    if (sktCtx == null)
                                        sktCtx = sslcontext;
                                }
                                retVal = new SSLIOSession(iosession, SSLMode.SERVER, sktCtx, sslHandler);
                            } else
                                retVal = super.createSSLIOSession(iosession, sktCtx, sslHandler);
                            if (sktCtx != null)
                                retVal.setAttribute("com.bytelightning.opensource.pokerface.secure", true);
                            return retVal;
                        }
                    });
        } else
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, ConnectionConfig.DEFAULT);
    }

    // Configure the httpclient reactor that will be used to do reverse proxing to the specified targets.
    lconf = config.configurationsAt("targets");
    if ((lconf != null) && (lconf.size() > 0)) {
        HierarchicalConfiguration conf = lconf.get(0);
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("targets[@cpu]", 0.667)));
        builder.setSoTimeout(conf.getInt("targets[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("targets[@soLinger]", -1));
        builder.setConnectTimeout(conf.getInt("targets[@connectTimeout]", 0));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        connectingReactor = new DefaultConnectingIOReactor(builder.build());

        final int bufferSize = conf.getInt("targets[@bufferSize]", 1024) * 1024;
        byteBufferPool = new SoftReferenceObjectPool<ByteBuffer>(new BasePooledObjectFactory<ByteBuffer>() {
            @Override
            public ByteBuffer create() throws Exception {
                return ByteBuffer.allocateDirect(bufferSize);
            }

            @Override
            public PooledObject<ByteBuffer> wrap(ByteBuffer buffer) {
                return new DefaultPooledObject<ByteBuffer>(buffer);
            }
        });

        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        if (keystore != null) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keystore, keypass);
            keyManagers = kmf.getKeyManagers();
        }
        // Will the httpclient's trust any remote target, or only specific ones.
        if (conf.getBoolean("targets[@trustAny]", false))
            trustManagers = new TrustManager[] { new X509TrustAllManager() };
        else if (keystore != null) {
            TrustManagerFactory instance = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            instance.init(keystore);
            trustManagers = instance.getTrustManagers();
        }
        SSLContext clientSSLContext = SSLContext.getInstance(conf.getString("targets[@protocol]", "TLS"));
        clientSSLContext.init(keyManagers, trustManagers, new SecureRandom());

        // Setup an SSL capable connection pool for the httpclients.
        connPool = new BasicNIOConnPool(connectingReactor,
                new BasicNIOConnFactory(clientSSLContext, null, ConnectionConfig.DEFAULT),
                conf.getInt("targets[@connectTimeout]", 0));
        connPool.setMaxTotal(conf.getInt("targets[@connMaxTotal]", 1023));
        connPool.setDefaultMaxPerRoute(conf.getInt("targets[@connMaxPerRoute]", 1023));

        // Set up HTTP protocol processor for outgoing connections
        String userAgent = conf.getString("targets.userAgent", "PokerFace/" + Utils.Version);
        HttpProcessor outhttpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                new RequestContent(), new RequestTargetHost(), new RequestConnControl(),
                new RequestUserAgent(userAgent), new RequestExpectContinue(true) });
        executor = new HttpAsyncRequester(outhttpproc, new DefaultConnectionReuseStrategy());

        // Now set up all the configured targets.
        mappings = new LinkedHashMap<String, TargetDescriptor>();
        hosts = new ConcurrentHashMap<String, HttpHost>();
        String[] scheme = { null };
        String[] host = { null };
        int[] port = { 0 };
        String[] path = { null };
        int[] stripPrefixCount = { 0 };
        for (HierarchicalConfiguration targetConfig : conf.configurationsAt("target")) {
            String match = targetConfig.getString("[@pattern]");
            if ((match == null) || (match.trim().length() < 1)) {
                Logger.error("Unable to configure target;  Invalid url match pattern");
                continue;
            }
            String key = RequestForTargetConsumer.UriToTargetKey(targetConfig.getString("[@url]"), scheme, host,
                    port, path, stripPrefixCount);
            if (key == null) {
                Logger.error("Unable to configure target");
                continue;
            }
            HttpHost targetHost = hosts.get(key);
            if (targetHost == null) {
                targetHost = new HttpHost(host[0], port[0], scheme[0]);
                hosts.put(key, targetHost);
            }
            TargetDescriptor desc = new TargetDescriptor(targetHost, path[0], stripPrefixCount[0]);
            mappings.put(match, desc);
        }
        connectionDispatcher = new DefaultHttpClientIODispatch(new HttpAsyncRequestExecutor(),
                ConnectionConfig.DEFAULT);
    }
    // Allocate the script map which will be populated by it's own executor thread.
    if (config.containsKey("scripts.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("scripts.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Scripts directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'scripts' path is not a directory.");
        scripts = new ConcurrentSkipListMap<String, ScriptObjectMirror>();
        boolean watch = config.getBoolean("scripts.dynamicWatch", false);
        List<Path> jsLibs;
        Object prop = config.getProperty("scripts.library");
        if (prop != null) {
            jsLibs = new ArrayList<Path>();
            if (prop instanceof Collection<?>) {
                @SuppressWarnings("unchecked")
                Collection<Object> oprop = (Collection<Object>) prop;
                for (Object obj : oprop)
                    jsLibs.add(Utils.MakePath(obj));
            } else {
                jsLibs.add(Utils.MakePath(prop));
            }
        } else
            jsLibs = null;

        lconf = config.configurationsAt("scripts.scriptConfig");
        if (lconf != null) {
            if (lconf.size() > 1)
                throw new ConfigurationException("Only one scriptConfig element is allowed.");
            if (lconf.size() == 0)
                lconf = null;
        }

        HierarchicalConfiguration scriptConfig;
        if (lconf == null)
            scriptConfig = new HierarchicalConfiguration();
        else
            scriptConfig = lconf.get(0);
        scriptConfig.setProperty("pokerface.scripts.rootDirectory", tmp.toString());

        configureScripts(jsLibs, scriptConfig, tmp, watch);
        if (watch)
            ScriptDirectoryWatcher = new DirectoryWatchService();
    }

    // Configure the static file directory (if any)
    Path staticFilesPath = null;
    if (config.containsKey("files.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("files.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Files directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'files' path is not a directory.");
        staticFilesPath = tmp;
        List<HierarchicalConfiguration> mimeEntries = config.configurationsAt("files.mime-entry");
        if (mimeEntries != null) {
            for (HierarchicalConfiguration entry : mimeEntries) {
                entry.setDelimiterParsingDisabled(true);
                String type = entry.getString("[@type]", "").trim();
                if (type.length() == 0)
                    throw new ConfigurationException("Invalid mime type entry");
                String extensions = entry.getString("[@extensions]", "").trim();
                if (extensions.length() == 0)
                    throw new ConfigurationException("Invalid mime extensions for: " + type);
                ScriptHelperImpl.AddMimeEntry(type, extensions);
            }
        }
    }

    handlerRegistry.register("/*",
            new RequestHandler(executor, connPool, byteBufferPool, staticFilesPath, mappings,
                    scripts != null ? Collections.unmodifiableNavigableMap(scripts) : null,
                    config.getBoolean("scripts.allowScriptsToSpecifyDynamicHosts", false) ? hosts : null));
}

From source file:edu.hawaii.soest.kilonalu.dvp2.DavisWxParser.java

public static void main(String[] args) {

    // Ensure we have a path to the binary file
    if (args.length != 1) {
        logger.info("Please provide the path to a file containing a binary LOOP packet.");
        System.exit(1);// w  w  w .ja  v a 2 s . c o m
    } else {
        try {
            // open and read the file
            File packetFile = new File(args[0]);
            FileInputStream fis = new FileInputStream(packetFile);
            FileChannel fileChannel = fis.getChannel();
            ByteBuffer inBuffer = ByteBuffer.allocateDirect(8192);
            ByteBuffer packetBuffer = ByteBuffer.allocateDirect(8192);

            while (fileChannel.read(inBuffer) != -1 || inBuffer.position() > 0) {
                inBuffer.flip();
                packetBuffer.put(inBuffer.get());
                inBuffer.compact();
            }
            fileChannel.close();
            fis.close();
            packetBuffer.put(inBuffer.get());

            // create an instance of the parser, and report the field contents after parsing
            DavisWxParser davisWxParser = new DavisWxParser(packetBuffer);

            // Set up a simple logger that logs to the console
            PropertyConfigurator.configure(davisWxParser.getLogConfigurationFile());

            logger.info("loopID:                         " + davisWxParser.getLoopID());
            logger.info("barTrend:                       " + davisWxParser.getBarTrend());
            logger.info("barTrendAsString:               " + davisWxParser.getBarTrendAsString());
            logger.info("packetType:                     " + davisWxParser.getPacketType());
            logger.info("nextRecord:                     " + davisWxParser.getNextRecord());
            logger.info("barometer:                      " + davisWxParser.getBarometer());
            logger.info("insideTemperature:              " + davisWxParser.getInsideTemperature());
            logger.info("insideHumidity:                 " + davisWxParser.getInsideHumidity());
            logger.info("outsideTemperature:             " + davisWxParser.getOutsideTemperature());
            logger.info("windSpeed:                      " + davisWxParser.getWindSpeed());
            logger.info("tenMinuteAverageWindSpeed:      " + davisWxParser.getTenMinuteAverageWindSpeed());
            logger.info("windDirection:                  " + davisWxParser.getWindDirection());
            logger.info(
                    "extraTemperatures:              " + Arrays.toString(davisWxParser.getExtraTemperatures()));
            logger.info(
                    "soilTemperatures:               " + Arrays.toString(davisWxParser.getSoilTemperatures()));
            logger.info(
                    "leafTemperatures:               " + Arrays.toString(davisWxParser.getLeafTemperatures()));
            logger.info("outsideHumidity:                " + davisWxParser.getOutsideHumidity());
            logger.info(
                    "extraHumidities:                " + Arrays.toString(davisWxParser.getExtraHumidities()));
            logger.info("rainRate:                       " + davisWxParser.getRainRate());
            logger.info("uvRadiation:                    " + davisWxParser.getUvRadiation());
            logger.info("solarRadiation:                 " + davisWxParser.getSolarRadiation());
            logger.info("stormRain:                      " + davisWxParser.getStormRain());
            logger.info("currentStormStartDate:          " + davisWxParser.getCurrentStormStartDate());
            logger.info("dailyRain:                      " + davisWxParser.getDailyRain());
            logger.info("monthlyRain:                    " + davisWxParser.getMonthlyRain());
            logger.info("yearlyRain:                     " + davisWxParser.getYearlyRain());
            logger.info("dailyEvapoTranspiration:        " + davisWxParser.getDailyEvapoTranspiration());
            logger.info("monthlyEvapoTranspiration:      " + davisWxParser.getMonthlyEvapoTranspiration());
            logger.info("yearlyEvapoTranspiration:       " + davisWxParser.getYearlyEvapoTranspiration());
            logger.info("soilMoistures:                  " + Arrays.toString(davisWxParser.getSoilMoistures()));
            logger.info("leafWetnesses:                  " + Arrays.toString(davisWxParser.getLeafWetnesses()));
            logger.info("insideAlarm:                    " + davisWxParser.getInsideAlarm());
            logger.info("rainAlarm:                      " + davisWxParser.getRainAlarm());
            logger.info("outsideAlarms:                  " + davisWxParser.getOutsideAlarms());
            logger.info("extraTemperatureHumidityAlarms: " + davisWxParser.getExtraTemperatureHumidityAlarms());
            logger.info("soilLeafAlarms:                 " + davisWxParser.getSoilLeafAlarms());
            logger.info("transmitterBatteryStatus:       " + davisWxParser.getTransmitterBatteryStatus());
            logger.info("consoleBatteryVoltage:          " + davisWxParser.getConsoleBatteryVoltage());
            logger.info("forecastIconValues:             " + davisWxParser.getForecastAsString());
            logger.info("forecastRuleNumber:             " + davisWxParser.getForecastRuleNumberAsString());
            logger.info("timeOfSunrise:                  " + davisWxParser.getTimeOfSunrise());
            logger.info("timeOfSunset:                   " + davisWxParser.getTimeOfSunset());
            logger.info("recordDelimiter:                " + davisWxParser.getRecordDelimiterAsHexString());
            logger.info("crcChecksum:                    " + davisWxParser.getCrcChecksum());

        } catch (java.io.FileNotFoundException fnfe) {
            fnfe.printStackTrace();

        } catch (java.io.IOException ioe) {
            ioe.printStackTrace();

        }

    }
}

From source file:com.sveder.cardboardpassthrough.MainActivity.java

/**
 * Creates the buffers we use to store information about the 3D world. OpenGL doesn't use Java
 * arrays, but rather needs data in a format it can understand. Hence we use ByteBuffers.
 * @param config The EGL configuration used when creating the surface.
 *//*from  w  ww .j  av  a  2s  . c om*/
@Override
public void onSurfaceCreated(EGLConfig config) {
    Log.i(TAG, "onSurfaceCreated");
    GLES20.glClearColor(0.1f, 0.1f, 0.1f, 0.5f); // Dark background so text shows up well

    ByteBuffer bb = ByteBuffer.allocateDirect(squareVertices.length * 4);
    bb.order(ByteOrder.nativeOrder());
    vertexBuffer = bb.asFloatBuffer();
    vertexBuffer.put(squareVertices);
    vertexBuffer.position(0);

    ByteBuffer dlb = ByteBuffer.allocateDirect(drawOrder.length * 2);
    dlb.order(ByteOrder.nativeOrder());
    drawListBuffer = dlb.asShortBuffer();
    drawListBuffer.put(drawOrder);
    drawListBuffer.position(0);

    ByteBuffer bb2 = ByteBuffer.allocateDirect(textureVertices.length * 4);
    bb2.order(ByteOrder.nativeOrder());
    textureVerticesBuffer = bb2.asFloatBuffer();
    textureVerticesBuffer.put(textureVertices);
    textureVerticesBuffer.position(0);

    int vertexShader = loadGLShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
    int fragmentShader = loadGLShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);

    mProgram = GLES20.glCreateProgram(); // create empty OpenGL ES Program
    GLES20.glAttachShader(mProgram, vertexShader); // add the vertex shader to program
    GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
    GLES20.glLinkProgram(mProgram);

    texture = createTexture();
    startCamera(texture);

    //        ByteBuffer bbVertices = ByteBuffer.allocateDirect(DATA.CUBE_COORDS.length * 4);
    //        bbVertices.order(ByteOrder.nativeOrder());
    //        mCubeVertices = bbVertices.asFloatBuffer();
    //        mCubeVertices.put(DATA.CUBE_COORDS);
    //        mCubeVertices.position(0);
    //
    //        ByteBuffer bbColors = ByteBuffer.allocateDirect(DATA.CUBE_COLORS.length * 4);
    //        bbColors.order(ByteOrder.nativeOrder());
    //        mCubeColors = bbColors.asFloatBuffer();
    //        mCubeColors.put(DATA.CUBE_COLORS);
    //        mCubeColors.position(0);
    //
    //        ByteBuffer bbFoundColors = ByteBuffer.allocateDirect(DATA.CUBE_FOUND_COLORS.length * 4);
    //        bbFoundColors.order(ByteOrder.nativeOrder());
    //        mCubeFoundColors = bbFoundColors.asFloatBuffer();
    //        mCubeFoundColors.put(DATA.CUBE_FOUND_COLORS);
    //        mCubeFoundColors.position(0);
    //
    //        ByteBuffer bbNormals = ByteBuffer.allocateDirect(DATA.CUBE_NORMALS.length * 4);
    //        bbNormals.order(ByteOrder.nativeOrder());
    //        mCubeNormals = bbNormals.asFloatBuffer();
    //        mCubeNormals.put(DATA.CUBE_NORMALS);
    //        mCubeNormals.position(0);
    //
    //        // make a floor
    //        ByteBuffer bbFloorVertices = ByteBuffer.allocateDirect(DATA.FLOOR_COORDS.length * 4);
    //        bbFloorVertices.order(ByteOrder.nativeOrder());
    //        mFloorVertices = bbFloorVertices.asFloatBuffer();
    //        mFloorVertices.put(DATA.FLOOR_COORDS);
    //        mFloorVertices.position(0);
    //
    //        ByteBuffer bbFloorNormals = ByteBuffer.allocateDirect(DATA.FLOOR_NORMALS.length * 4);
    //        bbFloorNormals.order(ByteOrder.nativeOrder());
    //        mFloorNormals = bbFloorNormals.asFloatBuffer();
    //        mFloorNormals.put(DATA.FLOOR_NORMALS);
    //        mFloorNormals.position(0);
    //
    //        ByteBuffer bbFloorColors = ByteBuffer.allocateDirect(DATA.FLOOR_COLORS.length * 4);
    //        bbFloorColors.order(ByteOrder.nativeOrder());
    //        mFloorColors = bbFloorColors.asFloatBuffer();
    //        mFloorColors.put(DATA.FLOOR_COLORS);
    //        mFloorColors.position(0);
    //
    //        int vertexShader = loadGLShader(GLES20.GL_VERTEX_SHADER, R.raw.light_vertex);
    //        int gridShader = loadGLShader(GLES20.GL_FRAGMENT_SHADER, R.raw.grid_fragment);
    //
    //        mGlProgram = GLES20.glCreateProgram();
    //        GLES20.glAttachShader(mGlProgram, vertexShader);
    //        GLES20.glAttachShader(mGlProgram, gridShader);
    //        GLES20.glLinkProgram(mGlProgram);
    //
    //        GLES20.glEnable(GLES20.GL_DEPTH_TEST);
    //
    //        // Object first appears directly in front of user
    //        Matrix.setIdentityM(mModelCube, 0);
    //        Matrix.translateM(mModelCube, 0, 0, 0, -mObjectDistance);
    //
    //        Matrix.setIdentityM(mModelFloor, 0);
    //        Matrix.translateM(mModelFloor, 0, 0, -mFloorDepth, 0); // Floor appears below user
    //
    //        checkGLError("onSurfaceCreated");
}

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.  j  a va2s  .  c om*/
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.pavlospt.rxfile.RxFile.java

private static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
        throws IOException {
    final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
    while (src.read(buffer) != -1) {
        buffer.flip();//from   www.j  ava2  s .  com
        dest.write(buffer);
        buffer.compact();
    }
    buffer.flip();
    while (buffer.hasRemaining()) {
        dest.write(buffer);
    }
}

From source file:com.ibm.crail.tools.CrailBenchmark.java

void readMultiStream(String filename, int size, int loop, int batch) throws Exception {
    System.out.println(/* w  ww  .ja v a  2s  .c  o m*/
            "readMultiStream, filename " + filename + ", size " + size + ", loop " + loop + ", batch " + batch);

    //warmup
    ConcurrentLinkedQueue<CrailBuffer> bufferQueue = new ConcurrentLinkedQueue<CrailBuffer>();
    for (int i = 0; i < warmup; i++) {
        CrailBuffer buf = fs.allocateBuffer().limit(size).slice();
        bufferQueue.add(buf);
    }
    warmUp(filename, warmup, bufferQueue);
    while (!bufferQueue.isEmpty()) {
        CrailBuffer buf = bufferQueue.poll();
        fs.freeBuffer(buf);
    }

    //benchmark
    System.out.println("starting benchmark...");
    fs.getStatistics().reset();
    CrailBuffer _buf = null;
    if (size == CrailConstants.BUFFER_SIZE) {
        _buf = fs.allocateBuffer();
    } else if (size < CrailConstants.BUFFER_SIZE) {
        CrailBuffer __buf = fs.allocateBuffer();
        __buf.clear().limit(size);
        _buf = __buf.slice();
    } else {
        _buf = OffHeapBuffer.wrap(ByteBuffer.allocateDirect(size));
    }
    ByteBuffer buf = _buf.getByteBuffer();
    for (int i = 0; i < loop; i++) {
        CrailBufferedInputStream multiStream = fs.lookup(filename).get().asMultiFile().getMultiStream(batch);
        double sumbytes = 0;
        long _sumbytes = 0;
        double ops = 0;
        buf.clear();
        long start = System.currentTimeMillis();
        int ret = multiStream.read(buf);
        while (ret >= 0) {
            sumbytes = sumbytes + ret;
            long _ret = (long) ret;
            _sumbytes += _ret;
            ops = ops + 1.0;
            buf.clear();
            ret = multiStream.read(buf);
        }
        long end = System.currentTimeMillis();
        multiStream.close();

        double executionTime = ((double) (end - start)) / 1000.0;
        double throughput = 0.0;
        double latency = 0.0;
        double sumbits = sumbytes * 8.0;
        if (executionTime > 0) {
            throughput = sumbits / executionTime / 1000.0 / 1000.0;
            latency = 1000000.0 * executionTime / ops;
        }

        System.out.println("round " + i + ":");
        System.out.println("bytes read " + _sumbytes);
        System.out.println("execution time " + executionTime);
        System.out.println("ops " + ops);
        System.out.println("throughput " + throughput);
        System.out.println("latency " + latency);
    }

    fs.getStatistics().print("close");
}

From source file:com.alvermont.terraj.fracplanet.geom.VertexBufferArray.java

/**
 * Resize the buffer. This is done by reallocating a new one and copying
 * data from the old buffer to the new one. This is necessary as buffers
 * cannot be dynamically resized.//w w  w.j a  va2  s .co m
 */
protected void resizeBuffer() {
    // we can't resize it so we have to allocate a new one and copy the data
    final int slots = (buffer.capacity() / ELEMENTSIZE);
    final int newCapacity = buffer.capacity()
            + (((slots * CAPACITY_PCT_INCREASE) / HUNDRED_PERCENT) * ELEMENTSIZE);

    final ByteBuffer newBuffer = ByteBuffer.allocateDirect(newCapacity).order(ByteOrder.nativeOrder());

    if (log.isDebugEnabled()) {
        log.debug("Resizing vertex buffer capacity to: " + newBuffer.capacity());
    }

    final FloatBuffer oldVertexBuffer = positionBuffer;
    final FloatBuffer oldNormalBuffer = normalBuffer;
    final ByteBuffer oldColourBuffer = colourBuffer;
    final ByteBuffer oldEmissiveBuffer = emissiveBuffer;

    this.buffer = newBuffer;

    sliceAndDice(newCapacity / ELEMENTSIZE);

    oldVertexBuffer.rewind();
    positionBuffer.rewind();
    positionBuffer.limit(oldVertexBuffer.limit());
    positionBuffer.put(oldVertexBuffer);

    oldNormalBuffer.rewind();
    normalBuffer.rewind();
    normalBuffer.limit(oldNormalBuffer.limit());
    normalBuffer.put(oldNormalBuffer);

    oldColourBuffer.rewind();
    colourBuffer.rewind();
    colourBuffer.limit(oldColourBuffer.limit());
    colourBuffer.put(oldColourBuffer);

    oldEmissiveBuffer.rewind();
    emissiveBuffer.rewind();
    emissiveBuffer.limit(oldEmissiveBuffer.limit());
    emissiveBuffer.put(oldEmissiveBuffer);
}

From source file:org.jtrfp.trcl.core.Texture.java

public static ByteBuffer RGBA8FromPNG(BufferedImage image, int startX, int startY, int sizeX, int sizeY) {
    //int color;/*w  ww  .  j av a  2  s.  co m*/
    ByteBuffer buf = ByteBuffer.allocateDirect(image.getWidth() * image.getHeight() * 4);
    final int[] row = new int[image.getWidth()];
    for (int y = startY; y < startY + sizeY; y++) {
        image.getRGB(0, y, image.getWidth(), 1, row, 0, image.getWidth());
        for (int color : row) {
            buf.put((byte) ((color & 0x00FF0000) >> 16));
            buf.put((byte) ((color & 0x0000FF00) >> 8));
            buf.put((byte) (color & 0x000000FF));
            buf.put((byte) ((color & 0xFF000000) >> 24));
        } // end for(x)
    } // end for(y)
    buf.clear();// Rewind
    return buf;
}