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:edu.msu.cme.rdp.classifier.train.validation.distance.TaxaSimilarityMain.java

public void createPlot(String plotTitle, File outdir) throws IOException {
    XYSeriesCollection dataset = new XYSeriesCollection();
    DefaultBoxAndWhiskerCategoryDataset scatterDataset = new DefaultBoxAndWhiskerCategoryDataset();

    PrintStream boxchart_dataStream = new PrintStream(new File(outdir, plotTitle + ".boxchart.txt"));

    boxchart_dataStream.println(//from   ww w  .  j  a  v  a 2 s . c o  m
            "#\tkmer" + "\trank" + "\t" + "max" + "\t" + "avg" + "\t" + "min" + "\t" + "Q1" + "\t" + "median"
                    + "\t" + "Q3" + "\t" + "98Pct" + "\t" + "2Pct" + "\t" + "comparisons" + "\t" + "sum");
    for (int i = 0; i < ranks.size(); i++) {
        long[] countArray = sabCoutMap.get(ranks.get(i));
        if (countArray == null)
            continue;

        double sum = 0.0;
        int max = 0;
        int min = 100;
        double mean = 0;
        int Q1 = -1;
        int median = -1;
        int Q3 = -1;
        int pct_98 = -1;
        int pct_2 = -1;
        long comparisons = 0;
        int minOutlier = 0; // we don't care about the outliers
        int maxOutlier = 0; //

        XYSeries series = new XYSeries(ranks.get(i));

        for (int c = 0; c < countArray.length; c++) {
            if (countArray[c] == 0)
                continue;
            comparisons += countArray[c];
            sum += countArray[c] * c;
            if (c < min) {
                min = c;
            }
            if (c > max) {
                max = c;
            }
        }

        // create series
        double cum = 0;
        for (int c = 0; c < countArray.length; c++) {
            if (countArray[c] == 0)
                continue;
            cum += countArray[c];
            int pct = (int) Math.floor(100 * cum / comparisons);
            series.add(c, pct);

            if (pct_2 == -1 && pct >= 5) {
                pct_2 = c;
            }
            if (Q3 == -1 && pct >= 25) {
                Q3 = c;
            }
            if (median == -1 && pct >= 50) {
                median = c;
            }
            if (Q1 == -1 && pct >= 75) {
                Q1 = c;
            }
            if (pct_98 == -1 && pct >= 98) {
                pct_98 = c;
            }
        }
        if (!series.isEmpty()) {
            dataset.addSeries(series);

            BoxAndWhiskerItem item = new BoxAndWhiskerItem(sum / comparisons, median, Q1, Q3, pct_2, pct_98,
                    minOutlier, maxOutlier, new ArrayList());
            scatterDataset.add(item, ranks.get(i), "");

            boxchart_dataStream.println("#\t" + GoodWordIterator.getWordsize() + "\t" + ranks.get(i) + "\t"
                    + max + "\t" + format.format(sum / comparisons) + "\t" + min + "\t" + Q1 + "\t" + median
                    + "\t" + Q3 + "\t" + pct_98 + "\t" + pct_2 + "\t" + comparisons + "\t" + sum);
        }
    }
    boxchart_dataStream.close();
    Font lableFont = new Font("Helvetica", Font.BOLD, 28);

    JFreeChart chart = ChartFactory.createXYLineChart(plotTitle, "Similarity%", "Percent Comparisions", dataset,
            PlotOrientation.VERTICAL, true, true, false);
    ((XYPlot) chart.getPlot()).getRenderer().setStroke(new BasicStroke(2.0f));
    chart.getLegend().setItemFont(new Font("Helvetica", Font.BOLD, 24));
    chart.getTitle().setFont(lableFont);
    ((XYPlot) chart.getPlot()).getDomainAxis().setLabelFont(lableFont);
    ((XYPlot) chart.getPlot()).getDomainAxis().setTickLabelFont(lableFont);
    ValueAxis rangeAxis = ((XYPlot) chart.getPlot()).getRangeAxis();
    rangeAxis.setRange(0, 100);
    rangeAxis.setTickLabelFont(lableFont);
    rangeAxis.setLabelFont(lableFont);
    ((NumberAxis) rangeAxis).setTickUnit(new NumberTickUnit(5));
    ChartUtilities.writeScaledChartAsPNG(new PrintStream(new File(outdir, plotTitle + ".linechart.png")), chart,
            800, 1000, 3, 3);

    BoxPlotUtils.createBoxplot(scatterDataset, new PrintStream(new File(outdir, plotTitle + ".boxchart.png")),
            plotTitle, "Rank", "Similarity%", lableFont);

}

From source file:com.vonglasow.michael.satstat.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);
            File dumpFile = new File(dumpDir, "satstat-" + System.currentTimeMillis() + ".log");
            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  ww  w  . j  a  va2s.  c  o m
                        i = buildInStream.read();
                    }
                    buildInStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                s.append("\n\n");
                e.printStackTrace(s);
                s.flush();
                s.close();
            } catch (FileNotFoundException e2) {
                e2.printStackTrace();
            }
            defaultUEH.uncaughtException(t, e);
        }
    });

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mSharedPreferences.registerOnSharedPreferenceChangeListener(this);

    final ActionBar actionBar = getActionBar();

    setContentView(R.layout.activity_main);

    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // 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("MainActivity", "isWideScreen=" + Boolean.toString(isWideScreen));

    // compact action bar
    int dpX = (int) (this.getResources().getDisplayMetrics().widthPixels
            / this.getResources().getDisplayMetrics().density);
    /*
     * This is a crude way to ensure a one-line action bar with tabs
     * (not a drop-down list) and home (incon) and title only if there
     * is space, depending on screen width:
     * divide screen in units of 64 dp
     * each tab requires 1 unit, home and menu require slightly less,
     * title takes up approx. 2.5 units in portrait,
     * home and title are about 2 units wide in landscape
     */
    if (dpX < 192) {
        // just enough space for drop-down list and menu
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
    } else if (dpX < 320) {
        // not enough space for four tabs, but home will fit next to list
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
    } else if (dpX < 384) {
        // just enough space for four tabs
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
    } else if ((dpX < 448) || ((config.orientation == Configuration.ORIENTATION_PORTRAIT) && (dpX < 544))) {
        // space for four tabs and home, but not title
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
    } else {
        // ample space for home, title and all four tabs
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
    }
    setEmbeddedTabs(actionBar, true);

    providerLocations = new HashMap<String, Location>();

    mAvailableProviderStyles = new ArrayList<String>(Arrays.asList(LOCATION_PROVIDER_STYLES));

    providerStyles = new HashMap<String, String>();
    providerAppliedStyles = new HashMap<String, String>();

    providerInvalidationHandler = new Handler();
    providerInvalidators = new HashMap<String, Runnable>();

    // Create the adapter that will return a fragment for each of the three
    // 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);
    mViewPager.setOnPageChangeListener(this);

    // Add tabs, specifying the tab's text and TabListener
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        actionBar.addTab(actionBar.newTab()
                //.setText(mSectionsPagerAdapter.getPageTitle(i))
                .setIcon(mSectionsPagerAdapter.getPageIcon(i)).setTabListener(this));
    }

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

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

    mAccSensorRes = getSensorDecimals(mAccSensor, mAccSensorRes);
    mGyroSensorRes = getSensorDecimals(mGyroSensor, mGyroSensorRes);
    mMagSensorRes = getSensorDecimals(mMagSensor, mMagSensorRes);
    mLightSensorRes = getSensorDecimals(mLightSensor, mLightSensorRes);
    mProximitySensorRes = getSensorDecimals(mProximitySensor, mProximitySensorRes);
    mPressureSensorRes = getSensorDecimals(mPressureSensor, mPressureSensorRes);
    mHumiditySensorRes = getSensorDecimals(mHumiditySensor, mHumiditySensorRes);
    mTempSensorRes = getSensorDecimals(mTempSensor, mTempSensorRes);

    networkTimehandler = new Handler();
    networkTimeRunnable = new Runnable() {
        @Override
        public void run() {
            int newNetworkType = mTelephonyManager.getNetworkType();
            if (getNetworkGeneration(newNetworkType) != mLastNetworkGen)
                onNetworkTypeChanged(newNetworkType);
            else
                networkTimehandler.postDelayed(this, NETWORK_REFRESH_DELAY);
        }
    };

    wifiTimehandler = new Handler();
    wifiTimeRunnable = new Runnable() {

        @Override
        public void run() {
            mWifiManager.startScan();
            wifiTimehandler.postDelayed(this, WIFI_REFRESH_DELAY);
        }
    };

    updateLocationProviderStyles();
}

From source file:org.apache.oozie.cli.OozieCLI.java

private void jobCommand(CommandLine commandLine) throws IOException, OozieCLIException {
    XOozieClient wc = createXOozieClient(commandLine);

    List<String> options = new ArrayList<String>();
    for (Option option : commandLine.getOptions()) {
        options.add(option.getOpt());//www.  j a  va2s  .  c  om
    }

    try {
        if (options.contains(SUBMIT_OPTION)) {
            System.out.println(JOB_ID_PREFIX + wc.submit(getConfiguration(wc, commandLine)));
        } else if (options.contains(START_OPTION)) {
            wc.start(commandLine.getOptionValue(START_OPTION));
        } else if (options.contains(DRYRUN_OPTION) && !options.contains(UPDATE_OPTION)) {
            String dryrunStr = wc.dryrun(getConfiguration(wc, commandLine));
            if (dryrunStr.equals("OK")) { // workflow
                System.out.println("OK");
            } else { // coordinator
                String[] dryrunStrs = dryrunStr.split("action for new instance");
                int arraysize = dryrunStrs.length;
                System.out.println("***coordJob after parsing: ***");
                System.out.println(dryrunStrs[0]);
                int aLen = dryrunStrs.length - 1;
                if (aLen < 0) {
                    aLen = 0;
                }
                System.out.println("***total coord actions is " + aLen + " ***");
                for (int i = 1; i <= arraysize - 1; i++) {
                    System.out.println(RULER);
                    System.out.println("coordAction instance: " + i + ":");
                    System.out.println(dryrunStrs[i]);
                }
            }
        } else if (options.contains(SUSPEND_OPTION)) {
            wc.suspend(commandLine.getOptionValue(SUSPEND_OPTION));
        } else if (options.contains(RESUME_OPTION)) {
            wc.resume(commandLine.getOptionValue(RESUME_OPTION));
        } else if (options.contains(IGNORE_OPTION)) {
            String ignoreScope = null;
            if (options.contains(ACTION_OPTION)) {
                ignoreScope = commandLine.getOptionValue(ACTION_OPTION);
                if (ignoreScope == null || ignoreScope.isEmpty()) {
                    throw new OozieCLIException("-" + ACTION_OPTION + " is empty");
                }
            }
            printCoordActionsStatus(wc.ignore(commandLine.getOptionValue(IGNORE_OPTION), ignoreScope));
        } else if (options.contains(KILL_OPTION)) {
            if (commandLine.getOptionValue(KILL_OPTION).contains("-C")
                    && (options.contains(DATE_OPTION) || options.contains(ACTION_OPTION))) {
                String coordJobId = commandLine.getOptionValue(KILL_OPTION);
                String scope = null;
                String rangeType = null;
                if (options.contains(DATE_OPTION) && options.contains(ACTION_OPTION)) {
                    throw new OozieCLIException("Invalid options provided for rerun: either" + DATE_OPTION
                            + " or " + ACTION_OPTION + " expected. Don't use both at the same time.");
                }
                if (options.contains(DATE_OPTION)) {
                    rangeType = RestConstants.JOB_COORD_SCOPE_DATE;
                    scope = commandLine.getOptionValue(DATE_OPTION);
                } else if (options.contains(ACTION_OPTION)) {
                    rangeType = RestConstants.JOB_COORD_SCOPE_ACTION;
                    scope = commandLine.getOptionValue(ACTION_OPTION);
                } else {
                    throw new OozieCLIException("Invalid options provided for rerun: " + DATE_OPTION + " or "
                            + ACTION_OPTION + " expected.");
                }
                printCoordActions(wc.kill(coordJobId, rangeType, scope));
            } else {
                wc.kill(commandLine.getOptionValue(KILL_OPTION));
            }
        } else if (options.contains(CHANGE_OPTION)) {
            wc.change(commandLine.getOptionValue(CHANGE_OPTION), getChangeValue(commandLine));
        } else if (options.contains(RUN_OPTION)) {
            System.out.println(JOB_ID_PREFIX + wc.run(getConfiguration(wc, commandLine)));
        } else if (options.contains(RERUN_OPTION)) {
            if (commandLine.getOptionValue(RERUN_OPTION).contains("-W")) {
                if (isConfigurationSpecified(wc, commandLine)) {
                    wc.reRun(commandLine.getOptionValue(RERUN_OPTION), getConfiguration(wc, commandLine));
                } else {
                    wc.reRun(commandLine.getOptionValue(RERUN_OPTION), new Properties());
                }
            } else if (commandLine.getOptionValue(RERUN_OPTION).contains("-B")) {
                String bundleJobId = commandLine.getOptionValue(RERUN_OPTION);
                String coordScope = null;
                String dateScope = null;
                boolean refresh = false;
                boolean noCleanup = false;
                if (options.contains(ACTION_OPTION)) {
                    throw new OozieCLIException("Invalid options provided for bundle rerun. " + ACTION_OPTION
                            + " is not valid for bundle rerun");
                }
                if (options.contains(DATE_OPTION)) {
                    dateScope = commandLine.getOptionValue(DATE_OPTION);
                }

                if (options.contains(COORD_OPTION)) {
                    coordScope = commandLine.getOptionValue(COORD_OPTION);
                }

                if (options.contains(RERUN_REFRESH_OPTION)) {
                    refresh = true;
                }
                if (options.contains(RERUN_NOCLEANUP_OPTION)) {
                    noCleanup = true;
                }
                wc.reRunBundle(bundleJobId, coordScope, dateScope, refresh, noCleanup);
                if (coordScope != null && !coordScope.isEmpty()) {
                    System.out.println("Coordinators [" + coordScope + "] of bundle " + bundleJobId
                            + " are scheduled to rerun on date ranges [" + dateScope + "].");
                } else {
                    System.out.println("All coordinators of bundle " + bundleJobId
                            + " are scheduled to rerun on the date ranges [" + dateScope + "].");
                }
            } else {
                String coordJobId = commandLine.getOptionValue(RERUN_OPTION);
                String scope = null;
                String rerunType = null;
                boolean refresh = false;
                boolean noCleanup = false;
                boolean failed = false;
                if (options.contains(DATE_OPTION) && options.contains(ACTION_OPTION)) {
                    throw new OozieCLIException("Invalid options provided for rerun: either" + DATE_OPTION
                            + " or " + ACTION_OPTION + " expected. Don't use both at the same time.");
                }
                if (options.contains(DATE_OPTION)) {
                    rerunType = RestConstants.JOB_COORD_SCOPE_DATE;
                    scope = commandLine.getOptionValue(DATE_OPTION);
                } else if (options.contains(ACTION_OPTION)) {
                    rerunType = RestConstants.JOB_COORD_SCOPE_ACTION;
                    scope = commandLine.getOptionValue(ACTION_OPTION);
                } else {
                    throw new OozieCLIException("Invalid options provided for rerun: " + DATE_OPTION + " or "
                            + ACTION_OPTION + " expected.");
                }
                if (options.contains(RERUN_REFRESH_OPTION)) {
                    refresh = true;
                }
                if (options.contains(RERUN_NOCLEANUP_OPTION)) {
                    noCleanup = true;
                }

                Properties props = null;
                if (isConfigurationSpecified(wc, commandLine)) {
                    props = getConfiguration(wc, commandLine);
                }

                if (options.contains(RERUN_FAILED_OPTION)) {
                    failed = true;
                }

                printCoordActions(
                        wc.reRunCoord(coordJobId, rerunType, scope, refresh, noCleanup, failed, props));
            }
        } else if (options.contains(INFO_OPTION)) {
            String timeZoneId = getTimeZoneId(commandLine);
            final String optionValue = commandLine.getOptionValue(INFO_OPTION);
            if (optionValue.endsWith("-B")) {
                String filter = commandLine.getOptionValue(FILTER_OPTION);
                if (filter != null) {
                    throw new OozieCLIException("Filter option is currently not supported for a Bundle job");
                }
                printBundleJob(wc.getBundleJobInfo(optionValue), timeZoneId, options.contains(VERBOSE_OPTION));
            } else if (optionValue.endsWith("-C")) {
                String s = commandLine.getOptionValue(OFFSET_OPTION);
                int start = Integer.parseInt((s != null) ? s : "-1");
                s = commandLine.getOptionValue(LEN_OPTION);
                int len = Integer.parseInt((s != null) ? s : "-1");
                String filter = commandLine.getOptionValue(FILTER_OPTION);
                String order = commandLine.getOptionValue(ORDER_OPTION);
                printCoordJob(wc.getCoordJobInfo(optionValue, filter, start, len, order), timeZoneId,
                        options.contains(VERBOSE_OPTION));
            } else if (optionValue.contains("-C@")) {
                if (options.contains(ALL_WORKFLOWS_FOR_COORD_ACTION)) {
                    printWfsForCoordAction(wc.getWfsForCoordAction(optionValue), timeZoneId);
                } else {
                    String filter = commandLine.getOptionValue(FILTER_OPTION);
                    if (filter != null) {
                        throw new OozieCLIException("Filter option is not supported for a Coordinator action");
                    }
                    printCoordAction(wc.getCoordActionInfo(optionValue), timeZoneId);
                }
            } else if (optionValue.contains("-W@")) {
                String filter = commandLine.getOptionValue(FILTER_OPTION);
                if (filter != null) {
                    throw new OozieCLIException("Filter option is not supported for a Workflow action");
                }
                printWorkflowAction(wc.getWorkflowActionInfo(optionValue), timeZoneId,
                        options.contains(VERBOSE_OPTION));

            } else {
                String filter = commandLine.getOptionValue(FILTER_OPTION);
                if (filter != null) {
                    throw new OozieCLIException("Filter option is currently not supported for a Workflow job");
                }
                String s = commandLine.getOptionValue(OFFSET_OPTION);
                int start = Integer.parseInt((s != null) ? s : "0");
                s = commandLine.getOptionValue(LEN_OPTION);
                String jobtype = commandLine.getOptionValue(JOBTYPE_OPTION);
                jobtype = (jobtype != null) ? jobtype : "wf";
                int len = Integer.parseInt((s != null) ? s : "0");
                printJob(wc.getJobInfo(optionValue, start, len), timeZoneId, options.contains(VERBOSE_OPTION));
            }
        } else if (options.contains(LOG_OPTION)) {
            PrintStream ps = System.out;
            String logFilter = null;
            if (options.contains(RestConstants.LOG_FILTER_OPTION)) {
                logFilter = commandLine.getOptionValue(RestConstants.LOG_FILTER_OPTION);
            }
            if (commandLine.getOptionValue(LOG_OPTION).contains("-C")) {
                String logRetrievalScope = null;
                String logRetrievalType = null;
                if (options.contains(ACTION_OPTION)) {
                    logRetrievalType = RestConstants.JOB_LOG_ACTION;
                    logRetrievalScope = commandLine.getOptionValue(ACTION_OPTION);
                }
                if (options.contains(DATE_OPTION)) {
                    logRetrievalType = RestConstants.JOB_LOG_DATE;
                    logRetrievalScope = commandLine.getOptionValue(DATE_OPTION);
                }
                try {
                    wc.getJobLog(commandLine.getOptionValue(LOG_OPTION), logRetrievalType, logRetrievalScope,
                            logFilter, ps);
                } finally {
                    ps.close();
                }
            } else {
                if (!options.contains(ACTION_OPTION) && !options.contains(DATE_OPTION)) {
                    wc.getJobLog(commandLine.getOptionValue(LOG_OPTION), null, null, logFilter, ps);
                } else {
                    throw new OozieCLIException("Invalid options provided for log retrieval. " + ACTION_OPTION
                            + " and " + DATE_OPTION + " are valid only for coordinator job log retrieval");
                }
            }
        } else if (options.contains(ERROR_LOG_OPTION)) {
            PrintStream ps = System.out;
            try {
                wc.getJobErrorLog(commandLine.getOptionValue(ERROR_LOG_OPTION), ps);
            } finally {
                ps.close();
            }
        } else if (options.contains(AUDIT_LOG_OPTION)) {
            PrintStream ps = System.out;
            try {
                wc.getJobAuditLog(commandLine.getOptionValue(AUDIT_LOG_OPTION), ps);
            } finally {
                ps.close();
            }
        } else if (options.contains(DEFINITION_OPTION)) {
            System.out.println(wc.getJobDefinition(commandLine.getOptionValue(DEFINITION_OPTION)));
        } else if (options.contains(CONFIG_CONTENT_OPTION)) {
            if (commandLine.getOptionValue(CONFIG_CONTENT_OPTION).endsWith("-C")) {
                System.out.println(
                        wc.getCoordJobInfo(commandLine.getOptionValue(CONFIG_CONTENT_OPTION)).getConf());
            } else if (commandLine.getOptionValue(CONFIG_CONTENT_OPTION).endsWith("-W")) {
                System.out.println(wc.getJobInfo(commandLine.getOptionValue(CONFIG_CONTENT_OPTION)).getConf());
            } else if (commandLine.getOptionValue(CONFIG_CONTENT_OPTION).endsWith("-B")) {
                System.out.println(
                        wc.getBundleJobInfo(commandLine.getOptionValue(CONFIG_CONTENT_OPTION)).getConf());
            } else {
                System.out.println("ERROR:  job id [" + commandLine.getOptionValue(CONFIG_CONTENT_OPTION)
                        + "] doesn't end with either C or W or B");
            }
        } else if (options.contains(UPDATE_OPTION)) {
            String coordJobId = commandLine.getOptionValue(UPDATE_OPTION);
            Properties conf = null;

            String dryrun = "";
            String showdiff = "";

            if (commandLine.getOptionValue(CONFIG_OPTION) != null) {
                conf = getConfiguration(wc, commandLine);
            }
            if (options.contains(DRYRUN_OPTION)) {
                dryrun = "true";
            }
            if (commandLine.getOptionValue(SHOWDIFF_OPTION) != null) {
                showdiff = commandLine.getOptionValue(SHOWDIFF_OPTION);
            }
            if (conf == null) {
                System.out.println(wc.updateCoord(coordJobId, dryrun, showdiff));
            } else {
                System.out.println(wc.updateCoord(coordJobId, conf, dryrun, showdiff));
            }
        } else if (options.contains(POLL_OPTION)) {
            String jobId = commandLine.getOptionValue(POLL_OPTION);
            int timeout = 30;
            int interval = 5;
            String timeoutS = commandLine.getOptionValue(TIMEOUT_OPTION);
            if (timeoutS != null) {
                timeout = Integer.parseInt(timeoutS);
            }
            String intervalS = commandLine.getOptionValue(INTERVAL_OPTION);
            if (intervalS != null) {
                interval = Integer.parseInt(intervalS);
            }
            boolean verbose = commandLine.hasOption(VERBOSE_OPTION);
            wc.pollJob(jobId, timeout, interval, verbose);
        } else if (options.contains(SLA_ENABLE_ALERT)) {
            slaAlertCommand(commandLine.getOptionValue(SLA_ENABLE_ALERT), wc, commandLine, options);
        } else if (options.contains(SLA_DISABLE_ALERT)) {
            slaAlertCommand(commandLine.getOptionValue(SLA_DISABLE_ALERT), wc, commandLine, options);
        } else if (options.contains(SLA_CHANGE)) {
            slaAlertCommand(commandLine.getOptionValue(SLA_CHANGE), wc, commandLine, options);
        } else if (options.contains(WORKFLOW_ACTIONS_RETRIES)) {
            printWorkflowActionRetries(
                    wc.getWorkflowActionRetriesInfo(commandLine.getOptionValue(WORKFLOW_ACTIONS_RETRIES)),
                    commandLine.getOptionValue(WORKFLOW_ACTIONS_RETRIES));
        } else if (options.contains(COORD_ACTION_MISSING_DEPENDENCIES)) {
            String actions = null, dates = null;

            if (options.contains(ACTION_OPTION)) {
                actions = commandLine.getOptionValue(ACTION_OPTION);
            }

            if (options.contains(DATE_OPTION)) {
                dates = commandLine.getOptionValue(DATE_OPTION);
            }
            wc.getCoordActionMissingDependencies(commandLine.getOptionValue(COORD_ACTION_MISSING_DEPENDENCIES),
                    actions, dates, System.out);
        }

    } catch (OozieClientException ex) {
        throw new OozieCLIException(ex.toString(), ex);
    }
}

From source file:de.juwimm.cms.remote.AdministrationServiceSpringImpl.java

/**
 * @see de.juwimm.cms.remote.AdministrationServiceSpring#exportXlsPersonData()
 *///from   w w w.  ja v a  2s  .c  o m
@Override
protected InputStream handleExportXlsPersonData() throws Exception {
    try {
        if (log.isInfoEnabled())
            log.info("exportXlsPersonData " + AuthenticationHelper.getUserName());
        File fle = File.createTempFile("XlsPersonData", ".xml.gz");
        FileOutputStream fout = new FileOutputStream(fle);
        PrintStream out = new PrintStream(fout, true, "UTF-8");

        UserHbm invoker = getUserHbmDao().load(AuthenticationHelper.getUserName());
        SiteHbm site = invoker.getActiveSite();
        if (log.isDebugEnabled())
            log.debug("Invoker is: " + invoker.getUserId() + " within Site " + site.getName());
        // header
        out.println("Titel,Vorname,Nachname,Adresse,PLZ,Ort,Telefon 1,Telefon 2,Fax,e-Mail,Einrichtung");
        Iterator<UnitHbm> it = getUnitHbmDao().findAll(site.getSiteId()).iterator();
        while (it.hasNext()) {
            UnitHbm currentUnit = it.next();

            Collection<PersonHbm> persons = getPersonHbmDao().findByUnit(currentUnit.getUnitId());
            for (PersonHbm currentPerson : persons) {
                Iterator<AddressHbm> addressIt = currentPerson.getAddresses().iterator();
                boolean hasAddress = false;
                while (addressIt.hasNext()) {
                    hasAddress = true;
                    AddressHbm currentAddress = addressIt.next();
                    out.print(currentPerson.getTitle() == null ? "," : currentPerson.getTitle() + ",");
                    out.print(currentPerson.getFirstname() == null ? "," : currentPerson.getFirstname() + ",");
                    out.print(currentPerson.getLastname() == null ? "," : currentPerson.getLastname() + ",");
                    String street = currentAddress.getStreet();
                    String streetNo = currentAddress.getStreetNr();
                    if (street == null)
                        street = "";
                    if (streetNo == null)
                        streetNo = "";
                    out.print(street + " " + streetNo + ",");
                    out.print(currentAddress.getZipCode() == null ? "," : currentAddress.getZipCode() + ",");
                    out.print(currentAddress.getCity() == null ? "," : currentAddress.getCity() + ",");
                    out.print(currentAddress.getPhone1() == null ? "," : currentAddress.getPhone1() + ",");
                    out.print(currentAddress.getPhone2() == null ? "," : currentAddress.getPhone2() + ",");
                    out.print(currentAddress.getFax() == null ? "," : currentAddress.getFax() + ",");
                    out.print(currentAddress.getEmail() == null ? "," : currentAddress.getEmail() + ",");
                    out.println(currentUnit.getName().trim());
                }
                if (!hasAddress) {
                    out.print(currentPerson.getTitle() == null ? "," : currentPerson.getTitle() + ",");
                    out.print(currentPerson.getFirstname() == null ? "," : currentPerson.getFirstname() + ",");
                    out.print(currentPerson.getLastname() == null ? ","
                            : currentPerson.getLastname() + ",,,,,,,,");
                    out.println(currentUnit.getName().trim());
                }
            }
        }
        if (log.isDebugEnabled())
            log.debug("Finished exportXlsPersonData");
        out.flush();
        out.close();
        out = null;
        return new FileInputStream(fle);
    } catch (Exception e) {
        throw new UserException(e.getMessage());
    }
}

From source file:fr.certu.chouette.command.Command.java

/**
 * @param beans/*from w  ww .ja va2  s . com*/
 * @param manager
 * @param parameters 
 * @throws ChouetteException
 */
private void executeValidate(List<NeptuneIdentifiedObject> beans,
        INeptuneManager<NeptuneIdentifiedObject> manager, Map<String, List<String>> parameters)
        throws ChouetteException {
    String fileName = getSimpleString(parameters, "file", "");
    boolean append = getBoolean(parameters, "append");

    Report valReport = manager.validate(null, beans, validationParameters);
    PrintStream stream = System.out;
    if (!fileName.isEmpty()) {
        try {
            stream = new PrintStream(new FileOutputStream(new File(fileName), append));
        } catch (FileNotFoundException e) {
            System.err.println("cannot open file :" + fileName);
            fileName = "";
        }
    }

    stream.println(valReport.getLocalizedMessage());
    printItems(stream, "", valReport.getItems());
    int nbUNCHECK = 0;
    int nbOK = 0;
    int nbWARN = 0;
    int nbERROR = 0;
    int nbFATAL = 0;
    for (ReportItem item1 : valReport.getItems()) // Categorie
    {
        for (ReportItem item2 : item1.getItems()) // fiche
        {
            for (ReportItem item3 : item2.getItems()) //test
            {
                STATE status = item3.getStatus();
                switch (status) {
                case UNCHECK:
                    nbUNCHECK++;
                    break;
                case OK:
                    nbOK++;
                    break;
                case WARNING:
                    nbWARN++;
                    break;
                case ERROR:
                    nbERROR++;
                    break;
                case FATAL:
                    nbFATAL++;
                    break;
                }

            }

        }
    }
    stream.println("Bilan : " + nbOK + " tests ok, " + nbWARN + " warnings, " + nbERROR + " erreurs, "
            + nbUNCHECK + " non effectus");
    if (!fileName.isEmpty()) {
        stream.close();
    }
}

From source file:org.apache.hadoop.hive.ql.exec.ExplainTask.java

@Override
public int execute(DriverContext driverContext) {

    PrintStream out = null;
    try {//w  w w . j  a  va 2s.c  o  m
        Path resFile = work.getResFile();
        OutputStream outS = resFile.getFileSystem(conf).create(resFile);
        out = new PrintStream(outS);

        if (work.isLogical()) {
            JSONObject jsonLogicalPlan = getJSONLogicalPlan(out, work);
            if (work.isFormatted()) {
                out.print(jsonLogicalPlan);
            }
        } else if (work.isAuthorize()) {
            JSONObject jsonAuth = collectAuthRelatedEntities(out, work);
            if (work.isFormatted()) {
                out.print(jsonAuth);
            }
        } else if (work.getDependency()) {
            JSONObject jsonDependencies = getJSONDependencies(work);
            out.print(jsonDependencies);
        } else {
            if (work.isUserLevelExplain()) {
                // Because of the implementation of the JsonParserFactory, we are sure
                // that we can get a TezJsonParser.
                JsonParser jsonParser = JsonParserFactory.getParser(conf);
                work.getConfig().setFormatted(true);
                JSONObject jsonPlan = getJSONPlan(out, work);
                if (work.getCboInfo() != null) {
                    jsonPlan.put("cboInfo", work.getCboInfo());
                }
                try {
                    jsonParser.print(jsonPlan, out);
                } catch (Exception e) {
                    // if there is anything wrong happen, we bail out.
                    LOG.error("Running explain user level has problem: " + e.toString()
                            + ". Falling back to normal explain");
                    work.getConfig().setFormatted(false);
                    work.getConfig().setUserLevelExplain(false);
                    jsonPlan = getJSONPlan(out, work);
                }
            } else {
                JSONObject jsonPlan = getJSONPlan(out, work);
                if (work.isFormatted()) {
                    // use the parser to get the output operators of RS
                    JsonParser jsonParser = JsonParserFactory.getParser(conf);
                    if (jsonParser != null) {
                        jsonParser.print(jsonPlan, null);
                        LOG.info("JsonPlan is augmented to " + jsonPlan.toString());
                    }
                    out.print(jsonPlan);
                }
            }
        }

        out.close();
        out = null;
        return (0);
    } catch (Exception e) {
        console.printError("Failed with exception " + e.getMessage(), "\n" + StringUtils.stringifyException(e));
        return (1);
    } finally {
        IOUtils.closeStream(out);
    }
}

From source file:de.juwimm.cms.remote.ViewServiceSpringImpl.java

@Override
protected InputStream handleExportViewComponent(Integer viewComponentId) throws Exception {
    File fle = File.createTempFile("view_component_export", ".xml.gz");
    FileOutputStream fout = new FileOutputStream(fle);
    GZIPOutputStream gzoudt = new GZIPOutputStream(fout);
    PrintStream out = new PrintStream(gzoudt, true, "UTF-8");
    out.print("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    out.print("<site>\n");
    out.print("<hostUrl>" + Constants.URL_HOST + "</hostUrl>\n");
    ViewComponentHbm viewComponent = getViewComponentHbmDao().load(viewComponentId);
    // TODO: depth 0 or 1 ???
    getViewComponentHbmDao().toXml(viewComponent, null, true, true, true, true, 0, true, false, out);

    ContentHbm content = getContentHbmDao().load(Integer.parseInt(viewComponent.getReference()));
    ContentVersionHbm contentVersion = content.getLastContentVersion();
    String contentVersionText = contentVersion.getText();
    if (contentVersionText != null) {
        Document doc = XercesHelper.string2Dom(contentVersionText);
        getMediaXML(doc, out, "picture", "description");
        getMediaXML(doc, out, "document", "src");
        getAggregationXML(doc, out);//  w  ww  .j av a  2 s . c o  m
    }
    out.print("</site>");
    out.flush();
    out.close();
    out = null;
    return new FileInputStream(fle);
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.sensitivity.SimpleStatistics.java

@Override
public void run(CommandLine commandLine) throws Exception {
    String mode = null;/*from  www .j a v a 2  s  .  com*/
    PrintStream out = null;
    List<double[][]> entries = new ArrayList<double[][]>();
    SummaryStatistics statistics = new SummaryStatistics();
    OptionCompleter completer = new OptionCompleter("minimum", "maximum", "average", "stdev", "count");

    //load data from all input files
    for (String filename : commandLine.getArgs()) {
        entries.add(load(new File(filename)));
    }

    //validate the inputs
    if (entries.isEmpty()) {
        throw new IllegalArgumentException("requires at least one file");
    }

    int numberOfRows = -1;
    int numberOfColumns = -1;

    for (int i = 0; i < entries.size(); i++) {
        if (numberOfRows == -1) {
            numberOfRows = entries.get(i).length;

            if (numberOfRows == 0) {
                throw new IllegalArgumentException("empty file: " + commandLine.getArgs()[i]);
            }
        } else if (numberOfRows != entries.get(i).length) {
            throw new IllegalArgumentException("unbalanced rows: " + commandLine.getArgs()[i]);
        }

        if (numberOfColumns == -1) {
            numberOfColumns = entries.get(i)[0].length;
        } else if (numberOfColumns != entries.get(i)[0].length) {
            throw new IllegalArgumentException("unbalanced columns: " + commandLine.getArgs()[i]);
        }
    }

    //setup the mode
    if (commandLine.hasOption("mode")) {
        mode = completer.lookup(commandLine.getOptionValue("mode"));

        if (mode == null) {
            throw new IllegalArgumentException("invalid mode");
        }
    } else {
        mode = "average";
    }

    try {
        //instantiate the writer
        if (commandLine.hasOption("output")) {
            out = new PrintStream(commandLine.getOptionValue("output"));
        } else {
            out = System.out;
        }

        //compute the statistics
        for (int i = 0; i < numberOfRows; i++) {
            for (int j = 0; j < numberOfColumns; j++) {
                statistics.clear();

                for (int k = 0; k < entries.size(); k++) {
                    double value = entries.get(k)[i][j];

                    if (Double.isInfinite(value) && commandLine.hasOption("maximum")) {
                        value = Double.parseDouble(commandLine.getOptionValue("maximum"));
                    }

                    if ((Double.isInfinite(value) || Double.isNaN(value)) && commandLine.hasOption("ignore")) {
                        // ignore infinity or NaN values
                    } else {
                        statistics.addValue(value);
                    }
                }

                if (j > 0) {
                    out.print(' ');
                }

                if (mode.equals("minimum")) {
                    out.print(statistics.getMin());
                } else if (mode.equals("maximum")) {
                    out.print(statistics.getMax());
                } else if (mode.equals("average")) {
                    out.print(statistics.getMean());
                } else if (mode.equals("stdev")) {
                    out.print(statistics.getStandardDeviation());
                } else if (mode.equals("count")) {
                    out.print(statistics.getN());
                } else {
                    throw new IllegalArgumentException("unknown mode: " + mode);
                }
            }

            out.println();
        }
    } finally {
        if ((out != null) && (out != System.out)) {
            out.close();
        }
    }
}

From source file:de.juwimm.cms.model.EditionHbmDaoImpl.java

private EditionHbm postCreate(EditionHbm edition, String comment, Integer rootViewComponentId, PrintStream out,
        boolean includeUnused) throws CreateException {
    if (log.isDebugEnabled())
        log.debug("Postcreating Edition");
    if (rootViewComponentId != null) {
        try {// w  ww  .j a va2  s .com
            UserHbm creator = getUserHbmDao().load(AuthenticationHelper.getUserName());
            edition.setCreator(creator);
        } catch (Exception exe) {
            log.warn("There went something wrong during ejbPostcreate and finding the right user", exe);
        }
        try {
            ViewComponentHbm vc = getViewComponentHbmDao().load(rootViewComponentId);

            Integer unitId = vc.getUnit4ViewComponent();
            Integer siteId = vc.getViewDocument().getSite().getSiteId();

            out.println("<edition>");

            if (log.isDebugEnabled())
                log.debug("picturesToXmlRecursive");
            this.picturesToXmlRecursive(unitId, siteId, out, edition);
            System.gc();
            if (log.isDebugEnabled())
                log.debug("documentsToXmlRecursive");
            this.documentsToXmlRecursive(unitId, siteId, out, includeUnused, edition);
            System.gc();
            if (vc.isRoot()) { // ROOT Deploy can only be done by a ROOT-User (and this must be automatically invoked!)
                if (log.isDebugEnabled())
                    log.debug("ROOT Deploy");
                this.hostsToXmlRecursive(siteId, out, edition);
                this.shortLinksToXmlRecursive(siteId, out, edition);
                this.unitsToXmlRecursive(siteId, out, edition);
                this.viewdocumentsToXmlRecursive(siteId, out, edition);
                this.realmsToXmlRecursive(siteId, out, edition);
            } else {
                UnitHbm unit = getUnitHbmDao().load(unitId);
                if (log.isDebugEnabled())
                    log.debug("Unit Export/Deploy " + unit.getUnitId() + "(" + unit.getName().trim() + ")");
                out.println("\t<units>");
                if (log.isDebugEnabled())
                    log.debug("unit.toXmlRecursive");
                this.unitsToXmlRecursive(siteId, out, edition);
                //            out.print(unit.toXmlRecursive(2));
                out.println("\t</units>");
                if (log.isDebugEnabled())
                    log.debug("realmsToXmlUsed");
                this.realmsToXmlUsed(unitId, out, edition);
            }
            System.gc();
            if (log.isDebugEnabled())
                log.debug("Creating ViewComponent Data");
            this.viewdocumentsToXmlRecursive(siteId, out, edition);
            //         vc.toXml(vc.getUnit4ViewComponent(), true, false, 0, 0, false, false, out);
            if (log.isDebugEnabled())
                log.debug("Finished creating ViewComponent Data");
            out.println("</edition>");

            edition.setUnitId(vc.getAssignedUnit().getUnitId().intValue());
            edition.setViewDocumentId(vc.getViewDocument().getViewDocumentId().intValue());

            out.flush();
            out.close();
            out = null;
            String siteConfig = vc.getViewDocument().getSite().getConfigXML();
            org.w3c.dom.Document doc = XercesHelper.string2Dom(siteConfig);
            String isEditionLimited = XercesHelper.getNodeValue(doc,
                    "/config/default/parameters/maxEditionStack_1");
            if (isEditionLimited != null && !"".equalsIgnoreCase(isEditionLimited)
                    && Boolean.valueOf(isEditionLimited).booleanValue()) {
                String maxEditionStack = XercesHelper.getNodeValue(doc,
                        "/config/default/parameters/maxEditionStack_2");
                if (maxEditionStack != null && !"".equalsIgnoreCase(maxEditionStack)) {
                    int max = Integer.valueOf(maxEditionStack);
                    // max must be > 0, otherwise the created edition would be deleted before the deploy
                    if (max > 0) {
                        if (log.isDebugEnabled())
                            log.debug("Site: " + siteId + " maxEditionStack: " + max);
                        Collection editions = findByUnitAndViewDocument(vc.getAssignedUnit().getUnitId(),
                                vc.getViewDocument().getViewDocumentId());
                        while (editions.size() > max) {
                            // get oldest edition
                            EditionHbm oldestEdition = null;
                            Iterator edIt = editions.iterator();
                            while (edIt.hasNext()) {
                                EditionHbm currentEdition = (EditionHbm) edIt.next();
                                if ((oldestEdition == null) || (currentEdition.getCreationDate() < oldestEdition
                                        .getCreationDate())) {
                                    oldestEdition = currentEdition;
                                }
                            }
                            if (oldestEdition != null) {
                                // delete oldest one
                                Date oldestCreateDate = new Date(oldestEdition.getCreationDate());
                                if (log.isDebugEnabled())
                                    log.debug("Deleting edition " + oldestEdition.getEditionId() + " of unit \""
                                            + vc.getAssignedUnit().getName().trim() + "\" (" + unitId
                                            + ") from " + sdf.format(oldestCreateDate) + " for language \""
                                            + vc.getViewDocument().getLanguage().trim() + "\"");
                                this.remove(oldestEdition);
                            }
                            editions = this.findByUnitAndViewDocument(vc.getAssignedUnit().getUnitId(),
                                    vc.getViewDocument().getViewDocumentId());
                        }
                    }
                }
            }
        } catch (Exception exe) {
            log.error("Error occured", exe);
        }
    }
    log.debug("Finished Postcreating Edition");
    return edition;
}

From source file:com.datatorrent.stram.cli.ApexCli.java

private void closeOutputPrintStream(PrintStream os) {
    if (os != System.out) {
        os.close();
        try {// w w  w. j  av  a2  s  . c  o  m
            pagerProcess.waitFor();
        } catch (InterruptedException ex) {
            LOG.debug("Interrupted");
        }
    }
}