001 /*
002 Copyright (c) 2009 Olivier Chafik, All Rights Reserved
003
004 This file is part of JNAerator (http://jnaerator.googlecode.com/).
005
006 JNAerator is free software: you can redistribute it and/or modify
007 it under the terms of the GNU General Public License as published by
008 the Free Software Foundation, either version 3 of the License, or
009 (at your option) any later version.
010
011 JNAerator is distributed in the hope that it will be useful,
012 but WITHOUT ANY WARRANTY; without even the implied warranty of
013 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
014 GNU General Public License for more details.
015
016 You should have received a copy of the GNU General Public License
017 along with JNAerator. If not, see <http://www.gnu.org/licenses/>.
018 */
019 package com.ochafik.lang.compiler;
020
021 import java.io.ByteArrayInputStream;
022 import java.io.ByteArrayOutputStream;
023 import java.io.IOException;
024 import java.io.InputStream;
025 import java.io.InputStreamReader;
026 import java.io.OutputStream;
027 import java.io.OutputStreamWriter;
028 import java.io.Reader;
029 import java.io.Writer;
030 import java.net.URI;
031 import java.net.URISyntaxException;
032
033 import javax.tools.FileObject;
034
035 public class MemoryFileObject implements FileObject {
036 String path;
037 byte[] content;
038
039 public MemoryFileObject(String path, String content) {
040 this.path = path;
041 this.content = content == null ? null : content.getBytes();
042 }
043 public MemoryFileObject(String path, byte[] content) {
044 this.path = path;
045 this.content = content;
046 }
047 public String getPath() {
048 return path;
049 }
050 public byte[] getContent() {
051 return content;
052 }
053 public boolean delete() {
054 content = null;
055 return true;
056 }
057 public String getCharContent(boolean ignoreEncodingErrors) {
058 return new String(content);
059 }
060 public long getLastModified() {
061 return System.currentTimeMillis();
062 }
063 public String getName() {
064 return getPath();
065 }
066 public InputStream openInputStream() {
067 if (content == null)
068 return null;
069
070 return new ByteArrayInputStream(content);
071 }
072 public OutputStream openOutputStream() {
073 return new ByteArrayOutputStream() {
074 public void close() throws IOException {
075 super.close();
076 content = toByteArray();
077 }
078 };
079 }
080 public Reader openReader(boolean ignoreEncodingErrors) {
081 InputStream in = openInputStream();
082 return in == null ? null : new InputStreamReader(in);
083 }
084 public Writer openWriter() {
085 OutputStream out = openOutputStream();
086 return out == null ? null : new OutputStreamWriter(out);
087 }
088 public URI toUri() {
089 try {
090 return new URI(//"file:" +
091 getPath());
092 } catch (URISyntaxException ex) {
093 ex.printStackTrace();
094 return null;
095 }
096 }
097 @Override
098 public String toString() {
099 return getPath() + ":\n" + getCharContent(true);
100 }
101 }