001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU General
007: * Public License Version 2 only ("GPL") or the Common Development and Distribution
008: * License("CDDL") (collectively, the "License"). You may not use this file except in
009: * compliance with the License. You can obtain a copy of the License at
010: * http://www.netbeans.org/cddl-gplv2.html or nbbuild/licenses/CDDL-GPL-2-CP. See the
011: * License for the specific language governing permissions and limitations under the
012: * License. When distributing the software, include this License Header Notice in
013: * each file and include the License file at nbbuild/licenses/CDDL-GPL-2-CP. Sun
014: * designates this particular file as subject to the "Classpath" exception as
015: * provided by Sun in the GPL Version 2 section of the License file that
016: * accompanied this code. If applicable, add the following below the License Header,
017: * with the fields enclosed by brackets [] replaced by your own identifying
018: * information: "Portions Copyrighted [year] [name of copyright owner]"
019: *
020: * Contributor(s):
021: *
022: * The Original Software is NetBeans. The Initial Developer of the Original Software
023: * is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun Microsystems, Inc. All
024: * Rights Reserved.
025: *
026: * If you wish your version of this file to be governed by only the CDDL or only the
027: * GPL Version 2, indicate your decision by adding "[Contributor] elects to include
028: * this software in this distribution under the [CDDL or GPL Version 2] license." If
029: * you do not indicate a single choice of license, a recipient has the option to
030: * distribute your version of this file under either the CDDL, the GPL Version 2 or
031: * to extend the choice of license to its licensees as provided above. However, if
032: * you add GPL Version 2 code and therefore, elected the GPL Version 2 license, then
033: * the option applies only if the new code is made subject to such option by the
034: * copyright holder.
035: */
036:
037: package org.netbeans.installer.downloader.impl;
038:
039: import java.io.*;
040: import java.nio.ByteBuffer;
041: import java.nio.channels.FileChannel;
042: import java.util.HashMap;
043: import java.util.Map;
044: import org.netbeans.installer.utils.LogManager;
045: import org.netbeans.installer.utils.helper.MutualHashMap;
046: import org.netbeans.installer.utils.helper.MutualMap;
047:
048: /**
049: * @author Danila_Dugurov
050: */
051: public class ChannelUtil {
052:
053: /////////////////////////////////////////////////////////////////////////////////
054: // Constants
055: public static final int BUFFER_SIZE = 64 * 1024;
056:
057: /////////////////////////////////////////////////////////////////////////////////
058: // Static
059: private static final Map<FileChannel, Integer> channel2ClientsCount = new HashMap<FileChannel, Integer>();
060: private static final MutualMap<File, FileChannel> file2Channel = new MutualHashMap<File, FileChannel>();
061:
062: //so synchronization on file save me from closing channel when
063: //concurrently another thread try to get fragment.
064: //No synchronization in methods signiture becouse
065: //I don't want to block threads wich deal with another resourses(files)
066:
067: public static OutputStream channelFragmentAsStream(final File file,
068: final SectionImpl pumpSection) throws FileNotFoundException {
069: if (file == null || pumpSection == null)
070: throw new IllegalArgumentException();
071: synchronized (file) {
072: if (!file.exists())
073: throw new FileNotFoundException();
074: FileChannel channel;
075: if (!file2Channel.containsKey(file)) {
076: channel = new RandomAccessFile(file, "rw").getChannel();
077: file2Channel.put(file, channel);
078: channel2ClientsCount.put(channel, 1);
079: } else {
080: channel = file2Channel.get(file);
081: int count = channel2ClientsCount.get(channel);
082: channel2ClientsCount.put(channel, ++count);
083: }
084: }
085: return new OutputStream() {
086: final FileChannel channel = file2Channel.get(file);
087: final SectionImpl section = pumpSection;
088: long position = pumpSection.offset();
089: long barier = section.length() > 0 ? section.offset()
090: + section.length() : Long.MAX_VALUE;
091:
092: ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
093:
094: public synchronized void write(int b) throws IOException {
095: if (position + buffer.position() >= barier)
096: return;
097: if (buffer.remaining() == 0)
098: flush();
099: buffer.put((byte) b);
100: }
101:
102: public synchronized void write(byte[] b, int off, int len)
103: throws IOException {
104: if (b == null)
105: throw new NullPointerException();
106: if (off < 0 || off > b.length || (off + len > b.length))
107: throw new IndexOutOfBoundsException();
108: while (len > 0) {
109: int length = len <= buffer.remaining() ? len
110: : buffer.remaining();
111: final long remaining = barier - position
112: - buffer.position();
113: if (remaining == 0)
114: break;
115: length = length <= remaining ? length
116: : (int) remaining;
117: buffer.put(b, off, length);
118: if (buffer.remaining() == 0)
119: flush();
120: len -= length;
121: off += length;
122: }
123: }
124:
125: // close may be invoked asynchroniously so synchronized modifer really need
126: public synchronized void flush() throws IOException {
127: final int written = this .channel.write(
128: (ByteBuffer) buffer.flip(), position);
129: position += written;
130: if (written > 0)
131: section.shiftOffset(written);
132: buffer.rewind();
133: }
134:
135: //on close() thread release channel in any case of exceptions
136: public void close() throws IOException {
137: try {
138: if (!channel.isOpen())
139: return;
140: flush();
141: } finally {
142: releaseFile(channel);
143: }
144: }
145: };
146: }
147:
148: private static void releaseFile(final FileChannel channel) {
149: final File file = file2Channel.reversedGet(channel);
150: if (file == null)
151: return;
152: synchronized (file) {
153: Integer count = channel2ClientsCount.get(channel);
154: if (count == null)
155: return;//already removed
156: if (count > 1) {
157: channel2ClientsCount.put(channel, --count);
158: } else {
159: channel2ClientsCount.remove(channel);
160: file2Channel.reversedRemove(channel);
161: try {
162: channel.close();
163: } catch (IOException ex) {
164: LogManager.log("can't close channel", ex);
165: }
166: }
167: }
168: }
169: }
|