List of usage examples for java.io InputStream available
public int available() throws IOException
From source file:net.sf.infrared.collector.impl.persistence.InProcessDataSource.java
boolean copy(String src, File dest) { // @TODO replace this with Commons FileUtils if (dest.exists()) { if (log.isDebugEnabled()) { log.debug(dest.getAbsoluteFile() + " exists"); }/*from ww w. j a v a2 s.c o m*/ return false; } else { if (log.isDebugEnabled()) { log.debug(dest.getAbsoluteFile() + " doesn't exists"); } } URL srcUrl = null; try { srcUrl = Thread.currentThread().getContextClassLoader().getResource(src); } catch (Throwable th) { log.error("Failed to find default in-process DB schema", th); return false; } if (srcUrl == null) { log.error("Failed to find default in-process DB schema"); return false; } InputStream srcStream = null; byte[] bytes = null; try { srcStream = srcUrl.openStream(); bytes = new byte[srcStream.available()]; srcStream.read(bytes); } catch (IOException e) { log.fatal("Failed to read in-process DB schema from " + srcUrl, e); return false; } finally { try { if (srcStream != null) { srcStream.close(); } } catch (IOException ignored) { } } FileOutputStream destStream = null; try { if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } dest.createNewFile(); destStream = new FileOutputStream(dest); destStream.write(bytes); if (log.isDebugEnabled()) { log.debug("Create new in-process database at " + getDbPath()); } return true; } catch (IOException e) { log.fatal("Failed to create file " + dest, e); return false; } finally { try { if (destStream != null) { destStream.close(); } } catch (IOException ignored) { } } }
From source file:gemlite.core.internal.support.hotdeploy.scanner.ScannerIteratorItem.java
private byte[] readContent(ClassLoader loader, JarEntry entry) throws IOException { URL url = loader.getResource(entry.getName()); URLConnection ulc = url.openConnection(); InputStream in3 = ulc.getInputStream(); InputStream in2 = url.openStream(); InputStream in = loader.getResourceAsStream(entry.getName()); if (in == null) { LogUtil.getCoreLog().trace("ReadContent inputStream is null entry.name={} , loader={}", entry.getName(), loader);//from ww w .j a v a2 s . co m } BufferedInputStream bi = new BufferedInputStream(in); byte[] bt = new byte[in.available()]; bi.read(bt); bi.close(); in.close(); return bt; }
From source file:us.pserver.revok.http.HttpContentFactory.java
/** * Create the <code>HttpEntity</code> with the content to be transmitted. * @return The <code>HttpEntity</code> with the content to be transmitted. * @throws IOException In case of error creating the <code>HttpEntity</code>. *//* w w w . j a v a 2s. c o m*/ public HttpEntity create() throws IOException { if (key == null && obj == null && input == null) return null; InputStream istream = createStream(); return new InputStreamEntity(istream, istream.available(), type); }
From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {// w w w . ja v a 2 s .c om SSLSession session = sslsock.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 = sslsock.getInputStream(); in.available(); // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = sslsock.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. sslsock.startHandshake(); session = sslsock.getSession(); } } if (session == null) { throw new SSLHandshakeException("SSL session not available"); } if (this.log.isDebugEnabled()) { this.log.debug("Secure session established"); this.log.debug(" negotiated protocol: " + session.getProtocol()); this.log.debug(" negotiated cipher suite: " + session.getCipherSuite()); try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal peer = x509.getSubjectX500Principal(); this.log.debug(" peer principal: " + peer.toString()); final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames(); if (altNames1 != null) { final List<String> altNames = new ArrayList<String>(); for (final List<?> aC : altNames1) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } this.log.debug(" peer alternative names: " + altNames); } final X500Principal issuer = x509.getIssuerX500Principal(); this.log.debug(" issuer principal: " + issuer.toString()); final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames(); if (altNames2 != null) { final List<String> altNames = new ArrayList<String>(); for (final List<?> aC : altNames2) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } this.log.debug(" issuer alternative names: " + altNames); } } catch (Exception ignore) { } } HostnameVerifier hostnameVerifier = insecure ? insecureHostnameVerifier : defaultHostnameVerifier; if (!hostnameVerifier.verify(hostname, session)) { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal x500Principal = x509.getSubjectX500Principal(); throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match " + "the certificate subject provided by the peer (" + x500Principal.toString() + ")"); } // verifyHostName() didn't blowup - good! } catch (final IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (final Exception x) { /*ignore*/ } throw iox; } }
From source file:controller.servlet.PostServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// ww w .jav a 2 s. c om * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PostDAOService postService = PostDAO.getInstance(); String title = null; String shortTitle = null; String sCategoryID = null; String content = null; String link = null; String action = null; // String pathImage; String imageName = ""; boolean isUploadSuccess = false; ServletFileUpload fileUpload = new ServletFileUpload(); try { FileItemIterator itr = fileUpload.getItemIterator(request); while (itr.hasNext()) { FileItemStream fileItemStream = itr.next(); if (fileItemStream.isFormField()) { String fieldName = fileItemStream.getFieldName(); InputStream is = fileItemStream.openStream(); byte[] b = new byte[is.available()]; is.read(b); String value = new String(b, "UTF-8"); if (fieldName.equals("action")) { action = value; } if (fieldName.equals("title")) { title = value; } if (fieldName.equals("content")) { content = value; } if (fieldName.equals("short-title")) { shortTitle = value; } if (fieldName.equals("category-id")) { sCategoryID = value; } if (fieldName.equals("link")) { link = value; } } else { String realPath = getServletContext().getRealPath("/"); String filePath = realPath.replace("\\build\\web", "\\web\\image\\post");//Duong dan luu file anh imageName = fileItemStream.getName(); StringTokenizer token = new StringTokenizer(imageName, "."); String fileNameExtension = ""; while (token.hasMoreElements()) { fileNameExtension = token.nextElement().toString(); } System.out.println("img: " + imageName); if (!imageName.equals("")) { imageName = Support.randomString(); isUploadSuccess = FileUpload.processFile(filePath, fileItemStream, imageName, fileNameExtension); imageName += "." + fileNameExtension; } } } Post currentPost = new Post(); currentPost.setPostID(postService.nextID()); currentPost.setTitle(title); currentPost.setShortTitle(shortTitle); currentPost.setCategory(new Category(Integer.valueOf(sCategoryID), "", false)); currentPost.setContent(content); currentPost.setDatePost(Support.getDatePost()); currentPost.setUser((User) request.getSession().getAttribute(Constants.CURRENT_USER)); currentPost.setLink(link); currentPost.setActive(false); request.setAttribute(Constants.CURRENT_POST, currentPost); request.setAttribute(Constants.LIST_CATEGORY, CategoryDAO.getInstance().getCategories()); if (action != null) { switch (action) { case "up-load": upLoad(request, response, imageName, isUploadSuccess); break; case "add-topic": addTopic(request, response, currentPost); break; } } } catch (IOException | org.apache.tomcat.util.http.fileupload.FileUploadException e) { response.getWriter().println(e.toString()); } }
From source file:no.nordicsemi.android.nrftoolbox.dfu.HexInputStream.java
private int calculateBinSize() throws IOException { int binSize = 0; final InputStream in = this.in; in.mark(in.available()); int b, lineSize, type; try {/* w w w . j a va 2s . c o m*/ b = in.read(); while (true) { checkComma(b); lineSize = readByte(in); // reading the length of the data in this line in.skip(4); // skipping address part type = readByte(in); // reading the line type switch (type) { case 0x00: // data type line binSize += lineSize; break; case 0x01: // end of file return binSize; case 0x02: // extended segment address record case 0x04: // extended linear address record default: break; } in.skip(lineSize * 2 /* 2 hex per one byte */ + 2 /* check sum */); // skip end of line while (true) { b = in.read(); if (b != '\n' && b != '\r') { break; } } } } finally { try { in.reset(); } catch (IOException ex) { this.in = new BufferedInputStream( new DefaultHttpClient().execute(this.httpGet).getEntity().getContent()); } } }
From source file:com.temenos.interaction.example.mashup.streaming.HypermediaITCase.java
@Test public void testFollowRelsToProfileImage() throws IOException, UniformInterfaceException, URISyntaxException { RepresentationFactory representationFactory = new StandardRepresentationFactory(); ClientResponse response = webResource.path("/").accept(MediaType.APPLICATION_HAL_JSON) .get(ClientResponse.class); assertEquals(Response.Status.Family.SUCCESSFUL, Response.Status.fromStatusCode(response.getStatus()).getFamily()); ReadableRepresentation homeResource = representationFactory.readRepresentation( MediaType.APPLICATION_HAL_JSON.toString(), new InputStreamReader(response.getEntityInputStream())); Link profileLink = homeResource.getLinkByRel("http://relations.rimdsl.org/profile"); assertNotNull(profileLink);//from w w w . j a va 2 s .c o m response.close(); ClientResponse profileResponse = webResource.uri(new URI(profileLink.getHref())) .accept(MediaType.APPLICATION_HAL_JSON).get(ClientResponse.class); assertEquals(Response.Status.Family.SUCCESSFUL, Response.Status.fromStatusCode(profileResponse.getStatus()).getFamily()); ReadableRepresentation profileResource = representationFactory.readRepresentation( MediaType.APPLICATION_HAL_JSON.toString(), new InputStreamReader(profileResponse.getEntityInputStream())); assertEquals("someone@somewhere.com", profileResource.getProperties().get("email")); Link profileImageLink = profileResource.getLinkByRel("http://relations.rimdsl.org/image"); assertNotNull(profileImageLink); profileResponse.close(); ClientResponse profileImageResponse = webResource.uri(new URI(profileImageLink.getHref())) .get(ClientResponse.class); assertEquals(Response.Status.Family.SUCCESSFUL, Response.Status.fromStatusCode(profileImageResponse.getStatus()).getFamily()); InputStream imageStream = profileImageResponse.getEntityInputStream(); FileOutputStream fos = new FileOutputStream("./testimg.jpg"); try { IOUtils.copy(imageStream, fos); } finally { IOUtils.closeQuietly(imageStream); } fos.flush(); fos.close(); // check image received correctly assertEquals("image/jpeg", profileImageResponse.getHeaders().getFirst("Content-Type")); long originalFileSize; InputStream stream = null; try { URL url = this.getClass().getResource("/testimg.jpg"); stream = url.openStream(); originalFileSize = stream.available(); } finally { IOUtils.closeQuietly(stream); } File receivedImage = new File("./testimg.jpg"); assertEquals(originalFileSize, receivedImage.length()); profileImageResponse.close(); }
From source file:mitm.common.util.SizeLimitedInputStreamTest.java
@Test public void testLimitNoException() throws IOException, CertificateException, NoSuchProviderException { InputStream input = new FileInputStream(new File(testBase, "certificates/random-self-signed-1000.p7b")); final int maxBytes = 1000; InputStream limitedInput = new SizeLimitedInputStream(input, maxBytes, false); byte[] data = IOUtils.toByteArray(limitedInput); /*/*w w w . j ava2 s. c om*/ * Actual read is 4096 because the buffer size is 4096 */ assertEquals(4096, data.length); assertEquals(0, limitedInput.available()); assertEquals(-1, limitedInput.read()); assertEquals(-1, limitedInput.read(data)); assertEquals(-1, limitedInput.read(data, 0, 100)); assertEquals(0, limitedInput.skip(10)); }
From source file:IAAS.Monitoring.java
public boolean updateContainer(int container, int ram, int cpu) throws JSchException, IOException { JSch jsch = new JSch(); String command;/* w w w . j av a 2 s.c om*/ if (cpu == 0) command = "/root/scripts/update_container.sh " + container + " " + ram; else command = "/root/scripts/update_container.sh " + container + " " + ram + " " + cpu; Session session = jsch.getSession(this.user, this.host, this.port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(this.pwd); session.connect(); ChannelExec channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); boolean result = channel.isConnected(); System.out.println("Unix system connected..."); byte[] tmp = new byte[1024]; boolean test = true; while (test) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) { break; } String line = new String(tmp, 0, i); System.out.println("Unix system console output: "); System.out.println("Here is a line " + line); } if (channel.isClosed()) { test = false; break; } try { Thread.sleep(1000); } catch (Exception ee) { //ignore } } channel.disconnect(); session.disconnect(); //return Pattern.matches(pattern, text); return result; }
From source file:cc.arduino.plugins.wifi101.flashers.Flasher.java
public byte[] getData() throws IOException { InputStream in = null; try {/*from w ww .ja va2 s .co m*/ in = new FileInputStream(file); ByteArrayOutputStream res = new ByteArrayOutputStream(); byte buff[] = new byte[4096]; while (in.available() > 0) { int read = in.read(buff); if (read == -1) { break; } res.write(buff, 0, read); } return res.toByteArray(); } finally { if (in != null) { in.close(); } } }