Example usage for java.nio CharBuffer wrap

List of usage examples for java.nio CharBuffer wrap

Introduction

In this page you can find the example usage for java.nio CharBuffer wrap.

Prototype

public static CharBuffer wrap(CharSequence chseq) 

Source Link

Document

Creates a new char buffer by wrapping the given char sequence.

Usage

From source file:org.apache.sqoop.lib.RecordParser.java

/**
 * Return a list of strings representing the fields of the input line.
 * This list is backed by an internal buffer which is cleared by the
 * next call to parseRecord()./*  www. j a  v  a 2 s .  c om*/
 */
public List<String> parseRecord(CharSequence input) throws com.cloudera.sqoop.lib.RecordParser.ParseError {
    if (null == input) {
        throw new com.cloudera.sqoop.lib.RecordParser.ParseError("null input string");
    }

    return parseRecord(CharBuffer.wrap(input));
}

From source file:org.apache.mahout.utils.nlp.collocations.llr.BloomTokenFilterTest.java

private static void setKey(Key k, String s) throws IOException {
    ByteBuffer buffer = encoder.encode(CharBuffer.wrap(s.toCharArray()));
    k.set(buffer.array(), 1.0);/*from   ww  w  . j a v  a  2 s.c om*/
}

From source file:com.packetsender.android.PacketListenerService.java

@Override
protected void onHandleIntent(Intent intent) {

    dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0));

    listenportTCP = dataStore.getTCPPort();
    listenportUDP = dataStore.getUDPPort();
    Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP));

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startNotification();// w w  w  .  j  a v a 2s  .  com

    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
    ByteBuffer response = null;
    try {
        response = encoder.encode(CharBuffer.wrap("response"));
    } catch (CharacterCodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {

        SocketAddress localportTCP = new InetSocketAddress(listenportTCP);
        SocketAddress localportUDP = new InetSocketAddress(listenportUDP);

        tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localportTCP);

        udpserver = DatagramChannel.open();
        udpserver.socket().bind(localportUDP);

        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        Selector selector = Selector.open();

        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
        receiveBuffer.clear();

        shutdownListener = new Runnable() {
            public void run() {

                if (false) {

                    try {
                        tcpserver.close();
                    } catch (IOException e) {
                    }
                    try {
                        udpserver.close();
                    } catch (IOException e) {
                    }
                    stopSelf();
                } else {
                    mHandler.postDelayed(shutdownListener, 2000);

                }

            }
        };

        sendListener = new Runnable() {
            public void run() {

                //Packet fetchedPacket = mDbHelper.needSendPacket();
                Packet[] fetchedPackets = dataStore.fetchAllServicePackets();

                if (fetchedPackets.length > 0) {
                    dataStore.clearServicePackets();
                    Log.d("service",
                            DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets"));

                    for (int i = 0; i < fetchedPackets.length; i++) {
                        Packet fetchedPacket = fetchedPackets[i];
                        Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString()));

                    }

                    new SendPacketsTask().execute(fetchedPackets);
                }

                mHandler.postDelayed(sendListener, 2000);

            }
        };

        //start shutdown listener
        mHandler.postDelayed(shutdownListener, 2000);

        //start send listener
        mHandler.postDelayed(sendListener, 5000);

        while (true) {
            try { // Handle per-connection problems below
                  // Wait for a client to connect
                Log.d("service", DataStorage.FILE_LINE("waiting for connection"));
                selector.select();
                Log.d("service", DataStorage.FILE_LINE("client connection"));

                Set keys = selector.selectedKeys();

                for (Iterator i = keys.iterator(); i.hasNext();) {

                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    Channel c = (Channel) key.channel();

                    if (key.isAcceptable() && c == tcpserver) {

                        SocketChannel client = tcpserver.accept();

                        if (client != null) {

                            Socket tcpSocket = client.socket();
                            packetCounter++;

                            DataInputStream in = new DataInputStream(tcpSocket.getInputStream());

                            byte[] buffer = new byte[1024];
                            int received = in.read(buffer);
                            byte[] bufferConvert = new byte[received];
                            System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "TCP";
                            storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = tcpSocket.getPort();
                            storepacket.port = tcpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            Log.i("service", DataStorage.FILE_LINE("Got TCP"));
                            //dataStore.SavePacket(storepacket);

                            /*
                            Intent tcpIntent = new Intent();
                            tcpIntent.setAction(ResponseReceiver.ACTION_RESP);
                            tcpIntent.addCategory(Intent.CATEGORY_DEFAULT);
                            tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name);
                            sendBroadcast(tcpIntent);
                            */

                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "TCP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = tcpSocket.getInetAddress().getHostAddress();
                                storepacket.fromPort = tcpSocket.getLocalPort();
                                storepacket.port = tcpSocket.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                                client.write(response); // send response
                            }

                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {

                        DatagramSocket udpSocket;
                        DatagramPacket udpPacket;

                        byte[] buffer = new byte[2048];
                        // Create a packet to receive data into the buffer
                        udpPacket = new DatagramPacket(buffer, buffer.length);

                        udpSocket = udpserver.socket();

                        receiveBuffer.clear();

                        InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer);

                        if (clientAddress != null) {

                            String fromAddress = clientAddress.getAddress().getHostAddress();

                            packetCounter++;

                            int received = receiveBuffer.position();
                            byte[] bufferConvert = new byte[received];

                            System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "UDP";
                            storepacket.fromIP = clientAddress.getAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = clientAddress.getPort();
                            storepacket.port = udpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            //dataStore.SavePacket(storepacket);
                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "UDP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = clientAddress.getAddress().getHostAddress();
                                storepacket.fromPort = udpSocket.getLocalPort();
                                storepacket.port = clientAddress.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                //dataStore.SavePacket(storepacket);
                                udpserver.send(response, clientAddress);
                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            }
                        }
                    }
                }
            } catch (java.io.IOException e) {
                Log.i("service", DataStorage.FILE_LINE("IOException "));
            } catch (Exception e) {
                Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e)));
            }
        }
    } catch (BindException e) {

        //mDbHelper.putServiceError("Error binding to port");
        dataStore.putToast("Port already in use.");
        Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e)));

    } catch (Exception e) {
        //mDbHelper.putServiceError("Fatal Error starting service");
        Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e)));
    }

    stopNotification();

}

From source file:org.cyclop.service.common.FileStorage.java

public void store(@NotNull UserIdentifier userId, @NotNull Object entity) throws ServiceException {
    LOG.debug("Storing file for {}", userId);
    Path histPath = getPath(userId, entity.getClass());
    try (FileChannel channel = openForWrite(histPath)) {
        String jsonText = jsonMarshaller.marshal(entity);
        ByteBuffer buf = encoder.get().encode(CharBuffer.wrap(jsonText));
        int written = channel.write(buf);
        channel.truncate(written);/*from  w w  w . j a va 2s  . c  om*/
    } catch (IOException | SecurityException | IllegalStateException e) {
        throw new ServiceException(
                "Error storing query history in:" + histPath + " - " + e.getClass() + " - " + e.getMessage(),
                e);
    }
    LOG.trace("File has been sotred {}", entity);
}

From source file:com.esri.geoevent.solutions.adapter.regexText.RegexTextInboundAdapter.java

private ByteBuffer encode(String str) {
    // Encode a string into a byte buffer
    ByteBuffer bb = null;/*from  w  w w  .ja v a  2  s .c  o  m*/
    CharsetEncoder isoencoder = charset.newEncoder();
    try {
        bb = isoencoder.encode(CharBuffer.wrap(str));
    } catch (CharacterCodingException e) {
        log.error(e);
    }
    return bb;
}

From source file:com.tinspx.util.io.callbacks.SegmentingCallbackTest.java

private static void testCharset(Charset charset) {
    final char[] chars = toChars(charset, 1024 * 64);
    final byte[] bytes = ByteUtils.toByteArray(charset.encode(CharBuffer.wrap(chars)));
    CAWriter writer = new CAWriter(chars.length);

    testWriteSingle(charset, chars, bytes, writer);
    testWriteParts(charset, chars, bytes, writer);
    testWriteFull(charset, chars, bytes, writer);
}

From source file:com.cloudera.sqoop.lib.RecordParser.java

/**
 * Return a list of strings representing the fields of the input line.
 * This list is backed by an internal buffer which is cleared by the
 * next call to parseRecord()./*  w w w.  ja va 2  s.c  o  m*/
 */
public List<String> parseRecord(char[] input) throws ParseError {
    if (null == input) {
        throw new ParseError("null input string");
    }

    return parseRecord(CharBuffer.wrap(input));
}

From source file:org.tolven.security.password.PasswordHolder.java

public void addPassword(PasswordInfo passwordInfo, char[] password, boolean replace) {
    if (password == null) {
        throw new RuntimeException("Password required for password Ref ID: " + passwordInfo.getRefId());
    }/*from w  ww .ja v  a 2  s  .  c  o m*/
    if (!replace) {
        PasswordInfo existingPasswordInfo = getPasswordInfo(passwordInfo.getRefId());
        if (existingPasswordInfo != null) {
            if (!CharBuffer.wrap(existingPasswordInfo.getPassword()).equals(CharBuffer.wrap(password))) {
                throw new RuntimeException("PasswordInfo with id '" + passwordInfo.getRefId()
                        + "' already exists.\nIt can be changed by supplying the old password.");
            } else {
                /*
                 * No need to add, since the password has not changed
                 */
                return;
            }
        }
    }
    passwordInfo.setPassword(password);
    getPasswordMap().put(passwordInfo.getRefId(), passwordInfo);
}

From source file:org.apache.sqoop.lib.RecordParser.java

/**
 * Return a list of strings representing the fields of the input line.
 * This list is backed by an internal buffer which is cleared by the
 * next call to parseRecord()./*from   www .j  a v  a  2s.  c  o  m*/
 */
public List<String> parseRecord(char[] input) throws com.cloudera.sqoop.lib.RecordParser.ParseError {
    if (null == input) {
        throw new com.cloudera.sqoop.lib.RecordParser.ParseError("null input string");
    }

    return parseRecord(CharBuffer.wrap(input));
}

From source file:org.geppetto.samplesimulation.SimulationServlet.java

private void sendUpdate(String message) {
    for (SimDataInbound connection : getConnections()) {
        try {/*  w  ww. jav a2s.  co  m*/
            CharBuffer buffer = CharBuffer.wrap(message);
            connection.getWsOutbound().writeTextMessage(buffer);
        } catch (IOException ignore) {
            // Ignore
        }
    }
}