Example usage for java.util Formatter close

List of usage examples for java.util Formatter close

Introduction

In this page you can find the example usage for java.util Formatter close.

Prototype

public void close() 

Source Link

Document

Closes this formatter.

Usage

From source file:org.paxle.crawler.impl.CrawlerTools.java

/**
 * Generates a file-listing in a standard format understood by Paxle. Currently this format
 * consists of a rudimentary HTML-page linking to the files in the list given by
 * <code>fileListIt</code>. The resulting format of this list not yet finalized and subject
 * to change./*from  w  ww . j  a  v  a2  s .co  m*/
 * 
 * @param cdoc the {@link ICrawlerDocument} to save the dir-listing to
 * @param tfm if <code>cdoc</code> does not already contain a
 *        {@link ICrawlerDocument#getContent() content-file}, the {@link ITempFileManager} is
 *        used to create one.
 * @param fileListIt the file-listing providing the required information to include in the result
 * @param compress determines whether the content should be compressed transparently (via GZip)
 *        to save space. Compression reduces the size of the representation of large directories
 *        up to a sixth.
 */
public void saveListing(final ICrawlerDocument cdoc, final Iterator<DirlistEntry> fileListIt,
        boolean inclParent, boolean compress) throws IOException {
    if (cdoc == null)
        throw new NullPointerException("The crawler-document is null.");

    File content = cdoc.getContent();
    if (content == null) {
        content = this.tfm.createTempFile();
        cdoc.setContent(content);
    }

    final String charset = "UTF-8";

    if (compress) {
        cdoc.setMimeType("application/x-gzip");
    } else {
        cdoc.setMimeType("text/html");
        cdoc.setCharset(charset);
    }

    OutputStream writerOut = null;
    Formatter writer = null;
    try {
        // no need to buffer here, the Formatter uses a buffer internally
        writerOut = new FileOutputStream(content);

        /* Since the generated format is plain text, contains much redundant information and can potentially
         * become quite large (several hundred KB), a parameter offering compression can be specified. */
        if (compress)
            writerOut = new GZIPOutputStream(writerOut);

        writer = new Formatter(writerOut, charset);

        // getting the base dir
        String baseURL = cdoc.getLocation().toASCIIString();
        if (!baseURL.endsWith("/"))
            baseURL += "/";

        writer.format("<html><head><title>Index of %s</title></head><hr><table><tbody>\r\n",
                cdoc.getLocation());
        if (inclParent) {
            // getting the parent dir
            String parentDir = "/";
            if (baseURL.length() > 1) {
                parentDir = baseURL.substring(0, baseURL.length() - 1);
                int idx = parentDir.lastIndexOf("/");
                parentDir = parentDir.substring(0, idx + 1);
            }

            writer.format("<tr><td colspan=\"3\"><a href=\"%s\">Up to higher level directory</a></td></tr>\r\n",
                    parentDir);
        }

        // generate directory listing
        // FIXME: we need to escape the urls properly here.
        while (fileListIt.hasNext()) {
            final DirlistEntry entry = fileListIt.next();
            final String nexturi;
            final URI entryuri = entry.getFileURI();
            if (entryuri == null) {
                nexturi = baseURL + entry.getFileName();
            } else {
                nexturi = entryuri.toASCIIString();
            }
            writer.format(
                    "<tr>" + "<td><a href=\"%1$s\">%2$s</a></td>" + "<td>%3$d Bytes</td>"
                            + "<td>%4$tY-%4$tm-%4$td %4$tT</td>" + "</tr>\r\n",
                    nexturi, entry.getFileName(), Long.valueOf(entry.getSize()),
                    Long.valueOf(entry.getLastModified()));
        }
        writer.format("</tbody></table><hr></body></html>");

        cdoc.setStatus(ICrawlerDocument.Status.OK);
    } catch (UnsupportedEncodingException e) {
        // XXX: shouldn't this be an Error?
        throw new RuntimeException(charset + " not supported", e);
    } finally {
        if (writer != null)
            writer.close();
        else if (writerOut != null)
            writerOut.close();
    }
}

From source file:fr.cs.examples.propagation.DSSTPropagation.java

/** Print the results in the output file
 *
 *  @param handler orbit handler/*from w  ww .  jav  a2 s. c  o  m*/
 *  @param output output file
 *  @param sart start date of propagation
 *  @throws OrekitException 
 *  @throws IOException 
 */
private void printOutput(final File output, final OrbitHandler handler, final AbsoluteDate start)
        throws OrekitException, IOException {
    // Output format:
    // time_from_start, a, e, i, raan, pa, aM, h, k, p, q, lM, px, py, pz, vx, vy, vz
    final String format = new String(
            " %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e");
    final BufferedWriter buffer = new BufferedWriter(new FileWriter(output));
    buffer.write(
            "##   time_from_start(s)            a(km)                      e                      i(deg)         ");
    buffer.write(
            "         raan(deg)                pa(deg)              mean_anomaly(deg)              ey/h          ");
    buffer.write(
            "           ex/k                    hy/p                     hx/q             mean_longitude_arg(deg)");
    buffer.write(
            "       Xposition(km)           Yposition(km)             Zposition(km)           Xvelocity(km/s)    ");
    buffer.write("      Yvelocity(km/s)         Zvelocity(km/s)");
    buffer.newLine();
    for (Orbit o : handler.getOrbits()) {
        final Formatter f = new Formatter(new StringBuilder(), Locale.ENGLISH);
        // Time from start (s)
        final double time = o.getDate().durationFrom(start);
        // Semi-major axis (km)
        final double a = o.getA() / 1000.;
        // Keplerian elements
        // Eccentricity
        final double e = o.getE();
        // Inclination (degrees)
        final double i = Math.toDegrees(MathUtils.normalizeAngle(o.getI(), FastMath.PI));
        // Right Ascension of Ascending Node (degrees)
        KeplerianOrbit ko = new KeplerianOrbit(o);
        final double ra = Math
                .toDegrees(MathUtils.normalizeAngle(ko.getRightAscensionOfAscendingNode(), FastMath.PI));
        // Perigee Argument (degrees)
        final double pa = Math.toDegrees(MathUtils.normalizeAngle(ko.getPerigeeArgument(), FastMath.PI));
        // Mean Anomaly (degrees)
        final double am = Math
                .toDegrees(MathUtils.normalizeAngle(ko.getAnomaly(PositionAngle.MEAN), FastMath.PI));
        // Equinoctial elements
        // ey/h component of eccentricity vector
        final double h = o.getEquinoctialEy();
        // ex/k component of eccentricity vector
        final double k = o.getEquinoctialEx();
        // hy/p component of inclination vector
        final double p = o.getHy();
        // hx/q component of inclination vector
        final double q = o.getHx();
        // Mean Longitude Argument (degrees)
        final double lm = Math.toDegrees(MathUtils.normalizeAngle(o.getLM(), FastMath.PI));
        // Cartesian elements
        // Position along X in inertial frame (km)
        final double px = o.getPVCoordinates().getPosition().getX() / 1000.;
        // Position along Y in inertial frame (km)
        final double py = o.getPVCoordinates().getPosition().getY() / 1000.;
        // Position along Z in inertial frame (km)
        final double pz = o.getPVCoordinates().getPosition().getZ() / 1000.;
        // Velocity along X in inertial frame (km/s)
        final double vx = o.getPVCoordinates().getVelocity().getX() / 1000.;
        // Velocity along Y in inertial frame (km/s)
        final double vy = o.getPVCoordinates().getVelocity().getY() / 1000.;
        // Velocity along Z in inertial frame (km/s)
        final double vz = o.getPVCoordinates().getVelocity().getZ() / 1000.;
        buffer.write(
                f.format(format, time, a, e, i, ra, pa, am, h, k, p, q, lm, px, py, pz, vx, vy, vz).toString());
        buffer.newLine();
        f.close();
    }
    buffer.close();
}

From source file:org.efaps.esjp.accounting.util.data.ImportDetails.java

protected List<Document> checkAccounts(final Parameter _parameter, final File _file,
        final Map<String, Instance> _docMap, final DateTime _date, final Boolean _inverse)
        throws IOException, EFapsException {
    final List<Document> ret = new ArrayList<>();
    final CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"));
    final List<String[]> entries = reader.readAll();
    reader.close();/*from   w  w w.  j a  v a2  s.c o  m*/
    entries.remove(0);
    int i = 1;
    final Map<String, Document> map = new HashMap<>();
    for (final String[] row : entries) {
        i++;
        final String docNumber = row[0];
        final String ruc = row[1];
        final String dateStr = row[2];
        final String accountStr = row[5];
        final String accountDesc = row[4];
        final DecimalFormat formater = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
        formater.setParseBigDecimal(true);
        final String amountMEStr = row[6];
        final String amountMNStr = row[7];

        final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
        queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, accountStr.trim());
        final InstanceQuery query = queryBldr.getQuery();
        query.executeWithoutAccessCheck();
        if (query.next()) {
            ImportDetails.LOG.info("Found account: '{}' ", accountStr);
            final String[] docSplit = docNumber.split("-");
            if (docSplit.length != 2 && _docMap != null) {
                ImportDetails.LOG.warn(
                        "Document '{}'  - Line: {} has no '-' to distinguish SerialNumber and No.", docNumber,
                        i);
            } else {
                try {
                    final Formatter criteria = new Formatter();
                    String name = docNumber;
                    if (_docMap != null) {
                        final String serialNo = docSplit[0];
                        final String docNo = docSplit[1];
                        final int serial = Integer.parseInt(serialNo.trim().replaceAll("\\D", ""));
                        final int no = Integer.parseInt(docNo.trim().replaceAll("\\D", ""));
                        criteria.format("%03d-%06d", serial, no);
                        name = criteria.toString();
                    }

                    Document doc;
                    if (map.containsKey(name)) {
                        doc = map.get(name);
                    } else {
                        if (_docMap != null && _docMap.containsKey(name)) {
                            doc = new Document(name, _docMap.get(name), ruc, dateStr, accountDesc);
                        } else {
                            doc = new Document(name, null, ruc, dateStr, accountDesc);
                        }
                    }

                    BigDecimal amountME = (BigDecimal) formater.parse(amountMEStr);
                    BigDecimal amountMN = (BigDecimal) formater.parse(amountMNStr);

                    if (_inverse) {
                        amountME = amountME.negate();
                        amountMN = amountMN.negate();
                    }

                    if (amountMN.compareTo(BigDecimal.ZERO) >= 0) {
                        doc.addAmountMECredit(amountME);
                        doc.addAmountMNCredit(amountMN);
                    } else {
                        doc.addAmountMEDebit(amountME);
                        doc.addAmountMNDebit(amountMN);
                    }

                    final Map<String, Account> accounts = doc.getAccounts();
                    Account acc;
                    if (accounts.containsKey(accountStr)) {
                        acc = accounts.get(accountStr);
                    } else {
                        acc = new Account(accountStr, accountDesc);
                        accounts.put(accountStr, acc);
                    }
                    acc.addAmountME(amountME);
                    acc.addAmountMN(amountMN);
                    acc.setInstance(query.getCurrentValue());

                    map.put(name, doc);

                    criteria.close();
                } catch (final NumberFormatException e) {
                    ImportDetails.LOG.error("wrong format for document '{}'", docNumber);
                } catch (final ParseException e) {
                    ImportDetails.LOG.error("wrong format for amounts '{}' - '{}'", amountMEStr, amountMNStr);
                }
            }
        } else {
            ImportDetails.LOG.error("Not found account: {}", accountStr);
        }
    }

    final Instance periodInst = getPeriodInstance();
    for (final Document doc : map.values()) {
        final BigDecimal amountCreditMN = doc.getAmountMNCredit() != null ? doc.getAmountMNCredit()
                : BigDecimal.ZERO;
        final BigDecimal amountDebitMN = doc.getAmountMNDebit() != null ? doc.getAmountMNDebit()
                : BigDecimal.ZERO;
        final BigDecimal amountMN = amountCreditMN.add(amountDebitMN);
        final BigDecimal amountCreditME = doc.getAmountMECredit() != null ? doc.getAmountMECredit()
                : BigDecimal.ZERO;
        final BigDecimal amountDebitME = doc.getAmountMEDebit() != null ? doc.getAmountMEDebit()
                : BigDecimal.ZERO;
        final BigDecimal amountME = amountCreditME.add(amountDebitME);
        if (BigDecimal.ZERO.compareTo(amountMN) == 0 && BigDecimal.ZERO.compareTo(amountME) == 0) {
            ImportDetails.LOG.info(
                    "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' and Credit with Debit Amount (MN): '{}' + '{}' are Zero (0)",
                    doc.getName(), amountCreditME, amountDebitME, amountCreditMN, amountDebitMN);
        } else {
            ImportDetails.LOG.error(
                    "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' = '{}' and Credit with Debit Amount (MN): '{}' + '{}' = '{}'",
                    doc.getName(), amountCreditME, amountDebitME, amountME, amountCreditMN, amountDebitMN,
                    amountMN);
        }

        final Insert insert = new Insert(CIAccounting.TransactionOpeningBalance);
        insert.add(CIAccounting.TransactionOpeningBalance.Date, _date);
        final StringBuilder descBldr = new StringBuilder()
                .append(doc.getInstance() != null ? doc.getInstance().getType().getLabel() : "Sin Documento")
                .append(": ").append(doc.getName()).append(" - RUC: ").append(doc.getRuc()).append(" - ")
                .append(doc.getDate()).append(" - ").append(doc.getDesc());

        insert.add(CIAccounting.TransactionOpeningBalance.Description, descBldr.toString());
        insert.add(CIAccounting.TransactionOpeningBalance.Status,
                Status.find(CIAccounting.TransactionStatus.Open));
        insert.add(CIAccounting.TransactionOpeningBalance.PeriodLink, periodInst);
        insert.executeWithoutAccessCheck();

        if (_docMap != null) {
            final Instance instance = insert.getInstance();
            new Create().connectDocs2Transaction(_parameter, instance, doc.getInstance());
        }

        final Map<String, Account> accounts = doc.getAccounts();
        final Instance basCur = Currency.getBaseCurrency();
        for (final Account acc : accounts.values()) {
            final Insert insertpos = new Insert(
                    acc.getAmountMN().compareTo(BigDecimal.ZERO) > 0 ? CIAccounting.TransactionPositionCredit
                            : CIAccounting.TransactionPositionDebit);
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        }

        if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0
                && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) <= 0) {
            Insert insertpos = null;
            Account acc = null;
            if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) {
                acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGDEBIT);
                acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate());
                acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate());
                insertpos = new Insert(CIAccounting.TransactionPositionDebit);
            } else {
                acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGCREDIT);
                acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN));
                acc.addAmountME(amountDebitME.abs().subtract(amountCreditME));
                insertpos = new Insert(CIAccounting.TransactionPositionCredit);
            }
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        } else if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0
                && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) > 0) {
            Insert insertpos = null;
            final Account acc = getRoundingAccount(AccountingSettings.PERIOD_TRANSFERACCOUNT);
            ;
            if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) {
                acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate());
                acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate());
                insertpos = new Insert(CIAccounting.TransactionPositionDebit);
            } else {
                acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN));
                acc.addAmountME(amountDebitME.abs().subtract(amountCreditME));
                insertpos = new Insert(CIAccounting.TransactionPositionCredit);
            }
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        }
    }

    return ret;
}

From source file:com.zimbra.cs.util.ProxyConfOverride.java

@Override
public void update() throws ServiceException, ProxyConfException {
    ArrayList<String> servers = new ArrayList<String>();

    /* $(zmprov gamcs) */
    List<Server> mcs = mProv.getAllServers(Provisioning.SERVICE_MEMCACHED);
    for (Server mc : mcs) {
        String serverName = mc.getAttr(Provisioning.A_zimbraServiceHostname, "");
        int serverPort = mc.getIntAttr(Provisioning.A_zimbraMemcachedBindPort, 11211);
        try {/* w  w w . jav  a  2 s  .c o  m*/
            InetAddress ip = ProxyConfUtil.getLookupTargetIPbyIPMode(serverName);

            Formatter f = new Formatter();
            if (ip instanceof Inet4Address) {
                f.format("%s:%d", ip.getHostAddress(), serverPort);
            } else {
                f.format("[%s]:%d", ip.getHostAddress(), serverPort);
            }

            servers.add(f.toString());
            f.close();
        } catch (ProxyConfException pce) {
            mLog.error("Error resolving memcached host name: '" + serverName + "'", pce);
        }
    }
    if (servers.isEmpty()) {
        throw new ProxyConfException("No available memcached servers could be contacted");
    }
    mValue = servers;
}

From source file:net.sourceforge.fenixedu.domain.candidacyProcess.secondCycle.SecondCycleIndividualCandidacy.java

@Override
public void exportValues(StringBuilder result) {
    super.exportValues(result);

    Formatter formatter = new Formatter(result);

    formatter.format("%s: %s\n", BundleUtil.getString(Bundle.CANDIDATE, "label.process.id"),
            getCandidacyProcess().getProcessCode());
    PrecedentDegreeInformation precedentDegreeInformation = getCandidacyProcess()
            .getPrecedentDegreeInformation();
    formatter.format("%s: %s\n",
            BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.previous.degree"),
            precedentDegreeInformation.getDegreeDesignation());
    formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.conclusionDate"),
            precedentDegreeInformation.getConclusionDate());
    formatter.format("%s: %s\n",
            BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.institution"),
            precedentDegreeInformation.getInstitution().getName());
    formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.conclusionGrade"),
            precedentDegreeInformation.getConclusionGrade());
    formatter.format("\n");
    formatter.format("%s: %s\n",
            BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.professionalStatus"),
            StringUtils.isEmpty(getProfessionalStatus()) ? StringUtils.EMPTY : getProfessionalStatus());
    formatter.format("%s: %s\n",
            BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.otherEducation"),
            StringUtils.isEmpty(getOtherEducation()) ? StringUtils.EMPTY : getOtherEducation());
    formatter.format("%s: %d\n",
            BundleUtil.getString(Bundle.ACADEMIC,
                    "label.SecondCycleIndividualCandidacy.professionalExperience"),
            getProfessionalExperience() != null ? getProfessionalExperience() : 0);
    formatter.format("%s: %f\n",
            BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.affinity"),
            getAffinity() != null ? getAffinity() : BigDecimal.ZERO);
    formatter.format("%s: %d\n",
            BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.degreeNature"),
            getDegreeNature() != null ? getDegreeNature() : 0);
    formatter.format("%s: %f\n",
            BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.candidacyGrade"),
            getCandidacyGrade() != null ? getCandidacyGrade() : BigDecimal.ZERO);
    formatter.format("%s: %s\n",
            BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.interviewGrade"),
            getInterviewGrade());//from ww  w.ja  v a 2s.c om
    formatter.format("%s: %f\n",
            BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.seriesCandidacyGrade"),
            getSeriesCandidacyGrade() != null ? getSeriesCandidacyGrade() : BigDecimal.ZERO);

    formatter.close();
}

From source file:com.zimbra.cs.util.ProxyConfOverride.java

@Override
public void update() throws ServiceException, ProxyConfException {
    ArrayList<String> servers = new ArrayList<String>();
    int numFailedHandlers = 0;

    String[] handlerNames = serverSource.getMultiAttr("zimbraReverseProxyAvailableLookupTargets");
    if (handlerNames.length > 0) {
        for (String handlerName : handlerNames) {
            Server s = mProv.getServerByName(handlerName);
            if (s != null) {
                String sn = s.getAttr(Provisioning.A_zimbraServiceHostname, "");
                int port = s.getIntAttr(Provisioning.A_zimbraExtensionBindPort, 7072);
                String proto = "http://";
                int major = s.getIntAttr(Provisioning.A_zimbraServerVersionMajor, 0);
                int minor = s.getIntAttr(Provisioning.A_zimbraServerVersionMinor, 0);
                if ((major == 8 && minor >= 7) || (major > 8)) {
                    proto = "https://";
                }// w  w  w .java 2 s  .  c om
                boolean isTarget = s.getBooleanAttr(Provisioning.A_zimbraReverseProxyLookupTarget, false);
                if (isTarget) {
                    try {
                        InetAddress ip = ProxyConfUtil.getLookupTargetIPbyIPMode(sn);
                        Formatter f = new Formatter();
                        if (ip instanceof Inet4Address) {
                            f.format("%s%s:%d", proto, ip.getHostAddress(), port);
                        } else {
                            f.format("%s[%s]:%d", proto, ip.getHostAddress(), port);
                        }
                        servers.add(f.toString());
                        f.close();
                        mLog.debug("Route Lookup: Added server " + ip);
                    } catch (ProxyConfException pce) {
                        numFailedHandlers++;
                        mLog.error("Error resolving service host name: '" + sn + "'", pce);
                    }
                }
            } else {
                mLog.warn("Invalid value found in 'zimbraReverseProxyAvailableLookupTargets': " + handlerName
                        + "\nPlease correct and run zmproxyconfgen again");
            }
        }
    } else {
        List<Server> allServers = mProv.getAllServers();

        for (Server s : allServers) {
            String sn = s.getAttr(Provisioning.A_zimbraServiceHostname, "");
            int port = s.getIntAttr(Provisioning.A_zimbraExtensionBindPort, 7072);
            String proto = "http://";
            int major = s.getIntAttr(Provisioning.A_zimbraServerVersionMajor, 0);
            int minor = s.getIntAttr(Provisioning.A_zimbraServerVersionMinor, 0);
            if ((major == 8 && minor >= 7) || (major > 8)) {
                proto = "https://";
            }
            boolean isTarget = s.getBooleanAttr(Provisioning.A_zimbraReverseProxyLookupTarget, false);
            if (isTarget) {
                try {
                    InetAddress ip = ProxyConfUtil.getLookupTargetIPbyIPMode(sn);
                    Formatter f = new Formatter();
                    if (ip instanceof Inet4Address) {
                        f.format("%s%s:%d", proto, ip.getHostAddress(), port);
                    } else {
                        f.format("%s[%s]:%d", proto, ip.getHostAddress(), port);
                    }
                    servers.add(f.toString());
                    f.close();
                    mLog.debug("Route Lookup: Added server " + ip);
                } catch (ProxyConfException pce) {
                    numFailedHandlers++;
                    mLog.error("Error resolving service host name: '" + sn + "'", pce);
                }
            }
        }
    }
    if (servers.isEmpty()) {
        if (numFailedHandlers > 0) {
            throw new ProxyConfException("No available nginx lookup handlers could be contacted");
        } else {
            mLog.warn("No available nginx lookup handlers could be found");
        }
    }
    mValue = servers;
}

From source file:com.diablominer.DiabloMiner.DiabloMiner.java

void execute(String[] args) throws Exception {
    threads.add(Thread.currentThread());

    Options options = new Options();
    options.addOption("u", "user", true, "bitcoin host username");
    options.addOption("p", "pass", true, "bitcoin host password");
    options.addOption("o", "host", true, "bitcoin host IP");
    options.addOption("r", "port", true, "bitcoin host port");
    options.addOption("l", "url", true, "bitcoin host url");
    options.addOption("x", "proxy", true, "optional proxy settings IP:PORT<:username:password>");
    options.addOption("g", "worklifetime", true, "maximum work lifetime in seconds");
    options.addOption("d", "debug", false, "enable debug output");
    options.addOption("dt", "debugtimer", false, "run for 1 minute and quit");
    options.addOption("D", "devices", true, "devices to enable, default all");
    options.addOption("f", "fps", true, "target GPU execution timing");
    options.addOption("na", "noarray", false, "turn GPU kernel array off");
    options.addOption("v", "vectors", true, "vector size in GPU kernel");
    options.addOption("w", "worksize", true, "override GPU worksize");
    options.addOption("ds", "ksource", false, "output GPU kernel source and quit");
    options.addOption("h", "help", false, "this help");

    PosixParser parser = new PosixParser();

    CommandLine line = null;/* w  w w. j  a  va2s  .  c  o  m*/

    try {
        line = parser.parse(options, args);

        if (line.hasOption("help")) {
            throw new ParseException("");
        }
    } catch (ParseException e) {
        System.out.println(e.getLocalizedMessage() + "\n");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DiabloMiner -u myuser -p mypassword [args]\n", "", options,
                "\nRemember to set rpcuser and rpcpassword in your ~/.bitcoin/bitcoin.conf "
                        + "before starting bitcoind or bitcoin --daemon");
        return;
    }

    String splitUrl[] = null;
    String splitUser[] = null;
    String splitPass[] = null;
    String splitHost[] = null;
    String splitPort[] = null;

    if (line.hasOption("url"))
        splitUrl = line.getOptionValue("url").split(",");

    if (line.hasOption("user"))
        splitUser = line.getOptionValue("user").split(",");

    if (line.hasOption("pass"))
        splitPass = line.getOptionValue("pass").split(",");

    if (line.hasOption("host"))
        splitHost = line.getOptionValue("host").split(",");

    if (line.hasOption("port"))
        splitPort = line.getOptionValue("port").split(",");

    int networkStatesCount = 0;

    if (splitUrl != null)
        networkStatesCount = splitUrl.length;

    if (splitUser != null)
        networkStatesCount = Math.max(splitUser.length, networkStatesCount);

    if (splitPass != null)
        networkStatesCount = Math.max(splitPass.length, networkStatesCount);

    if (splitHost != null)
        networkStatesCount = Math.max(splitHost.length, networkStatesCount);

    if (splitPort != null)
        networkStatesCount = Math.max(splitPort.length, networkStatesCount);

    if (networkStatesCount == 0) {
        error("You forgot to give any bitcoin connection info, please add either -l, or -u -p -o and -r");
        System.exit(-1);
    }

    int j = 0;

    for (int i = 0; j < networkStatesCount; i++, j++) {
        String protocol = "http";
        String host = "localhost";
        int port = 8332;
        String path = "/";
        String user = "diablominer";
        String pass = "diablominer";
        byte hostChain = 0;

        if (splitUrl != null && splitUrl.length > i) {
            String[] usernameFix = splitUrl[i].split("@", 3);
            if (usernameFix.length > 2)
                splitUrl[i] = usernameFix[0] + "+++++" + usernameFix[1] + "@" + usernameFix[2];

            URL url = new URL(splitUrl[i]);

            if (url.getProtocol() != null && url.getProtocol().length() > 1)
                protocol = url.getProtocol();

            if (url.getHost() != null && url.getHost().length() > 1)
                host = url.getHost();

            if (url.getPort() != -1)
                port = url.getPort();

            if (url.getPath() != null && url.getPath().length() > 1)
                path = url.getPath();

            if (url.getUserInfo() != null && url.getUserInfo().length() > 1) {
                String[] userPassSplit = url.getUserInfo().split(":");

                user = userPassSplit[0].replace("+++++", "@");

                if (userPassSplit.length > 1 && userPassSplit[1].length() > 1)
                    pass = userPassSplit[1];
            }
        }

        if (splitUser != null && splitUser.length > i)
            user = splitUser[i];

        if (splitPass != null && splitPass.length > i)
            pass = splitPass[i];

        if (splitHost != null && splitHost.length > i)
            host = splitHost[i];

        if (splitPort != null && splitPort.length > i)
            port = Integer.parseInt(splitPort[i]);

        NetworkState networkState;

        try {
            networkState = new JSONRPCNetworkState(this, new URL(protocol, host, port, path), user, pass,
                    hostChain);
        } catch (MalformedURLException e) {
            throw new DiabloMinerFatalException(this, "Malformed connection paramaters");
        }

        if (networkStateHead == null) {
            networkStateHead = networkStateTail = networkState;
        } else {
            networkStateTail.setNetworkStateNext(networkState);
            networkStateTail = networkState;
        }
    }

    networkStateTail.setNetworkStateNext(networkStateHead);

    if (line.hasOption("proxy")) {
        final String[] proxySettings = line.getOptionValue("proxy").split(":");

        if (proxySettings.length >= 2) {
            proxy = new Proxy(Type.HTTP,
                    new InetSocketAddress(proxySettings[0], Integer.valueOf(proxySettings[1])));
        }

        if (proxySettings.length >= 3) {
            Authenticator.setDefault(new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxySettings[2], proxySettings[3].toCharArray());
                }
            });
        }
    }

    if (line.hasOption("worklifetime"))
        workLifetime = Integer.parseInt(line.getOptionValue("worklifetime")) * 1000;

    if (line.hasOption("debug"))
        debug = true;

    if (line.hasOption("debugtimer")) {
        debugtimer = true;
    }

    if (line.hasOption("devices")) {
        String devices[] = line.getOptionValue("devices").split(",");
        enabledDevices = new HashSet<String>();
        for (String s : devices) {
            enabledDevices.add(s);

            if (Integer.parseInt(s) == 0) {
                error("Do not use 0 with -D, devices start at 1");
                System.exit(-1);
            }
        }
    }

    if (line.hasOption("fps")) {
        GPUTargetFPS = Float.parseFloat(line.getOptionValue("fps"));

        if (GPUTargetFPS < 0.1) {
            error("--fps argument is too low, adjusting to 0.1");
            GPUTargetFPS = 0.1;
        }
    }

    if (line.hasOption("noarray")) {
        GPUNoArray = true;
    }

    if (line.hasOption("worksize"))
        GPUForceWorkSize = Integer.parseInt(line.getOptionValue("worksize"));

    if (line.hasOption("vectors")) {
        String tempVectors[] = line.getOptionValue("vectors").split(",");

        GPUVectors = new Integer[tempVectors.length];

        try {
            for (int i = 0; i < GPUVectors.length; i++) {
                GPUVectors[i] = Integer.parseInt(tempVectors[i]);

                if (GPUVectors[i] > 16) {
                    error("DiabloMiner now uses comma-seperated vector layouts, use those instead");
                    System.exit(-1);
                } else if (GPUVectors[i] != 1 && GPUVectors[i] != 2 && GPUVectors[i] != 3 && GPUVectors[i] != 4
                        && GPUVectors[i] != 8 && GPUVectors[i] != 16) {
                    error(GPUVectors[i] + " is not a vector length of 1, 2, 3, 4, 8, or 16");
                    System.exit(-1);
                }
            }

            Arrays.sort(GPUVectors, Collections.reverseOrder());
        } catch (NumberFormatException e) {
            error("Cannot parse --vector argument(s)");
            System.exit(-1);
        }
    } else {
        GPUVectors = new Integer[1];
        GPUVectors[0] = 1;
    }

    if (line.hasOption("ds"))
        GPUDebugSource = true;

    info("Started");

    StringBuilder list = new StringBuilder(networkStateHead.getQueryUrl().toString());
    NetworkState networkState = networkStateHead.getNetworkStateNext();

    while (networkState != networkStateHead) {
        list.append(", " + networkState.getQueryUrl());
        networkState = networkState.getNetworkStateNext();
    }

    info("Connecting to: " + list);

    long previousHashCount = 0;
    double previousAdjustedHashCount = 0.0;
    long previousAdjustedStartTime = startTime = (now()) - 1;
    StringBuilder hashMeter = new StringBuilder(80);
    Formatter hashMeterFormatter = new Formatter(hashMeter);

    int deviceCount = 0;

    List<List<? extends DeviceState>> allDeviceStates = new ArrayList<List<? extends DeviceState>>();

    List<? extends DeviceState> GPUDeviceStates = new GPUHardwareType(this).getDeviceStates();
    deviceCount += GPUDeviceStates.size();
    allDeviceStates.add(GPUDeviceStates);

    while (running.get()) {
        for (List<? extends DeviceState> deviceStates : allDeviceStates) {
            for (DeviceState deviceState : deviceStates) {
                deviceState.checkDevice();
            }
        }

        long now = now();
        long currentHashCount = hashCount.get();
        double adjustedHashCount = (double) (currentHashCount - previousHashCount)
                / (double) (now - previousAdjustedStartTime);
        double hashLongCount = (double) currentHashCount / (double) (now - startTime) / 1000.0;

        if (now - startTime > TIME_OFFSET * 2) {
            double averageHashCount = (adjustedHashCount + previousAdjustedHashCount) / 2.0 / 1000.0;

            hashMeter.setLength(0);

            if (!debug) {
                hashMeterFormatter.format("\rmhash: %.1f/%.1f | accept: %d | reject: %d | hw error: %d",
                        averageHashCount, hashLongCount, blocks.get(), rejects.get(), hwErrors.get());
            } else {
                hashMeterFormatter.format("\rmh: %.1f/%.1f | a/r/hwe: %d/%d/%d | gh: ", averageHashCount,
                        hashLongCount, blocks.get(), rejects.get(), hwErrors.get());

                double basisAverage = 0.0;

                for (List<? extends DeviceState> deviceStates : allDeviceStates) {
                    for (DeviceState deviceState : deviceStates) {
                        hashMeterFormatter.format("%.1f ",
                                deviceState.getDeviceHashCount() / 1000.0 / 1000.0 / 1000.0);
                        basisAverage += deviceState.getBasis();
                    }
                }

                basisAverage = 1000 / (basisAverage / deviceCount);

                hashMeterFormatter.format("| fps: %.1f", basisAverage);
            }

            System.out.print(hashMeter);
        } else {
            System.out.print("\rWaiting...");
        }

        if (now() - TIME_OFFSET * 2 > previousAdjustedStartTime) {
            previousHashCount = currentHashCount;
            previousAdjustedHashCount = adjustedHashCount;
            previousAdjustedStartTime = now - 1;
        }

        if (debugtimer && now() > startTime + 60 * 1000) {
            System.out.print("\n");
            info("Debug timer is up, quitting...");
            System.exit(0);
        }

        try {
            if (now - startTime > TIME_OFFSET)
                Thread.sleep(1000);
            else
                Thread.sleep(1);
        } catch (InterruptedException e) {
        }
    }

    hashMeterFormatter.close();
}

From source file:org.fenixedu.academic.domain.student.Registration.java

public void exportValues(StringBuilder result) {
    Formatter formatter = new Formatter(result);
    final Student student = getStudent();
    formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.ingression"),
            getIngressionType() == null ? " - " : getIngressionType().getDescription().getContent());
    formatter.format("%s: %d\n", BundleUtil.getString(Bundle.ACADEMIC, "label.studentNumber"),
            student.getNumber());//from w  w w. j ava 2s .c o m
    formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.Student.Person.name"),
            student.getPerson().getName());
    formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.degree"),
            getDegree().getPresentationName());
    formatter.close();
}

From source file:org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverterSWAN.java

/**
 * Formats the lines for boundary condition ( Wave boundaries... ).
 *///from  w w  w.  j av a 2 s. c  o m
private void formatBoundConds(final Formatter pFormatter, final int pIntContiLineId) throws IOException {
    for (final IBoundaryCondition boundaryCondition : m_unitBoundaryConditions) {
        if (boundaryCondition.getTypeByLocation().equals(IBoundaryCondition.PARENT_TYPE_LINE1D2D)) {
            final IObservation<TupleResult> obs = boundaryCondition.getObservation();
            final TupleResult obsResult = obs.getResult();
            final IComponent abscissaComponent = TupleResultUtilities.findComponentById(obsResult,
                    Kalypso1D2DDictConstants.DICT_COMPONENT_TIME);
            final IComponent ordinateComponent = TupleResultUtilities.findComponentById(obsResult,
                    Kalypso1D2DDictConstants.DICT_COMPONENT_WAVE_HSIG);

            if (abscissaComponent != null && ordinateComponent != null) {
                IFELine lContiLineAct = null;
                try {
                    lContiLineAct = m_discretisationModel.findContinuityLine(boundaryCondition.getPosition(),
                            0.01);
                } catch (final Exception e) {
                    continue;
                }
                if (m_mapContiLinesWithConditions.get(lContiLineAct) != pIntContiLineId) {
                    continue;
                }
                if (obsResult.size() == 0 || boundaryCondition.isAbsolute()) {
                    pFormatter.format("BOUN SIDE %d %s\n", pIntContiLineId, //$NON-NLS-1$
                            boundaryCondition.getStationaryCondition());
                    return;
                }

                final String lStrBoundFileNameAct = ISimulation1D2DConstants.SWAN_BOUNDARY_FILE_PREFIX
                        + pIntContiLineId + ISimulation1D2DConstants.SIM_SWAN_DATA_FILE_EXT;
                final Formatter lFormatter = getFormatter(lStrBoundFileNameAct);
                lFormatter.format("TPAR\n"); //$NON-NLS-1$

                final IComponent lComponentTime = TupleResultUtilities.findComponentById(obsResult,
                        Kalypso1D2DDictConstants.DICT_COMPONENT_TIME);
                final IComponent lComponentHsig = TupleResultUtilities.findComponentById(obsResult,
                        Kalypso1D2DDictConstants.DICT_COMPONENT_WAVE_HSIG);
                final IComponent lComponentPer = TupleResultUtilities.findComponentById(obsResult,
                        Kalypso1D2DDictConstants.DICT_COMPONENT_WAVE_PER);
                final IComponent lComponentDir = TupleResultUtilities.findComponentById(obsResult,
                        Kalypso1D2DDictConstants.DICT_COMPONENT_WAVE_DIR);
                final IComponent lComponentDD = TupleResultUtilities.findComponentById(obsResult,
                        Kalypso1D2DDictConstants.DICT_COMPONENT_WAVE_DD);
                if (lComponentTime == null || lComponentHsig == null)
                    continue;

                final TupleResultIndex tupleResultIndex = new TupleResultIndex(obsResult, lComponentTime);
                final Iterator<IRecord> tupleIterator = tupleResultIndex.getIterator();
                boolean lBoolWrittenBnd = false;
                final int lIndexTime = obsResult.indexOfComponent(lComponentTime);
                final int lIndexHsig = obsResult.indexOfComponent(lComponentHsig);
                final int lIndexPer = obsResult.indexOfComponent(lComponentPer);
                final int lIndexDir = obsResult.indexOfComponent(lComponentDir);
                final int lIndexDD = obsResult.indexOfComponent(lComponentDD);
                while (tupleIterator.hasNext()) {
                    final IRecord record = tupleIterator.next();
                    final XMLGregorianCalendar lGregCalendar = (XMLGregorianCalendar) record
                            .getValue(lIndexTime);

                    final Date lDateAct = DateUtilities.toDate(lGregCalendar);
                    if (m_calculatedSteps[0].getTime() <= lDateAct.getTime()
                            && m_calculatedSteps[m_calculatedSteps.length - 1].getTime() >= lDateAct
                                    .getTime()) {
                        final String lStrTime = SWANDataConverterHelper
                                .getTimeStringFormatedForSWANInput(lDateAct);

                        final BigDecimal lBDHsig = (BigDecimal) record.getValue(lIndexHsig);
                        final BigDecimal lBDPer = (BigDecimal) record.getValue(lIndexPer);
                        final BigDecimal lBDDir = (BigDecimal) record.getValue(lIndexDir);
                        final BigDecimal lBDDD = (BigDecimal) record.getValue(lIndexDD);
                        lFormatter.format("%s %.2f %.2f %.2f %.2f\n", lStrTime, lBDHsig, lBDPer, lBDDir, lBDDD); //$NON-NLS-1$
                        lBoolWrittenBnd = true;
                    }
                }
                if (lBoolWrittenBnd) {
                    pFormatter.format("BOUN SIDE %d CON FILE '%s'\n$\n", pIntContiLineId, lStrBoundFileNameAct); //$NON-NLS-1$
                } else {
                    pFormatter.format("BOUN SIDE %d %s\n$\n", pIntContiLineId, //$NON-NLS-1$
                            boundaryCondition.getStationaryCondition());
                }

                FormatterUtils.checkIoException(lFormatter);
                lFormatter.close();
            }
        }

        FormatterUtils.checkIoException(pFormatter);
    }
}

From source file:org.kalypso.model.wspm.tuhh.core.wspwin.WspWinExporter.java

private static void write1DTuhhSteuerparameter(final TuhhCalculation calculation, final File batFile,
        final File zustFile, final File qwtFile, final File psiFile, final TuhhStationRange stationRange)
        throws IOException {
    final MODE calcMode = calculation.getCalcMode();

    Formatter pw = null;
    try {/*  w  w w.j  a  va  2  s .  c  o  m*/
        batFile.getParentFile().mkdirs();

        pw = new Formatter(batFile);

        pw.format("# %s%n", calculation.getName()); //$NON-NLS-1$
        pw.format("# %s%n", //$NON-NLS-1$
                DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date()));

        pw.format("%n"); //$NON-NLS-1$
        pw.format("PROJEKTPFAD=%s%n", "."); //$NON-NLS-1$ //$NON-NLS-2$
        pw.format("STRANGDATEI=%s%n", zustFile.getName()); //$NON-NLS-1$

        pw.format("%n"); //$NON-NLS-1$
        pw.format("# mgliche Werte:%n"); //$NON-NLS-1$
        pw.format("# WATERLEVEL%n"); //$NON-NLS-1$
        pw.format("# BF_UNIFORM%n"); //$NON-NLS-1$
        pw.format("# BF_NON_UNIFORM%n"); //$NON-NLS-1$
        pw.format("# REIB_KONST%n"); //$NON-NLS-1$

        pw.format("BERECHNUNGSMODUS=%s%n", calcMode.name()); //$NON-NLS-1$

        pw.format("%n"); //$NON-NLS-1$
        pw.format("# mgliche Werte:%n"); //$NON-NLS-1$
        pw.format("# DARCY_WEISBACH_OHNE_FORMEINFLUSS%n"); //$NON-NLS-1$
        pw.format("# DARCY_WEISBACH_MIT_FORMEINFLUSS%n"); //$NON-NLS-1$
        pw.format("# MANNING_STRICKLER%n"); //$NON-NLS-1$
        pw.format("FLIESSGESETZ=%s%n", calculation.getFliessgesetz().name()); //$NON-NLS-1$

        pw.format("%n"); //$NON-NLS-1$

        pw.format(Locale.US, "ANFANGSSTATION=%s%n", stationRange.getExportFrom()); //$NON-NLS-1$
        pw.format(Locale.US, "ENDSTATION=%s%n", stationRange.getExportTo()); //$NON-NLS-1$

        pw.format("%n"); //$NON-NLS-1$
        pw.format("# mgliche Werte%n"); //$NON-NLS-1$
        pw.format("# CRITICAL_WATER_DEPTH%n"); //$NON-NLS-1$
        pw.format("# UNIFORM_BOTTOM_SLOPE%n"); //$NON-NLS-1$
        pw.format("# WATERLEVEL%n"); //$NON-NLS-1$
        pw.format("ART_RANDBEDINGUNG=%s%n", calculation.getStartKind().name()); //$NON-NLS-1$
        final Double startWaterlevel = calculation.getStartWaterlevel();
        if (startWaterlevel != null) {
            pw.format(Locale.US, "ANFANGSWASSERSPIEGEL=%s%n", startWaterlevel); //$NON-NLS-1$
        }
        final BigDecimal startSlope = calculation.getStartSlope();
        if (startSlope != null) {
            pw.format("GEFAELLE=%s%n", startSlope); //$NON-NLS-1$
        }

        pw.format("%n"); //$NON-NLS-1$
        pw.format("# mgliche Werte%n"); //$NON-NLS-1$
        pw.format("# NON%n"); //$NON-NLS-1$
        pw.format("# DVWK%n"); //$NON-NLS-1$
        pw.format("# BJOERNSEN%n"); //$NON-NLS-1$
        pw.format("# DFG%n"); //$NON-NLS-1$
        pw.format("VERZOEGERUNGSVERLUST=%s%n", calculation.getVerzoegerungsverlust().name()); //$NON-NLS-1$

        pw.format("%n"); //$NON-NLS-1$
        pw.format("# mgliche Werte%n"); //$NON-NLS-1$
        pw.format("# SIMPLE%n"); //$NON-NLS-1$
        pw.format("# EXACT%n"); //$NON-NLS-1$
        pw.format("ITERATIONSART=%s%n", calculation.getIterationType().name()); //$NON-NLS-1$

        pw.format("%n"); //$NON-NLS-1$
        pw.format("# mgliche Werte%n"); //$NON-NLS-1$
        pw.format("# TRAPEZ_FORMULA%n"); //$NON-NLS-1$
        pw.format("# GEOMETRIC_FORMULA%n"); //$NON-NLS-1$
        pw.format("REIBUNGSVERLUST=%s%n", calculation.getReibungsverlust().name()); //$NON-NLS-1$

        pw.format("%n"); //$NON-NLS-1$
        pw.format("# mgliche Werte: true / false%n"); //$NON-NLS-1$
        pw.format("MIT_BRUECKEN=%b%n", calculation.isCalcBridges()); //$NON-NLS-1$
        pw.format("MIT_WEHREN=%b%n", calculation.isCalcBarrages()); //$NON-NLS-1$
        pw.format("USE_EXTREM_ROUGH=%b%n", calculation.isUseExtremeRoughness()); //$NON-NLS-1$

        pw.format("%n"); //$NON-NLS-1$
        pw.format("ABFLUSSEREIGNIS=%s%n", qwtFile.getName()); //$NON-NLS-1$

        pw.format("%n"); //$NON-NLS-1$
        pw.format("EINZELVERLUSTE=%s%n", psiFile.getName()); //$NON-NLS-1$ //$NON-NLS-2$

        pw.format("%n"); //$NON-NLS-1$
        final Double minQ = calculation.getMinQ();
        if (minQ != null) {
            pw.format(Locale.US, "MIN_Q=%s%n", minQ); //$NON-NLS-1$
        }
        final Double maxQ = calculation.getMaxQ();
        if (maxQ != null) {
            pw.format(Locale.US, "MAX_Q=%s%n", maxQ); //$NON-NLS-1$
        }
        final Double qstep = calculation.getQStep();
        if (qstep != null) {
            pw.format(Locale.US, "DELTA_Q=%s%n", qstep); //$NON-NLS-1$
        }

        pw.format("%n"); //$NON-NLS-1$
        // Einheit des Durchflusses wird standardmig festgelegt
        pw.format("# mgliche Werte%n"); //$NON-NLS-1$
        pw.format("# QM_S%n"); //$NON-NLS-1$
        pw.format("# L_S%n"); //$NON-NLS-1$
        pw.format("DURCHFLUSS_EINHEIT=QM_S%n"); //$NON-NLS-1$

        FormatterUtils.checkIoException(pw);
    } finally {
        if (pw != null) {
            pw.close();
        }
    }

}