Example usage for java.io PrintStream flush

List of usage examples for java.io PrintStream flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flushes the stream.

Usage

From source file:edu.cornell.med.icb.goby.modes.SequenceVariationStats2Mode.java

/**
 * Display sequence variations./*from w w w.  j  a  v  a 2s. c o  m*/
 *
 * @throws java.io.IOException error reading / writing
 */
@Override
public void execute() throws IOException {
    final PrintStream stream = outputFilename == null ? System.out
            : new PrintStream(new FileOutputStream(outputFilename));
    try {

        switch (outputFormat) {
        case TAB_DELIMITED:
        case TSV:
            stream.println(
                    "basename\tread-index\tcount-variation-bases\tbases-at-index/all-variations-bases\tbases-at-index/all-reference-bases\tcount-reference-bases\tcount-reference-bases-at-index");
            break;
        }

        DoInParallel loop = new DoInParallel() {
            @Override
            public void action(DoInParallel forDataAccess, String inputBasename, int loopIndex) {
                //To change body of implemented methods use File | Settings | File Templates.
                try {
                    MyIterateSortedAlignments iterator = new MyIterateSortedAlignments();
                    iterator.parseIncludeReferenceArgument(jsapResult);

                    final String[] singleBasename = { inputBasename };

                    // Iterate through each alignment and write sequence variations to output file:

                    iterator.iterate(singleBasename);

                    final long[] readIndexVariationTallies = iterator.getReadIndexVariationTally();
                    final long[] readIndexReferenceTallies = iterator.getReadIndexReferenceTally();
                    final double totalNumberOfVariationBases = sum(readIndexVariationTallies);
                    final double numberOfAlignmentEntries = iterator.getNumAlignmentEntries();

                    final long countReferenceBases = iterator.getReferenceBaseCount();
                    int maxReadIndex = iterator.getMaxReadIndex();
                    synchronized (this) {
                        for (int readIndex = 1; readIndex < maxReadIndex + 1; readIndex++) {
                            final long countVariationBasesAtReadIndex = readIndexVariationTallies[readIndex];
                            final long countReferenceBasesAtReadIndex = readIndexReferenceTallies[readIndex];
                            final double frequency = ((double) countVariationBasesAtReadIndex)
                                    / totalNumberOfVariationBases;
                            final double alignFrequency = ((double) countVariationBasesAtReadIndex)
                                    / countReferenceBases;

                            stream.printf("%s\t%d\t%d\t%s\t%f\t%d\t%d%n",
                                    FilenameUtils.getBaseName(inputBasename), readIndex,
                                    countVariationBasesAtReadIndex, frequency, alignFrequency,
                                    countReferenceBases, countReferenceBasesAtReadIndex);
                        }
                    }
                    stream.flush();
                } catch (IOException e) {
                    System.err.println(e);
                    e.printStackTrace();

                }
            }

        };
        try {
            loop.execute(true, basenames);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    finally

    {
        if (stream != System.out) {
            IOUtils.closeQuietly(stream);
        }
    }
}

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);// w  ww .ja v  a2 s  .  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:de.juwimm.cms.remote.AdministrationServiceSpringImpl.java

/**
 * @see de.juwimm.cms.remote.AdministrationServiceSpring#exportXlsPersonData()
 *///  w  ww . j  a v a  2 s . co  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:org.apache.slider.client.SliderClient.java

/**
  * list configs available for an instance
  *//from  www  .  j a v  a2  s  .  c  o  m
  * @param registryArgs registry Arguments
  * @throws YarnException YARN problems
  * @throws IOException Network or other problems
  */
public void actionRegistryListConfigsYarn(ActionRegistryArgs registryArgs) throws YarnException, IOException {

    ServiceRecord instance = lookupServiceRecord(registryArgs);

    RegistryRetriever retriever = new RegistryRetriever(instance);
    PublishedConfigSet configurations = retriever.getConfigurations(!registryArgs.internal);
    PrintStream out = null;
    try {
        if (registryArgs.out != null) {
            out = new PrintStream(new FileOutputStream(registryArgs.out));
        } else {
            out = System.out;
        }
        for (String configName : configurations.keys()) {
            if (!registryArgs.verbose) {
                out.println(configName);
            } else {
                PublishedConfiguration published = configurations.get(configName);
                out.printf("%s: %s\n", configName, published.description);
            }
        }
    } finally {
        if (registryArgs.out != null && out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:fr.univnantes.lina.UIMAProfiler.java

@Override
public void display(PrintStream stream) {
    if (isEmpty())
        return;/*from  w  w  w. j  a  v a 2  s . c om*/
    stream.println(
            "###########################################################################################");
    stream.println(
            "#################################### " + this.name + " ####################################");
    stream.println(
            "###########################################################################################");
    String formatString = "%30s %10sms\n";
    if (!tasks.isEmpty()) {
        stream.println("--------------- Tasks --------------");
        for (String taskName : tasks.keySet()) {
            long t = 0;
            for (ProfilingTask task : tasks.get(taskName))
                t += task.getTotal();
            stream.format(formatString, taskName, t);
        }
        stream.format(formatString, "TOTAL", getTotal());
    }
    if (!counters.isEmpty()) {
        stream.println("--------------- Hits ------------------");
        formatString = "%30s %10s\n";
        long total = 0;
        Comparator<String> comp = new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return Integer.compare(counters.get(o2).intValue(), counters.get(o1).intValue());
            }
        };
        List<String> sortedkeys = new LinkedList<String>();
        sortedkeys.addAll(counters.keySet());
        Collections.sort(sortedkeys, comp);
        for (String hitName : sortedkeys) {
            int h = counters.get(hitName).intValue();
            total += h;
            stream.format(formatString, hitName, h);
        }
        stream.format(formatString, "TOTAL", total);
        if (latexFormat) {
            stream.println("--------------- Hits (Latex) ----------");
            total = 0;
            sortedkeys = new LinkedList<String>();
            sortedkeys.addAll(counters.keySet());
            Collections.sort(sortedkeys, comp);
            for (String hitName : sortedkeys) {
                int h = counters.get(hitName).intValue();
                total += h;
                stream.println(hitName + " & " + counters.get(hitName).intValue() + " \\\\");
            }
            stream.println("TOTAL & " + total + " \\\\");
        }
    }
    if (!examples.isEmpty()) {
        stream.println("-------------- Examples ---------------");
        List<String> keySet = Lists.newArrayList(examples.keySet());
        Collections.shuffle(keySet);
        for (String hitName : keySet) {
            int i = 0;
            stream.println("* " + hitName);
            for (Object o : examples.get(hitName)) {
                i++;
                if (i > exampleLimit)
                    break;
                String str = o == null ? "null"
                        : o.toString().replaceAll("\n", " ").replaceAll("\r", " ").toLowerCase();
                stream.println("\t" + str);
            }
        }
    }
    if (!pointStatus.isEmpty()) {
        stream.println("-------------- Point status -----------");
        for (String point : pointStatus.keySet()) {
            stream.println(point + ": " + pointStatus.get(point));
        }
    }
    stream.flush();
}

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);/*from  w  w w.  j  a va2s.com*/
    }
    out.print("</site>");
    out.flush();
    out.close();
    out = null;
    return new FileInputStream(fle);
}

From source file:org.proteomecommons.tranche.cacheupdater.CacheUpdater.java

private void printFileTypeLog() {
    try {//w  w  w.  j a va 2s  .c  o m
        File fileTypeLogFile = new File(workingDirectory, "filetype.log");
        if (fileTypeLogFile.exists()) {
            fileTypeLogFile.delete();
        }
        if (!fileTypeLogFile.createNewFile()) {
            throw new RuntimeException("There was a problem creating the file type log file.");
        }
        PrintStream fileTypeLog = new PrintStream(new FileOutputStream(fileTypeLogFile));

        try {
            fileTypeLog.println("filetype\tfiles\tsize\tfileshr\tsizehr");
            for (String fileType : numFilesFileTypeMap.keySet()) {
                try {
                    String filesHR = GUIUtil.integerFormat
                            .format(numFilesFileTypeMap.get(fileType).longValue()),
                            sizeHR = Text.getFormattedBytes(sizeFileTypeMap.get(fileType).longValue());
                    fileTypeLog.println(fileType + "\t" + numFilesFileTypeMap.get(fileType).toString() + "\t"
                            + sizeFileTypeMap.get(fileType).toString() + "\t" + filesHR + "\t" + sizeHR);
                } catch (Exception e) {
                    // noop
                }
            }
        } finally {
            fileTypeLog.flush();
            fileTypeLog.close();
        }
    } catch (Exception e) {
        log.println("ERROR: Could not print file type log.");
        err.println(e.getMessage());
    }
}

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 w w . j a v a2 s . c om*/
            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:org.apache.slider.client.SliderClient.java

/**
 * list exports available for an instance
 *
 * @param registryArgs registry Arguments
 * @throws YarnException YARN problems// www . j a  va2 s  .c  o m
 * @throws IOException Network or other problems
 */
public void actionRegistryListExports(ActionRegistryArgs registryArgs) throws YarnException, IOException {
    ServiceRecord instance = lookupServiceRecord(registryArgs);

    RegistryRetriever retriever = new RegistryRetriever(instance);
    PublishedExportsSet exports = retriever.getExports(!registryArgs.internal);
    PrintStream out = null;
    boolean streaming = false;
    try {
        if (registryArgs.out != null) {
            out = new PrintStream(new FileOutputStream(registryArgs.out));
            streaming = true;
            log.debug("Saving output to {}", registryArgs.out);
        } else {
            out = System.out;
        }
        log.debug("Number of exports: {}", exports.keys().size());
        for (String exportName : exports.keys()) {
            if (streaming) {
                log.debug(exportName);
            }
            if (!registryArgs.verbose) {
                out.println(exportName);
            } else {
                PublishedExports published = exports.get(exportName);
                out.printf("%s: %s\n", exportName, published.description);
            }
        }
    } finally {
        if (streaming) {
            out.flush();
            out.close();
        }
    }
}