Example #1
1
 /**
  * construct a HTTP-Redirect-Response
  *
  * @param dest the destination to redirect to
  */
 public void setRedirectTo(String dest, String CookieDomain) {
   StringBuffer cntnt =
       new StringBuffer(
           "<html><head><title>redirection</title><head><body>Redirected to <a href=\"");
   cntnt.append(dest);
   cntnt.append("\">");
   cntnt.append(dest);
   cntnt.append("</a>");
   cntnt.append("</body></html>");
   int len = cntnt.length();
   StringBuffer sb = new StringBuffer(isHTTP11 ? "HTTP/1.1" : "HTTP/1.0");
   sb.append(REDIRECT_HDR);
   sb.append(Server.srv.DEFAULT_CHARSET);
   sb.append("\r\nLocation: ");
   sb.append(dest);
   sb.append("\r\nContent-Length: ");
   sb.append(len);
   sb = appendCookie(sb, CookieDomain);
   sb.append("\r\n\r\n");
   if ("iso-8859-1".equals(Server.srv.DEFAULT_CHARSET)) {
     sb.append(cntnt);
     sb.trimToSize();
     prepareForSending(CharBuffer.wrap(sb.toString()));
   } else {
     CharBuffer hdrChar = CharBuffer.wrap(sb.toString());
     cntnt.trimToSize();
     prepareForSending(hdrChar, CharBuffer.wrap(cntnt));
   }
   isRedirect = true;
 }
Example #2
1
 public void setContent(byte[] cntnt) throws Exception {
   StringBuffer sb = new StringBuffer(isHTTP11 ? "HTTP/1.1" : "HTTP/1.0");
   sb.append(OK_HDR);
   sb.append("Content-Type: ");
   sb.append(contentType);
   if (!isHTTP11 || !keepAlive || isMessages) {
     sb.append("\r\nConnection: close\r\nProxy-Connection: close");
   } else {
     sb.append("\r\nConnection: Keep-Alive\r\nProxy-Connection: Keep-Alive");
     sb.append("\r\nContent-Length: ");
     sb.append(cntnt.length);
   }
   sb.append("\r\n\r\n");
   sb.trimToSize();
   CharBuffer cb = CharBuffer.wrap(sb.toString());
   ByteBuffer tempBuffer;
   try {
     tempBuffer = Charset.forName("iso-8859-1").newEncoder().encode(cb);
   } catch (CharacterCodingException cce) {
     Server.debug(this, "prepareForSending: ", cce, Server.MSG_ERROR, Server.LVL_MINOR);
     try {
       tempBuffer = ByteBuffer.wrap(cb.toString().getBytes(Server.srv.DEFAULT_CHARSET));
     } catch (Exception e) {
       Server.debug(this, "prepareForSending: ", e, Server.MSG_ERROR, Server.LVL_MAJOR);
       throw e;
     }
   }
   this.buf = ByteBuffer.allocate(tempBuffer.capacity() + cntnt.length);
   this.buf.put(tempBuffer.array());
   this.buf.put(cntnt);
   this.buf.flip();
 }
  /**
   * Write String using specified encoding
   *
   * <p>When this is called multiple times, all but the last value has a trailing null
   *
   * @param encoder
   * @param next
   * @param i
   * @param noOfValues
   * @return
   * @throws CharacterCodingException
   */
  private ByteBuffer writeString(CharsetEncoder encoder, String next, int i, int noOfValues)
      throws CharacterCodingException {

    ByteBuffer bb;
    if ((i + 1) == noOfValues) {
      bb = encoder.encode(CharBuffer.wrap(next));
    } else {
      bb = encoder.encode(CharBuffer.wrap(next + '\0'));
    }
    bb.rewind();
    return bb;
  }
  public void testAppendableInterface() {
    CharTermAttributeImpl t = new CharTermAttributeImpl();
    Formatter formatter = new Formatter(t, Locale.ROOT);
    formatter.format("%d", 1234);
    assertEquals("1234", t.toString());
    formatter.format("%d", 5678);
    assertEquals("12345678", t.toString());
    t.append('9');
    assertEquals("123456789", t.toString());
    t.append((CharSequence) "0");
    assertEquals("1234567890", t.toString());
    t.append((CharSequence) "0123456789", 1, 3);
    assertEquals("123456789012", t.toString());
    t.append((CharSequence) CharBuffer.wrap("0123456789".toCharArray()), 3, 5);
    assertEquals("12345678901234", t.toString());
    t.append((CharSequence) t);
    assertEquals("1234567890123412345678901234", t.toString());
    t.append((CharSequence) new StringBuilder("0123456789"), 5, 7);
    assertEquals("123456789012341234567890123456", t.toString());
    t.append((CharSequence) new StringBuffer(t));
    assertEquals("123456789012341234567890123456123456789012341234567890123456", t.toString());
    // very wierd, to test if a subSlice is wrapped correct :)
    CharBuffer buf = CharBuffer.wrap("0123456789".toCharArray(), 3, 5);
    assertEquals("34567", buf.toString());
    t.setEmpty().append((CharSequence) buf, 1, 2);
    assertEquals("4", t.toString());
    CharTermAttribute t2 = new CharTermAttributeImpl();
    t2.append("test");
    t.append((CharSequence) t2);
    assertEquals("4test", t.toString());
    t.append((CharSequence) t2, 1, 2);
    assertEquals("4teste", t.toString());

    try {
      t.append((CharSequence) t2, 1, 5);
      fail("Should throw IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException iobe) {
    }

    try {
      t.append((CharSequence) t2, 1, 0);
      fail("Should throw IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException iobe) {
    }

    t.append((CharSequence) null);
    assertEquals("4testenull", t.toString());
  }
Example #5
0
 public char[] encode(byte[] data, String encoding) throws IOException {
   if (encoding == null) {
     encoding = DEFAULT_ENCODING;
   }
   if (!Charset.isSupported(encoding)) throw new IOException("Unsupported encoding " + encoding);
   Charset charset = Charset.forName(encoding);
   CharsetDecoder cd =
       charset
           .newDecoder()
           .onMalformedInput(CodingErrorAction.REPLACE)
           .onUnmappableCharacter(CodingErrorAction.REPLACE);
   int en = (int) (cd.maxCharsPerByte() * data.length);
   char[] ca = new char[en];
   ByteBuffer bb = ByteBuffer.wrap(data);
   CharBuffer cb = CharBuffer.wrap(ca);
   CoderResult cr = cd.decode(bb, cb, true);
   if (!cr.isUnderflow()) {
     cr.throwException();
   }
   cr = cd.flush(cb);
   if (!cr.isUnderflow()) {
     cr.throwException();
   }
   return trim(ca, cb.position());
 }
Example #6
0
    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {

      char[] result;
      Reader in;

      if (encoding != null) {
        in = new InputStreamReader(new FileInputStream(this.f), encoding);
      } else {
        in = new InputStreamReader(new FileInputStream(this.f));
      }
      int red = 0;
      try {
        int len = (int) this.f.length();
        if (len == 0) len++; // len - red would be 0 while reading from the stream
        result = new char[len + 1];
        int rv;
        while ((rv = in.read(result, red, len - red)) >= 0) {
          red += rv;
          // In case the filter enlarged the file
          if (red == len) {
            char[] _tmp = new char[2 * len];
            System.arraycopy(result, 0, _tmp, 0, len);
            result = _tmp;
            len = result.length;
          }
        }
      } finally {
        in.close();
      }
      result[red++] = '\n'; // NOI18N
      CharSequence buffer = CharBuffer.wrap(result, 0, red);
      return buffer;
    }
Example #7
0
 public void writeMessage(int result, String actionType, String message) {
   StringBuffer buffer = new StringBuffer();
   if ("RECEIVE".equals(actionType)) {
     buffer.append(message);
   } else {
     buffer
         .append("{")
         .append("\"result\" : ")
         .append(result)
         .append(", ")
         .append("\"actionType\" : \"")
         .append(actionType)
         .append("\", ")
         .append("\"message\" : \"")
         .append(message)
         .append("\"}");
   }
   //		logger.debug("Write Message {}", buffer.toString());
   try {
     this.getWsOutbound().writeTextMessage(CharBuffer.wrap(buffer.toString()));
     this.getWsOutbound().flush();
   } catch (IOException e) {
     logger.debug(e.getMessage(), e);
   }
 }
Example #8
0
 public static void saveFile(File file, String content, String charsetName) {
   // if (Utils.isEmpty(fileName) || Utils.isEmpty(content)) {
   // return;
   // }
   // logger.info("save file:" + fileName + " charset:" + charsetName);
   file.getParentFile().mkdirs();
   Charset cs;
   if (null == charsetName || "".equals(charsetName)) {
     cs = Charset.defaultCharset();
   } else {
     cs = Charset.forName(charsetName);
   }
   CharsetEncoder encoder = cs.newEncoder();
   FileOutputStream os = null;
   FileChannel out = null;
   try {
     os = new FileOutputStream(file);
     out = os.getChannel();
     out.write(encoder.encode(CharBuffer.wrap(content)));
   } catch (CharacterCodingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     close(out);
     close(os);
   }
 }
Example #9
0
 public static int encode(
     final CharsetEncoder ce,
     final char[] ca,
     final int off,
     final int len,
     final byte[] targetArray) {
   if (len == 0) {
     return 0;
   }
   if (ce instanceof ArrayEncoder) {
     return ((ArrayEncoder) ce).encode(ca, off, len, targetArray);
   } else {
     ce.reset();
     ByteBuffer bb = ByteBuffer.wrap(targetArray);
     CharBuffer cb = CharBuffer.wrap(ca, off, len);
     try {
       CoderResult cr = ce.encode(cb, bb, true);
       if (!cr.isUnderflow()) {
         cr.throwException();
       }
       cr = ce.flush(bb);
       if (!cr.isUnderflow()) {
         cr.throwException();
       }
     } catch (CharacterCodingException x) {
       throw new Error(x);
     }
     return bb.position();
   }
 }
Example #10
0
    byte[] encode(char[] ca, int off, int len) {

      int en = (int) (ce.maxBytesPerChar() * len);

      byte[] ba = new byte[en];

      if (len == 0) return ba;

      ce.reset();

      ByteBuffer bb = ByteBuffer.wrap(ba);

      CharBuffer cb = CharBuffer.wrap(ca, off, len);

      try {

        CoderResult cr = ce.encode(cb, bb, true);

        if (!cr.isUnderflow()) cr.throwException();

        cr = ce.flush(bb);

        if (!cr.isUnderflow()) cr.throwException();

      } catch (CharacterCodingException x) {

        // Substitution is always enabled,

        // so this shouldn't happen

        throw new Error(x);
      }

      return trim(ba, bb.position());
    }
Example #11
0
    char[] decode(byte[] ba, int off, int len) {

      int en = (int) (cd.maxCharsPerByte() * len);

      char[] ca = new char[en];

      if (len == 0) return ca;

      cd.reset();

      ByteBuffer bb = ByteBuffer.wrap(ba, off, len);

      CharBuffer cb = CharBuffer.wrap(ca);

      try {

        CoderResult cr = cd.decode(bb, cb, true);

        if (!cr.isUnderflow()) cr.throwException();

        cr = cd.flush(cb);

        if (!cr.isUnderflow()) cr.throwException();

      } catch (CharacterCodingException x) {

        // Substitution is always enabled,

        // so this shouldn't happen

        throw new Error(x);
      }

      return trim(ca, cb.position());
    }
Example #12
0
  private static void writeEntry(
      OutputStream os, Attributes.Name name, String value, CharsetEncoder encoder, ByteBuffer bBuf)
      throws IOException {
    byte[] out = name.getBytes();
    if (out.length > LINE_LENGTH_LIMIT) {
      throw new IOException(
          Messages.getString(
              "archive.33", name, Integer.valueOf(LINE_LENGTH_LIMIT))); // $NON-NLS-1$
    }

    os.write(out);
    os.write(VALUE_SEPARATOR);

    encoder.reset();
    bBuf.clear().limit(LINE_LENGTH_LIMIT - out.length - 2);

    CharBuffer cBuf = CharBuffer.wrap(value);
    CoderResult r;

    while (true) {
      r = encoder.encode(cBuf, bBuf, true);
      if (CoderResult.UNDERFLOW == r) {
        r = encoder.flush(bBuf);
      }
      os.write(bBuf.array(), bBuf.arrayOffset(), bBuf.position());
      os.write(LINE_SEPARATOR);
      if (CoderResult.UNDERFLOW == r) {
        break;
      }
      os.write(' ');
      bBuf.clear().limit(LINE_LENGTH_LIMIT - 1);
    }
  }
Example #13
0
 @SuppressFBWarnings("SUA_SUSPICIOUS_UNINITIALIZED_ARRAY")
 public static String decode(
     final CharsetDecoder cd, final byte[] ba, final int off, final int len) {
   if (len == 0) {
     return "";
   }
   int en = (int) (len * (double) cd.maxCharsPerByte());
   char[] ca = Arrays.getCharsTmp(en);
   if (cd instanceof ArrayDecoder) {
     int clen = ((ArrayDecoder) cd).decode(ba, off, len, ca);
     return new String(ca, 0, clen);
   }
   cd.reset();
   ByteBuffer bb = ByteBuffer.wrap(ba, off, len);
   CharBuffer cb = CharBuffer.wrap(ca);
   try {
     CoderResult cr = cd.decode(bb, cb, true);
     if (!cr.isUnderflow()) {
       cr.throwException();
     }
     cr = cd.flush(cb);
     if (!cr.isUnderflow()) {
       cr.throwException();
     }
   } catch (CharacterCodingException x) {
     throw new Error(x);
   }
   return new String(ca, 0, cb.position());
 }
Example #14
0
  // Writes a C string and expands the frame if necessary
  // FIXME: Property strings containing nul ('\0') characters will corrupt the frame when they are
  // written.
  //        Figure out how to throw an exception here if any nul chars are encountered
  private static ByteBuffer writeCString(ByteBuffer frame, String string) {
    Byte b = propertyAbbreviations.get(string);
    if (b != null) {
      if (frame.remaining() < 2)
        frame = ByteBuffer.allocate(frame.capacity() << 1).put((ByteBuffer) frame.rewind());
      frame.put(b);
      frame.put((byte) 0);
    } else {
      CharsetEncoder cStringEncoder = cStringCharset.newEncoder();

      CharBuffer chars = CharBuffer.wrap(string);
      for (int size = frame.capacity(); ; cStringEncoder.flush(frame)) {
        cStringEncoder.reset();
        if (cStringEncoder.encode(chars, frame, true) == CoderResult.OVERFLOW) {
          // debug output
          // System.out.println("overflow, reallocating to size " + (size << 1) + " (printing \"" +
          // string + "\")");
          frame = ByteBuffer.allocate(size = (size << 1)).put((ByteBuffer) frame.rewind());
        } else break;
      }
      cStringEncoder.flush(frame);
      frame.put((byte) 0);
    }
    return frame;
  }
Example #15
0
 static byte[] encode(char[] cc, Charset cs, boolean testDirect, Time t) throws Exception {
   ByteBuffer bbf;
   CharBuffer cbf;
   CharsetEncoder enc = cs.newEncoder();
   String csn = cs.name();
   if (testDirect) {
     bbf = ByteBuffer.allocateDirect(cc.length * 4);
     cbf = ByteBuffer.allocateDirect(cc.length * 2).asCharBuffer();
     cbf.put(cc).flip();
   } else {
     bbf = ByteBuffer.allocate(cc.length * 4);
     cbf = CharBuffer.wrap(cc);
   }
   CoderResult cr = null;
   long t1 = System.nanoTime() / 1000;
   for (int i = 0; i < iteration; i++) {
     cbf.rewind();
     bbf.clear();
     enc.reset();
     cr = enc.encode(cbf, bbf, true);
   }
   long t2 = System.nanoTime() / 1000;
   t.t = (t2 - t1) / iteration;
   if (cr != CoderResult.UNDERFLOW) {
     System.out.println("ENC-----------------");
     int pos = cbf.position();
     System.out.printf("  cr=%s, cbf.pos=%d, cc[pos]=%x%n", cr.toString(), pos, cc[pos] & 0xffff);
     throw new RuntimeException("Encoding err: " + csn);
   }
   byte[] bb = new byte[bbf.position()];
   bbf.flip();
   bbf.get(bb);
   return bb;
 }
Example #16
0
 /**
  * Adds an authentication header for basic authentication
  *
  * @param con the connection
  * @throws OsmTransferException thrown if something went wrong. Check for nested exceptions
  */
 protected void addBasicAuthorizationHeader(HttpURLConnection con) throws OsmTransferException {
   CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
   CredentialsManagerResponse response;
   String token;
   try {
     synchronized (CredentialsManagerFactory.getCredentialManager()) {
       response =
           CredentialsManagerFactory.getCredentialManager()
               .getCredentials(
                   RequestorType.SERVER,
                   false /* don't know yet whether the credentials will succeed */);
     }
   } catch (CredentialsManagerException e) {
     throw new OsmTransferException(e);
   }
   if (response == null) {
     token = ":";
   } else if (response.isCanceled()) {
     cancel = true;
     return;
   } else {
     String username = response.getUsername() == null ? "" : response.getUsername();
     String password =
         response.getPassword() == null ? "" : String.valueOf(response.getPassword());
     token = username + ":" + password;
     try {
       ByteBuffer bytes = encoder.encode(CharBuffer.wrap(token));
       con.addRequestProperty("Authorization", "Basic " + Base64.encode(bytes));
     } catch (CharacterCodingException e) {
       throw new OsmTransferException(e);
     }
   }
 }
Example #17
0
 public void flush() throws IOException {
   // Log.i("PackageManager", "flush mPos=" + mPos);
   if (mPos > 0) {
     if (mOutputStream != null) {
       CharBuffer charBuffer = CharBuffer.wrap(mText, 0, mPos);
       CoderResult result = mCharset.encode(charBuffer, mBytes, true);
       while (true) {
         if (result.isError()) {
           throw new IOException(result.toString());
         } else if (result.isOverflow()) {
           flushBytes();
           result = mCharset.encode(charBuffer, mBytes, true);
           continue;
         }
         break;
       }
       flushBytes();
       mOutputStream.flush();
     } else {
       mWriter.write(mText, 0, mPos);
       mWriter.flush();
     }
     mPos = 0;
   }
 }
Example #18
0
  /**
   * Find potential matches for a query
   *
   * @param query The query string
   * @return Search results object
   */
  public EdictSearchResults search(String query) {

    CharsetEncoder encoder = this.dictionary.getCharacterHandler().getCharsetEncoder();
    ByteBuffer encodedQuery = null;
    try {
      encodedQuery = encoder.encode(CharBuffer.wrap(query));
    } catch (CharacterCodingException e) {
      // If we can't encode it we can't search for it here
      // TODO some sort of exception
      return null;
    }

    try {

      EdictComparator comparator = this.dictionary.comparator();

      int start = 0;
      int end = this.dictionary.getIndexSize() - 1;
      int match = -1;

      do {
        int current = start + ((end - start) / 2);

        int character =
            comparator.compareLeft(encodedQuery, this.dictionary.getIndexEntry(current));
        if (character > 0) {
          start = current + 1;
        } else if (character < 0) {
          end = current - 1;
        } else {
          match = current;
        }
      } while ((start <= end) && (match == -1));

      if (match != -1) {
        end = this.dictionary.getIndexSize() - 1;
        int min = match;
        int max = match;
        while ((min > 0)
            && (comparator.compareLeft(encodedQuery, this.dictionary.getIndexEntry(min - 1))
                == 0)) {
          min--;
        }
        while ((max < end)
            && (comparator.compareLeft(encodedQuery, this.dictionary.getIndexEntry(max + 1))
                == 0)) {
          max++;
        }

        return new EdictSearchResults(this.dictionary, encodedQuery, min, max);
      }

    } catch (CharacterCodingException e) {
      // Shouldn't happen. If any entries of the dictionary were broken, the term index should omit
      // all terms from that entry
      e.printStackTrace();
    }

    return new EdictSearchResults(this.dictionary, encodedQuery, null, null);
  }
Example #19
0
    @Override
    protected void onTextMessage(CharBuffer message) throws IOException {
      String temp = message.toString();
      JSONObject json = (JSONObject) JSONSerializer.toJSON(temp);

      String type = json.getString("type").toLowerCase().replaceAll(" ", "");
      String location = json.getString("location");
      String lat = json.getString("lat");
      String lng = json.getString("lng");
      String radius = json.getString("radius");
      String keywords = json.getString("keywords");

      String result = null;
      try {
        if (type.equals("overview")) result = getOverViewData(location, lat, lng, radius, keywords);
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        JSONObject jsonResult = new JSONObject();
        jsonResult.put("error", "true");
        result = jsonResult.toString();
      }
      if (result == null || result.equals("")) {
        JSONObject jsonResult = new JSONObject();
        jsonResult.put("error", "true");
        result = jsonResult.toString();
      }
      Charset charset = Charset.forName("ISO-8859-1");
      CharsetDecoder decoder = charset.newDecoder();
      CharsetEncoder encoder = charset.newEncoder();
      CharBuffer uCharBuffer = CharBuffer.wrap(result);
      ByteBuffer bbuf = encoder.encode(uCharBuffer);
      CharBuffer cbuf = decoder.decode(bbuf);
      getWsOutbound().writeTextMessage(cbuf);
    }
Example #20
0
 public void setInputLineSeparator(ThreadContext tc, String sep) {
   try {
     linesep = enc.charset().newEncoder().encode(CharBuffer.wrap(sep)).array();
   } catch (IOException e) {
     throw ExceptionHandling.dieInternal(tc, e);
   }
 }
 static byte[] encode(Charset cs, char[] ca, int off, int len) {
   CharsetEncoder ce = cs.newEncoder();
   int en = scale(len, ce.maxBytesPerChar());
   byte[] ba = new byte[en];
   if (len == 0) return ba;
   boolean isTrusted = false;
   if (System.getSecurityManager() != null) {
     if (!(isTrusted = (cs.getClass().getClassLoader0() == null))) {
       ca = Arrays.copyOfRange(ca, off, off + len);
       off = 0;
     }
   }
   ce.onMalformedInput(CodingErrorAction.REPLACE)
       .onUnmappableCharacter(CodingErrorAction.REPLACE)
       .reset();
   if (ce instanceof ArrayEncoder) {
     int blen = ((ArrayEncoder) ce).encode(ca, off, len, ba);
     return safeTrim(ba, blen, cs, isTrusted);
   } else {
     ByteBuffer bb = ByteBuffer.wrap(ba);
     CharBuffer cb = CharBuffer.wrap(ca, off, len);
     try {
       CoderResult cr = ce.encode(cb, bb, true);
       if (!cr.isUnderflow()) cr.throwException();
       cr = ce.flush(bb);
       if (!cr.isUnderflow()) cr.throwException();
     } catch (CharacterCodingException x) {
       throw new Error(x);
     }
     return safeTrim(ba, bb.position(), cs, isTrusted);
   }
 }
  /**
   * Creates a string in a specfied character set.
   *
   * @param value String constant, must not be null
   * @param charsetName Name of the character set, may be null
   * @param collation Collation, may be null
   * @throws IllegalCharsetNameException If the given charset name is illegal
   * @throws UnsupportedCharsetException If no support for the named charset is available in this
   *     instance of the Java virtual machine
   * @throws RuntimeException If the given value cannot be represented in the given charset
   */
  public NlsString(String value, String charsetName, SqlCollation collation) {
    assert value != null;
    if (null != charsetName) {
      charsetName = charsetName.toUpperCase();
      this.charsetName = charsetName;
      String javaCharsetName = SqlUtil.translateCharacterSetName(charsetName);
      if (javaCharsetName == null) {
        throw new UnsupportedCharsetException(charsetName);
      }
      this.charset = Charset.forName(javaCharsetName);
      CharsetEncoder encoder = charset.newEncoder();

      // dry run to see if encoding hits any problems
      try {
        encoder.encode(CharBuffer.wrap(value));
      } catch (CharacterCodingException ex) {
        throw RESOURCE.charsetEncoding(value, javaCharsetName).ex();
      }
    } else {
      this.charsetName = null;
      this.charset = null;
    }
    this.collation = collation;
    this.value = value;
  }
Example #23
0
    public CharBuffer getCharContent(boolean ignoreEncodingErrors) throws IOException {
      Reader r = openReader(ignoreEncodingErrors);
      try {
        int red = 0, rv;

        int len = (int) this.getSize();
        char[] result = new char[len + 1];
        while ((rv = r.read(result, red, len - red)) > 0 && (red = red + rv) < len) ;

        int j = 0;
        for (int i = 0; i < red; i++) {
          if (result[i] == '\r') { // NOI18N
            if (i + 1 >= red || result[i + 1] != '\n') { // NOI18N
              result[j++] = '\n'; // NOI18N
            }
          } else {
            result[j++] = result[i];
          }
        }
        result[j] = '\n'; // NOI18N
        return CharBuffer.wrap(result, 0, j);
      } finally {
        r.close();
      }
    }
  public void testAppendableInterfaceWithLongSequences() {
    CharTermAttributeImpl t = new CharTermAttributeImpl();
    t.append((CharSequence) "01234567890123456789012345678901234567890123456789");
    t.append(
        (CharSequence)
            CharBuffer.wrap("01234567890123456789012345678901234567890123456789".toCharArray()),
        3,
        50);
    assertEquals(
        "0123456789012345678901234567890123456789012345678934567890123456789012345678901234567890123456789",
        t.toString());
    t.setEmpty().append((CharSequence) new StringBuilder("01234567890123456789"), 5, 17);
    assertEquals((CharSequence) "567890123456", t.toString());
    t.append(new StringBuffer(t));
    assertEquals((CharSequence) "567890123456567890123456", t.toString());
    // very wierd, to test if a subSlice is wrapped correct :)
    CharBuffer buf = CharBuffer.wrap("012345678901234567890123456789".toCharArray(), 3, 15);
    assertEquals("345678901234567", buf.toString());
    t.setEmpty().append(buf, 1, 14);
    assertEquals("4567890123456", t.toString());

    // finally use a completely custom CharSequence that is not catched by instanceof checks
    final String longTestString = "012345678901234567890123456789";
    t.append(
        new CharSequence() {
          @Override
          public char charAt(int i) {
            return longTestString.charAt(i);
          }

          @Override
          public int length() {
            return longTestString.length();
          }

          @Override
          public CharSequence subSequence(int start, int end) {
            return longTestString.subSequence(start, end);
          }

          @Override
          public String toString() {
            return longTestString;
          }
        });
    assertEquals("4567890123456" + longTestString, t.toString());
  }
Example #25
0
 public void print(ThreadContext tc, String s) {
   try {
     ByteBuffer buffer = enc.encode(CharBuffer.wrap(s));
     write(tc, buffer);
   } catch (IOException e) {
     throw ExceptionHandling.dieInternal(tc, e);
   }
 }
  /**
   * Write String in UTF-BEBOM format
   *
   * <p>When this is called multiple times, all but the last value has a trailing null
   *
   * @param next
   * @param i
   * @param noOfValues
   * @return
   * @throws CharacterCodingException
   */
  private ByteBuffer writeStringUTF16BEBOM(String next, int i, int noOfValues)
      throws CharacterCodingException {
    CharsetEncoder encoder =
        Charset.forName(TextEncoding.CHARSET_UTF_16_BE_ENCODING_FORMAT).newEncoder();
    encoder.onMalformedInput(CodingErrorAction.IGNORE);
    encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);

    ByteBuffer bb = null;
    // Add BOM
    if ((i + 1) == noOfValues) {
      bb = encoder.encode(CharBuffer.wrap('\ufeff' + next));
    } else {
      bb = encoder.encode(CharBuffer.wrap('\ufeff' + next + '\0'));
    }
    bb.rewind();
    return bb;
  }
 /**
  * Writes the character {@code oneChar} to this writer. The lowest two bytes of the integer {@code
  * oneChar} are immediately converted to bytes by the character converter and stored in a local
  * buffer. If the buffer gets full by converting this character, this writer is flushed.
  *
  * @param oneChar the character to write.
  * @throws IOException if this writer is closed or another I/O error occurs.
  */
 @Override
 public void write(int oneChar) throws IOException {
   synchronized (lock) {
     checkStatus();
     CharBuffer chars = CharBuffer.wrap(new char[] {(char) oneChar});
     convert(chars);
   }
 }
Example #28
0
 public static void setDelimiter(String delimiter) {
   List<String> l = new ArrayList<String>();
   CharBuffer buf = CharBuffer.wrap(delimiter);
   while (buf.hasRemaining()) {
     l.add(String.valueOf(buf.get()));
   }
   delimiters = l.toArray(new String[l.size()]);
 }
  public void writeString(String text) throws IllegalArgumentException, IOException {
    if (text == null) throw new IllegalArgumentException("text cannot be null");

    /*
     * Write body - CharBuffer uses a reflection-optimized wrapper for
     * String instances specifically.
     */
    writeString(CharBuffer.wrap(text));
  }
  public void writeHuge(BigDecimal huge) throws IllegalArgumentException, IOException {
    if (huge == null) throw new IllegalArgumentException("huge cannot be null");

    /*
     * Write body - CharBuffer uses a reflection-optimized wrapper for
     * String instances specifically.
     */
    writeHuge(CharBuffer.wrap(huge.toString()));
  }