List of usage examples for java.nio CharBuffer allocate
public static CharBuffer allocate(int capacity)
From source file:org.auraframework.util.text.Hash.java
/** * Consumes and closes a reader to generate its contents' hash. * * @param reader the reader for pulling content. Must be at the beginning of file. *///from w w w. jav a2 s . c om public void setHash(Reader reader) throws IOException, IllegalStateException { try { MessageDigest digest = MessageDigest.getInstance("MD5"); Charset utf8 = Charset.forName("UTF-8"); CharBuffer cbuffer = CharBuffer.allocate(2048); while (reader.read(cbuffer) >= 0) { cbuffer.flip(); ByteBuffer bytes = utf8.encode(cbuffer); digest.update(bytes); cbuffer.clear(); } setHash(digest.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 is a required MessageDigest algorithm, but is not registered here."); } finally { reader.close(); } }
From source file:org.codehaus.groovy.grails.web.util.StreamByteBuffer.java
public String readAsString(Charset charset) throws CharacterCodingException { int unreadSize = totalBytesUnread(); if (unreadSize > 0) { CharsetDecoder decoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); CharBuffer charbuffer = CharBuffer.allocate(unreadSize); ByteBuffer buf = null;/*from w ww . ja v a 2s.c o m*/ while (prepareRead() != -1) { buf = currentReadChunk.readToNioBuffer(); boolean endOfInput = (prepareRead() == -1); CoderResult result = decoder.decode(buf, charbuffer, endOfInput); if (endOfInput) { if (!result.isUnderflow()) { result.throwException(); } } } CoderResult result = decoder.flush(charbuffer); if (buf.hasRemaining()) { throw new IllegalStateException("There's a bug here, buffer wasn't read fully."); } if (!result.isUnderflow()) { result.throwException(); } charbuffer.flip(); String str; if (charbuffer.hasArray()) { int len = charbuffer.remaining(); char[] ch = charbuffer.array(); if (len != ch.length) { ch = ArrayUtils.subarray(ch, 0, len); } str = StringCharArrayAccessor.createString(ch); } else { str = charbuffer.toString(); } return str; } return null; }
From source file:org.colombbus.tangara.io.ScriptReader.java
/** * Try to decode a byte buffer with a charset */* ww w . j a va 2 s . c o m*/ * @param content * the bute buffer * @param cs * the charset * @return <code>null</code> if the charset is not supported, or the decoded * string */ private static String tryDecodeBufferWithCharset(ByteBuffer content, Charset cs) { CharBuffer buffer = CharBuffer.allocate(content.capacity() * 2); CharsetDecoder decoder = createDecoder(cs); content.rewind(); CoderResult coderRes = decoder.decode(content, buffer, true); if (coderRes.isError() == false) { buffer.rewind(); return buffer.toString().trim(); } return null; }
From source file:org.gradle.testkit.runner.internal.io.WriterOutputStream.java
/** * Constructs a new {@link WriterOutputStream}. * * @param writer the target {@link Writer} * @param decoder the charset decoder//from www . jav a 2 s .c o m * @param bufferSize the size of the output buffer in number of characters * @param writeImmediately If <tt>true</tt> the output buffer will be flushed after each * write operation, i.e. all available data will be written to the * underlying {@link Writer} immediately. If <tt>false</tt>, the * output buffer will only be flushed when it overflows or when * {@link #flush()} or {@link #close()} is called. * @since 2.1 */ public WriterOutputStream(Writer writer, CharsetDecoder decoder, int bufferSize, boolean writeImmediately) { this.writer = writer; this.decoder = decoder; this.writeImmediately = writeImmediately; decoderOut = CharBuffer.allocate(bufferSize); }
From source file:org.gtdfree.model.GTDDataXMLTools.java
static public DataHeader load(GTDModel model, InputStream in) throws XMLStreamException, IOException { model.setSuspendedForMultipleChanges(true); model.getDataRepository().suspend(true); XMLStreamReader r;//ww w.ja v a 2s. com try { // buffer size is same as default in 1.6, we explicitly request it so, not to brake if defaut changes. BufferedInputStream bin = new BufferedInputStream(in, 8192); bin.mark(8191); Reader rr = new InputStreamReader(bin); CharBuffer b = CharBuffer.allocate(96); rr.read(b); b.position(0); //System.out.println(b); Pattern pattern = Pattern.compile("<\\?.*?encoding\\s*?=.*?\\?>", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$ Matcher matcher = pattern.matcher(b); // reset back to start of file bin.reset(); // we check if encoding is defined in xml, by the book encoding on r should be null if not defined in xml, // but in reality it can be arbitrary if not defined in xml. So we have to check ourselves. if (matcher.find()) { //System.out.println(matcher); // if defined, then XML parser will pick it up and use it r = XMLInputFactory.newInstance().createXMLStreamReader(bin); Logger.getLogger(GTDDataXMLTools.class).info("XML declared encoding: " + r.getEncoding() //$NON-NLS-1$ + ", system default encoding: " + Charset.defaultCharset()); //$NON-NLS-1$ } else { //System.out.println(matcher); // if not defined, then we assume it is generated by gtd-free version 0.4 or some local editor, // so we assume system default encoding. r = XMLInputFactory.newInstance().createXMLStreamReader(new InputStreamReader(bin)); Logger.getLogger(GTDDataXMLTools.class) .info("XML assumed system default encoding: " + Charset.defaultCharset()); //$NON-NLS-1$ } r.nextTag(); if ("gtd-data".equals(r.getLocalName())) { //$NON-NLS-1$ DataHeader dh = new DataHeader(null, r.getAttributeValue(null, "version"), //$NON-NLS-1$ r.getAttributeValue(null, "modified")); //$NON-NLS-1$ if (dh.version != null) { if (dh.version.equals("2.0")) { //$NON-NLS-1$ r.nextTag(); _load_2_0(model, r); return dh; } } String s = r.getAttributeValue(null, "lastActionID"); //$NON-NLS-1$ if (s != null) { try { model.setLastActionID(Integer.parseInt(s)); } catch (Exception e) { Logger.getLogger(GTDDataXMLTools.class).debug("Internal error.", e); //$NON-NLS-1$ } } if (dh.version != null) { if (dh.version.equals("2.1")) { //$NON-NLS-1$ r.nextTag(); _load_2_1(model, r); return dh; } if (dh.version.startsWith("2.2")) { //$NON-NLS-1$ r.nextTag(); _load_2_2(model, r); return dh; } } throw new IOException("XML gtd-free data with version number " + dh.version //$NON-NLS-1$ + " can not be imported. Data version is newer then supported versions. Update your GTD-Free application to latest version."); //$NON-NLS-1$ } _load_1_0(model, r); return null; } catch (XMLStreamException e) { if (e.getNestedException() != null) { Logger.getLogger(GTDDataXMLTools.class).debug("Parse error.", e.getNestedException()); //$NON-NLS-1$ } else { Logger.getLogger(GTDDataXMLTools.class).debug("Parse error.", e); //$NON-NLS-1$ } throw e; } catch (IOException e) { throw e; } finally { model.setSuspendedForMultipleChanges(false); model.getDataRepository().suspend(false); } }
From source file:org.ingini.mongodb.jongo.example.util.CollectionManager.java
private static void fill(DBCollection collection, String collectionContentFilePath) { StringBuilder stringBuilder = new StringBuilder(); try {/* w w w .j a va 2 s . co m*/ InputStreamReader inputStreamReader = new InputStreamReader( // CollectionManager.class.getClassLoader().getResourceAsStream(collectionContentFilePath), "UTF-8"); CharBuffer buf = CharBuffer.allocate(BUFFER_SIZE); for (int read = inputStreamReader.read(buf); read != EOF; read = inputStreamReader.read(buf)) { buf.flip(); stringBuilder.append(buf, START, read); } } catch (IOException e) { System.out.println("Unable to read input stream due to an exception! Exception: " + ExceptionUtils.getStackTrace(e)); throw new IllegalStateException(e); } BasicDBList parse = (BasicDBList) JSON.parse(stringBuilder.toString(), new MongoIdTransformerJSONCallback()); collection.insert(parse.toArray(new DBObject[parse.size()])); }
From source file:org.itstechupnorth.walrus.base.ArticleBuffer.java
public ArticleBuffer(final int bufferSize) { super();//from w w w .jav a 2 s . c om buffer = CharBuffer.allocate(bufferSize); this.number = instanceNumber.getAndIncrement(); outBuffer = ByteBuffer.allocate(OUT_BUFFER_CAPACITY); encoder = UTF8.newEncoder(); }
From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.auth.HMACAuthenticator.java
private String generateToken(final String username, final String salt, final String time) { try {/* w w w. j ava 2 s . c o m*/ final CharBuffer secretAndSalt = CharBuffer.allocate(secret.length + salt.length() + 1); secretAndSalt.put(secret); secretAndSalt.put(":"); secretAndSalt.put(salt); final String tokenPrefix = username + ":" + time.toString() + ":"; final SecretKeySpec keySpec = new SecretKeySpec(toBytes(secretAndSalt.array()), hmacAlgo); final Mac hmac = Mac.getInstance(hmacAlgo); hmac.init(keySpec); hmac.update(username.getBytes()); hmac.update(time.toString().getBytes()); final Base64.Encoder encoder = Base64.getUrlEncoder(); final byte[] hmacbytes = encoder.encode(hmac.doFinal()); final byte[] tokenbytes = tokenPrefix.getBytes(); final byte[] token = ByteBuffer.wrap(new byte[tokenbytes.length + hmacbytes.length]).put(tokenbytes) .put(hmacbytes).array(); return new String(encoder.encode(token)); } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:org.jboss.additional.testsuite.jdkall.present.elytron.application.CredentialStoreTestCase.java
private static String generateString(int len, char c) { return CharBuffer.allocate(len).toString().replace('\0', c); }
From source file:org.kuali.student.common.io.IOUtils.java
private static String decode(CharsetDecoder decoder, byte[] in) { ByteBuffer inBuf = ByteBuffer.wrap(in); CharBuffer outBuf = CharBuffer.allocate(inBuf.capacity() * Math.round(decoder.maxCharsPerByte() + 0.5f)); decoder.decode(inBuf, outBuf, true); decoder.flush(outBuf);//www . ja va 2s .c o m decoder.reset(); return outBuf.flip().toString(); }