List of usage examples for java.nio ByteBuffer array
public final byte[] array()
From source file:com.github.neoio.net.message.staging.file.TestFileMessageStaging.java
@Test public void test() throws Exception { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put("Hello World".getBytes("US-ASCII")); buffer.flip();//from w ww . jav a 2 s . co m Assert.assertEquals(11, staging.writeTempReadBytes(buffer)); Assert.assertTrue(staging.hasTempReadBytes()); buffer.clear(); Assert.assertEquals(11, staging.readTempReadBytes(buffer)); buffer.put("Hello World".getBytes("US-ASCII")); buffer.flip(); staging.writePrimaryStaging(buffer, 22); buffer.clear(); staging.getPrimaryStage().read(buffer); Assert.assertEquals("Hello WorldHello World", new String(buffer.array(), 0, 22)); }
From source file:com.urbancode.terraform.main.Main.java
/** * Initializes Terraform so it can execute the given commands. * Here is the order of operations://from w w w . j ava 2 s .c om * Parses the credentials file and verifies the given credentials. * Generates a random string for this environment, which is appended to the output xml file. * Parses the xml file. * Runs the specified command (create, destroy, etc). * @throws XmlParsingException * @throws IOException * @throws CredentialsException * @throws CreationException * @throws DestructionException * @throws RestorationException */ public void execute() throws XmlParsingException, IOException, CredentialsException, CreationException, DestructionException, RestorationException { TerraformContext context = null; try { // parse xml and set context context = parseContext(inputXmlFile); Credentials credentials = parseCredentials(credsFile); context.setCredentials(credentials); if (AllowedCommands.CREATE.getCommandName().equalsIgnoreCase(command)) { // create new file if creating a new environment UUID uuid = UUID.randomUUID(); //convert uuid to base 62 (allowed chars: 0-9 a-z A-Z) ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); String suffix = Base64.encodeBase64URLSafeString(bb.array()); suffix = suffix.replaceAll("-", "Y"); suffix = suffix.replaceAll("_", "Z"); suffix = suffix.substring(0, 4); if (context.getEnvironment() != null) { context.getEnvironment().addSuffixToEnvName(suffix); log.debug("UUID for env " + context.getEnvironment().getName() + " is " + suffix); } else { throw new NullPointerException("No environment on context!"); } String name = context.getEnvironment().getName(); log.debug("Output filename = " + name); outputXmlFile = new File("env-" + name + ".xml"); log.debug("Calling create() on context"); context.create(); } else if (AllowedCommands.DESTROY.getCommandName().equalsIgnoreCase(command)) { String suffix = parseSuffix(context.getEnvironment().getName()); context.getEnvironment().setSuffix(suffix); log.debug("found suffix " + suffix); // write out instance failure regardless of success or failure outputXmlFile = inputXmlFile; log.debug("Calling destroy() on context"); context.destroy(); } else if (AllowedCommands.SUSPEND.getCommandName().equalsIgnoreCase(command)) { outputXmlFile = inputXmlFile; log.debug("Calling restore() on context"); log.info("Attempting to suspend power on all instances/VMs in the environment."); context.restore(); if (context instanceof ContextVmware) { SuspendCommand newCommand = new SuspendCommand((ContextVmware) context); newCommand.execute(); } else if (context instanceof ContextAWS) { com.urbancode.terraform.commands.aws.SuspendCommand newCommand = new com.urbancode.terraform.commands.aws.SuspendCommand( (ContextAWS) context); newCommand.execute(); } else { log.warn("Could not resolve context to call command \"" + command + "\""); } } else if (AllowedCommands.RESUME.getCommandName().equalsIgnoreCase(command)) { outputXmlFile = inputXmlFile; log.debug("Calling restore() on context"); context.restore(); log.info("Attempting to power on all instances/VMs in the environment."); if (context instanceof ContextVmware) { ResumeCommand newCommand = new ResumeCommand((ContextVmware) context); newCommand.execute(); } else if (context instanceof ContextAWS) { com.urbancode.terraform.commands.aws.ResumeCommand newCommand = new com.urbancode.terraform.commands.aws.ResumeCommand( (ContextAWS) context); newCommand.execute(); } else { log.warn("Could not resolve context to call command \"" + command + "\""); } } else if (AllowedCommands.TAKE_SNAPSHOT.getCommandName().equalsIgnoreCase(command)) { outputXmlFile = inputXmlFile; log.debug("Calling restore() on context"); context.restore(); log.info("Attempting to take snapshots of all instances/VMs in the environment."); if (context instanceof ContextVmware) { TakeSnapshotCommand newCommand = new TakeSnapshotCommand((ContextVmware) context); newCommand.execute(); } else if (context instanceof ContextAWS) { log.warn("Taking snapshots is not currently supported with Terraform and AWS."); } else { log.warn("Could not resolve context to call command \"" + command + "\""); } } } catch (ParserConfigurationException e1) { throw new XmlParsingException("ParserConfigurationException: " + e1.getMessage(), e1); } catch (SAXException e2) { throw new XmlParsingException("SAXException: " + e2.getMessage(), e2); } finally { if (context != null && context.doWriteContext() && outputXmlFile != null) { log.debug("Writing context out to " + outputXmlFile); writeEnvToXml(outputXmlFile, context); } } }
From source file:byps.test.TestRemoteStreams.java
/** * Send and receive a stream with content length information. * // ww w .j a v a 2s .com * @throws InterruptedException * @throws IOException */ @Test public void testRemoteStreamsOneStreamContentLength() throws InterruptedException, IOException { log.info("testRemoteStreamsOneStreamContentLength("); String str = "hello"; InputStream istrm = new ByteArrayInputStream(str.getBytes()); remote.setImage(istrm); InputStream istrmR = remote.getImage(); ByteBuffer buf = BWire.bufferFromStream(istrmR); String strR = new String(buf.array(), buf.position(), buf.remaining()); TestUtils.assertEquals(log, "stream", str, strR); remote.setImage(null); TestUtils.checkTempDirEmpty(client); log.info(")testRemoteStreamsOneStreamContentLength"); }
From source file:net.dv8tion.jda.core.audio.AudioWebSocket.java
private void setupKeepAlive(final int keepAliveInterval) { if (keepAliveHandle != null) LOG.fatal("Setting up a KeepAlive runnable while the previous one seems to still be active!!"); Runnable keepAliveRunnable = () -> { if (socket.isOpen() && socket.isOpen() && !udpSocket.isClosed()) { send(new JSONObject().put("op", 3).put("d", System.currentTimeMillis()).toString()); long seq = 0; try { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES + 1); buffer.put((byte) 0xC9); buffer.putLong(seq);/* w w w .j a va2s.c o m*/ DatagramPacket keepAlivePacket = new DatagramPacket(buffer.array(), buffer.array().length, address); udpSocket.send(keepAlivePacket); } catch (NoRouteToHostException e) { LOG.warn("Closing AudioConnection due to inability to ping audio packets."); LOG.warn("Cannot send audio packet because JDA navigate the route to Discord.\n" + "Are you sure you have internet connection? It is likely that you've lost connection."); AudioWebSocket.this.close(ConnectionStatus.ERROR_LOST_CONNECTION); } catch (IOException e) { LOG.log(e); } } }; try { keepAliveHandle = keepAlivePool.scheduleAtFixedRate(keepAliveRunnable, 0, keepAliveInterval, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException ignored) { } //ignored because this is probably caused due to a race condition // related to the threadpool shutdown. }
From source file:com.joyent.manta.client.MantaSeekableByteChannel.java
@Override public int read(final ByteBuffer dst) throws IOException { if (!open) {/* w w w .j a v a2 s .co m*/ throw new ClosedChannelException(); } final MantaObjectInputStream stream = connectOrGetResponse(); final long size = size(); if (position.get() >= size) { return EOF; } final byte[] buff = dst.array(); final int bytesRead = stream.read(buff); position.addAndGet(bytesRead); return bytesRead; }
From source file:com.facebook.presto.accumulo.index.Indexer.java
private void addIndexMutation(ByteBuffer row, ByteBuffer family, ColumnVisibility visibility, byte[] qualifier) { // Create the mutation and add it to the batch writer Mutation indexMutation = new Mutation(row.array()); indexMutation.put(family.array(), qualifier, visibility, EMPTY_BYTES); try {/*from ww w . j av a 2 s. co m*/ indexWriter.addMutation(indexMutation); } catch (MutationsRejectedException e) { throw new PrestoException(UNEXPECTED_ACCUMULO_ERROR, "Index mutation rejected by server", e); } // Increment the cardinality metrics for this value of index // metrics is a mapping of row ID to column family MetricsKey key = new MetricsKey(row, family, visibility); AtomicLong count = metrics.get(key); if (count == null) { count = new AtomicLong(0); metrics.put(key, count); } count.incrementAndGet(); }
From source file:byps.test.TestRemoteStreams.java
/** * Send and receive a stream without content length information * //ww w.ja va2s. c o m * @throws InterruptedException * @throws IOException */ @Test public void testRemoteStreamsOneStreamChunked() throws InterruptedException, IOException { log.info("testRemoteStreamsOneStreamChunked("); String str = "hello"; final ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes()); InputStream istrm = new BContentStream() { @Override public long getContentLength() { return -1L; } @Override public int read() throws IOException { return bis.read(); } }; remote.setImage(istrm); InputStream istrmR = remote.getImage(); ByteBuffer buf = BWire.bufferFromStream(istrmR); String strR = new String(buf.array(), buf.position(), buf.remaining()); TestUtils.assertEquals(log, "stream", str, strR); remote.setImage(null); TestUtils.checkTempDirEmpty(client); log.info(")testRemoteStreamsOneStreamChunked"); }
From source file:com.twitter.common.thrift.text.TTextProtocol.java
@Override public void writeBinary(ByteBuffer buf) throws TException { writeString(new String(base64Encoder.encode(buf.array()))); }
From source file:byps.test.TestRemoteStreams.java
/** * Send file stream.// w w w . j a v a 2 s.co m * A file stream has the fileName property set. * @throws InterruptedException * @throws IOException */ @Test public void testRemoteStreamsFileStream() throws InterruptedException, IOException { log.info("testRemoteStreamsFileStream("); File file = File.createTempFile("byps", ".txt"); String str = "hello"; FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(str.getBytes()); } finally { if (fos != null) fos.close(); } InputStream istrm = new BContentStreamWrapper(file); remote.setImage(istrm); BContentStream istrmR = (BContentStream) remote.getImage(); TestUtils.assertEquals(log, "Content-Type", "text/plain", istrmR.getContentType()); TestUtils.assertEquals(log, "Content-Length", file.length(), istrmR.getContentLength()); TestUtils.assertEquals(log, "FileName", file.getName(), istrmR.getFileName()); ByteBuffer buf = BWire.bufferFromStream(istrmR); String strR = new String(buf.array(), buf.position(), buf.remaining()); TestUtils.assertEquals(log, "stream", str, strR); TestUtils.assertEquals(log, "Content-Type", "text/plain", istrmR.getContentType()); TestUtils.assertEquals(log, "Content-Length", file.length(), istrmR.getContentLength()); TestUtils.assertEquals(log, "FileName", file.getName(), istrmR.getFileName()); remote.setImage(null); TestUtils.checkTempDirEmpty(client); log.info(")testRemoteStreamsFileStream"); }
From source file:org.jmangos.sniffer.handler.PKTLogHandler.java
@Override public void init() { final String date = String.format("%X", System.currentTimeMillis()); final ByteBuffer buffer = ByteBuffer.allocate(66); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put("PKT".getBytes()); buffer.put((byte) 1); buffer.put((byte) 3); buffer.put((byte) 12); buffer.putInt(this.build); buffer.put("xxXX".getBytes()); buffer.put(this.keyReader.getKey()); buffer.putInt((int) (System.currentTimeMillis() / 1000L)); buffer.putInt(0);/*w w w .j a v a 2 s. co m*/ buffer.putInt(0); try { this.fous = new DataOutputStream(new FileOutputStream(new File(this.build + "_" + date + ".pkt"))); this.fous.write(buffer.array()); setInit(true); } catch (final FileNotFoundException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } }