List of usage examples for java.io InputStream available
public int available() throws IOException
From source file:info.guardianproject.netcipher.client.SSLConnectionSocketFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {// ww w . j ava2 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) { } } */ if (!this.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:be.tarsos.transcoder.ffmpeg.FFMPEGExecutor.java
public AudioInputStream pipe(Attributes attributes) throws EncoderException { String pipeEnvironment;/*from ww w . ja v a 2s.c om*/ String pipeArgument; File pipeLogFile; int pipeBuffer; if (System.getProperty("os.name").indexOf("indows") > 0) { pipeEnvironment = "cmd.exe"; pipeArgument = "/C"; } else { pipeEnvironment = "/bin/bash"; pipeArgument = "-c"; } pipeLogFile = new File("decoder_log.txt"); //buffer 1/4 second of audio. pipeBuffer = attributes.getSamplingRate() / 4; AudioFormat audioFormat = Encoder.getTargetAudioFormat(attributes); String command = toString(); ProcessBuilder pb = new ProcessBuilder(pipeEnvironment, pipeArgument, command); pb.redirectError(Redirect.appendTo(pipeLogFile)); LOG.fine("Starting piped decoding process"); final Process process; try { process = pb.start(); } catch (IOException e1) { throw new EncoderException("Problem starting piped sub process: " + e1.getMessage()); } InputStream stdOut = new BufferedInputStream(process.getInputStream(), pipeBuffer); //read and ignore the 46 byte wav header, only pipe the pcm samples to the audioinputstream byte[] header = new byte[46]; double sleepSeconds = 0; double timeoutLimit = 20; //seconds try { while (stdOut.available() < header.length) { try { Thread.sleep(100); sleepSeconds += 0.1; } catch (InterruptedException e) { e.printStackTrace(); } if (sleepSeconds > timeoutLimit) { throw new Error("Could not read from pipe within " + timeoutLimit + " seconds: timeout!"); } } int bytesRead = stdOut.read(header); if (bytesRead != header.length) { throw new EncoderException( "Could not read complete WAV-header from pipe. This could result in mis-aligned frames!"); } } catch (IOException e1) { throw new EncoderException("Problem reading from piped sub process: " + e1.getMessage()); } final AudioInputStream audioStream = new AudioInputStream(stdOut, audioFormat, AudioSystem.NOT_SPECIFIED); //This thread waits for the end of the subprocess. new Thread(new Runnable() { public void run() { try { process.waitFor(); LOG.fine("Finished piped decoding process"); } catch (InterruptedException e) { LOG.severe("Interrupted while waiting for sub process exit."); e.printStackTrace(); } } }, "Decoding Pipe Reader").start(); return audioStream; }
From source file:ClassPath.java
/** * @param name/*from w w w . ja v a 2 s. c om*/ * fully qualified file name, e.g. java/lang/String * @param suffix * file name ends with suffix, e.g. .java * @return byte array for file on class path */ public byte[] getBytes(String name, String suffix) throws IOException { DataInputStream dis = null; try { InputStream is = getInputStream(name, suffix); if (is == null) { throw new IOException("Couldn't find: " + name + suffix); } dis = new DataInputStream(is); byte[] bytes = new byte[is.available()]; dis.readFully(bytes); return bytes; } finally { if (dis != null) { dis.close(); } } }
From source file:net.pms.dlna.DVDISOTitle.java
@Override protected void resolveOnce() { String cmd[] = new String[] { configuration.getMplayerPath(), "-identify", "-endpos", "0", "-v", "-ao", "null", "-vc", "null", "-vo", "null", "-dvd-device", ProcessUtil.getShortFileNameIfWideChars(file.getAbsolutePath()), "dvd://" + title }; OutputParams params = new OutputParams(configuration); params.maxBufferSize = 1;/*from www . j a v a 2 s. com*/ if (configuration.isDvdIsoThumbnails()) { try { params.workDir = configuration.getTempFolder(); } catch (IOException e1) { logger.debug("Caught exception", e1); } cmd[2] = "-frames"; cmd[3] = "2"; cmd[7] = "-quiet"; cmd[8] = "-quiet"; String frameName = "" + this.hashCode(); frameName = "mplayer_thumbs:subdirs=\"" + frameName + "\""; frameName = frameName.replace(',', '_'); cmd[10] = "jpeg:outdir=" + frameName; } params.log = true; final ProcessWrapperImpl pw = new ProcessWrapperImpl(cmd, params, true, false); Runnable r = new Runnable() { @Override public void run() { try { Thread.sleep(10000); } catch (InterruptedException e) { } pw.stopProcess(); } }; Thread failsafe = new Thread(r, "DVD ISO Title Failsafe"); failsafe.start(); pw.runInSameThread(); List<String> lines = pw.getOtherResults(); String duration = null; int nbsectors = 0; String fps = null; String aspect = null; String width = null; String height = null; ArrayList<DLNAMediaAudio> audio = new ArrayList<DLNAMediaAudio>(); ArrayList<DLNAMediaSubtitle> subs = new ArrayList<DLNAMediaSubtitle>(); if (lines != null) { for (String line : lines) { if (line.startsWith("DVD start=")) { nbsectors = Integer.parseInt(line.substring(line.lastIndexOf("=") + 1).trim()); } if (line.startsWith("audio stream:")) { DLNAMediaAudio lang = new DLNAMediaAudio(); lang.setId(Integer .parseInt(line.substring(line.indexOf("aid: ") + 5, line.lastIndexOf(".")).trim())); lang.setLang(line.substring(line.indexOf("language: ") + 10, line.lastIndexOf(" aid")).trim()); int end = line.lastIndexOf(" langu"); if (line.lastIndexOf("(") < end && line.lastIndexOf("(") > line.indexOf("format: ")) { end = line.lastIndexOf("("); } lang.setCodecA(line.substring(line.indexOf("format: ") + 8, end).trim()); if (line.contains("(stereo)")) { lang.getAudioProperties().setNumberOfChannels(2); } else { lang.getAudioProperties().setNumberOfChannels(6); } audio.add(lang); } if (line.startsWith("subtitle")) { DLNAMediaSubtitle lang = new DLNAMediaSubtitle(); lang.setId(Integer.parseInt( line.substring(line.indexOf("): ") + 3, line.lastIndexOf("language")).trim())); lang.setLang(line.substring(line.indexOf("language: ") + 10).trim()); if (lang.getLang().equals("unknown")) { lang.setLang(DLNAMediaLang.UND); } lang.setType(SubtitleType.UNKNOWN); subs.add(lang); } if (line.startsWith("ID_VIDEO_WIDTH=")) { width = line.substring(line.indexOf("ID_VIDEO_WIDTH=") + 15).trim(); } if (line.startsWith("ID_VIDEO_HEIGHT=")) { height = line.substring(line.indexOf("ID_VIDEO_HEIGHT=") + 16).trim(); } if (line.startsWith("ID_VIDEO_FPS=")) { fps = line.substring(line.indexOf("ID_VIDEO_FPS=") + 13).trim(); } if (line.startsWith("ID_LENGTH=")) { duration = line.substring(line.indexOf("ID_LENGTH=") + 10).trim(); } if (line.startsWith("ID_VIDEO_ASPECT=")) { aspect = line.substring(line.indexOf("ID_VIDEO_ASPECT=") + 16).trim(); } } } if (configuration.isDvdIsoThumbnails()) { try { String frameName = "" + this.hashCode(); frameName = configuration.getTempFolder() + "/mplayer_thumbs/" + frameName + "00000001/0000000"; frameName = frameName.replace(',', '_'); File jpg = new File(frameName + "2.jpg"); if (jpg.exists()) { InputStream is = new FileInputStream(jpg); try { int sz = is.available(); if (sz > 0) { getMedia().setThumb(new byte[sz]); is.read(getMedia().getThumb()); } } finally { if (is != null) { is.close(); } } if (!jpg.delete()) { jpg.deleteOnExit(); } // Try and retry if (!jpg.getParentFile().delete() && !jpg.getParentFile().delete()) { logger.debug("Failed to delete \"" + jpg.getParentFile().getAbsolutePath() + "\""); } } jpg = new File(frameName + "1.jpg"); if (jpg.exists()) { if (!jpg.delete()) { jpg.deleteOnExit(); } if (!jpg.getParentFile().delete()) { jpg.getParentFile().delete(); } } } catch (IOException e) { logger.trace("Error in DVD ISO thumbnail retrieval: " + e.getMessage()); } } length = nbsectors * 2048; double d = 0; if (duration != null) { d = Double.parseDouble(duration); } getMedia().setAudioTracksList(audio); getMedia().setSubtitleTracksList(subs); if (duration != null) { getMedia().setDuration(d); } getMedia().setFrameRate(fps); getMedia().setAspect(aspect); getMedia().setDvdtrack(title); getMedia().setContainer("iso"); getMedia().setCodecV("mpeg2video"); try { getMedia().setWidth(Integer.parseInt(width)); } catch (NumberFormatException nfe) { logger.debug("Could not parse width \"" + width + "\""); } try { getMedia().setHeight(Integer.parseInt(height)); } catch (NumberFormatException nfe) { logger.debug("Could not parse height \"" + height + "\""); } getMedia().setMediaparsed(true); }
From source file:com.cloud.test.stress.StressTestDirectAttach.java
private static String sshWinTest(String host) { if (host == null) { s_logger.info("Did not receive a host back from test, ignoring win ssh test"); return null; }// w w w .ja v a 2s . co m // We will retry 5 times before quitting int retry = 1; while (true) { try { if (retry > 0) { s_logger.info("Retry attempt : " + retry + " ...sleeping 300 seconds before next attempt. Account is " + _account.get()); Thread.sleep(300000); } s_logger.info("Attempting to SSH into windows host " + host + " with retry attempt: " + retry + " for account " + _account.get()); Connection conn = new Connection(host); conn.connect(null, 60000, 60000); s_logger.info("User " + _account.get() + " ssHed successfully into windows host " + host); boolean success = false; boolean isAuthenticated = conn.authenticateWithPassword("Administrator", "password"); if (isAuthenticated == false) { return "Authentication failed"; } else { s_logger.info("Authentication is successfull"); } try { SCPClient scp = new SCPClient(conn); scp.put("wget.exe", "wget.exe", "C:\\Users\\Administrator", "0777"); s_logger.info("Successfully put wget.exe file"); } catch (Exception ex) { s_logger.error("Unable to put wget.exe " + ex); } if (conn == null) { s_logger.error("Connection is null"); } Session sess = conn.openSession(); s_logger.info("User + " + _account.get() + " executing : wget http://192.168.1.250/dump.bin"); sess.execCommand("wget http://192.168.1.250/dump.bin && dir dump.bin"); InputStream stdout = sess.getStdout(); InputStream stderr = sess.getStderr(); byte[] buffer = new byte[8192]; while (true) { if ((stdout.available() == 0) && (stderr.available() == 0)) { int conditions = sess.waitForCondition( ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 120000); if ((conditions & ChannelCondition.TIMEOUT) != 0) { s_logger.info("Timeout while waiting for data from peer."); return null; } if ((conditions & ChannelCondition.EOF) != 0) { if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { break; } } } while (stdout.available() > 0) { success = true; int len = stdout.read(buffer); if (len > 0) // this check is somewhat paranoid s_logger.info(new String(buffer, 0, len)); } while (stderr.available() > 0) { /* int len = */stderr.read(buffer); } } sess.close(); conn.close(); if (success) { Thread.sleep(120000); return null; } else { retry++; if (retry == MAX_RETRY_WIN) { return "SSH Windows Network test fail for account " + _account.get(); } } } catch (Exception e) { s_logger.error(e); retry++; if (retry == MAX_RETRY_WIN) { return "SSH Windows Network test fail with error " + e.getMessage(); } } } }
From source file:com.cloud.test.stress.StressTestDirectAttach.java
private static String sshTest(String host, String password) { int i = 0;//from www.j av a2s . co m if (host == null) { s_logger.info("Did not receive a host back from test, ignoring ssh test"); return null; } if (password == null) { s_logger.info("Did not receive a password back from test, ignoring ssh test"); return null; } // We will retry 5 times before quitting String result = null; int retry = 0; while (true) { try { if (retry > 0) { s_logger.info("Retry attempt : " + retry + " ...sleeping 120 seconds before next attempt. Account is " + _account.get()); Thread.sleep(120000); } s_logger.info("Attempting to SSH into linux host " + host + " with retry attempt: " + retry + ". Account is " + _account.get()); Connection conn = new Connection(host); conn.connect(null, 60000, 60000); s_logger.info("User + " + _account.get() + " ssHed successfully into linux host " + host); boolean isAuthenticated = conn.authenticateWithPassword("root", password); if (isAuthenticated == false) { s_logger.info("Authentication failed for root with password" + password); return "Authentication failed"; } boolean success = false; String linuxCommand = null; if (i % 10 == 0) linuxCommand = "rm -rf *; wget http://192.168.1.250/dump.bin && ls -al dump.bin"; else linuxCommand = "wget http://192.168.1.250/dump.bin && ls -al dump.bin"; Session sess = conn.openSession(); s_logger.info("User " + _account.get() + " executing : " + linuxCommand); sess.execCommand(linuxCommand); InputStream stdout = sess.getStdout(); InputStream stderr = sess.getStderr(); byte[] buffer = new byte[8192]; while (true) { if ((stdout.available() == 0) && (stderr.available() == 0)) { int conditions = sess.waitForCondition( ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 120000); if ((conditions & ChannelCondition.TIMEOUT) != 0) { s_logger.info("Timeout while waiting for data from peer."); return null; } if ((conditions & ChannelCondition.EOF) != 0) { if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { break; } } } while (stdout.available() > 0) { success = true; int len = stdout.read(buffer); if (len > 0) // this check is somewhat paranoid s_logger.info(new String(buffer, 0, len)); } while (stderr.available() > 0) { /* int len = */stderr.read(buffer); } } sess.close(); conn.close(); if (!success) { retry++; if (retry == MAX_RETRY_LINUX) { result = "SSH Linux Network test fail"; } } return result; } catch (Exception e) { retry++; s_logger.error("SSH Linux Network test fail with error"); if (retry == MAX_RETRY_LINUX) { return "SSH Linux Network test fail with error " + e.getMessage(); } } i++; } }
From source file:com.bean.ImagenLogica.java
public String guardarImagen() { File archivo = null;/*from w ww .ja v a2 s. c o m*/ InputStream in = null; String codUsuario = ""; String extension = ""; int i = 0; extension = "." + FilenameUtils.getExtension(this.getObjImagen().getImagen().getFileName()); codUsuario = String.valueOf(new SessionLogica().obtenerUsuarioSession().getCodUsuario()); try { in = this.getObjImagen().getImagen().getInputstream(); byte[] data = new byte[in.available()]; in.read(data); archivo = new File(this.rutaImgPerfil + codUsuario + extension); FileOutputStream out = new FileOutputStream(archivo); out.write(data); System.out.println("Ruta de Path Absolute"); System.out.println(archivo.getAbsolutePath()); in.close(); out.flush(); out.close(); Usuario obj = new SessionLogica().obtenerUsuarioSession(); obj.getObjPerfil().setImagenPer(codUsuario + extension); new SessionLogica().setUsuarioSession(obj); new PerfilLogica().actualizarImagenPerfil(obj); } catch (IOException ex) { System.out.println(ex.getMessage()); return "none.jpg"; } return codUsuario + extension; }
From source file:com.test.hwautotest.emmagee.service.EmmageeService.java
public String getFromAsset(String fileName) { String res = ""; try {//from w w w .ja v a 2 s . c om InputStream in = getResources().getAssets().open(fileName); int length = in.available(); byte[] buffer = new byte[length]; in.read(buffer); res = EncodingUtils.getString(buffer, "GBK"); in.close(); } catch (Exception e) { e.printStackTrace(); } return res; }
From source file:com.ewcms.web.pubsub.PubsubServlet.java
/** * Comet event?// w w w . j a v a2 s . c om * * ???<a href = "http://tomcat.apache.org/tomcat-6.0-doc/aio.html#Example_code">ChatServlet</a> * * @param event * The Comet event that will be processed * @throws IOException * @throws ServletException */ public void event(CometEvent event) throws IOException, ServletException { HttpServletRequest request = event.getHttpServletRequest(); HttpServletResponse response = event.getHttpServletResponse(); if (event.getEventType() == CometEvent.EventType.BEGIN) { logger.debug("Begin for session:{} ", request.getSession(true).getId()); String fullContentType = "text/html;charset=UTF-8"; response.setContentType(fullContentType); addConnection(request.getPathInfo(), response); } else if (event.getEventType() == CometEvent.EventType.ERROR) { logger.debug("Error for session: {}", request.getSession(true).getId()); removeConnection(response); event.close(); } else if (event.getEventType() == CometEvent.EventType.END) { logger.debug("End for session:{} ", request.getSession(true).getId()); removeConnection(response); event.close(); } else if (event.getEventType() == CometEvent.EventType.READ) { InputStream is = request.getInputStream(); byte[] buf = new byte[512]; do { int n = is.read(buf); // can throw an IOException if (n > 0) { logger.debug("Read {} bytes:{} for session:{}", new Object[] { n, new String(buf, 0, n), request.getSession(true).getId() }); } else if (n < 0) { return; } } while (is.available() > 0); } }
From source file:com.janoz.usenet.searchers.impl.NewzbinConnectorTest.java
private String readStream(InputStream is) throws IOException { byte[] bytes = new byte[is.available()]; is.read(bytes);//from www . j a va 2 s. co m return new String(bytes, "UTF8"); }