List of usage examples for java.nio ByteBuffer hasRemaining
public final boolean hasRemaining()
From source file:ffx.realspace.CCP4MapFilter.java
/** * {@inheritDoc}/* w w w . j av a 2s . c om*/ */ @Override public boolean readFile(String filename, RealSpaceRefinementData refinementdata, CompositeConfiguration properties) { int imapData; double cellA, cellB, cellC, cellAlpha, cellBeta, cellGamma; String stampString; ByteOrder byteOrder = ByteOrder.nativeOrder(); FileInputStream fileInputStream; DataInputStream dataInputStream; double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; double mean = 0.0; double sd = 0.0; double rmsd = 0.0; // First determine byte order of file versus system try { fileInputStream = new FileInputStream(filename); dataInputStream = new DataInputStream(fileInputStream); dataInputStream.skipBytes(212); byte bytes[] = new byte[4]; dataInputStream.read(bytes, 0, 4); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); imapData = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt(); stampString = Integer.toHexString(imapData); switch (stampString.charAt(0)) { case '1': case '3': if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) { byteOrder = ByteOrder.BIG_ENDIAN; } break; case '4': if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) { byteOrder = ByteOrder.LITTLE_ENDIAN; } break; } if (logger.isLoggable(Level.INFO)) { StringBuilder sb = new StringBuilder(); sb.append(String.format("\n Opening CCP4 map: %s\n", filename)); //sb.append(String.format("file type (machine stamp): %s\n", stampString)); logger.info(sb.toString()); } fileInputStream.close(); } catch (Exception e) { String message = " Fatal exception reading CCP4 map.\n"; logger.log(Level.SEVERE, message, e); } try { fileInputStream = new FileInputStream(filename); dataInputStream = new DataInputStream(fileInputStream); byte bytes[] = new byte[2048]; dataInputStream.read(bytes, 0, 1024); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); int ext[] = new int[3]; ext[0] = byteBuffer.order(byteOrder).getInt(); ext[1] = byteBuffer.order(byteOrder).getInt(); ext[2] = byteBuffer.order(byteOrder).getInt(); // mode (2 = reals, only one we accept) int mode = byteBuffer.order(byteOrder).getInt(); int ori[] = new int[3]; ori[0] = byteBuffer.order(byteOrder).getInt(); ori[1] = byteBuffer.order(byteOrder).getInt(); ori[2] = byteBuffer.order(byteOrder).getInt(); int ni[] = new int[3]; ni[0] = byteBuffer.order(byteOrder).getInt(); ni[1] = byteBuffer.order(byteOrder).getInt(); ni[2] = byteBuffer.order(byteOrder).getInt(); cellA = byteBuffer.order(byteOrder).getFloat(); cellB = byteBuffer.order(byteOrder).getFloat(); cellC = byteBuffer.order(byteOrder).getFloat(); cellAlpha = byteBuffer.order(byteOrder).getFloat(); cellBeta = byteBuffer.order(byteOrder).getFloat(); cellGamma = byteBuffer.order(byteOrder).getFloat(); int axisi[] = new int[3]; for (int i = 0; i < 3; i++) { int axis = byteBuffer.order(byteOrder).getInt(); switch (axis) { case 1: axisi[0] = i; break; case 2: axisi[1] = i; break; case 3: axisi[2] = i; break; } } min = byteBuffer.order(byteOrder).getFloat(); max = byteBuffer.order(byteOrder).getFloat(); mean = byteBuffer.order(byteOrder).getFloat(); int sg = byteBuffer.order(byteOrder).getInt(); int nsymb = byteBuffer.order(byteOrder).getInt(); int skew = byteBuffer.order(byteOrder).getInt(); for (int i = 0; i < 12; i++) { byteBuffer.order(byteOrder).getFloat(); } for (int i = 0; i < 15; i++) { byteBuffer.order(byteOrder).getInt(); } byte word[] = new byte[2048]; byteBuffer.order(byteOrder).get(word, 0, 4); String mapString = new String(word); sd = byteBuffer.order(byteOrder).getFloat(); rmsd = byteBuffer.order(byteOrder).getFloat(); if (logger.isLoggable(Level.INFO)) { StringBuilder sb = new StringBuilder(); sb.append(String.format(" Column origin: %d\t Extent: %d\n", ori[0], ext[0])); sb.append(String.format(" Row origin: %d\t Extent: %d\n", ori[1], ext[1])); sb.append(String.format(" Section origin: %d\t Extent: %d\n", ori[2], ext[2])); sb.append(String.format(" Axis order: %d %d %d\n", axisi[0], axisi[1], axisi[2])); sb.append(String.format(" Number of X, Y, Z columns: %d %d %d\n", ni[0], ni[1], ni[2])); sb.append(String.format(" Spacegroup: %d (%s)\n", sg, SpaceGroup.spaceGroupNames[sg - 1])); sb.append(String.format(" Cell: %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", cellA, cellB, cellC, cellAlpha, cellBeta, cellGamma)); logger.info(sb.toString()); } int nlabel = byteBuffer.order(byteOrder).getInt(); for (int i = 0; i < 10; i++) { byteBuffer.order(byteOrder).get(word, 0, 80); mapString = new String(word); } if (nsymb > 0) { byteBuffer.rewind(); dataInputStream.read(bytes, 0, nsymb); for (int i = 0; i < nsymb / 80; i += 80) { byteBuffer.order(byteOrder).get(word, 0, 80); mapString = new String(word); } } byteBuffer.rewind(); dataInputStream.read(bytes, 0, 2048); refinementdata.setData(new double[ext[0] * ext[1] * ext[2]]); int ijk[] = new int[3]; int index, x, y, z; refinementdata.setOrigin(ori[axisi[0]], ori[axisi[1]], ori[axisi[2]]); int nx = ext[axisi[0]]; int ny = ext[axisi[1]]; int nz = ext[axisi[2]]; refinementdata.setExtent(nx, ny, nz); refinementdata.setNI(ni[0], ni[1], ni[2]); for (ijk[2] = 0; ijk[2] < ext[2]; ijk[2]++) { for (ijk[1] = 0; ijk[1] < ext[1]; ijk[1]++) { for (ijk[0] = 0; ijk[0] < ext[0]; ijk[0]++) { x = ijk[axisi[0]]; y = ijk[axisi[1]]; z = ijk[axisi[2]]; index = x + nx * (y + ny * z); refinementdata.getData()[index] = byteBuffer.order(byteOrder).getFloat(); if (!byteBuffer.hasRemaining()) { byteBuffer.rewind(); dataInputStream.read(bytes, 0, 2048); } } } } fileInputStream.close(); } catch (Exception e) { String message = " Fatal exception reading CCP4 map.\n"; logger.log(Level.SEVERE, message, e); } return true; }
From source file:ffx.xray.CCP4MapFilter.java
/** * {@inheritDoc}// w ww. ja v a 2 s .com */ @Override public boolean readFile(String filename, RealSpaceRefinementData refinementdata, CompositeConfiguration properties) { int imapdata; double cella, cellb, cellc, cellalpha, cellbeta, cellgamma; String stampstr; ByteOrder b = ByteOrder.nativeOrder(); FileInputStream fis; DataInputStream dis; double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; double mean = 0.0; double sd = 0.0; double rmsd = 0.0; // first determine byte order of file versus system try { fis = new FileInputStream(filename); dis = new DataInputStream(fis); dis.skipBytes(212); byte bytes[] = new byte[4]; dis.read(bytes, 0, 4); ByteBuffer bb = ByteBuffer.wrap(bytes); imapdata = bb.order(ByteOrder.BIG_ENDIAN).getInt(); stampstr = Integer.toHexString(imapdata); // System.out.println("stamp: " + stampstr); switch (stampstr.charAt(0)) { case '1': case '3': if (b.equals(ByteOrder.LITTLE_ENDIAN)) { b = ByteOrder.BIG_ENDIAN; } break; case '4': if (b.equals(ByteOrder.BIG_ENDIAN)) { b = ByteOrder.LITTLE_ENDIAN; } break; } if (logger.isLoggable(Level.INFO)) { StringBuilder sb = new StringBuilder(); sb.append(String.format("\nOpening CCP4 map: %s\n", filename)); sb.append(String.format("file type (machine stamp): %s\n", stampstr)); logger.info(sb.toString()); } fis.close(); } catch (Exception e) { String message = "Fatal exception reading CCP4 map.\n"; logger.log(Level.SEVERE, message, e); System.exit(-1); } try { fis = new FileInputStream(filename); dis = new DataInputStream(fis); byte bytes[] = new byte[2048]; dis.read(bytes, 0, 1024); ByteBuffer bb = ByteBuffer.wrap(bytes); int ext[] = new int[3]; ext[0] = bb.order(b).getInt(); ext[1] = bb.order(b).getInt(); ext[2] = bb.order(b).getInt(); // mode (2 = reals, only one we accept) int mode = bb.order(b).getInt(); int ori[] = new int[3]; ori[0] = bb.order(b).getInt(); ori[1] = bb.order(b).getInt(); ori[2] = bb.order(b).getInt(); int ni[] = new int[3]; ni[0] = bb.order(b).getInt(); ni[1] = bb.order(b).getInt(); ni[2] = bb.order(b).getInt(); cella = bb.order(b).getFloat(); cellb = bb.order(b).getFloat(); cellc = bb.order(b).getFloat(); cellalpha = bb.order(b).getFloat(); cellbeta = bb.order(b).getFloat(); cellgamma = bb.order(b).getFloat(); int axisi[] = new int[3]; for (int i = 0; i < 3; i++) { int axis = bb.order(b).getInt(); switch (axis) { case 1: axisi[0] = i; break; case 2: axisi[1] = i; break; case 3: axisi[2] = i; break; } } min = bb.order(b).getFloat(); max = bb.order(b).getFloat(); mean = bb.order(b).getFloat(); int sg = bb.order(b).getInt(); int nsymb = bb.order(b).getInt(); int skew = bb.order(b).getInt(); for (int i = 0; i < 12; i++) { bb.order(b).getFloat(); } for (int i = 0; i < 15; i++) { bb.order(b).getInt(); } byte word[] = new byte[2048]; bb.order(b).get(word, 0, 4); String mapstr = new String(word); // System.out.println("MAP?: " + mapstr); sd = bb.order(b).getFloat(); rmsd = bb.order(b).getFloat(); /* System.out.println("col: " + ori[0] + " " + ext[0] + " " + ni[0]); System.out.println("row: " + ori[1] + " " + ext[1] + " " + ni[1]); System.out.println("sec: " + ori[2] + " " + ext[2] + " " + ni[2]); System.out.println("order: " + axisi[0] + " " + axisi[1] + " " + axisi[2]); System.out.println("min: " + min + " max: " + max + " mean: " + mean); System.out.println("sd: " + sd + " rmsd: " + rmsd); System.out.println("sg: " + sg); System.out.println("a: " + cella + " b: " + cellb + " c: " + cellc + " alpha: " + cellalpha + " beta: " + cellbeta + " gamma: " + cellgamma); */ if (logger.isLoggable(Level.INFO)) { StringBuilder sb = new StringBuilder(); sb.append(String.format(" column origin: %d extent: %d\n", ori[0], ext[0])); sb.append(String.format(" row origin: %d extent: %d\n", ori[1], ext[1])); sb.append(String.format(" section origin: %d extent: %d\n", ori[2], ext[2])); sb.append(String.format(" axis order: %d %d %d\n", axisi[0], axisi[1], axisi[2])); sb.append(String.format(" number of X, Y, Z columns: %d %d %d\n", ni[0], ni[1], ni[2])); sb.append(String.format(" spacegroup #: %d (name: %s)\n", sg, SpaceGroup.spaceGroupNames[sg - 1])); sb.append(String.format(" cell: %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", cella, cellb, cellc, cellalpha, cellbeta, cellgamma)); logger.info(sb.toString()); } int nlabel = bb.order(b).getInt(); // System.out.println("nsymb: " + nsymb + " nlabel: " + nlabel); for (int i = 0; i < 10; i++) { bb.order(b).get(word, 0, 80); mapstr = new String(word); // System.out.println("label " + i + " : " + mapstr); } if (nsymb > 0) { bb.rewind(); dis.read(bytes, 0, nsymb); for (int i = 0; i < nsymb / 80; i += 80) { bb.order(b).get(word, 0, 80); mapstr = new String(word); // System.out.println("symm: " + mapstr); } } bb.rewind(); dis.read(bytes, 0, 2048); refinementdata.data = new double[ext[0] * ext[1] * ext[2]]; int ijk[] = new int[3]; int index, x, y, z; refinementdata.ori[0] = ori[axisi[0]]; refinementdata.ori[1] = ori[axisi[1]]; refinementdata.ori[2] = ori[axisi[2]]; int nx = ext[axisi[0]]; int ny = ext[axisi[1]]; int nz = ext[axisi[2]]; refinementdata.ext[0] = nx; refinementdata.ext[1] = ny; refinementdata.ext[2] = nz; refinementdata.ni[0] = ni[0]; refinementdata.ni[1] = ni[1]; refinementdata.ni[2] = ni[2]; for (ijk[2] = 0; ijk[2] < ext[2]; ijk[2]++) { for (ijk[1] = 0; ijk[1] < ext[1]; ijk[1]++) { for (ijk[0] = 0; ijk[0] < ext[0]; ijk[0]++) { x = ijk[axisi[0]]; y = ijk[axisi[1]]; z = ijk[axisi[2]]; index = x + nx * (y + ny * z); refinementdata.data[index] = bb.order(b).getFloat(); if (!bb.hasRemaining()) { bb.rewind(); dis.read(bytes, 0, 2048); } } } } fis.close(); } catch (Exception e) { String message = "Fatal exception reading CCP4 map.\n"; logger.log(Level.SEVERE, message, e); System.exit(-1); } return true; }
From source file:org.apache.geode.internal.cache.Oplog.java
private void flush(OplogFile olf, ByteBuffer b1, ByteBuffer b2) throws IOException { try {//from w w w . j a v a 2 s . co m // No need to get the backup lock prior to synchronizing (correct lock order) since the // synchronized block does not attempt to get the backup lock (incorrect lock order) synchronized (this.lock/* olf */) { if (olf.RAFClosed) { return; } this.bbArray[0] = b1; this.bbArray[1] = b2; b1.flip(); long flushed = 0; do { flushed += olf.channel.write(this.bbArray); } while (b2.hasRemaining()); this.bbArray[0] = null; this.bbArray[1] = null; // update bytesFlushed after entire writeBuffer is flushed to fix bug 41201 olf.bytesFlushed += flushed; b1.clear(); } } catch (ClosedChannelException ignore) { // It is possible for a channel to be closed when our code does not // explicitly call channel.close (when we will set RAFclosed). // This can happen when a thread is doing an io op and is interrupted. // That thread will see ClosedByInterruptException but it will also // close the channel and then we will see ClosedChannelException. } }
From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java
/** * This function drives the initiating side of the context establishment * process. It is expected to be called in tandem with the * {@link #acceptSecContext(byte[], int, int) acceptSecContext} function. * <BR>/*from w w w . j a v a 2 s .co m*/ * The behavior of context establishment process can be modified by * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE}, * {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE}, and * {@link GSSConstants#REJECT_LIMITED_PROXY GSSConstants.REJECT_LIMITED_PROXY} * context options. If the {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * option is set to {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL} * the context establishment process will be compatible with regular SSL * (no credential delegation support). If the option is set to * {@link GSIConstants#MODE_GSI GSIConstants.GSS_MODE_GSI} * credential delegation during context establishment process will performed. * The delegation type to be performed can be set using the * {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE} * context option. If the {@link GSSConstants#REJECT_LIMITED_PROXY * GSSConstants.REJECT_LIMITED_PROXY} option is enabled, * a peer presenting limited proxy credential will be automatically * rejected and the context establishment process will be aborted. * * @return a byte[] containing the token to be sent to the peer. * null indicates that no token is generated (needs more data). */ public byte[] initSecContext(byte[] inBuff, int off, int len) throws GSSException { logger.debug("enter initSecContext"); if (!this.conn) { this.role = INITIATE; logger.debug("enter initializing in initSecContext"); if (this.anonymity || this.ctxCred.getName().isAnonymous()) { this.anonymity = true; } else { this.anonymity = false; setCredential(); if (this.ctxCred.getUsage() != GSSCredential.INITIATE_ONLY && this.ctxCred.getUsage() != GSSCredential.INITIATE_AND_ACCEPT) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN, "badCredUsage"); } } if (getCredDelegState()) { if (this.gssMode == GSIConstants.MODE_SSL) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "initCtx00"); } if (this.anonymity) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "initCtx01"); } } try { init(this.role); } catch (SSLException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.conn = true; logger.debug("done initializing in initSecContext"); } // Unless explicitly disabled, check if delegation is // requested and expected target is null logger.debug("Require authz with delegation: " + this.requireAuthzWithDelegation); if (!Boolean.FALSE.equals(this.requireAuthzWithDelegation)) { if (this.expectedTargetName == null && getCredDelegState()) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "initCtx02"); } } /*DEL this.out.reset(); this.in.putToken(inBuff, off, len); */ this.outByteBuff.clear(); ByteBuffer inByteBuff; if (savedInBytes != null) { if (len > 0) { byte[] allInBytes = new byte[savedInBytes.length + len]; logger.debug("ALLOCATED for allInBytes " + savedInBytes.length + " + " + len + " bytes\n"); System.arraycopy(savedInBytes, 0, allInBytes, 0, savedInBytes.length); System.arraycopy(inBuff, off, allInBytes, savedInBytes.length, len); inByteBuff = ByteBuffer.wrap(allInBytes, 0, allInBytes.length); } else { inByteBuff = ByteBuffer.wrap(savedInBytes, 0, savedInBytes.length); } savedInBytes = null; } else { inByteBuff = ByteBuffer.wrap(inBuff, off, len); } switch (state) { case HANDSHAKE: try { logger.debug("STATUS BEFORE: " + this.sslEngine.getHandshakeStatus().toString()); SSLEngineResult.HandshakeStatus handshake_status = sslEngine.getHandshakeStatus(); if (handshake_status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // return null; throw new Exception("GSSAPI in HANDSHAKE state but " + "SSLEngine in NOT_HANDSHAKING state!"); } else { outByteBuff = this.sslProcessHandshake(inByteBuff, outByteBuff); } logger.debug("STATUS AFTER: " + this.sslEngine.getHandshakeStatus().toString()); outByteBuff.flip(); /*DEL this.conn.getHandshake().processHandshake(); if (this.conn.getHandshake().finishedP()) { */ if (this.sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // the wrap/unwrap above has resulted in handshaking // being complete on our end. logger.debug("initSecContext handshake finished"); handshakeFinished(); /*DEL Vector chain = this.conn.getCertificateChain(); X509Cert crt = (X509Cert)chain.elementAt(chain.size()-1); setGoodUntil(crt.getValidityNotAfter()); */ Certificate[] chain = this.sslEngine.getSession().getPeerCertificates(); if (!(chain instanceof X509Certificate[])) { throw new Exception("Certificate chain not of type X509Certificate"); } for (X509Certificate cert : (X509Certificate[]) chain) { setGoodUntil(cert.getNotAfter()); } // acceptor - peer /*DEL String identity = verifyChain(chain); */ // chain verification would have already been done by // JSSE String identity = BouncyCastleUtil.getIdentity( bcConvert(BouncyCastleUtil.getIdentityCertificate((X509Certificate[]) chain))); this.targetName = new GlobusGSSName(CertificateUtil.toGlobusID(identity, false)); this.peerLimited = Boolean.valueOf(ProxyCertificateUtil .isLimitedProxy(BouncyCastleUtil.getCertificateType((X509Certificate) chain[0]))); logger.debug("Peer Identity is: " + identity + " Target name is: " + this.targetName + " Limited Proxy: " + this.peerLimited.toString()); // initiator if (this.anonymity) { this.sourceName = new GlobusGSSName(); } else { for (X509Certificate cert : this.ctxCred.getCertificateChain()) { setGoodUntil(cert.getNotAfter()); } this.sourceName = this.ctxCred.getName(); } // mutual authentication test if (this.expectedTargetName != null && !this.expectedTargetName.equals(this.targetName)) { throw new GlobusGSSException(GSSException.UNAUTHORIZED, GlobusGSSException.BAD_NAME, "authFailed00", new Object[] { this.expectedTargetName, this.targetName }); } if (this.gssMode == GSIConstants.MODE_GSI) { this.state = CLIENT_START_DEL; // if there is data to return then // break. otherwise we fall through!!! if (this.outByteBuff.remaining() > 0) { break; } } else { setDone(); break; } } else { break; } } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } case CLIENT_START_DEL: logger.debug("CLIENT_START_DEL"); // sanity check - might be invalid state if (this.state != CLIENT_START_DEL || this.outByteBuff.remaining() > 0) { throw new GSSException(GSSException.FAILURE); } if (inByteBuff.hasRemaining()) { throw new GlobusGSSException(GSSException.FAILURE, new Exception( "Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining() + " Handshaking status: " + sslEngine.getHandshakeStatus())); } this.outByteBuff.clear(); try { String deleg; if (getCredDelegState()) { deleg = Character.toString(GSIConstants.DELEGATION_CHAR); this.state = CLIENT_END_DEL; } else { deleg = Character.toString('0'); setDone(); } byte[] a = deleg.getBytes("US-ASCII"); inByteBuff = ByteBuffer.wrap(a, 0, a.length); outByteBuff = sslDataWrap(inByteBuff, outByteBuff); outByteBuff.flip(); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } break; case CLIENT_END_DEL: logger.debug("CLIENT_END_DEL"); if (!inByteBuff.hasRemaining()) { throw new GSSException(GSSException.DEFECTIVE_TOKEN); } ByteArrayInputStream byteArrayInputStream = null; try { /*DEL if (this.in.available() <= 0) { return null; } */ outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff); outByteBuff.flip(); if (!outByteBuff.hasRemaining()) break; byte[] certReq = new byte[outByteBuff.remaining()]; outByteBuff.get(certReq, 0, certReq.length); X509Certificate[] chain = this.ctxCred.getCertificateChain(); byteArrayInputStream = new ByteArrayInputStream(certReq); X509Certificate cert = this.certFactory.createCertificate(byteArrayInputStream, chain[0], this.ctxCred.getPrivateKey(), -1, /*DEL getDelegationType(chain[0])); */ BouncyCastleCertProcessingFactory.decideProxyType(chain[0], this.delegationType)); byte[] enc = cert.getEncoded(); /*DEL this.conn.getOutStream().write(enc, 0, enc.length); */ inByteBuff = ByteBuffer.wrap(enc, 0, enc.length); outByteBuff.clear(); outByteBuff = sslDataWrap(inByteBuff, outByteBuff); outByteBuff.flip(); setDone(); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } finally { if (byteArrayInputStream != null) { try { byteArrayInputStream.close(); } catch (Exception e) { logger.warn("Unable to close stream."); } } } break; default: throw new GSSException(GSSException.FAILURE); } if (inByteBuff.hasRemaining()) { // Likely BUFFER_UNDERFLOW; save the // inByteBuff bytes here like in the unwrap() case logger.debug("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining() + " Handshaking status: " + sslEngine.getHandshakeStatus()); logger.debug("SAVING unprocessed " + inByteBuff.remaining() + "BYTES\n"); savedInBytes = new byte[inByteBuff.remaining()]; inByteBuff.get(savedInBytes, 0, savedInBytes.length); } logger.debug("exit initSecContext"); //XXX: Why is here a check for CLIENT_START_DEL? // if (this.outByteBuff.hasRemaining() || this.state == CLIENT_START_DEL) { if (this.outByteBuff.hasRemaining()) { // TODO can we avoid this copy if the ByteBuffer is array based // and we return that array, each time allocating a new array // for outByteBuff? byte[] out = new byte[this.outByteBuff.remaining()]; this.outByteBuff.get(out, 0, out.length); return out; } else return null; }
From source file:com.sonicle.webtop.mail.Service.java
public static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException { final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024); while (src.read(buffer) != -1) { // prepare the buffer to be drained buffer.flip();/*from w ww.j a v a 2 s . com*/ // write to the channel, may block dest.write(buffer); // If partial transfer, shift remainder down // If buffer is empty, same as doing clear() buffer.compact(); } // EOF will leave buffer in fill state buffer.flip(); // make sure the buffer is fully drained. while (buffer.hasRemaining()) { dest.write(buffer); } }
From source file:edu.hawaii.soest.kilonalu.dvp2.DavisWxSource.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. */// ww w . j a v a 2s . c o m protected boolean execute() { logger.debug("DavisWxSource.execute() called."); // do not execute the stream if there is no connection if (!isConnected()) return false; boolean failed = false; // while data are being sent, read them into the buffer try { this.socketChannel = getSocketConnection(); // create four byte placeholders used to evaluate up to a four-byte // window. The FIFO layout looks like: // ------------------------- // in ---> | One | Two |Three|Four | ---> out // ------------------------- byte byteOne = 0x00, // set initial placeholder values byteTwo = 0x00, byteThree = 0x00, byteFour = 0x00; // Create a buffer that will store the sample bytes as they are read ByteBuffer sampleBuffer = ByteBuffer.allocate(getBufferSize()); // create a byte buffer to store bytes from the TCP stream ByteBuffer buffer = ByteBuffer.allocateDirect(getBufferSize()); // add a channel of data that will be pushed to the server. // Each sample will be sent to the Data Turbine as an rbnb frame. ChannelMap rbnbChannelMap = new ChannelMap(); int channelIndex = 0; // add the raw binary LOOP packet data //channelIndex = rbnbChannelMap.Add(getRBNBChannelName()); //rbnbChannelMap.PutUserInfo(channelIndex, "units=none"); // add the barTrendAsString field data channelIndex = rbnbChannelMap.Add("barTrendAsString"); // Falling Slowly rbnbChannelMap.PutUserInfo(channelIndex, "units=none"); // add the barometer field data channelIndex = rbnbChannelMap.Add("barometer"); // 29.9 rbnbChannelMap.PutUserInfo(channelIndex, "units=inch Hg"); // add the insideTemperature field data channelIndex = rbnbChannelMap.Add("insideTemperature"); // 83.9 rbnbChannelMap.PutUserInfo(channelIndex, "units=degrees F"); // add the insideHumidity field data channelIndex = rbnbChannelMap.Add("insideHumidity"); // 51 rbnbChannelMap.PutUserInfo(channelIndex, "units=percent"); // add the outsideTemperature field data channelIndex = rbnbChannelMap.Add("outsideTemperature"); // 76.7 rbnbChannelMap.PutUserInfo(channelIndex, "units=degrees F"); // add the windSpeed field data channelIndex = rbnbChannelMap.Add("windSpeed"); // 5 rbnbChannelMap.PutUserInfo(channelIndex, "units=mph"); // add the tenMinuteAverageWindSpeed field data channelIndex = rbnbChannelMap.Add("tenMinuteAverageWindSpeed"); // 4 rbnbChannelMap.PutUserInfo(channelIndex, "units=mph"); // add the windDirection field data channelIndex = rbnbChannelMap.Add("windDirection"); // 80 rbnbChannelMap.PutUserInfo(channelIndex, "units=degrees"); // add the outsideHumidity field data channelIndex = rbnbChannelMap.Add("outsideHumidity"); // 73 rbnbChannelMap.PutUserInfo(channelIndex, "units=percent"); // add the rainRate field data channelIndex = rbnbChannelMap.Add("rainRate"); // 0.0 rbnbChannelMap.PutUserInfo(channelIndex, "units=inch/hour"); // add the uvRadiation field data channelIndex = rbnbChannelMap.Add("uvRadiation"); // 0 rbnbChannelMap.PutUserInfo(channelIndex, "UV index"); // add the solarRadiation field data channelIndex = rbnbChannelMap.Add("solarRadiation"); // 0.0 rbnbChannelMap.PutUserInfo(channelIndex, "watt/m^2"); // add the stormRain field data channelIndex = rbnbChannelMap.Add("stormRain"); // 0.0 rbnbChannelMap.PutUserInfo(channelIndex, "inch"); // add the currentStormStartDate field data channelIndex = rbnbChannelMap.Add("currentStormStartDate"); // -1--1-1999 rbnbChannelMap.PutUserInfo(channelIndex, "units=none"); // add the dailyRain field data channelIndex = rbnbChannelMap.Add("dailyRain"); // 0.0 rbnbChannelMap.PutUserInfo(channelIndex, "units=inch"); // add the monthlyRain field data channelIndex = rbnbChannelMap.Add("monthlyRain"); // 0.0 rbnbChannelMap.PutUserInfo(channelIndex, "units=inch"); // add the yearlyRain field data channelIndex = rbnbChannelMap.Add("yearlyRain"); // 15.0 rbnbChannelMap.PutUserInfo(channelIndex, "units=inch"); // add the dailyEvapoTranspiration field data channelIndex = rbnbChannelMap.Add("dailyEvapoTranspiration"); // 0.0 rbnbChannelMap.PutUserInfo(channelIndex, "units=inch"); // add the monthlyEvapoTranspiration field data channelIndex = rbnbChannelMap.Add("monthlyEvapoTranspiration"); // 0.0 rbnbChannelMap.PutUserInfo(channelIndex, "units=inch"); // add the yearlyEvapoTranspiration field data channelIndex = rbnbChannelMap.Add("yearlyEvapoTranspiration"); // 93.0 rbnbChannelMap.PutUserInfo(channelIndex, "units=inch"); // add the transmitterBatteryStatus field data channelIndex = rbnbChannelMap.Add("transmitterBatteryStatus"); // 0 rbnbChannelMap.PutUserInfo(channelIndex, "units=none"); // add the consoleBatteryVoltage field data channelIndex = rbnbChannelMap.Add("consoleBatteryVoltage"); // 4.681640625 rbnbChannelMap.PutUserInfo(channelIndex, "units=volts"); // add the forecastAsString field data channelIndex = rbnbChannelMap.Add("forecastAsString"); // Partially Cloudy rbnbChannelMap.PutUserInfo(channelIndex, "units=none"); // add the forecastRuleNumberAsString field data //channelIndex = rbnbChannelMap.Add("forecastRuleNumberAsString"); // Increasing clouds with little temperature change. //rbnbChannelMap.PutUserInfo(channelIndex, "units=none"); // add the timeOfSunrise field data channelIndex = rbnbChannelMap.Add("timeOfSunrise"); // 05:49 rbnbChannelMap.PutUserInfo(channelIndex, "units=none"); // add the timeOfSunset field data channelIndex = rbnbChannelMap.Add("timeOfSunset"); // 19:11 rbnbChannelMap.PutUserInfo(channelIndex, "units=none"); channelIndex = rbnbChannelMap.Add("DecimalASCIISampleData"); // sample data as ASCII rbnbChannelMap.PutUserInfo(channelIndex, "units=none"); // register the channel map of variables and units with the DataTurbine getSource().Register(rbnbChannelMap); // reset variables for use with the incoming data rbnbChannelMap.Clear(); channelIndex = 0; // wake the instrument with an initial '\n' command this.command = this.commandSuffix; this.sentCommand = queryInstrument(this.command); // allow time for the instrument response streamingThread.sleep(2000); this.command = this.commandPrefix + this.takeSampleCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); // while there are bytes to read from the socket ... while (this.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" + // "sample pos: " + sampleBuffer.position() + "\t" + // "sample rem: " + sampleBuffer.remaining() + "\t" + // "sample cnt: " + sampleByteCount + "\t" + // "buffer pos: " + buffer.position() + "\t" + // "buffer rem: " + buffer.remaining() + "\t" + // "state: " + 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: // sample line is begun by "ACK L" (the first part of ACK + "LOOP") // note bytes are in reverse order in the FIFO window if (byteOne == 0x4C && byteTwo == 0x06) { sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } // we've found the beginning of a sample, move on state = 1; break; } else { break; } case 1: // read the rest of the bytes to the next EOL characters // sample line is terminated by "\n\r" // note bytes are in reverse order in the FIFO window if (byteOne == 0x0D && byteTwo == 0x0A) { sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } state = 3; break; } else { // not 0x0A0D // still in the middle of the sample, keep adding bytes sampleByteCount++; // add each byte found if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); logger.debug("Compacting sampleBuffer ..."); sampleBuffer.put(byteOne); } break; } // end if for 0x0A0D EOL case 3: // At this point, we've found the \n\r delimiter, read the first // of 2 CRC bytes sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } state = 4; break; case 4: // At this point, we've found the \n\r delimiter, read the second // of 2 CRC bytes sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } state = 0; // extract just the length of the sample bytes out of the // sample buffer, and place it in the channel map as a // byte array. Then, send it to the data turbine. byte[] sampleArray = new byte[sampleByteCount]; try { sampleBuffer.flip(); sampleBuffer.get(sampleArray); // parse and send the sample to the data turbine this.davisWxParser = new DavisWxParser(sampleBuffer); } catch (java.lang.Exception e) { logger.info( "There was a problem parsing the binary weather LOOP packet. Skipping this sample."); byteOne = 0x00; byteTwo = 0x00; byteThree = 0x00; byteFour = 0x00; sampleBuffer.clear(); sampleByteCount = 0; rbnbChannelMap.Clear(); break; } // create a character string to store characters from the TCP stream StringBuilder decimalASCIISampleData = new StringBuilder(); rbnbChannelMap.PutTimeAuto("server"); // add the raw binary LOOP packet data //channelIndex = rbnbChannelMap.Add(getRBNBChannelName()); //rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); //rbnbChannelMap.PutDataAsByteArray(channelIndex, sampleArray); // raw binary LOOP packet // add the barTrendAsString field data channelIndex = rbnbChannelMap.Add("barTrendAsString"); // Falling Slowly rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, davisWxParser.getBarTrendAsString()); decimalASCIISampleData.append( String.format("\"%16s\"", (Object) davisWxParser.getBarTrendAsString()) + ", "); // add the packetType field to the ASCII string only decimalASCIISampleData.append( String.format("%1d", (Object) new Integer(davisWxParser.getPacketType())) + ", "); // add the nextRecord field to the ASCII string only decimalASCIISampleData.append( String.format("%04d", (Object) new Integer(davisWxParser.getNextRecord())) + ", "); // add the barometer field data channelIndex = rbnbChannelMap.Add("barometer"); // 29.9 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getBarometer() }); decimalASCIISampleData.append( String.format("%06.4f", (Object) new Float(davisWxParser.getBarometer())) + ", "); // add the insideTemperature field data channelIndex = rbnbChannelMap.Add("insideTemperature"); // 83.9 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getInsideTemperature() }); decimalASCIISampleData.append( String.format("%05.2f", (Object) new Float(davisWxParser.getInsideTemperature())) + ", "); // add the insideHumidity field data channelIndex = rbnbChannelMap.Add("insideHumidity"); // 51 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { davisWxParser.getInsideHumidity() }); decimalASCIISampleData.append( String.format("%03d", (Object) new Integer(davisWxParser.getInsideHumidity())) + ", "); // add the outsideTemperature field data channelIndex = rbnbChannelMap.Add("outsideTemperature"); // 76.7 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getOutsideTemperature() }); decimalASCIISampleData.append( String.format("%05.2f", (Object) new Float(davisWxParser.getOutsideTemperature())) + ", "); // add the windSpeed field data channelIndex = rbnbChannelMap.Add("windSpeed"); // 5 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { davisWxParser.getWindSpeed() }); decimalASCIISampleData.append( String.format("%03d", (Object) new Integer(davisWxParser.getWindSpeed())) + ", "); // add the tenMinuteAverageWindSpeed field data channelIndex = rbnbChannelMap.Add("tenMinuteAverageWindSpeed"); // 4 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { davisWxParser.getTenMinuteAverageWindSpeed() }); decimalASCIISampleData.append(String.format("%03d", (Object) new Integer(davisWxParser.getTenMinuteAverageWindSpeed())) + ", "); // add the windDirection field data channelIndex = rbnbChannelMap.Add("windDirection"); // 80 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { davisWxParser.getWindDirection() }); decimalASCIISampleData.append( String.format("%03d", (Object) new Integer(davisWxParser.getWindDirection())) + ", "); // add the extraTemperature fields as ASCII only float[] extraTemperatures = davisWxParser.getExtraTemperatures(); for (float temperature : extraTemperatures) { decimalASCIISampleData .append(String.format("%05.2f", (Object) new Float(temperature)) + ", "); } // add the soilTemperature fields as ASCII only float[] soilTemperatures = davisWxParser.getSoilTemperatures(); for (float soil : soilTemperatures) { decimalASCIISampleData.append(String.format("%05.2f", (Object) new Float(soil)) + ", "); } // add the leafTemperature fields as ASCII only float[] leafTemperatures = davisWxParser.getLeafTemperatures(); for (float leaf : leafTemperatures) { decimalASCIISampleData.append(String.format("%05.2f", (Object) new Float(leaf)) + ", "); } // add the outsideHumidity field data channelIndex = rbnbChannelMap.Add("outsideHumidity"); // 73 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { davisWxParser.getOutsideHumidity() }); decimalASCIISampleData.append( String.format("%03d", (Object) new Integer(davisWxParser.getOutsideHumidity())) + ", "); // add the rainRate field data channelIndex = rbnbChannelMap.Add("rainRate"); // 0.0 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getRainRate() }); decimalASCIISampleData.append( String.format("%04.2f", (Object) new Float(davisWxParser.getRainRate())) + ", "); // add the uvRadiation field data channelIndex = rbnbChannelMap.Add("uvRadiation"); // 0 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { davisWxParser.getUvRadiation() }); decimalASCIISampleData.append( String.format("%03d", (Object) new Integer(davisWxParser.getUvRadiation())) + ", "); // add the solarRadiation field data channelIndex = rbnbChannelMap.Add("solarRadiation"); // 0.0 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getSolarRadiation() }); decimalASCIISampleData.append( String.format("%04.1f", (Object) new Float(davisWxParser.getSolarRadiation())) + ", "); // add the stormRain field data channelIndex = rbnbChannelMap.Add("stormRain"); // 0.0 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getStormRain() }); decimalASCIISampleData.append( String.format("%04.2f", (Object) new Float(davisWxParser.getStormRain())) + ", "); // add the currentStormStartDate field data channelIndex = rbnbChannelMap.Add("currentStormStartDate"); // -1--1-1999 rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, davisWxParser.getCurrentStormStartDate()); decimalASCIISampleData.append( String.format("%10s", (Object) davisWxParser.getCurrentStormStartDate()) + ", "); // add the dailyRain field data channelIndex = rbnbChannelMap.Add("dailyRain"); // 0.0 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getDailyRain() }); decimalASCIISampleData.append( String.format("%04.2f", (Object) new Float(davisWxParser.getDailyRain())) + ", "); // add the monthlyRain field data channelIndex = rbnbChannelMap.Add("monthlyRain"); // 0.0 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getMonthlyRain() }); decimalASCIISampleData.append( String.format("%04.2f", (Object) new Float(davisWxParser.getMonthlyRain())) + ", "); // add the yearlyRain field data channelIndex = rbnbChannelMap.Add("yearlyRain"); // 15.0 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getYearlyRain() }); decimalASCIISampleData.append( String.format("%04.2f", (Object) new Float(davisWxParser.getYearlyRain())) + ", "); // add the dailyEvapoTranspiration field data channelIndex = rbnbChannelMap.Add("dailyEvapoTranspiration"); // 0.0 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getDailyEvapoTranspiration() }); decimalASCIISampleData.append(String.format("%04.2f", (Object) new Float(davisWxParser.getDailyEvapoTranspiration())) + ", "); // add the monthlyEvapoTranspiration field data channelIndex = rbnbChannelMap.Add("monthlyEvapoTranspiration"); // 0.0 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getMonthlyEvapoTranspiration() }); decimalASCIISampleData.append(String.format("%04.2f", (Object) new Float(davisWxParser.getMonthlyEvapoTranspiration())) + ", "); // add the yearlyEvapoTranspiration field data channelIndex = rbnbChannelMap.Add("yearlyEvapoTranspiration"); // 93.0 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getYearlyEvapoTranspiration() }); decimalASCIISampleData.append(String.format("%04.2f", (Object) new Float(davisWxParser.getYearlyEvapoTranspiration())) + ", "); // add the consoleBatteryVoltage field data channelIndex = rbnbChannelMap.Add("consoleBatteryVoltage"); // 4.681640625 rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat32(channelIndex, new float[] { davisWxParser.getConsoleBatteryVoltage() }); decimalASCIISampleData.append(String.format("%04.2f", (Object) new Float(davisWxParser.getConsoleBatteryVoltage())) + ", "); // add the forecastAsString field data channelIndex = rbnbChannelMap.Add("forecastAsString"); // Partially Cloudy rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, davisWxParser.getForecastAsString()); decimalASCIISampleData.append( String.format("\"%47s\"", (Object) davisWxParser.getForecastAsString()) + ", "); // add the forecastRuleNumberAsString field data as ASCII only decimalASCIISampleData.append( String.format("\"%167s\"", (Object) davisWxParser.getForecastRuleNumberAsString()) + ", "); // add the timeOfSunrise field data channelIndex = rbnbChannelMap.Add("timeOfSunrise"); // 05:49 rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, davisWxParser.getTimeOfSunrise()); decimalASCIISampleData .append(String.format("%5s", (Object) davisWxParser.getTimeOfSunrise()) + ", "); // add the timeOfSunset field data channelIndex = rbnbChannelMap.Add("timeOfSunset"); // 19:11 rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, davisWxParser.getTimeOfSunset()); decimalASCIISampleData .append(String.format("%5s", (Object) davisWxParser.getTimeOfSunset()) + ", "); // then add a timestamp to the end of the sample DATE_FORMAT.setTimeZone(TZ); String sampleDateAsString = DATE_FORMAT.format(new Date()).toString(); decimalASCIISampleData.append(sampleDateAsString); decimalASCIISampleData.append("\n"); // add the ASCII CSV string of selected fields as a channel channelIndex = rbnbChannelMap.Add(getRBNBChannelName()); // 19:11 rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, decimalASCIISampleData.toString()); // finally, send the channel map of data to the DataTurbine getSource().Flush(rbnbChannelMap); String sampleString = new String(Hex.encodeHex(sampleArray)); logger.info("Sample: " + sampleString); logger.debug("barTrendAsString: " + davisWxParser.getBarTrendAsString()); logger.debug("barometer: " + davisWxParser.getBarometer()); logger.debug("insideTemperature: " + davisWxParser.getInsideTemperature()); logger.debug("insideHumidity: " + davisWxParser.getInsideHumidity()); logger.debug("outsideTemperature: " + davisWxParser.getOutsideTemperature()); logger.debug("windSpeed: " + davisWxParser.getWindSpeed()); logger.debug( "tenMinuteAverageWindSpeed: " + davisWxParser.getTenMinuteAverageWindSpeed()); logger.debug("windDirection: " + davisWxParser.getWindDirection()); logger.debug("outsideHumidity: " + davisWxParser.getOutsideHumidity()); logger.debug("rainRate: " + davisWxParser.getRainRate()); logger.debug("uvRadiation: " + davisWxParser.getUvRadiation()); logger.debug("solarRadiation: " + davisWxParser.getSolarRadiation()); logger.debug("stormRain: " + davisWxParser.getStormRain()); logger.debug("currentStormStartDate: " + davisWxParser.getCurrentStormStartDate()); logger.debug("dailyRain: " + davisWxParser.getDailyRain()); logger.debug("monthlyRain: " + davisWxParser.getMonthlyRain()); logger.debug("yearlyRain: " + davisWxParser.getYearlyRain()); logger.debug( "dailyEvapoTranspiration: " + davisWxParser.getDailyEvapoTranspiration()); logger.debug( "monthlyEvapoTranspiration: " + davisWxParser.getMonthlyEvapoTranspiration()); logger.debug( "yearlyEvapoTranspiration: " + davisWxParser.getYearlyEvapoTranspiration()); logger.debug("transmitterBatteryStatus: " + Arrays.toString(davisWxParser.getTransmitterBatteryStatus())); logger.debug("consoleBatteryVoltage: " + davisWxParser.getConsoleBatteryVoltage()); logger.debug("forecastAsString: " + davisWxParser.getForecastAsString()); //logger.debug("forecastRuleNumberAsString: " + davisWxParser.getForecastRuleNumberAsString()); logger.debug("timeOfSunrise: " + davisWxParser.getTimeOfSunrise()); logger.debug("timeOfSunset: " + davisWxParser.getTimeOfSunset()); logger.info(" flushed data to the DataTurbine. "); byteOne = 0x00; byteTwo = 0x00; byteThree = 0x00; byteFour = 0x00; sampleBuffer.clear(); sampleByteCount = 0; rbnbChannelMap.Clear(); //logger.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap."); //state = 0; // Once the sample is flushed, take a new sample // allow time for the instrument response streamingThread.sleep(2000); this.command = this.commandPrefix + this.takeSampleCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); } // 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 socket bytes to read) this.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 (SAPIException sapie) { // In the event of an RBNB communication exception, log the exception, // and allow execute() to return false, which will prompt a retry. failed = true; sapie.printStackTrace(); return !failed; } catch (java.lang.InterruptedException ine) { failed = true; ine.printStackTrace(); return !failed; } return !failed; }
From source file:org.apache.geode.internal.cache.Oplog.java
private void flush(OplogFile olf, boolean doSync) throws IOException { try {/*w ww . ja v a 2 s . c om*/ // No need to get the backup lock prior to synchronizing (correct lock order) since the // synchronized block does not attempt to get the backup lock (incorrect lock order) synchronized (this.lock/* olf */) { if (olf.RAFClosed) { return; } ByteBuffer bb = olf.writeBuf; if (bb != null && bb.position() != 0) { bb.flip(); int flushed = 0; int numChannelRetries = 0; do { int channelBytesWritten = 0; final int bbStartPos = bb.position(); final long channelStartPos = olf.channel.position(); // differentiate between bytes written on this channel.write() iteration and the // total number of bytes written to the channel on this call channelBytesWritten = olf.channel.write(bb); // Expect channelBytesWritten and the changes in pp.position() and channel.position() to // be the same. If they are not, then the channel.write() silently failed. The following // retry separates spurious failures from permanent channel failures. if (channelBytesWritten != bb.position() - bbStartPos) { if (numChannelRetries++ < MAX_CHANNEL_RETRIES) { // Reset the ByteBuffer position, but take into account anything that did get // written to the channel channelBytesWritten = (int) (olf.channel.position() - channelStartPos); bb.position(bbStartPos + channelBytesWritten); } else { throw new IOException("Failed to write Oplog entry to" + olf.f.getName() + ": " + "channel.write() returned " + channelBytesWritten + ", " + "change in channel position = " + (olf.channel.position() - channelStartPos) + ", " + "change in source buffer position = " + (bb.position() - bbStartPos)); } } flushed += channelBytesWritten; } while (bb.hasRemaining()); // update bytesFlushed after entire writeBuffer is flushed to fix bug // 41201 olf.bytesFlushed += flushed; bb.clear(); } if (doSync) { if (SYNC_WRITES) { // Synch Meta Data as well as content olf.channel.force(true); } } } } catch (ClosedChannelException ignore) { // It is possible for a channel to be closed when our code does not // explicitly call channel.close (when we will set RAFclosed). // This can happen when a thread is doing an io op and is interrupted. // That thread will see ClosedByInterruptException but it will also // close the channel and then we will see ClosedChannelException. } }
From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java
/** * This function drives the accepting side of the context establishment * process. It is expected to be called in tandem with the * {@link #initSecContext(byte[], int, int) initSecContext} function. * <BR>/*from w w w . java2 s .c om*/ * The behavior of context establishment process can be modified by * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * and {@link GSSConstants#REJECT_LIMITED_PROXY * GSSConstants.REJECT_LIMITED_PROXY} context options. If the * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * option is set to * {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL} * the context establishment process will be compatible with regular SSL * (no credential delegation support). If the option is set to * {@link GSIConstants#MODE_GSI GSIConstants.MODE_GSI} * credential delegation during context establishment process will be accepted. * If the {@link GSSConstants#REJECT_LIMITED_PROXY * GSSConstants.REJECT_LIMITED_PROXY} option is enabled, a peer * presenting limited proxy credential will be automatically * rejected and the context establishment process will be aborted. * * @return a byte[] containing the token to be sent to the peer. * null indicates that no token is generated (needs more data) */ public byte[] acceptSecContext(byte[] inBuff, int off, int len) throws GSSException { logger.debug("enter acceptSecContext"); if (!this.conn) { this.role = ACCEPT; logger.debug("enter initializing in acceptSecContext"); if (this.ctxCred.getName().isAnonymous()) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN, "acceptCtx00"); } if (this.ctxCred.getUsage() != GSSCredential.ACCEPT_ONLY && this.ctxCred.getUsage() != GSSCredential.INITIATE_AND_ACCEPT) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN, "badCredUsage"); } setCredential(); try { init(this.role); } catch (SSLException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.conn = true; logger.debug("done initializing in acceptSecContext"); } /*DEL this.out.reset(); this.in.putToken(inBuff, off, len); */ this.outByteBuff.clear(); ByteBuffer inByteBuff; if (savedInBytes != null) { if (len > 0) { byte[] allInBytes = new byte[savedInBytes.length + len]; logger.debug("ALLOCATED for allInBytes " + savedInBytes.length + " + " + len + " bytes\n"); System.arraycopy(savedInBytes, 0, allInBytes, 0, savedInBytes.length); System.arraycopy(inBuff, off, allInBytes, savedInBytes.length, len); inByteBuff = ByteBuffer.wrap(allInBytes, 0, allInBytes.length); } else { inByteBuff = ByteBuffer.wrap(savedInBytes, 0, savedInBytes.length); } savedInBytes = null; } else { inByteBuff = ByteBuffer.wrap(inBuff, off, len); } switch (state) { case HANDSHAKE: try { logger.debug("STATUS BEFORE: " + this.sslEngine.getHandshakeStatus().toString()); SSLEngineResult.HandshakeStatus handshake_status = sslEngine.getHandshakeStatus(); if (handshake_status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // return null; throw new Exception("GSSAPI in HANDSHAKE state but " + "SSLEngine in NOT_HANDSHAKING state!"); } else { outByteBuff = this.sslProcessHandshake(inByteBuff, outByteBuff); } logger.debug("STATUS AFTER: " + this.sslEngine.getHandshakeStatus().toString()); outByteBuff.flip(); /*DEL if (this.conn.getHandshake().finishedP()) { */ if (this.sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // the wrap/unwrap above has resulted in handshaking // being complete on our end. logger.debug("acceptSecContext handshake finished"); handshakeFinished(); // acceptor for (X509Certificate cert : this.ctxCred.getCertificateChain()) { setGoodUntil(cert.getNotAfter()); } this.targetName = this.ctxCred.getName(); // initiator - peer /*DEL Vector chain = this.conn.getCertificateChain(); */ Certificate[] chain; try { chain = this.sslEngine.getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { chain = null; } if (chain == null || chain.length == 0) { this.sourceName = new GlobusGSSName(); this.anonymity = true; } else { /*DEL X509Cert crt = (X509Cert)chain.elementAt(chain.size()-1); setGoodUntil(crt.getValidityNotAfter()); String identity = verifyChain(chain); */ for (X509Certificate cert : (X509Certificate[]) chain) { setGoodUntil(cert.getNotAfter()); } String identity = BouncyCastleUtil.getIdentity( bcConvert(BouncyCastleUtil.getIdentityCertificate((X509Certificate[]) chain))); this.sourceName = new GlobusGSSName(CertificateUtil.toGlobusID(identity, false)); this.peerLimited = Boolean.valueOf(ProxyCertificateUtil .isLimitedProxy(BouncyCastleUtil.getCertificateType((X509Certificate) chain[0]))); logger.debug("Peer Identity is: " + identity + " Target name is: " + this.targetName + " Limited Proxy: " + this.peerLimited.toString()); this.anonymity = false; } if (this.gssMode == GSIConstants.MODE_GSI) { this.state = SERVER_START_DEL; } else { setDone(); } } } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } break; case SERVER_START_DEL: try { if (inByteBuff.remaining() <= 0) { return null; } /*DEL int delChar = this.conn.getInStream().read(); */ outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff); outByteBuff.flip(); byte[] delChar = new byte[outByteBuff.remaining()]; outByteBuff.get(delChar, 0, delChar.length); /*DEL if (delChar != GSIConstants.DELEGATION_CHAR) { */ if (!Arrays.equals(delChar, DELEGATION_TOKEN)) { setDone(); break; } /*DEL Vector chain = this.conn.getCertificateChain(); */ Certificate[] chain; try { chain = this.sslEngine.getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { chain = null; } if (chain == null || chain.length == 0) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.DELEGATION_ERROR, "noClientCert"); } X509Certificate tmpCert = (X509Certificate) chain[0]; /*DEL PureTLSUtil.convertCert((X509Cert)chain.lastElement()); */ byte[] req = generateCertRequest(tmpCert); /*DEL this.conn.getOutStream().write(req, 0, req.length); */ inByteBuff = ByteBuffer.wrap(req, 0, req.length); outByteBuff.clear(); outByteBuff = sslDataWrap(inByteBuff, outByteBuff); outByteBuff.flip(); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.state = SERVER_END_DEL; break; case SERVER_END_DEL: try { if (inByteBuff.remaining() <= 0) { return null; } /*DEL X509Certificate certificate = CertUtil.loadCertificate(this.conn.getInStream()); */ outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff); outByteBuff.flip(); if (!outByteBuff.hasRemaining()) break; byte[] buf = new byte[outByteBuff.remaining()]; outByteBuff.get(buf, 0, buf.length); ByteArrayInputStream inStream = new ByteArrayInputStream(buf, 0, buf.length); CertificateFactory cf = null; X509Certificate certificate = null; try { cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate(inStream); } finally { inStream.close(); } if (logger.isTraceEnabled()) { logger.trace("Received delegated cert: " + certificate.toString()); } verifyDelegatedCert(certificate); /*DEL Vector chain = this.conn.getCertificateChain(); */ Certificate[] chain = this.sslEngine.getSession().getPeerCertificates(); int chainLen = chain.length; X509Certificate[] newChain = new X509Certificate[chainLen + 1]; newChain[0] = bcConvert((X509Certificate) certificate); for (int i = 0; i < chainLen; i++) { /*DEL newChain[i+1] = PureTLSUtil.convertCert((X509Cert)chain.elementAt(chainLen - 1 - i)); */ newChain[i + 1] = bcConvert((X509Certificate) chain[i]); } X509Credential proxy = new X509Credential(this.keyPair.getPrivate(), newChain); this.delegCred = new GlobusGSSCredentialImpl(proxy, GSSCredential.INITIATE_AND_ACCEPT); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } setDone(); break; default: throw new GSSException(GSSException.FAILURE); } if (inByteBuff.hasRemaining()) { // Likely BUFFER_UNDERFLOW; save the // inByteBuff bytes here like in the unwrap() case logger.debug("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining() + " Handshaking status: " + sslEngine.getHandshakeStatus()); logger.debug("SAVING unprocessed " + inByteBuff.remaining() + "BYTES\n"); savedInBytes = new byte[inByteBuff.remaining()]; inByteBuff.get(savedInBytes, 0, savedInBytes.length); } logger.debug("exit acceptSecContext"); /*DEL return (this.out.size() > 0) ? this.out.toByteArray() : null; */ if (this.outByteBuff.hasRemaining()) { // TODO can we avoid this copy if the ByteBuffer is array based // and we return that array, each time allocating a new array // for outByteBuff? byte[] out = new byte[this.outByteBuff.remaining()]; this.outByteBuff.get(out, 0, out.length); return out; } else return null; }