0001: package com.sun.portal.sra.admin.util;
0002:
0003: import java.io.BufferedInputStream;
0004: import java.io.BufferedReader;
0005: import java.io.BufferedWriter;
0006: import java.io.ByteArrayOutputStream;
0007: import java.io.File;
0008: import java.io.FileInputStream;
0009: import java.io.FileNotFoundException;
0010: import java.io.FileOutputStream;
0011: import java.io.FileReader;
0012: import java.io.FilenameFilter;
0013: import java.io.IOException;
0014: import java.io.InputStream;
0015: import java.io.InputStreamReader;
0016: import java.io.OutputStreamWriter;
0017: import java.io.Reader;
0018: import java.io.StringReader;
0019: import java.lang.reflect.Method;
0020: import java.net.URL;
0021: import java.net.URLClassLoader;
0022: import java.util.ArrayList;
0023: import java.util.Enumeration;
0024: import java.util.Properties;
0025: import java.util.Vector;
0026: import java.util.jar.JarEntry;
0027: import java.util.jar.JarFile;
0028: import java.util.jar.JarOutputStream;
0029: import java.util.zip.ZipEntry;
0030:
0031: import com.sun.portal.sra.admin.ConfigurationConstants;
0032:
0033: public class Util {
0034:
0035: protected static String name_ = System.getProperty("os.name");
0036:
0037: public Util() {
0038: }
0039:
0040: public static void debug(String str) {
0041: String debug = System.getProperty("PS_CONFIG_DEBUG");
0042: if (debug != null && debug.equals("y")) {
0043: System.out.println(str);
0044: }
0045: }
0046:
0047: public static boolean isRoot() {
0048: String user = System.getProperty("user.name");
0049: if (is_windows()) {
0050: //return (user.equalsIgnoreCase("Administrator")) ? true : false;
0051: return true;
0052: } else {
0053: return (user.equals("root")) ? true : false;
0054: }
0055: }
0056:
0057: public static boolean fileExists(String filename) {
0058: try {
0059: File file = new File(filename);
0060: if (file.exists()) {
0061: return true;
0062: }
0063: } catch (NullPointerException npe) {
0064: return false;
0065: } catch (SecurityException se) {
0066: return false;
0067: }
0068: return false;
0069: }
0070:
0071: public static FilenameFilter getExtensionFilter(String ext) {
0072: ExtensionFilter filter = new ExtensionFilter(ext);
0073: return (FilenameFilter) filter;
0074: }
0075:
0076: public static void getFiles(File pwd, Vector allFiles)
0077: throws NullPointerException {
0078: File[] pwdFiles = pwd.listFiles();
0079: for (int i = 0; i < pwdFiles.length; i++) {
0080: File file = (File) pwdFiles[i];
0081: if (file.isFile()) {
0082: allFiles.add(file);
0083: } else if (file.isDirectory()) {
0084: allFiles.add(file);
0085: getFiles(file, allFiles);
0086: }
0087: }
0088: }
0089:
0090: public static void getFilteredFiles(File pwd, Vector allFiles,
0091: String ext) throws NullPointerException {
0092: FilenameFilter filter = getExtensionFilter(ext);
0093: File[] pwdFiles = pwd.listFiles(filter);
0094: for (int i = 0; i < pwdFiles.length; i++) {
0095: File file = (File) pwdFiles[i];
0096: if (file.isFile()) {
0097: allFiles.add(file);
0098: } else if (file.isDirectory()) {
0099: allFiles.add(file);
0100: getFiles(file, allFiles);
0101: }
0102: }
0103: }
0104:
0105: public static File[] getSubDirectories(File parent) {
0106: FilenameFilter dirFilter = new DirectoryFilter();
0107: return parent.listFiles(dirFilter);
0108:
0109: }
0110:
0111: public static void moveFile(String fromFilename, String toFilename)
0112: throws FileNotFoundException, IOException {
0113: copyFile(new File(fromFilename), new File(toFilename), true);
0114: }
0115:
0116: public static void moveFile(File fromFile, File toFile)
0117: throws FileNotFoundException, IOException {
0118: copyFile(fromFile, toFile, true);
0119: }
0120:
0121: public static void copyFile(String fromFilename, String toFilename)
0122: throws FileNotFoundException, IOException {
0123: copyFile(new File(fromFilename), new File(toFilename), false);
0124: }
0125:
0126: public static void copyFile(File fromFile, File toFile)
0127: throws FileNotFoundException, IOException {
0128: copyFile(fromFile, toFile, false);
0129: }
0130:
0131: private static byte[] getByteData(InputStream cistream)
0132: throws IOException {
0133: byte[] byteBuf = new byte[1024];
0134: ByteArrayOutputStream bout = new ByteArrayOutputStream();
0135:
0136: int num = 0;
0137: try {
0138: while ((num = cistream.read(byteBuf)) != -1) {
0139: bout.write(byteBuf, 0, num);
0140: }
0141: } catch (NullPointerException npe) {
0142: throw new IOException(npe.toString());
0143: } catch (IOException ioe) {
0144: throw new IOException(ioe.toString());
0145: }
0146: return bout.toByteArray();
0147: }
0148:
0149: public static void copyFile(File fromFile, File toFile,
0150: boolean deleteSourceFile) throws FileNotFoundException,
0151: IOException {
0152: if ((fromFile != null) && (toFile != null)) {
0153: if (!fromFile.exists()) {
0154: fromFile.createNewFile();
0155: } else if (fromFile.isDirectory()) {
0156: fromFile.mkdirs();
0157: return;
0158: }
0159:
0160: if ((toFile.exists()) && (!toFile.isDirectory())) {
0161: toFile.delete();
0162: }
0163:
0164: File parent = toFile.getParentFile();
0165: if (parent != null) {
0166: parent.mkdirs();
0167: }
0168: FileInputStream fis = new FileInputStream(fromFile);
0169: byte[] b = getByteData(fis);
0170: fis.close();
0171:
0172: FileOutputStream fout = new FileOutputStream(toFile);
0173: fout.write(b);
0174: fout.close();
0175:
0176: if (deleteSourceFile) {
0177: fromFile.delete();
0178: }
0179: }
0180: }
0181:
0182: public static boolean deleteFile(String filename) {
0183: return deleteFile(new File(filename));
0184: }
0185:
0186: public static boolean deleteFile(File file) {
0187: return file.delete();
0188: }
0189:
0190: public static boolean directoryExists(String dirName) {
0191: try {
0192: File file = new File(dirName);
0193: if ((file.exists()) && (file.isDirectory())) {
0194: return true;
0195: }
0196: } catch (NullPointerException npe) {
0197: return false;
0198: } catch (SecurityException se) {
0199: return false;
0200: }
0201: return false;
0202: }
0203:
0204: public static boolean makeDir(String dirName) {
0205: File dir = new File(dirName);
0206: if (!dir.exists()) {
0207: return dir.mkdirs();
0208: }
0209: return true;
0210: }
0211:
0212: public static void renameDir(String fromDirName, String toDirName)
0213: throws FileNotFoundException, IOException {
0214: Vector allFiles = new Vector();
0215: try {
0216: getFiles(new File(fromDirName), allFiles);
0217: } catch (NullPointerException npe) {
0218: }
0219:
0220: makeDir(toDirName);
0221: for (int i = 0; i < allFiles.size(); i++) {
0222: File fromFile = (File) allFiles.get(i);
0223: String absolutePath = fromFile.getAbsolutePath();
0224: String relativePath = absolutePath.substring(fromDirName
0225: .length(), absolutePath.length());
0226: String destPath = toDirName + relativePath;
0227: copyFile(fromFile, new File(destPath));
0228: }
0229: }
0230:
0231: public static void copyDir(String fromDirName, String toDirName)
0232: throws FileNotFoundException, IOException {
0233: Vector allFiles = new Vector();
0234: try {
0235: getFiles(new File(fromDirName), allFiles);
0236: } catch (NullPointerException npe) {
0237: }
0238:
0239: makeDir(toDirName);
0240: for (int i = 0; i < allFiles.size(); i++) {
0241: File fromFile = (File) allFiles.get(i);
0242: String absolutePath = fromFile.getAbsolutePath();
0243: String relativePath = absolutePath.substring(fromDirName
0244: .length(), absolutePath.length());
0245: String destPath = toDirName + relativePath;
0246: copyFile(fromFile, new File(destPath));
0247: }
0248: }
0249:
0250: public static boolean deleteDir(String dirName) {
0251: Util.debug("Deleting dir:" + dirName);
0252: File dir = new File(dirName);
0253:
0254: if (!dir.isDirectory())
0255: return deleteFile(dir);
0256:
0257: return deleteDir(dir);
0258: }
0259:
0260: public static boolean deleteDir(File dir) {
0261: if (!dir.isDirectory())
0262: return deleteFile(dir);
0263:
0264: boolean deleted = false;
0265: File[] dirFiles = dir.listFiles();
0266: for (int i = 0; i < dirFiles.length; i++) {
0267: File file = (File) dirFiles[i];
0268: if (file.isFile()) {
0269: deleted = deleteFile(file);
0270: } else if (file.isDirectory()) {
0271: deleted = deleteDir(file);
0272: }
0273: if (!deleted)
0274: return false;
0275: }
0276:
0277: return dir.delete();
0278: }
0279:
0280: public static boolean isOS(String type) {
0281: Properties sysProps = System.getProperties();
0282: String osName = sysProps.getProperty("os.name");
0283: if (osName.equals(type)) {
0284: return true;
0285: } else {
0286: return false;
0287: }
0288: }
0289:
0290: public static void createSymbolicLink(String source, String target)
0291: throws Exception {
0292: if (isOS("SunOS")) {
0293: String cmd = "/usr/bin/ln";
0294: String[] args = { "-fs", source, target };
0295: runCommandLine(cmd, args);
0296: } else if (isOS("Linux")) {
0297: String cmd = "/bin/ln";
0298: String[] args = { "-fs", source, target };
0299: runCommandLine(cmd, args);
0300: } else if (isOS("HP-UX")) {
0301: String cmd = "/bin/ln";
0302: String[] args = { "-fs", source, target };
0303: runCommandLine(cmd, args);
0304: } else if (Util.is_windows()) {
0305: //Symbolic links not supported in windows
0306: //So copy instead of link
0307: //If source is a dir then copydir, else copyfile
0308: File file = new File(source);
0309: if (file.exists()) {
0310: if (file.isDirectory()) {
0311: copyDir(source, target);
0312: } else {
0313: copyFile(source, target);
0314: }
0315: }
0316: } else {
0317: debug("Util:createSymbolicLink error - unsupported OS");
0318: }
0319: }
0320:
0321: public static void changeFilePermission(String targetfile,
0322: String permission) throws Exception {
0323: if (isOS("SunOS")) {
0324: String cmd = "/usr/bin/chmod";
0325: String[] args = { permission, targetfile };
0326: runCommandLine(cmd, args);
0327: } else if (isOS("Linux")) {
0328: String cmd = "/bin/chmod";
0329: String[] args = { permission, targetfile };
0330: runCommandLine(cmd, args);
0331: } else if (isOS("HP-UX")) {
0332: String cmd = "/bin/chmod";
0333: String[] args = { permission, targetfile };
0334: runCommandLine(cmd, args);
0335: } else {
0336: debug("Util:changeFilePermission error - unsupported OS");
0337: }
0338: }
0339:
0340: public static String decoratePath(String path) {
0341: if (is_windows()) {
0342: //Since spaces are valid in windows paths
0343: //if path contains spaces, return path quoted .i.e. "path"
0344: if (path != null && path.indexOf(' ') != -1) {
0345: StringBuffer quotedPath = new StringBuffer("\"" + path
0346: + "\"");
0347: return quotedPath.toString();
0348: }
0349: }
0350: return path;
0351: }
0352:
0353: //Append text at line after the first matching line
0354: public static boolean appendLineInFile(File file, String match,
0355: String text) throws IOException, FileNotFoundException {
0356: File tmpFile = null;
0357: try {
0358: tmpFile = File.createTempFile("appendlineinfile", ".tmp");
0359: } catch (IllegalArgumentException iae) {
0360: throw new IOException(iae.toString());
0361: } catch (SecurityException se) {
0362: throw new IOException(se.toString());
0363: }
0364:
0365: BufferedReader in = new BufferedReader(new InputStreamReader(
0366: new FileInputStream(file), "UTF-8"));
0367: BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
0368: new FileOutputStream(tmpFile), "UTF-8"));
0369:
0370: boolean appended = false;
0371: String line = null;
0372: while ((line = in.readLine()) != null) {
0373: out.write(line);
0374: out.newLine();
0375: if (!appended) {
0376: if (line.indexOf(match) != -1) {
0377: out.write(text);
0378: out.newLine();
0379: appended = true;
0380: }
0381: }
0382: }
0383: in.close();
0384: out.close();
0385: Util.copyFile(tmpFile, file);
0386: tmpFile.delete();
0387: return appended;
0388: }
0389:
0390: public static void replaceLineInFile(File file, String pattern,
0391: StringBuffer text) throws IOException,
0392: FileNotFoundException {
0393: File tmpFile = null;
0394: try {
0395: tmpFile = File.createTempFile("replacelineinfile", ".tmp");
0396: } catch (IllegalArgumentException iae) {
0397: throw new IOException(iae.toString());
0398: } catch (SecurityException se) {
0399: throw new IOException(se.toString());
0400: }
0401:
0402: BufferedReader in = new BufferedReader(new InputStreamReader(
0403: new FileInputStream(file), "UTF-8"));
0404: BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
0405: new FileOutputStream(tmpFile), "UTF-8"));
0406:
0407: String line = null;
0408: while ((line = in.readLine()) != null) {
0409: if (line.indexOf(pattern) != -1) {
0410: out.write(text.toString());
0411: out.newLine();
0412: } else {
0413: out.write(line);
0414: out.newLine();
0415: }
0416: }
0417:
0418: in.close();
0419: out.close();
0420: Util.copyFile(tmpFile, file);
0421: tmpFile.delete();
0422: }
0423:
0424: public static void deleteLineInFile(File file, String pattern)
0425: throws IOException, FileNotFoundException {
0426:
0427: File tmpFile = null;
0428: try {
0429: tmpFile = File.createTempFile("deletelineinfile", ".tmp");
0430: } catch (IllegalArgumentException iae) {
0431: throw new IOException(iae.toString());
0432: } catch (SecurityException se) {
0433: throw new IOException(se.toString());
0434: }
0435:
0436: BufferedReader in = new BufferedReader(new InputStreamReader(
0437: new FileInputStream(file), "UTF-8"));
0438: BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
0439: new FileOutputStream(tmpFile), "UTF-8"));
0440:
0441: String line = null;
0442: while ((line = in.readLine()) != null) {
0443: if (line.indexOf(pattern) == -1) {
0444: out.write(line);
0445: out.newLine();
0446: }
0447: }
0448:
0449: in.close();
0450: out.close();
0451: Util.copyFile(tmpFile, file);
0452: tmpFile.delete();
0453: }
0454:
0455: public static void deleteUntilBlankLineInFile(File file,
0456: String startPattern) throws IOException,
0457: FileNotFoundException {
0458:
0459: File tmpFile = null;
0460: try {
0461: tmpFile = File.createTempFile("deletelineinfile", ".tmp");
0462: } catch (IllegalArgumentException iae) {
0463: throw new IOException(iae.toString());
0464: } catch (SecurityException se) {
0465: throw new IOException(se.toString());
0466: }
0467:
0468: BufferedReader in = new BufferedReader(new InputStreamReader(
0469: new FileInputStream(file), "UTF-8"));
0470: BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
0471: new FileOutputStream(tmpFile), "UTF-8"));
0472:
0473: boolean doCopy = true;
0474: String endPattern = "";
0475: String line = null;
0476: while ((line = in.readLine()) != null) {
0477: //Dont copy from start of pattern
0478: if (line.indexOf(startPattern) >= 0) {
0479: doCopy = false;
0480: }
0481: //till the next blank line
0482: if (!doCopy && line.trim().equals(endPattern)) {
0483: doCopy = true;
0484: }
0485:
0486: if (doCopy) {
0487: out.write(line);
0488: out.newLine();
0489: }
0490: }
0491:
0492: in.close();
0493: out.close();
0494: Util.copyFile(tmpFile, file);
0495: tmpFile.delete();
0496: }
0497:
0498: public static void appendLineEof(File file, String text,
0499: boolean checkIfExists) throws IOException,
0500: FileNotFoundException {
0501: File tmpFile = null;
0502: try {
0503: tmpFile = File.createTempFile("appendlineeof", ".tmp");
0504: } catch (IllegalArgumentException iae) {
0505: throw new IOException(iae.toString());
0506: } catch (SecurityException se) {
0507: throw new IOException(se.toString());
0508: }
0509:
0510: BufferedReader in = new BufferedReader(new InputStreamReader(
0511: new FileInputStream(file), "UTF-8"));
0512: BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
0513: new FileOutputStream(tmpFile), "UTF-8"));
0514:
0515: boolean found = false;
0516: String line;
0517: while ((line = in.readLine()) != null) {
0518: if (checkIfExists) {
0519: if (line.equals(text)) {
0520: found = true;
0521: }
0522: }
0523: out.write(line);
0524: out.newLine();
0525: }
0526: in.close();
0527:
0528: if (!found) {
0529: out.write(text);
0530: out.newLine();
0531: }
0532: out.close();
0533: Util.copyFile(tmpFile, file);
0534: tmpFile.delete();
0535: }
0536:
0537: public static String findTextInFile(File file, String text)
0538: throws FileNotFoundException, IOException {
0539: BufferedReader in = new BufferedReader(new InputStreamReader(
0540: new FileInputStream(file), "UTF-8"));
0541:
0542: String line;
0543: while ((line = in.readLine()) != null) {
0544: if (line.indexOf(text) >= 0) {
0545: in.close();
0546: return line;
0547: }
0548: }
0549: in.close();
0550: return "";
0551: }
0552:
0553: public static void replaceAllInstancesOfTokenInFile(File file,
0554: String token, String newText) throws FileNotFoundException,
0555: IOException {
0556: File tmpFile = null;
0557: try {
0558: tmpFile = File.createTempFile("replacetokeninfile", ".tmp");
0559: } catch (IllegalArgumentException iae) {
0560: throw new IOException(iae.toString());
0561: } catch (SecurityException se) {
0562: throw new IOException(se.toString());
0563: }
0564:
0565: replaceAllInstancesOfTokenInFile(file, tmpFile, token, newText);
0566:
0567: Util.copyFile(tmpFile, file);
0568: tmpFile.delete();
0569: }
0570:
0571: public static void replaceAllInstancesOfTokenInFile(File origFile,
0572: File newFile, String token, String newText)
0573: throws FileNotFoundException, IOException {
0574: //replaces all occurences of the token in the same line
0575: BufferedReader in = new BufferedReader(new InputStreamReader(
0576: new FileInputStream(origFile)));
0577: BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
0578: new FileOutputStream(newFile)));
0579:
0580: String line;
0581: while ((line = in.readLine()) != null) {
0582: int startIndex = line.indexOf(token);
0583: while (startIndex >= 0) {
0584: int endIndex = startIndex + token.length();
0585: StringBuffer newLine = new StringBuffer();
0586: newLine.append(line.substring(0, startIndex));
0587: newLine.append(newText);
0588: newLine.append(line.substring(endIndex, line.length()));
0589: line = new String(newLine);
0590: int newIndex = startIndex + newText.length();
0591: startIndex = line.indexOf(token, newIndex);
0592: }
0593: out.write(line);
0594: out.newLine();
0595:
0596: }
0597: in.close();
0598: out.close();
0599:
0600: }
0601:
0602: public static void replaceTokenInFile(File origFile, File newFile,
0603: String token, String newText) throws FileNotFoundException,
0604: IOException {
0605:
0606: BufferedReader in = new BufferedReader(new InputStreamReader(
0607: new FileInputStream(origFile)));
0608: BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
0609: new FileOutputStream(newFile)));
0610:
0611: StringBuffer newLine;
0612:
0613: String line;
0614: while ((line = in.readLine()) != null) {
0615: int startIndex = line.indexOf(token);
0616: if (startIndex >= 0) {
0617: newLine = new StringBuffer();
0618: int endIndex = startIndex + token.length();
0619: newLine.append(line.substring(0, startIndex));
0620: newLine.append(newText);
0621: newLine.append(line.substring(endIndex, line.length()));
0622: out.write(newLine.toString());
0623: out.newLine();
0624: } else {
0625: out.write(line);
0626: out.newLine();
0627: }
0628: }
0629: in.close();
0630: out.close();
0631: }
0632:
0633: public static void replaceTokenInFile(File file, String token,
0634: String newText) throws FileNotFoundException, IOException {
0635: File tmpFile = null;
0636: try {
0637: tmpFile = File.createTempFile("replacetokeninfile", ".tmp");
0638: } catch (IllegalArgumentException iae) {
0639: throw new IOException(iae.toString());
0640: } catch (SecurityException se) {
0641: throw new IOException(se.toString());
0642: }
0643:
0644: BufferedReader in = new BufferedReader(new InputStreamReader(
0645: new FileInputStream(file)));
0646: BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
0647: new FileOutputStream(tmpFile)));
0648:
0649: StringBuffer newLine;
0650:
0651: String line;
0652: while ((line = in.readLine()) != null) {
0653: int startIndex = line.indexOf(token);
0654: if (startIndex >= 0) {
0655: newLine = new StringBuffer();
0656: int endIndex = startIndex + token.length();
0657: newLine.append(line.substring(0, startIndex));
0658: newLine.append(newText);
0659: newLine.append(line.substring(endIndex, line.length()));
0660: out.write(newLine.toString());
0661: out.newLine();
0662: } else {
0663: out.write(line);
0664: out.newLine();
0665: }
0666: }
0667: in.close();
0668: out.close();
0669: Util.copyFile(tmpFile, file);
0670: tmpFile.delete();
0671: }
0672:
0673: public static void replaceTokenInFile(File file, String[] tokens,
0674: String[] values) throws FileNotFoundException, IOException {
0675: File tmpFile = null;
0676: try {
0677: tmpFile = File.createTempFile("replacetokeninfile", ".tmp");
0678: } catch (IllegalArgumentException iae) {
0679: throw new IOException(iae.toString());
0680: } catch (SecurityException se) {
0681: throw new IOException(se.toString());
0682: }
0683:
0684: BufferedReader in = new BufferedReader(new InputStreamReader(
0685: new FileInputStream(file)));
0686: BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
0687: new FileOutputStream(tmpFile)));
0688:
0689: StringBuffer newLine;
0690:
0691: String line;
0692: while ((line = in.readLine()) != null) {
0693: for (int i = 0; i < tokens.length; ++i) {
0694: String token = tokens[i];
0695: int startIndex = line.indexOf(token);
0696: if (startIndex >= 0) {
0697: newLine = new StringBuffer();
0698: int endIndex = startIndex + token.length();
0699: newLine.append(line.substring(0, startIndex));
0700: String newText = values[i];
0701: newLine.append(newText);
0702: newLine.append(line.substring(endIndex, line
0703: .length()));
0704: line = newLine.toString();
0705: }
0706: }
0707: out.write(line);
0708: out.newLine();
0709: }
0710: in.close();
0711: out.close();
0712: Util.copyFile(tmpFile, file);
0713: tmpFile.delete();
0714: }
0715:
0716: public static String extractPatternTillEOL(File file, String key,
0717: String separator) {
0718: String rline = "";
0719: String answer = "";
0720: try {
0721: BufferedReader inBuff = new BufferedReader(new FileReader(
0722: file));
0723: while ((rline = inBuff.readLine()) != null) {
0724: if (rline.indexOf(key) >= 0) {
0725: answer = rline
0726: .substring(rline.indexOf(separator) + 1);
0727: answer = answer.trim();
0728: break;
0729: }
0730: }
0731: } catch (Exception e) {
0732: Util.debug("Error in extracting pattern");
0733: }
0734: return answer;
0735: }
0736:
0737: public static String extractPattern(File file, String patternBegin,
0738: String patternEnd) throws IOException,
0739: FileNotFoundException {
0740: BufferedReader in = new BufferedReader(new FileReader(file));
0741: String str = null;
0742: ArrayList lines = new ArrayList();
0743: while ((str = in.readLine()) != null) {
0744: lines.add(str + "\n");
0745: }
0746: in.close();
0747: int size = lines.size();
0748: int i = 0;
0749: int start = 0, end = 0;
0750: for (i = 0; i < size; i++) {
0751: str = ((String) lines.get(i)).trim();
0752: if (str.indexOf(patternBegin) >= 0) {
0753: if (str.indexOf(patternEnd) >= 0) {
0754: str = str.substring(str.indexOf(patternBegin)
0755: + patternBegin.length());
0756: return str.substring(0, str.indexOf(patternEnd));
0757: }
0758: }
0759: }
0760: return "";
0761: }
0762:
0763: public static void extractPatternFromFile(File file,
0764: StringBuffer target, String patternBegin, String patternEnd)
0765: throws IOException, FileNotFoundException {
0766: BufferedReader in = new BufferedReader(new FileReader(file));
0767: String str = null;
0768: ArrayList lines = new ArrayList();
0769: while ((str = in.readLine()) != null) {
0770: lines.add(str + "\n");
0771: }
0772: in.close();
0773:
0774: int size = lines.size();
0775: int i = 0;
0776: int start = 0, end = 0;
0777: for (i = 0; i < size; i++) {
0778: if (((String) lines.get(i)).trim().startsWith(patternBegin)) {
0779: if (i == size) {
0780: return;
0781: }
0782: start = i;
0783: for (; i < size; i++) {
0784: if (((String) lines.get(i)).trim().startsWith(
0785: patternEnd)) {
0786: end = i;
0787: for (int j = start; j <= end; j++) {
0788: target.append((String) lines.get(j));
0789: }
0790: break;
0791: }
0792: }
0793: }
0794: }
0795: }
0796:
0797: public static void dos2unix(File file)
0798: throws FileNotFoundException, IOException {
0799: File tmpFile = null;
0800: try {
0801: tmpFile = File.createTempFile("dos2unix", ".tmp");
0802: } catch (IllegalArgumentException iae) {
0803: throw new IOException(iae.toString());
0804: } catch (SecurityException se) {
0805: throw new IOException(se.toString());
0806: }
0807:
0808: BufferedReader in = new BufferedReader(new InputStreamReader(
0809: new FileInputStream(file)));
0810: BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
0811: new FileOutputStream(tmpFile)));
0812:
0813: StringBuffer newLine;
0814:
0815: String line;
0816: //Assumes that the input file has dos-style \r\n line seperators).
0817: //Reads a line and writes out with only \n line seperator
0818: while ((line = in.readLine()) != null) {
0819: out.write(line);
0820: out.write("\n");
0821: }
0822: in.close();
0823: out.close();
0824: Util.copyFile(tmpFile, file);
0825: tmpFile.delete();
0826: }
0827:
0828: public static Reader runCommandLine(String command)
0829: throws Exception {
0830: return runCommandLine(command, null, null, null);
0831: }
0832:
0833: public static Reader runCommandLine(String command, String[] args)
0834: throws Exception {
0835: return runCommandLine(command, args, null, null);
0836: }
0837:
0838: public static Reader runCommandLine(String command, String[] args,
0839: Vector envs) throws Exception {
0840: return runCommandLine(command, args, envs, null);
0841: }
0842:
0843: public static Reader runCommandLine(String command, String[] args,
0844: Vector envs, File dir) throws Exception {
0845: if (is_windows()) {
0846: return executeWindows(command, args, envs, dir);
0847: }
0848: return execute(command, args, envs, dir);
0849: }
0850:
0851: public static Reader execute(String command, String[] args,
0852: Vector envs, File dir) throws Exception {
0853: int length = (args != null) ? args.length + 1 : 1;
0854: String[] cmd = new String[length];
0855:
0856: cmd[0] = command;
0857: if (args != null) {
0858: for (int i = 0; i < args.length; i++) {
0859: cmd[i + 1] = args[i];
0860: }
0861: }
0862:
0863: int envSize = (envs != null) ? envs.size() + 7 : 7;
0864: String[] envVars = new String[envSize];
0865: envVars[0] = "DEPLOY_ADMIN_PASSWORD="
0866: + System
0867: .getProperty(ConfigurationConstants.DEPLOY_ADMIN_PASSWORD);
0868: envVars[1] = "DS_DIRMGR_PASSWORD="
0869: + System
0870: .getProperty(ConfigurationConstants.DS_DIRMGR_PASSWORD);
0871: envVars[2] = "IDSAME_LDAPUSER_PASSWORD="
0872: + System
0873: .getProperty(ConfigurationConstants.IS_LDAPUSER_PASSWORD);
0874: envVars[3] = "IDSAME_ADMIN_PASSWORD="
0875: + System
0876: .getProperty(ConfigurationConstants.IS_ADMIN_PASSWORD);
0877: envVars[4] = "sra.log.user.password="
0878: + System
0879: .getProperty(ConfigurationConstants.SRA_LOG_USER_PASSWORD);
0880: envVars[5] = "certificate.database.password="
0881: + System
0882: .getProperty(ConfigurationConstants.CERT_PASSWORD);
0883: envVars[6] = "PATH=/usr/bin:/usr/sbin:/bin";
0884: if (envs != null) {
0885: for (int i = 0; i < envs.size(); i++) {
0886: envVars[i + 7] = (String) envs.get(i);
0887: }
0888: }
0889:
0890: boolean inPassword = false;
0891: for (int i = 0; i < cmd.length; i++) {
0892: if (inPassword == true) {
0893: inPassword = false;
0894: debug("cmd[" + i + "] = ********");
0895: } else {
0896: if (cmd[i] != null && cmd[i].indexOf("_password") != -1) {
0897: inPassword = true;
0898: }
0899: debug("cmd[" + i + "] = " + cmd[i]);
0900: }
0901: }
0902:
0903: for (int i = 0; i < envVars.length; i++) {
0904: if (envVars[i] != null
0905: && envVars[i].indexOf("_PASSWORD") != -1) {
0906: int index = envVars[i].indexOf("=");
0907: if (index != -1) {
0908: debug("env[" + i + "] = "
0909: + envVars[i].substring(0, index)
0910: + "=********");
0911: } else {
0912: debug("env[" + i + "] = " + envVars[i]);
0913: }
0914: } else {
0915: debug("env[" + i + "] = " + envVars[i]);
0916: }
0917: }
0918:
0919: Runtime rt = Runtime.getRuntime();
0920: Process proc = rt.exec(cmd, envVars, dir);
0921:
0922: BufferedInputStream output = new BufferedInputStream(proc
0923: .getInputStream());
0924: BufferedInputStream error = new BufferedInputStream(proc
0925: .getErrorStream());
0926:
0927: ProcessStreamBuffer inputStream = new ProcessStreamBuffer(
0928: output);
0929: ProcessStreamBuffer errorStream = new ProcessStreamBuffer(error);
0930:
0931: new Thread(inputStream).start();
0932: new Thread(errorStream).start();
0933:
0934: if (proc.waitFor() == 0) {
0935: debug("Command - " + command);
0936: debug("output log:");
0937: debug(inputStream.output());
0938: debug("error log:");
0939: debug(errorStream.output());
0940: return new StringReader(inputStream.output());
0941: } else {
0942: debug("Command - " + command + " - exited with error");
0943: debug("output log:");
0944: debug(inputStream.output());
0945: debug("error log:");
0946: debug(errorStream.output());
0947: return new StringReader(errorStream.output());
0948: }
0949: }
0950:
0951: /*
0952: * Problem with Process.waitFor() on windows:
0953: * If the process generates output/error streams that
0954: * exceed the buffer length 612bytes, the
0955: * Process.waitFor() waits (hangs) until the
0956: * InputStream, ErrorStream is read. Since this
0957: * function returns the InputStream/ErrorStream,
0958: * reading these before returning will make these
0959: * streams unreadable. In this implementation, the
0960: * input and error streams are always read in a thread
0961: * so that in case there is any error/output, the
0962: * application does not hang, but returns NOTE: Since
0963: * windows allows spaces in file-paths, any such
0964: * command/argument needs to be suitable enclosed in
0965: * quotes.
0966: */
0967: public static Reader executeWindows(String command, String[] args,
0968: Vector envs, File dir) throws Exception {
0969: StringBuffer cmdBuf = new StringBuffer("");
0970: cmdBuf.append("\"" + command + "\" ");
0971: if (args != null) {
0972: for (int i = 0; i < args.length; i++) {
0973: if (i != args.length - 1) {
0974: cmdBuf.append(args[i] + " ");
0975: } else {
0976: cmdBuf.append(args[i]);
0977: }
0978: }
0979: }
0980:
0981: boolean isWorkingDirSpecified = false;
0982: if (dir != null) {
0983: if (dir.exists() && dir.isDirectory())
0984: isWorkingDirSpecified = true;
0985: }
0986:
0987: Runtime rt = Runtime.getRuntime();
0988: Process proc = null;
0989: if (envs == null || envs.size() == 0) {
0990: debug(" windows exec:" + cmdBuf.toString());
0991: if (isWorkingDirSpecified)
0992: proc = rt.exec(cmdBuf.toString(), null, dir);
0993: else
0994: proc = rt.exec(cmdBuf.toString());
0995: } else {
0996: String[] envVars = new String[envs.size()];
0997: for (int i = 0; i < envs.size(); i++) {
0998: envVars[i] = (String) envs.get(i);
0999: }
1000: debug(" windows exec+env:" + cmdBuf.toString());
1001: if (isWorkingDirSpecified)
1002: proc = rt.exec(cmdBuf.toString(), envVars, dir);
1003: else
1004: proc = rt.exec(cmdBuf.toString(), envVars);
1005: }
1006:
1007: BufferedInputStream output = new BufferedInputStream(proc
1008: .getInputStream());
1009: BufferedInputStream error = new BufferedInputStream(proc
1010: .getErrorStream());
1011:
1012: ProcessStreamBuffer inputStream = new ProcessStreamBuffer(
1013: output);
1014: ProcessStreamBuffer errorStream = new ProcessStreamBuffer(error);
1015:
1016: new Thread(inputStream).start();
1017: new Thread(errorStream).start();
1018:
1019: if (proc.waitFor() == 0) {
1020: debug(" windows exec success");
1021: debug("output log:" + inputStream.output());
1022: debug("error log:" + errorStream.output());
1023: return new StringReader(inputStream.output());
1024: } else {
1025: debug(" windows exec " + command + " failure");
1026: debug("output log:" + inputStream.output());
1027: debug("error log:" + errorStream.output());
1028: return new StringReader(errorStream.output());
1029: }
1030: }
1031:
1032: static public boolean match_os(String os_name) {
1033: return match(os_name);
1034: }
1035:
1036: static public boolean match(String name) {
1037: return (name_.equalsIgnoreCase(name) == true);
1038: }
1039:
1040: static public boolean is_windows() {
1041: return System.getProperty("os.name").indexOf("indows") != -1;
1042: }
1043:
1044: static public boolean is_linux() {
1045: return System.getProperty("os.name").startsWith("Linux");
1046: }
1047:
1048: static public boolean is_hpux() {
1049: return System.getProperty("os.name").startsWith("HP-UX");
1050: }
1051:
1052: public static String replaceToken(String source, String token,
1053: String newText) {
1054: if (token == null || newText == null || source == null) {
1055: return source;
1056: }
1057: StringBuffer buf = new StringBuffer(source);
1058: int loc = 0, tokenLen = token.length(), ntLen = newText
1059: .length();
1060:
1061: while ((loc = buf.toString().indexOf(token, loc)) != -1) {
1062: buf.replace(loc, loc + tokenLen, newText);
1063: loc = loc + ntLen;
1064: }
1065: return buf.toString();
1066: }
1067:
1068: public static String replaceTokens(String source, String[] tokens,
1069: String[] values) {
1070: StringBuffer newLine;
1071: String line = source;
1072:
1073: for (int i = 0; i < tokens.length; ++i) {
1074: String token = tokens[i];
1075: int startIndex = line.indexOf(token);
1076: if (startIndex >= 0) {
1077: newLine = new StringBuffer();
1078: int endIndex = startIndex + token.length();
1079: newLine.append(line.substring(0, startIndex));
1080: String newText = values[i];
1081: newLine.append(newText);
1082: newLine.append(line.substring(endIndex, line.length()));
1083: line = newLine.toString();
1084: }
1085: }
1086: return line;
1087: }
1088:
1089: public static File extractFileFromJar(String jarPath,
1090: String filePath) throws IOException, FileNotFoundException {
1091: if (is_windows() && filePath.indexOf('\\') != -1) {
1092: filePath = filePath.replace('\\', '/');
1093: }
1094: System.out.println("Extracting :" + filePath + ":from:"
1095: + jarPath);
1096: JarFile jar = new JarFile(jarPath);
1097: ZipEntry entry = jar.getEntry(filePath);
1098: if (null == entry)
1099: throw new FileNotFoundException("file:" + filePath
1100: + " not in jar file:" + jarPath);
1101: InputStream inputstream = jar.getInputStream(entry);
1102: int leafIdx = filePath.lastIndexOf("/");
1103: if (leafIdx < 0)
1104: leafIdx = 0;
1105: String fileName = filePath.substring(leafIdx + 1, filePath
1106: .length());
1107: int extIdx = fileName.indexOf('.');
1108: String pfx;
1109: String sfx;
1110: if (extIdx > 0) {
1111: pfx = fileName.substring(0, extIdx);
1112: sfx = fileName.substring(extIdx + 1);
1113: } else {
1114: pfx = fileName;
1115: sfx = null;
1116: }
1117: File extract = File.createTempFile(pfx, sfx);
1118: FileOutputStream fileoutputstream = new FileOutputStream(
1119: extract);
1120: int length = 0;
1121: byte buffer[] = new byte[2048];
1122: while (-1 != length) {
1123: length = inputstream.read(buffer);
1124: if (length > 0)
1125: fileoutputstream.write(buffer, 0, length);
1126: }
1127: inputstream.close();
1128: fileoutputstream.close();
1129: jar.close();
1130: return extract;
1131: }
1132:
1133: public static void addFileToJar(String jarPath, String entryName,
1134: File file) throws IOException, FileNotFoundException {
1135: JarFile jarfile = new JarFile(jarPath);
1136: File changedJarFile = new File(jarPath + ".tmp");
1137: JarOutputStream jarOutputStream = new JarOutputStream(
1138: new FileOutputStream(changedJarFile));
1139: FileInputStream fileInputStream = new FileInputStream(file);
1140: ZipEntry entry = new ZipEntry(entryName);
1141: jarOutputStream.putNextEntry(entry);
1142: byte buffer[] = new byte[2048];
1143: int length = 0;
1144: do {
1145: jarOutputStream.write(buffer, 0, length);
1146: length = fileInputStream.read(buffer, 0, buffer.length);
1147: } while (-1 != length);
1148: for (Enumeration jarEntries = jarfile.entries(); jarEntries
1149: .hasMoreElements();) {
1150: JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
1151: if (!jarEntry.getName().equals(entryName)) {
1152: InputStream inputStream = jarfile
1153: .getInputStream(jarEntry);
1154: jarOutputStream.putNextEntry(jarEntry);
1155: int entryLength;
1156: while ((entryLength = inputStream.read(buffer)) != -1)
1157: jarOutputStream.write(buffer, 0, entryLength);
1158: }
1159: }
1160:
1161: fileInputStream.close();
1162: jarOutputStream.close();
1163: deleteFile(jarPath);
1164: moveFile(changedJarFile.getAbsolutePath(), jarPath);
1165: }
1166:
1167: //Unix jdk implementations have a problem with for Runtime.exec args
1168: //that contain spaces. So use this function to escape space charectors
1169: //for such cases
1170: public static String escapeSpaces(String str) {
1171: if (str != null && str.indexOf(" ") != -1) {
1172: // Replacing space charectars with escape sequence for
1173: // unicode space charectar
1174: //str = replaceToken(str, " ", "\u0020");
1175: str.replace(' ', '\u0020');
1176: }
1177: return str;
1178: }
1179:
1180: public static void addJarToClasspath(String jarFileName) {
1181: String classpath = System.getProperty("java.class.path");
1182: /**
1183: * Check if the jar file is already in classpath.
1184: */
1185: if (classpath == null || classpath.indexOf(jarFileName) == -1) {
1186: try {
1187:
1188: /**
1189: * Add the jar file to classpath dynamically using reflection APIs.
1190: */
1191: File jarFile = new File(jarFileName);
1192: URLClassLoader sysloader = (URLClassLoader) ClassLoader
1193: .getSystemClassLoader();
1194: Class sysclass = URLClassLoader.class;
1195: Class[] parameters = new Class[] { URL.class };
1196: Method method = sysclass.getDeclaredMethod("addURL",
1197: parameters);
1198: method.setAccessible(true);
1199: method.invoke(sysloader,
1200: new Object[] { jarFile.toURL() });
1201:
1202: /**
1203: * Update the java.class.path system property to reflect the classpath change.
1204: */
1205: String ps = System.getProperty("path.separator");
1206: System.setProperty("java.class.path", classpath + ps
1207: + jarFileName);
1208:
1209: } catch (Throwable t) {
1210: debug("Unable to add " + jarFileName
1211: + " to classpath dynmaically. " + t.toString());
1212: }
1213: }
1214: }
1215:
1216: }
1217:
1218: class DirectoryFilter implements FilenameFilter {
1219:
1220: public DirectoryFilter() {
1221: }
1222:
1223: public boolean accept(File dir, String name) {
1224: File file = new File(dir, name);
1225: return file.isDirectory();
1226: }
1227:
1228: }
1229:
1230: class ExtensionFilter implements FilenameFilter {
1231:
1232: private String extension;
1233:
1234: public ExtensionFilter(String ext) {
1235: this .extension = "." + ext;
1236: }
1237:
1238: public boolean accept(File dir, String name) {
1239: return name.endsWith(extension);
1240: }
1241:
1242: }
1243:
1244: class CaseInsensitiveComparator implements java.util.Comparator {
1245:
1246: public int compare(Object o1, Object o2) {
1247: String s1 = o1.toString().toUpperCase();
1248: String s2 = o2.toString().toUpperCase();
1249: return s1.compareTo(s2);
1250: }
1251:
1252: }
1253:
1254: class ProcessStreamBuffer implements Runnable {
1255: private InputStream istream;
1256: private InputStreamReader reader;
1257:
1258: public StringBuffer buffer;
1259:
1260: public ProcessStreamBuffer(InputStream istream) {
1261: reader = new InputStreamReader(istream);
1262: buffer = new StringBuffer();
1263: }
1264:
1265: public void run() {
1266: BufferedReader br_in = null;
1267: try {
1268: br_in = new BufferedReader(reader);
1269: String buff = null;
1270: while ((buff = br_in.readLine()) != null) {
1271: buffer.append(buff + "\n");
1272: }
1273: // TODO: verify this
1274: // DANGER: not closing stream as it can be used
1275: // by calling function. Is this a resource leak?
1276: // However closing this will not allow the calling
1277: // application to procee the outputstream if it
1278: // chooses too. But almost all calling opertions do
1279: // not procces the returned output stream
1280: // br_in.close();
1281: } catch (IOException ioe) {
1282: Util.debug("Exception caught ");
1283: ioe.printStackTrace();
1284: } finally {
1285: try {
1286: br_in.close();
1287: } catch (IOException ioe) {
1288: Util.debug("Exception caught ");
1289: ioe.printStackTrace();
1290: }
1291: }
1292: }
1293:
1294: public String output() {
1295: return buffer.toString();
1296: }
1297:
1298: }
|