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:com.odiago.flumebase.io.CharBufferUtils.java

/**
 * Parses a CharSequence into a list of values, all of some other type.
 *//* www. j a  va  2 s  .com*/
public static List<Object> parseList(CharBuffer chars, Type listItemType, String nullStr, String listDelim)
        throws ColumnParseException {
    StrTokenizer tokenizer = new StrTokenizer(chars.toString(), listDelim.charAt(0));
    List<Object> out = new ArrayList<Object>();

    while (tokenizer.hasNext()) {
        String part = (String) tokenizer.next();
        out.add(parseType(CharBuffer.wrap(part), listItemType, nullStr, listDelim));
    }

    return Collections.unmodifiableList(out);
}

From source file:pl.psnc.synat.wrdz.realm.digest.WrdzDigestAuthHandler.java

@Override
public char[] hashPassword(char[] password, byte[] salt) throws CharacterCodingException {
    byte[] bytes = ArrayUtils.addAll(Charset.forName(charset).encode(CharBuffer.wrap(password)).array(), salt);
    if (messageDigest != null) {
        synchronized (messageDigest) {
            messageDigest.reset();//  ww w . j a v  a2s  .  com
            bytes = messageDigest.digest(bytes);
        }
    }
    if (HEX.equalsIgnoreCase(encoding)) {
        return hexEncode(bytes);
    } else if (BASE64.equalsIgnoreCase(encoding)) {
        return base64Encode(bytes);
    } else { // no encoding specified
        return Charset.forName(charset).decode(ByteBuffer.wrap(bytes)).array();
    }
}

From source file:fi.jyu.student.jatahama.onlineinquirytool.server.LoadSaveServlet.java

private String formSafeAscii(String utfName) {
    asciiEncoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
    try {/*from ww  w  . jav  a2 s  . c  om*/
        String ascii = new String(asciiEncoder.encode(CharBuffer.wrap(utfName)).array()).replaceAll("\"", "_");
        return ascii;
    } catch (CharacterCodingException e) {
        log.warning("asciiEncoder failure: " + e.getMessage());
        // Fallback to default name
        return defaultFilename;
    }
}

From source file:org.geppetto.frontend.controllers.GeppettoServletController.java

/**
 * Performs start up check when new connection is established.
 * /*from   www .  ja v  a2  s.  c  o  m*/
 * @param newVisitor
 *            - New visitor
 */
private void performStartUpCheck(GeppettoMessageInbound newVisitor) {

    for (GeppettoMessageInbound client : this.getConnections()) {
        CharBuffer buffer = CharBuffer.wrap("ping");
        try {
            client.getWsOutbound().writeTextMessage(buffer);
        } catch (IOException e) {
            _logger.error("Unable to communicate with client " + e.getMessage() + ". Removing connection.");
            this.removeConnection(client);
        }
    }

    if (this._simulationServerConfig.getServerBehaviorMode() == ServerBehaviorModes.OBSERVE) {
        // Simulation is being used, notify new user controls are
        // unavailable
        if (isSimulationInUse()) {
            simulationControlsUnavailable(newVisitor);
        }
    } else if (this._simulationServerConfig.getServerBehaviorMode() == ServerBehaviorModes.MULTIUSER) {
        int simulatorCapacity = newVisitor.getSimulationService().getSimulationCapacity();

        if ((this.getConnections().size() > simulatorCapacity) && (simulatorCapacity > 1)) {

            int position = (this.getConnections().size()
                    - newVisitor.getSimulationService().getSimulationCapacity());
            String update = "Simulation is full, you are number " + position + " on the" + " waitlist";

            _queueUsers.add(newVisitor);
            messageClient(null, newVisitor, OUTBOUND_MESSAGE_TYPES.SIMULATOR_FULL, update);
        } else {
            messageClient(null, newVisitor, OUTBOUND_MESSAGE_TYPES.READ_URL_PARAMETERS);
        }
    }
}

From source file:com.mgmtp.perfload.perfalyzer.util.IoUtilities.java

public static void writeLineToChannel(final WritableByteChannel destChannel, final String line,
        final Charset charset) {
    try {//from  www .j  ava2 s.c  o m
        String tmpLine = line.endsWith(SystemUtils.LINE_SEPARATOR) ? line : line + SystemUtils.LINE_SEPARATOR;
        CharBuffer buffer = CharBuffer.wrap(tmpLine);
        CharsetEncoder encoder = charset.newEncoder();
        ByteBuffer bb = encoder.encode(buffer);
        writeToChannel(destChannel, bb);
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}

From source file:fr.natoine.html.HTMLPage.java

private void encodeBody() {
    //CharsetEncoder encoder = Charset.forName("UTF-16").newEncoder();
    if (encoding != null) {
        if (encoding.equalsIgnoreCase("UTF-8")) {
            CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder();
            try {
                String decoded = new String(encoder.encode(CharBuffer.wrap(body.toCharArray())).array());
                //System.out.println("decoded : " + decoded);
                //CharsetDecoder decoder = Charset.forName(encoding).newDecoder();
                CharsetDecoder decoder = Charset.forName(encoding).newDecoder();
                decoded = decoder.decode(ByteBuffer.wrap(decoded.getBytes())).toString();
                //System.out.println("decoded2 : " + decoded);
                body = decoded;/*ww w . jav a  2 s  .co m*/
            } catch (CharacterCodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else {
        String[] olds = new String[16];
        String[] news = new String[16];
        olds[0] = "&acirc;";
        news[0] = "";
        olds[1] = "&agrave;";
        news[1] = "";
        olds[2] = "&eacute;";
        news[2] = "";
        olds[3] = "&ecirc;";
        news[3] = "";
        olds[4] = "&egrave;";
        news[4] = "";
        olds[5] = "&euml;";
        news[5] = "";
        olds[6] = "&icirc;";
        news[6] = "";
        olds[7] = "&iuml;";
        news[7] = "";
        olds[8] = "&ocirc;";
        news[8] = "";
        olds[9] = "&oelig;";
        news[9] = "";
        olds[10] = "&ucirc;";
        news[10] = "";
        olds[11] = "&ugrave;";
        news[11] = "";
        olds[12] = "&uuml;";
        news[12] = "";
        olds[13] = "&ccedil;";
        news[13] = "";
        olds[14] = "&lt;";
        news[14] = "<";
        olds[15] = "&gt;";
        news[15] = ">";
        for (int i = 0; i < olds.length; i++) {
            body = body.replaceAll(olds[i], news[i]);
        }
    }
}

From source file:gda.device.scannable.keyence.Keyence.java

/**
 * Send command to the server.// w  ww.j  ava2s . c  o  m
 * 
 * @param msg
 *            an unterminated command
 * @return the reply string.
 * @throws DeviceException
 */
public String processCommand(String msg) throws DeviceException {
    String command = msg + '\r';
    String reply = null;
    logger.debug(getName() + ": sent command: |" + msg + "|");
    synchronized (socketAccessLock) {
        if (!isConnected()) {
            throw new DeviceException("not connected");
        }
        try {
            cleanPipe();
            socketChannel.write(encoder.encode(CharBuffer.wrap(command)));
            bb.clear();
            socketChannel.read(bb);
            bb.flip();
            reply = decoder.decode(bb).toString();
            logger.debug(getName() + ": got reply: |" + reply.trim() + "|");
        } catch (SocketTimeoutException ex) {
            throw new DeviceException("sendCommand read timeout " + ex.getMessage(), ex);
        } catch (IOException ex) {
            connected = false;
            throw new DeviceException("sendCommand: " + ex.getMessage(), ex);
        }
    }
    return reply;
}

From source file:com.amazonaws.services.kinesis.clientlibrary.proxies.KinesisLocalFileProxy.java

private void populateDataRecordsFromFile(String file) throws IOException {
    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
        Charset charset = Charset.forName("UTF-8");
        CharsetEncoder encoder = charset.newEncoder();
        String str;//  w  w  w  . j av  a 2s. co  m
        str = in.readLine();
        if (str != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            SerializedShardList shards = objectMapper.readValue(str, SerializedShardList.class);
            shardList = shards.getShardList();
        }
        if (shardList == null) {
            shardList = new ArrayList<Shard>();
        }

        // Populate shardIds of shards that have an ending sequence number (and which != maxSeqNum).
        // GetRecords will return a null iterator for these after all data has been returned.
        for (Shard shard : shardList) {
            SequenceNumberRange range = shard.getSequenceNumberRange();
            if ((range != null) && (range.getEndingSequenceNumber() != null)) {
                BigInteger endingSequenceNumber = new BigInteger(range.getEndingSequenceNumber());
                if (endingSequenceNumber.compareTo(MAX_SEQUENCE_NUMBER) != 0) {
                    closedShards.add(shard.getShardId());
                }
            }
            shardedDataRecords.put(shard.getShardId(), new ArrayList<Record>());
        }

        while ((str = in.readLine()) != null) {
            String[] strArr = str.split(",");
            if (strArr.length != NUM_FIELDS_IN_FILE) {
                throw new InvalidArgumentException("Unexpected input in file."
                        + "Expected format (shardId, sequenceNumber, partitionKey, dataRecord, timestamp)");
            }
            String shardId = strArr[LocalFileFields.SHARD_ID.getPosition()];
            Record record = new Record();
            record.setSequenceNumber(strArr[LocalFileFields.SEQUENCE_NUMBER.getPosition()]);
            record.setPartitionKey(strArr[LocalFileFields.PARTITION_KEY.getPosition()]);
            ByteBuffer byteBuffer = encoder.encode(CharBuffer.wrap(strArr[LocalFileFields.DATA.getPosition()]));
            record.setData(byteBuffer);
            Date timestamp = new Date(
                    Long.parseLong(strArr[LocalFileFields.APPROXIMATE_ARRIVAL_TIMESTAMP.getPosition()]));
            record.setApproximateArrivalTimestamp(timestamp);
            List<Record> shardRecords = shardedDataRecords.get(shardId);
            if (shardRecords == null) {
                shardRecords = new ArrayList<Record>();
            }
            shardRecords.add(record);
            shardedDataRecords.put(shardId, shardRecords);
        }
    }
}

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

public void changePassword(PasswordInfo passwordInfo, char[] oldPassword, char[] newPassword) {
    char[] storedPassword = getPassword(passwordInfo.getRefId());
    if (storedPassword != null) {
        if (oldPassword == null || !CharBuffer.wrap(oldPassword).equals(CharBuffer.wrap(storedPassword))) {
            throw new RuntimeException(
                    "Old password does not match new password for: " + passwordInfo.getRefId());
        }/*w w w  .ja  v a  2s . c o  m*/
    }
    addPassword(passwordInfo, newPassword, true);
}