/** * Starts a native process on the server * * @param command the command to start the process * @param dir the dir in which the process starts */ static String startProcess(String command, String dir) throws IOException { StringBuffer ret = new StringBuffer(); String[] comm = new String[3]; comm[0] = COMMAND_INTERPRETER[0]; comm[1] = COMMAND_INTERPRETER[1]; comm[2] = command; long start = System.currentTimeMillis(); try { // Start process Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir)); // Get input and error streams BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream()); BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream()); boolean end = false; while (!end) { int c = 0; while ((ls_err.available() > 0) && (++c <= 1000)) { ret.append(conv2Html(ls_err.read())); } c = 0; while ((ls_in.available() > 0) && (++c <= 1000)) { ret.append(conv2Html(ls_in.read())); } try { ls_proc.exitValue(); // if the process has not finished, an exception is thrown // else while (ls_err.available() > 0) ret.append(conv2Html(ls_err.read())); while (ls_in.available() > 0) ret.append(conv2Html(ls_in.read())); end = true; } catch (IllegalThreadStateException ex) { // Process is running } // The process is not allowed to run longer than given time. if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) { ls_proc.destroy(); end = true; ret.append("!!!! Process has timed out, destroyed !!!!!"); } try { Thread.sleep(50); } catch (InterruptedException ie) { } } } catch (IOException e) { ret.append("Error: " + e); } return ret.toString(); }
public boolean shutdown(int port, boolean ssl) { try { String protocol = "http" + (ssl ? "s" : ""); URL url = new URL(protocol, "127.0.0.1", port, "shutdown"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("servicemanager", "shutdown"); conn.connect(); StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); int n; char[] cbuf = new char[1024]; while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n); br.close(); String message = sb.toString().replace("<br>", "\n"); if (message.contains("Goodbye")) { cp.appendln("Shutting down the server:"); String[] lines = message.split("\n"); for (String line : lines) { cp.append("..."); cp.appendln(line); } return true; } } catch (Exception ex) { } cp.appendln("Unable to shutdown CTP"); return false; }
/** Converts a normal string to a html conform string */ public static String conv2Html(String st) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < st.length(); i++) { buf.append(conv2Html(st.charAt(i))); } return buf.toString(); }
public static void main(String[] args) throws Exception { Reader trainingFile = null; // Process arguments int restArgs = commandOptions.processOptions(args); // Check arguments if (restArgs != args.length) { commandOptions.printUsage(true); throw new IllegalArgumentException("Unexpected arg " + args[restArgs]); } if (trainFileOption.value == null) { commandOptions.printUsage(true); throw new IllegalArgumentException("Expected --train-file FILE"); } if (modelFileOption.value == null) { commandOptions.printUsage(true); throw new IllegalArgumentException("Expected --model-file FILE"); } // Get the CRF structure specification. ZipFile zipFile = new ZipFile(modelFileOption.value); ZipEntry zipEntry = zipFile.getEntry("crf-info.xml"); CRFInfo crfInfo = new CRFInfo(zipFile.getInputStream(zipEntry)); StringBuffer crfInfoBuffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry))); String line; while ((line = reader.readLine()) != null) { crfInfoBuffer.append(line).append('\n'); } reader.close(); // Create the CRF, and train it. CRF4 crf = createCRF(trainFileOption.value, crfInfo); // Create a new zip file for our output. This will overwrite // the file we used for input. ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(modelFileOption.value)); // Copy the CRF info xml to the output zip file. zos.putNextEntry(new ZipEntry("crf-info.xml")); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zos)); writer.write(crfInfoBuffer.toString()); writer.flush(); zos.closeEntry(); // Save the CRF classifier model to the output zip file. zos.putNextEntry(new ZipEntry("crf-model.ser")); ObjectOutputStream oos = new ObjectOutputStream(zos); oos.writeObject(crf); oos.flush(); zos.closeEntry(); zos.close(); }
private String replace(String string, Properties table) { try { Pattern pattern = Pattern.compile("\\$\\{\\w+\\}"); Matcher matcher = pattern.matcher(string); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String group = matcher.group(); String key = group.substring(2, group.length() - 1).trim(); String repl = table.getProperty(key); if (repl == null) repl = matcher.quoteReplacement(group); matcher.appendReplacement(sb, repl); } matcher.appendTail(sb); return sb.toString(); } catch (Exception ex) { return string; } }
/** * Dumps a zip entry into a string. * * @param ze a ZipEntry */ private String dumpZipEntry(ZipEntry ze) { StringBuffer sb = new StringBuffer(); if (ze.isDirectory()) { sb.append("d "); } else { sb.append("f "); } if (ze.getMethod() == ZipEntry.STORED) { sb.append("stored "); } else { sb.append("defalted "); } sb.append(ze.getName()); sb.append("\t"); sb.append("" + ze.getSize()); if (ze.getMethod() == ZipEntry.DEFLATED) { sb.append("/" + ze.getCompressedSize()); } return (sb.toString()); }
private byte[] readMultiPartChunk(ServletInputStream requestStream, String contentType) throws IOException { // fast forward stream past multi-part header int boundaryOff = contentType.indexOf("boundary="); // $NON-NLS-1$ String boundary = contentType.substring(boundaryOff + 9); BufferedReader reader = new BufferedReader(new InputStreamReader(requestStream, "ISO-8859-1")); // $NON-NLS-1$ StringBuffer out = new StringBuffer(); // skip headers up to the first blank line String line = reader.readLine(); while (line != null && line.length() > 0) line = reader.readLine(); // now process the file char[] buf = new char[1000]; int read; while ((read = reader.read(buf)) > 0) { out.append(buf, 0, read); } // remove the boundary from the output (end of input is \r\n--<boundary>--\r\n) out.setLength(out.length() - (boundary.length() + 8)); return out.toString().getBytes("ISO-8859-1"); // $NON-NLS-1$ }
/** * Converts a dir string to a linked dir string * * @param dir the directory string (e.g. /usr/local/httpd) * @param browserLink web-path to Browser.jsp */ public static String dir2linkdir(String dir, String browserLink, int sortMode) { File f = new File(dir); StringBuffer buf = new StringBuffer(); while (f.getParentFile() != null) { if (f.canRead()) { String encPath = URLEncoder.encode(f.getAbsolutePath()); buf.insert( 0, "<a href=\"" + browserLink + "?sort=" + sortMode + "&dir=" + encPath + "\">" + conv2Html(f.getName()) + File.separator + "</a>"); } else buf.insert(0, conv2Html(f.getName()) + File.separator); f = f.getParentFile(); } if (f.canRead()) { String encPath = URLEncoder.encode(f.getAbsolutePath()); buf.insert( 0, "<a href=\"" + browserLink + "?sort=" + sortMode + "&dir=" + encPath + "\">" + conv2Html(f.getAbsolutePath()) + "</a>"); } else buf.insert(0, f.getAbsolutePath()); return buf.toString(); }
private static String toString(Node node) { StringBuffer sb = new StringBuffer(); renderNode(sb, node); return sb.toString(); }
/** * Parse an old style OBR repository. * * <p><dtd-version>1.0</dtd-version> <repository> <name>Oscar Bundle Repository</name> * <url>http://oscar-osgi.sourceforge.net/</url> <date>Fri May 07 16:45:07 CEST 2004</date> * <extern-repositories> * <!-- * Stefano Lenzi ([email protected]) --> * <url>http://domoware.isti.cnr.it/osgi-obr/niche-osgi-obr.xml</url> * <!--Manuel Palencia ([email protected]) --> * <!-- * <url>http://jmood.forge.os4os.org/repository.xml</url> --> * <!-- Enrique * Rodriguez ([email protected]) --> * <url>http://update.cainenable.org/repository.xml</url> </extern-repositories> </repository> * <bundle> <bundle-name>Bundle Repository</bundle-name> <bundle-description> A bundle repository * service for Oscar. </bundle-description> <bundle-updatelocation> * http://oscar-osgi.sf.net/repo/bundlerepository/bundlerepository.jar </bundle-updatelocation> * <bundle-sourceurl> http://oscar-osgi.sf.net/repo/bundlerepository/bundlerepository-src.jar * </bundle-sourceurl> <bundle-version>1.1.3</bundle-version> <bundle-docurl> * http://oscar-osgi.sf.net/repo/bundlerepository/ </bundle-docurl> * <bundle-category>General</bundle-category> <import-package package="org.osgi.framework"/> * <export-package package="org.ungoverned.osgi.service.bundlerepository" * specification-version="1.1.0"/> </bundle> * */ private void parseOscar(XmlPullParser parser) throws Exception { parser.require(XmlPullParser.START_TAG, null, "bundles"); while (true) { int event = parser.next(); // Error .. if (event == XmlPullParser.TEXT) event = parser.next(); if (event != XmlPullParser.START_TAG) break; ResourceImpl resource = new ResourceImpl(this); if (parser.getName().equals("bundle")) { while (parser.nextTag() == XmlPullParser.START_TAG) { String key = parser.getName(); if (key.equals("import-package")) { RequirementImpl requirement = new RequirementImpl("package"); requirement.setOptional(false); requirement.setMultiple(false); String p = parser.getAttributeValue(null, "package"); StringBuffer sb = new StringBuffer(); sb.append("(&(package="); sb.append(p); sb.append(")"); String version = parser.getAttributeValue(null, "specification-version"); VersionRange v = new VersionRange("0"); if (version != null) { sb.append("(version="); sb.append(v = new VersionRange(version)); sb.append(")"); } sb.append(")"); requirement.setFilter(sb.toString()); requirement.setComment("Import-Package: " + p + ";" + v); resource.addRequirement(requirement); parser.nextTag(); } else if (key.equals("export-package")) { CapabilityImpl capability = new CapabilityImpl("package"); capability.addProperty("package", parser.getAttributeValue(null, "package")); String version = parser.getAttributeValue(null, "specification-version"); if (version != null) { capability.addProperty("version", new VersionRange(version)); } resource.addCapability(capability); parser.nextTag(); } else { String value = parser.nextText().trim(); if (key.equals("bundle-sourceurl")) resource.setSource(new URL(value)); else if (key.equals("bundle-docurl")) resource.setDocumentation(new URL(value)); else if (key.equals("bundle-updatelocation")) resource.setURL(new URL(value)); else if (key.equals("bundle-description")) resource.setDescription(value); else if (key.equals("bundle-category")) resource.addCategory(value); else if (key.equals("bundle-name")) { resource.setName(value); resource.setPresentationName(value); } else if (key.equals("bundle-version")) resource.setVersion(new VersionRange(value)); else { resource.put(key, value); } } } resources.add(resource); parser.require(XmlPullParser.END_TAG, null, "bundle"); } else if (parser.getName().equals("repository")) { parser.require(XmlPullParser.START_TAG, null, "repository"); while (parser.nextTag() == XmlPullParser.START_TAG) { String tag = parser.getName(); if (tag.equals("name")) { String name = parser.nextText(); if (this.name == null) this.name = name.trim(); } else if (tag.equals("url")) parser.nextText().trim(); else if (tag.equals("date")) parser.nextText().trim(); else if (tag.equals("extern-repositories")) { parser.require(XmlPullParser.START_TAG, null, "extern-repositories"); while (parser.nextTag() == XmlPullParser.START_TAG) { if (parser.getName().equals("url")) parseDocument(new URL(parser.nextText().trim())); else throw new IllegalArgumentException( "Invalid tag in repository while parsing extern repositories: " + url + " " + parser.getName()); } parser.require(XmlPullParser.END_TAG, null, "extern-repositories"); } else throw new IllegalArgumentException( "Invalid tag in repository: " + url + " " + parser.getName()); } parser.require(XmlPullParser.END_TAG, null, "repository"); } else if (parser.getName().equals("dtd-version")) { parser.nextText(); } else throw new IllegalArgumentException( "Invalid tag in repository: " + url + " " + parser.getName()); } parser.require(XmlPullParser.END_TAG, null, "bundles"); }
// =============================================================================