List of usage examples for java.io RandomAccessFile length
public native long length() throws IOException;
From source file:com.metamx.druid.merger.coordinator.ForkingTaskRunner.java
@Override public Optional<InputSupplier<InputStream>> streamTaskLog(final String taskid, final long offset) { final ProcessHolder processHolder; synchronized (tasks) { final TaskInfo taskInfo = tasks.get(taskid); if (taskInfo != null && taskInfo.processHolder != null) { processHolder = taskInfo.processHolder; } else {/*from w w w . j a v a2 s . c om*/ return Optional.absent(); } } return Optional.<InputSupplier<InputStream>>of(new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { final RandomAccessFile raf = new RandomAccessFile(processHolder.logFile, "r"); final long rafLength = raf.length(); if (offset > 0) { raf.seek(offset); } else if (offset < 0 && offset < rafLength) { raf.seek(rafLength + offset); } return Channels.newInputStream(raf.getChannel()); } }); }
From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java
private boolean updateINIOnJDKUpgrade(String javaHome) { logger.debug("Updating INI file if JDK path is updated"); RandomAccessFile file = null; boolean isUpdated = false; try {//from w w w . jav a 2s. com file = new RandomAccessFile(new File(HYDROGRAPH_INI), "rw"); byte[] text = new byte[(int) file.length()]; while (file.getFilePointer() != file.length()) { if (StringUtils.equals(file.readLine(), "-vm")) { String currentLine = file.readLine(); if (StringUtils.equals(currentLine, javaHome)) { logger.debug("JAVA_HOME and -vm in configuration file are same"); } else { logger.debug( "JAVA_HOME and -vm in configuration file are different. Updating configuration file with JAVA_HOME"); file.seek(0); file.readFully(text); file.seek(0); updateData(text, javaHome, currentLine, file); isUpdated = true; } break; } } } catch (IOException ioException) { logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException); } finally { try { if (file != null) { file.close(); } } catch (IOException ioException) { logger.error("IOException occurred while closing " + HYDROGRAPH_INI + " file", ioException); } } return isUpdated; }
From source file:com.android.volley.toolbox.UploadNetwork.java
/** Reads the contents of HttpEntity into a byte[]. * @param request // ww w .ja va 2 s . co m * @param acessfile */ private byte[] entityToBytes(HttpEntity entity, DownOrUpRequest request, RandomAccessFile acessfile) throws IOException, ServerError { // PoolingByteArrayOutputStream bytes = // new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength()); long length = acessfile.length(); request.setmMaxLength(entity.getContentLength()); byte[] buffer = new byte[1024]; try { InputStream in = entity.getContent(); if (in == null) { throw new ServerError(); } int count; while ((count = in.read(buffer)) != -1) { if (request.isCanceled()) { break; } acessfile.write(buffer, 0, count); length += count; request.doProcess(length); } return null; } finally { try { // Close the InputStream and release the resources by "consuming the content". entity.consumeContent(); } catch (IOException e) { // This can happen if there was an exception above that left the entity in // an invalid state. VolleyLog.v("Error occured when calling consumingContent"); } // bytes.close(); } }
From source file:com.metamx.druid.indexing.coordinator.ForkingTaskRunner.java
@Override public Optional<InputSupplier<InputStream>> streamTaskLog(final String taskid, final long offset) { final ProcessHolder processHolder; synchronized (tasks) { final ForkingTaskRunnerWorkItem taskWorkItem = tasks.get(taskid); if (taskWorkItem != null && taskWorkItem.processHolder != null) { processHolder = taskWorkItem.processHolder; } else {// w w w .ja va 2 s.c om return Optional.absent(); } } return Optional.<InputSupplier<InputStream>>of(new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { final RandomAccessFile raf = new RandomAccessFile(processHolder.logFile, "r"); final long rafLength = raf.length(); if (offset > 0) { raf.seek(offset); } else if (offset < 0 && offset < rafLength) { raf.seek(rafLength + offset); } return Channels.newInputStream(raf.getChannel()); } }); }
From source file:com.example.android.vault.EncryptedDocument.java
/** * Decrypt and read content section of this document, writing it into the * given pipe./* ww w . ja v a 2 s .c om*/ * <p/> * Pipe is left open, so caller is responsible for calling * {@link ParcelFileDescriptor#close()} or * {@link ParcelFileDescriptor#closeWithError(String)}. * * @param contentOut write end of a pipe. * @throws DigestException if content fails MAC check. Some or all content * may have already been written to the pipe when the MAC is * validated. */ public void readContent(ParcelFileDescriptor contentOut) throws IOException, GeneralSecurityException { final RandomAccessFile f = new RandomAccessFile(mFile, "r"); try { assertMagic(f); if (f.length() <= CONTENT_OFFSET) { throw new IOException("Document has no content"); } // Skip over metadata section f.seek(CONTENT_OFFSET); readSection(f, new FileOutputStream(contentOut.getFileDescriptor())); } finally { f.close(); } }
From source file:edu.harvard.i2b2.adminTool.dataModel.PatientMappingFactory.java
public static void append(RandomAccessFile f, String outString) throws IOException { try {/*from w w w . j a v a2 s . c o m*/ f.seek(f.length()); f.writeBytes(outString); } catch (IOException e) { throw new IOException("trouble writing to random access file."); } return; }
From source file:com.filelocker.encryption.AES_Encryption.java
/** * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). * We have the password from initializing the class. pass the iv and salt here which is * obtained when encrypting the file initially. * * @param inFile - The Encrypted File containing encrypted data , salt and InitVec * @throws NoSuchAlgorithmException//ww w. j a va 2 s . c o m * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws DecoderException * @throws IOException */ public void setupDecrypt(File inFile) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DecoderException, IOException { SecretKeyFactory factory = null; SecretKey tmp = null; SecretKey secret = null; byte[] vSalt = new byte[8]; byte[] vInitVec = new byte[16]; RandomAccessFile vFile = new RandomAccessFile(inFile, "rw"); //The last 8 bits are salt so seek to length of file minus 9 bits vFile.seek(vFile.length() - 8); vFile.readFully(vSalt); //The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24 //Thus to seek to length of file minus 24 bits vFile.seek(vFile.length() - 24); vFile.readFully(vInitVec); vFile.seek(0); File tmpFile = new File(inFile.getAbsolutePath() + ".tmpEncryption.file"); RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile, "rw"); for (int i = 0; i < (vFile.length() - 24); ++i) { vTmpFile.write(vFile.readByte()); } vFile.close(); vTmpFile.close(); inFile.delete(); tmpFile.renameTo(inFile); Db("got salt " + Hex.encodeHexString(vSalt)); Db("got initvector :" + Hex.encodeHexString(vInitVec)); /* Derive the key, given password and salt. */ // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security" // The end user must also install them (not compiled in) so beware. // see here: // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml // PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function //found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard) factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); secret = new SecretKeySpec(tmp.getEncoded(), "AES"); // Decrypt the message, given derived key and initialization vector. vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec)); }
From source file:org.ros.osgi.deployment.master.internal.NettyWebServerHandler.java
/** * Attempt to handle an HTTP request by scanning through all registered * handlers.// ww w. j a v a 2 s . c o m * * @param ctx * The context for the request. * @param req * The request. * @return True if the request was handled, false otherwise. */ private boolean handleWebRequest(ChannelHandlerContext ctx, HttpRequest req) throws IOException { String url = req.getUri(); int pos = url.indexOf('?'); if (pos != -1) url = url.substring(0, pos); int luriPrefixLength = uriPrefix.length(); String bundleName = url.substring(url.indexOf(uriPrefix) + luriPrefixLength); File file = featureRepository.getFeatureFile(bundleName); if (file == null) { return false; } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException fnfe) { // sendError(ctx, NOT_FOUND); return false; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); setContentLength(response, fileLength); Channel ch = ctx.getChannel(); // Write the initial line and the header. ch.write(response); // Write the content. ChannelFuture writeFuture; if (ch.getPipeline().get(SslHandler.class) != null) { // Cannot use zero-copy with HTTPS. writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192)); } else { // No encryption - use zero-copy. final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength); writeFuture = ch.write(region); writeFuture.addListener(new ChannelFutureProgressListener() { @Override public void operationComplete(ChannelFuture future) { region.releaseExternalResources(); } @Override public void operationProgressed(ChannelFuture arg0, long arg1, long arg2, long arg3) throws Exception { // Do nothing } }); } // Decide whether to close the connection or not. if (!isKeepAlive(req)) { // Close the connection when the whole content is written out. writeFuture.addListener(ChannelFutureListener.CLOSE); } return true; }
From source file:cc.arduino.utils.network.FileDownloader.java
private void downloadFile(boolean noResume) throws InterruptedException { RandomAccessFile file = null; try {/*from ww w. j a v a 2 s. c o m*/ // Open file and seek to the end of it file = new RandomAccessFile(outputFile, "rw"); initialSize = file.length(); if (noResume && initialSize > 0) { // delete file and restart downloading Files.delete(outputFile.toPath()); initialSize = 0; } file.seek(initialSize); setStatus(Status.CONNECTING); Proxy proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(downloadUrl.toURI()); if ("true".equals(System.getProperty("DEBUG"))) { System.err.println("Using proxy " + proxy); } HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(proxy); connection.setRequestProperty("User-agent", userAgent); if (downloadUrl.getUserInfo() != null) { String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes())); connection.setRequestProperty("Authorization", auth); } connection.setRequestProperty("Range", "bytes=" + initialSize + "-"); connection.setConnectTimeout(5000); setDownloaded(0); // Connect connection.connect(); int resp = connection.getResponseCode(); if (resp == HttpURLConnection.HTTP_MOVED_PERM || resp == HttpURLConnection.HTTP_MOVED_TEMP) { URL newUrl = new URL(connection.getHeaderField("Location")); proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(newUrl.toURI()); // open the new connnection again connection = (HttpURLConnection) newUrl.openConnection(proxy); connection.setRequestProperty("User-agent", userAgent); if (downloadUrl.getUserInfo() != null) { String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes())); connection.setRequestProperty("Authorization", auth); } connection.setRequestProperty("Range", "bytes=" + initialSize + "-"); connection.setConnectTimeout(5000); connection.connect(); resp = connection.getResponseCode(); } if (resp < 200 || resp >= 300) { throw new IOException("Received invalid http status code from server: " + resp); } // Check for valid content length. long len = connection.getContentLength(); if (len >= 0) { setDownloadSize(len); } setStatus(Status.DOWNLOADING); synchronized (this) { stream = connection.getInputStream(); } byte buffer[] = new byte[10240]; while (status == Status.DOWNLOADING) { int read = stream.read(buffer); if (read == -1) break; file.write(buffer, 0, read); setDownloaded(getDownloaded() + read); if (Thread.interrupted()) { file.close(); throw new InterruptedException(); } } if (getDownloadSize() != null) { if (getDownloaded() < getDownloadSize()) throw new Exception("Incomplete download"); } setStatus(Status.COMPLETE); } catch (InterruptedException e) { setStatus(Status.CANCELLED); // lets InterruptedException go up to the caller throw e; } catch (SocketTimeoutException e) { setStatus(Status.CONNECTION_TIMEOUT_ERROR); setError(e); } catch (Exception e) { setStatus(Status.ERROR); setError(e); } finally { IOUtils.closeQuietly(file); synchronized (this) { IOUtils.closeQuietly(stream); } } }
From source file:org.artifactory.webapp.wicket.page.logs.SystemLogsViewPanel.java
/** * Attemps to continue reading the log file from the last position, and the updates the log path, size and link * According to the outcome.// ww w . j a v a 2 s.c o m * * @param cleanPanel True if the text container should be cleaned of content. false if not * @return String - The newly read content */ protected String readLogAndUpdateSize(boolean cleanPanel) { if ((lastPointer > systemLogFile.length()) || cleanPanel) { lastPointer = 0; } long size = systemLogFile.length(); setLogInfo(); if (lastPointer == size) { return ""; } StringBuilder sb = new StringBuilder(); RandomAccessFile logRandomAccessFile = null; try { logRandomAccessFile = new RandomAccessFile(systemLogFile, "r"); //If the log file is larger than 100K if (lastPointer == 0 && logRandomAccessFile.length() > FIRST_READ_BLOCK_SIZE) { //Point to the begining of the last 100K lastPointer = logRandomAccessFile.length() - FIRST_READ_BLOCK_SIZE; } logRandomAccessFile.seek(lastPointer); String line; while ((line = logRandomAccessFile.readLine()) != null) { CharSequence escapedLine = Strings.escapeMarkup(line, false, false); sb.append("<div>").append(escapedLine).append("<br/></div>"); } lastPointer = logRandomAccessFile.getFilePointer(); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } finally { try { if (logRandomAccessFile != null) { logRandomAccessFile.close(); } } catch (IOException ignore) { } } return sb.toString(); }