/** * Determines if file is jsp fragment or not (does a deep, indepth check, looking into contents of * file) * * @param file assumes file is not null and exists * @return true if file is jsp fragment, false otherwise */ private boolean isFragment(IFile file) { // copied from JSPValidator boolean isFragment = false; InputStream is = null; try { IContentDescription contentDescription = file.getContentDescription(); // it can be null if (contentDescription == null) { is = file.getContents(); contentDescription = Platform.getContentTypeManager() .getDescriptionFor( is, file.getName(), new QualifiedName[] {IContentDescription.CHARSET}); } if (contentDescription != null) { String fileCtId = contentDescription.getContentType().getId(); isFragment = (fileCtId != null && ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT.equals(fileCtId)); } } catch (IOException e) { // ignore, assume it's invalid JSP } catch (CoreException e) { // ignore, assume it's invalid JSP } finally { // must close input stream in case others need it if (is != null) try { is.close(); } catch (Exception e) { // not sure how to recover at this point } } return isFragment; }
private void processReturn() throws IOException { InputStream is = null; BufferedReader rd = null; try { if (processReturn(connection.getResponseCode())) { is = connection.getInputStream(); rd = new BufferedReader(new InputStreamReader(is)); String line; response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } } } catch (IOException e) { if (e instanceof ConnectException) throw new IOException("Não foi possível conectar com o servidor."); throw new IOException("Erro ao efetuar leitura dos dados retornados"); } finally { try { if (rd != null) rd.close(); if (is != null) is.close(); } catch (IOException e) { L.output(e.getMessage()); } } }
private void performHttpCall(String host, int port, String path, String expected) throws IOException { URLConnection conn = null; InputStream in = null; StringWriter writer = new StringWriter(); try { URL url = new URL( "http://" + TestSuiteEnvironment.formatPossibleIpv6Address(host) + ":" + port + "/" + path); // System.out.println("Reading response from " + url + ":"); conn = url.openConnection(); conn.setDoInput(true); in = new BufferedInputStream(conn.getInputStream()); int i = in.read(); while (i != -1) { writer.write((char) i); i = in.read(); } assertTrue((writer.toString().indexOf(expected) > -1)); // System.out.println("OK"); } finally { safeClose(in); safeClose(writer); } }
public Bitmap getBitmap(String fileId, String size, boolean fromUrl) { File file = fileCache.getFile(fileId + size); // from SD cache Bitmap bitmap = decodeFile(file, size); if (bitmap != null) { return bitmap; } // from web try { bitmap = null; if (fromUrl) { InputStream is = ConnectionHandler.httpGetRequest(fileId, UsersManagement.getLoginUser().getId()); OutputStream os = new FileOutputStream(file); Utils.copyStream(is, os); os.close(); is.close(); } else { CouchDB.downloadFile(fileId, file); } bitmap = decodeFile(file, size); return bitmap; // return ConnectionHandler.getBitmapObject(url); } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
@Test public void verifySignedJar() throws Exception { String classpath = System.getProperty("java.class.path"); String[] entries = classpath.split(System.getProperty("path.separator")); String signedJarFile = null; for (String entry : entries) { if (entry.contains("bcprov")) { signedJarFile = entry; } } assertThat(signedJarFile).isNotNull(); java.util.jar.JarFile jarFile = new JarFile(new File(signedJarFile)); jarFile.getManifest(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); InputStream inputStream = jarFile.getInputStream(jarEntry); inputStream.skip(Long.MAX_VALUE); inputStream.close(); if (!jarEntry.getName().startsWith("META-INF") && !jarEntry.isDirectory() && !jarEntry.getName().endsWith("TigerDigest.class")) { assertThat(jarEntry.getCertificates()).isNotNull(); } } jarFile.close(); }
public static void saveImageToDisk( InputStream inputStream, String fileOriginalName, String fileSaveName, String savePath) { int read = 0; byte[] bytes = new byte[1024]; OutputStream out = null; try { String extension = getExtension(fileOriginalName); out = new FileOutputStream(new File(savePath, fileSaveName + "." + extension)); while ((read = inputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } } catch (Exception e) { e.printStackTrace(); } finally { try { inputStream.close(); out.flush(); out.close(); // Chama o garbage collector para remover a img temporaria System.gc(); } catch (IOException e) { e.printStackTrace(); } } }
/** * Load a system library from a stream. Copies the library to a temp file and loads from there. * * @param libname name of the library (just used in constructing the library name) * @param is InputStream pointing to the library */ private void loadLibraryFromStream(String libname, InputStream is) { try { File tempfile = createTempFile(libname); OutputStream os = new FileOutputStream(tempfile); logger.debug("tempfile.getPath() = " + tempfile.getPath()); long savedTime = System.currentTimeMillis(); // Leo says 8k block size is STANDARD ;) byte buf[] = new byte[8192]; int len; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } os.flush(); InputStream lock = new FileInputStream(tempfile); os.close(); double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3; logger.debug("Copying took " + seconds + " seconds."); logger.debug("Loading library from " + tempfile.getPath() + "."); System.load(tempfile.getPath()); lock.close(); } catch (IOException io) { logger.error("Could not create the temp file: " + io.toString() + ".\n"); } catch (UnsatisfiedLinkError ule) { logger.error("Couldn't load copied link file: " + ule.toString() + ".\n"); throw ule; } }
public Object engineRead() throws StreamParsingException { try { if (sData != null) { if (sDataObjectCount != sData.size()) { return getCertificate(); } else { sData = null; sDataObjectCount = 0; return null; } } currentStream.mark(10); int tag = currentStream.read(); if (tag == -1) { return null; } if (tag != 0x30) // assume ascii PEM encoded. { currentStream.reset(); return readPEMCertificate(currentStream); } else { currentStream.reset(); return readDERCertificate(currentStream); } } catch (Exception e) { throw new StreamParsingException(e.toString(), e); } }
private Section readNextSection(InputStream inChannel) throws IOException { int read = inChannel.read(lengthBytes); if (read != -1) { if (read < lengthBytes.length) { throw new IllegalArgumentException(); } if (inChannel.read(chunkTypeBytes) < chunkTypeBytes.length) { throw new IllegalArgumentException(); } IntBuffer lengthBuffer = ByteBuffer.wrap(lengthBytes).order(ByteOrder.BIG_ENDIAN).asIntBuffer(); sectionLength = lengthBuffer.get(0); String chunkTypeString = new String(chunkTypeBytes, asciiCharset); if ("IHDR".equals(chunkTypeString)) { return new HeaderSection(); } else if ("PLTE".equals(chunkTypeString)) { return new PaletteSection(); } else if ("IDAT".equals(chunkTypeString)) { return new DataSection(); } else { return new Section(); } } else { return null; } }
private String downloadUrl(String myurl) throws IOException { InputStream is = null; // Only display the first 500 characters of the retrieved // web page content. int len = 500; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); Log.d(DEBUG_TAG, "The response is: " + response); is = conn.getInputStream(); // Convert the InputStream into a string String contentAsString = readIt(is, len); return contentAsString; // Makes sure that the InputStream is closed after the app is // finished using it. } finally { if (is != null) { is.close(); } } }
public static BinaryData createBinaryData(final FileItem fileItem, final String label) throws VerticalAdminException { BinaryData binaryData = new BinaryData(); InputStream fis = null; try { binaryData.fileName = FileUtil.getFileName(fileItem); fis = fileItem.getInputStream(); ByteArrayOutputStream bao = new ByteArrayOutputStream(); byte[] buf = new byte[1024 * 10]; int size; while ((size = fis.read(buf)) > 0) { bao.write(buf, 0, size); } binaryData.data = bao.toByteArray(); binaryData.label = label; } catch (IOException e) { VerticalAdminLogger.errorAdmin(AdminHandlerBaseServlet.class, 20, "I/O error: %t", e); } finally { try { if (fis != null) { fis.close(); } } catch (IOException ioe) { String message = "Failed to close file input stream: %t"; VerticalAdminLogger.warn(AdminHandlerBaseServlet.class, 0, message, ioe); } } return binaryData; }
public boolean copyFile(String oldPath, String newPath) { boolean isok = true; try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { // 文件存在时 InputStream inStream = new FileInputStream(oldPath); // 读入原文件 FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1024]; int length; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; // 字节数 文件大小 // System.out.println(bytesum); fs.write(buffer, 0, byteread); } fs.flush(); fs.close(); inStream.close(); } else { isok = false; } } catch (Exception e) { // System.out.println("复制单个文件操作出错"); // e.printStackTrace(); isok = false; } return isok; }
private static SSLContext createBougusServerSslContext() throws GeneralSecurityException, IOException { // Create keystore KeyStore ks = KeyStore.getInstance("JKS"); InputStream in = null; try { in = BogusSslContextFactory.class.getResourceAsStream(BOGUS_KEYSTORE); ks.load(in, BOGUS_PW); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } } // Set up key manager factory to use our key store KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM); kmf.init(ks, BOGUS_PW); // Initialize the SSLContext to work with our key managers. SSLContext sslContext = SSLContext.getInstance(PROTOCOL); sslContext.init(kmf.getKeyManagers(), BogusTrustManagerFactory.X509_MANAGERS, null); return sslContext; }
public void run() { runs = true; // notification about starting the input process stream.postEvent(new ServerEvent(this, stream, ServerEvent.INPUT_START)); changeState(new HeaderDetectionState(this, stream)); byte[] buffer = new byte[65535]; int offset = 0; int length = 0; while (runs && stream.running()) { try { // starting time of the transfer long transferStart = new Date().getTime(); // reading data int red = input.read(buffer, offset, buffer.length - offset); // notification about the transfer stream.postEvent( new TransferEvent( this, stream, TransferEvent.STREAM_INPUT, red, new Date().getTime() - transferStart)); if (red == -1) runs = false; length += red; int newOffset = currentState.processData(buffer, 0, length); if (newOffset < offset + length) { length = length - newOffset; System.arraycopy(buffer, newOffset, buffer, 0, length); offset = length; } else { length = 0; offset = 0; } } catch (SocketTimeoutException e) { continue; } catch (Exception e) { e.printStackTrace(); runs = false; } } try { input.close(); } catch (Exception e) { throw new RuntimeException(e); } // notification about ending the input process stream.postEvent(new ServerEvent(this, stream, ServerEvent.INPUT_STOP)); }
@Test public void testByteRange() throws Exception { String urlString = "http://www.broadinstitute.org/igv/projects/dev/echo.php"; String byteRange = "bytes=" + 5 + "-" + 10; HttpURLConnection conn = (HttpURLConnection) (new URL(urlString)).openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Range", byteRange); InputStream is = null; int lines = 0; try { is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String nextLine; while ((nextLine = br.readLine()) != null) { lines++; } } finally { if (is != null) { is.close(); } } assertTrue(lines > 0); }
/** * 从文件读取json字符串 * * @param path 目录 * @param name 文件名称 * @return 返回字符串 */ public static String readJsonFromFile(String path, String name) { if (StringUtils.isEmpty(path) || StringUtils.isEmpty(name)) { return null; } String content = ""; File file = new File(path + name); if (!file.exists()) { return null; } InputStream in = null; try { in = new FileInputStream(file); if (in != null) { InputStreamReader inputreader = new InputStreamReader(in); BufferedReader buffreader = new BufferedReader(inputreader); String line; // 分行读取 while ((line = buffreader.readLine()) != null) { content += line; } in.close(); } } catch (IOException e) { e.printStackTrace(); return null; } return content; }
/** * Copies resource file 'from' from destination 'to' and set execution permission. * * @param from * @param to * @throws Exception */ protected void copyFile(String from, String to, String workingDirectory) throws Exception { // // copy the shell script to the working directory // // URL monitorCallShellScriptUrl = // Thread.currentThread().getContextClassLoader().getResource(from); // File f = new File(monitorCallShellScriptUrl.getFile()); // String directoryPath = f.getAbsolutePath(); /* URL urlJar = new URL(directoryPath.substring( directoryPath.indexOf("file:"), directoryPath.indexOf("plato.jar")+"plato.jar".length())); JarFile jf = new JarFile(urlJar.getFile()); JarEntry je = jf.getJarEntry(from); String fileName = je.getName(); */ InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(from); File outScriptFile = new File(to); FileOutputStream fos = new FileOutputStream(outScriptFile); int nextChar; while ((nextChar = in.read()) != -1) { fos.write(nextChar); } fos.flush(); fos.close(); }
/** * Load an entire resource text file into {@link String}. * * @param path the path to the resource file. * @return the entire content of the resource text file. */ private String getResourceDocumentContent(String path) { InputStream in = this.getClass().getClassLoader().getResourceAsStream(path); if (in != null) { try { StringBuffer content = new StringBuffer(in.available()); InputStreamReader isr = new InputStreamReader(in); try { BufferedReader reader = new BufferedReader(isr); for (String str = reader.readLine(); str != null; str = reader.readLine()) { content.append(str); content.append('\n'); } } finally { isr.close(); } return content.toString(); } catch (IOException e) { // No resource file as been found or there is a problem when read it. } } return null; }
@Override protected void writeSectionData(InputStream inChannel, OutputStream outChannel) throws IOException { if (!isIndexed) { super.writeSectionData(inChannel, outChannel); } else { byte[] data = new byte[2000 * 3]; int read; int remaining = sectionLength; assert (data.length < BUFFER_SIZE); CRC32 crc32 = new CRC32(); crc32.update(chunkTypeBytes); while ((read = (inChannel.read(data, 0, Math.min(remaining, data.length)))) > 0) { remaining -= read; transformColors(data, 0, read); outChannel.write(data, 0, read); crc32.update(data, 0, read); } if (remaining > 0) { throw new IllegalArgumentException(); } inChannel.skip(4); writeInt(outChannel, (int) crc32.getValue()); } }
public String getDeviceName(Context context) { String manufacturer = Build.MANUFACTURER; String undecodedModel = Build.MODEL; String model = null; try { Properties prop = new Properties(); InputStream fileStream; // Read the device name from a precomplied list: // see http://making.meetup.com/post/29648976176/human-readble-android-device-names fileStream = context.getAssets().open("android_models.properties"); prop.load(fileStream); fileStream.close(); String decodedModel = prop.getProperty(undecodedModel.replaceAll(" ", "_")); if (decodedModel != null && !decodedModel.trim().equals("")) { model = decodedModel; } } catch (IOException e) { AppLog.e(T.UTILS, e.getMessage()); } if (model == null) { // Device model not found in the list if (undecodedModel.startsWith(manufacturer)) { model = capitalize(undecodedModel); } else { model = capitalize(manufacturer) + " " + undecodedModel; } } return model; }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) { System.gc(); try { InputStream in = getContentResolver().openInputStream(data.getData()); Bitmap img = BitmapFactory.decodeStream(in); in.close(); // ?½I?½?½?½?½?½?½?½æ‘œï¿½?½\?½?½ // imgView.setImageBitmap(img); // TwCameraActivity.Picture = img; } catch (Exception e) { } // TwCameraActivity.Mode = TwCameraActivity.MODE_RESULT; // Intent intent = new Intent(this, biz.r8b.twitter.basic.TwCameraActivity.class); startActivity(intent); finish(); } }
private void streamResponse(Response resp, ResponseParams rp) throws IOException { OutputStream body = null; try { if (rp.staticFile) { String fileName = rp.message; body = resp.getOutputStream(); byte[] buffer = new byte[32 * 1024]; InputStream input = configReader.getStaticFile(fileName); int bytesRead; while ((bytesRead = input.read(buffer, 0, buffer.length)) > 0) { body.write(buffer, 0, bytesRead); } } else { body = resp.getPrintStream(); if (body != null) { ((PrintStream) body).print(rp.message); } } } finally { if (body != null) { try { body.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Exception on MockServer close", e); } } } }
public Bitmap getBitmap(String url) { File f = fileCache.getFile(url); // from SD cache Bitmap bitmap = decodeFile(f); if (bitmap != null) { Logger.error("ImageLoader", "fileCache.returnBitmap : " + url); return bitmap; } // from web try { bitmap = null; InputStream is = ConnectionHandler.httpGetRequest(url, UsersManagement.getLoginUser().getId()); OutputStream os = new FileOutputStream(f); Utils.copyStream(is, os); os.close(); is.close(); // conn.disconnect(); bitmap = decodeFile(f); return bitmap; // return ConnectionHandler.getBitmapObject(url); } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
private boolean loadManagementAgentViaJcmd(VirtualMachine vm) throws IOException { if (vm instanceof HotSpotVirtualMachine) { HotSpotVirtualMachine hsvm = (HotSpotVirtualMachine) vm; InputStream in = null; try { byte b[] = new byte[256]; int n; in = hsvm.executeJCmd(ENABLE_LOCAL_AGENT_JCMD); do { n = in.read(b); if (n > 0) { String s = new String(b, 0, n, "UTF-8"); // NOI18N System.out.print(s); } } while (n > 0); return true; } catch (IOException ex) { LOGGER.log( Level.INFO, "jcmd command \"" + ENABLE_LOCAL_AGENT_JCMD + "\" for PID " + vmid + " failed", ex); // NOI18N } finally { if (in != null) { in.close(); } } } return false; }
private void copyDataBase() throws IOException { /** * Copies your database from your local assets-folder to the just created empty database in the * system folder, from where it can be accessed and handled. This is done by transferring byte * stream. */ // Open your local db as the input stream InputStream myInput = context.getAssets().open(DATABASE_NAME); // Path to the just created empty db String outFileName = DB_PATH + DATABASE_NAME; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the input file to the output file byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); }
/** * Copy a file into another. The directory structure of target file will be created if needed. * * @param source the source file * @param destination the target file * @return true if the copy happened without error, false otherwise */ public static boolean copy(final File source, final File destination) { FileUtils.mkdirs(destination.getParentFile()); InputStream input = null; OutputStream output = null; boolean copyDone = false; try { input = new BufferedInputStream(new FileInputStream(source)); output = new BufferedOutputStream(new FileOutputStream(destination)); copyDone = copy(input, output); // close here already to catch any issue with closing input.close(); output.close(); } catch (final FileNotFoundException e) { Log.e("LocalStorage.copy: could not copy file", e); return false; } catch (final IOException e) { Log.e("LocalStorage.copy: could not copy file", e); return false; } finally { // close here quietly to clean up in all situations IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } return copyDone; }
public static void downloadIt() { URL website; try { website = new URL(MainConstants.SOURCES_URL); try { InputStream in = new BufferedInputStream(website.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n = 0; while (-1 != (n = in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); byte[] response = out.toByteArray(); FileOutputStream fos = new FileOutputStream(MainConstants.INPUT_ZIP_FILE); fos.write(response); fos.close(); System.out.println("Download finished."); } catch (IOException ce) { System.out.print("Connection problem : " + ce); } } catch (MalformedURLException e) { e.printStackTrace(); } }
public void testAll() throws Exception { XMLHelper xmlHelper = new XMLHelper(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = cl.getResourceAsStream("org/hibernate/test/annotations/reflection/orm.xml"); assertNotNull("ORM.xml not found", is); XMLContext context = new XMLContext(); List errors = new ArrayList(); SAXReader saxReader = xmlHelper.createSAXReader("XML InputStream", errors, EJB3DTDEntityResolver.INSTANCE); // saxReader.setValidation( false ); try { saxReader.setFeature("http://apache.org/xml/features/validation/schema", true); } catch (SAXNotSupportedException e) { saxReader.setValidation(false); } org.dom4j.Document doc; try { doc = saxReader.read(new InputSource(new BufferedInputStream(is))); } finally { try { is.close(); } catch (IOException ioe) { // log.warn( "Could not close input stream", ioe ); } } assertEquals(0, errors.size()); context.addDocument(doc); }
/** * 写文件 * * @param 文件写的文件被打开 。 * @param 流的输入流 * @param 附加 如果为 ture,然后将写入的字节数文件,而不是开始 * @return return true * @throws RuntimeException 如果运行时FileOutputStream时发生错误 */ public static boolean writeFile(File file, InputStream stream, boolean append) { OutputStream o = null; try { makeDirs(file.getAbsolutePath()); o = new FileOutputStream(file, append); byte data[] = new byte[1024]; int length = -1; while ((length = stream.read(data)) != -1) { o.write(data, 0, length); } o.flush(); return true; } catch (FileNotFoundException e) { throw new RuntimeException("FileNotFoundException occurred. ", e); } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { if (o != null) { try { o.close(); stream.close(); } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } } } }
// Only for test private int getVideoDimens() { File file = new File("sdcard/nim.properties"); if (file.exists()) { InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); Properties properties = new Properties(); properties.load(is); int dimens = Integer.parseInt(properties.getProperty("avchat.video.dimens", "0")); LogUtil.i(TAG, "dimes:" + dimens); return dimens; } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } return 0; }