/** * This verifies that the PseudoServer can be restricted to a HTTP/1.0. */ public void testProtocolThrottling() throws Exception { getServer().setMaxProtocolLevel( 1, 0 ); defineResource( "sample", "Get this", "text/plain" ); Socket socket = new Socket( "localhost", getHostPort() ); OutputStream os = socket.getOutputStream(); InputStream is = new BufferedInputStream( socket.getInputStream() ); sendHTTPLine( os, "GET /sample HTTP/1.1" ); sendHTTPLine( os, "Host: meterware.com" ); sendHTTPLine( os, "Connection: close" ); sendHTTPLine( os, "" ); StringBuffer sb = new StringBuffer(); int b; while (-1 != (b = is.read())) sb.append( (char) b ); String result = sb.toString(); assertTrue( "Did not find matching protocol", result.startsWith( "HTTP/1.0" ) ); assertTrue( "Did not find expected text", result.indexOf( "Get this" ) > 0 ); }
/** * The sound is load and play in a thread no slow down the engine. * */ @Override public void run() { try { InputStream in = new BufferedInputStream(this.getClass().getResourceAsStream(this.filename + ".wav")); Clip clip = AudioSystem.getClip(); clip.open(AudioSystem.getAudioInputStream(in)); if (this.loop){ clip.loop(Clip.LOOP_CONTINUOUSLY); } clip.start(); }catch (Exception e){ System.err.println(e); } }
public boolean uploadFile(File file, byte[] value) { boolean result = false; if (null == value) { return result; } FTPClient ftpClient = ftpConnManager.getFTPClient(); if (null == ftpClient || !ftpClient.isConnected()) { return result; } try (BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(value))) { boolean storeFile = ftpClient.storeFile(file.getName(), in); if (storeFile) { result = true; log.info("file-->" + file.getPath() + "成功上传至FTP服务器"); } } catch (Exception e) { log.error("error", e); } finally { disconnect(ftpClient); } return result; }
public Bitmap decodeSampledBitmapFromUri(Uri fileUri, int reqWidth, int reqHeight) throws IOException { InputStream stream = new BufferedInputStream( mApplicationContext.getContentResolver().openInputStream(fileUri)); stream.mark(stream.available()); BitmapFactory.Options options = new BitmapFactory.Options(); // First decode with inJustDecodeBounds=true to check dimensions options.inJustDecodeBounds = true; BitmapFactory.decodeStream(stream, null, options); stream.reset(); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; BitmapFactory.decodeStream(stream, null, options); // Decode bitmap with inSampleSize set stream.reset(); return BitmapFactory.decodeStream(stream, null, options); }
/** * Load UTF8withBOM or any ansi text file. * * @throws java.io.IOException */ public static String loadFileAsString(String filename) throws java.io.IOException { final int BUFLEN = 1024; BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN); byte[] bytes = new byte[BUFLEN]; boolean isUTF8 = false; int read, count = 0; while ((read = is.read(bytes)) != -1) { if (count == 0 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { isUTF8 = true; baos.write(bytes, 3, read - 3); // drop UTF8 bom marker } else { baos.write(bytes, 0, read); } count += read; } return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray()); } finally { try { is.close(); } catch (Exception ex) { } } }
/** * 压缩文件 * * @param resFile 需要压缩的文件(夹) * @param zipout 压缩的目的文件 * @param rootpath 压缩的文件路径 * @throws FileNotFoundException 找不到文件时抛出 * @throws IOException 当压缩过程出错时抛出 */ public static void zipFile(File resFile, ZipOutputStream zipout, String rootpath) throws FileNotFoundException, IOException { rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator) + resFile.getName(); rootpath = new String(rootpath.getBytes("8859_1"), "GB2312"); if (resFile.isDirectory()) { File[] fileList = resFile.listFiles(); for (File file : fileList) { zipFile(file, zipout, rootpath); } } else { byte buffer[] = new byte[BUFF_SIZE]; BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile), BUFF_SIZE); zipout.putNextEntry(new ZipEntry(rootpath)); int realLength; while ((realLength = in.read(buffer)) != -1) { zipout.write(buffer, 0, realLength); } in.close(); zipout.flush(); zipout.closeEntry(); } }
/** * Tests whether iTXt chunks are successfully skipped without losing * any other image data. */ @Test public void testSkipiTXt() throws IOException { final InputStream ein = new FileInputStream(no_iTXt); final byte[] expected = IOUtils.toByteArray(ein); ein.close(); final InputStream rin = new PNGChunkSkipInputStream(Collections.singleton(PNGDecoder.iTXt), new BufferedInputStream(new FileInputStream(iTXt)) ); final byte[] result = IOUtils.toByteArray(rin); rin.close(); assertArrayEquals(expected, result); }
void connect() throws IOException { System.out.println("Client: connect to server"); try ( BufferedInputStream bis = new BufferedInputStream( socket.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream( socket.getOutputStream())) { bos.write('x'); bos.flush(); int read = bis.read(); if (read < 0) { throw new IOException("Client: couldn't read a response"); } socket.getSession().invalidate(); } }
/** * Loads an xml file without doing xml validation and return a {@link XmlDocument} * * @param displayName the xml file display name. * @param xmlFile the xml file. * @return the initialized {@link XmlDocument} */ public static XmlDocument load( KeyResolver<String> selectors, KeyBasedValueResolver<SystemProperty> systemPropertyResolver, String displayName, File xmlFile, XmlDocument.Type type, Optional<String> mainManifestPackageName) throws IOException, SAXException, ParserConfigurationException { InputStream inputStream = new BufferedInputStream(new FileInputStream(xmlFile)); PositionXmlParser positionXmlParser = new PositionXmlParser(); Document domDocument = positionXmlParser.parse(inputStream); return domDocument != null ? new XmlDocument(positionXmlParser, new SourceLocation(displayName, xmlFile), selectors, systemPropertyResolver, domDocument.getDocumentElement(), type, mainManifestPackageName) : null; }
/** * Returns the md5 hash of a file in hex form. * @param file the file to hash * @return the md5 hash */ public static String getMD5(File file) { try { InputStream in = new BufferedInputStream(new FileInputStream(file)); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] buf = new byte[4096]; while (true) { int len = in.read(buf); if (len < 0) break; md.update(buf, 0, len); } in.close(); byte[] md5byte = md.digest(); StringBuilder result = new StringBuilder(); for (byte b : md5byte) result.append(String.format("%02x", b)); return result.toString(); } catch (NoSuchAlgorithmException | IOException e) { System.err.println("Failed to calculate MD5 hash."); } return null; }
/** * Initializes an input stream from a URL. * * @param url the URL * @throws IllegalArgumentException if cannot open {@code url} * @throws NullPointerException if {@code url} is {@code null} */ public In(URL url) { if (url == null) throw new NullPointerException("argument is null"); try { URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME); scanner.useLocale(LOCALE); } catch (IOException ioe) { throw new IllegalArgumentException("Could not open " + url); } }
/** * Loads the requested {@link GameSaveInterface} from the requested file * * @param gameSaveFile The file from which to get the save * * @return the {@link GameSaveInterface} stored into the given file * @throws UnableToLoadSaveException if a problem happens during the loading of the save, for example if the file can't * be opened or the content of the file isn't a serialized {@link GameSaveInterface} */ public static GameSaveInterface loadGameSave(File gameSaveFile) throws UnableToLoadSaveException { // We check the file's integrity, if the save is acceptable. if (!gameSaveFile.isFile() || !gameSaveFile.getName().endsWith(GameSaver.GAME_SAVES_FILES_EXTENSION)) { throw new UnableToLoadSaveException(); } // We try to load the GameSave from the file. If an error happens, we throw an Exception try { ObjectInputStream objectInputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(gameSaveFile))); GameSaveInterface gameSave = (GameSaveInterface) objectInputStream.readObject(); objectInputStream.close(); return gameSave; } catch (IOException | ClassNotFoundException e) { throw new UnableToLoadSaveException(); } }
public SSLContextPinner(String pemAssetName) { try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); InputStream certInputStream = getAssets().open(pemAssetName); BufferedInputStream bis = new BufferedInputStream(certInputStream); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); int idx = -1; while (bis.available() > 0) { Certificate cert = certificateFactory.generateCertificate(bis); keyStore.setCertificateEntry("" + ++idx, cert); Log.i("App", "pinned " + idx + ": " + ((X509Certificate) cert).getSubjectDN()); } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); trustManager = trustManagers[0]; sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, null); } catch(Exception e) { sslContext = null; trustManager = null; Log.e("App", e.toString()); } }
public InputStream openInputStream() throws IOException { // Get the inputstream from the connection to avoid duplicate calls // to URL.openConnection _lastModifiedTime = URLUtils.getLastModified(_url); URLConnection connection = _url.openConnection(); // avoid URL caching // if we use URL caching the files which changed do not get loaded completely connection.setUseCaches(false); // In theory, should not need to close InputStream base = connection.getInputStream(); if (base instanceof BufferedInputStream) return base; else return new BufferedInputStream(base); }
LearnerHandler(Socket sock, BufferedInputStream bufferedInput, Leader leader) throws IOException { super("LearnerHandler-" + sock.getRemoteSocketAddress()); this.sock = sock; this.leader = leader; this.bufferedInput = bufferedInput; try { leader.self.authServer.authenticate(sock, new DataInputStream(bufferedInput)); } catch (IOException e) { LOG.error("Server failed to authenticate quorum learner, addr: {}, closing connection", sock.getRemoteSocketAddress(), e); try { sock.close(); } catch (IOException ie) { LOG.error("Exception while closing socket", ie); } throw new SaslException("Authentication failure: " + e.getMessage()); } }
private void downloadFile(ResponseBody body) throws IOException { int count; byte data[] = new byte[1024 * 4]; InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8); outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "file.zip"); OutputStream output = new FileOutputStream(outputFile); while ((count = bis.read(data)) != -1) { output.write(data, 0, count); } output.flush(); output.close(); bis.close(); Intent target = new Intent(Intent.ACTION_VIEW); target.setDataAndType(Uri.fromFile(outputFile), "application/pdf"); target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); Intent intent = Intent.createChooser(target, "Open File"); try { startActivity(intent); } catch (ActivityNotFoundException e) { e.printStackTrace(); } }
/** * Check if the CRC of the snapshot file matches the digest. * @param f The snapshot file object * @return The table list as a string * @throws IOException If CRC does not match */ public static String CRCCheck(File f) throws IOException { final FileInputStream fis = new FileInputStream(f); try { final BufferedInputStream bis = new BufferedInputStream(fis); ByteBuffer crcBuffer = ByteBuffer.allocate(4); if (4 != bis.read(crcBuffer.array())) { throw new EOFException("EOF while attempting to read CRC from snapshot digest"); } final int crc = crcBuffer.getInt(); final InputStreamReader isr = new InputStreamReader(bis, "UTF-8"); CharArrayWriter caw = new CharArrayWriter(); while (true) { int nextChar = isr.read(); if (nextChar == -1) { throw new EOFException("EOF while reading snapshot digest"); } if (nextChar == '\n') { break; } caw.write(nextChar); } String tableList = caw.toString(); byte tableListBytes[] = tableList.getBytes("UTF-8"); CRC32 tableListCRC = new CRC32(); tableListCRC.update(tableListBytes); tableListCRC.update("\n".getBytes("UTF-8")); final int calculatedValue = (int)tableListCRC.getValue(); if (crc != calculatedValue) { throw new IOException("CRC of snapshot digest did not match digest contents"); } return tableList; } finally { try { if (fis != null) fis.close(); } catch (IOException e) {} } }
public static boolean verifyBitmap(InputStream input) { if (input == null) { return false; } final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; input = input instanceof BufferedInputStream ? input : new BufferedInputStream(input); BitmapFactory.decodeStream(input, null, options); try { input.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return (options.outHeight > 0) && (options.outWidth > 0); }
/** * 读取文件file,返回文件内容。如果文件为空,返回空字符串 * * @param file File * @return 文件内容 */ public static String readFile(File file) { try { FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); byte[] byteArray = getByteArray(); StringBuffer stringBuffer = new StringBuffer(); int length; while((length = bis.read(byteArray)) != -1) { stringBuffer.append(new String(byteArray, 0, length)); } bis.close(); fis.close(); return stringBuffer.toString(); } catch(IOException e) { e.printStackTrace(); } return TextTool.emptyString(); }
public static void unzip( ZipFile zip, File dest ) throws IOException { for( Enumeration<? extends ZipEntry> e = zip.entries(); e.hasMoreElements(); ) { ZipEntry entry = e.nextElement(); File f = new File( dest, entry.getName() ); if ( entry.isDirectory() ) { f.mkdirs(); } else { f.getParentFile().mkdirs(); f.createNewFile(); BufferedInputStream bis = new BufferedInputStream( zip.getInputStream( entry ) ); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream( f ) ); copyFile( bis, bos ); } } }
/** * Load the gzipped compound from the inputstream. */ public static NBTTagCompound readCompressed(InputStream is) throws IOException { DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new GZIPInputStream(is))); NBTTagCompound nbttagcompound; try { nbttagcompound = read(datainputstream, NBTSizeTracker.INFINITE); } finally { datainputstream.close(); } return nbttagcompound; }
@SuppressWarnings("unchecked") public synchronized void load(Context context) throws IOException, ClassNotFoundException { FileInputStream fout = new FileInputStream(new File(context.getFilesDir(), "namedb.dat")); ObjectInputStream oos = new ObjectInputStream(new BufferedInputStream(fout)); addressbook = (HashMap<String, String>) oos.readObject(); oos.close(); fout.close(); }
public static boolean closeFile(BufferedInputStream bufStreamIn) { try { if(bufStreamIn != null) { bufStreamIn.close(); return true; } } catch (IOException e) { e.printStackTrace(); } return false; }
public static void main(String[] args) throws Exception { File file = new File(System.getProperty("test.src", "."), "ding.dls"); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); try { Soundbank dls = new DLSSoundbankReader().getSoundbank(bis); assertTrue(dls.getInstruments().length == 1); Patch patch = dls.getInstruments()[0].getPatch(); assertTrue(patch.getProgram() == 0); assertTrue(patch.getBank() == 0); } finally { bis.close(); } }
synchronized public void doLoadFordVIDataFile() { JFileChooser c = new JFileChooser(lastFordVIFile); FileFilter filt = new FileNameExtensionFilter("Ford Vehicle Interface (VI) data file", "dat"); c.addChoosableFileFilter(filt); c.setFileFilter(filt); c.setSelectedFile(new File(lastFordVIFile)); int ret = c.showOpenDialog(chip.getAeViewer()); if (ret != JFileChooser.APPROVE_OPTION) { return; } lastFordVIFile = c.getSelectedFile().toString(); putString("lastFordVIFile", lastFordVIFile); try { fordViFile = c.getSelectedFile(); fordViInputStream = new BufferedInputStream(new FileInputStream(fordViFile)); fordViStates = readFordViJsonStream(fordViInputStream); } catch (Exception ex) { Logger.getLogger(DavisClassifierCNNProcessor.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(chip.getAeViewer().getFilterFrame(), "Couldn't load from this file, caught exception " + ex + ". See console for logging.", "Bad data file", JOptionPane.WARNING_MESSAGE); } }
/** * Download Captured Image Data * Change to Image object from file form of Image data */ private void downloadCapturedImageData(InputStream inputStream) { // inputStream -> bitmap -> file BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); Bitmap imageBitmapData = BitmapFactory.decodeStream(bufferedInputStream); imageToGallery(imageBitmapData); }
/** * Creates a WaveData container from the specified url * * @param path URL to file * @return WaveData containing data, or null if a failure occured */ public static WaveData create(URL path) { try { return create( AudioSystem.getAudioInputStream( new BufferedInputStream(path.openStream()))); } catch (Exception e) { org.lwjgl.LWJGLUtil.log("Unable to create from: " + path); e.printStackTrace(); return null; } }
@RequestMapping(value = "/download/{id}") public void downloadFile(@PathVariable Long id,HttpServletRequest request, HttpServletResponse response) throws Exception { try{ if(id != 0){ EFile fileInfo = fileDao.fetch(id); if(fileInfo!= null){ String path = fileInfo.getPath(); // String suffix = path.split("\\.")[1]; File file = new File(rootPath+path); // String filename = fileInfo.getName()+"."+suffix; InputStream fis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); response.addHeader("Content-Disposition","attachment;filename=" + new String(java.net.URLEncoder.encode(fileInfo.getName(), "UTF-8"))); response.addHeader("Content-Length","" + file.length()); response.setContentType("application/octet-stream"); OutputStream toClient = new BufferedOutputStream( response.getOutputStream()); toClient.write(buffer); toClient.flush(); toClient.close(); } } }catch(Exception e){ LOG.error("下载失败,原因:"+e.getMessage()); } }
@Override protected InputService<TarDriverEntry> newInput( final FsModel model, final FsInputSocketSource source) throws IOException { final class Source extends AbstractSource { @Override public InputStream stream() throws IOException { final InputStream in = source.stream(); try { return new BZip2CompressorInputStream( new BufferedInputStream(in, getBufferSize())); } catch (final Throwable ex) { try { in.close(); } catch (final Throwable ex2) { ex.addSuppressed(ex2); } throw ex; } } } // Source return new TarInputService(model, new Source(), this); }
private static void readHams(String dataSetDirPath, List<Document> dataSet, boolean skipStopwords) { File trainingDataSetHamDir = new File(dataSetDirPath + DIR_HAM); if (trainingDataSetHamDir.exists() && trainingDataSetHamDir.isDirectory()) { File[] hamFiles = trainingDataSetHamDir.listFiles(); if (hamFiles != null) { for (File hamFile : hamFiles) { try { Scanner scanner = new Scanner(new BufferedInputStream(new FileInputStream(hamFile))); StringBuilder stringBuilder = new StringBuilder(); while (scanner.hasNext()) { stringBuilder.append(scanner.nextLine().toLowerCase()); } scanner.close(); Document document = new Document(); document.setDocumentClass(Document.Class.HAM); String[] split = stringBuilder.toString().split("\\s"); List<String> terms = new ArrayList<>(); Collections.addAll(terms, split); if (skipStopwords) { terms.removeAll(Stopwords.wordList); } document.setTerms(terms); dataSet.add(document); } catch (FileNotFoundException e) { e.printStackTrace(); } } } } }
private void internalReset() throws IOException { if (needsReset) { needsReset = false; BufferedInputStream bufferedIn = readStreamHeader(); input = new CBZip2InputStream(bufferedIn, this.readMode); } }
private void readJournal() throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(journalFile), IO_BUFFER_SIZE); try { String magic = readAsciiLine(in); String version = readAsciiLine(in); String appVersionString = readAsciiLine(in); String valueCountString = readAsciiLine(in); String blank = readAsciiLine(in); if (!MAGIC.equals(magic) || !VERSION_1.equals(version) || !Integer.toString(appVersion).equals(appVersionString) || !Integer.toString(valueCount).equals(valueCountString) || !"".equals(blank)) { throw new IOException("unexpected journal header: [" + magic + ", " + version + ", " + valueCountString + ", " + blank + "]"); } while (true) { try { readJournalLine(readAsciiLine(in)); } catch (EOFException endOfJournal) { break; } } } finally { closeQuietly(in); } }
public static <T> DataSinkTransferThread<T> asyncPipeToDataSink( SMimeDataSink<T> dataSink, ParcelFileDescriptor output) throws IOException { InputStream inputStream = new BufferedInputStream(new AutoCloseInputStream(output)); DataSinkTransferThread<T> dataSinkTransferThread = new DataSinkTransferThread<T>(dataSink, inputStream); dataSinkTransferThread.start(); return dataSinkTransferThread; }
/** Obtiene el flujo de entrada de un fichero (para su lectura) a partir de su URI. * @param uri URI del fichero a leer * @return Flujo de entrada hacia el contenido del fichero * @throws IOException Cuando no se ha podido abrir el fichero de datos. */ public static InputStream loadFile(final URI uri) throws IOException { if (uri == null) { throw new IllegalArgumentException("Se ha pedido el contenido de una URI nula"); //$NON-NLS-1$ } if (uri.getScheme().equals("file")) { //$NON-NLS-1$ // Es un fichero en disco. Las URL de Java no soportan file://, con // lo que hay que diferenciarlo a mano // Retiramos el "file://" de la uri String path = uri.getSchemeSpecificPart(); if (path.startsWith("//")) { //$NON-NLS-1$ path = path.substring(2); } return new FileInputStream(new File(path)); } // Es una URL final InputStream tmpStream = new BufferedInputStream(uri.toURL().openStream()); // Las firmas via URL fallan en la descarga por temas de Sun, asi que // descargamos primero // y devolvemos un Stream contra un array de bytes final byte[] tmpBuffer = getDataFromInputStream(tmpStream); return new java.io.ByteArrayInputStream(tmpBuffer); }
public static PGPPublicKey readPublicKey(String fileName) throws IOException, PGPException { InputStream keyIn = new BufferedInputStream(new FileInputStream(fileName)); PGPPublicKey pubKey = readPublicKey(keyIn); keyIn.close(); return pubKey; }
public void setTrustedCertificate(InputStream inputFile) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = new BufferedInputStream(inputFile); Certificate ca = cf.generateCertificate(caInput); // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); } catch (Exception e) { e.printStackTrace(); } }
public void play() { try { BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(filename)); player = new Player(buffer); player.play(); } catch (Exception e) { System.out.println(e); } }
public ReadOnceInputEvent(String appName, String route, String requestUrl, String method, InputStream body, Headers headers, QueryParameters parameters) { this.appName = Objects.requireNonNull(appName); this.route = Objects.requireNonNull(route); this.requestUrl = Objects.requireNonNull(requestUrl); this.method = Objects.requireNonNull(method).toUpperCase(); this.body = new BufferedInputStream(Objects.requireNonNull(body)); this.headers = Objects.requireNonNull(headers); this.queryParameters = Objects.requireNonNull(parameters); body.mark(Integer.MAX_VALUE); }
/** * Utility method that converts an HttpResponse to a String. * * @param response * the response to convert. * @return a String with the response content. * @throws IOException * Signals that an I/O exception has occurred. */ private static String getResponseContent(HttpResponse response) throws IOException { InputStream inputStream = response.getEntity().getContent(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); InputStreamReader inputStreamReader = new InputStreamReader(bufferedInputStream); BufferedReader br = new BufferedReader(inputStreamReader); StringBuilder builder = new StringBuilder(); String output = null; while ((output = br.readLine()) != null) { builder.append(output); } return builder.toString(); }
void connect() throws IOException { System.out.println("Client: connect to server"); try (BufferedInputStream bis = new BufferedInputStream( socket.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream( socket.getOutputStream())) { for (byte[] bytes : arrays) { System.out.println("Client: send byte array: " + Arrays.toString(bytes)); bos.write(bytes); bos.flush(); byte[] recieved = new byte[bytes.length]; int read = bis.read(recieved, 0, bytes.length); if (read < 0) { throw new IOException("Client: couldn't read a response"); } System.out.println("Client: recieved byte array: " + Arrays.toString(recieved)); if (!Arrays.equals(bytes, recieved)) { throw new IOException("Client: sent byte array " + "is not equal with recieved byte array"); } } socket.getSession().invalidate(); } finally { if (!socket.isClosed()) { socket.close(); } } }