Revision created by MOE tool push_codebase.
[gae.git] / java / src / main / com / google / appengine / api / files / FileWriteChannelImpl.java
blobcef50470cf613d0b17e14bfdb8c89bf1a58ac177
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 FileWriteChannel}.
13 class FileWriteChannelImpl implements FileWriteChannel {
15 private FileServiceImpl fileService;
16 private AppEngineFile file;
17 private boolean lockHeld;
18 private boolean isOpen;
19 private final Object lock = new Object();
21 FileWriteChannelImpl(AppEngineFile f, boolean lock, FileServiceImpl fs) {
22 this.file = f;
23 this.lockHeld = lock;
24 this.fileService = fs;
25 isOpen = true;
26 if (null == file) {
27 throw new NullPointerException("file is null");
29 if (!f.isWritable()) {
30 throw new IllegalArgumentException("file is not writable");
34 private void checkOpen() throws ClosedChannelException {
35 if (!isOpen) {
36 throw new ClosedChannelException();
40 /**
41 * {@inheritDoc}
43 @Override
44 public int write(ByteBuffer src) throws IOException {
45 synchronized (lock) {
46 return write(src, null);
50 /**
51 * {@inheritDoc}
53 @Override
54 public int write(ByteBuffer buffer, String sequenceKey) throws IOException {
55 synchronized (lock) {
56 checkOpen();
57 return fileService.append(file, buffer, sequenceKey);
61 /**
62 * {@inheritDoc}
64 @Override
65 public boolean isOpen() {
66 synchronized (lock) {
67 return isOpen;
71 /**
72 * {@inheritDoc}
74 @Override
75 public void close() throws IOException {
76 synchronized (lock) {
77 if (!isOpen) {
78 return;
80 fileService.close(file, false);
81 isOpen = false;
85 /**
86 * {@inheritDoc}
88 @Override
89 public void closeFinally() throws IllegalStateException, IOException {
90 synchronized (lock) {
91 if (!lockHeld) {
92 throw new IllegalStateException(
93 "The lock for this file is not held by the current request");
95 if (isOpen) {
96 fileService.close(file, true);
97 } else {
98 try {
99 fileService.openForAppend(file, true);
100 fileService.close(file, true);
101 } catch (FinalizationException e) {
104 isOpen = false;