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
007: * General Public License Version 2 only ("GPL") or the Common
008: * Development and Distribution License("CDDL") (collectively, the
009: * "License"). You may not use this file except in compliance with the
010: * License. You can obtain a copy of the License at
011: * http://www.netbeans.org/cddl-gplv2.html
012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013: * specific language governing permissions and limitations under the
014: * License. When distributing the software, include this License Header
015: * Notice in each file and include the License file at
016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
017: * particular file as subject to the "Classpath" exception as provided
018: * by Sun in the GPL Version 2 section of the License file that
019: * accompanied this code. If applicable, add the following below the
020: * License Header, with the fields enclosed by brackets [] replaced by
021: * your own identifying information:
022: * "Portions Copyrighted [year] [name of copyright owner]"
023: *
024: * Contributor(s):
025: *
026: * The Original Software is NetBeans. The Initial Developer of the Original
027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
028: * Microsystems, Inc. All Rights Reserved.
029: *
030: * If you wish your version of this file to be governed by only the CDDL
031: * or only the GPL Version 2, indicate your decision by adding
032: * "[Contributor] elects to include this software in this distribution
033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
034: * single choice of license, a recipient has the option to distribute
035: * your version of this file under either the CDDL, the GPL Version 2 or
036: * to extend the choice of license to its licensees as provided above.
037: * However, if you add GPL Version 2 code and therefore, elected the GPL
038: * Version 2 license, then the option applies only if the new code is
039: * made subject to such option by the copyright holder.
040: */
041:
042: package org.netbeans.nbbuild;
043:
044: import java.io.File;
045: import java.io.FileInputStream;
046: import java.io.FileOutputStream;
047: import java.io.IOException;
048: import java.net.URL;
049: import java.net.URLClassLoader;
050: import java.util.ArrayList;
051: import java.util.Iterator;
052: import java.util.jar.JarFile;
053: import org.apache.tools.ant.AntClassLoader;
054: import org.apache.tools.ant.Project;
055: import org.apache.tools.ant.types.Path;
056: import org.apache.tools.ant.types.FileSet;
057: import org.apache.tools.ant.BuildException;
058: import org.apache.tools.ant.taskdefs.MatchingTask;
059: import org.apache.tools.ant.DirectoryScanner;
060: import java.util.Vector;
061:
062: /**
063: * @author Jaroslav Tulach
064: */
065: public class NbPatchClass extends MatchingTask {
066:
067: /* Path to library containing the patch method */
068: private Path patchPath;
069:
070: public Path createClasspath() {
071: if (patchPath == null) {
072: patchPath = new Path(getProject());
073: }
074: return patchPath.createPath();
075: }
076:
077: /* Name of class with patch method */
078: private String patchClass = "org.netbeans.PatchByteCode"; //NOI18N
079:
080: public void setPatchClass(String f) {
081: patchClass = f;
082: }
083:
084: /** Name of the method to call. Must have byte[] array argument and return the same
085: */
086: private String patchMethod = "patch"; //NOI18N
087:
088: public void setPatchMethod(String f) {
089: patchMethod = f;
090: }
091:
092: /** Source JAR to extract.
093: */
094: public void setSource(File f) {
095: if (f.exists()) {
096: log("Adding source file " + f.getAbsolutePath(),
097: Project.MSG_VERBOSE);
098: FileSet xfs = new FileSet();
099: xfs.setDir(f.getParentFile());
100: log("Setting FileSet's dir to \""
101: + f.getParentFile().getAbsolutePath() + "\"",
102: Project.MSG_DEBUG);
103: xfs.setIncludes(f.getName());
104: log("Setting FileSet's include to \"" + f.getName() + "\"",
105: Project.MSG_DEBUG);
106: DirectoryScanner ds = xfs.getDirectoryScanner(getProject());
107: String[] files = ds.getIncludedFiles();
108: if (files.length < 1) {
109: log("FileSet is empty, source doesn't doesn't exist ("
110: + f.getParentFile().getAbsolutePath() + ")",
111: Project.MSG_VERBOSE);
112: } else {
113: log("Adding FileSet with " + files.length + " file(s)",
114: Project.MSG_VERBOSE);
115: addFileset(xfs);
116: }
117: }
118: }
119:
120: /* Base dir to find classes relative to */
121: private File targetdir;
122:
123: public void setTargetdir(File f) {
124: targetdir = f;
125: }
126:
127: /**
128: * Adds a set of files (nested fileset attribute).
129: */
130: private Vector<FileSet> filesets = new Vector<FileSet>();
131:
132: public void addFileset(FileSet set) {
133: log("Adding new FileSet", Project.MSG_DEBUG);
134: filesets.addElement(set);
135: }
136:
137: public void execute() throws BuildException {
138: if (targetdir == null) {
139: throw new BuildException(
140: "Attribute targetdir must be specified");
141: }
142:
143: boolean fs_empty = true;
144: for (int i = 0; i < filesets.size() && fs_empty; i++) {
145: FileSet n = filesets.elementAt(i);
146: if (n != null) {
147: DirectoryScanner ds = n
148: .getDirectoryScanner(getProject());
149: String[] files = ds.getIncludedFiles();
150: File bdir = ds.getBasedir();
151: if (files.length < 1)
152: log(
153: "FileSet is empty, doesn't have included files",
154: Project.MSG_VERBOSE);
155: for (int k = 0; k < files.length && fs_empty; k++) {
156: File n_file = new File(bdir, files[k]);
157: if (n_file.exists())
158: fs_empty = false;
159: }
160: }
161: }
162:
163: if (fs_empty) {
164: throw new BuildException(
165: "Attribute \"source\" or fileset includes must be specified");
166: }
167:
168: //
169: // Initialize the method
170: //
171:
172: log("Initializing patching " + patchClass + '.' + patchMethod);
173:
174: ClassLoader cl = new AntClassLoader(getProject(), patchPath);
175:
176: java.lang.reflect.Method m;
177: try {
178: Class<?> c = cl.loadClass(patchClass);
179: m = c.getMethod(patchMethod, byte[].class, String.class);
180: if (m.getReturnType() != byte[].class) {
181: throw new BuildException(
182: "Method does not return byte[]: " + m);
183: }
184: } catch (Exception ex) {
185: throw new BuildException("Cannot initialize class "
186: + patchClass + " and method " + patchMethod, ex);
187: }
188:
189: /*
190: try {
191: log ("Testing method " + m);
192: byte[] res = (byte[])m.invoke (null, new Object[] { new byte[0], "someString" });
193: } catch (Exception ex) {
194: throw new BuildException ("Exception during test invocation of the method", ex);
195: }
196: */
197:
198: //
199: // Ok we have the method and we can do the patching
200: // go over fileset includes
201: for (FileSet n : filesets) {
202: if (n != null) {
203: DirectoryScanner ds = n
204: .getDirectoryScanner(getProject());
205: String[] files = ds.getIncludedFiles();
206: File bdir = ds.getBasedir();
207: for (int k = 0; k < files.length; k++) {
208: File n_file = new File(bdir, files[k]);
209: JarFile jar;
210: log("Checking classes in jarfile " + n_file,
211: Project.MSG_VERBOSE);
212:
213: try {
214: jar = new JarFile(n_file);
215: } catch (IOException ex) {
216: throw new BuildException(
217: "Problem initializing file " + n_file,
218: ex);
219: }
220:
221: // do the patching
222: java.util.Enumeration it = jar.entries();
223: while (it.hasMoreElements()) {
224: java.util.jar.JarEntry e = (java.util.jar.JarEntry) it
225: .nextElement();
226: String entryname = e.getName();
227: if (!entryname.endsWith(".class")) { //NOI18N
228: // resource, skip
229: log(
230: "Skipping record (probably directory or resource) "
231: + entryname,
232: Project.MSG_DEBUG);
233: continue;
234: }
235: String name = entryname.substring(0,
236: entryname.length() - 6).replace('/',
237: '.');
238:
239: int size = (int) e.getSize();
240: if (size <= 4) {
241: // not interesting entry
242: log(
243: "Class "
244: + name
245: + " is not an interesting entry (<5 bytes)",
246: Project.MSG_DEBUG);
247: continue;
248: }
249:
250: log("Checking class " + name, Project.MSG_DEBUG);
251:
252: byte[] arr = new byte[size];
253:
254: try {
255: java.io.InputStream is = jar
256: .getInputStream(e);
257:
258: int indx = 0;
259: while (indx < arr.length) {
260: int read = is.read(arr, indx,
261: arr.length - indx);
262: if (read == -1) {
263: throw new BuildException("Entry: "
264: + name
265: + " size should be: "
266: + size
267: + " but was read just: "
268: + indx);
269: }
270: indx += read;
271: }
272: } catch (IOException ex) {
273: throw new BuildException(ex);
274: }
275:
276: byte[] original = arr.clone();
277: byte[] out;
278: try {
279: out = (byte[]) m.invoke(null, new Object[] {
280: arr, name });
281: } catch (java.lang.reflect.InvocationTargetException ex) {
282: throw new BuildException(ex
283: .getTargetException());
284: } catch (Exception ex) {
285: throw new BuildException(ex);
286: }
287:
288: if (java.util.Arrays.equals(original, out)) {
289: // no patching, go on
290: log("Not patching class " + name,
291: Project.MSG_DEBUG);
292: continue;
293: }
294:
295: File f = new File(targetdir, e.getName()
296: .replace('/', File.separatorChar));
297: if (f.exists()
298: && f.lastModified() > n_file
299: .lastModified()) {
300: // if the file is newer
301: log(
302: "Patched class "
303: + name
304: + " in "
305: + targetdir
306: .getAbsolutePath()
307: + " is newer than jarfile of origin, not saving patched bytestream to file "
308: + f.getAbsolutePath(),
309: Project.MSG_VERBOSE);
310: continue;
311: }
312:
313: f.getParentFile().mkdirs();
314:
315: log("Writing patched file " + f,
316: Project.MSG_INFO);
317: //log ("Writing patched file " + f + " (jarfile of origin " + n_file.getName() + ")", Project.MSG_VERBOSE);
318:
319: try {
320: FileOutputStream os = new FileOutputStream(
321: f);
322: os.write(out);
323: os.close();
324: } catch (IOException ex) {
325: throw new BuildException(
326: "Cannot write file " + f, ex);
327: }
328: }
329: }
330: }
331: }
332: }
333:
334: }
|