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.grouplens.lenskit.data.dao.packed.BinaryIndexTableTest.java

@Test
public void testLimitedView() throws IOException {
    File file = folder.newFile();
    FileChannel chan = new RandomAccessFile(file, "rw").getChannel();
    BinaryIndexTableWriter writer = BinaryIndexTableWriter.create(BinaryFormat.create(), chan, 3);
    writer.writeEntry(12, new int[] { 0 });
    writer.writeEntry(17, new int[] { 1, 3 });
    writer.writeEntry(19, new int[] { 4, 5 });

    MappedByteBuffer buffer = chan.map(FileChannel.MapMode.READ_ONLY, 0, chan.size());
    BinaryIndexTable tbl = BinaryIndexTable.fromBuffer(3, buffer);
    tbl = tbl.createLimitedView(2);/*w ww .java2 s  .  c om*/
    assertThat(tbl.getKeys(), hasSize(2));
    assertThat(tbl.getKeys(), contains(12L, 17L));
    assertThat(tbl.getEntry(12), contains(0));
    assertThat(tbl.getEntry(17), contains(1));
    assertThat(tbl.getEntry(19), nullValue());
    assertThat(tbl.getEntry(-1), nullValue());

    BinaryIndexTable serializedTbl = SerializationUtils.clone(tbl);
    assertThat(serializedTbl.getKeys(), hasSize(2));
    assertThat(serializedTbl.getKeys(), contains(12L, 17L));
    assertThat(serializedTbl.getEntry(12), contains(0));
    assertThat(serializedTbl.getEntry(17), contains(1));
    assertThat(serializedTbl.getEntry(19), nullValue());
    assertThat(serializedTbl.getEntry(-1), nullValue());
}

From source file:org.opennms.systemreport.AbstractSystemReportPlugin.java

protected String slurp(final File lsb) {
    if (lsb != null && lsb.exists()) {
        FileInputStream stream = null;
        try {/*ww w. j a v a  2 s  . c  om*/
            stream = new FileInputStream(lsb);
            FileChannel fc = stream.getChannel();
            MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
            return Charset.defaultCharset().decode(bb).toString().replace("[\\r\\n]*$", "");
        } catch (final Exception e) {
            LOG.debug("Unable to read from file '{}'", lsb.getPath(), e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }
    return null;
}

From source file:org.ednovo.gooru.application.util.ResourceProcessor.java

public void postPdfUpdate(final String resourceGooruOid) throws Exception {

    new TransactionBox() {

        @Override/*from  w w  w  . j  av a 2s  .c  om*/
        public void execute() {

            try {

                logger.info("Updating Resource: " + resourceGooruOid);
                Resource resource = resourceRepository.findResourceByContentGooruId(resourceGooruOid);
                String repoPath = resource.getOrganization().getNfsStorageArea().getInternalPath()
                        + resource.getFolder();
                /*
                 * getGooruImageUtil().scaleImage(repoPath +
                 * resource.getThumbnail(), repoPath, null,
                 * ResourceImageUtil.RESOURCE_THUMBNAIL_SIZES);
                 */
                ResourceInfo resourceInfo = resourceRepository.findResourceInfo(resource.getGooruOid());
                if (resourceInfo == null) {
                    resourceInfo = new ResourceInfo();
                    resourceInfo.setResource(resource);
                }

                resourceInfo.setLastUpdated(new Date());

                RandomAccessFile raf = new RandomAccessFile(new File(repoPath + resource.getUrl()), "r");
                FileChannel channel = raf.getChannel();
                ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
                PDFFile pdffile = new PDFFile(buf);
                resourceInfo.setNumOfPages(pdffile.getNumPages());

                resourceRepository.save(resourceInfo);
                resource.setResourceInfo(resourceInfo);
                resourceRepository.save(resource);

                s3ResourceApiHandler.uploadResourceFolder(resource);

            } catch (Exception ex) {
                logger.error("Error while generating thumbnail ", ex);
                s3ResourceApiHandler.uploadResourceFolderWithNewSession(resourceGooruOid);
            }
        }
    };
}

From source file:com.amaze.filemanager.utils.files.GenericCopyUtil.java

private void copyFile(BufferedInputStream bufferedInputStream, FileChannel outChannel) throws IOException {

    MappedByteBuffer byteBuffer = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, mSourceFile.getSize());
    int count = 0;
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    while (count != -1) {

        count = bufferedInputStream.read(buffer);
        if (count != -1 && !progressHandler.getCancelled()) {

            byteBuffer.put(buffer, 0, count);
            ServiceWatcherUtil.position += count;
        } else//from  ww  w .  ja v  a  2s.c o  m
            break;
    }
}

From source file:com.wwpass.connection.WWPassConnection.java

private static PKCS8EncodedKeySpec readKeyFile(String path) throws IOException {
    FileInputStream stream = new FileInputStream(new File(path));
    try {/*from  w  w  w .j  a v a  2  s  .c om*/
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        String pem = Charset.defaultCharset().decode(bb).toString();
        pem = pem.replaceFirst("-----BEGIN (RSA )?PRIVATE KEY-----\r?\n?", "")
                .replace("-----END (RSA )?PRIVATE KEY-----", "");
        Base64 dec1 = new Base64();
        byte[] encoded = dec1.decode(pem);
        return new PKCS8EncodedKeySpec(encoded);
    } finally {
        stream.close();
    }
}

From source file:esg.node.components.monitoring.MonitorDAO.java

private void loadDiskInfoResource() {
    disk_info_dsroot_pat = Pattern.compile("thredds_dataset_roots\\s*=\\s*(.*?)\\s*\\w+\\s*?=");
    disk_info_dsroot_keyval_pat = Pattern.compile("\\s*(\\w+)\\s*\\|\\s*(\\S+)\\s*");

    String filename = props.getProperty("monitor.esg.ini",
            System.getenv().get("ESG_USER_HOME") + "/.esgcet/esg.ini");
    File iniFile = new File(filename);
    if (!iniFile.exists()) {
        log.warn("ESG publisher config file [" + filename + "] not found! Cannot provide disk info!");
        return;/*from  w  ww  . jav a2 s  .  co  m*/
    }

    log.debug("Scanning for drives specified in: " + filename);

    try {
        FileInputStream fis = new FileInputStream(iniFile);
        FileChannel fc = fis.getChannel();
        disk_info_byte_buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int) fc.size());
    } catch (FileNotFoundException e) {
        log.error(e);
    } catch (IOException e) {
        log.error(e);
    }
}

From source file:com.amaze.filemanager.utils.files.GenericCopyUtil.java

private void copyFile(FileChannel inChannel, BufferedOutputStream bufferedOutputStream) throws IOException {
    MappedByteBuffer inBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, mSourceFile.getSize());

    int count = -1;
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    try {/*from   w  ww.j  ava2 s .c o  m*/
        while (inBuffer.hasRemaining() && count != 0) {

            int tempPosition = inBuffer.position();

            try {

                // try normal way of getting bytes
                ByteBuffer tempByteBuffer = inBuffer.get(buffer);
                count = tempByteBuffer.position() - tempPosition;
            } catch (BufferUnderflowException exception) {
                exception.printStackTrace();

                // not enough bytes left in the channel to read, iterate over each byte and store
                // in the buffer

                // reset the counter bytes
                count = 0;
                for (int i = 0; i < buffer.length && inBuffer.hasRemaining(); i++) {
                    buffer[i] = inBuffer.get();
                    count++;
                }
            }

            if (count != -1 && !progressHandler.getCancelled()) {

                bufferedOutputStream.write(buffer, 0, count);
                ServiceWatcherUtil.position = inBuffer.position();
            } else
                break;

        }
    } finally {
        bufferedOutputStream.flush();
    }
}

From source file:com.topsem.common.net.IPSeeker.java

public IPSeeker(File ipFile) throws Exception {
    this.ipFile = new RandomAccessFile(ipFile, "r");
    ipCache = new HashMap<String, IPLocation>();
    FileChannel fc = this.ipFile.getChannel();
    mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, ipFile.length());
    mbb.order(ByteOrder.LITTLE_ENDIAN);
    ipBegin = readInt(0);/*from   ww  w.j av a2  s.  c om*/
    ipEnd = readInt(4);
    if (ipBegin == -1 || ipEnd == -1) {
        throw new IOException("IP???IP");
    }
    log.debug("IP?:" + ipFile.getAbsolutePath());
}

From source file:org.lic.ip.ipseeker.IPSeeker.java

/**
 * ?/*from  www  . ja v a2  s. c om*/
 */
private IPSeeker() {
    tmpBuf = new byte[100];
    tmpB4 = new byte[4];

    try {
        String filepath = getClass().getClassLoader().getResource("qqwry.dat").getPath();
        ipFile = new RandomAccessFile(filepath, "r");
        // ipFile = new RandomAccessFile(ClassLoader.getSystemResource(
        // ip_filename).getPath(), "r");
    } catch (IOException e) {
        logger.error("IP??IP");
        return;
    }

    if (ipFile == null)
        return;

    // ??
    try {
        ipBegin = readInt4(0);
        ipEnd = readInt4(4);
        if (ipBegin == -1 || ipEnd == -1) {
            ipFile.close();
            ipFile = null;
            return;
        }
    } catch (IOException e) {
        logger.error("IP???IP");
        ipFile = null;
        return;
    }

    // IP?
    try {
        FileChannel fc = ipFile.getChannel();
        long ipFileLen = ipFile.length();
        mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, ipFileLen);
        mbb.order(ByteOrder.LITTLE_ENDIAN);
        ipFile.close();

        logger.info("read ip file to memory, len = " + ipFileLen + " bytes");
    } catch (IOException e) {
        e.printStackTrace();
    }
}