List of usage examples for java.io PrintStream flush
public void flush()
From source file:com.orange.atk.graphAnalyser.LectureJATKResult.java
/** * save config file./*from w w w . ja v a2 s. c om*/ * * */ private void jMenuItemSaveConfigFileActionPerformed(ActionEvent evt) { String JATKpath = Platform.getInstance().getJATKPath(); String pathihmconfig = JATKpath + Platform.FILE_SEPARATOR + "log" + Platform.FILE_SEPARATOR + "ConfigIHM.cfg"; //get a value from confile String Scriptpath = getvalueconfigfile(pathihmconfig, "path_READGRAPH"); PrintStream ps = null; try { ps = new PrintStream(new FileOutputStream(Scriptpath + Platform.FILE_SEPARATOR + "Confile2.xml")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); Logger.getLogger(this.getClass()).warn("Can't Create config file"); return; } ps.println("<confile>"); ps.println("<graphlist>"); Set<String> cles = mapPerfGraph.keySet(); Iterator<String> it = cles.iterator(); while (it.hasNext()) { String cle = (String) it.next(); PerformanceGraph graph = (PerformanceGraph) mapPerfGraph.get(cle); ps.println("<graph name=\"" + cle + ".csv" + "\"" + " color=\"" + getcolor(graph.getColor()) + "\"" + "/>"); } ps.println("</graphlist>"); ps.println("<markerlist>"); ps.println("<marker name=\"keyPress\" position=\"0.2\" color=\"gray\"/>"); ps.println("<marker name=\"log\" position=\"0.4\" color=\"gray\"/>"); ps.println("<marker name=\"Action\" position=\"0.5\" color=\"gray\"/>"); ps.println("<marker name=\"Standard Out/Err\" position=\"0.7\" color=\"gray\"/>"); ps.println("<marker name=\"ScreenShot\" position=\"0.9\" color=\"gray\"/>"); ps.println("<marker name=\"Error JATK\" position=\"0.9\" color=\"gray\"/>"); ps.println("</markerlist>"); ps.println("</confile>"); ps.flush(); ps.close(); }
From source file:org.kuali.kfs.module.tem.batch.service.impl.AgencyDataImportServiceImpl.java
/** * @see org.kuali.kfs.module.tem.batch.service.AgencyDataImportService#moveAgencyDataToHistoricalExpenseTable() *///from w w w .j a va 2s . c o m @Override public boolean moveAgencyDataToHistoricalExpenseTable() { LOG.info("Starting Agency Expense Distribution/Reconciliation Process"); List<AgencyStagingData> agencyData = travelExpenseService.retrieveValidAgencyData(); if (ObjectUtils.isNotNull(agencyData) && agencyData.size() > 0) { PrintStream reportDataStream = dataReportService.getReportPrintStream(getAgencyDataReportDirectory(), getAgencyDataReconciliationReportFilePrefix()); BusinessObjectReportHelper reportHelper = getAgencyDataReconciliationReportHelper(); try { dataReportService.writeReportHeader(reportDataStream, null, TemKeyConstants.MESSAGE_AGENCY_DATA_RECONCILIATION_REPORT_HEADER, reportHelper); //set up map for keeping track of sequence helpers per Trip Id. Sequence helper is not needed for ImportBy=TRV Map<String, GeneralLedgerPendingEntrySequenceHelper> sequenceHelperMap = new HashMap<String, GeneralLedgerPendingEntrySequenceHelper>(); GeneralLedgerPendingEntrySequenceHelper sequenceHelper = null; for (AgencyStagingData agency : agencyData) { List<ErrorMessage> errorMessages = new ArrayList<ErrorMessage>(); if (agency.getExpenseImport() == ExpenseImport.trip) { sequenceHelper = getGeneralLedgerPendingEntrySequenceHelper(agency, sequenceHelperMap); } errorMessages.addAll(processAgencyStagingExpense(agency, sequenceHelper)); getBusinessObjectService().save(agency); //writer to error report if (!errorMessages.isEmpty()) { dataReportService.writeToReport(reportDataStream, agency, errorMessages, reportHelper); LOG.info("Agency Data Id: " + agency.getId() + " was not processed."); } else { LOG.info("Agency Data Id: " + agency.getId() + " was processed."); } } } finally { if (reportDataStream != null) { reportDataStream.flush(); reportDataStream.close(); } } } LOG.info("Finished Agency Expense Distribution/Reconciliation Process"); return true; }
From source file:org.opentravel.schemacompiler.admin.CredentialsManager.java
/** * Updates the contents of the credentials file using the information provided. * /*ww w. j a v a2 s . c o m*/ * @param credentialsFile * the credentials file to update * @param userId * the user ID to be added, updated, or removed * @param password * the password to be assigned to the requested user * @param removeUserId * indicates that the user's credentials are to be removed * @throws IOException * thrown if a error prevents the update operation from succeeding */ protected void updateCredentialsFile(File credentialsFile, String userId, String password, boolean removeUserId) throws IOException { BufferedReader reader = null; PrintStream out = null; boolean success = false; File backupFile = null; try { // Read the contents of the existing file (if one exists) List<String> fileEntries = new ArrayList<String>(); if (credentialsFile.exists()) { // Backup the existing file before we start backupFile = Utils.createBackupFile(credentialsFile); reader = new BufferedReader(new FileReader(credentialsFile)); String line; while ((line = reader.readLine()) != null) { fileEntries.add(line); } reader.close(); reader = null; } // Write the contents of the file back out, making sure the appropriate action was taken // for the entry that corresponds to the request user ID boolean userEntryProcessed = false; out = new PrintStream(new FileOutputStream(credentialsFile)); for (String fileEntry : fileEntries) { if (fileEntry.trim().startsWith("#")) { out.println(fileEntry); } else { String[] entryParts = fileEntry.split(":"); String entryUserId = (entryParts.length >= 1) ? entryParts[0] : ""; if ((entryUserId != null) && entryUserId.equals(userId)) { if (!removeUserId) { StringBuilder newEntry = new StringBuilder(); newEntry.append(userId).append(':').append(PasswordHelper.encrypt(password)); for (int i = 2; i < entryParts.length; i++) { newEntry.append(':').append(entryParts[i]); } out.println(newEntry.toString()); } userEntryProcessed = true; } else { out.println(fileEntry); } } } // Handle case of a new user entry if (!userEntryProcessed) { out.println(userId + ":" + PasswordHelper.encrypt(password)); } out.flush(); out.close(); out = null; if (backupFile != null) { backupFile.delete(); } success = true; } finally { if (!success) { try { if (backupFile != null) { Utils.restoreOriginalFile(credentialsFile, backupFile); } } catch (IOException e) { System.out.println("ERROR: " + e.getMessage()); } } try { if (reader != null) reader.close(); } catch (Throwable t) { } try { if (out != null) out.close(); } catch (Throwable t) { } } }
From source file:edu.cornell.med.icb.goby.modes.TallyBasesMode.java
/** * Run the tally bases mode./* www . j ava 2 s. c om*/ * * @throws java.io.IOException error reading / writing */ @Override public void execute() throws IOException { if (basenames.length != 2) { System.err.println("Exactly two basenames are supported at this time."); System.exit(1); } final CountsArchiveReader[] archives = new CountsArchiveReader[basenames.length]; int i = 0; for (final String basename : basenames) { archives[i++] = new CountsArchiveReader(basename, alternativeCountArhive); } final CountsArchiveReader archiveA = archives[0]; final CountsArchiveReader archiveB = archives[1]; // keep only common reference sequences between the two input count archives. final ObjectSet<String> identifiers = new ObjectOpenHashSet<String>(); identifiers.addAll(archiveA.getIdentifiers()); identifiers.retainAll(archiveB.getIdentifiers()); // find the optimal offset A vs B: final int offset = offsetString.equals("auto") ? optimizeOffset(archiveA, archiveB, identifiers) : Integer.parseInt(offsetString); System.out.println("offset: " + offset); final RandomAccessSequenceCache cache = new RandomAccessSequenceCache(); if (cache.canLoad(genomeCacheFilename)) { try { cache.load(genomeCacheFilename); } catch (ClassNotFoundException e) { System.err.println("Cannot load cache from disk. Consider deleting the cache and rebuilding."); e.printStackTrace(); System.exit(1); } } else { Reader reader = null; try { if (genomeFilename.endsWith(".fa") || genomeFilename.endsWith(".fasta")) { reader = new FileReader(genomeFilename); cache.loadFasta(reader); } else if (genomeFilename.endsWith(".fa.gz") || genomeFilename.endsWith(".fasta.gz")) { reader = new InputStreamReader(new GZIPInputStream(new FileInputStream(genomeFilename))); cache.loadFasta(reader); } else { System.err.println("The format of the input file is not supported at this time."); System.exit(1); } } finally { IOUtils.closeQuietly(reader); } } System.out.println("Will use genome cache basename: " + genomeCacheFilename); cache.save(genomeCacheFilename); final Random random = new Random(new Date().getTime()); final double delta = cutoff; final int countThreshold = 30; final PrintStream output = new PrintStream(outputFilename); writeHeader(output, windowSize); for (final String referenceSequenceId : identifiers) { if (isReferenceIncluded(referenceSequenceId)) { final int referenceIndex = cache.getReferenceIndex(referenceSequenceId); if (referenceIndex != -1) { // sequence in cache. System.out.println("Processing sequence " + referenceSequenceId); final double sumA = getSumOfCounts(archiveA.getCountReader(referenceSequenceId)); final double sumB = getSumOfCounts(archiveB.getCountReader(referenceSequenceId)); final int referenceSize = cache.getSequenceSize(referenceIndex); // process this sequence: final AnyTransitionCountsIterator iterator = new AnyTransitionCountsIterator( archiveA.getCountReader(referenceSequenceId), new OffsetCountsReader(archiveB.getCountReader(referenceSequenceId), offset)); while (iterator.hasNextTransition()) { iterator.nextTransition(); final int position = iterator.getPosition(); final int countA = iterator.getCount(0); final int countB = iterator.getCount(1); if (countA + countB >= countThreshold) { final double foldChange = Math.log1p(countA) - Math.log1p(countB) - Math.log(sumA) + Math.log(sumB); if (foldChange >= delta || foldChange <= -delta) { if (random.nextDouble() < sampleRate) { tallyPosition(cache, referenceIndex, position, foldChange, windowSize, referenceSize, referenceSequenceId, output, countA, countB, sumA, sumB); } } } } iterator.close(); } } output.flush(); } output.close(); }
From source file:org.apache.nifi.toolkit.cli.impl.result.writer.DynamicTableWriter.java
@Override public void write(final Table table, final PrintStream output) { if (table == null) { throw new IllegalArgumentException("Table cannot be null"); }/*from w ww . j a va2s . c om*/ if (output == null) { throw new IllegalArgumentException("Output cannot be null"); } if (table.getColumns().isEmpty()) { throw new IllegalArgumentException("Table has no columns to write"); } output.println(); final List<TableColumn> columns = table.getColumns(); final List<String[]> rows = table.getRows(); final int numColumns = columns.size(); final Integer[] columnLengths = determineColumnLengths(columns, rows); final List<String> columnNames = columns.stream().map(c -> c.getName()).collect(Collectors.toList()); final Object[] columnLengthsObj = Arrays.copyOf(columnLengths, numColumns, Object[].class); final Object[] columnNamesObj = columnNames.toArray(new Object[numColumns]); final String columnsPatternFormat = String.join("", Collections.nCopies(numColumns, "%%-%ds ")); final String columnsPattern = String.format(columnsPatternFormat, columnLengthsObj); // format the header line which will include the column names final String header = String.format(columnsPattern, columnNamesObj); output.println(header); // a little clunky way to dynamically create a nice header line, but at least no external dependency final Object[] headerLineValues = new Object[numColumns]; for (int i = 0; i < numColumns; i++) { int length = columnLengths[i]; headerLineValues[i] = String.join("", Collections.nCopies(length, "-")); } final String headerLine = String.format(columnsPattern, headerLineValues); output.println(headerLine); // format the rows and print them for (String[] row : rows) { // convert the row to an Object[] for the String.format and also abbreviate any values final Object[] rowValues = new Object[row.length]; for (int i = 0; i < row.length; i++) { final TableColumn column = columns.get(i); if (column.isAbbreviated()) { rowValues[i] = StringUtils.abbreviate(row[i], columnLengths[i]); } else { rowValues[i] = row[i]; } } final String rowString = String.format(columnsPattern, rowValues); output.println(rowString); } output.println(); output.flush(); }
From source file:com.lmco.ddf.commands.catalog.RemoveAllCommand.java
@Override protected Object doExecute() throws Exception { PrintStream console = System.out; if (batchSize < PAGE_SIZE_LOWER_LIMIT) { printColor(console, Ansi.Color.RED, String.format(BATCH_SIZE_ERROR_MESSAGE_FORMAT, batchSize)); return null; }//from w ww .j a v a 2 s. c o m CatalogFacade catalog = this.getCatalog(); if (isAccidentalRemoval(console)) { return null; } FilterBuilder filterBuilder = getFilterBuilder(); QueryRequest firstQuery = getIntendedQuery(filterBuilder, batchSize, expired, true); QueryRequest subsequentQuery = getIntendedQuery(filterBuilder, batchSize, expired, false); long totalAmountDeleted = 0; long start = System.currentTimeMillis(); SourceResponse response = null; try { response = catalog.query(firstQuery); } catch (UnsupportedQueryException e) { firstQuery = getAlternateQuery(filterBuilder, batchSize, expired, true); subsequentQuery = getAlternateQuery(filterBuilder, batchSize, expired, false); response = catalog.query(firstQuery); } if (response == null) { printColor(console, Ansi.Color.RED, "No response from Catalog."); return null; } if (needsAlternateQueryAndResponse(response)) { firstQuery = getAlternateQuery(filterBuilder, batchSize, expired, true); subsequentQuery = getAlternateQuery(filterBuilder, batchSize, expired, false); response = catalog.query(firstQuery); } String totalAmount = getTotalAmount(response.getHits()); while (response.getResults().size() > 0) { List<String> ids = new ArrayList<String>(); // Add metacard ids to string array for (Result result : response.getResults()) { if (result != null && result.getMetacard() != null) { Metacard metacard = result.getMetacard(); ids.add(metacard.getId()); } } // Delete the records DeleteRequestImpl request = new DeleteRequestImpl(ids.toArray(new String[ids.size()])); DeleteResponse deleteResponse = catalog.delete(request); int amountDeleted = deleteResponse.getDeletedMetacards().size(); totalAmountDeleted += amountDeleted; console.print(String.format(PROGRESS_FORMAT, totalAmountDeleted, totalAmount)); console.flush(); // Break out if there are no more records to delete if (amountDeleted < batchSize || batchSize < 1) { break; } // Re-query when necessary response = catalog.query(subsequentQuery); } long end = System.currentTimeMillis(); console.println(); console.printf(" %d file(s) removed in %3.3f seconds%n", totalAmountDeleted, (end - start) / MILLISECONDS_PER_SECOND); return null; }
From source file:de.juwimm.cms.remote.ContentServiceSpringImpl.java
/** * Creates a new Unit-Edition for the active site and returns it as SOAP-Attachment. * /*from w ww. j a v a2 s . c o m*/ * @throws UserException * * @see de.juwimm.cms.remote.ContentServiceSpring#exportEditionUnit(java.lang.Integer) */ @Override protected InputStream handleExportEditionUnit(Integer rootViewComponentId) throws Exception { try { File fle = File.createTempFile("edition_unit_export", ".xml.gz"); FileOutputStream fout = new FileOutputStream(fle); GZIPOutputStream gzoudt = new GZIPOutputStream(fout); PrintStream out = new PrintStream(gzoudt, true, "UTF-8"); EditionHbm edition = super.getEditionHbmDao().create("RETURNEDITION", rootViewComponentId, out, true); super.getEditionHbmDao().remove(edition); out.flush(); out.close(); out = null; return new FileInputStream(fle); } catch (Exception e) { log.error("Could not export edition unit", e); throw new UserException(e.getMessage()); } }
From source file:com.netscape.cms.servlet.csadmin.ConfigurationUtils.java
public static String submitAdminCertRequest(String ca_hostname, int ca_port, String profileId, String certRequestType, String certRequest, String subjectDN) throws Exception { logger.debug("ConfigurationUtils: submitAdminCertRequest()"); IConfigStore config = CMS.getConfigStore(); if (profileId == null) { profileId = config.getString("preop.admincert.profile", "caAdminCert"); }/*from w w w. ja va 2 s . c o m*/ String session_id = CMS.getConfigSDSessionId(); MultivaluedMap<String, String> content = new MultivaluedHashMap<String, String>(); content.putSingle("profileId", profileId); content.putSingle("cert_request_type", certRequestType); content.putSingle("cert_request", certRequest); content.putSingle("xmlOutput", "true"); content.putSingle("sessionID", session_id); content.putSingle("subject", subjectDN); String c = post(ca_hostname, ca_port, true, "/ca/ee/ca/profileSubmit", content, null, null); // retrieve the request Id and admin certificate if (c != null) { ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes()); XMLObject parser = new XMLObject(bis); String status = parser.getValue("Status"); logger.debug("submitAdminXertRequest: status=" + status); if (status.equals(AUTH_FAILURE)) { throw new EAuthException("Unable to generate admin certificate: authentication failure"); } else if (!status.equals(SUCCESS)) { String error = parser.getValue("Error"); logger.error("Error: " + error); throw new IOException("Unable to generate admin certificate: " + error); } IConfigStore cs = CMS.getConfigStore(); String id = parser.getValue("Id"); cs.putString("preop.admincert.requestId.0", id); String serial = parser.getValue("serialno"); cs.putString("preop.admincert.serialno.0", serial); String b64 = parser.getValue("b64"); // save in a file for access by ImportAdminCertPanel String instanceRoot = cs.getString("instanceRoot", ""); String dir = instanceRoot + File.separator + "conf" + File.separator + "admin.b64"; cs.putString("preop.admincert.b64", dir); PrintStream ps = new PrintStream(dir, "UTF-8"); ps.println(b64); ps.flush(); ps.close(); return b64; } else { throw new IOException("submitAdminCertRequest: Failed to get response from ca"); } }
From source file:org.apache.oodt.cas.workflow.misc.WingsTask.java
public void run(Metadata metadata, WorkflowTaskConfiguration config) { Properties props = config.getProperties(); // Component Info String compid = props.getProperty("COMPONENT_ID"); String tname = props.getProperty("TASKNAME"); String jobid = props.getProperty("JOBID"); String argstring = props.getProperty("ARGUMENT"); ArrayList<String> inputs = fetchFromProps(props, "INPUT"); ArrayList<String> outputs = fetchFromProps(props, "OUTPUT"); // Following paths should be Shared across the cluster //String script = props.getProperty("SCRIPT_PATH"); String origjobdir = props.getProperty("JOB_DIR"); String jobdir = origjobdir;//from w ww.ja v a 2 s .c o m //String datadir = props.getProperty("DATA_DIR"); // File Manager Access String fmurl = props.getProperty("FM_URL"); String fmprefix = props.getProperty("FM_PREFIX"); // Logging specific info String logfile = props.getProperty("LOGFILE"); String wlogfile = props.getProperty("W_LOGFILE"); String tplid = wlogfile.replace(".log", ""); PrintStream wlogout = null; PrintStream logout = null; XmlRpcFileManagerClient fmclient = null; try { fmclient = new XmlRpcFileManagerClient(new URL(fmurl)); DataTransfer dt = new RemoteDataTransferFactory().createDataTransfer(); dt.setFileManagerUrl(new URL(fmurl)); // Check if outputs already exist in the file manager boolean outputs_already_present = true; for (String op : outputs) { String prodid = fmprefix + op; Product prod = null; try { prod = fmclient.getProductById(prodid); } catch (Exception e) { } if (prod == null) { outputs_already_present = false; } } // If outputs already present, no need to execute if (outputs_already_present) return; File tmpdir = File.createTempFile("oodt-run-", ""); if (tmpdir.delete() && tmpdir.mkdirs()) jobdir = tmpdir.getAbsolutePath() + File.separator; argstring = argstring.replace(origjobdir, jobdir); wlogout = new PrintStream(new FileOutputStream(jobdir + wlogfile, true)); logout = new PrintStream(jobdir + logfile); wlogout.println(jobid + " (" + tname + "): RUNNING"); wlogout.close(); this.uploadProduct(wlogfile, wlogfile, "GenericFile", new File(jobdir + wlogfile), new Metadata(), fmclient); wlogout = new PrintStream(new FileOutputStream(jobdir + wlogfile, true)); logout.println("[INFO]: Component Initializing"); logout.println(tname + " " + argstring); // Fetch input files from file manager if not already present in directory for (String ip : inputs) { File f = new File(jobdir + ip); if (!f.exists()) { logout.println("[INFO] Fetching Input from File Manager: " + ip); Product prod = fmclient.getProductById(fmprefix + ip); prod.setProductReferences(fmclient.getProductReferences(prod)); dt.retrieveProduct(prod, new File(jobdir)); } } logout.flush(); // Fetch component from file manager File compdir = new File(jobdir + File.separator + "comp"); compdir.mkdir(); Product cprod = fmclient.getProductById(compid); cprod.setProductReferences(fmclient.getProductReferences(cprod)); dt.retrieveProduct(cprod, compdir); String scriptPath = null; for (File czip : compdir.listFiles()) { if (czip.getName().endsWith(".zip")) { this.unZipIt(czip.getAbsolutePath(), compdir.getAbsolutePath()); File tmpf = new File(compdir.getAbsolutePath() + File.separator + "run"); if (!tmpf.exists()) tmpf = new File(compdir.getAbsolutePath() + File.separator + "run.bat"); scriptPath = tmpf.getAbsolutePath(); } else scriptPath = czip.getAbsolutePath(); } File scriptf = new File(scriptPath); scriptf.setExecutable(true); // Create command execution ArrayList<String> command = new ArrayList<String>(); command.add(scriptf.getAbsolutePath()); for (String s : argstring.split(" ")) { command.add(s); } ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(jobdir)); builder.redirectErrorStream(true); final Process process = builder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { logout.println(line); } process.waitFor(); int exitStatus = process.exitValue(); if (exitStatus != 0) throw new Exception("[ERROR] Component failed with a non-zero exit code"); // Ingest output files to file manager for (String op : outputs) { File f = new File(jobdir + op); File metf = new File(jobdir + op + ".met"); HashMap<String, String> cmeta = new HashMap<String, String>(); if (metf.exists()) { for (Object ln : FileUtils.readLines(metf)) { String metline = (String) ln; String[] kv = metline.split("\\s*=\\s*"); if (kv.length == 2) cmeta.put(kv[0], kv[1]); } } if (!f.exists()) throw new Exception("[ERROR] Missing Output " + op); if (f.exists()) { logout.println("[INFO] Putting Output into File Manager: " + op); // Get Output Metadata & Product Type String typeid = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; Metadata meta = metadata.getSubMetadata(op); String prodtypeid = meta.getMetadata(typeid); meta.removeMetadata(typeid); // Override metadata with custom metadata (if any) for (String key : meta.getAllKeys()) { String[] nsname = key.split("#"); if (nsname.length == 2) { if (cmeta.containsKey(nsname[1])) { meta.removeMetadata(key); meta.addMetadata(key, cmeta.get(nsname[1])); } } } // Upload output to file manager String prodid = fmprefix + op; this.uploadProduct(prodid, op, prodtypeid, f, meta, fmclient); } if (metf.exists()) { String metname = op + ".met"; String prodid = fmprefix + metname; this.uploadProduct(prodid, metname, "GenericFile", metf, new Metadata(), fmclient); } } logout.println("SUCCESS: Component finished successfully !"); logout.close(); wlogout.println(jobid + " (" + tname + "): SUCCESS"); wlogout.close(); } catch (Exception e) { if (logout != null) { logout.println(e.getMessage()); logout.println("FAILURE: Component Failed"); logout.close(); wlogout.println(jobid + " (" + tname + "): FAILURE"); wlogout.close(); } } try { if (fmclient != null) { this.uploadProduct(wlogfile, wlogfile, "GenericFile", new File(jobdir + wlogfile), new Metadata(), fmclient); String logid = tplid + "-" + logfile; this.uploadProduct(logid, logid, "GenericFile", new File(jobdir + logfile), new Metadata(), fmclient); } } catch (CatalogException e) { e.printStackTrace(); } catch (RepositoryManagerException e) { e.printStackTrace(); } }
From source file:org.openlaszlo.sc.SWF9External.java
/** * Run the compiler using the command/arguments in cmd. Invokes the Flex compiler classes * directly, does not exec a subprocess. * Collect and report any errors, and check for the existence * of the output file.//from w ww . j a va2 s .c o m * @throw CompilerError if there are errors messages from the external * compiler, or if any part of the compilation process has problems */ public void callJavaCompileCommand(List acmd, String dir, List tunits, String outfileName) throws IOException // TODO: [2007-11-20 dda] clean up, why catch only some exceptions? { final List cmd = acmd; final String compilerClass = (String) cmd.remove(0); String[] cmdstr = (String[]) cmd.toArray(new String[0]); String prettycmd = prettyCommand(cmd); System.err.println("Executing compiler: (cd " + dir + "; " + prettycmd + ")"); BigErrorString bigErrorString = new BigErrorString(); // Generate a small script (unix style) to document how // to build this batch of files. String buildsh = isWindows() ? "rem build script\n" : "#!/bin/sh\n"; buildsh += "cd \"" + dir + "\"\n"; buildsh += prettycmd + "\n"; String buildfn = isWindows() ? "build.bat" : "build.sh"; Compiler.emitFile(workDirectoryName(buildfn), buildsh); // Remove the shell script executable path from beginning of cmd arg list cmd.remove(0); if (options.getBoolean(Compiler.EMIT_AS3_ONLY)) { // write out the command line as the output instead PrintWriter outf = new PrintWriter(new FileWriter(outfileName)); for (Iterator iter = cmd.iterator(); iter.hasNext();) { String arg = (String) iter.next(); outf.println(arg); } outf.close(); System.err.println( "option EMIT_AS3_ONLY set, returning without invoking flex compiler, call 'lcompile #' to compile as3"); return; } // Save original System.err, System.out PrintStream sout = System.out; PrintStream serr = System.err; ByteArrayOutputStream bout = new ByteArrayOutputStream(); ByteArrayOutputStream berr = new ByteArrayOutputStream(); PrintStream nout = new PrintStream(bout); PrintStream nerr = new PrintStream(berr); // Rebind to capture output System.setErr(nerr); System.setOut(nout); // flex2.tools.Mxmlc +flexlib="$FLEX_HOME/frameworks" // flex2.tools.Compc // System.setProperty("FLEX_HOME", FLEX_HOME()); // The Mxlmc and Compc util classes need to see this arg first in the args list cmd.add(0, "+flexlib=" + FLEX_HOME() + "/frameworks"); final Integer exitval[] = new Integer[1]; Thread worker = new Thread() { public void run() { //Process proc = Runtime.getRuntime().exec(cmdstr, (String[])newenv.toArray(new String[0]), null); String args[] = (String[]) cmd.toArray(new String[0]); if (compilerClass.equals("mxmlc")) { flex2.tools.Mxmlc.mxmlc(args); exitval[0] = new Integer(flex2.compiler.util.ThreadLocalToolkit.errorCount()); } else if (compilerClass.equals("compc")) { flex2.tools.Compc.compc(args); exitval[0] = new Integer(flex2.compiler.util.ThreadLocalToolkit.errorCount()); } } }; try { worker.start(); worker.join(); } catch (java.lang.InterruptedException e) { throw new CompilerError("Errors from compiler, output file not created" + e); } finally { // Restore system output and err streams System.setErr(serr); System.setOut(sout); } try { nerr.flush(); nout.flush(); System.out.println("compiler output is " + bout.toString()); OutputCollector outcollect = new OutputCollector(new ByteArrayInputStream(bout.toByteArray())); ExternalCompilerErrorCollector errcollect = new ExternalCompilerErrorCollector( new ByteArrayInputStream(berr.toByteArray()), tunits); outcollect.start(); errcollect.start(); outcollect.join(); errcollect.join(); if (outcollect.getException() != null) { System.err.println("Error collecting compiler output: " + outcollect.getException()); // TODO: [2007-11-20 dda] log this } String compilerOutput = outcollect.getOutput(); if (compilerOutput.length() > 0) { System.err.println("compiler output:\n" + compilerOutput); } if (errcollect.getException() != null) { System.err.println("Error collecting compiler output: " + errcollect.getException()); // TODO: [2007-11-20 dda] log this } List severe = errcollect.getSevereErrors(); if (severe.size() > 0) { for (Iterator iter = severe.iterator(); iter.hasNext();) { String errstr = "SEVERE ERROR: " + (String) iter.next(); bigErrorString.add(errstr); System.err.println(errstr); } } List errs = errcollect.getErrors(); if (errs.size() > 0) { System.err.println("ERRORS: "); for (Iterator iter = errs.iterator(); iter.hasNext();) { ExternalCompilerError err = (ExternalCompilerError) iter.next(); TranslationUnit tunit = err.getTranslationUnit(); String srcLineStr; TranslationUnit.SourceFileLine srcFileLine; // actualSrcLine is the name/linenumber of the actual files // used in compilation, not the original sources. String actualSrcFile = null; if (tunit == null) { actualSrcFile = "(unknown)"; } else { actualSrcFile = tunit.getSourceFileName(); if (actualSrcFile == null) actualSrcFile = "(" + tunit.getName() + ")"; } String actualSrcLine = "[" + actualSrcFile + ": " + err.getLineNumber() + "] "; if (tunit == null) { srcLineStr = "tunit/line unknown: "; } else if ((srcFileLine = tunit.originalLineNumber(err.getLineNumber())) == null) { srcLineStr = "line unknown: "; } else { srcLineStr = srcFileLine.sourcefile.name + ": " + srcFileLine.line + ": "; } System.err.println(actualSrcLine + srcLineStr + err.getErrorString()); bigErrorString.add(srcLineStr + err.cleanedErrorString()); } } if (exitval[0].intValue() != 0) { System.err.println("FAIL: compiler returned " + exitval[0].intValue()); } } catch (InterruptedException ie) { throw new CompilerError("Interrupted compiler"); } System.err.println("Done executing compiler"); if (!new File(outfileName).exists()) { System.err.println("Intermediate file " + outfileName + ": does not exist"); if (bigErrorString.str.length() > 0) { throw new CompilerError(bigErrorString.str); } else { throw new CompilerError("Errors from compiler, output file not created"); } } }