private static Header parseHeader(Node parent) throws XmlParserException { Header header = new Header(); NodeList nodes = parent.getChildNodes(); for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) { Node node = nodes.item(nodeid); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Element element = (Element) node; try { if (element.getTagName().equals("nrpeaks")) header.setNrPeaks(Integer.parseInt(element.getTextContent())); else if (element.getTagName().equals("date")) header.setDate(element.getTextContent()); else if (element.getTagName().equals("owner")) header.setOwner(element.getTextContent()); else if (element.getTagName().equals("description")) header.setDescription(element.getTextContent()); else if (element.getTagName().equals("sets")) header.addSetInfos(parseSets(element)); else if (element.getTagName().equals("measurements")) header.addMeasurementInfos(parseMeasurements(element)); else if (element.getTagName().equals("annotations")) { Vector<Annotation> annotations = parseAnnotations(element); if (annotations != null) for (Annotation annotation : annotations) header.addAnnotation(annotation); } } catch (Exception e) { throw new XmlParserException( "Invalid value in header (" + element.getTagName() + "): '" + e.getMessage() + "'."); } } return header; }
private synchronized void init() throws SQLException { if (isClosed) return; // do tables exists? Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(TABLE_NAMES_SELECT_STMT); ArrayList<String> missingTables = new ArrayList(TABLES.keySet()); while (rs.next()) { String tableName = rs.getString("name"); missingTables.remove(tableName); } for (String missingTable : missingTables) { try { Statement createStmt = conn.createStatement(); // System.out.println("Adding table "+ missingTable); createStmt.executeUpdate(TABLES.get(missingTable)); createStmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } }
protected void flushSerialBuffer() throws RunnerException, SerialException { // Cleanup the serial buffer try { Serial serialPort = new Serial(); byte[] readBuffer; while (serialPort.available() > 0) { readBuffer = serialPort.readBytes(); try { Thread.sleep(100); } catch (InterruptedException e) { } } serialPort.setDTR(false); serialPort.setRTS(false); try { Thread.sleep(100); } catch (InterruptedException e) { } serialPort.setDTR(true); serialPort.setRTS(true); serialPort.dispose(); } catch (SerialNotFoundException e) { throw e; } catch (Exception e) { e.printStackTrace(); throw new RunnerException(e.getMessage()); } }
private Hashtable<String, String> getJarManifestAttributes(String path) { Hashtable<String, String> h = new Hashtable<String, String>(); JarInputStream jis = null; try { cp.appendln(Color.black, "Looking for " + path); InputStream is = getClass().getResourceAsStream(path); if (is == null) { if (!path.endsWith("/MIRC.jar")) { cp.appendln(Color.red, "...could not find it."); } else { cp.appendln( Color.black, "...could not find it. [OK, this is a " + programName + " installation]"); } return null; } jis = new JarInputStream(is); Manifest manifest = jis.getManifest(); h = getManifestAttributes(manifest); } catch (Exception ex) { ex.printStackTrace(); } if (jis != null) { try { jis.close(); } catch (Exception ignore) { } } return h; }
public static boolean download( URL url, String file, int prefix, int totalFilesize, IProgressUpdater updater) { File fFile = new File(new File(file).getParentFile().getPath()); if (!fFile.exists()) fFile.mkdirs(); boolean downloaded = true; BufferedInputStream in = null; FileOutputStream out = null; BufferedOutputStream bout = null; try { int count; int totalCount = 0; byte data[] = new byte[BUFFER]; in = new BufferedInputStream(url.openStream()); out = new FileOutputStream(file); bout = new BufferedOutputStream(out); while ((count = in.read(data, 0, BUFFER)) != -1) { bout.write(data, 0, count); totalCount += count; if (updater != null) updater.update(prefix + totalCount, totalFilesize); } } catch (Exception e) { e.printStackTrace(); Utils.logger.log(Level.SEVERE, "Download error!"); downloaded = false; } finally { try { close(in); close(bout); close(out); } catch (Exception e) { e.printStackTrace(); } } return downloaded; }
/** * main method * * <p>This uses the system properties: * * <ul> * <li><code>rjava.path</code> : path of the rJava package * <li><code>rjava.lib</code> : lib sub directory of the rJava package * <li><code>main.class</code> : main class to "boot", assumes Main if not specified * <li><code>rjava.class.path</code> : set of paths to populate the initiate the class path * </ul> * * <p>and boots the "main" method of the specified <code>main.class</code>, passing the args down * to the booted class * * <p>This makes sure R and rJava are known by the class loader */ public static void main(String[] args) { String rJavaPath = System.getProperty("rjava.path"); if (rJavaPath == null) { System.err.println("ERROR: rjava.path is not set"); System.exit(2); } String rJavaLib = System.getProperty("rjava.lib"); if (rJavaLib == null) { // it is not really used so far, just for rJava.so, so we can guess rJavaLib = rJavaPath + File.separator + "libs"; } RJavaClassLoader cl = new RJavaClassLoader(u2w(rJavaPath), u2w(rJavaLib)); String mainClass = System.getProperty("main.class"); if (mainClass == null || mainClass.length() < 1) { System.err.println("WARNING: main.class not specified, assuming 'Main'"); mainClass = "Main"; } String classPath = System.getProperty("rjava.class.path"); if (classPath != null) { StringTokenizer st = new StringTokenizer(classPath, File.pathSeparator); while (st.hasMoreTokens()) { String dirname = u2w(st.nextToken()); cl.addClassPath(dirname); } } try { cl.bootClass(mainClass, "main", args); } catch (Exception ex) { System.err.println("ERROR: while running main method: " + ex); ex.printStackTrace(); } }
public static JSONObject readJSONUrlFile(String url) { try { return readJSONUrlFile(new URL(url)); } catch (Exception e) { e.printStackTrace(); return null; } }
public synchronized void close() { if (isClosed) return; try { if (conn != null) conn.close(); isClosed = true; } catch (Exception e) { e.printStackTrace(); } }
public static JSONObject readJSONUrlFile(URL url) { try { JSONParser tmp = new JSONParser(); Object o = tmp.parse(new InputStreamReader(url.openStream())); if (!(o instanceof JSONObject)) return null; else return (JSONObject) o; } catch (Exception e) { e.printStackTrace(); return null; } }
public static JSONObject readJSONFile(String filename) { try { JSONParser tmp = new JSONParser(); Object o = tmp.parse(new InputStreamReader(new FileInputStream(filename))); if (!(o instanceof JSONObject)) return null; else return (JSONObject) o; } catch (Exception e) { e.printStackTrace(); return null; } }
/** setVol(float) adjusts overall volume. Checks for min/max limits to avoid crashes. */ public void setVol(float newvol) { if (newvol > -40.0f && newvol < 6.020f) { try { volCtrl.setValue(newvol); } catch (Exception e) { PApplet.println(e.getMessage()); } } else { PApplet.println( "Error - volume '" + newvol + "' is out of range. Must be between -40.0f and 6.020f!"); } }
public void writeIdToVertexMap(String filePath) { try { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath))); for (Entry<Integer, String> entry : nodes.entrySet()) { bw.write(entry.getKey() + " " + entry.getValue() + "\n"); } bw.close(); } catch (Exception ex) { ex.printStackTrace(); System.exit(-1); } }
/** * setPanning(float) takes a float from -1.0f to 1.0f to pan the overall audio output across the * stereo spectrum. The centre-point is 0. */ public void setPanning(float panval) { if (panval > -1.0f && panval < 1.0f) { try { FloatControl panctrl = (FloatControl) player.output_line.getControl(FloatControl.Type.BALANCE); panctrl.setValue(panval); panning = panval; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public static void close(Object o) { try { if (o == null) return; if (o instanceof InputStream) { ((InputStream) o).close(); } else if (o instanceof OutputStream) { ((OutputStream) o).flush(); ((OutputStream) o).close(); } } catch (Exception e) { e.printStackTrace(); } }
/** * Refresh the repository from the URL. * * @throws Exception */ public boolean refresh() { exception = null; try { resources.clear(); parseDocument(url); visited = null; return true; } catch (Exception e) { e.printStackTrace(); exception = e; } return false; }
public static String loadStringFromFile(String filename) { String line = ""; File file = new File(filename); if (!file.exists()) return line; try { BufferedReader reader = new BufferedReader(new FileReader(file)); line = reader.readLine(); reader.close(); } catch (Exception e) { e.printStackTrace(); } return line; }
public static void main(String[] args) { try { ZipFile zipFile = new ZipFile(testDirName + zipFileName); ZipEntry ze = zipFile.getEntry(zipEntryName); byte[] digest1 = getZipDigest(zipFile, ze, true); System.out.println("Digest1: " + Base64Util.encode(digest1)); byte[] digest2 = getZipDigest(zipFile, ze, false); System.out.println("Digest2: " + Base64Util.encode(digest2)); } catch (Exception ex) { System.out.println("Error: " + ex.toString()); ex.printStackTrace(System.out); } }
// Take a tree of files starting in a directory in a zip file // and copy them to a disk directory, recreating the tree. private int unpackZipFile( File inZipFile, String directory, String parent, boolean suppressFirstPathElement) { int count = 0; if (!inZipFile.exists()) return count; parent = parent.trim(); if (!parent.endsWith(File.separator)) parent += File.separator; if (!directory.endsWith(File.separator)) directory += File.separator; File outFile = null; try { ZipFile zipFile = new ZipFile(inZipFile); Enumeration zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipEntries.nextElement(); String name = entry.getName().replace('/', File.separatorChar); if (name.startsWith(directory)) { if (suppressFirstPathElement) name = name.substring(directory.length()); outFile = new File(parent + name); // Create the directory, just in case if (name.indexOf(File.separatorChar) >= 0) { String p = name.substring(0, name.lastIndexOf(File.separatorChar) + 1); File dirFile = new File(parent + p); dirFile.mkdirs(); } if (!entry.isDirectory()) { System.out.println("Installing " + outFile); // Copy the file BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile)); BufferedInputStream in = new BufferedInputStream(zipFile.getInputStream(entry)); int size = 1024; int n = 0; byte[] b = new byte[size]; while ((n = in.read(b, 0, size)) != -1) out.write(b, 0, n); in.close(); out.flush(); out.close(); // Count the file count++; } } } zipFile.close(); } catch (Exception e) { System.err.println("...an error occured while installing " + outFile); e.printStackTrace(); System.err.println("Error copying " + outFile.getName() + "\n" + e.getMessage()); return -count; } System.out.println(count + " files were installed."); return count; }
/** * a Constructor, usually called in the setup() method in your sketch to initialize and start the * library. * * @example portaTest * @param p */ public PortaMod(PApplet p) { this.p = p; IBXM.SetMC(this); try { noteArrived = p.getClass().getMethod("grabNewdata", new Class[] {PortaMod.class}); } catch (Exception e) { PApplet.println(e.getMessage()); } try { noteArrivedB = p.getClass().getMethod("grabNewdataB", new Class[] {PortaMod.class}); } catch (Exception e) { PApplet.println(e.getMessage()); } }
/** * We have a referral to another repository. Just create another parser and read it inline. * * @param parser */ void referral(XmlPullParser parser) { // TODO handle depth! try { parser.require(XmlPullParser.START_TAG, null, "referral"); // String depth = parser.getAttributeValue(null, "depth"); String path = parser.getAttributeValue(null, "url"); URL url = new URL(this.url, path); parseDocument(url); parser.next(); parser.require(XmlPullParser.END_TAG, null, "referral"); } catch (Exception e) { e.printStackTrace(); } }
/** * getSeek() returns the current position of the song in milliseconds as an int. * * @return songSeek */ public int getSeek() { if (playing) { try { songPosition = player.play_position / 48; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return (int) songPosition; } else { System.out.println("Couldn't get song position"); return 0; } }
public boolean process(String[] args, BytecodeReader reader, JavaParser parser) { program.initBytecodeReader(reader); program.initJavaParser(parser); initOptions(); processArgs(args); Collection files = program.options().files(); if (program.options().hasOption("-version")) { printVersion(); return false; } if (program.options().hasOption("-help") || files.isEmpty()) { printUsage(); return false; } try { for (Iterator iter = files.iterator(); iter.hasNext(); ) { String name = (String) iter.next(); if (!new File(name).exists()) System.err.println("WARNING: file \"" + name + "\" does not exist"); program.addSourceFile(name); } for (Iterator iter = program.compilationUnitIterator(); iter.hasNext(); ) { CompilationUnit unit = (CompilationUnit) iter.next(); if (unit.fromSource()) { Collection errors = unit.parseErrors(); Collection warnings = new LinkedList(); // compute static semantic errors when there are no parse errors or // the recover from parse errors option is specified if (errors.isEmpty() || program.options().hasOption("-recover")) unit.errorCheck(errors, warnings); if (!errors.isEmpty()) { processErrors(errors, unit); return false; } else { if (!warnings.isEmpty()) processWarnings(warnings, unit); processNoErrors(unit); } } } } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } return true; }
private boolean startLauncher(File dir) { try { Runtime rt = Runtime.getRuntime(); ArrayList<String> command = new ArrayList<String>(); command.add("java"); command.add("-jar"); command.add("Launcher.jar"); String[] cmdarray = command.toArray(new String[command.size()]); Process proc = rt.exec(cmdarray, null, dir); return true; } catch (Exception ex) { System.err.println("Unable to start the Launcher program.\n" + ex.getMessage()); return false; } }
void displayCurrentpattern() { for (int thisrow = 0; thisrow < currentpatternrows[0].size(); thisrow++) { for (int channelcount = 0; channelcount < player.get_num_channels(); channelcount++) { try { CurrentPattern tempdata = (CurrentPattern) currentpatternrows[channelcount].get( thisrow); // channelcount works, thisrow is often out of bounds } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
/** * Get an input stream for a resource contained in the jar file * * @param name file name of the resource within the jar file * @return an input stream representing the resouce if it exists or null */ public InputStream getResourceAsStream(String name) { if (zfile == null || hasChanged()) { update(); } try { if (zfile == null) return null; ZipEntry e = zfile.getEntry(name); if (e != null) return zfile.getInputStream(e); } catch (Exception e) { if (verbose) System.err.println("RJavaClassLoader$UnixJarFile: exception: " + e.getMessage()); } return null; }
private void updateLinuxServiceInstaller() { try { File dir = new File(directory, "CTP"); if (suppressFirstPathElement) dir = dir.getParentFile(); Properties props = new Properties(); String ctpHome = dir.getAbsolutePath(); cp.appendln(Color.black, "...CTP_HOME: " + ctpHome); ctpHome = ctpHome.replaceAll("\\\\", "\\\\\\\\"); props.put("CTP_HOME", ctpHome); File javaHome = new File(System.getProperty("java.home")); String javaBin = (new File(javaHome, "bin")).getAbsolutePath(); cp.appendln(Color.black, "...JAVA_BIN: " + javaBin); javaBin = javaBin.replaceAll("\\\\", "\\\\\\\\"); props.put("JAVA_BIN", javaBin); File linux = new File(dir, "linux"); File install = new File(linux, "ctpService-ubuntu.sh"); cp.appendln(Color.black, "Linux service installer:"); cp.appendln(Color.black, "...file: " + install.getAbsolutePath()); String bat = getFileText(install); bat = replace(bat, props); // do the substitutions bat = bat.replace("\r", ""); setFileText(install, bat); // If this is an ISN installation, put the script in the correct place. String osName = System.getProperty("os.name").toLowerCase(); if (programName.equals("ISN") && !osName.contains("windows")) { install = new File(linux, "ctpService-red.sh"); cp.appendln(Color.black, "ISN service installer:"); cp.appendln(Color.black, "...file: " + install.getAbsolutePath()); bat = getFileText(install); bat = replace(bat, props); // do the substitutions bat = bat.replace("\r", ""); File initDir = new File("/etc/init.d"); File initFile = new File(initDir, "ctpService"); if (initDir.exists()) { setOwnership(initDir, "edge", "edge"); setFileText(initFile, bat); initFile.setReadable(true, false); // everybody can read //Java 1.6 initFile.setWritable(true); // only the owner can write //Java 1.6 initFile.setExecutable(true, false); // everybody can execute //Java 1.6 } } } catch (Exception ex) { ex.printStackTrace(); System.err.println("Unable to update the Linux service ctpService.sh file"); } }
public static void loadAnimations() { System.out.println("Testing"); int i = 0; try { GZIPInputStream gzipDataFile = new GZIPInputStream(new FileInputStream(getDir() + "frames.dat")); DataInputStream dataFile = new DataInputStream(gzipDataFile); GZIPInputStream gzipIndexFile = new GZIPInputStream(new FileInputStream(getDir() + "frames.idx")); DataInputStream indexFile = new DataInputStream(gzipIndexFile); int length = indexFile.readInt(); for (i = 0; i < length; i++) { int id = indexFile.readInt(); int invlength = indexFile.readInt(); byte[] data = new byte[invlength]; dataFile.readFully(data); allFrames[id] = data; } indexFile.close(); dataFile.close(); } catch (Exception e) { System.out.println("Error: " + i); e.printStackTrace(); } try { GZIPInputStream gzipDataFile = new GZIPInputStream(new FileInputStream(getDir() + "skinlist.dat")); DataInputStream dataFile = new DataInputStream(gzipDataFile); GZIPInputStream gzipIndexFile = new GZIPInputStream(new FileInputStream(getDir() + "skinlist.idx")); DataInputStream indexFile = new DataInputStream(gzipIndexFile); int length = indexFile.readInt(); for (i = 0; i < length; i++) { int id = indexFile.readInt(); int invlength = indexFile.readInt(); byte[] data = new byte[invlength]; dataFile.readFully(data); allSkinlist[id] = data; } indexFile.close(); dataFile.close(); } catch (Exception e) { System.out.println("Error: " + i); e.printStackTrace(); } }
/** Mute audio (playback continues) */ public void mute() { if (!muted) { try { muteCtrl.setValue(true); muted = true; } catch (Exception e) { PApplet.println(e.getMessage()); } } else { try { muteCtrl.setValue(false); muted = false; } catch (Exception e) { PApplet.println(e.getMessage()); } } }
public static boolean saveStringToFile(String filename, String data) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(filename)); writer.write(data); writer.close(); } catch (Exception e) { e.printStackTrace(); if (writer != null) try { writer.close(); } catch (Exception ee) { } return false; } return true; }
public void doit(String archiveFilename) { f.clear(); try { tar = new TarInputStream(new GZIPInputStream(new FileInputStream(archiveFilename))); while ((current = tar.getNextEntry()) != null) { System.err.println("ok:" + current.getName()); long s = current.getSize(); if (!current.isDirectory()) { // System.err.println(current.getFile()); f.prepareForBulkInsert(tar, current.getName()); } } } catch (Exception e) { e.printStackTrace(); } f.flushFiles(); }