App Engine Java SDK version 1.7.0
[gae.git] / java / src / main / com / google / appengine / api / files / FileWriteChannelImpl.java
blob8f8895ccc30bb04024229df29210acfb32cd9fc2
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;
20 FileWriteChannelImpl(AppEngineFile f, boolean lock, FileServiceImpl fs) {
21 this.file = f;
22 this.lockHeld = lock;
23 this.fileService = fs;
24 isOpen = true;
25 if (null == file) {
26 throw new NullPointerException("file is null");
28 if (!f.isWritable()) {
29 throw new IllegalArgumentException("file is not writable");
33 private void checkOpen() throws ClosedChannelException {
34 if (!isOpen) {
35 throw new ClosedChannelException();
39 /**
40 * {@inheritDoc}
42 public int write(ByteBuffer src) throws IOException {
43 return write(src, null);
46 /**
47 * {@inheritDoc}
49 public int write(ByteBuffer buffer, String sequenceKey) throws IOException {
50 checkOpen();
51 return fileService.append(file, buffer, sequenceKey);
54 /**
55 * {@inheritDoc}
57 public boolean isOpen() {
58 return isOpen;
61 /**
62 * {@inheritDoc}
64 public void close() throws IOException {
65 if (!isOpen) {
66 return;
68 fileService.close(file, false);
69 isOpen = false;
72 /**
73 * {@inheritDoc}
75 public void closeFinally() throws IllegalStateException, IOException {
76 if (!lockHeld) {
77 throw new IllegalStateException("The lock for this file is not held by the current request");
79 if (isOpen) {
80 fileService.close(file, true);
81 } else {
82 try {
83 fileService.openForAppend(file, true);
84 fileService.close(file, true);
85 } catch (FinalizationException e) {
88 isOpen = false;