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.hc.client5.http.impl.auth.CredSspScheme.java

private byte[] encodeUnicode(final String string) {
    if (string == null) {
        return EMPTYBUFFER;
    }//from   ww  w .  j a va  2s  .c  o  m
    return encodeUnicode(CharBuffer.wrap(string));
}

From source file:org.apache.hc.client5.http.impl.auth.CredSspScheme.java

private byte[] encodeUnicode(final char[] chars) {
    if (chars == null) {
        return EMPTYBUFFER;
    }//from  ww  w .  ja v  a2 s .c o  m
    return encodeUnicode(CharBuffer.wrap(chars));
}

From source file:org.apache.ctakes.ytex.uima.annotators.NegexAnnotator.java

private void checkNegation2(JCas aJCas, Sentence s, IdentifiedAnnotation ne, boolean negPoss) {
    // Sorter s = new Sorter();
    String sToReturn = "";
    String sScope = "";
    // String sentencePortion = "";
    // ArrayList sortedRules = null;

    String filler = "_";
    // boolean negationScope = true;

    // Sort the rules by length in descending order.
    // Rules need to be sorted so the longest rule is always tried to match
    // first.//  w w  w . j a v a  2s.  c  o  m
    // Some of the rules overlap so without sorting first shorter rules
    // (some of them POSSIBLE or PSEUDO)
    // would match before longer legitimate negation rules.
    //

    // There is efficiency issue here. It is better if rules are sorted by
    // the
    // calling program once and used without sorting in GennegEx.
    // sortedRules = this.rules;

    // Process the sentence and tag each matched negation
    // rule with correct negation rule tag.
    //
    // At the same time check for the phrase that we want to decide
    // the negation status for and
    // tag the phrase with [PHRASE] ... [PHRASE]
    // In both the negation rules and in the phrase replace white space
    // with "filler" string. (This could cause problems if the sentences
    // we study has "filler" on their own.)

    // Sentence needs one character in the beginning and end to match.
    // We remove the extra characters after processing.
    // vng String sentence = "." + sentenceString + ".";
    String sentence = "." + s.getCoveredText() + ".";

    // Tag the phrases we want to detect for negation.
    // Should happen before rule detection.
    // vng String phrase = phraseString;
    String phrase = ne.getCoveredText();
    Pattern pph = Pattern.compile(phrase.trim(), Pattern.CASE_INSENSITIVE);
    Matcher mph = pph.matcher(sentence);
    CharBuffer buf = CharBuffer.wrap(sentence.toCharArray());

    while (mph.find() == true) {
        sentence = mph.replaceAll(" [PHRASE]" + mph.group().trim().replaceAll(" ", filler) + "[PHRASE]");
    }

    for (NegexRule rule : this.listNegexRules) {
        Matcher m = rule.getPattern().matcher(sentence);
        while (m.find() == true) {
            sentence = m.replaceAll(
                    " " + rule.getTag() + m.group().trim().replaceAll(" ", filler) + rule.getTag() + " ");
        }
    }

    // Exchange the [PHRASE] ... [PHRASE] tags for [NEGATED] ... [NEGATED]
    // based of PREN, POST rules and if flag is set to true
    // then based on PREP and POSP, as well.

    // Because PRENEGATION [PREN} is checked first it takes precedent over
    // POSTNEGATION [POST].
    // Similarly POSTNEGATION [POST] takes precedent over POSSIBLE
    // PRENEGATION [PREP]
    // and [PREP] takes precedent over POSSIBLE POSTNEGATION [POSP].

    Pattern pSpace = Pattern.compile("[\\s+]");
    String[] sentenceTokens = pSpace.split(sentence);
    StringBuilder sb = new StringBuilder();

    // Check for [PREN]
    for (int i = 0; i < sentenceTokens.length; i++) {
        sb.append(" " + sentenceTokens[i].trim());
        if (sentenceTokens[i].trim().startsWith("[PREN]")) {

            for (int j = i + 1; j < sentenceTokens.length; j++) {
                if (sentenceTokens[j].trim().startsWith("[CONJ]")
                        || sentenceTokens[j].trim().startsWith("[PSEU]")
                        || sentenceTokens[j].trim().startsWith("[POST]")
                        || sentenceTokens[j].trim().startsWith("[PREP]")
                        || sentenceTokens[j].trim().startsWith("[POSP]")) {
                    break;
                }

                if (sentenceTokens[j].trim().startsWith("[PHRASE]")) {
                    sentenceTokens[j] = sentenceTokens[j].trim().replaceAll("\\[PHRASE\\]", "[NEGATED]");
                }
            }
        }
    }

    sentence = sb.toString();
    pSpace = Pattern.compile("[\\s+]");
    sentenceTokens = pSpace.split(sentence);
    StringBuilder sb2 = new StringBuilder();

    // Check for [POST]
    for (int i = sentenceTokens.length - 1; i > 0; i--) {
        sb2.insert(0, sentenceTokens[i] + " ");
        if (sentenceTokens[i].trim().startsWith("[POST]")) {
            for (int j = i - 1; j > 0; j--) {
                if (sentenceTokens[j].trim().startsWith("[CONJ]")
                        || sentenceTokens[j].trim().startsWith("[PSEU]")
                        || sentenceTokens[j].trim().startsWith("[PREN]")
                        || sentenceTokens[j].trim().startsWith("[PREP]")
                        || sentenceTokens[j].trim().startsWith("[POSP]")) {
                    break;
                }

                if (sentenceTokens[j].trim().startsWith("[PHRASE]")) {
                    sentenceTokens[j] = sentenceTokens[j].trim().replaceAll("\\[PHRASE\\]", "[NEGATED]");
                }
            }
        }
    }
    sentence = sb2.toString();

    // If POSSIBLE negation is detected as negation.
    // negatePossible being set to "true" then check for [PREP] and [POSP].
    if (negPoss == true) {
        pSpace = Pattern.compile("[\\s+]");
        sentenceTokens = pSpace.split(sentence);

        StringBuilder sb3 = new StringBuilder();

        // Check for [PREP]
        for (int i = 0; i < sentenceTokens.length; i++) {
            sb3.append(" " + sentenceTokens[i].trim());
            if (sentenceTokens[i].trim().startsWith("[PREP]")) {

                for (int j = i + 1; j < sentenceTokens.length; j++) {
                    if (sentenceTokens[j].trim().startsWith("[CONJ]")
                            || sentenceTokens[j].trim().startsWith("[PSEU]")
                            || sentenceTokens[j].trim().startsWith("[POST]")
                            || sentenceTokens[j].trim().startsWith("[PREN]")
                            || sentenceTokens[j].trim().startsWith("[POSP]")) {
                        break;
                    }

                    if (sentenceTokens[j].trim().startsWith("[PHRASE]")) {
                        sentenceTokens[j] = sentenceTokens[j].trim().replaceAll("\\[PHRASE\\]", "[POSSIBLE]");
                    }
                }
            }
        }
        sentence = sb3.toString();
        pSpace = Pattern.compile("[\\s+]");
        sentenceTokens = pSpace.split(sentence);
        StringBuilder sb4 = new StringBuilder();

        // Check for [POSP]
        for (int i = sentenceTokens.length - 1; i > 0; i--) {
            sb4.insert(0, sentenceTokens[i] + " ");
            if (sentenceTokens[i].trim().startsWith("[POSP]")) {
                for (int j = i - 1; j > 0; j--) {
                    if (sentenceTokens[j].trim().startsWith("[CONJ]")
                            || sentenceTokens[j].trim().startsWith("[PSEU]")
                            || sentenceTokens[j].trim().startsWith("[PREN]")
                            || sentenceTokens[j].trim().startsWith("[PREP]")
                            || sentenceTokens[j].trim().startsWith("[POST]")) {
                        break;
                    }

                    if (sentenceTokens[j].trim().startsWith("[PHRASE]")) {
                        sentenceTokens[j] = sentenceTokens[j].trim().replaceAll("\\[PHRASE\\]", "[POSSIBLE]");
                    }
                }
            }
        }
        sentence = sb4.toString();
    }

    // Remove the filler character we used.
    sentence = sentence.replaceAll(filler, " ");

    // Remove the extra periods at the beginning
    // and end of the sentence.
    sentence = sentence.substring(0, sentence.trim().lastIndexOf('.'));
    sentence = sentence.replaceFirst(".", "");

    // Get the scope of the negation for PREN and PREP
    if (sentence.contains("[PREN]") || sentence.contains("[PREP]")) {
        int startOffset = sentence.indexOf("[PREN]");
        if (startOffset == -1) {
            startOffset = sentence.indexOf("[PREP]");
        }

        int endOffset = sentence.indexOf("[CONJ]");
        if (endOffset == -1) {
            endOffset = sentence.indexOf("[PSEU]");
        }
        if (endOffset == -1) {
            endOffset = sentence.indexOf("[POST]");
        }
        if (endOffset == -1) {
            endOffset = sentence.indexOf("[POSP]");
        }
        if (endOffset == -1 || endOffset < startOffset) {
            endOffset = sentence.length() - 1;
        }
        sScope = sentence.substring(startOffset, endOffset + 1);
    }

    // Get the scope of the negation for POST and POSP
    if (sentence.contains("[POST]") || sentence.contains("[POSP]")) {
        int endOffset = sentence.lastIndexOf("[POST]");
        if (endOffset == -1) {
            endOffset = sentence.lastIndexOf("[POSP]");
        }

        int startOffset = sentence.lastIndexOf("[CONJ]");
        if (startOffset == -1) {
            startOffset = sentence.lastIndexOf("[PSEU]");
        }
        if (startOffset == -1) {
            startOffset = sentence.lastIndexOf("[PREN]");
        }
        if (startOffset == -1) {
            startOffset = sentence.lastIndexOf("[PREP]");
        }
        if (startOffset == -1) {
            startOffset = 0;
        }
        sScope = sentence.substring(startOffset, endOffset);
    }

    // Classify to: negated/possible/affirmed
    if (sentence.contains("[NEGATED]")) {
        sentence = sentence + "\t" + "negated" + "\t" + sScope;
    } else if (sentence.contains("[POSSIBLE]")) {
        sentence = sentence + "\t" + "possible" + "\t" + sScope;
    } else {
        sentence = sentence + "\t" + "affirmed" + "\t" + sScope;
    }

    sToReturn = sentence;
    System.out.println(sToReturn);
}

From source file:openblocks.yacodeblocks.DeviceReplCommController.java

private ImageIcon generateQRCode(String code) {
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetEncoder encoder = charset.newEncoder();
    byte[] b = null;
    try {// www. j av a 2 s . c o  m
        // Convert a string to ISO-8859-1 bytes in a ByteBuffer
        ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(code));
        b = bbuf.array();
    } catch (CharacterCodingException e) {
        System.out.println(e.getMessage());
    }

    String data = null;
    try {
        data = new String(b, "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        System.out.println(e.getMessage());
    }

    // get a byte matrix for the data
    BitMatrix matrix = null;
    int h = 200;
    int w = 200;
    com.google.zxing.Writer writer = new QRCodeWriter();
    try {
        matrix = writer.encode(data, com.google.zxing.BarcodeFormat.QR_CODE, w, h);
        ImageIcon qrcode = new ImageIcon();
        qrcode.setImage(MatrixToImageWriter.toBufferedImage(matrix));
        return qrcode;
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return null;
}

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

/**
 * Sends a message to a specific user. The id of the WebSocket connection is used to contact the desired user.
 * //from w ww .  j  ava2  s . com
 * @param id
 *            - ID of WebSocket connection that will be sent a message
 * @param msg
 *            - The message the user will be receiving
 */
public void sendMessage(GeppettoMessageInbound visitor, String msg) {
    try {
        long startTime = System.currentTimeMillis();
        CharBuffer buffer = CharBuffer.wrap(msg);
        visitor.getWsOutbound().writeTextMessage(buffer);
        String debug = ((long) System.currentTimeMillis() - startTime) + "ms were spent sending a message of "
                + msg.length() / 1024 + "KB to the client";
        _logger.info(debug);
    } catch (IOException ignore) {
        _logger.error("Unable to communicate with client " + ignore.getMessage());
        this.removeConnection(visitor);
    }
}

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

/**
 * Sends a message to a specific user. The id of the WebSocket connection is
 * used to contact the desired user.// www .j a v  a  2s.  c  o m
 * 
 * @param id
 *            - ID of WebSocket connection that will be sent a message
 * @param msg
 *            - The message the user will be receiving
 */
public void sendMessage(GeppettoMessageInbound visitor, String msg) {
    try {
        long startTime = System.currentTimeMillis();
        CharBuffer buffer = CharBuffer.wrap(msg);
        visitor.getWsOutbound().writeTextMessage(buffer);
        String debug = ((long) System.currentTimeMillis() - startTime) + "ms were spent sending a message of "
                + msg.length() / 1024 + "KB to the client";
        _logger.info(debug);
    } catch (IOException ignore) {
        _logger.error("Unable to communicate with client " + ignore.getMessage());
    }
}

From source file:org.owasp.webgoat.lessons.Encoding.java

/**
 * Description of the Method//  w w w.j  av  a2  s . c om
 * 
 * @param str
 *            Description of the Parameter
 * @return Description of the Return Value
 */

public static String unicodeEncode(String str) {
    // FIXME: TOTALLY EXPERIMENTAL
    try {
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetEncoder encoder = charset.newEncoder();
        ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(str));
        return (new String(bbuf.array()));
    } catch (Exception e) {
        return ("Encoding problem");
    }
}

From source file:com.silentcircle.silenttext.application.SilentTextApplication.java

public CharSequence getFullJIDForUsername(CharSequence username) {
    CharArrayWriter out = new CharArrayWriter();
    boolean shouldAppend = true;
    for (int i = 0; i < username.length(); i++) {
        char c = username.charAt(i);
        out.append(username.charAt(i));//from  ww w .  j ava 2  s.  c o m
        if (c == '@') {
            shouldAppend = false;
        }
    }
    if (shouldAppend) {
        out.append('@');
        out.append(getDomain());
    }
    return CharBuffer.wrap(out.toCharArray());
}

From source file:com.silentcircle.silenttext.application.SilentTextApplication.java

@Override
public Session getSession() {
    try {//from  w  w w. j a  va2 s .  c  o  m
        Credential credential = getServer("broker").getCredential();
        AbstractHTTPClient http = createHTTPClient();
        String url = getAPIURL();
        CharBuffer apiKey = CharBuffer.wrap(credential.getPassword());
        CharBuffer deviceID = CharBuffer.wrap(credential.getUsername());
        if (http == null || url == null) {
            throw new NullPointerException();
        }
        return new AuthenticatedSessionClient(http, url, apiKey, deviceID);
    } catch (NullPointerException exception) {
        return getSharedSession();
    }
}

From source file:com.silentcircle.silenttext.application.SilentTextApplication.java

public CharSequence getSharedDataFromKeyManagerAsCharSequence(String id) {
    char[] array = getSharedDataFromKeyManagerAsCharArray(id);
    return array == null ? null : CharBuffer.wrap(array);
}