@Override public void render(Parameters blockParameters, Writer w, RenderHints hints) throws FrameworkException { log.debug("Error rendering " + blockParameters); switch (getType()) { case BODY: try { decorateIntro(hints, w, "error"); w.write("<h1>" + error.status); w.write(": "); CharTransformer escape = new Xml(Xml.ESCAPE); w.write(escape.transform(error.exception.getMessage())); w.write(" "); w.write(escape.transform(url)); w.write("</h1>"); w.write("<pre>"); HttpServletRequest request = blockParameters.get(Parameter.REQUEST); error.getErrorReport(w, request, escape); w.write("</pre>"); decorateOutro(hints, w); } catch (IOException eio) { throw new FrameworkException(eio.getMessage(), eio); } break; default: } }
public String fetchCleanupReviewDirLinkGenXml() { String s = null; try { s = // Organize and Clean Up Section "<ReviewDirGenerator class='operator.ReviewDirGenerator' destination.dir='" + outputDirectory.getCanonicalPath() + "' sample='" + outputDirectory.getName() + "' submitter='" + submitter + "' analysis.type='" + analysisType + "'> \n" + " <finalVariants /> \n" + " <ViewerCSV /> \n" + " <InstanceLog class='buffer.InstanceLogFile' /> \n" + " <finalBAM /> \n" + " <QCOutputFile /> \n" + " <bedForVars /> \n" + "</ReviewDirGenerator> \n\n"; } catch (IOException e) { e.printStackTrace(); Misc.printErrAndExit("\nError fetching clean up and review dir links.\n"); } return s; }
/** * Performs an XPATH lookup in an xml document whose filename is specified by the first parameter * (assumed to be in the auxiliary subdirectory) The XPATH expression is supplied as the second * string parameter The return value is of type string e.g. this is currently used primarily for * looking up the Company Prefix Index for encoding a GS1 Company Prefix into a 64-bit EPC tag */ private String xpathlookup(String xml, String expression) { try { // Parse the XML as a W3C document. DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new File(xmldir + File.separator + "auxiliary" + File.separator + xml)); XPath xpath = XPathFactory.newInstance().newXPath(); String rv = (String) xpath.evaluate(expression, document, XPathConstants.STRING); return rv; } catch (ParserConfigurationException e) { System.err.println("ParserConfigurationException caught..."); e.printStackTrace(); return null; } catch (XPathExpressionException e) { System.err.println("XPathExpressionException caught..."); e.printStackTrace(); return null; } catch (SAXException e) { System.err.println("SAXException caught..."); e.printStackTrace(); return null; } catch (IOException e) { System.err.println("IOException caught..."); e.printStackTrace(); return null; } }
/** * Get the noun and verb <roots> (i.e. 'the highest' synsets in WordNet) from the particular * 'icfile' (Information Content) that you are applying. Store a noun <root>: a synset offset * number of type Integer in nounroots: an ArrayList<Integer> defined in the constructor of this * class. Store a verb <root>: a synset offset number of type Integer in verbroots: an * ArrayList<Integer> defined in the constructor of this class. * * <p>An example line in an 'icfile', showing a noun <root>: 1740n 128767 ROOT */ private void getRoots() { Pattern pn = Pattern.compile("[0-9]+n [0-9]+ ROOT"); // find noun <root> Pattern pv = Pattern.compile("[0-9]+v [0-9]+ ROOT"); // find verb <root> Matcher m = null; String root = ""; try { BufferedReader in = new BufferedReader(new FileReader(icfile)); String line; while ((line = in.readLine()) != null) { // nouns m = pn.matcher(line); if (m.matches()) { root = (line.split("\\s")[0]).split("n")[0]; // !!! double split !!! nounroots.add(Integer.parseInt(root)); } // verbs m = pv.matcher(line); if (m.matches()) { root = (line.split("\\s")[0]).split("v")[0]; // !!! double split !!! verbroots.add(Integer.parseInt(root)); } } in.close(); } catch (IOException e) { e.printStackTrace(); } }
/** * Checks if a given file exists and, if not, create it by copying a default template from * resources; used to create default conf files. * * @param file The path of the file that needs to exist * @param template The path of the template for the file */ public static void ensureFileExists(final String file, final String template) { if (LAUNCHED_FROM_JAR && !Files.exists(Paths.get(file))) { if (Debug.on) printDebug("[Meta] " + file + " does not exist: creating a default one."); InputStream stream = Meta.class.getResourceAsStream(template); if (stream == null) { printDebug( "[ WARNING ] template for " + template + " not found. Won't create a default " + file + "."); } else { int readBytes; byte[] buffer = new byte[4096]; try (OutputStream outStream = new FileOutputStream(new File(file))) { while ((readBytes = stream.read(buffer)) > 0) { outStream.write(buffer, 0, readBytes); } if (Debug.on) printDebug("[Meta] created default file " + file + " from " + template + "."); } catch (IOException e) { e.printStackTrace(); } finally { try { stream.close(); } catch (IOException ignore) { } } } } else { if (Meta.LAUNCHED_FROM_JAR && Debug.on) printDebug("[Meta] file exists: " + file + "."); } }
/** Returns true if this VM has acquired the right to run this TestTask */ private static DUnitRun getDUnitRun() { if (dunitRun != null) { System.out.println("BBB dunitRun not null returning"); return dunitRun; } try { SwarmBB.getBB().getSharedLock().lock(); Integer runId = (Integer) SwarmBB.getBB().getSharedMap().get(SwarmBB.RUN_ID); System.out.println("BBB runID=" + runId); if (runId != null) { dunitRun = Swarm.getDUnitRun(runId); System.out.println("BBB lookedUp RUN:" + dunitRun); } else { dunitRun = Swarm.generateNewDUnitRun(); System.out.println( "BBB GENNED UP A RUN:" + dunitRun + " mapping to id:" + dunitRun.getId()); SwarmBB.getBB().getSharedMap().put(SwarmBB.RUN_ID, dunitRun.getId()); } } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { SwarmBB.getBB().getSharedLock().unlock(); } return dunitRun; }
private void dumpFailedLaunchInfo(Process process) { try { dumpStream(process.getErrorStream()); dumpStream(process.getInputStream()); } catch (IOException e) { MessageOutput.println("Unable to display process output:", e.getMessage()); } }
static void searchFiles() { try { for (int i = 0; i < options.filenames.length; i++) { Scanner input = new Scanner(new File(options.filenames[i])); scanfile(input, options.filenames[i], options.pattern); input.close(); } } catch (IOException e) { messages.warn(e.getMessage()); messages.exit_status = messages.EXIT_NOMATCH; } }
/** The main program for ReTrace. */ public static void main(String[] args) { if (args.length < 1) { System.err.println( "Usage: java proguard.ReTrace [-verbose] <mapping_file> [<stacktrace_file>]"); System.exit(-1); } String regularExpresssion = STACK_TRACE_EXPRESSION; boolean verbose = false; int argumentIndex = 0; while (argumentIndex < args.length) { String arg = args[argumentIndex]; if (arg.equals(REGEX_OPTION)) { regularExpresssion = args[++argumentIndex]; } else if (arg.equals(VERBOSE_OPTION)) { verbose = true; } else { break; } argumentIndex++; } if (argumentIndex >= args.length) { System.err.println( "Usage: java proguard.ReTrace [-regex <regex>] [-verbose] <mapping_file> [<stacktrace_file>]"); System.exit(-1); } File mappingFile = new File(args[argumentIndex++]); File stackTraceFile = argumentIndex < args.length ? new File(args[argumentIndex]) : null; ReTrace reTrace = new ReTrace(regularExpresssion, verbose, mappingFile, stackTraceFile); try { // Execute ReTrace with its given settings. reTrace.execute(); } catch (IOException ex) { if (verbose) { // Print a verbose stack trace. ex.printStackTrace(); } else { // Print just the stack trace message. System.err.println("Error: " + ex.getMessage()); } System.exit(1); } System.exit(0); }
/* attach to running target vm */ private VirtualMachine attachTarget() { AttachingConnector attacher = (AttachingConnector) connector; try { return attacher.attach(connectorArgs); } catch (IOException ioe) { ioe.printStackTrace(); MessageOutput.fatalError("Unable to attach to target VM."); } catch (IllegalConnectorArgumentsException icae) { icae.printStackTrace(); MessageOutput.fatalError("Internal debugger error."); } return null; // Shuts up the compiler }
public static void main(String[] args) { File f = new File(args[0]); try { Parser<GeneOrthologyEntry> entries = new Parser<GeneOrthologyEntry>(f, new GeneOrthologyEntry.ParsingMapper()); while (entries.hasNext()) { GeneOrthologyEntry entry = entries.next(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public Class<?> findClass(String s) { try { byte[] bytes = loadClassData(s); return defineClass(s, bytes, 0, bytes.length); } catch (IOException ioe) { try { return super.loadClass(s); } catch (ClassNotFoundException ignore) { } ioe.printStackTrace(System.out); return null; } }
// Writes the program to a source file, compiles it, and runs it. private void compileAndRun(String fileName, String code) { // Exceptions here can pick and choose what font to use, as needed. // Exceptions thrown by the program, that cause the Playground to be unstable, should be in // blue. println("Deleting old temp files...", progErr); new File(fileName + ".java").delete(); new File(fileName + ".class").delete(); println("Creating source file...", progErr); file = new File(fileName + ".java"); println("Writing code to source file...", progErr); try { new FileWriter(file).append(code).close(); } catch (IOException i) { println("Had an IO Exception when trying to write the code. Stack trace:", error); i.printStackTrace(); return; // Exit on error } println("Compiling code...", progErr); // This should only ever be called if the JDK isn't installed. How you'd get here, I don't // know. if (compiler == null) { println("Fatal Error: JDK not installed. Go to java.sun.com and install.", error); return; } // Tries to compile. Success code is 0, so if something goes wrong, do stuff. int result = compiler.run( null, null, null, file .getAbsolutePath()); // Possibly add a new outputstream to parse through the // compiler errors if (result != 0) { displayLog(); println("Failed to compile.", error); return; // Return on error } println("Code compiled with 0 errors.", progErr); println("Attempting to run code...", progErr); run(fileName); }
public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(args[0])); int tIndex = 0; int pIndex = 0; // This will probably change soon (name and implementation) NgramParser tnp = new NgramParser(args[1]); ArrayList<String> triplet = tnp.getTriplet(); ArrayList<String> polarity = tnp.getPolarity(); FileWriter sw = new FileWriter(args[2]); String line = null; while (((line = br.readLine()) != null) && (tIndex < triplet.size()) && (pIndex < polarity.size())) { if (line.matches("^[\\d]*:")) { // System.out.println(line); sw.write(line + "\n"); } else { Scanner sc = new Scanner(line); String trip = sc.findInLine(Pattern.compile("[a-zA-Z]+#[a-z]+[#]?[0-9]*")); // if (trip != null && trip.equals(triplet.get(tIndex))) { System.out.println(trip); if (trip != null && !trip.toLowerCase().contains("no#cl")) { // System.out.println(triplet.get(tIndex) + ":" +polarity.get(pIndex)); String pol = polarity.get(pIndex); sw.write(line + " " + pol + "\n"); sc.close(); tIndex++; pIndex++; } else { String pol = "neg"; sw.write("no#a#1" + " " + pol + "\n"); sc.close(); } } // sw.flush(); } sw.close(); } catch (IOException e) { e.printStackTrace(); } }
public void run() { for (; ; ) { try { int n = sel.select(); if (n > 0) processSelectedKeys(); processPendingTargets(); if (shutdown) { sel.close(); return; } } catch (IOException x) { x.printStackTrace(); } } }
public BackupHdfs() { try { m_wrMkdirs = new PrintWriter(new BufferedWriter(new FileWriter("hdfs-mkdirs.sh"))); m_wrMkdirs.println("hadoop fs -mkdir /mapred"); m_wrMkdirs.println("hadoop fs -mkdir /mapred/system"); m_wrChmods = new PrintWriter(new BufferedWriter(new FileWriter("hdfs-chmods.sh"))); m_wrChmods.println("hadoop fs -chmod 775 /"); m_wrChmods.println("hadoop fs -chown hdfs:hadoop /"); m_wrChmods.println("hadoop fs -chown mapred:hadoop /mapred/system"); m_wrChmods.println("hadoop fs -chmod 700 /mapred/system"); } catch (IOException e) { System.err.println("ERROR: failed to open files for writing: " + e.toString()); } }
public static void lookingCode() { int procura = 0; boolean entrou = false; do { procura = Entrada.leiaInt("Digite o código da carta: "); } while (procura < 0 || procura > 32); try { FileReader arq = new FileReader(FileManenger.fileName); BufferedReader lerArq = new BufferedReader(arq); String linha = lerArq.readLine(); while (linha != null) { // procura na string '.' if (linha.toLowerCase().contains(".".toLowerCase())) { // separ em um array a linha que tem o nome do personagem ex: 1.CARLOS String columnArray[] = linha.split(Pattern.quote(".")); // testa se o codigo é o que ele procura if (procura == Integer.parseInt(columnArray[0])) { // achou o codigo que ele procura entrou = true; } } // testa se a linha é igual a * se for ele já não é mais o personagem que procuramos if (linha.equals("*")) { entrou = false; } // mostra as inforamações do personagem if (entrou) { System.out.println(linha); } linha = lerArq.readLine(); } arq.close(); } catch (IOException e) { System.err.printf("Erro na abertura do arquivo: %s.\n", e.getMessage()); } }
/* listen for connection from target vm */ private VirtualMachine listenTarget() { ListeningConnector listener = (ListeningConnector) connector; try { String retAddress = listener.startListening(connectorArgs); MessageOutput.println("Listening at address:", retAddress); vm = listener.accept(connectorArgs); listener.stopListening(connectorArgs); return vm; } catch (IOException ioe) { ioe.printStackTrace(); MessageOutput.fatalError("Unable to attach to target VM."); } catch (IllegalConnectorArgumentsException icae) { icae.printStackTrace(); MessageOutput.fatalError("Internal debugger error."); } return null; // Shuts up the compiler }
private void dumpStream(InputStream stream) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(stream)); int i; try { while ((i = in.read()) != -1) { MessageOutput.printDirect((char) i); // Special case: use // printDirect() } } catch (IOException ex) { String s = ex.getMessage(); if (!s.startsWith("Bad file number")) { throw ex; } // else we got a Bad file number IOException which just means // that the debuggee has gone away. We'll just treat it the // same as if we got an EOF. } }
public static void readFile() { try { FileReader arq = new FileReader(FileManenger.fileName); BufferedReader lerArq = new BufferedReader(arq); String linha = lerArq .readLine(); // lê a primeira linha a variável "linha" recebe o valor "null" quando o // processo de repetição atingir o final do arquivo texto while (linha != null) { System.out.println(linha); linha = lerArq.readLine(); // lê da segunda até a última linha } arq.close(); } catch (IOException e) { System.err.printf("Erro na abertura do arquivo: %s.\n", e.getMessage()); } }
public static void main(String[] args) { try { Genome g = Organism.findGenome(args[0]); File blasttab = new File(args[1]); ProbesFromPrimers pfp = new ProbesFromPrimers(g, blasttab); Collection<NamedRegion> probes = pfp.parseProbes(); for (NamedRegion probe : probes) { String probeName = probe.getName(); System.out.println( String.format( "%s\t%s\t%d\t%d", probeName, probe.getChrom(), probe.getStart(), probe.getEnd())); } } catch (NotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/* launch child target vm */ private VirtualMachine launchTarget() { LaunchingConnector launcher = (LaunchingConnector) connector; try { VirtualMachine vm = launcher.launch(connectorArgs); process = vm.process(); displayRemoteOutput(process.getErrorStream()); displayRemoteOutput(process.getInputStream()); return vm; } catch (IOException ioe) { ioe.printStackTrace(); MessageOutput.fatalError("Unable to launch target VM."); } catch (IllegalConnectorArgumentsException icae) { icae.printStackTrace(); MessageOutput.fatalError("Internal debugger error."); } catch (VMStartException vmse) { MessageOutput.println("vmstartexception", vmse.getMessage()); MessageOutput.println(); dumpFailedLaunchInfo(vmse.process()); MessageOutput.fatalError("Target VM failed to initialize."); } return null; // Shuts up the compiler }
protected void getDimensionsFromLogFile(BufferedReader reader, PicText text) { if (reader == null) { return; } String line = ""; // il rale si j'initialise pas ... boolean finished = false; while (!finished) { try { line = reader.readLine(); } catch (IOException ioex) { ioex.printStackTrace(); return; } if (line == null) { System.out.println("Size of text not found in log file..."); return; } System.out.println(line); Matcher matcher = LogFilePattern.matcher(line); if (line != null && matcher.find()) { System.out.println("FOUND :" + line); finished = true; try { text.setDimensions( 0.3515 * Double.parseDouble(matcher.group(1)), // height, pt->mm (1pt=0.3515 mm) 0.3515 * Double.parseDouble(matcher.group(2)), // width 0.3515 * Double.parseDouble(matcher.group(3))); // depth areDimensionsComputed = true; } catch (NumberFormatException e) { System.out.println("Logfile number format problem: $line" + e.getMessage()); } catch (IndexOutOfBoundsException e) { System.out.println("Logfile regexp problem: $line" + e.getMessage()); } } } return; }
/** * Searches for the directory 'dirPath'; if not found, tries to create it, then returns a File * object for that directory. */ public static File ensureDirExists(final String dirPath) { File dirpath = new File(dirPath); if (!dirpath.isDirectory()) { if (!dirpath.exists()) { printDebug("[Meta] " + dirpath + " does not exist: creating it..."); try { Files.createDirectories(Paths.get(dirpath.getPath())); return dirpath; } catch (IOException e) { printDebug("[Meta] Exception while creating directory:"); e.printStackTrace(); return null; } } else { printDebug( "[Meta] Error: path `" + dirpath + "' is not a valid directory path, and could not create it."); return null; } } else return dirpath; }
// Takes a PImage and compresses it into a JPEG byte stream // Adapted from Dan Shiffman's UDP Sender code public byte[] compressImage(PImage img) { // We need a buffered image to do the JPG encoding BufferedImage bimg = new BufferedImage(img.width, img.height, BufferedImage.TYPE_INT_RGB); img.loadPixels(); bimg.setRGB(0, 0, img.width, img.height, img.pixels, 0, img.width); // Need these output streams to get image as bytes for UDP communication ByteArrayOutputStream baStream = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baStream); // Turn the BufferedImage into a JPG and put it in the BufferedOutputStream // Requires try/catch try { ImageIO.write(bimg, "jpg", bos); } catch (IOException e) { e.printStackTrace(); } // Get the byte array, which we will send out via UDP! return baStream.toByteArray(); }
// Creates a new thread, runs the program in that thread, and reports any errors as needed. private void run(String clazz) { try { // Makes sure the JVM resets if it's already running. if (JVMrunning) kill(); // Some String constants for java path and OS-specific separators. String separator = System.getProperty("file.separator"); String path = System.getProperty("java.home") + separator + "bin" + separator + "java"; // Tries to run compiled code. ProcessBuilder builder = new ProcessBuilder(path, clazz); // Should be good now! Everything past this is on you. Don't mess it up. println( "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr); println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr); JVM = builder.start(); // Note that as of right now, there is no support for input. Only output. Reader errorReader = new InputStreamReader(JVM.getErrorStream()); Reader outReader = new InputStreamReader(JVM.getInputStream()); // Writer inReader = new OutputStreamWriter(JVM.getOutputStream()); redirectErr = redirectIOStream(errorReader, err); redirectOut = redirectIOStream(outReader, out); // redirectIn = redirectIOStream(null, inReader); } catch (IOException e) { // JVM = builder.start() can throw this. println("IOException when running the JVM.", progErr); e.printStackTrace(); displayLog(); return; } }
/** * Compare the checksums of the hdfs file as well as the local copied file. * * @author [email protected] * @date Fri Jan 27 06:06:00 2012 */ boolean compareChecksums(FileSystem fs, Path p, String sFsPath) { try { // get hdfs file info FileStatus stat = fs.getFileStatus(p); // get HDFS checksum FileChecksum ck = fs.getFileChecksum(p); String sCk, sCkShort; if (ck == null) { sCk = sCkShort = "<null>"; } else { sCk = ck.toString(); sCkShort = sCk.replaceAll("^.*:", ""); } // System.out.println(p.toUri().getPath() + " len=" + stat.getLen() // + " " + stat.getOwner() + "/" + stat.getGroup() // + " checksum=" + sCk); // find the local file File fLocal = new File(sFsPath); if (!fLocal.exists()) { System.out.println("CHECKSUM-ERROR: file does not exist: " + sFsPath); return false; } if (!fLocal.isFile()) { System.out.println("CHECKSUM-ERROR: path is not a file: " + sFsPath); return false; } if (stat.getLen() != fLocal.length()) { System.out.println( "CHECKSUM-ERROR: length mismatch: " + sFsPath + " hdfslen=" + stat.getLen() + " fslen=" + fLocal.length()); return false; } // get local fs checksum FileChecksum ckLocal = getLocalFileChecksum(sFsPath); if (ckLocal == null) { System.out.println("ERROR Failed to get checksum for local file " + sFsPath); return false; } // compare checksums as a string, after stripping the // algorithm name from the beginning String sCkLocal = ckLocal.toString(); String sCkLocalShort = sCkLocal.replaceAll("^.*:", ""); if (false == sCkShort.equals(sCkLocalShort)) { System.out.println( "CHECKSUM-ERROR: checksum mismatch: " + sFsPath + "\nhdfs = " + sCk + "\nlocal= " + sCkLocal); return false; } return true; } catch (IOException e) { System.out.println("CHECKSUM-ERROR: " + sFsPath + " exception " + e.toString()); } return false; }
public void init() throws ServletException { final String CONFIG_PATH = getServletContext().getRealPath("/") + "config.ini"; final String APPLICATION_NAME = getServletContext().getServletContextName(); BasicConfigurator.configure(); FileInputStream config_file = null; File config = new File(CONFIG_PATH); if (config.canRead()) { log.debug("Parsing " + CONFIG_PATH); try { config_file = new FileInputStream(CONFIG_PATH); } catch (java.io.FileNotFoundException e) { throw new ServletException(e); } Properties config_prop = new Properties(); try { config_prop.load(config_file); } catch (java.io.IOException e) { throw new ServletException(e); } this.config = config_prop; log.debug("Parsing finished"); } else { log.fatal("Error, cannot read " + CONFIG_PATH); } log.debug("maximumRecords : " + this.config.getProperty("default_maximumRecords")); log.debug("srw_header_file: " + this.config.getProperty("srw_header_file")); log.debug("srw_diag: " + this.config.getProperty("srw_diag_file")); // log.debug("server_list: " + this.config.getProperty("server_list")); try { FileReader fis = new FileReader( getServletContext().getRealPath("/") + this.config.getProperty("srw_header_file")); BufferedReader in1 = new BufferedReader(fis); fis = new FileReader( getServletContext().getRealPath("/") + this.config.getProperty("srw_footer_file")); BufferedReader in2 = new BufferedReader(fis); fis = new FileReader( getServletContext().getRealPath("/") + this.config.getProperty("srw_diag_file")); BufferedReader in3 = new BufferedReader(fis); try { String line = null; while ((line = in1.readLine()) != null) { this.SRW_HEADER = this.SRW_HEADER + line; } while ((line = in2.readLine()) != null) { this.SRW_FOOTER = this.SRW_FOOTER + line; } while ((line = in3.readLine()) != null) { this.SRW_DIAG = this.SRW_DIAG + line; } } finally { in1.close(); in2.close(); in3.close(); } } catch (IOException ex) { ex.printStackTrace(); } }
/** Performs the subsequent ReTrace operations. */ public void execute() throws IOException { // Read the mapping file. MappingReader mappingReader = new MappingReader(mappingFile); mappingReader.pump(this); StringBuffer expressionBuffer = new StringBuffer(regularExpression.length() + 32); char[] expressionTypes = new char[32]; int expressionTypeCount = 0; int index = 0; while (true) { int nextIndex = regularExpression.indexOf('%', index); if (nextIndex < 0 || nextIndex == regularExpression.length() - 1 || expressionTypeCount == expressionTypes.length) { break; } expressionBuffer.append(regularExpression.substring(index, nextIndex)); expressionBuffer.append('('); char expressionType = regularExpression.charAt(nextIndex + 1); switch (expressionType) { case 'c': expressionBuffer.append(REGEX_CLASS); break; case 'C': expressionBuffer.append(REGEX_CLASS_SLASH); break; case 'l': expressionBuffer.append(REGEX_LINE_NUMBER); break; case 't': expressionBuffer.append(REGEX_TYPE); break; case 'f': expressionBuffer.append(REGEX_MEMBER); break; case 'm': expressionBuffer.append(REGEX_MEMBER); break; case 'a': expressionBuffer.append(REGEX_ARGUMENTS); break; } expressionBuffer.append(')'); expressionTypes[expressionTypeCount++] = expressionType; index = nextIndex + 2; } expressionBuffer.append(regularExpression.substring(index)); Pattern pattern = Pattern.compile(expressionBuffer.toString()); // Read the stack trace file. LineNumberReader reader = new LineNumberReader( stackTraceFile == null ? (Reader) new InputStreamReader(System.in) : (Reader) new BufferedReader(new FileReader(stackTraceFile))); try { StringBuffer outLine = new StringBuffer(256); List extraOutLines = new ArrayList(); String className = null; // Read the line in the stack trace. while (true) { String line = reader.readLine(); if (line == null) { break; } Matcher matcher = pattern.matcher(line); if (matcher.matches()) { int lineNumber = 0; String type = null; String arguments = null; // Figure out a class name, line number, type, and // arguments beforehand. for (int expressionTypeIndex = 0; expressionTypeIndex < expressionTypeCount; expressionTypeIndex++) { int startIndex = matcher.start(expressionTypeIndex + 1); if (startIndex >= 0) { String match = matcher.group(expressionTypeIndex + 1); char expressionType = expressionTypes[expressionTypeIndex]; switch (expressionType) { case 'c': className = originalClassName(match); break; case 'C': className = originalClassName(ClassUtil.externalClassName(match)); break; case 'l': lineNumber = Integer.parseInt(match); break; case 't': type = originalType(match); break; case 'a': arguments = originalArguments(match); break; } } } // Actually construct the output line. int lineIndex = 0; outLine.setLength(0); extraOutLines.clear(); for (int expressionTypeIndex = 0; expressionTypeIndex < expressionTypeCount; expressionTypeIndex++) { int startIndex = matcher.start(expressionTypeIndex + 1); if (startIndex >= 0) { int endIndex = matcher.end(expressionTypeIndex + 1); String match = matcher.group(expressionTypeIndex + 1); // Copy a literal piece of input line. outLine.append(line.substring(lineIndex, startIndex)); char expressionType = expressionTypes[expressionTypeIndex]; switch (expressionType) { case 'c': className = originalClassName(match); outLine.append(className); break; case 'C': className = originalClassName(ClassUtil.externalClassName(match)); outLine.append(ClassUtil.internalClassName(className)); break; case 'l': lineNumber = Integer.parseInt(match); outLine.append(match); break; case 't': type = originalType(match); outLine.append(type); break; case 'f': originalFieldName(className, match, type, outLine, extraOutLines); break; case 'm': originalMethodName( className, match, lineNumber, type, arguments, outLine, extraOutLines); break; case 'a': arguments = originalArguments(match); outLine.append(arguments); break; } // Skip the original element whose processed version // has just been appended. lineIndex = endIndex; } } // Copy the last literal piece of input line. outLine.append(line.substring(lineIndex)); // Print out the main line. System.out.println(outLine); // Print out any additional lines. for (int extraLineIndex = 0; extraLineIndex < extraOutLines.size(); extraLineIndex++) { System.out.println(extraOutLines.get(extraLineIndex)); } } else { // Print out the original line. System.out.println(line); } } } catch (IOException ex) { throw new IOException("Can't read stack trace (" + ex.getMessage() + ")"); } finally { if (stackTraceFile != null) { try { reader.close(); } catch (IOException ex) { // This shouldn't happen. } } } }
// Thread's run method aimed at creating a bitmap asynchronously public void run() { Drawing drawing = new Drawing(); PicText rawPicText = new PicText(); String s = ((PicText) element).getText(); rawPicText.setText(s); drawing.add( rawPicText); // bug fix: we must add a CLONE of the PicText, otherwise it loses it former // parent... (then pb with the view ) drawing.setNotparsedCommands( "\\newlength{\\jpicwidth}\\settowidth{\\jpicwidth}{" + s + "}" + CR_LF + "\\newlength{\\jpicheight}\\settoheight{\\jpicheight}{" + s + "}" + CR_LF + "\\newlength{\\jpicdepth}\\settodepth{\\jpicdepth}{" + s + "}" + CR_LF + "\\typeout{JPICEDT INFO: \\the\\jpicwidth, \\the\\jpicheight, \\the\\jpicdepth }" + CR_LF); RunExternalCommand.Command commandToRun = RunExternalCommand.Command.BITMAP_CREATION; // RunExternalCommand command = new RunExternalCommand(drawing, contentType,commandToRun); boolean isWriteTmpTeXfile = true; String bitmapExt = "png"; // [pending] preferences String cmdLine = "{i}/unix/tetex/create_bitmap.sh {p} {f} " + bitmapExt + " " + fileDPI; // [pending] preferences ContentType contentType = getContainer().getContentType(); RunExternalCommand.isGUI = false; // System.out, no dialog box // [pending] debug RunExternalCommand command = new RunExternalCommand(drawing, contentType, cmdLine, isWriteTmpTeXfile); command .run(); // synchronous in an async. thread => it's ok (anyway, we must way until the LaTeX // process has completed) if (wantToComputeLatexDimensions) { // load size of text: try { File logFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + ".log"); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(logFile)); } catch (FileNotFoundException fnfe) { System.out.println("Cannot find log file! " + fnfe.getMessage()); System.out.println(logFile); } catch (IOException ioex) { System.out.println("Log file IO exception"); ioex.printStackTrace(); } // utile ? System.out.println("Log file created! file=" + logFile); getDimensionsFromLogFile(reader, (PicText) element); syncStringLocation(); // update dimensions syncBounds(); syncFrame(); SwingUtilities.invokeLater( new Thread() { public void run() { repaint(null); } }); // repaint(null); // now that dimensions are available, we force a repaint() [pending] // smart-repaint ? } catch (Exception e) { e.printStackTrace(); } } if (wantToGetBitMap) { // load image: try { File bitmapFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + "." + bitmapExt); this.image = ImageIO.read(bitmapFile); System.out.println( "Bitmap created! file=" + bitmapFile + ", width=" + image.getWidth() + "pixels, height=" + image.getHeight() + "pixels"); if (image == null) return; syncStringLocation(); // sets strx, stry, and dimensions of text syncBounds(); // update the AffineTransform that will be applied to the bitmap before displaying on screen PicText te = (PicText) element; text2ModelTr.setToIdentity(); // reset PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf); text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR ! text2ModelTr.translate(te.getLeftX(), te.getTopY()); text2ModelTr.scale( te.getWidth() / image.getWidth(), -(te.getHeight() + te.getDepth()) / image.getHeight()); // [pending] should do something special to avoid dividing by 0 or setting a rescaling // factor to 0 [non invertible matrix] (java will throw an exception) syncFrame(); SwingUtilities.invokeLater( new Thread() { public void run() { repaint(null); } }); // repaint(null); // now that bitmap is available, we force a repaint() [pending] // smart-repaint ? } catch (Exception e) { e.printStackTrace(); } } }