List of usage examples for java.io RandomAccessFile getChannel
public final FileChannel getChannel()
From source file:org.meerkat.util.FileUtil.java
/** * writeToFile/* ww w .j av a 2s .co m*/ * @param filename * @param contents */ public final void writeToFile(String filename, String contents) { RandomAccessFile destFile = null; File tmpFile; try { tmpFile = new File(filename); if (tmpFile.exists()) { tmpFile.delete(); } destFile = new RandomAccessFile(filename, "rw"); } catch (FileNotFoundException e) { log.error("Error accessing file: " + filename + " (" + e.getMessage() + ")"); } ByteBuffer buf = ByteBuffer.allocate(contents.length()); FileChannel outChannel = destFile.getChannel(); buf.put(contents.getBytes()); buf.flip(); //buffer set for read try { outChannel.write(buf); destFile.close(); } catch (IOException e) { log.error("Error writing to file " + filename + " (" + e.getMessage() + ")"); } }
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 {//ww w . j av a 2s . co m 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:hornet.framework.clamav.service.ClamAVCheckService.java
/** * Rcupration du fichier stream./* w w w . j a v a 2 s . c o m*/ * * @param fileForTest * fichier de test * @param fileForTestSize * taille du fichier * @return MappedByteBuffer * @throws IOException * probleme de lecture */ protected MappedByteBuffer recupFichierStream(final File fileForTest, final long fileForTestSize) throws IOException { // Rcupration du fichier stream final RandomAccessFile raf = new RandomAccessFile(fileForTest, "r"); final FileChannel readChannel = raf.getChannel(); MappedByteBuffer bufFile = null; try { bufFile = readChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileForTestSize); } finally { if (readChannel != null) { try { readChannel.close(); } catch (final IOException e) { ClamAVCheckService.LOGGER.error("Erreur lors de la fermeture de la socket", e); } } if (raf != null) { try { raf.close(); } catch (final IOException e) { ClamAVCheckService.LOGGER.error("Erreur lors de la fermeture de la socket", e); } } } return bufFile; }
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 ww . j a v a2 s . co m 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:org.dcache.xrootd.standalone.DataServerHandler.java
/** * Use the file descriptor retrieved from the mover upon open and let it * obtain a reader object on the pool. The reader object will be placed * in a queue, from which it can be taken when sending read information * to the client.// w w w . j a v a2 s.c o m * @param ctx Received from the netty pipeline * @param msg The actual request */ @Override protected Object doOnRead(ChannelHandlerContext ctx, ReadRequest msg) throws XrootdException { RandomAccessFile raf = getOpenFile(msg.getFileHandle()); if (msg.bytesToRead() == 0) { return withOk(msg); } else if (_configuration.useZeroCopy) { try { return new ZeroCopyReadResponse(msg, raf.getChannel()); } catch (IOException e) { throw new XrootdException(kXR_IOError, e.getMessage()); } } else { return new ChunkedFileChannelReadResponse(msg, MAX_FRAME_SIZE, raf.getChannel()); } }
From source file:com.clustercontrol.agent.job.PublicKeyThread.java
/** * ?Authorized_key????<BR>//from w w w . j ava 2 s . c o m * * @param publicKey * @return */ private synchronized boolean addKey(String publicKey) { m_log.debug("add key start"); if (SKIP_KEYFILE_UPDATE) { m_log.info("skipped appending publicKey"); return true; } //??? String fileName = AgentProperties.getProperty(execUser.toLowerCase() + AUTHORIZED_KEY_PATH); m_log.debug("faileName" + fileName); if (fileName == null || fileName.length() == 0) return false; //File? File fi = new File(fileName); RandomAccessFile randomAccessFile = null; FileChannel channel = null; FileLock lock = null; boolean add = false; try { //RandomAccessFile? randomAccessFile = new RandomAccessFile(fi, "rw"); //FileChannel? channel = randomAccessFile.getChannel(); // for (int i = 0; i < (FILELOCK_TIMEOUT / FILELOCK_WAIT); i++) { if (null != (lock = channel.tryLock())) { break; } m_log.info("waiting for locked file... [" + (i + 1) + "/" + (FILELOCK_TIMEOUT / FILELOCK_WAIT) + " : " + fileName + "]"); Thread.sleep(FILELOCK_WAIT); } if (null == lock) { m_log.warn("file locking timeout."); return false; } // (?) synchronized (authKeyLock) { //?? channel.position(channel.size()); //? String writeData = "\n" + publicKey; // m_log.debug("add key : " + writeData); //????? ByteBuffer buffer = ByteBuffer.allocate(512); //??? buffer.clear(); buffer.put(writeData.getBytes()); buffer.flip(); channel.write(buffer); } add = true; } catch (Exception e) { m_log.error(e); } finally { try { if (channel != null) { channel.close(); } if (randomAccessFile != null) { randomAccessFile.close(); } if (lock != null) { // lock.release(); } } catch (Exception e) { } } return add; }
From source file:org.mitre.math.linear.BufferRealMatrix.java
/** * Create a new matrix with the supplied row and column dimensions. * * @param rows the number of rows in the new matrix * @param columns the number of columns in the new matrix * @param file the file to use to store the mapped matrix (<code>null</code> allowed and a tempFile will be created) * @throws IllegalArgumentException// w w w. ja va 2 s .co m * @throws IOException */ public BufferRealMatrix(final int rows, final int columns, File file) throws IllegalArgumentException, IOException { super(rows, columns); this.rows = rows; this.columns = columns; // number of blocks this.blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; this.blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; if (file == null) { file = File.createTempFile(TEMP_FILE_PREFIX, null); LOG.debug(String.format("Created tempFile '%s'", file.getAbsolutePath())); } RandomAccessFile raf = new RandomAccessFile(file, "rw"); this.dataFileChannel = raf.getChannel(); long mbbSize = (long) (Double.SIZE / Byte.SIZE) * (long) rows * (long) columns + BUFFER_HEADER_SIZE; LOG.debug(String.format("Matrix size will be %d bytes and %d by %d blocks", mbbSize, this.blockRows, this.blockColumns)); MappedByteBuffer bb = this.dataFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, BUFFER_HEADER_SIZE); bb.clear(); bb.putInt(BLOCK_BYTE_SIZE); bb.putInt(rows); bb.putInt(columns); // note: we don't create the layout like BlockedRealMatrix // Is this set to zeros? It would be a pain/slow to init it if it is realy big }
From source file:omero.util.TempFileManager.java
/** * Returns a platform-specific user-writable temporary directory. * * First, the value of "OMERO_TEMPDIR" is attempted (if available), * then user's home ("user.home") directory, then the global temp director * ("java.io.tmpdir")./*from ww w . java2 s . c om*/ * * Typical errors for any of the possible temp locations are: * <ul> * <li>non-existence</li> * <li>inability to lock</li> * </ul> * * @see <a href="https://trac.openmicroscopy.org.uk/omero/ticket/1653">ticket:1653</a> */ protected File tmpdir() { File locktest = null; String omerotmp = System.getenv().get("OMERO_TEMPDIR"); String homeprop = System.getProperty("user.home", null); String tempprop = System.getProperty("java.io.tmpdir", null); List<String> targets = Arrays.asList(omerotmp, homeprop, tempprop); for (String target : targets) { if (target == null) { continue; } RandomAccessFile raftest = null; try { File testdir = new File(target); locktest = File.createTempFile("._omero_util_TempFileManager_lock_test", ".tmp", testdir); locktest.delete(); raftest = new RandomAccessFile(locktest, "rw"); FileLock channeltest = raftest.getChannel().tryLock(); channeltest.release(); } catch (Exception e) { if ("Operation not permitted".equals(e.getMessage()) || "Operation not supported".equals(e.getMessage())) { // This is the issue described in ticket:1653 // To prevent printing the warning, we just continue // here. log.debug(target + " does not support locking."); } else { log.warn("Invalid tmp dir: " + target, e); } continue; } finally { if (locktest != null && raftest != null) { try { raftest.close(); locktest.delete(); } catch (Exception e) { log.warn("Failed to close/delete lock file: " + locktest); } } } log.debug("Chose global tmpdir: " + locktest.getParent()); break; // Something found! } if (locktest == null) { throw new RuntimeException("Could not find lockable tmp dir"); } File omero = new File(locktest.getParentFile(), "omero"); File tmp = new File(omero, "tmp"); return tmp; }
From source file:com.clustercontrol.agent.job.PublicKeyThread.java
/** * ?Authorized_key????<BR>/*from w w w . j a v a 2 s . c o m*/ * * @param publicKey * @return true : ?false: */ private synchronized boolean deleteKey(String publicKey) { m_log.debug("delete key start"); if (SKIP_KEYFILE_UPDATE) { m_log.info("skipped deleting publicKey"); return true; } Charset charset = Charset.forName("UTF-8"); CharsetEncoder encoder = charset.newEncoder(); CharsetDecoder decoder = charset.newDecoder(); //??? String fileName = AgentProperties.getProperty(execUser.toLowerCase() + AUTHORIZED_KEY_PATH); if (fileName == null || fileName.length() == 0) return false; //File? File fi = new File(fileName); RandomAccessFile randomAccessFile = null; FileChannel channel = null; FileLock lock = null; boolean delete = false; try { //RandomAccessFile? randomAccessFile = new RandomAccessFile(fi, "rw"); //FileChannel? channel = randomAccessFile.getChannel(); // for (int i = 0; i < (FILELOCK_TIMEOUT / FILELOCK_WAIT); i++) { if (null != (lock = channel.tryLock())) { break; } m_log.info("waiting for locked file... [" + (i + 1) + "/" + (FILELOCK_TIMEOUT / FILELOCK_WAIT) + " : " + fileName + "]"); Thread.sleep(FILELOCK_WAIT); } if (null == lock) { m_log.warn("file locking timeout."); return false; } // (?) synchronized (authKeyLock) { //?? ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); //?? channel.read(buffer); // ???????????0? buffer.flip(); //?? String contents = decoder.decode(buffer).toString(); // ? m_log.debug("contents " + contents.length() + " : " + contents); //?? List<String> keyCheck = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(contents, "\n"); while (tokenizer.hasMoreTokens()) { keyCheck.add(tokenizer.nextToken()); } //?????? int s = keyCheck.lastIndexOf(publicKey); if (s != -1) { // ? m_log.debug("remobe key : " + keyCheck.get(s)); keyCheck.remove(s); } //????? encoder.reset(); buffer.clear(); int i; if (keyCheck.size() > 0) { for (i = 0; i < keyCheck.size() - 1; i++) { encoder.encode(CharBuffer.wrap(keyCheck.get(i) + "\n"), buffer, false); } encoder.encode(CharBuffer.wrap(keyCheck.get(i)), buffer, true); } //??? buffer.flip(); channel.truncate(0); channel.position(0); channel.write(buffer); } delete = true; } catch (IOException e) { m_log.error(e.getMessage(), e); } catch (RuntimeException e) { m_log.error(e.getMessage(), e); } catch (InterruptedException e) { m_log.error(e.getMessage(), e); } finally { try { if (channel != null) { channel.close(); } if (randomAccessFile != null) { randomAccessFile.close(); } //? if (lock != null) { lock.release(); } } catch (Exception e) { } } return delete; }