1.9.30 sync.
[gae.git] / java / src / main / com / google / appengine / api / files / FileReadChannelImpl.java
blob7b767f91b79a18e17e721d01a6dd5c637cd4ddf1
1 // Copyright 2011 Google Inc. All Rights Reserved.
3 package com.google.appengine.api.files;
5 import java.io.IOException;
6 import java.nio.ByteBuffer;
7 import java.nio.channels.ClosedChannelException;
9 /**
10 * An implementation of {@code FileReadChannel}.
13 @Deprecated
14 class FileReadChannelImpl implements FileReadChannel {
16 private FileServiceImpl fileService;
17 private AppEngineFile file;
18 private long position;
19 private boolean isOpen;
20 private boolean reachedEOF;
21 private final Object lock = new Object();
23 FileReadChannelImpl(AppEngineFile f, FileServiceImpl fs) {
24 this.file = f;
25 this.fileService = fs;
26 isOpen = true;
27 reachedEOF = false;
28 if (null == file) {
29 throw new NullPointerException("file is null");
31 if (null == fs) {
32 throw new NullPointerException("fs is null");
34 if (!f.isReadable()) {
35 throw new IllegalArgumentException("file is not readable");
39 private void checkOpen() throws ClosedChannelException {
40 synchronized (lock) {
41 if (!isOpen) {
42 throw new ClosedChannelException();
47 /**
48 * {@inheritDoc}
49 * @throws ClosedChannelException
51 @Override
52 public long position() throws ClosedChannelException {
53 synchronized (lock) {
54 checkOpen();
55 return position;
59 /**
60 * {@inheritDoc}
62 @Override
63 public FileReadChannel position(long newPosition) throws IOException {
64 if (newPosition < 0) {
65 throw new IllegalArgumentException("newPosition may not be negative");
67 synchronized (lock) {
68 checkOpen();
69 position = newPosition;
70 reachedEOF = false;
71 return this;
75 /**
76 * {@inheritDoc}
78 @Override
79 public int read(ByteBuffer dst) throws IOException {
80 synchronized (lock) {
81 if (reachedEOF) {
82 return -1;
84 int numBytesRead = fileService.read(file, dst, position);
85 if (numBytesRead >= 0) {
86 position += numBytesRead;
87 } else {
88 reachedEOF = true;
90 return numBytesRead;
94 /**
95 * {@inheritDoc}
97 @Override
98 public boolean isOpen() {
99 synchronized (lock) {
100 return isOpen;
105 * {@inheritDoc}
107 @Override
108 public void close() throws IOException {
109 synchronized (lock) {
110 if (!isOpen) {
111 return;
113 fileService.close(file, false);
114 isOpen = false;
118 @Override
119 public String toString() {
120 return "FileReadChannel [file=" + file + ", position=" + position + ", isOpen=" + isOpen
121 + ", reachedEOF=" + reachedEOF + "]";