Example usage for java.io PrintStream close

List of usage examples for java.io PrintStream close

Introduction

In this page you can find the example usage for java.io PrintStream close.

Prototype

public void close() 

Source Link

Document

Closes the stream.

Usage

From source file:com.vonglasow.michael.satstat.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            Context c = getApplicationContext();
            File dumpDir = c.getExternalFilesDir(null);
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.ROOT);
            fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
            String fileName = String.format("satstat-%s.log", fmt.format(new Date(System.currentTimeMillis())));

            File dumpFile = new File(dumpDir, fileName);
            PrintStream s;
            try {
                InputStream buildInStream = getResources().openRawResource(R.raw.build);
                s = new PrintStream(dumpFile);
                s.append("SatStat build: ");

                int i;
                try {
                    i = buildInStream.read();
                    while (i != -1) {
                        s.write(i);/*from www  .ja  v a  2  s .  c om*/
                        i = buildInStream.read();
                    }
                    buildInStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                s.append("\n\n");
                e.printStackTrace(s);
                s.flush();
                s.close();

                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(dumpFile);
                mediaScanIntent.setData(contentUri);
                c.sendBroadcast(mediaScanIntent);
            } catch (FileNotFoundException e2) {
                e2.printStackTrace();
            }
            defaultUEH.uncaughtException(t, e);
        }
    });

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
    prefUnitType = mSharedPreferences.getBoolean(Const.KEY_PREF_UNIT_TYPE, prefUnitType);
    prefKnots = mSharedPreferences.getBoolean(Const.KEY_PREF_KNOTS, prefKnots);
    prefCoord = Integer
            .valueOf(mSharedPreferences.getString(Const.KEY_PREF_COORD, Integer.toString(prefCoord)));
    prefUtc = mSharedPreferences.getBoolean(Const.KEY_PREF_UTC, prefUtc);
    prefCid = mSharedPreferences.getBoolean(Const.KEY_PREF_CID, prefCid);
    prefCid2 = mSharedPreferences.getBoolean(Const.KEY_PREF_CID2, prefCid2);
    prefWifiSort = Integer
            .valueOf(mSharedPreferences.getString(Const.KEY_PREF_WIFI_SORT, Integer.toString(prefWifiSort)));
    prefMapOffline = mSharedPreferences.getBoolean(Const.KEY_PREF_MAP_OFFLINE, prefMapOffline);
    prefMapPath = mSharedPreferences.getString(Const.KEY_PREF_MAP_PATH, prefMapPath);

    ActionBar actionBar = getSupportActionBar();

    setContentView(R.layout.activity_main);

    // Find out default screen orientation
    Configuration config = getResources().getConfiguration();
    WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    int rot = wm.getDefaultDisplay().getRotation();
    isWideScreen = (config.orientation == Configuration.ORIENTATION_LANDSCAPE
            && (rot == Surface.ROTATION_0 || rot == Surface.ROTATION_180)
            || config.orientation == Configuration.ORIENTATION_PORTRAIT
                    && (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270));
    Log.d(TAG, "isWideScreen=" + Boolean.toString(isWideScreen));

    // Create the adapter that will return a fragment for each of the
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    Context ctx = new ContextThemeWrapper(getApplication(), R.style.AppTheme);
    mTabLayout = new TabLayout(ctx);
    LinearLayout.LayoutParams mTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
    mTabLayout.setLayoutParams(mTabLayoutParams);

    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        TabLayout.Tab newTab = mTabLayout.newTab();
        newTab.setIcon(mSectionsPagerAdapter.getPageIcon(i));
        mTabLayout.addTab(newTab);
    }

    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setCustomView(mTabLayout);

    mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));

    // This is needed by the mapsforge library.
    AndroidGraphicFactory.createInstance(this.getApplication());

    // Get system services for event delivery
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mOrSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    mAccSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mGyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    mMagSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    mLightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    mProximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    mPressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
    mHumiditySensor = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
    mTempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
}

From source file:com.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java

/**
 * Outputs the results as a csv file (sorted, best first).
 *
 * @param cmdLine the parsed command line parameters
 * @param bestKeywords the optimized set of keywords
 * @throws KeywordOptimizerException in case there is a problem writing to the output file
 *//* w  w  w  . ja  va  2s .c o m*/
private static void outputCsv(CommandLine cmdLine, KeywordCollection bestKeywords)
        throws KeywordOptimizerException {
    if (!cmdLine.hasOption("of")) {
        throw new KeywordOptimizerException("No output file (option -of specified)");
    }

    try {
        PrintStream printer = new PrintStream(cmdLine.getOptionValue("of"));
        printer.println(CSV_JOINER.join(CSV_HEADERS));

        for (KeywordInfo eval : bestKeywords.getListSortedByScore()) {
            TrafficEstimate estimate = eval.getEstimate();
            Object[] rowData = { eval.getKeyword().getText(), eval.getKeyword().getMatchType(), eval.getScore(),
                    KeywordOptimizerUtil.formatCsv(estimate.getMin().getImpressionsPerDay()),
                    KeywordOptimizerUtil.formatCsv(estimate.getMean().getImpressionsPerDay()),
                    KeywordOptimizerUtil.formatCsv(estimate.getMax().getImpressionsPerDay()),
                    KeywordOptimizerUtil.formatCsv(estimate.getMin().getClicksPerDay()),
                    KeywordOptimizerUtil.formatCsv(estimate.getMean().getClicksPerDay()),
                    KeywordOptimizerUtil.formatCsv(estimate.getMax().getClicksPerDay()),
                    KeywordOptimizerUtil.formatCsv(estimate.getMin().getClickThroughRate()),
                    KeywordOptimizerUtil.formatCsv(estimate.getMean().getClickThroughRate()),
                    KeywordOptimizerUtil.formatCsv(estimate.getMax().getClickThroughRate()),
                    KeywordOptimizerUtil.formatCsv(estimate.getMin().getAveragePosition()),
                    KeywordOptimizerUtil.formatCsv(estimate.getMean().getAveragePosition()),
                    KeywordOptimizerUtil.formatCsv(estimate.getMax().getAveragePosition()),
                    KeywordOptimizerUtil.format(estimate.getMin().getAverageCpc()),
                    KeywordOptimizerUtil.format(estimate.getMean().getAverageCpc()),
                    KeywordOptimizerUtil.format(estimate.getMax().getAverageCpc()),
                    KeywordOptimizerUtil.format(estimate.getMin().getTotalCost()),
                    KeywordOptimizerUtil.format(estimate.getMean().getTotalCost()),
                    KeywordOptimizerUtil.format(estimate.getMax().getTotalCost()) };

            printer.println(CSV_JOINER.join(rowData));
        }
        printer.close();
    } catch (IOException e) {
        throw new KeywordOptimizerException("Error writing to output file", e);
    }
}

From source file:it.unimi.di.big.mg4j.document.SimpleCompressedDocumentCollectionBuilder.java

public void close() throws IOException {
    documentsOutputBitStream.close();// ww  w.j a  v  a  2 s .  c om
    termsOutputStream.close();
    IOUtils.closeQuietly(nonTermsOutputStream);
    documentOffsetsObs.close();
    termOffsetsObs.close();
    if (nonTermOffsetsObs != null)
        nonTermOffsetsObs.close();
    if (hasNonText) {
        if (documents == 0)
            nonTextZipOutputStream.putNextEntry(new ZipEntry("dummy"));
        nonTextZipDataOutputStream.close();
    }

    final SimpleCompressedDocumentCollection simpleCompressedDocumentCollection = new SimpleCompressedDocumentCollection(
            relative ? new File(basenameSuffix).getName().toString() : basenameSuffix, documents, terms.size(),
            nonTerms != null ? nonTerms.size() : -1, exact, documentFactory);
    IOFactories.storeObject(ioFactory, simpleCompressedDocumentCollection,
            basenameSuffix + DocumentCollection.DEFAULT_EXTENSION);
    simpleCompressedDocumentCollection.close();

    final PrintStream stats = new PrintStream(
            ioFactory.getOutputStream(basenameSuffix + SimpleCompressedDocumentCollection.STATS_EXTENSION));
    final long overallBits = bitsForTitles + bitsForUris + bitsForFieldLengths + bitsForWords + bitsForNonWords;
    stats.println("Documents: " + Util.format(documents) + " (" + Util.format(overallBits) + ", "
            + Util.format(overallBits / (double) documents) + " bits per document)");
    stats.println("Terms: " + Util.format(terms.size()) + " (" + Util.format(words) + " words, "
            + Util.format(bitsForWords) + " bits, " + Util.format(bitsForWords / (double) words)
            + " bits per word)");
    if (exact)
        stats.println("Nonterms: " + Util.format(nonTerms.size()) + " (" + Util.format(words) + " nonwords, "
                + Util.format(bitsForNonWords) + " bits, " + Util.format(bitsForNonWords / (double) words)
                + " bits per nonword)");
    stats.println("Bits for field lengths: " + Util.format(bitsForFieldLengths) + " ("
            + Util.format(bitsForFieldLengths / (double) fields) + " bits per field)");
    stats.println("Bits for URIs: " + Util.format(bitsForUris) + " ("
            + Util.format(bitsForUris / (double) documents) + " bits per URI)");
    stats.println("Bits for titles: " + Util.format(bitsForTitles) + " ("
            + Util.format(bitsForTitles / (double) documents) + " bits per title)");
    stats.close();

}

From source file:com.knowbout.epg.EPG.java

private static void updateSitemap(String sitemap) {
    int lastslash = sitemap.lastIndexOf('/');
    String inprogress = sitemap.substring(0, lastslash) + "/inprogress-" + sitemap.substring(lastslash + 1);
    String marker = "<!-- EVERYTHING BELOW IS AUTOMATICALLY GENERATED -->";
    String baseurl = null;/*from www  .  j a va 2s . com*/
    try {
        PrintStream doc = new PrintStream(new GZIPOutputStream(new FileOutputStream(inprogress)));
        BufferedReader orig = new BufferedReader(
                new InputStreamReader(new GZIPInputStream(new FileInputStream(sitemap))));
        String line = orig.readLine();
        while (line != null) {
            if ((line.indexOf("</urlset>") >= 0) || (line.indexOf(marker) >= 0)) {
                break;
            }
            if (baseurl == null) {
                if (line.indexOf("<loc>") >= 0) {
                    int http = line.indexOf("http://");
                    int nextslash = line.indexOf("/", http + 7);
                    baseurl = line.substring(http, nextslash);
                }
            }
            doc.println(line);
            line = orig.readLine();
        }
        doc.println(marker);
        Set<String> teams = new HashSet<String>();
        HibernateUtil.openSession();
        try {
            ScrollableResults scroll = Program.selectAllTeams();
            while (scroll.next()) {
                Program program = (Program) scroll.get(0);
                addToSitemap(doc, baseurl, program);
                teams.add(program.getSportName() + ":" + program.getTeamName());
            }
            scroll = Program.selectAllShowsMoviesSports();
            while (scroll.next()) {
                Program program = (Program) scroll.get(0);
                if (program.isSports()) {
                    if (!teams.contains(program.getSportName() + ":" + program.getHomeTeamName())) {
                        Program home = Program.selectByTeam(program.getSportName(), program.getHomeTeamName());
                        addToSitemap(doc, baseurl, home);
                        teams.add(home.getSportName() + ":" + home.getTeamName());
                    }
                    if (!teams.contains(program.getSportName() + ":" + program.getAwayTeamName())) {
                        Program away = Program.selectByTeam(program.getSportName(), program.getAwayTeamName());
                        addToSitemap(doc, baseurl, away);
                        teams.add(away.getSportName() + ":" + away.getTeamName());
                    }
                } else {
                    addToSitemap(doc, baseurl, program);
                }
            }
        } finally {
            HibernateUtil.closeSession();
        }
        doc.println("</urlset>");
        doc.close();
        orig.close();
        File origFile = new File(sitemap);
        File backupFile = new File(sitemap + ".bak");
        File inprogressFile = new File(inprogress);
        backupFile.delete();
        if (!origFile.renameTo(backupFile)) {
            throw new IOException("Could not rename " + origFile + " to " + backupFile);
        }
        if (!inprogressFile.renameTo(origFile)) {
            throw new IOException("Could not rename " + inprogressFile + " to " + origFile);
        }
    } catch (FileNotFoundException e) {
        log.error("Could not write to " + inprogress, e);
    } catch (IOException e) {
        log.error("IO Exception for " + inprogress + " or " + sitemap, e);
    }
}

From source file:com.act.lcms.MS2Simple.java

private void plot(List<Pair<MS2Collected, Integer>> ms2Spectra, Double mz, List<Double> ms2SearchMZs,
        String outPrefix, String fmt) throws IOException {
    String outPDF = outPrefix + "." + fmt;
    String outDATA = outPrefix + ".data";

    // Write data output to outfile
    PrintStream out = new PrintStream(new FileOutputStream(outDATA));

    List<String> plotID = new ArrayList<>(ms2Spectra.size());
    for (Pair<MS2Collected, Integer> pair : ms2Spectra) {
        MS2Collected yzSlice = pair.getLeft();
        String caption;//  w w  w.ja  va  2s .c  o  m
        if (ms2SearchMZs != null && ms2SearchMZs.size() > 0) {
            caption = String.format("target: %.4f, time: %.4f, volts: %.4f, %d / %d matches",
                    yzSlice.triggerMass, yzSlice.triggerTime, yzSlice.voltage,
                    pair.getRight() == null ? 0 : pair.getRight(), ms2SearchMZs.size());
        } else {
            caption = String.format("target: %.4f, time: %.4f, volts: %.4f", yzSlice.triggerMass,
                    yzSlice.triggerTime, yzSlice.voltage);
        }
        plotID.add(caption);
        // Compute the total intensity on the fly so we can plot on a percentage scale.
        double maxIntensity = 0.0;
        for (YZ yz : yzSlice.ms2) {
            if (yz.intensity > maxIntensity) {
                maxIntensity = yz.intensity;
            }
        }
        // print out the spectra to outDATA
        for (YZ yz : yzSlice.ms2) {
            out.format("%.4f\t%.4f\n", yz.mz, 100.0 * yz.intensity / maxIntensity);
            out.flush();
        }
        // delimit this dataset from the rest
        out.print("\n\n");
    }

    // close the .data
    out.close();

    // render outDATA to outPDF using gnuplot
    // 105.0 here means 105% for the y-range of a [0%:100%] plot. We want to leave some buffer space at
    // at the top, and hence we go a little outside of the 100% max range.
    /* We intend to plot the fragmentation pattern, and so do not expect to see fragments that are bigger than the
     * original selected molecule.  We truncate the x-range to the specified m/z but since that will make values close
     * to the max hard to see we add a buffer and truncate the plot in the x-range to m/z + 50.0. */
    new Gnuplotter().plot2DImpulsesWithLabels(outDATA, outPDF, plotID.toArray(new String[plotID.size()]),
            mz + 50.0, "mz", 105.0, "intensity (%)", fmt);
}

From source file:org.apache.jackrabbit.oak.plugins.document.rdb.RDBExport.java

private static void dumpJDBC(String url, String user, String pw, String table, String query, Format format,
        PrintStream out, List<String> fieldNames, RDBDocumentSerializer ser) throws SQLException {
    String driver = RDBJDBCTools.driverForDBType(RDBJDBCTools.jdbctype(url));
    try {// w  w w.  ja v  a2  s  .c o m
        Class.forName(driver);
    } catch (ClassNotFoundException ex) {
        System.err.println(
                RDBExport.class.getName() + ":attempt to load class " + driver + " failed:" + ex.getMessage());
    }
    Connection c = DriverManager.getConnection(url, user, pw);
    c.setReadOnly(true);
    Statement stmt = c.createStatement();
    String sql = "select ID, MODIFIED, MODCOUNT, CMODCOUNT, HASBINARY, DELETEDONCE, DATA, BDATA from " + table;
    if (query != null) {
        sql += " where " + query;
    }
    sql += " order by id";
    ResultSet rs = stmt.executeQuery(sql);

    if (format == Format.JSONARRAY) {
        out.println("[");
    } else if (format == Format.CSV) {
        out.println(dumpFieldNames(fieldNames));
    }
    boolean needComma = format == Format.JSONARRAY;
    ResultSetMetaData rsm = null;
    boolean idIsAscii = true;
    while (rs.next()) {
        if (rsm == null) {
            rsm = rs.getMetaData();
            idIsAscii = !isBinaryType(rsm.getColumnType(1));
        }
        String id = idIsAscii ? rs.getString("ID") : new String(rs.getBytes("ID"), UTF8);
        long modified = rs.getLong("MODIFIED");
        long modcount = rs.getLong("MODCOUNT");
        long cmodcount = rs.getLong("CMODCOUNT");
        long hasBinary = rs.getLong("HASBINARY");
        long deletedOnce = rs.getLong("DELETEDONCE");
        String data = rs.getString("DATA");
        byte[] bdata = rs.getBytes("BDATA");

        RDBRow row = new RDBRow(id, hasBinary == 1, deletedOnce == 1, modified, modcount, cmodcount, data,
                bdata);
        StringBuilder fulljson = dumpRow(ser, id, row);
        if (format == Format.CSV) {
            out.println(asCSV(fieldNames, fulljson));
        } else {
            fulljson = asJSON(fieldNames, fulljson);
            if (format == Format.JSONARRAY && needComma && !rs.isLast()) {
                fulljson.append(",");
            }
            out.println(fulljson);
            needComma = true;
        }
    }
    if (format == Format.JSONARRAY) {
        out.println("]");
    }
    out.close();
    rs.close();
    stmt.close();
    c.close();
}

From source file:edu.umn.cs.spatialHadoop.nasa.MultiHDFPlot.java

private static void createKML(FileSystem outFs, Path output, Rectangle mbr, OperationsParams params)
        throws IOException, ParseException {
    FileStatus[] all_images = outFs.listStatus(output, new PathFilter() {
        @Override/*from  ww  w.  j av a2  s .com*/
        public boolean accept(Path path) {
            return path.getName().matches("\\d+\\.\\d+\\.\\d+\\.png");
        }
    });

    Path kmlPath = new Path(output, "index.kml");
    PrintStream ps = new PrintStream(outFs.create(kmlPath));
    ps.println("<?xml version='1.0' encoding='UTF-8'?>");
    ps.println("<kml xmlns='http://www.opengis.net/kml/2.2'>");
    ps.println("<Folder>");
    String mbrStr = String.format(
            "<LatLonBox><west>%f</west><south>%f</south><east>%f</east><north>%f</north></LatLonBox>", mbr.x1,
            mbr.y1, mbr.x2, mbr.y2);
    for (FileStatus image : all_images) {
        SimpleDateFormat fileDateFormat = new SimpleDateFormat("yyyy.MM.dd");
        SimpleDateFormat kmlDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String name = image.getPath().getName();
        int dotIndex = name.lastIndexOf('.');
        name = name.substring(0, dotIndex);
        Date date = fileDateFormat.parse(name);
        String kmlDate = kmlDateFormat.format(date);
        ps.println("<GroundOverlay>");
        ps.println("<name>" + kmlDate + "</name>");
        ps.println("<TimeStamp><when>" + kmlDate + "</when></TimeStamp>");
        ps.println("<Icon><href>" + image.getPath().getName() + "</href></Icon>");
        ps.println(mbrStr);
        ps.println("</GroundOverlay>");
    }
    String scale = params.get("scale", "none").toLowerCase();
    if (scale.equals("vertical")) {
        ps.println("<ScreenOverlay>");
        ps.println("<name>Scale</name>");
        ps.println("<Icon><href>scale.png</href></Icon>");
        ps.println("<overlayXY x='1' y='0.5' xunits='fraction' yunits='fraction'/>");
        ps.println("<screenXY x='1' y='0.5' xunits='fraction' yunits='fraction'/>");
        ps.println("<rotationXY x='0' y='0' xunits='fraction' yunits='fraction'/>");
        ps.println("<size x='0' y='0.7' xunits='fraction' yunits='fraction'/>");
        ps.println("</ScreenOverlay>");
    } else if (scale.equals("horizontal")) {
        ps.println("<ScreenOverlay>");
        ps.println("<name>Scale</name>");
        ps.println("<Icon><href>scale.png</href></Icon>");
        ps.println("<overlayXY x='0.5' y='0' xunits='fraction' yunits='fraction'/>");
        ps.println("<screenXY x='0.5' y='0' xunits='fraction' yunits='fraction'/>");
        ps.println("<rotationXY x='0' y='0' xunits='fraction' yunits='fraction'/>");
        ps.println("<size x='0.7' y='0' xunits='fraction' yunits='fraction'/>");
        ps.println("</ScreenOverlay>");
    }
    ps.println("</Folder>");
    ps.println("</kml>");
    ps.close();
}

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  w w  . j  a v  a  2s  .  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:com.surevine.alfresco.webscript.gsa.getallitems.GetAllItemsCommandWebscriptImpl.java

@Override
/**//w ww.ja v  a 2s .c o m
 * Webscript execute method, and the entry-point for this class under normal operation
 */
public void execute(WebScriptRequest request, WebScriptResponse response) throws IOException {
    PrintStream ps = null;

    try {
        ps = new PrintStream(response.getOutputStream());
        GetAllItemsParameters params = getParametersFromRequest(request);
        if (_logger.isInfoEnabled()) {
            _logger.info("WebScript called with " + params);
        }
        SearchResults modelResults = executeCommand(params);
        String responseString = createXMLResponse(modelResults);

        if (_logger.isDebugEnabled()) {
            _logger.debug("Response Length: " + responseString.length()); //We used to log the whole string but this was OOMing 
        }
        ps.println(responseString);

    }
    //If we catch an exception, return an appropriate HTTP response code and a summary of the exception, then dump the full
    //details of the exception to the logs.  Non-GSA Exceptions are wrapped, non-Exception Throwables are left to percolate upward
    catch (GSAInvalidParameterException e) {
        response.setStatus(400); //Something wrong with the parameters so we use Bad Request
        ps.println(e);
        _logger.error(e.getMessage(), e);
    } catch (GSAProcessingException exx) {
        response.setStatus(500); //Internal Server Error
        ps.println(exx);
        _logger.error(exx.getMessage(), exx);
    } catch (Exception ex) {
        response.setStatus(500);
        ps.println(new GSAProcessingException("Exception occured processing the commanmd: " + ex, ex, 1000));
        _logger.error(ex.getMessage(), ex);
    } finally {
        if (ps != null) {
            ps.close();
        }
    }
}

From source file:com.algollabs.rgx.java

/**
 * Handles an API Construct request./*ww  w .j  a va  2 s. co m*/
 *
 * Request JSON structure:
 * {
 *   "pattern": "json_encoded_regex",
 *   "subject": "string",
 *   "flags": ""
 * }
 *
 */
private void testExpression(Request request, Response response, PrintStream stream) {
    try {
        String ptrn = null;
        String subj = null;
        String flags = null;

        // parse the required attributes: pattern, subject, and flags

        JsonElement jsonElement = parser_.parse(request.getContent());
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            String k = entry.getKey();
            JsonElement v = entry.getValue();

            if (k.equals("pattern")) {
                ptrn = gson_.fromJson(v, String.class);
            } else if (k.equals("subject")) {
                subj = gson_.fromJson(v, String.class);
            } else if (k.equals("flags")) {
                flags = gson_.fromJson(v, String.class);
            } else {
                throw new UnrecognizedAttributeException(k);
            }
        }

        // have a Construct test the expression
        stream.println((new Construct(ptrn, subj, flags, true)).test());
        response.setStatus(Status.OK);
    } catch (UnrecognizedAttributeException e) {
        e.printStackTrace();

        response.setStatus(Status.BAD_REQUEST);
        stream.println(e.getMessage());

    } catch (Exception e) {
        e.printStackTrace();

        response.setStatus(Status.INTERNAL_SERVER_ERROR);
        stream.println(e.getMessage());
    }

    stream.close();
}