List of usage examples for java.io InputStream available
public int available() throws IOException
From source file:eu.europa.esig.dss.DSSUtils.java
/** * Returns an estimate of the number of bytes that can be read (or * skipped over) from this input stream without blocking by the next * invocation of a method for this input stream. The next invocation * might be the same thread or another thread. A single read or skip of this * many bytes will not block, but may read or skip fewer bytes. * the total number of bytes in the stream, many will not. It is * never correct to use the return value of this method to allocate * a buffer intended to hold all data in this stream. {@link IOException} if this input stream has been closed by * invoking the {@link InputStream#close()} method. * returns {@code 0}.//from w ww . j a va 2s . c om * * @return an estimate of the number of bytes that can be read (or skipped * over) from this input stream without blocking or {@code 0} when * it reaches the end of the input stream. * @throws DSSException * if IOException occurs (if an I/O error occurs) */ public static int available(final InputStream is) throws DSSException { try { return is.available(); } catch (IOException e) { throw new DSSException(e); } }
From source file:net.paissad.jcamstream.utils.FTPUtils.java
/** * Stores a file on the server using the given name and taking input from * the given InputStream.//from w w w .j a v a2s .co m * <p> * <b>Note</b>: The InputStream is not closed ! Feel free or responsible to * close it (or not) after use. * </p> * * @param remoteFileName * - The name that will be given to the file onto the FTP server. * @param in * - The stream to upload the FTP server. * @throws IOException * @throws FTPException */ public void uploadStream(String remoteFileName, InputStream in) throws IOException, FTPException { FTPClient client = this.getFtpClient(); String errMsg; int filesize = in.available(); client.allocate(filesize); String humanFileSize = CommonUtils.humanReadableByteCount(filesize, false); errMsg = "Unable to allocate the amount of size " + humanFileSize + " for the file " + remoteFileName; this.verifyReplyCode(errMsg); client.storeFile(remoteFileName, in); errMsg = "Unable to store the file " + remoteFileName + " to the server"; this.verifyReplyCode(errMsg); }
From source file:de.xaniox.heavyspleef.core.uuid.UUIDManager.java
private GameProfile fetchOriginalGameProfile(String name) throws IOException, ParseException { URL url = new URL(String.format(ORIGINAL_NAME_BASE_URL, name.trim())); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true);//from w w w .jav a 2 s .c om connection.setUseCaches(true); connection.setRequestProperty("Content-Type", "application/json"); InputStream in = connection.getInputStream(); if (in.available() == 0) { return null; } Reader reader = new InputStreamReader(in); JSONObject obj = (JSONObject) parser.parse(reader); UUID uuid = getUUID((String) obj.get("id")); String currentName = (String) obj.get("name"); GameProfile profile = new OriginalGameProfile(uuid, currentName, name); return profile; }
From source file:com.orinus.script.safe.jetty.SRequest.java
public byte[] getPartFileData(String name) { byte[] tag = new byte[0]; try {//from w w w . j av a2 s .c om if (formFileData.containsKey(name)) { String filename = formFileData.get(name); InputStream is = new FileInputStream(filename); tag = new byte[is.available()]; is.read(tag); is.close(); } } catch (Exception e) { } return tag; }
From source file:at.gv.egiz.bku.local.stal.LocalSecureViewer.java
private HashDataInput ensureCachedHashDataInput(HashDataInput hashDataInput) throws IOException { if (!(hashDataInput instanceof DataObjectHashDataInput)) { log.warn("Expected DataObjectHashDataInput for LocalSignRequestHandler, got {}.", hashDataInput.getClass().getName()); InputStream hdIs = hashDataInput.getHashDataInput(); ByteArrayOutputStream baos = new ByteArrayOutputStream(hdIs.available()); int b;// w ww .j a va2 s . c om while ((b = hdIs.read()) != -1) { baos.write(b); } hashDataInput = new ByteArrayHashDataInput(baos.toByteArray(), hashDataInput.getReferenceId(), hashDataInput.getMimeType(), hashDataInput.getEncoding(), hashDataInput.getFilename()); } return hashDataInput; }
From source file:com.sencha.gxt.explorer.rebind.SampleGenerator.java
private void writeFileToHtml(TreeLogger l, GeneratorContext ctx, String path) throws UnableToCompleteException { Resource file = ctx.getResourcesOracle().getResource(path); if (file == null) { l.log(Type.ERROR, "File cannot be found."); throw new UnableToCompleteException(); }//from w ww . java 2 s. com OutputStream stream = ctx.tryCreateResource(l, "code/" + path.replace('/', '.') + ".html"); if (stream == null) { // file already exists for this compile return; } try { InputStream input = file.openContents(); byte[] bytes = new byte[input.available()]; input.read(bytes); input.close(); // Write out the HTML file // TODO change this header stream.write(javaHeader.getBytes()); stream.write(bytes); // use file extension for the type for now? String type = FilenameUtils.getExtension(file.getPath()); if ("gss".equals(type)) { type = "css"; } stream.write(footer.replaceAll("\\{type\\}", type).getBytes()); stream.close(); } catch (Exception e) { l.log(Type.ERROR, "An error occured writing out a file into html", e); throw new UnableToCompleteException(); } ctx.commitResource(l, stream); }
From source file:com.qualys.jserf.SerfClientHandler.java
@Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception { byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(bytes);//from w w w . j a va2 s .c om InputStream inputStream = new ByteArrayInputStream(bytes); Map<String, Value> headerValues = messagePack.read(inputStream, templateMap); log.trace("Response header was {}", headerValues); Map<String, Value> bodyValues = Collections.emptyMap(); if (inputStream.available() != 0) { bodyValues = messagePack.read(inputStream, templateMap); } log.trace("Response body was {}", bodyValues); int sequence = headerValues.get("Seq").asIntegerValue().getInt(); String errorMessage = headerValues.get("Error").asRawValue().getString(); ResponseHeader header = new ResponseHeader(errorMessage, sequence); Pair<Command, SerfResponseCallBack> commandCallBackPair = callBacksBySequence.getIfPresent(sequence); if (commandCallBackPair == null) { log.debug( "Couldn't find corresponding Command/SerfResponseCallBack pair for sequence={}. Maybe it was already stopped?", sequence); return; } Command command = commandCallBackPair.getLeft(); if (StringUtils.isNotEmpty(errorMessage)) { log.debug("Received error message '{}' with response for command={} and sequence={}", errorMessage, command, sequence); } Optional<ResponseBodyExtractor> extractor = extractorManager.getExtractor(command); if (!extractor.isPresent()) { log.warn("Couldn't find extractor for command={}", command); return; } SerfResponse response = new SerfResponse<>(header, extractor.get().extractBody(bodyValues, extractorManager)); if (Command.QUERY.equals(command)) { QueryResponseBody queryResponseBody = (QueryResponseBody) response.getBody(); if (QueryResponseBody.Type.DONE.equals(queryResponseBody.getType())) { log.trace( "Removing Command/SerfResponseCallBack pair for sequence={} because it query command and the returned 'type' value was 'done'", sequence); callBacksBySequence.invalidate(sequence); } } if (!multipleResponseCommands.contains(command)) { log.trace( "Removing Command/SerfResponseCallBack pair for sequence={} because it wasn't a command that returns multiple responses (those commands are: {})", sequence, multipleResponseCommands); callBacksBySequence.invalidate(sequence); } if (commandCallBackPair.getRight() == null) { log.trace("Callback for Command/SerfResponseCallBack pair with sequence={} was null", sequence); return; } log.trace("Invoking callback for command={} with sequence={}", command, sequence); commandCallBackPair.getRight().call(response); log.trace("Invoked callback for command={} with sequence={}", command, sequence); }
From source file:EditorDropTarget3.java
protected boolean dropContent(Transferable transferable, DropTargetDropEvent dtde) { if (!pane.isEditable()) { // Can't drop content on a read-only text control return false; }/* w ww .j a v a 2 s . co m*/ try { // Check for a match with the current content type DataFlavor[] flavors = dtde.getCurrentDataFlavors(); DataFlavor selectedFlavor = null; // Look for either plain text or a String. for (int i = 0; i < flavors.length; i++) { DataFlavor flavor = flavors[i]; DnDUtils.debugPrintln("Drop MIME type " + flavor.getMimeType() + " is available"); if (flavor.equals(DataFlavor.plainTextFlavor) || flavor.equals(DataFlavor.stringFlavor)) { selectedFlavor = flavor; break; } } if (selectedFlavor == null) { // No compatible flavor - should never happen return false; } DnDUtils.debugPrintln("Selected flavor is " + selectedFlavor.getHumanPresentableName()); // Get the transferable and then obtain the data Object data = transferable.getTransferData(selectedFlavor); DnDUtils.debugPrintln("Transfer data type is " + data.getClass().getName()); String insertData = null; if (data instanceof InputStream) { // Plain text flavor String charSet = selectedFlavor.getParameter("charset"); InputStream is = (InputStream) data; byte[] bytes = new byte[is.available()]; is.read(bytes); try { insertData = new String(bytes, charSet); } catch (UnsupportedEncodingException e) { // Use the platform default encoding insertData = new String(bytes); } } else if (data instanceof String) { // String flavor insertData = (String) data; } if (insertData != null) { int selectionStart = pane.getCaretPosition(); pane.replaceSelection(insertData); pane.select(selectionStart, selectionStart + insertData.length()); return true; } return false; } catch (Exception e) { return false; } }
From source file:de.vanita5.twittnuker.util.net.ssl.AbstractCheckSignatureVerifier.java
@Override public final void verify(final String host, final SSLSocket ssl) throws IOException { if (host == null) throw new NullPointerException("host to verify is null"); SSLSession session = ssl.getSession(); if (session == null) { // In our experience this only happens under IBM 1.4.x when // spurious (unrelated) certificates show up in the server' // chain. Hopefully this will unearth the real problem: final InputStream in = ssl.getInputStream(); in.available(); /*//ww w.ja v a 2 s . c o m * If you're looking at the 2 lines of code above because you're * running into a problem, you probably have two options: * * #1. Clean up the certificate chain that your server is presenting * (e.g. edit "/etc/apache2/server.crt" or wherever it is your * server's certificate chain is defined). * * OR * * #2. Upgrade to an IBM 1.5.x or greater JVM, or switch to a * non-IBM JVM. */ // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = ssl.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. ssl.startHandshake(); // Okay, if we still haven't managed to cause an exception, // might as well go for the NPE. Or maybe we're okay now? session = ssl.getSession(); } } final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); }
From source file:org.apache.camel.component.restlet.RestletSetBodyTest.java
@Test public void testSetBodyRepresentation() throws Exception { HttpGet get = new HttpGet("http://0.0.0.0:" + portNum + "/images/123"); HttpClient httpclient = new DefaultHttpClient(); InputStream is = null; try {/*from w ww . j a v a 2s.c om*/ HttpResponse response = httpclient.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("image/png", response.getEntity().getContentType().getValue()); is = response.getEntity().getContent(); assertEquals("Get wrong available size", 10, is.available()); byte[] buffer = new byte[10]; is.read(buffer); for (int i = 0; i < 10; i++) { assertEquals(i + 1, buffer[i]); } } finally { httpclient.getConnectionManager().shutdown(); if (is != null) { is.close(); } } }