Example usage for java.nio.channels FileChannel map

List of usage examples for java.nio.channels FileChannel map

Introduction

In this page you can find the example usage for java.nio.channels FileChannel map.

Prototype

public abstract MappedByteBuffer map(MapMode mode, long position, long size) throws IOException;

Source Link

Document

Maps a region of this channel's file directly into memory.

Usage

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);/*from   w  w w.j  a  v  a 2 s . co 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:eu.medsea.mimeutil.detector.OpendesktopMimeDetector.java

private void init(final String mimeCacheFile) {
    String cacheFile = mimeCacheFile;
    if (!new File(cacheFile).exists()) {
        cacheFile = internalMimeCacheFile;

    }/*from w  ww.ja  v  a2  s .  c  o m*/
    // Map the mime.cache file as a memory mapped file
    FileChannel rCh = null;
    try {
        RandomAccessFile raf = null;
        raf = new RandomAccessFile(cacheFile, "r");
        rCh = (raf).getChannel();
        content = rCh.map(FileChannel.MapMode.READ_ONLY, 0, rCh.size());

        // Read all of the MIME type from the Alias list
        initMimeTypes();

        if (log.isDebugEnabled()) {
            log.debug("Registering a FileWatcher for [" + cacheFile + "]");
        }
        TimerTask task = new FileWatcher(new File(cacheFile)) {
            protected void onChange(File file) {
                initMimeTypes();
            }
        };

        timer = new Timer();
        // repeat the check every 10 seconds
        timer.schedule(task, new Date(), 10000);

    } catch (Exception e) {
        throw new MimeException(e);
    } finally {
        if (rCh != null) {
            try {
                rCh.close();
            } catch (Exception e) {
                log.error(e.getLocalizedMessage(), e);
            }
        }
    }
}

From source file:edu.cmu.graphchi.shards.QueryShard.java

public QueryShard(String fileName, int shardNum, int numShards, VertexInterval interval, Config dbConfig)
        throws IOException {
    this.shardNum = shardNum;
    this.interval = interval;

    pinIndexToMemory = dbConfig.getBoolean("queryshard.pinindex");
    queryCacheSize = dbConfig.getInt("queryshard.cachesize");

    adjFile = new File(ChiFilenames.getFilenameShardsAdj(fileName, shardNum, numShards));
    numEdges = (int) (adjFile.length() / BYTES_PER_EDGE);

    FileChannel channel = new java.io.RandomAccessFile(adjFile, "rw").getChannel();
    adjBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, adjFile.length()).asLongBuffer();
    channel.close();//ww  w .  j a  v  a2s .c o  m

    index = (pinIndexToMemory ? null : createSparseIndex());

    loadPointers();
    loadInEdgeStartBuffer();
}

From source file:ome.io.nio.RomioPixelBuffer.java

/**
 * Implemented as specified by {@link PixelBuffer} I/F.
 * @see PixelBuffer#getRegion(Integer, Long)
*///from   w  ww.  j a  v  a  2s.c  o m
public PixelData getRegion(Integer size, Long offset) throws IOException {
    FileChannel fileChannel = getFileChannel();

    /*
     * fileChannel should not be "null" as it will throw an exception if
     * there happens to be an error.
     */

    MappedByteBuffer b = fileChannel.map(MapMode.READ_ONLY, offset, size);
    return new PixelData(pixels.getPixelsType().getValue(), b);
}

From source file:org.cytobank.fcs_files.events.MemoryEvents.java

protected synchronized boolean writeOut() {
    if (memoryEventsArray == null)
        return false;

    File memoryEventsArrayOnDisk = null;

    synchronized (memoryEventsArray) {
        memoryEventsArrayOnDisk = memoryEventsArray.getOnDisk();

        if (memoryEventsArrayOnDisk != null || events == null)
            return false;

        RandomAccessFile randomAccessFile = null;
        FileChannel fileChannel = null;

        try {//from   w  ww  .  ja  v a2 s. c  o  m
            memoryEventsArrayOnDisk = File.createTempFile("memoryEventsArrayOnDisk", "evt");
            memoryEventsArrayOnDisk.deleteOnExit();
            randomAccessFile = new RandomAccessFile(memoryEventsArrayOnDisk, "rw");
            fileChannel = randomAccessFile.getChannel();

            MappedByteBuffer mappedByteBuffer = fileChannel.map(MapMode.READ_WRITE, 0,
                    numberOfEvents * BYTES_PER_DOUBLE);
            DoubleBuffer doubleBuffer = mappedByteBuffer.asDoubleBuffer();
            doubleBuffer.put(events, 0, numberOfEvents);
            mappedByteBuffer.force();
            fileChannel.close();
            randomAccessFile.close();

            memoryEventsArray.setOnDisk(memoryEventsArrayOnDisk);

        } catch (IOException ioe) {
            logger.log(Level.INFO, "::::: Failed to write out MemoryEventsArray :::::", ioe);
            if (memoryEventsArrayOnDisk != null) {
                memoryEventsArrayOnDisk.delete();
                memoryEventsArrayOnDisk = null;
            }
        } finally {
            memoryEventsArrayOnDisk.delete();
        }
    }

    return true;

}

From source file:automenta.knowtention.channel.LineFileChannel.java

@Override
public void run() {

    FileInputStream fileInputStream = null;
    FileChannel channel = null;
    ByteBuffer buffer = null;//from  w  w w . ja  va  2 s .  co m
    LinkedList<String> lines = new LinkedList();
    StringBuilder builder = new StringBuilder();
    long lastSize = -1, lastLastModified = -1;

    while (running) {
        try {
            Thread.sleep(delayPeriodMS);
        } catch (InterruptedException ex) {
        }

        lines.clear();
        try {
            fileInputStream = new FileInputStream(file);

            channel = fileInputStream.getChannel();

            long lastModified = file.lastModified();
            long csize = channel.size();
            if ((lastModified == lastLastModified) && (csize == lastSize)) { //also check file update time?
                fileInputStream.close();
                continue;
            }

            int currentPos = (int) csize;

            buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, csize);
            buffer.position(currentPos);
            lastSize = csize;
            lastLastModified = lastModified;

            int count = 0;

            for (long i = csize - 1; i >= 0; i--) {

                char c = (char) buffer.get((int) i);

                if (c == '\n') {
                    count++;
                    builder.reverse();
                    lines.addFirst(builder.toString());
                    if (count == numLines) {
                        break;
                    }
                    builder.setLength(0);
                } else
                    builder.append(c);
            }

            update(lines);

            lines.clear();
            buffer.clear();
            channel.close();
            fileInputStream.close();
            fileInputStream = null;

        } catch (Exception ex) {
            Logger.getLogger(LineFileChannel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    try {
        channel.close();
    } catch (IOException ex) {
        Logger.getLogger(LineFileChannel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.cmu.graphchi.shards.QueryShard.java

private void loadInEdgeStartBuffer() throws IOException {
    File inEdgeStartBufferFile = new File(
            ChiFilenames.getFilenameShardsAdjStartIndices(adjFile.getAbsolutePath()));
    FileChannel inEdgeStartChannel = new java.io.RandomAccessFile(inEdgeStartBufferFile, "r").getChannel();
    inEdgeStartBuffer = inEdgeStartChannel.map(FileChannel.MapMode.READ_ONLY, 0, inEdgeStartBufferFile.length())
            .asIntBuffer();//from  ww w .  j a  v a 2  s . c  om
    inEdgeStartChannel.close();
}

From source file:edu.cmu.graphchi.shards.QueryShard.java

void loadPointers() throws IOException {
    File pointerFile = new File(ChiFilenames.getFilenameShardsAdjPointers(adjFile.getAbsolutePath()));
    if (!pinIndexToMemory) {
        FileChannel ptrFileChannel = new java.io.RandomAccessFile(pointerFile, "r").getChannel();
        pointerIdxBuffer = ptrFileChannel.map(FileChannel.MapMode.READ_ONLY, 0, pointerFile.length())
                .asLongBuffer();/*from   w  w w .  j  ava  2s .  co  m*/
        ptrFileChannel.close();
    } else {
        byte[] data = new byte[(int) pointerFile.length()];

        if (data.length == 0)
            return;
        totalOrigSize += data.length;

        FileInputStream fis = new FileInputStream(pointerFile);
        int i = 0;
        while (i < data.length) {
            i += fis.read(data, i, data.length - i);
        }
        fis.close();

        pointerIdxBuffer = ByteBuffer.wrap(data).asLongBuffer();

        long[] vertices = new long[pointerIdxBuffer.capacity() - 1];
        long[] offs = new long[vertices.length];

        for (int j = 0; j < vertices.length; j++) {
            long x = pointerIdxBuffer.get(j);
            vertices[j] = VertexIdTranslate.getVertexId(x);
            offs[j] = VertexIdTranslate.getAux(x);
        }

        boolean extraZero = (offs.length > 1 && offs[1] == offs[0]);
        if (extraZero) {
            vertices = Arrays.copyOfRange(vertices, 1, vertices.length);
            offs = Arrays.copyOfRange(offs, 1, offs.length);
        }

        gammaSeqVertices = new IncreasingEliasGammaSeq(vertices);
        gammaSeqOffs = new IncreasingEliasGammaSeq(offs);

        totalPinnedSize += gammaSeqVertices.sizeInBytes();
        totalPinnedSize += gammaSeqOffs.sizeInBytes();
        pointerIdxBuffer = null;

    }
}

From source file:org.geotools.data.shapefile.ShpFiles.java

/**
 * Internal method that the file channel decorators will call to allow reuse of the memory mapped
 * buffers/*from w  ww. j  a  v  a  2 s.  c  o m*/
 * 
 * @param wrapped
 * @param url
 * @param mode
 * @param position
 * @param size
 * @return
 * @throws IOException
 */
MappedByteBuffer map(FileChannel wrapped, URL url, MapMode mode, long position, long size) throws IOException {
    if (memoryMapCacheEnabled) {
        return mapCache.map(wrapped, url, mode, position, size);
    } else {
        return wrapped.map(mode, position, size);
    }
}

From source file:adept.io.Reader.java

/**
 * Reads specified file into a string./*  w ww  . j a  va 2  s  .  co m*/
 *
 * @param path the path
 * @return the string
 */
public String readFileIntoString(String path) {
    try {
        String absolutePath = path;
        //         String absolutePath = getAbsolutePathFromClasspathOrFileSystem(path);
        FileInputStream stream = new FileInputStream(new File(absolutePath));
        try {
            FileChannel fc = stream.getChannel();
            MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
            /* Instead of using default, pass in a decoder. */
            return Charset.forName("UTF-8").decode(bb).toString();
        } finally {
            stream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}