List of usage examples for java.nio CharBuffer allocate
public static CharBuffer allocate(int capacity)
From source file:com.cloudera.sqoop.io.TestLobFile.java
/** Verifies that the next record in the LobFile is the expected one. */ private void verifyNextRecord(LobFile.Reader reader, long expectedId, String expectedRecord) throws Exception { assertTrue(reader.next());// w ww.j a v a 2s. c o m assertTrue(reader.isRecordAvailable()); assertEquals(expectedId, reader.getRecordId()); Reader r = reader.readClobRecord(); CharBuffer buf = CharBuffer.allocate(expectedRecord.length()); int bytesRead = 0; while (bytesRead < expectedRecord.length()) { int thisRead = r.read(buf); if (-1 == thisRead) { break; } bytesRead += thisRead; } LOG.info("Got record of " + bytesRead + " chars"); assertEquals(expectedRecord.length(), bytesRead); char[] charData = buf.array(); String finalRecord = new String(charData); assertEquals(expectedRecord, finalRecord); }
From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java
/** * Initialize UI model from a .touchosc file * //from w ww .j a v a2 s . c om * @param zipTouchoscFilePath a .touchosc file * * @return UI model */ public TouchOscApp loadAppFromTouchOscXML2(String zipTouchoscFilePath) { // // Create a resource set. // ResourceSet resourceSet = new ResourceSetImpl(); // // Register the default resource factory -- only needed for stand-alone! // resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX, new TouchoscResourceFactoryImpl()); resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE); resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE); List<String> touchoscFilePathList = new ArrayList<String>(); try { URL url = TouchOSCUtils.class.getClassLoader().getResource("."); FileInputStream touchoscFile = new FileInputStream(url.getPath() + "../samples/" + zipTouchoscFilePath); ZipInputStream fileIS = new ZipInputStream(touchoscFile); ZipEntry zEntry = null; while ((zEntry = fileIS.getNextEntry()) != null) { if (zEntry.getName().endsWith(".xml")) { touchoscFilePathList.add(url.getPath() + "../samples/_" + zipTouchoscFilePath); } FileOutputStream os = new FileOutputStream(url.getPath() + "../samples/_" + zipTouchoscFilePath); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os)); BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8"))); CharBuffer charBuffer = CharBuffer.allocate(65535); while (reader.read(charBuffer) != -1) charBuffer.append("</touchosc:TOP>\n"); charBuffer.flip(); String content = charBuffer.toString(); content = content.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", TOUCHOSC_XMLNS_HEADER); content = content.replace("numberX=", "number_x="); content = content.replace("numberY=", "number_y="); content = content.replace("invertedX=", "inverted_x="); content = content.replace("invertedY=", "inverted_y="); content = content.replace("localOff=", "local_off="); content = content.replace("oscCs=", "osc_cs="); writer.write(content); writer.flush(); os.flush(); os.close(); } fileIS.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } // // Get the URI of the model file. // URI touchoscURI = URI.createFileURI(touchoscFilePathList.get(0)); // // Demand load the resource for this file. // Resource resource = resourceSet.getResource(touchoscURI, true); Object obj = (Object) resource.getContents().get(0); if (obj instanceof TOP) { TOP top = (TOP) obj; reverseZOrders(top); return initAppFromTouchOsc(top.getLayout(), "horizontal".equals(top.getLayout().getOrientation()), "0".equals(top.getLayout().getMode())); } return null; }
From source file:com.atilika.kuromoji.trie.DoubleArrayTrie.java
/** * Add characters(nodes) to tail array//from w ww . j a v a 2s . co m * * @param node */ private void addToTail(Trie.Node node) { while (true) { if (tailBuffer.capacity() < tailIndex - TAIL_OFFSET + 1) { CharBuffer newTailBuffer = CharBuffer .allocate(tailBuffer.capacity() + (int) (tailBuffer.capacity() * BUFFER_GROWTH_PERCENTAGE)); tailBuffer.rewind(); newTailBuffer.put(tailBuffer); tailBuffer = newTailBuffer; } tailBuffer.put(tailIndex++ - TAIL_OFFSET, node.getKey());// set character of current node if (node.getChildren().isEmpty()) { // if it reached the end of input, break. break; } node = node.getChildren().get(0); // Move to next node } }
From source file:com.asakusafw.runtime.io.csv.CsvParser.java
private void emit(int c) throws IOException { assert c >= 0; CharBuffer buf = lineBuffer;/*w ww. java2s . c o m*/ if (buf.remaining() == 0) { if (buf.capacity() == BUFFER_LIMIT) { throw new IOException( MessageFormat.format("Line is too large (near {0}:{1}, size={2}, record-number={3})", path, currentPhysicalHeadLine, BUFFER_LIMIT, currentRecordNumber)); } CharBuffer newBuf = CharBuffer.allocate(Math.min(buf.capacity() * 2, BUFFER_LIMIT)); newBuf.clear(); buf.flip(); newBuf.put(buf); buf = newBuf; lineBuffer = newBuf; } buf.put((char) c); }
From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java
public void dumpTouchOsc(TOP top, String destDirname, String destFilename) { reverseZOrders(top);/*from ww w. j ava2 s .c om*/ // // Get tests for TouchOSC legacy compliances : need precise version info // //applyBase64Transformation(top); // Create a resource set. // ResourceSet resourceSet = new ResourceSetImpl(); // // Register the default resource factory -- only needed for stand-alone! // resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX, new TouchoscResourceFactoryImpl()); resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE); resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE); String dirname; if (destDirname == null) { dirname = Platform.getInstanceLocation().getURL().getPath() + "/" + UUID.randomUUID().toString(); if (Platform.inDebugMode()) { System.out.println("creating " + dirname + " directory"); } new File(dirname).mkdir(); } else { dirname = destDirname; } // // Get the URI of the model file. // URI touchoscURI = URI.createFileURI(dirname + "/" + "index.xml"); // // Demand load the resource for this file. // Resource resource = resourceSet.createResource(touchoscURI); resource.getContents().add(top); try { Map<Object, Object> options = new HashMap<Object, Object>(); options.put(XMLResource.OPTION_ENCODING, "UTF-8"); resource.save(options); } catch (IOException e) { e.printStackTrace(); } String TOUCHOSC_HEADER = "<touchosc:TOP xmi:version=\"2.0\" xmlns:xmi=\"http://www.omg.org/XMI\" xmlns:touchosc=\"http:///net.sf.smbt.touchosc/src/net/sf/smbt/touchosc/model/touchosc.xsd\">"; String TOUCHOSC_FOOTER = "</touchosc:TOP>"; String path = touchoscURI.path().toString(); String outputZipFile = dirname + "/" + destFilename + ".touchosc"; try { FileInputStream touchoscFile = new FileInputStream(path); BufferedReader reader = new BufferedReader( new InputStreamReader(touchoscFile, Charset.forName("ASCII"))); CharBuffer charBuffer = CharBuffer.allocate(65535); while (reader.read(charBuffer) != -1) charBuffer.flip(); String content = charBuffer.toString(); content = content.replace(TOUCHOSC_HEADER, "<touchosc>"); content = content.replace(TOUCHOSC_FOOTER, "</touchosc>"); content = content.replace("<layout>", "<layout version=\"10\" mode=\"" + top.getLayout().getMode() + "\" orientation=\"" + top.getLayout().getOrientation() + "\">"); content = content.replace("numberX=", "number_x="); content = content.replace("numberY=", "number_y="); content = content.replace("invertedX=", "inverted_x="); content = content.replace("invertedY=", "inverted_y="); content = content.replace("localOff=", "local_off="); content = content.replace("oscCs=", "osc_cs="); content = content.replace("xypad", "xy"); touchoscFile.close(); FileOutputStream os = new FileOutputStream(path); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName("UTF-8"))); writer.write(content); writer.flush(); os.flush(); os.close(); FileOutputStream fos = new FileOutputStream(outputZipFile); ZipOutputStream fileOS = new ZipOutputStream(fos); ZipEntry ze = new ZipEntry("index.xml"); fileOS.putNextEntry(ze); fileOS.write(content.getBytes(Charset.forName("UTF-8"))); fileOS.flush(); fileOS.close(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { File f = new File(path); if (f.exists() && f.canWrite()) { if (!f.delete()) { throw new IllegalArgumentException(path + " deletion failed"); } } } }
From source file:ch.rasc.edsutil.optimizer.WebResourceProcessor.java
private static String inputStream2String(InputStream is, Charset cs) throws IOException { StringBuilder to = new StringBuilder(); try (Reader from = new InputStreamReader(is, cs.newDecoder())) { CharBuffer buf = CharBuffer.allocate(0x800); while (from.read(buf) != -1) { buf.flip();/*from w w w.ja va2s .c o m*/ to.append(buf); buf.clear(); } return to.toString(); } }
From source file:hudson.Util.java
/** * Encode a single path component for use in an HTTP URL. * Escapes all non-ASCII, general unsafe (space and "#%<>[\]^`{|}~) * and HTTP special characters (/;:?) as specified in RFC1738, * plus backslash (Windows path separator). * Note that slash(/) is encoded, so the given string should be a * single path component used in constructing a URL. * Method name inspired by PHP's rawencode. */// w w w .j a va 2 s.c o m public static String rawEncode(String s) { boolean escaped = false; StringBuilder out = null; CharsetEncoder enc = null; CharBuffer buf = null; char c; for (int i = 0, m = s.length(); i < m; i++) { c = s.charAt(i); if ((c < 64 || c > 90) && (c < 97 || c > 122) && (c < 38 || c > 57 || c == 47) && c != 61 && c != 36 && c != 33 && c != 95) { if (!escaped) { out = new StringBuilder(i + (m - i) * 3); out.append(s.substring(0, i)); enc = Charset.forName("UTF-8").newEncoder(); buf = CharBuffer.allocate(1); escaped = true; } // 1 char -> UTF8 buf.put(0, c); buf.rewind(); try { for (byte b : enc.encode(buf).array()) { out.append('%'); out.append(toDigit((b >> 4) & 0xF)); out.append(toDigit(b & 0xF)); } } catch (CharacterCodingException ex) { } } else if (escaped) { out.append(c); } } return escaped ? out.toString() : s; }
From source file:hudson.Util.java
/** * Encode a single path component for use in an HTTP URL. * Escapes all non-ASCII, general unsafe (space and "#%<>[\]^`{|}~) * and HTTP special characters (/;:?) as specified in RFC1738. * (so alphanumeric and !@$&*()-_=+',. are not encoded) * Note that slash(/) is encoded, so the given string should be a * single path component used in constructing a URL. * Method name inspired by PHP's rawurlencode. */// w w w . j a va 2s . co m public static String rawEncode(String s) { boolean escaped = false; StringBuilder out = null; CharsetEncoder enc = null; CharBuffer buf = null; char c; for (int i = 0, m = s.length(); i < m; i++) { c = s.charAt(i); if (c > 122 || uriMap[c]) { if (!escaped) { out = new StringBuilder(i + (m - i) * 3); out.append(s.substring(0, i)); enc = Charset.forName("UTF-8").newEncoder(); buf = CharBuffer.allocate(1); escaped = true; } // 1 char -> UTF8 buf.put(0, c); buf.rewind(); try { ByteBuffer bytes = enc.encode(buf); while (bytes.hasRemaining()) { byte b = bytes.get(); out.append('%'); out.append(toDigit((b >> 4) & 0xF)); out.append(toDigit(b & 0xF)); } } catch (CharacterCodingException ex) { } } else if (escaped) { out.append(c); } } return escaped ? out.toString() : s; }
From source file:ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository.java
/** * Returns the resource uri or <code>null</code> if no resource id and/or path * could be found on the specified document. This method is intended to serve * as a utility method when importing resources. * /*from ww w . j a v a 2 s.co m*/ * @param site * the resource uri * @param contentUrl * location of the resource file * @return the resource uri */ protected ResourceURI loadResourceURI(Site site, URL contentUrl) throws IOException { InputStream is = null; InputStreamReader reader = null; try { is = new BufferedInputStream(contentUrl.openStream()); reader = new InputStreamReader(is); CharBuffer buf = CharBuffer.allocate(1024); reader.read(buf); String s = new String(buf.array()); s = s.replace('\n', ' '); Matcher m = resourceHeaderRegex.matcher(s); if (m.matches()) { long version = ResourceUtils.getVersion(m.group(4)); return new ResourceURIImpl(m.group(1), site, m.group(3), m.group(2), version); } return null; } finally { if (reader != null) reader.close(); IOUtils.closeQuietly(is); } }
From source file:com.arksoft.epamms.ZGlobal1_Operation.java
public int StartEmailClientForListReus(View vResult, String entityName, String attributeName, String contextName, String stringScope, int bUseOnlySelectedEntities, int bUseParentSelectedEntities, String stringSubject, String stringCopyTo, // comma separated list String stringBlindCopy, // comma separated list String stringBody, String stringAttachment, String stringEmailClient, int lFlags, String stringBlindCopyFlag) // reserved { String stringParentEntity = null; String s = null;/*from w w w . j a v a 2 s. c o m*/ int lEntityCnt; int ulAttributeLth = 0; int lTotalSize; int lLth = 0; int lRC; if (bUseParentSelectedEntities != 0) stringParentEntity = MiGetParentEntityNameForView(stringParentEntity, vResult, entityName); lEntityCnt = CountEntitiesForView(vResult, entityName); ulAttributeLth = GetAttributeDisplayLength(ulAttributeLth, vResult, entityName, attributeName, contextName); lTotalSize = lEntityCnt * (int) ulAttributeLth; // a starting point CharBuffer cbMemory = CharBuffer.allocate(lTotalSize + 1); // DrAllocTaskMemory( cbMemory, lTotalSize + 1 ); // For each entity, append the specified data to the list. // lRC = SetCursorFirstEntity( vResult, entityName, stringScope ); lRC = SetEntityCursor(vResult, entityName, "", zPOS_FIRST, "", "", "", 0, stringScope, ""); while (lRC > zCURSOR_UNCHANGED) { if (bUseOnlySelectedEntities == 0 || ((bUseOnlySelectedEntities != 0) && GetSelectStateOfEntity(vResult, entityName) != 0) || ((bUseParentSelectedEntities != 0) && GetSelectStateOfEntity(vResult, stringParentEntity) != 0)) { s = GetVariableFromAttribute(s, 0, zTYPE_STRING, lTotalSize - lLth - 1, vResult, entityName, attributeName, contextName, contextName != null && contextName.isEmpty() == false ? 0 : zUSE_DEFAULT_CONTEXT); lLth = zstrcpy(cbMemory, lLth, s); while (lLth > 0 && cbMemory.charAt(lLth - 1) == ' ') { lLth--; cbMemory.put(lLth, '\0'); } } // lRC = SetCursorNextEntity( vResult, entityName, stringScope ); lRC = SetEntityCursor(vResult, entityName, "", zPOS_NEXT, "", "", "", 0, stringScope, ""); if (lRC > zCURSOR_UNCHANGED) { // lLth = zstrlen( stringMemory ); if (lTotalSize - lLth < (int) ulAttributeLth) { s = cbMemory.toString(); lEntityCnt *= 2; lTotalSize = lEntityCnt * (int) ulAttributeLth; cbMemory = CharBuffer.allocate(lTotalSize + 1); zstrcpy(cbMemory, 0, s); } if (lLth > 0 && cbMemory.charAt(lLth - 1) != ',') { cbMemory.put(lLth++, ','); cbMemory.put(lLth, '\0'); } } } if (stringBlindCopyFlag.charAt(0) == 'Y') { // Email Addresses are to be put in Blind Copy parameter. TraceLineS("Blind Copies: ", cbMemory.toString()); lRC = m_ZDRVROPR.StartEmailClient(stringBlindCopy, // Regular send parameter stringSubject, stringCopyTo, // comma separated list cbMemory.toString(), // Blind Copy parameter stringBody, stringAttachment, "", lFlags); // reserved } else { // Email Addresses are to be put in regular Send parameter. TraceLineS("Regular Copies: ", cbMemory.toString()); lRC = m_ZDRVROPR.StartEmailClient(cbMemory.toString(), // comma separated list stringSubject, stringCopyTo, // comma separated list stringBlindCopy, // comma separated list stringBody, stringAttachment, stringEmailClient, lFlags); // reserved } // DrFreeTaskMemory( (String) cbMemory ); return lRC; }