List of usage examples for java.nio CharBuffer toString
public String toString()
From source file:LoggingReader.java
@Override public int read(CharBuffer target) throws IOException { int read = theBase.read(target); if (theLog != null) theLog.write(target.array(), 0, read); else//from www .j a v a2 s. c o m System.out.print(target.toString().substring(0, read)); return read; }
From source file:com.dclab.preparation.ReadTest.java
public String scan(Reader r) { try {/*from w w w. j a v a 2 s .c o m*/ CharBuffer cb = CharBuffer.allocate(MAX_CAPACITY); int i = r.read(cb); Logger.getAnonymousLogger().log(Level.INFO, "read {0} bytes", i); String content = cb.toString(); return extract(content); } catch (IOException ex) { Logger.getLogger(ReadTest.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.idega.servlet.filter.WebServiceAuthorizationFilter.java
private String getDecodedNamePassword(HttpServletRequest request) { String basicNamePassword = request.getHeader("Authorization"); if (basicNamePassword == null) { return null; }/* ww w .j ava 2s .c o m*/ basicNamePassword = basicNamePassword.trim(); if (!basicNamePassword.startsWith("Basic")) { return null; } if (basicNamePassword.length() < 6) { return null; } String namePassword = basicNamePassword.substring(6); try { byte[] decodedNamePasswordArray = Base64.decodeBase64(namePassword.getBytes()); ByteBuffer wrappedDecodedNamePasswordArray = ByteBuffer.wrap(decodedNamePasswordArray); Charset charset = Charset.forName("ISO-8859-1"); CharBuffer buffer = charset.decode(wrappedDecodedNamePasswordArray); return buffer.toString(); } catch (Exception ex) { return null; } }
From source file:foam.blob.RestBlobService.java
@Override public Blob put_(X x, Blob blob) { if (blob instanceof IdentifiedBlob) { return blob; }/* w ww.java 2 s . c o m*/ HttpURLConnection connection = null; OutputStream os = null; InputStream is = null; try { URL url = new URL(address_); connection = (HttpURLConnection) url.openConnection(); //configure HttpURLConnection connection.setConnectTimeout(5 * 1000); connection.setReadTimeout(5 * 1000); connection.setDoOutput(true); connection.setUseCaches(false); //set request method connection.setRequestMethod("PUT"); //configure http header connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("Connection", "keep-alive"); connection.setRequestProperty("Content-Type", "application/octet-stream"); // get connection ouput stream os = connection.getOutputStream(); //output blob into connection blob.read(os, 0, blob.getSize()); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new RuntimeException("Upload failed"); } is = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); CharBuffer cb = CharBuffer.allocate(65535); reader.read(cb); cb.rewind(); return (Blob) getX().create(JSONParser.class).parseString(cb.toString(), IdentifiedBlob.class); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); IOUtils.close(connection); } }
From source file:StreamUtil.java
/** * Reads the stream and generates a String content using the charset specified. * Stream will be closed at the end of the operation. * @param in InputStream as the input./* w w w . jav a 2 s . c om*/ * @param charset The charset to use to create the String object. * @return The output String. * @throws IOException */ public static String inputStream2String(final InputStream is, final Charset charset) throws IOException { try { StringBuilder out = new StringBuilder(); byte[] b = new byte[4096]; byte[] savedBytes = new byte[1]; boolean hasSavedBytes = false; CharsetDecoder decoder = charset.newDecoder(); for (int n; (n = is.read(b)) != -1;) { if (hasSavedBytes) { byte[] bTmp = new byte[savedBytes.length + b.length]; System.arraycopy(savedBytes, 0, bTmp, 0, savedBytes.length); System.arraycopy(b, 0, bTmp, savedBytes.length, b.length); b = bTmp; hasSavedBytes = false; n = n + savedBytes.length; } CharBuffer charBuffer = decodeHelper(b, n, charset); if (charBuffer == null) { int nrOfChars = 0; while (charBuffer == null) { nrOfChars++; charBuffer = decodeHelper(b, n - nrOfChars, charset); if (nrOfChars > 10 && nrOfChars < n) { try { charBuffer = decoder.decode(ByteBuffer.wrap(b, 0, n)); } catch (MalformedInputException ex) { throw new IOException( "File not in supported encoding (" + charset.displayName() + ")", ex); } } } savedBytes = new byte[nrOfChars]; hasSavedBytes = true; for (int i = 0; i < nrOfChars; i++) { savedBytes[i] = b[n - nrOfChars + i]; } } charBuffer.rewind(); // Bring the buffer's pointer to 0 out.append(charBuffer.toString()); } if (hasSavedBytes) { try { CharBuffer charBuffer = decoder.decode(ByteBuffer.wrap(savedBytes, 0, savedBytes.length)); } catch (MalformedInputException ex) { throw new IOException("File not in supported encoding (" + charset.displayName() + ")", ex); } } return out.toString(); } finally { if (is != null) { is.close(); } } }
From source file:org.springframework.web.reactive.resource.AppCacheManifestTransformer.java
@Override public Mono<Resource> transform(ServerWebExchange exchange, Resource inputResource, ResourceTransformerChain chain) { return chain.transform(exchange, inputResource).flatMap(outputResource -> { String name = outputResource.getFilename(); if (!this.fileExtension.equals(StringUtils.getFilenameExtension(name))) { return Mono.just(outputResource); }/* www .j a va2 s.co m*/ DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory(); Flux<DataBuffer> flux = DataBufferUtils.read(outputResource, bufferFactory, StreamUtils.BUFFER_SIZE); return DataBufferUtils.join(flux).flatMap(dataBuffer -> { CharBuffer charBuffer = DEFAULT_CHARSET.decode(dataBuffer.asByteBuffer()); DataBufferUtils.release(dataBuffer); String content = charBuffer.toString(); return transform(content, outputResource, chain, exchange); }); }); }
From source file:com.google.dart.engine.services.internal.correction.CorrectionUtils.java
/** * @return the {@link String} content of the given {@link Source}. *//*www. j av a 2s . c o m*/ public static String getSourceContent(Source source) throws Exception { final String result[] = { null }; source.getContents(new Source.ContentReceiver() { @Override public void accept(CharBuffer contents, long modificationTime) { result[0] = contents.toString(); } @Override public void accept(String contents, long modificationTime) { result[0] = contents; } }); return result[0]; }
From source file:com.gargoylesoftware.htmlunit.NoHttpResponseTest.java
@Override public void run() { try {/* ww w . j a v a 2 s . com*/ serverSocket_ = new ServerSocket(port_); started_.set(true); LOG.info("Starting listening on port " + port_); while (!shutdown_) { final Socket s = serverSocket_.accept(); final BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); final CharBuffer cb = CharBuffer.allocate(5000); br.read(cb); cb.flip(); final String in = cb.toString(); cb.rewind(); final RawResponseData responseData = getResponseData(in); if (responseData == null || responseData.getStringContent() == DROP_CONNECTION) { LOG.info("Closing impolitely in & output streams"); s.getOutputStream().close(); } else { final PrintWriter pw = new PrintWriter(s.getOutputStream()); pw.println("HTTP/1.0 " + responseData.getStatusCode() + " " + responseData.getStatusMessage()); for (final NameValuePair header : responseData.getHeaders()) { pw.println(header.getName() + ": " + header.getValue()); } pw.println(); pw.println(responseData.getStringContent()); pw.println(); pw.flush(); pw.close(); } br.close(); s.close(); } } catch (final SocketException e) { if (!shutdown_) { LOG.error(e); } } catch (final IOException e) { LOG.error(e); } finally { LOG.info("Finished listening on port " + port_); } }
From source file:org.geppetto.frontend.GeppettoMessageInbound.java
/** * Receives message(s) from client./*from www. j av a 2s.c o m*/ * * @throws JsonProcessingException */ @Override protected void onTextMessage(CharBuffer message) throws JsonProcessingException { String msg = message.toString(); // de-serialize JSON GeppettoTransportMessage gmsg = new Gson().fromJson(msg, GeppettoTransportMessage.class); String requestID = gmsg.requestID; // switch on message type // NOTE: each message handler knows how to interpret the GeppettoMessage data field switch (INBOUND_MESSAGE_TYPES.valueOf(gmsg.type.toUpperCase())) { case GEPPETTO_VERSION: { _servletController.getVersionNumber(requestID, this); break; } case INIT_URL: { String urlString = gmsg.data; URL url; try { url = new URL(urlString); _servletController.load(requestID, urlString, this); } catch (MalformedURLException e) { _servletController.messageClient(requestID, this, OUTBOUND_MESSAGE_TYPES.ERROR_LOADING_SIMULATION); } break; } case INIT_SIM: { String simulation = gmsg.data; _servletController.load(requestID, simulation, this); break; } case RUN_SCRIPT: { String urlString = gmsg.data; URL url = null; try { url = new URL(urlString); _servletController.sendScriptData(requestID, url, this); } catch (MalformedURLException e) { _servletController.messageClient(requestID, this, OUTBOUND_MESSAGE_TYPES.ERROR_READING_SCRIPT); } break; } case SIM: { String url = gmsg.data; _servletController.getSimulationConfiguration(requestID, url, this); break; } case START: { _servletController.startSimulation(requestID, this); break; } case PAUSE: { _servletController.pauseSimulation(requestID, this); break; } case STOP: { _servletController.stopSimulation(requestID, this); break; } case OBSERVE: { _servletController.observeSimulation(requestID, this); break; } case LIST_WATCH_VARS: { _servletController.listWatchableVariables(requestID, this); break; } case LIST_FORCE_VARS: { _servletController.listForceableVariables(requestID, this); break; } case SET_WATCH: { String watchListsString = gmsg.data; try { _servletController.addWatchLists(requestID, watchListsString, this); } catch (GeppettoExecutionException e) { _servletController.messageClient(requestID, this, OUTBOUND_MESSAGE_TYPES.ERROR_ADDING_WATCH_LIST); } catch (GeppettoInitializationException e) { _servletController.messageClient(requestID, this, OUTBOUND_MESSAGE_TYPES.ERROR_ADDING_WATCH_LIST); } break; } case GET_WATCH: { _servletController.getWatchLists(requestID, this); break; } case START_WATCH: { _servletController.startWatch(requestID, this); break; } case STOP_WATCH: { _servletController.stopWatch(requestID, this); break; } case CLEAR_WATCH: { _servletController.clearWatchLists(requestID, this); break; } case IDLE_USER: { _servletController.disableUser(requestID, this); break; } case GET_MODEL_TREE: { String instancePath = gmsg.data; _servletController.getModelTree(requestID, instancePath, this); } default: { // NOTE: no other messages expected for now } } }
From source file:org.apache.htrace.impl.PackedBufferManager.java
private void readAndValidateResponseFrame(SelectionKey sockKey, ByteBuffer buf, long expectedSeq, int expectedMethodId) throws IOException { buf.clear();//from www. j ava2 s . c o m buf.limit(PackedBuffer.HRPC_RESP_FRAME_LENGTH); doRecv(sockKey, buf); buf.flip(); buf.order(ByteOrder.LITTLE_ENDIAN); long seq = buf.getLong(); if (seq != expectedSeq) { throw new IOException("Expected sequence number " + expectedSeq + ", but got sequence number " + seq); } int methodId = buf.getInt(); if (expectedMethodId != methodId) { throw new IOException("Expected method id " + expectedMethodId + ", but got " + methodId); } int errorLength = buf.getInt(); buf.getInt(); if ((errorLength < 0) || (errorLength > PackedBuffer.MAX_HRPC_ERROR_LENGTH)) { throw new IOException("Got server error with invalid length " + errorLength); } else if (errorLength > 0) { buf.clear(); buf.limit(errorLength); doRecv(sockKey, buf); buf.flip(); CharBuffer charBuf = StandardCharsets.UTF_8.decode(buf); String serverErrorStr = charBuf.toString(); throw new IOException("Got server error " + serverErrorStr); } }