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.wings.session.SmartURLsFilter.java

private static void encode(ByteArrayOutputStream bytes, ServletOutputStream out) throws IOException {
    String regex = "(href|src|action) *= *\"([^\"]*)\"";

    SmartURLsFilter smartURLsFilter = new SmartURLsFilter();
    String replacement = smartURLsFilter.parameterSeparator + "$2" + smartURLsFilter.nameValueSeparator + "$4";

    smartURLsFilter.encodePattern = Pattern
            .compile("(" + "\\?|&" + ")([a-zA-Z0-9%+.-[*]_]*)" + "(" + "=" + ")([a-zA-Z0-9%+.-[*]_=/]*)");

    CharBuffer chars = CharBuffer.wrap(bytes.toString());
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(chars);
    int pos = 0;//from   www  . j a  va2 s.c  o m
    while (matcher.find()) {
        out.print(chars.subSequence(pos, matcher.start()).toString());
        pos = matcher.end();
        Matcher matcher2 = smartURLsFilter.encodePattern.matcher(matcher.group(2));
        String group2 = matcher2.replaceAll(replacement);

        out.print(matcher.group(1) + "=\"" + group2 + "\"");
    }
    out.print(chars.subSequence(pos, bytes.size()).toString());
}

From source file:org.sonar.scanner.scan.filesystem.CharsetValidationTest.java

private byte[] encode(String txt, Charset charset) throws CharacterCodingException {
    CharsetEncoder encoder = charset.newEncoder().onMalformedInput(CodingErrorAction.REPORT)
            .onUnmappableCharacter(CodingErrorAction.REPORT);
    ByteBuffer encoded = encoder.encode(CharBuffer.wrap(txt));
    byte[] b = new byte[encoded.remaining()];
    encoded.get(b);/*  w  w  w. j  a v a  2  s . c  o m*/
    return b;
}

From source file:org.glite.slcs.util.Utils.java

/**
 * Converts a Java unicode string in a ISO-8859-1 (ISO Latin1) string.
 * //  w w w .j  a v  a2 s.  c  om
 * @param unicode
 *            The string to convert
 * @return The ISO-8859-1 string or <code>null</code> if the convertion
 *         failed.
 */
static public String convertUnicodeToISOLatin1(String unicode) {
    if (unicode == null) {
        return null;
    }
    String iso_8859_1 = null;
    try {
        Charset latin1 = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = latin1.newDecoder();
        CharsetEncoder encoder = latin1.newEncoder();
        ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(unicode));
        CharBuffer cbuf = decoder.decode(bbuf);
        iso_8859_1 = cbuf.toString();
    } catch (CharacterCodingException e) {
        // ignored: e.printStackTrace();
        LOG.error("Failed to convert Unicode: " + unicode + " to ISO-8859-1", e);
    }
    return iso_8859_1;
}

From source file:com.tinspx.util.json.JSONParserTest.java

@SuppressWarnings({ "CallToPrintStackTrace", "BroadCatchBlock", "TooBroadCatch" })
private void testRandomStandardParsing(CAWriter w) throws IOException {
    Object value = gen.buildRandomJSON(16, 12);

    w.reset();/*from w w w . j  a  v a 2 s. co  m*/
    ConfigurableWriter.INSTANCE.writeTo(w, value);
    Object parse = null;
    try {
        parse = JSONValue.parse(w);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail("parse exception normal");
    }
    assertJsonEquals(value, parse, "normal");

    w.reset();
    IndentingWriter.indentingBuilder().build().writeTo(w, value);
    parse = null;
    try {
        parse = JSONValue.parse(new CharSequenceReader(w));
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail("parse exception indenting");
    }
    assertJsonEquals(value, parse, "indenting");

    w.reset();
    JSONValue.writeTo(w, value);
    parse = null;
    try {
        parse = JSONValue.parse((Readable) CharBuffer.wrap(w.toCharArray()));
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail("parse exception indenting");
    }
    assertJsonEquals(value, parse, "indenting");
}

From source file:org.minig.imap.EncodedWord.java

/**
 * Takes a text in form of a CharSequence encoded in the given charset (e.g.
 * ISO-8859-1) and makes it US-ASCII compatible and RFC822 compatible for
 * the use as e.g. subject with special characters. <br>
 * This algorithm tries to achieve several goals when decoding: <li>never
 * encode a single character but try to encode whole words</li> <li>if two
 * words must be encoded and there a no more than 3 characters inbetween,
 * encode everything in one single encoded word</li> <li>an encoded word
 * must never be longer than 76 characters in total</li> <li>ensure that no
 * encodedWord is in a line-wrap (RFC822 advices to no have more than 78
 * characters in a headerline)</li>
 * //  ww w. ja v  a2s . co m
 * @param input
 *            the headerline
 * @param charset
 *            the used charset (e.g. ISO-8859-1)
 * @param type
 *            the encoding to be used
 * @return input encoded in EncodedWords
 */
public static StringBuilder encode(CharSequence input, Charset charset, int type) {
    StringBuilder result = new StringBuilder(input.length());
    LinkedList<int[]> words = new LinkedList<int[]>();
    String encodedWordPrototype;

    int maxLength;
    if (type == QUOTED_PRINTABLE) {
        encodedWordPrototype = "=?" + charset.displayName() + "?q?";
        maxLength = 75 - encodedWordPrototype.length() - 2;
    } else {
        encodedWordPrototype = "=?" + charset.displayName() + "?b?";
        maxLength = 75 - encodedWordPrototype.length() - 6;
    }

    // First find words which need to be encoded
    Matcher matcher = wordTokenizerPattern.matcher(input);
    float encodedChar = type == QUOTED_PRINTABLE ? 3.0f : 4.0f / 3.0f;
    float normalChar = type == QUOTED_PRINTABLE ? 1.0f : 4.0f / 3.0f;

    while (matcher.find()) {
        String word = matcher.group(1);
        float encodedLength = 0.0f;
        int start = matcher.start();
        int end = matcher.end();
        boolean mustEncode = false;

        for (int i = 0; i < word.length(); i++) {
            if (word.charAt(i) > 127) {
                encodedLength += encodedChar;
                mustEncode = true;
            } else {
                encodedLength += normalChar;
            }

            // Split if too long
            if (Math.ceil(encodedLength) > maxLength) {
                words.add(new int[] { start, start + i, maxLength });
                word = word.substring(i);

                start += i;
                i = 0;
                encodedLength = 0.0f;
                mustEncode = false;
            }
        }
        if (mustEncode)
            words.add(new int[] { start, end, (int) Math.ceil(encodedLength) });
    }

    // No need to create encodedWords
    if (words.isEmpty()) {
        return result.append(input);
    }

    // Second group them together if possible (see goals above)
    int[] last = null;
    for (int i = 0; i < words.size(); i++) {
        int[] act = words.get(i);
        if (last != null && (last[2] + act[2] + (act[0] - last[1]) * normalChar < maxLength)
                && (act[0] - last[1]) < 10) {
            words.remove(i--);
            last[1] = act[1];
            last[2] += act[2] + (act[0] - last[1]) * normalChar;
        } else {
            last = act;
        }
    }

    // Create encodedWords
    Iterator<int[]> it = words.iterator();
    int lastWordEnd = 0;
    while (it.hasNext()) {
        int[] act = it.next();

        // create encoded part
        CharSequence rawWord = input.subSequence(act[0], act[1]);
        CharSequence encodedPart;
        if (type == QUOTED_PRINTABLE) {
            // Replace <space> with _
            Matcher wsMatcher = whitespacePattern.matcher(rawWord);
            rawWord = wsMatcher.replaceAll("_");

            encodedPart = QuotedPrintable.encode(rawWord, charset);
        } else {
            encodedPart = Base64.encodeBase64String(charset.encode(CharBuffer.wrap(rawWord)).array());
        }

        result.append(input.subSequence(lastWordEnd, act[0]));
        result.append(encodedWordPrototype);
        result.append(encodedPart);
        result.append("?=");

        lastWordEnd = act[1];
    }
    result.append(input.subSequence(lastWordEnd, input.length()));

    return result;
}

From source file:org.multibit.viewsystem.swing.action.SendBitcoinNowAction.java

/**
 * Actually send the bitcoin.//  w w  w  . j a  v a  2s .  c om
 */
@Override
public void actionPerformed(ActionEvent event) {
    sendBitcoinConfirmPanel.setMessageText(" ", " ");

    // Check to see if the wallet files have changed.
    final WalletData perWalletModelData = this.bitcoinController.getModel().getActivePerWalletModelData();
    boolean haveFilesChanged = this.bitcoinController.getFileHandler().haveFilesChanged(perWalletModelData);

    if (haveFilesChanged) {
        // Set on the perWalletModelData that files have changed and fire data changed.
        perWalletModelData.setFilesHaveBeenChangedByAnotherProcess(true);
        this.bitcoinController.fireFilesHaveBeenChangedByAnotherProcess(perWalletModelData);
    } else {
        // Put sending message and remove the send button.
        sendBitcoinConfirmPanel.setMessageText(
                controller.getLocaliser().getString(assetify("sendBitcoinNowAction.sendingBitcoin")));

        // Get the label and address out of the wallet preferences.
        String sendAddress = this.bitcoinController.getModel()
                .getActiveWalletPreference(BitcoinModel.SEND_ADDRESS);
        String sendLabel = this.bitcoinController.getModel().getActiveWalletPreference(BitcoinModel.SEND_LABEL);

        if (sendLabel != null && !sendLabel.equals("")) {
            WalletInfoData addressBook = perWalletModelData.getWalletInfo();
            addressBook.addSendingAddress(new WalletAddressBookData(sendLabel, sendAddress));
        }

        final char[] walletPassword = walletPasswordField.getPassword();

        if (this.bitcoinController.getModel().getActiveWallet() != null && this.bitcoinController.getModel()
                .getActiveWallet().getEncryptionType() != EncryptionType.UNENCRYPTED) {
            // Encrypted wallet.
            if (walletPassword == null || walletPassword.length == 0) {
                // User needs to enter password.
                sendBitcoinConfirmPanel.setMessageText(controller.getLocaliser()
                        .getString("showExportPrivateKeysAction.youMustEnterTheWalletPassword"), "");
                return;
            }

            try {
                if (!this.bitcoinController.getModel().getActiveWallet()
                        .checkPassword(CharBuffer.wrap(walletPassword))) {
                    // The password supplied is incorrect.
                    sendBitcoinConfirmPanel.setMessageText(controller.getLocaliser()
                            .getString("createNewReceivingAddressSubmitAction.passwordIsIncorrect"), "");
                    return;
                }
            } catch (KeyCrypterException kce) {
                log.debug(kce.getClass().getCanonicalName() + " " + kce.getMessage());
                // The password supplied is probably incorrect.
                sendBitcoinConfirmPanel.setMessageText(controller.getLocaliser()
                        .getString("createNewReceivingAddressSubmitAction.passwordIsIncorrect"), "");
                return;
            }
        }

        // Double check wallet is not busy then declare that the active wallet is busy with the task
        if (!perWalletModelData.isBusy()) {
            perWalletModelData.setBusy(true);
            perWalletModelData.setBusyTaskVerbKey(assetify("sendBitcoinNowAction.sendingBitcoin"));

            this.bitcoinController.fireWalletBusyChange(true);
            sendBitcoinConfirmPanel.setMessageText(
                    controller.getLocaliser().getString("sendBitcoinNowAction.preparingToSend"), "");
            //assetify("sendBitcoinNowAction.sendingBitcoin")), "");
            sendBitcoinConfirmPanel.invalidate();
            sendBitcoinConfirmPanel.validate();
            sendBitcoinConfirmPanel.repaint();

            // Message delivery could take a while and we can't cancel it, so disable button
            sendBitcoinConfirmPanel.getCancelButton().setVisible(false);

            // Perform send
            Executors.newSingleThreadExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    performSend(perWalletModelData, sendRequest, CharBuffer.wrap(walletPassword));
                }
            });

            //       performSend(perWalletModelData, sendRequest, CharBuffer.wrap(walletPassword));
        }
    }
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.auth.HMACAuthenticator.java

private byte[] toBytes(char[] chars) {
    CharBuffer charBuffer = CharBuffer.wrap(chars);
    ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
    byte[] bytes = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit());
    Arrays.fill(charBuffer.array(), '\u0000'); //Clear sensitive data from memory
    Arrays.fill(byteBuffer.array(), (byte) 0); //Clear sensitive data from memory
    return bytes;
}

From source file:org.bimserver.ifc.step.serializer.IfcStepSerializer.java

private void writePrimitive(Object val) throws SerializerException, IOException {
    if (val.getClass().getSimpleName().equals("Tristate")) {
        if (val.toString().equals("TRUE")) {
            print(BOOLEAN_TRUE);/*from  ww  w  .  ja va2  s .  co m*/
        } else if (val.toString().equals("FALSE")) {
            print(BOOLEAN_FALSE);
        } else if (val.toString().equals("UNDEFINED")) {
            print(BOOLEAN_UNDEFINED);
        }
    } else if (val instanceof Double) {
        if (((Double) val).isInfinite() || (((Double) val).isNaN())) {
            LOGGER.info("Serializing infinite or NaN double as 0.0");
            print("0.0");
        } else {
            String string = val.toString();
            if (string.endsWith(DOT_0)) {
                print(string.substring(0, string.length() - 1));
            } else {
                print(string);
            }
        }
    } else if (val instanceof Boolean) {
        Boolean bool = (Boolean) val;
        if (bool) {
            print(BOOLEAN_TRUE);
        } else {
            print(BOOLEAN_FALSE);
        }
    } else if (val instanceof String) {
        print(SINGLE_QUOTE);
        String stringVal = (String) val;
        for (int i = 0; i < stringVal.length(); i++) {
            char c = stringVal.charAt(i);
            if (c == '\'') {
                print("\'\'");
            } else if (c == '\\') {
                print("\\\\");
            } else if (c >= 32 && c <= 126) {
                // ISO 8859-1
                print("" + c);
            } else if (c < 255) {
                //  ISO 10646 and ISO 8859-1 are the same < 255 , using ISO_8859_1
                print("\\X\\" + new String(Hex.encodeHex(
                        Charsets.ISO_8859_1.encode(CharBuffer.wrap(new char[] { (char) c })).array()))
                                .toUpperCase());
            } else {
                if (useIso8859_1) {
                    // ISO 8859-1 with -128 offset
                    ByteBuffer encode = Charsets.ISO_8859_1.encode(new String(new char[] { (char) (c - 128) }));
                    print("\\S\\" + (char) encode.get());
                } else {
                    // The following code has not been tested (2012-04-25)
                    // Use UCS-2 or UCS-4

                    // TODO when multiple sequential characters should be encoded in UCS-2 or UCS-4, we don't really need to add all those \X0\ \X2\ and \X4\ chars
                    if (Character.isLowSurrogate(c)) {
                        throw new SerializerException("Unexpected low surrogate range char");
                    } else if (Character.isHighSurrogate(c)) {
                        // We need UCS-4, this is probably never happening
                        if (i + 1 < stringVal.length()) {
                            char low = stringVal.charAt(i + 1);
                            if (!Character.isLowSurrogate(low)) {
                                throw new SerializerException(
                                        "High surrogate char should be followed by char in low surrogate range");
                            }
                            try {
                                print("\\X4\\" + new String(Hex.encodeHex(Charset.forName("UTF-32")
                                        .encode(new String(new char[] { c, low })).array())).toUpperCase()
                                        + "\\X0\\");
                            } catch (UnsupportedCharsetException e) {
                                throw new SerializerException(e);
                            }
                            i++;
                        } else {
                            throw new SerializerException(
                                    "High surrogate char should be followed by char in low surrogate range, but end of string reached");
                        }
                    } else {
                        // UCS-2 will do
                        print("\\X2\\" + new String(Hex
                                .encodeHex(Charsets.UTF_16BE.encode(CharBuffer.wrap(new char[] { c })).array()))
                                        .toUpperCase()
                                + "\\X0\\");
                    }
                }
            }
        }
        print(SINGLE_QUOTE);
    } else if (val instanceof Enumerator) {
        print("." + val + ".");
    } else {
        print(val == null ? "$" : val.toString());
    }
}

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

public boolean verify(PasswordInfo passwordInfo, char[] password) {
    if (password == null) {
        return getPassword(passwordInfo.getRefId()) == null;
    } else {//from ww  w.j  av a 2 s.co m
        return getPassword(passwordInfo.getRefId()) != null
                && CharBuffer.wrap(password).equals(CharBuffer.wrap(getPassword(passwordInfo.getRefId())));
    }
}

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

/**
 * Send command to the server./*from   www  .  j  a va2 s  .c om*/
 * 
 * @param msg
 *            an unterminated command
 * @param expectedReplyItems 
 * @return the reply string.
 * @throws DeviceException
 */
public Object[] processImageRequest(String msg, int expectedReplyItems) throws DeviceException {
    if (expectedReplyItems < 2)
        throw new IllegalArgumentException("need at least two values for images (length definition and data)");
    String command = msg + '\r';
    Object reply[] = new Object[expectedReplyItems + 1];
    logger.debug(getName() + ": sent command: " + msg);
    synchronized (socketAccessLock) {
        try {
            if (!isConnected()) {
                throw new DeviceException("not connected");
            }
            cleanPipe();
            socketChannel.write(encoder.encode(CharBuffer.wrap(command)));

            ByteBuffer singleByte = ByteBuffer.allocate(1);

            StringBuilder sb = new StringBuilder();
            int argCounter = 0;
            while (argCounter < expectedReplyItems) {
                singleByte.clear();
                socketChannel.socket().setSoTimeout(socketTimeOut);
                socketChannel.configureBlocking(true);
                while (singleByte.position() == 0)
                    socketChannel.read(singleByte);
                singleByte.flip();
                String c = decoder.decode(singleByte).toString();
                logger.debug(c.toString());
                if (c.equals(",")) {
                    reply[argCounter] = sb.toString();
                    sb = new StringBuilder();
                    argCounter++;
                } else if (c.equals("\r")) {
                    throw new DeviceException(
                            "sendCommand: not enough data for image received - suspect an error");
                } else {
                    sb.append(c);
                }
            }

            int imageLength = Integer.parseInt(reply[expectedReplyItems - 1].toString());

            byte[] imageData = new byte[imageLength];
            ByteBuffer bybu = ByteBuffer.wrap(imageData);

            while (bybu.remaining() != 0) {
                socketChannel.read(bybu);
            }

            reply[expectedReplyItems] = imageData;
        } catch (SocketTimeoutException ex) {
            throw new DeviceException("sendCommand read timeout " + ex.getMessage(), ex);
        } catch (IOException ex) {
            // treat as fatal
            connected = false;
            throw new DeviceException("sendCommand: " + ex.getMessage(), ex);
        }
    }
    return reply;
}