List of usage examples for java.io RandomAccessFile getChannel
public final FileChannel getChannel()
From source file:org.apache.tajo.pullserver.HttpDataServerHandler.java
private ChannelFuture sendFile(ChannelHandlerContext ctx, FileChunk file) throws IOException { RandomAccessFile raf; try {// www. j a v a2 s . c o m raf = new RandomAccessFile(file.getFile(), "r"); } catch (FileNotFoundException fnfe) { return null; } ChannelFuture writeFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) != null) { // Cannot use zero-copy with HTTPS. lastContentFuture = ctx .write(new HttpChunkedInput(new ChunkedFile(raf, file.startOffset(), file.length(), 8192))); } else { // No encryption - use zero-copy. final FileRegion region = new DefaultFileRegion(raf.getChannel(), file.startOffset(), file.length()); writeFuture = ctx.write(region); lastContentFuture = ctx.write(LastHttpContent.EMPTY_LAST_CONTENT); writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { if (region.refCnt() > 0) { region.release(); } } }); } return lastContentFuture; }
From source file:interactivespaces.liveactivity.runtime.standalone.development.DevelopmentStandaloneLiveActivityRuntime.java
/** * Get the instance suffix to use for this instance. The suffix returned depends on the number of already running * instances./*from ww w .j a v a 2 s .co m*/ * * @param rootDir * the root directory that holds the instance locks * * @return suffix to use for directories and files */ private String findInstanceSuffix(File rootDir) { if (instanceSuffix != null) { return instanceSuffix; } int instance = 0; while (instance < MAX_INSTANCE_COUNT) { String suffix = instance > 0 ? ("-" + instance) : ""; File lockFile = new File(rootDir, LOCK_FILE_NAME + suffix); try { RandomAccessFile pidRaf = new RandomAccessFile(lockFile, "rw"); FileLock fileLock = pidRaf.getChannel().tryLock(0, Long.MAX_VALUE, false); if (fileLock != null) { return suffix; } } catch (IOException e) { // Do nothing, increment and try again. } instance++; } throw new InteractiveSpacesException("Could not lock run file after " + MAX_INSTANCE_COUNT + " tries"); }
From source file:io.pcp.parfait.dxm.FileByteBufferFactory.java
public ByteBuffer build(int length) throws IOException { RandomAccessFile fos = null; try {//w w w. j ava2s. co m File parent = file.getParentFile(); if (parent == null) { throw new RuntimeException("Could not find parent of output file " + file.getCanonicalPath()); } else if (parent.exists()) { file.delete(); /* directory update visible to MMV PMDA */ if (file.exists()) { throw new RuntimeException("Could not delete existing file " + file.getCanonicalPath()); } } else if (!parent.mkdirs()) { throw new RuntimeException("Could not create output directory " + parent.getCanonicalPath()); } fos = new RandomAccessFile(file, "rw"); fos.setLength(length); ByteBuffer tempDataFile = fos.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, length); tempDataFile.order(ByteOrder.nativeOrder()); fos.close(); return tempDataFile; } finally { if (fos != null) { fos.close(); } } }
From source file:org.fuin.utils4j.Utils4J.java
/** * Lock the file./*from w w w. j av a 2 s . c om*/ * * @param file * File to lock - Cannot be <code>null</code>. * @param tryLockMax * Number of tries to lock before throwing an exception. * @param tryWaitMillis * Milliseconds to sleep between retries. * * @return FileLock. * * @throws LockingFailedException * Locking the file failed. */ public static FileLock lockRandomAccessFile(final RandomAccessFile file, final int tryLockMax, final long tryWaitMillis) throws LockingFailedException { checkNotNull("file", file); final FileChannel channel = file.getChannel(); int tryCount = 0; while (tryCount < tryLockMax) { tryCount++; try { final FileLock lock = channel.tryLock(); if (lock != null) { return lock; } } catch (final IOException ex) { throw new LockingFailedException("Unexpected I/O-Exception!", ex); } catch (final OverlappingFileLockException ex) { ignore(); } try { Thread.sleep(tryWaitMillis); } catch (final InterruptedException ex) { throw new LockingFailedException("Unexpected interrupt!", ex); } } throw new LockingFailedException("Number of max tries (" + tryLockMax + ") exceeded!"); }
From source file:org.oscarehr.document.web.ManageDocumentAction.java
public File createCacheVersion(Document d, int pageNum) throws Exception { File documentCacheDir = new File(EDocUtil.getCacheDirectory()); File file = new File(EDocUtil.getDocumentPath(d.getDocfilename())); RandomAccessFile raf = new RandomAccessFile(file, "r"); FileChannel channel = raf.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); PDFFile pdffile = new PDFFile(buf); if (raf != null) raf.close();// w w w. j a va 2 s .c o m if (channel != null) channel.close(); // draw the first page to an image PDFPage ppage = pdffile.getPage(pageNum); log.debug("WIDTH " + (int) ppage.getBBox().getWidth() + " height " + (int) ppage.getBBox().getHeight()); // get the width and height for the doc at the default zoom Rectangle rect = new Rectangle(0, 0, (int) ppage.getBBox().getWidth(), (int) ppage.getBBox().getHeight()); log.debug("generate the image"); Image img = ppage.getImage(rect.width, rect.height, // width & height rect, // clip rect null, // null for the ImageObserver true, // fill background with white true // block until drawing is done ); log.debug("about to Print to stream"); File outfile = new File(documentCacheDir, d.getDocfilename() + "_" + pageNum + ".png"); OutputStream outs = null; try { outs = new FileOutputStream(outfile); RenderedImage rendImage = (RenderedImage) img; ImageIO.write(rendImage, "png", outs); outs.flush(); } finally { if (outs != null) outs.close(); } return outfile; }
From source file:org.oscarehr.document.web.ManageDocumentAction.java
public ActionForward view2(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO: NEED TO CHECK FOR ACCESS String doc_no = request.getParameter("doc_no"); log.debug("Document No :" + doc_no); LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.READ, LogConst.CON_DOCUMENT, doc_no, request.getRemoteAddr()); Document d = documentDAO.getDocument(doc_no); log.debug("Document Name :" + d.getDocfilename()); // TODO: Right now this assumes it's a pdf which it shouldn't response.setContentType("image/png"); // response.setHeader("Content-Disposition", "attachment;filename=\"" + filename+ "\""); // read the file name. File file = new File(EDocUtil.getDocumentPath(d.getDocfilename())); RandomAccessFile raf = new RandomAccessFile(file, "r"); FileChannel channel = raf.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); PDFFile pdffile = new PDFFile(buf); // draw the first page to an image PDFPage ppage = pdffile.getPage(0);/*w ww . j a v a 2s. c o m*/ log.debug("WIDTH " + (int) ppage.getBBox().getWidth() + " height " + (int) ppage.getBBox().getHeight()); // get the width and height for the doc at the default zoom Rectangle rect = new Rectangle(0, 0, (int) ppage.getBBox().getWidth(), (int) ppage.getBBox().getHeight()); log.debug("generate the image"); Image img = ppage.getImage(rect.width, rect.height, // width & height rect, // clip rect null, // null for the ImageObserver true, // fill background with white true // block until drawing is done ); log.debug("about to Print to stream"); ServletOutputStream outs = response.getOutputStream(); RenderedImage rendImage = (RenderedImage) img; ImageIO.write(rendImage, "png", outs); outs.flush(); outs.close(); return null; }
From source file:tachyon.worker.WorkerStorage.java
/** * Swap out those blocks missing INode information onto underFS which can be retrieved by user * later. Its cleanup only happens while formating the mTachyonFS. *//*www . ja v a 2 s .c o m*/ private void swapoutOrphanBlocks(long blockId, File file) throws IOException { RandomAccessFile localFile = new RandomAccessFile(file, "r"); ByteBuffer buf = localFile.getChannel().map(MapMode.READ_ONLY, 0, file.length()); String ufsOrphanBlock = CommonUtils.concat(mUfsOrphansFolder, blockId); OutputStream os = mUfs.create(ufsOrphanBlock); final int bulkSize = Constants.KB * 64; byte[] bulk = new byte[bulkSize]; for (int k = 0; k < (buf.limit() + bulkSize - 1) / bulkSize; k++) { int len = bulkSize < buf.remaining() ? bulkSize : buf.remaining(); buf.get(bulk, 0, len); os.write(bulk, 0, len); } os.close(); localFile.close(); }
From source file:ro.ieugen.fileserver.http.HttpStaticFileServerHandler.java
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); final String path = sanitizeUri(request.getUri()); LOG.info("Requested URI is {}, sanitised path is {}", request.getUri(), path); if (path == null) { sendError(ctx, FORBIDDEN);/*w w w . j av a 2 s.c o m*/ return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (!(file.isFile() || file.isDirectory())) { sendError(ctx, FORBIDDEN); return; } Channel ch = e.getChannel(); ChannelFuture writeFuture = null; if (file.isDirectory()) { ch.write(directoryListingResponse(file)); } else { // Cache Validation if (sendRetrieveFromCacheIfNotModified(ctx, request, file)) return; RandomAccessFile raf = openFileOrSendError(ctx, file); if (raf == null) return; // Write the initial line and the header. ch.write(fileDownloadResponse(file, raf)); // Write the content. if (ch.getPipeline().get(SslHandler.class) != null) { // Cannot use zero-copy with HTTPS. writeFuture = ch.write(new ChunkedFile(raf, 0, raf.length(), 8192)); } else { // No encryption - use zero-copy. final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, raf.length()); writeFuture = ch.write(region); writeFuture.addListener(new ChannelFutureProgressListener() { public void operationComplete(ChannelFuture future) { region.releaseExternalResources(); } public void operationProgressed(ChannelFuture future, long amount, long current, long total) { LOG.info("{}", String.format("%s: %d / %d (+%d)%n", path, current, total, amount)); } }); } } // Decide whether to close the connection or not. if (!isKeepAlive(request)) { // Close the connection when the whole content is written out. writeFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:org.openspaces.pu.container.jee.jetty.support.FileLockFreePortGenerator.java
public PortHandle nextAvailablePort(int startFromPort, int retryCount) { int portNumber = -1; FileLock portFileLock = null; RandomAccessFile portFile = null; for (int i = 0; i < retryCount; i++) { portNumber = startFromPort + i;/* www . j ava 2s . c om*/ File portF = new File(portDirectory, portNumber + ".port"); try { portFile = new RandomAccessFile(portF, "rw"); } catch (FileNotFoundException e) { if (logger.isDebugEnabled()) { logger.debug("Failed to open port marker file [" + portF.getAbsolutePath() + "]", e); } // can't get this one, continue continue; } try { if (logger.isDebugEnabled()) { logger.debug("Trying to lock file [" + portF.getAbsolutePath() + "]"); } portFileLock = portFile.getChannel().tryLock(); if (portFileLock == null) { if (logger.isDebugEnabled()) { logger.debug("Can't get lock for [" + portF.getAbsolutePath() + "], try another"); } try { portFile.close(); } catch (Exception e) { // ignore } continue; } } catch (OverlappingFileLockException e) { if (logger.isDebugEnabled()) { logger.debug( "Can't get lock for [" + portF.getAbsolutePath() + "], try another, " + e.getMessage()); } try { portFile.close(); } catch (Exception e1) { // ignore } // failed to get the lock, continue continue; } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug("Failed to get lock file for [" + portF.getAbsolutePath() + "]", e); } try { portFile.close(); } catch (Exception e1) { // ignore } // failed to get the lock, continue continue; } // all is well, break break; } if (portFileLock == null) { throw new IllegalStateException("Failed to acquire port file lock, tried for [" + retryCount + "], basePort [" + startFromPort + "]"); } return new FileLockPortHandle(portFile, portFileLock, portNumber); }
From source file:org.commoncrawl.service.crawler.CrawlLog.java
private static void updateLogFileHeader(File logFileName, LogFileHeader header, long addedRecordCount) throws IOException { RandomAccessFile file = new RandomAccessFile(logFileName, "rw"); try {//from w ww.j a v a 2 s . c o m // update cached header ... header._fileSize = file.getChannel().size(); header._itemCount += addedRecordCount; // set the position at zero .. file.seek(0); // and write header to disk ... header.writeHeader(file); } finally { // major bottle neck.. // file.getFD().sync(); file.close(); } }