private void initSender() { aa(this, sockType == SocketType.SENDER, ""); sendWindow = 3 * Transport.MAX_PAYLOAD_SIZE; sendBase = 0; seqNum = 0; sendbb = ByteBuffer.allocate(SEND_BUFFER_SIZE); }
public static void main(String args[]) { try { aServer asr = new aServer(); // file channel. FileInputStream is = new FileInputStream(""); is.read(); FileChannel cha = is.getChannel(); ByteBuffer bf = ByteBuffer.allocate(1024); bf.flip(); cha.read(bf); // Path Paths Path pth = Paths.get("", ""); // Files some static operation. Files.newByteChannel(pth); Files.copy(pth, pth); // file attribute, other different class for dos and posix system. BasicFileAttributes bas = Files.readAttributes(pth, BasicFileAttributes.class); bas.size(); } catch (Exception e) { System.err.println(e); } System.out.println("hello "); }
void isReadable(SelectionKey k) { EventableChannel ec = (EventableChannel) k.attachment(); long b = ec.getBinding(); if (ec.isWatchOnly()) { if (ec.isNotifyReadable()) eventCallback(b, EM_CONNECTION_NOTIFY_READABLE, null); } else { myReadBuffer.clear(); try { ec.readInboundData(myReadBuffer); myReadBuffer.flip(); if (myReadBuffer.limit() > 0) { if (ProxyConnections != null) { EventableChannel target = ProxyConnections.get(b); if (target != null) { ByteBuffer myWriteBuffer = ByteBuffer.allocate(myReadBuffer.limit()); myWriteBuffer.put(myReadBuffer); myWriteBuffer.flip(); target.scheduleOutboundData(myWriteBuffer); } else { eventCallback(b, EM_CONNECTION_READ, myReadBuffer); } } else { eventCallback(b, EM_CONNECTION_READ, myReadBuffer); } } } catch (IOException e) { UnboundConnections.add(b); } } }
static boolean check(CharsetDecoder dec, byte[] bytes, boolean direct, int[] flow) { int inPos = flow[0]; int inLen = flow[1]; int outPos = flow[2]; int outLen = flow[3]; int expedInPos = flow[4]; int expedOutPos = flow[5]; CoderResult expedCR = (flow[6] == 0) ? CoderResult.UNDERFLOW : CoderResult.OVERFLOW; ByteBuffer bbf; CharBuffer cbf; if (direct) { bbf = ByteBuffer.allocateDirect(inPos + bytes.length); cbf = ByteBuffer.allocateDirect((outPos + outLen) * 2).asCharBuffer(); } else { bbf = ByteBuffer.allocate(inPos + bytes.length); cbf = CharBuffer.allocate(outPos + outLen); } bbf.position(inPos); bbf.put(bytes).flip().position(inPos).limit(inPos + inLen); cbf.position(outPos); dec.reset(); CoderResult cr = dec.decode(bbf, cbf, false); if (cr != expedCR || bbf.position() != expedInPos || cbf.position() != expedOutPos) { System.out.printf("Expected(direct=%5b): [", direct); for (int i : flow) System.out.print(" " + i); System.out.println( "] CR=" + cr + ", inPos=" + bbf.position() + ", outPos=" + cbf.position()); return false; } return true; }
static byte[] encode(char[] cc, Charset cs, boolean testDirect, Time t) throws Exception { ByteBuffer bbf; CharBuffer cbf; CharsetEncoder enc = cs.newEncoder(); String csn = cs.name(); if (testDirect) { bbf = ByteBuffer.allocateDirect(cc.length * 4); cbf = ByteBuffer.allocateDirect(cc.length * 2).asCharBuffer(); cbf.put(cc).flip(); } else { bbf = ByteBuffer.allocate(cc.length * 4); cbf = CharBuffer.wrap(cc); } CoderResult cr = null; long t1 = System.nanoTime() / 1000; for (int i = 0; i < iteration; i++) { cbf.rewind(); bbf.clear(); enc.reset(); cr = enc.encode(cbf, bbf, true); } long t2 = System.nanoTime() / 1000; t.t = (t2 - t1) / iteration; if (cr != CoderResult.UNDERFLOW) { System.out.println("ENC-----------------"); int pos = cbf.position(); System.out.printf(" cr=%s, cbf.pos=%d, cc[pos]=%x%n", cr.toString(), pos, cc[pos] & 0xffff); throw new RuntimeException("Encoding err: " + csn); } byte[] bb = new byte[bbf.position()]; bbf.flip(); bbf.get(bb); return bb; }
public static void runTests() { try { // SHA1 sha1Jmule = new SHA1(); MessageDigest sha1Sun = MessageDigest.getInstance("SHA-1"); SHA1 sha1Gudy = new SHA1(); // SHA1Az shaGudyResume = new SHA1Az(); ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024); File dir = new File(dirname); File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { FileChannel fc = new RandomAccessFile(files[i], "r").getChannel(); System.out.println("Testing " + files[i].getName() + " ..."); while (fc.position() < fc.size()) { fc.read(buffer); buffer.flip(); byte[] raw = new byte[buffer.limit()]; System.arraycopy(buffer.array(), 0, raw, 0, raw.length); sha1Gudy.update(buffer); sha1Gudy.saveState(); ByteBuffer bb = ByteBuffer.wrap(new byte[56081]); sha1Gudy.digest(bb); sha1Gudy.restoreState(); sha1Sun.update(raw); buffer.clear(); } byte[] sun = sha1Sun.digest(); sha1Sun.reset(); byte[] gudy = sha1Gudy.digest(); sha1Gudy.reset(); if (Arrays.equals(sun, gudy)) { System.out.println(" SHA1-Gudy: OK"); } else { System.out.println(" SHA1-Gudy: FAILED"); } buffer.clear(); fc.close(); System.out.println(); } } catch (Throwable e) { Debug.printStackTrace(e); } }
public static byte[] getNBOPort(short p) { ByteBuffer buf = ByteBuffer.allocate(2); buf.putShort((short) p); buf.order(ByteOrder.BIG_ENDIAN); buf.rewind(); byte[] rtn = new byte[2]; buf.get(rtn); return rtn; }
private void init() throws IOException { messageBuffer = new ArrayList(); receiveBuffer = ByteBuffer.allocate(CAPACITY); sendBuffer = ByteBuffer.allocate(CAPACITY); buf = new byte[CAPACITY]; channel = DatagramChannel.open(); channel.configureBlocking(false); InetAddress host = null; if (getAddress() != null) { host = InetAddress.getByAddress(getAddress().getBytes()); } channel.socket().bind(new InetSocketAddress(host, getPort())); channel.socket().setReceiveBufferSize(CAPACITY); certifier = new MessageCertifier(this); extractor = new MessageExtractor(this); }
public static byte[] getNBOHost(String h) { if (h.equals(PEER)) return null; byte hostBytes[] = h.getBytes(); int len = Array.getLength(hostBytes); ByteBuffer buf = ByteBuffer.allocate(len); buf.put(hostBytes); buf.order(ByteOrder.BIG_ENDIAN); buf.rewind(); return (buf.array()); }
// creates the header and pads the content returning a new byte[] // in the proper format. The secret is 4bytes (int), the step // is 2 bytes (short). public static byte[] createBuffer(byte[] content, int secret, short step) { short studentNum = 456; // my student number is 1340456 int paddedSize = content.length; while (paddedSize % 4 != 0) { paddedSize++; } ByteBuffer bb = ByteBuffer.allocate(HEADER_SIZE + paddedSize); bb.putInt(content.length); bb.putInt(secret); bb.putShort(step); bb.putShort(studentNum); bb.put(content); return bb.array(); }
public EmReactor() { Timers = new TreeMap<Long, ArrayList<Long>>(); Connections = new HashMap<Long, EventableChannel>(); Acceptors = new HashMap<Long, ServerSocketChannel>(); NewConnections = new ArrayList<Long>(); UnboundConnections = new ArrayList<Long>(); DetachedConnections = new ArrayList<EventableSocketChannel>(); BindingIndex = 0; loopBreaker = new AtomicBoolean(); loopBreaker.set(false); myReadBuffer = ByteBuffer.allocate( 32 * 1024); // don't use a direct buffer. Ruby doesn't seem to like them. timerQuantum = 98; }
public final byte[] serialize() { final byte[] cdata = StringUtils.toUTF8(this.m_criterion); final int presize = cdata.length; final ByteBuffer bb = ByteBuffer.allocate(32 + presize); bb.putInt(this.m_id); bb.put(this.m_order); bb.putInt(this.m_gfx); bb.putInt(cdata.length); bb.put(cdata); bb.put((byte) (this.m_success ? 1 : 0)); bb.putInt(this.m_itemId); bb.putShort(this.m_itemQty); bb.putInt(this.m_xp); bb.putInt(this.m_kama); bb.putInt(this.m_guildPoints); return bb.array(); }
@FXML private void Ok_click(ActionEvent event) { logger.entry(); LogEntry log = new LogEntry("6.16", "Local Delete Object Instance service"); try { ObjectInstanceHandle instanceHandle = rtiAmb .getObjectInstanceHandleFactory() .decode( ByteBuffer.allocate(4) .putInt(Integer.parseInt(ObjectInstanceDesignator.getText())) .array(), 0); log.getSuppliedArguments() .add( new ClassValuePair( "Object instance designator", ObjectInstanceHandle.class, instanceHandle.toString())); rtiAmb.localDeleteObjectInstance(instanceHandle); log.setDescription("Local Object instance deleted successfully"); log.setLogType(LogEntryType.REQUEST); } catch (FederateNotExecutionMember | NotConnected | NumberFormatException | CouldNotDecode | RTIinternalError | OwnershipAcquisitionPending | FederateOwnsAttributes | ObjectInstanceNotKnown | SaveInProgress | RestoreInProgress ex) { log.setException(ex); log.setLogType(LogEntryType.ERROR); logger.log(Level.ERROR, ex.getMessage(), ex); } catch (Exception ex) { log.setException(ex); log.setLogType(LogEntryType.FATAL); logger.log(Level.FATAL, ex.getMessage(), ex); } logEntries.add(log); ((Stage) OkButton.getScene().getWindow()).close(); logger.exit(); }
static CoderResult encodeCR(char[] cc, Charset cs, boolean testDirect) throws Exception { ByteBuffer bbf; CharBuffer cbf; CharsetEncoder enc = cs.newEncoder(); if (testDirect) { bbf = ByteBuffer.allocateDirect(cc.length * 4); cbf = ByteBuffer.allocateDirect(cc.length * 2).asCharBuffer(); cbf.put(cc).flip(); } else { bbf = ByteBuffer.allocate(cc.length * 4); cbf = CharBuffer.wrap(cc); } CoderResult cr = null; for (int i = 0; i < iteration; i++) { cbf.rewind(); bbf.clear(); enc.reset(); cr = enc.encode(cbf, bbf, true); } return cr; }
public final byte[] serialize() { ByteBuffer bb = null; try { final byte[] targetPosition = (this.m_targetPosition == null) ? new byte[0] : this.m_targetPosition.getBytes("UTF-8"); final byte[] jaugeVarName = (this.m_jaugeVarName == null) ? new byte[0] : this.m_jaugeVarName.getBytes("UTF-8"); bb = ByteBuffer.allocate(9 + targetPosition.length + 4 + 1 + 4 + jaugeVarName.length); bb.putInt(this.m_id); bb.put((byte) (this.m_isChallengeGoal ? 1 : 0)); bb.putInt(targetPosition.length); bb.put(targetPosition); bb.put((byte) (this.m_isCountDownJauge ? 1 : 0)); bb.putInt(this.m_jaugeMaxValue); bb.putInt(jaugeVarName.length); bb.put(jaugeVarName); } catch (UnsupportedEncodingException e) { ScenarioBinaryStorable.m_logger.error((Object) "Exception", (Throwable) e); } return bb.array(); }
/** * Decode file charset. * * @param f File to process. * @return File charset. * @throws IOException in case of error. */ public static Charset decode(File f) throws IOException { SortedMap<String, Charset> charsets = Charset.availableCharsets(); String[] firstCharsets = { Charset.defaultCharset().name(), "US-ASCII", "UTF-8", "UTF-16BE", "UTF-16LE" }; Collection<Charset> orderedCharsets = U.newLinkedHashSet(charsets.size()); for (String c : firstCharsets) if (charsets.containsKey(c)) orderedCharsets.add(charsets.get(c)); orderedCharsets.addAll(charsets.values()); try (RandomAccessFile raf = new RandomAccessFile(f, "r")) { FileChannel ch = raf.getChannel(); ByteBuffer buf = ByteBuffer.allocate(4096); ch.read(buf); buf.flip(); for (Charset charset : orderedCharsets) { CharsetDecoder decoder = charset.newDecoder(); decoder.reset(); try { decoder.decode(buf); return charset; } catch (CharacterCodingException ignored) { } } } return Charset.defaultCharset(); }
/** {@inheritDoc} */ @Override public ByteBuffer encode(GridNioSession ses, GridClientMessage msg) throws IOException, GridException { assert msg != null; if (msg instanceof GridTcpRestPacket) return encodeMemcache((GridTcpRestPacket) msg); else if (msg == PING_MESSAGE) return ByteBuffer.wrap(PING_PACKET); else { byte[] data = marshaller.marshal(msg); assert data.length > 0; ByteBuffer res = ByteBuffer.allocate(data.length + 5); res.put(GRIDGAIN_REQ_FLAG); res.put(U.intToBytes(data.length)); res.put(data); res.flip(); return res; } }
@Override public byte[] getBinaryData() { final ArrayList<byte[]> binGroups = new ArrayList<byte[]>(this.m_actionGroups.size()); final ArrayList<byte[]> binRewars = new ArrayList<byte[]>(this.m_rewards.size()); int presize = 0; presize += 4; try { for (final String var : this.m_varMapping) { presize += 4 + var.getBytes("UTF-8").length; } } catch (Exception e) { ScenarioBinaryStorable.m_logger.error((Object) "Exception", (Throwable) e); } try { presize += 8; presize += ((this.m_joinCriterion != null) ? this.m_joinCriterion.getBytes("UTF-8").length : 0); presize += ((this.m_rewardEligibilityCriterion != null) ? this.m_rewardEligibilityCriterion.getBytes("UTF-8").length : 0); } catch (Exception e) { ScenarioBinaryStorable.m_logger.error((Object) "Exception", (Throwable) e); } for (final ActionGroupStorable g : this.m_actionGroups) { final byte[] bin = g.serialize(); presize += bin.length + 4; binGroups.add(bin); } for (final RewardStorable r : this.m_rewards) { final byte[] bin = r.serialize(); presize += bin.length + 4; binRewars.add(bin); } try { presize += 4; presize += ((this.m_params != null) ? this.m_params.getBytes("UTF-8").length : 0); } catch (Exception e) { ScenarioBinaryStorable.m_logger.error((Object) "Exception", (Throwable) e); } final ByteBuffer bb = ByteBuffer.allocate(31 + presize); bb.putInt(this.m_id); bb.put(this.m_type); bb.put(this.m_userType); bb.put((byte) (this.m_autoTrigger ? 1 : 0)); bb.put((byte) (this.m_isChallenge ? 1 : 0)); bb.put((byte) (this.m_isChaos ? 1 : 0)); bb.putShort(this.m_duration); bb.putShort(this.m_minUsers); bb.putShort(this.m_maxUsers); if (this.m_expirationDate != null) { bb.putLong(this.m_expirationDate.toLong()); } else { bb.putLong(0L); } try { if (this.m_params != null) { final byte[] bytes = this.m_params.getBytes("UTF-8"); bb.putInt(bytes.length); bb.put(bytes); } else { bb.putInt(0); } } catch (Exception e2) { ScenarioBinaryStorable.m_logger.error((Object) "Exception", (Throwable) e2); } try { bb.putInt(this.m_varMapping.length); for (final String var2 : this.m_varMapping) { final byte[] bytes2 = var2.getBytes("UTF-8"); bb.putInt(bytes2.length); bb.put(bytes2); } } catch (Exception e2) { ScenarioBinaryStorable.m_logger.error((Object) "Exception", (Throwable) e2); } try { if (this.m_joinCriterion != null) { final byte[] bytes = this.m_joinCriterion.getBytes("UTF-8"); bb.putInt(bytes.length); bb.put(bytes); } else { bb.putInt(0); } if (this.m_rewardEligibilityCriterion != null) { final byte[] bytes = this.m_rewardEligibilityCriterion.getBytes("UTF-8"); bb.putInt(bytes.length); bb.put(bytes); } else { bb.putInt(0); } } catch (Exception e2) { ScenarioBinaryStorable.m_logger.error((Object) "Exception", (Throwable) e2); } bb.putInt(binGroups.size()); for (final byte[] gdata : binGroups) { bb.putInt(gdata.length); bb.put(gdata); } bb.putInt(binRewars.size()); for (final byte[] rdata : binRewars) { bb.putInt(rdata.length); bb.put(rdata); } return bb.array(); }
public class MultiPortEcho { private int ports[]; private ByteBuffer echoBuffer = ByteBuffer.allocate(1024); public MultiPortEcho(int ports[]) throws IOException { this.ports = ports; go(); } private void go() throws IOException { // Create a new selector Selector selector = Selector.open(); // Open a listener on each port, and register each one // with the selector for (int i = 0; i < ports.length; ++i) { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); ServerSocket ss = ssc.socket(); InetSocketAddress address = new InetSocketAddress(ports[i]); ss.bind(address); SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT); System.out.println("Going to listen on " + ports[i]); } while (true) { int num = selector.select(); Set selectedKeys = selector.selectedKeys(); Iterator it = selectedKeys.iterator(); while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) { // Accept the new connection ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); // Add the new connection to the selector SelectionKey newKey = sc.register(selector, SelectionKey.OP_READ); it.remove(); System.out.println("Got connection from " + sc); } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { // Read the data SocketChannel sc = (SocketChannel) key.channel(); // Echo data int bytesEchoed = 0; while (true) { echoBuffer.clear(); int r = sc.read(echoBuffer); if (r <= 0) { break; } echoBuffer.flip(); sc.write(echoBuffer); bytesEchoed += r; } System.out.println("Echoed " + bytesEchoed + " from " + sc); it.remove(); } } // System.out.println( "going to clear" ); // selectedKeys.clear(); // System.out.println( "cleared" ); } } public static void main(String args[]) throws Exception { int ports[] = new int[] {9001, 9002, 9003}; for (int i = 0; i < args.length; ++i) { ports[i] = Integer.parseInt(args[i]); } new MultiPortEcho(ports); } }
public static void main(String[] argv) { if (argv.length != 3) { usage(); } String tempFile = argv[0]; String testFile = argv[1]; int fileSize = Integer.valueOf(argv[2]).intValue(); int exitcode = 0; int numRead; int numThisBuf; int numWritten; if ((fileSize <= 0) || (fileSize % 4096 != 0)) { System.out.println("Error: size is not a multiple of 4096!!!!!!"); System.out.println(); usage(); } try { int bufSize = 4096; byte[] inBytes = new byte[bufSize]; byte[] outBytes = new byte[bufSize]; Random ioRandom = new Random(2006); ioRandom.nextBytes(outBytes); ByteBuffer inBuf = ByteBuffer.allocate(bufSize); ByteBuffer outBuf = ByteBuffer.wrap(outBytes); // // Loop forever // while (true) { // // Write the temporary file // FileOutputStream fos = new FileOutputStream(tempFile); FileChannel foc = fos.getChannel(); numWritten = 0; while (numWritten < fileSize) { outBuf.clear(); // sets limit to capacity & position to zero while (outBuf.hasRemaining()) { numWritten += foc.write(outBuf); } } // // Move to permanent location // FileChannel srcChannel = new FileInputStream(tempFile).getChannel(); FileChannel dstChannel = new FileOutputStream(testFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); boolean success = (new File(tempFile)).delete(); if (!success) { System.out.println("Warning: unable to delete temporary file"); } // // Read and compare // FileInputStream fis = new FileInputStream(testFile); FileChannel fic = fis.getChannel(); for (numRead = 0, numThisBuf = 0; numRead < fileSize; numThisBuf = 0) { inBuf.rewind(); // Set the buffer position to 0 numThisBuf = fic.read(inBuf); while (numThisBuf < bufSize) { numThisBuf += fic.read(inBuf); } numRead += bufSize; inBuf.rewind(); // Set the buffer position to 0 inBuf.get(inBytes); boolean same = Arrays.equals(inBytes, outBytes); if (same = false) { System.out.println("Data read does not equal data written at " + numRead + " bytes"); } } } } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(System.err); exitcode = 1; // break; } catch (SecurityException se) { se.printStackTrace(System.err); exitcode = 1; // break; } catch (Throwable t) { t.printStackTrace(System.err); exitcode = 1; } System.exit(exitcode); }
/** * A reactor that selects on some stuff and then notifies some Communicators that things happened */ public class Overlord { private Selector selector; private Pipe pipe; private static final Logger log = Logger.getLogger("Overlord"); private ConcurrentLinkedQueue<Communicator> queue; // This is just used to read the one byte off of pipes informing us that // there is data on some queue. ByteBuffer ignored = ByteBuffer.allocate(10); public Overlord() { try { selector = Selector.open(); queue = new ConcurrentLinkedQueue<Communicator>(); // open the pipe and register it with our selector pipe = Pipe.open(); pipe.sink().configureBlocking(false); pipe.source().configureBlocking(false); pipe.source().register(selector, SelectionKey.OP_READ); } catch (IOException e) { throw new RuntimeException("select() failed"); } } /** Selects on sockets and informs their Communicator when there is something to do. */ public void communicate(int timeout) { try { selector.select(timeout); } catch (IOException e) { // Not really sure why/when this happens yet return; } Iterator<SelectionKey> keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = keys.next(); keys.remove(); if (!key.isValid()) continue; // WHY Communicator communicator = (Communicator) key.attachment(); if (key.isReadable()) communicator.onReadable(); if (key.isWritable()) communicator.onWritable(); if (key.isAcceptable()) communicator.onAcceptable(); } // Go through the queue and handle each communicator while (!queue.isEmpty()) { Communicator c = queue.poll(); c.onMemo(); } } public void offer(Communicator c) { queue.offer(c); } /** Registers a SelectableChannel */ public boolean register(SelectableChannel sc, Communicator communicator) { try { sc.register(selector, sc.validOps(), communicator); return true; } catch (Exception e) { return false; } } /** If the selector is waiting, wake it up */ public void interrupt() { selector.wakeup(); } /** Registers a SelectableQueue */ public boolean register(SelectableQueue sq, Communicator communicator) { try { // Register the new pipe with the queue. It will write a byte to this // pipe when the queue is hot, and it will offer its communicator to our // queue. sq.register(this, communicator); return true; } catch (Exception e) { e.printStackTrace(); return false; } } }
/** * Opens new WebRTC data channel using specified parameters. * * @param type channel type as defined in control protocol description. Use 0 for "reliable". * @param prio channel priority. The higher the number, the lower the priority. * @param reliab Reliability Parameter<br> * This field is ignored if a reliable channel is used. If a partial reliable channel with * limited number of retransmissions is used, this field specifies the number of * retransmissions. If a partial reliable channel with limited lifetime is used, this field * specifies the maximum lifetime in milliseconds. The following table summarizes this:<br> * </br> * <p>+------------------------------------------------+------------------+ | Channel Type | * Reliability | | | Parameter | * +------------------------------------------------+------------------+ | * DATA_CHANNEL_RELIABLE | Ignored | | DATA_CHANNEL_RELIABLE_UNORDERED | Ignored | | * DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT | Number of RTX | | * DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED | Number of RTX | | * DATA_CHANNEL_PARTIAL_RELIABLE_TIMED | Lifetime in ms | | * DATA_CHANNEL_PARTIAL_RELIABLE_TIMED_UNORDERED | Lifetime in ms | * +------------------------------------------------+------------------+ * @param sid SCTP stream id that will be used by new channel (it must not be already used). * @param label text label for the channel. * @return new instance of <tt>WebRtcDataStream</tt> that represents opened WebRTC data channel. * @throws IOException if IO error occurs. */ public synchronized WebRtcDataStream openChannel( int type, int prio, long reliab, int sid, String label) throws IOException { if (channels.containsKey(sid)) { throw new IOException("Channel on sid: " + sid + " already exists"); } // Label Length & Label byte[] labelBytes; int labelByteLength; if (label == null) { labelBytes = null; labelByteLength = 0; } else { labelBytes = label.getBytes("UTF-8"); labelByteLength = labelBytes.length; if (labelByteLength > 0xFFFF) labelByteLength = 0xFFFF; } // Protocol Length & Protocol String protocol = WEBRTC_DATA_CHANNEL_PROTOCOL; byte[] protocolBytes; int protocolByteLength; if (protocol == null) { protocolBytes = null; protocolByteLength = 0; } else { protocolBytes = protocol.getBytes("UTF-8"); protocolByteLength = protocolBytes.length; if (protocolByteLength > 0xFFFF) protocolByteLength = 0xFFFF; } ByteBuffer packet = ByteBuffer.allocate(12 + labelByteLength + protocolByteLength); // Message open new channel on current sid // Message Type packet.put((byte) MSG_OPEN_CHANNEL); // Channel Type packet.put((byte) type); // Priority packet.putShort((short) prio); // Reliability Parameter packet.putInt((int) reliab); // Label Length packet.putShort((short) labelByteLength); // Protocol Length packet.putShort((short) protocolByteLength); // Label if (labelByteLength != 0) { packet.put(labelBytes, 0, labelByteLength); } // Protocol if (protocolByteLength != 0) { packet.put(protocolBytes, 0, protocolByteLength); } int sentCount = sctpSocket.send(packet.array(), true, sid, WEB_RTC_PPID_CTRL); if (sentCount != packet.capacity()) { throw new IOException("Failed to open new chanel on sid: " + sid); } WebRtcDataStream channel = new WebRtcDataStream(sctpSocket, sid, label, false); channels.put(sid, channel); return channel; }
private void initReceiver() { aa(this, sockType == SocketType.RECEIVER, ""); recvBase = 0; recvbb = ByteBuffer.allocate(RECV_BUFFER_SIZE); transportBuffer = new HashMap<Integer, Transport>(); }
// returns byte array of content meant to be sent in packet b1 public static byte[] partB(int packet_id, int len) { ByteBuffer bb = ByteBuffer.allocate(len + 4); bb.putInt(packet_id); return bb.array(); }
public void build_bricks() { ImagePlus imp; ImagePlus orgimp; ImageStack stack; FileInfo finfo; if (lvImgTitle.isEmpty()) return; orgimp = WindowManager.getImage(lvImgTitle.get(0)); imp = orgimp; finfo = imp.getFileInfo(); if (finfo == null) return; int[] dims = imp.getDimensions(); int imageW = dims[0]; int imageH = dims[1]; int nCh = dims[2]; int imageD = dims[3]; int nFrame = dims[4]; int bdepth = imp.getBitDepth(); double xspc = finfo.pixelWidth; double yspc = finfo.pixelHeight; double zspc = finfo.pixelDepth; double z_aspect = Math.max(xspc, yspc) / zspc; int orgW = imageW; int orgH = imageH; int orgD = imageD; double orgxspc = xspc; double orgyspc = yspc; double orgzspc = zspc; lv = lvImgTitle.size(); if (filetype == "JPEG") { for (int l = 0; l < lv; l++) { if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) { IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE"); return; } } } // calculate levels /* int baseXY = 256; int baseZ = 256; if (z_aspect < 0.5) baseZ = 128; if (z_aspect > 2.0) baseXY = 128; if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect); if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect); IJ.log("Z_aspect: " + z_aspect); IJ.log("BaseXY: " + baseXY); IJ.log("BaseZ: " + baseZ); */ int baseXY = 256; int baseZ = 128; int dbXY = Math.max(orgW, orgH) / baseXY; if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2; int dbZ = orgD / baseZ; if (orgD % baseZ > 0) dbZ *= 2; lv = Math.max(log2(dbXY), log2(dbZ)) + 1; int ww = orgW; int hh = orgH; int dd = orgD; for (int l = 0; l < lv; l++) { int bwnum = ww / baseXY; if (ww % baseXY > 0) bwnum++; int bhnum = hh / baseXY; if (hh % baseXY > 0) bhnum++; int bdnum = dd / baseZ; if (dd % baseZ > 0) bdnum++; if (bwnum % 2 == 0) bwnum++; if (bhnum % 2 == 0) bhnum++; if (bdnum % 2 == 0) bdnum++; int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0); int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0); int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0); bwlist.add(bw); bhlist.add(bh); bdlist.add(bd); IJ.log("LEVEL: " + l); IJ.log(" width: " + ww); IJ.log(" hight: " + hh); IJ.log(" depth: " + dd); IJ.log(" bw: " + bw); IJ.log(" bh: " + bh); IJ.log(" bd: " + bd); int xyl2 = Math.max(ww, hh) / baseXY; if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2; if (lv - 1 - log2(xyl2) <= l) { ww /= 2; hh /= 2; } IJ.log(" xyl2: " + (lv - 1 - log2(xyl2))); int zl2 = dd / baseZ; if (dd % baseZ > 0) zl2 *= 2; if (lv - 1 - log2(zl2) <= l) dd /= 2; IJ.log(" zl2: " + (lv - 1 - log2(zl2))); if (l < lv - 1) { lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1)); IJ.selectWindow(lvImgTitle.get(0)); IJ.run( "Scale...", "x=- y=- z=- width=" + ww + " height=" + hh + " depth=" + dd + " interpolation=Bicubic average process create title=" + lvImgTitle.get(l + 1)); } } for (int l = 0; l < lv; l++) { IJ.log(lvImgTitle.get(l)); } Document doc = newXMLDocument(); Element root = doc.createElement("BRK"); root.setAttribute("version", "1.0"); root.setAttribute("nLevel", String.valueOf(lv)); root.setAttribute("nChannel", String.valueOf(nCh)); root.setAttribute("nFrame", String.valueOf(nFrame)); doc.appendChild(root); for (int l = 0; l < lv; l++) { IJ.showProgress(0.0); int[] dims2 = imp.getDimensions(); IJ.log( "W: " + String.valueOf(dims2[0]) + " H: " + String.valueOf(dims2[1]) + " C: " + String.valueOf(dims2[2]) + " D: " + String.valueOf(dims2[3]) + " T: " + String.valueOf(dims2[4]) + " b: " + String.valueOf(bdepth)); bw = bwlist.get(l).intValue(); bh = bhlist.get(l).intValue(); bd = bdlist.get(l).intValue(); boolean force_pow2 = false; /* if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true; if(force_pow2){ //force pow2 if(Pow2(bw) > bw) bw = Pow2(bw)/2; if(Pow2(bh) > bh) bh = Pow2(bh)/2; if(Pow2(bd) > bd) bd = Pow2(bd)/2; } if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2; if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2; if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2; */ if (bw > imageW) bw = imageW; if (bh > imageH) bh = imageH; if (bd > imageD) bd = imageD; if (bw <= 1 || bh <= 1 || bd <= 1) break; if (filetype == "JPEG" && (bw < 8 || bh < 8)) break; Element lvnode = doc.createElement("Level"); lvnode.setAttribute("lv", String.valueOf(l)); lvnode.setAttribute("imageW", String.valueOf(imageW)); lvnode.setAttribute("imageH", String.valueOf(imageH)); lvnode.setAttribute("imageD", String.valueOf(imageD)); lvnode.setAttribute("xspc", String.valueOf(xspc)); lvnode.setAttribute("yspc", String.valueOf(yspc)); lvnode.setAttribute("zspc", String.valueOf(zspc)); lvnode.setAttribute("bitDepth", String.valueOf(bdepth)); root.appendChild(lvnode); Element brksnode = doc.createElement("Bricks"); brksnode.setAttribute("brick_baseW", String.valueOf(bw)); brksnode.setAttribute("brick_baseH", String.valueOf(bh)); brksnode.setAttribute("brick_baseD", String.valueOf(bd)); lvnode.appendChild(brksnode); ArrayList<Brick> bricks = new ArrayList<Brick>(); int mw, mh, md, mw2, mh2, md2; double tx0, ty0, tz0, tx1, ty1, tz1; double bx0, by0, bz0, bx1, by1, bz1; for (int k = 0; k < imageD; k += bd) { if (k > 0) k--; for (int j = 0; j < imageH; j += bh) { if (j > 0) j--; for (int i = 0; i < imageW; i += bw) { if (i > 0) i--; mw = Math.min(bw, imageW - i); mh = Math.min(bh, imageH - j); md = Math.min(bd, imageD - k); if (force_pow2) { mw2 = Pow2(mw); mh2 = Pow2(mh); md2 = Pow2(md); } else { mw2 = mw; mh2 = mh; md2 = md; } if (filetype == "JPEG") { if (mw2 < 8) mw2 = 8; if (mh2 < 8) mh2 = 8; } tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2); ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2); tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2); tx1 = 1.0d - 0.5d / mw2; if (mw < bw) tx1 = 1.0d; if (imageW - i == bw) tx1 = 1.0d; ty1 = 1.0d - 0.5d / mh2; if (mh < bh) ty1 = 1.0d; if (imageH - j == bh) ty1 = 1.0d; tz1 = 1.0d - 0.5d / md2; if (md < bd) tz1 = 1.0d; if (imageD - k == bd) tz1 = 1.0d; bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW; by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH; bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD; bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d); if (imageW - i == bw) bx1 = 1.0d; by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d); if (imageH - j == bh) by1 = 1.0d; bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d); if (imageD - k == bd) bz1 = 1.0d; int x, y, z; x = i - (mw2 - mw); y = j - (mh2 - mh); z = k - (md2 - md); bricks.add( new Brick( x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1, by1, bz1)); } } } Element fsnode = doc.createElement("Files"); lvnode.appendChild(fsnode); stack = imp.getStack(); int totalbricknum = nFrame * nCh * bricks.size(); int curbricknum = 0; for (int f = 0; f < nFrame; f++) { for (int ch = 0; ch < nCh; ch++) { int sizelimit = bdsizelimit * 1024 * 1024; int bytecount = 0; int filecount = 0; int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8); byte[] packed_data = new byte[pd_bufsize]; String base_dataname = basename + "_Lv" + String.valueOf(l) + "_Ch" + String.valueOf(ch) + "_Fr" + String.valueOf(f); String current_dataname = base_dataname + "_data" + filecount; Brick b_first = bricks.get(0); if (b_first.z_ != 0) IJ.log("warning"); int st_z = b_first.z_; int ed_z = b_first.z_ + b_first.d_; LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>(); for (int s = st_z; s < ed_z; s++) iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); // ImagePlus test; // ImageStack tsst; // test = NewImage.createByteImage("test", imageW, imageH, imageD, // NewImage.FILL_BLACK); // tsst = test.getStack(); for (int i = 0; i < bricks.size(); i++) { Brick b = bricks.get(i); if (ed_z > b.z_ || st_z < b.z_ + b.d_) { if (b.z_ > st_z) { for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst(); st_z = b.z_; } else if (b.z_ < st_z) { IJ.log("warning"); for (int s = st_z - 1; s > b.z_; s--) iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); st_z = b.z_; } if (b.z_ + b.d_ > ed_z) { for (int s = ed_z; s < b.z_ + b.d_; s++) iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); ed_z = b.z_ + b.d_; } else if (b.z_ + b.d_ < ed_z) { IJ.log("warning"); for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast(); ed_z = b.z_ + b.d_; } } else { IJ.log("warning"); iplist.clear(); st_z = b.z_; ed_z = b.z_ + b.d_; for (int s = st_z; s < ed_z; s++) iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); } if (iplist.size() != b.d_) { IJ.log("Stack Error"); return; } // int zz = st_z; int bsize = 0; byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8]; Iterator<ImageProcessor> ipite = iplist.iterator(); while (ipite.hasNext()) { // ImageProcessor tsip = tsst.getProcessor(zz+1); ImageProcessor ip = ipite.next(); ip.setRoi(b.x_, b.y_, b.w_, b.h_); if (bdepth == 8) { byte[] data = (byte[]) ip.crop().getPixels(); System.arraycopy(data, 0, bdata, bsize, data.length); bsize += data.length; } else if (bdepth == 16) { ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8); buffer.order(ByteOrder.LITTLE_ENDIAN); short[] data = (short[]) ip.crop().getPixels(); for (short e : data) buffer.putShort(e); System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length); bsize += buffer.array().length; } else if (bdepth == 32) { ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8); buffer.order(ByteOrder.LITTLE_ENDIAN); float[] data = (float[]) ip.crop().getPixels(); for (float e : data) buffer.putFloat(e); System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length); bsize += buffer.array().length; } } String filename = basename + "_Lv" + String.valueOf(l) + "_Ch" + String.valueOf(ch) + "_Fr" + String.valueOf(f) + "_ID" + String.valueOf(i); int offset = bytecount; int datasize = bdata.length; if (filetype == "RAW") { int dummy = -1; // do nothing } if (filetype == "JPEG" && bdepth == 8) { try { DataBufferByte db = new DataBufferByte(bdata, datasize); Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null); BufferedImage img = new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY); img.setData(raster); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(baos); String format = "jpg"; Iterator<javax.imageio.ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg"); javax.imageio.ImageWriter writer = iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality((float) jpeg_quality * 0.01f); writer.setOutput(ios); writer.write(null, new IIOImage(img, null, null), iwp); // ImageIO.write(img, format, baos); bdata = baos.toByteArray(); datasize = bdata.length; } catch (IOException e) { e.printStackTrace(); return; } } if (filetype == "ZLIB") { byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8]; Deflater compresser = new Deflater(); compresser.setInput(bdata); compresser.setLevel(Deflater.DEFAULT_COMPRESSION); compresser.setStrategy(Deflater.DEFAULT_STRATEGY); compresser.finish(); datasize = compresser.deflate(tmpdata); bdata = tmpdata; compresser.end(); } if (bytecount + datasize > sizelimit && bytecount > 0) { BufferedOutputStream fis = null; try { File file = new File(directory + current_dataname); fis = new BufferedOutputStream(new FileOutputStream(file)); fis.write(packed_data, 0, bytecount); } catch (IOException e) { e.printStackTrace(); return; } finally { try { if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); return; } } filecount++; current_dataname = base_dataname + "_data" + filecount; bytecount = 0; offset = 0; System.arraycopy(bdata, 0, packed_data, bytecount, datasize); bytecount += datasize; } else { System.arraycopy(bdata, 0, packed_data, bytecount, datasize); bytecount += datasize; } Element filenode = doc.createElement("File"); filenode.setAttribute("filename", current_dataname); filenode.setAttribute("channel", String.valueOf(ch)); filenode.setAttribute("frame", String.valueOf(f)); filenode.setAttribute("brickID", String.valueOf(i)); filenode.setAttribute("offset", String.valueOf(offset)); filenode.setAttribute("datasize", String.valueOf(datasize)); filenode.setAttribute("filetype", String.valueOf(filetype)); fsnode.appendChild(filenode); curbricknum++; IJ.showProgress((double) (curbricknum) / (double) (totalbricknum)); } if (bytecount > 0) { BufferedOutputStream fis = null; try { File file = new File(directory + current_dataname); fis = new BufferedOutputStream(new FileOutputStream(file)); fis.write(packed_data, 0, bytecount); } catch (IOException e) { e.printStackTrace(); return; } finally { try { if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); return; } } } } } for (int i = 0; i < bricks.size(); i++) { Brick b = bricks.get(i); Element bricknode = doc.createElement("Brick"); bricknode.setAttribute("id", String.valueOf(i)); bricknode.setAttribute("st_x", String.valueOf(b.x_)); bricknode.setAttribute("st_y", String.valueOf(b.y_)); bricknode.setAttribute("st_z", String.valueOf(b.z_)); bricknode.setAttribute("width", String.valueOf(b.w_)); bricknode.setAttribute("height", String.valueOf(b.h_)); bricknode.setAttribute("depth", String.valueOf(b.d_)); brksnode.appendChild(bricknode); Element tboxnode = doc.createElement("tbox"); tboxnode.setAttribute("x0", String.valueOf(b.tx0_)); tboxnode.setAttribute("y0", String.valueOf(b.ty0_)); tboxnode.setAttribute("z0", String.valueOf(b.tz0_)); tboxnode.setAttribute("x1", String.valueOf(b.tx1_)); tboxnode.setAttribute("y1", String.valueOf(b.ty1_)); tboxnode.setAttribute("z1", String.valueOf(b.tz1_)); bricknode.appendChild(tboxnode); Element bboxnode = doc.createElement("bbox"); bboxnode.setAttribute("x0", String.valueOf(b.bx0_)); bboxnode.setAttribute("y0", String.valueOf(b.by0_)); bboxnode.setAttribute("z0", String.valueOf(b.bz0_)); bboxnode.setAttribute("x1", String.valueOf(b.bx1_)); bboxnode.setAttribute("y1", String.valueOf(b.by1_)); bboxnode.setAttribute("z1", String.valueOf(b.bz1_)); bricknode.appendChild(bboxnode); } if (l < lv - 1) { imp = WindowManager.getImage(lvImgTitle.get(l + 1)); int[] newdims = imp.getDimensions(); imageW = newdims[0]; imageH = newdims[1]; imageD = newdims[3]; xspc = orgxspc * ((double) orgW / (double) imageW); yspc = orgyspc * ((double) orgH / (double) imageH); zspc = orgzspc * ((double) orgD / (double) imageD); bdepth = imp.getBitDepth(); } } File newXMLfile = new File(directory + basename + ".vvd"); writeXML(newXMLfile, doc); for (int l = 1; l < lv; l++) { imp = WindowManager.getImage(lvImgTitle.get(l)); imp.changes = false; imp.close(); } }