Example usage for java.io PrintWriter printf

List of usage examples for java.io PrintWriter printf

Introduction

In this page you can find the example usage for java.io PrintWriter printf.

Prototype

public PrintWriter printf(String format, Object... args) 

Source Link

Document

A convenience method to write a formatted string to this writer using the specified format string and arguments.

Usage

From source file:com.nridge.core.base.io.xml.DocumentOpXML.java

/**
 * Saves the previous assigned document list (e.g. via constructor or set method)
 * to the print writer stream wrapped in a tag name specified in the parameter.
 *
 * @param aPW PrintWriter stream instance.
 * @param aTagName Document tag name./*from  ww w  .j a  v a2s . com*/
 * @param anIndentAmount Indentation count.
 *
 * @throws java.io.IOException I/O related exception.
 */
public void save(PrintWriter aPW, String aTagName, int anIndentAmount) throws IOException {
    DocumentXML documentXML;

    if (mCriteria == null) {
        IOXML.indentLine(aPW, anIndentAmount);
        aPW.printf("<%s", IO.XML_OPERATION_NODE_NAME);
        IOXML.writeAttrNameValue(aPW, Doc.FEATURE_OP_NAME, mField.getName());
        int docCount = mDocumentList.size();
        if (docCount > 0)
            IOXML.writeAttrNameValue(aPW, "count", mDocumentList.size());
        for (Map.Entry<String, String> featureEntry : mField.getFeatures().entrySet())
            IOXML.writeAttrNameValue(aPW, featureEntry.getKey(), featureEntry.getValue());

        if (docCount == 0)
            aPW.printf("/>%n");
        else {
            aPW.printf(">%n");
            for (Document document : mDocumentList) {
                documentXML = new DocumentXML(document);
                documentXML.setIsSimpleFlag(mIsSimple);
                documentXML.setSaveFieldsWithoutValues(true);
                documentXML.save(aPW, aTagName, anIndentAmount + 1);
            }
            IOXML.indentLine(aPW, anIndentAmount);
            aPW.printf("</%s>%n", IO.XML_OPERATION_NODE_NAME);
        }
    } else {
        IOXML.indentLine(aPW, anIndentAmount);
        aPW.printf("<%s", IO.XML_OPERATION_NODE_NAME);
        IOXML.writeAttrNameValue(aPW, Doc.FEATURE_OP_NAME, mField.getName());
        for (Map.Entry<String, String> featureEntry : mField.getFeatures().entrySet())
            IOXML.writeAttrNameValue(aPW, featureEntry.getKey(), featureEntry.getValue());
        aPW.printf(">%n");
        DSCriteriaXML dsCriteriaXML = new DSCriteriaXML(mCriteria);
        dsCriteriaXML.save(aPW, IO.XML_CRITERIA_NODE_NAME, anIndentAmount + 1);
        IOXML.indentLine(aPW, anIndentAmount);
        aPW.printf("</%s>%n", IO.XML_OPERATION_NODE_NAME);
    }
}

From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferService.java

@Override
protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
    // only available when the application is debuggable
    if ((getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
        return;/*  ww w .j  a  va  2 s .co  m*/
    }

    writer.printf("start id: %d\n", startId);
    writer.printf("network status: %s\n", networkInfoReceiver.isNetworkConnected());
    writer.printf("lastActiveTime: %s, shouldScan: %s\n", new Date(lastActiveTime), shouldScan);
    final Map<Integer, TransferRecord> transfers = updater.getTransfers();
    writer.printf("# of active transfers: %d\n", transfers.size());
    for (final TransferRecord transfer : transfers.values()) {
        writer.printf("bucket: %s, key: %s, status: %s, total size: %d, current: %d\n", transfer.bucketName,
                transfer.key, transfer.state, transfer.bytesTotal, transfer.bytesCurrent);
    }
    writer.flush();
}

From source file:com.nridge.core.base.io.xml.DSCriteriaXML.java

/**
 * Saves the previous assigned criteria (e.g. via constructor or set method)
 * to the print writer stream wrapped in a tag name specified in the parameter.
 *
 * @param aPW            PrintWriter stream instance.
 * @param aTagName       Tag name./*  w  w  w .j  a va 2s .com*/
 * @param anIndentAmount Indentation count.
 *
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void save(PrintWriter aPW, String aTagName, int anIndentAmount) throws IOException {
    DataField dataField;
    DSCriterion dsCriterion;

    String tagName = StringUtils.remove(aTagName, StrUtl.CHAR_SPACE);
    ArrayList<DSCriterionEntry> dsCriterionEntries = mDSCriteria.getCriterionEntries();
    int ceCount = dsCriterionEntries.size();

    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("<%s", tagName);
    IOXML.writeAttrNameValue(aPW, "type", IO.extractType(mDSCriteria.getClass().getName()));
    IOXML.writeAttrNameValue(aPW, "name", mDSCriteria.getName());
    IOXML.writeAttrNameValue(aPW, "version", IO.CRITERIA_XML_FORMAT_VERSION);
    IOXML.writeAttrNameValue(aPW, "operator", Field.operatorToString(Field.Operator.AND));
    IOXML.writeAttrNameValue(aPW, "count", ceCount);
    for (Map.Entry<String, String> featureEntry : mDSCriteria.getFeatures().entrySet())
        IOXML.writeAttrNameValue(aPW, featureEntry.getKey(), featureEntry.getValue());
    aPW.printf(">%n");

    if (ceCount > 0) {
        for (DSCriterionEntry ce : dsCriterionEntries) {
            dsCriterion = ce.getCriterion();

            dataField = new DataField(dsCriterion.getField());
            dataField.addFeature("operator", Field.operatorToString(ce.getLogicalOperator()));
            mDataFieldXML.saveNode(aPW, anIndentAmount + 1);
            mDataFieldXML.saveAttr(aPW, dataField);
            mDataFieldXML.saveValue(aPW, dataField, anIndentAmount + 1);
        }
    }

    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("</%s>%n", tagName);
}

From source file:org.apache.mahout.clustering.streaming.tools.ResplitSequenceFiles.java

private void run(PrintWriter printWriter) throws IOException {
    conf = new Configuration();
    SequenceFileDirIterable<Writable, Writable> inputIterable = new SequenceFileDirIterable<Writable, Writable>(
            new Path(inputFile), PathType.LIST, conf);
    fs = FileSystem.get(conf);/*from  www. j  a v  a  2s.c  om*/

    int numEntries = Iterables.size(inputIterable);
    int numEntriesPerSplit = numEntries / numSplits;
    int numEntriesLastSplit = numEntriesPerSplit + numEntries - numEntriesPerSplit * numSplits;
    Iterator<Pair<Writable, Writable>> inputIterator = inputIterable.iterator();

    printWriter.printf("Writing %d splits\n", numSplits);
    for (int i = 0; i < numSplits - 1; ++i) {
        printWriter.printf("Writing split %d\n", i);
        writeSplit(inputIterator, i, numEntriesPerSplit);
    }
    printWriter.printf("Writing split %d\n", numSplits - 1);
    writeSplit(inputIterator, numSplits - 1, numEntriesLastSplit);
}

From source file:org.liberty.android.fantastischmemo.converter.Mnemosyne2CardsExporter.java

private void createXMLFile(String dbPath, File xmlFile) throws IOException {
    AnyMemoDBOpenHelper helper = null;// www.  j  av  a2 s .co  m
    PrintWriter outXml = null;
    try {
        helper = AnyMemoDBOpenHelperManager.getHelper(dbPath);
        CardDao cardDao = helper.getCardDao();
        CategoryDao categoryDao = helper.getCategoryDao();
        LearningDataDao learningDataDao = helper.getLearningDataDao();
        int cardCount = (int) cardDao.countOf();

        outXml = new PrintWriter(new BufferedWriter(new FileWriter(xmlFile)));
        outXml.printf("<openSM2sync number_of_entries=\"%d\">\n", cardCount);
        // First card tags (categories)

        Map<String, String> categoryOidMap = new HashMap<String, String>();
        Map<Integer, String> cardIdOidMap = new HashMap<Integer, String>(cardCount * 4 / 3);
        Iterator<Category> categoryIterator = categoryDao.iterator();
        while (categoryIterator.hasNext()) {
            Category category = categoryIterator.next();
            String tagName = "__UNTAGGED__";
            String oId = generateOid();
            if (!Strings.isNullOrEmpty(category.getName())) {
                tagName = category.getName();
            }
            categoryOidMap.put(tagName, oId);
            outXml.printf("<log type=\"10\" o_id=\"%s\"><name>%s</name></log>\n", oId,
                    AMStringUtils.encodeXML(tagName));
        }
        // Then cards
        Iterator<Card> cardIterator = cardDao.iterator();
        while (cardIterator.hasNext()) {
            Card card = cardIterator.next();
            String front = card.getQuestion();
            String back = card.getAnswer();
            String oId = generateOid();
            cardIdOidMap.put(card.getId(), oId);
            outXml.printf("<log type=\"16\" o_id=\"%s\"><b>%s</b><f>%s</f></log>\n", oId,
                    AMStringUtils.encodeXML(back), AMStringUtils.encodeXML(front));
        }

        // Then learningData
        // <log card_t="1" fact_v="1.1" e="2.5" gr="-1" tags="5SfWDFGwqrlnGLDQxHHyG0" rt_rp_l="0" lps="0" l_rp="-1" n_rp="-1" ac_rp_l="0" rt_rp="0" ac_rp="0" type="6" o_id="7IXjCysHuCDtXo8hlFrK55" fact="7xmRCBH0WP0DZaxeFn5NLw"></log>
        Iterator<Card> cardIterator2 = cardDao.iterator();
        while (cardIterator2.hasNext()) {
            Card card = cardIterator2.next();
            categoryDao.refresh(card.getCategory());
            learningDataDao.refresh(card.getLearningData());
            String fact = cardIdOidMap.get(card.getId());
            String category = card.getCategory().getName();
            if (Strings.isNullOrEmpty(category)) {
                category = "__UNTAGGED__";
            }
            String tags = categoryOidMap.get(category);
            String oId = generateOid();

            // Needs to converter to unix time
            LearningData learningData = card.getLearningData();
            long l_rp = learningData.getLastLearnDate().getTime() / 1000;
            long n_rp = learningData.getNextLearnDate().getTime() / 1000;
            outXml.printf(
                    "<log card_t=\"1\" fact_v=\"1.1\" e=\"%f\" gr=\"%d\" tags=\"%s\" rt_rp_l=\"%d\" lps=\"%d\" l_rp=\"%d\" n_rp=\"%d\" ac_rp_l=\"%d\" rt_rp=\"%d\" ac_rp=\"%d\" type=\"6\" o_id=\"%s\" fact=\"%s\"></log>\n",
                    learningData.getEasiness(), learningData.getGrade(), tags,
                    learningData.getRetRepsSinceLapse(), learningData.getLapses(), l_rp, n_rp,
                    learningData.getAcqRepsSinceLapse(), learningData.getRetReps(), learningData.getAcqReps(),
                    oId, fact);
        }
        outXml.print("</openSM2sync>\n");
    } finally {
        if (helper != null) {
            AnyMemoDBOpenHelperManager.releaseHelper(helper);
        }
        if (outXml != null) {
            outXml.close();
        }
    }
}

From source file:com.nridge.ds.solr.SolrSchemaXML.java

public void save(PrintWriter aPW, String aTagName, int anIndentAmount) throws IOException {
    DataField dataField;/*  w  ww  .j  a v a  2 s  .  co  m*/

    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("<%s>%n", aTagName);
    saveComment(aPW, anIndentAmount);
    anIndentAmount++;

    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("<field name=\"text\" type=\"%s\" indexed=\"true\" stored=\"true\" multiValued=\"true\"/>%n",
            SOLR_TEXT_FIELD_TYPE_DEFAULT);

    DataBag dataBag = mDocument.getBag();
    int fieldCount = dataBag.count();
    for (int i = 0; i < fieldCount; i++) {
        dataField = dataBag.getByOffset(i);

        IOXML.indentLine(aPW, anIndentAmount);
        aPW.printf("<field name=\"%s\"", dataField.getName());
        if (dataField.isFeatureAssigned(Solr.FEATURE_SOLR_TYPE))
            aPW.printf(" type=\"%s\"", dataField.getFeature(Solr.FEATURE_SOLR_TYPE));
        else
            aPW.printf(" type=\"%s\"", mapFieldType(dataField));
        if (dataField.isFeatureAssigned(Solr.FEATURE_IS_INDEXED))
            aPW.printf(" indexed=\"%s\"", dataField.getFeature(Solr.FEATURE_IS_INDEXED));
        else
            aPW.printf(" indexed=\"true\"");
        if (dataField.isFeatureAssigned(Solr.FEATURE_IS_STORED))
            aPW.printf(" stored=\"%s\"", dataField.getFeature(Solr.FEATURE_IS_STORED));
        else
            aPW.printf(" stored=\"true\"");
        if (dataField.isFeatureTrue(Field.FEATURE_IS_REQUIRED))
            aPW.printf(" required=\"true\"");
        if (dataField.isMultiValue())
            aPW.printf(" multiValued=\"true\"");
        if (dataField.isFeatureTrue(Solr.FEATURE_IS_OMIT_NORMS))
            aPW.printf(" omitNorms=\"%s\"", dataField.getFeature(Solr.FEATURE_IS_OMIT_NORMS));
        if ((dataField.isFeatureTrue(Solr.FEATURE_IS_DEFAULT))
                && (StringUtils.isNotEmpty(dataField.getDefaultValue())))
            aPW.printf(" default=\"%s\"", dataField.getDefaultValue());
        aPW.printf("/>%n");
    }

    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("<field name=\"_version_\" type=\"long\" indexed=\"true\" stored=\"true\"/>%n");

    anIndentAmount--;
    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("</%s>%n", aTagName);

    dataField = dataBag.getPrimaryKeyField();
    if (dataField != null) {
        IOXML.indentLine(aPW, anIndentAmount);
        aPW.printf("<uniqueKey>%s</uniqueKey>%n", dataField.getName());
    }

    String fieldName;
    for (int i = 0; i < fieldCount; i++) {
        dataField = dataBag.getByOffset(i);

        fieldName = dataField.getName();
        if ((StringUtils.endsWith(fieldName, "_name")) || (StringUtils.endsWith(fieldName, "_title"))
                || (StringUtils.endsWith(fieldName, "_description"))
                || (StringUtils.endsWith(fieldName, "_content"))) {
            IOXML.indentLine(aPW, anIndentAmount);
            aPW.printf("<copyField source=\"%s\" dest=\"text\"/>%n", fieldName);
        }
    }
}

From source file:com.adobe.acs.commons.wcm.impl.AemEnvironmentIndicatorFilter.java

@Override
@SuppressWarnings("squid:S3776")
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain filterChain) throws IOException, ServletException {

    if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;//  w ww. java2s .  co  m
    }

    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;

    if (!this.accepts(request)) {
        filterChain.doFilter(request, response);
        return;
    }

    final BufferingResponse capturedResponse = new BufferingResponse(response);

    filterChain.doFilter(request, capturedResponse);

    boolean doInclude = true;
    if (ArrayUtils.isNotEmpty(excludedWCMModes)) {
        // Test for configured WCM modes, where the indicators are not displayed
        WCMMode wcmmode = extractFromRequest(request);

        if (wcmmode != null) {
            for (String m : excludedWCMModes) {
                if (StringUtils.equalsIgnoreCase(wcmmode.name(), m)) {
                    doInclude = false;
                    break;
                }
            }
        } else {
            // No wcmmode could be extracted from the request
        }
    }

    // Get contents
    final String contents = capturedResponse.getContents();

    if (doInclude && contents != null && StringUtils.contains(response.getContentType(), "html")) {

        final int bodyIndex = contents.indexOf("</body>");

        if (bodyIndex != -1) {
            final PrintWriter printWriter = response.getWriter();

            printWriter.write(contents.substring(0, bodyIndex));

            if (StringUtils.isNotBlank(css)) {
                printWriter.write("<style>" + css + " </style>");
                printWriter.write("<div id=\"" + DIV_ID + "\">" + innerHTML + "</div>");
            }

            if (StringUtils.isNotBlank(titlePrefix)) {
                printWriter.printf(TITLE_UPDATE_SCRIPT, titlePrefix);
            }

            printWriter.write(contents.substring(bodyIndex));
            return;
        }
    }

    if (contents != null) {
        response.getWriter().write(contents);
    }
}

From source file:com.nridge.core.base.io.xml.DataTableXML.java

/**
 * Saves the previous assigned bag/table (e.g. via constructor or set method)
 * to the print writer stream wrapped in a tag name specified in the parameter.
 *
 * @param aPW            PrintWriter stream instance.
 * @param aTagName       Tag name.//ww  w.  j  a v  a  2  s .c  om
 * @param anIndentAmount Indentation count.
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void save(PrintWriter aPW, String aTagName, int anIndentAmount) throws IOException {
    String cellValue;
    DataField dataField;
    int columnCount, rowCount;

    rowCount = mDataTable.rowCount();
    columnCount = mDataTable.columnCount();
    String tagName = StringUtils.remove(aTagName, StrUtl.CHAR_SPACE);
    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("<%s", tagName);
    IOXML.writeAttrNameValue(aPW, "type", IO.extractType(mDataTable.getClass().getName()));
    IOXML.writeAttrNameValue(aPW, "name", mDataTable.getName());
    IOXML.writeAttrNameValue(aPW, "dimensions", String.format("%d cols x %d rows", columnCount, rowCount));
    IOXML.writeAttrNameValue(aPW, "version", IO.DATATABLE_XML_FORMAT_VERSION);
    for (Map.Entry<String, String> featureEntry : mDataTable.getFeatures().entrySet())
        IOXML.writeAttrNameValue(aPW, featureEntry.getKey(), featureEntry.getValue());
    aPW.printf(">%n");

    if ((mContextTotal != 0) || (mContextLimit != 0)) {
        IOXML.indentLine(aPW, anIndentAmount + 2);
        aPW.printf("<Context");
        IOXML.writeAttrNameValue(aPW, "start", mContextStart);
        IOXML.writeAttrNameValue(aPW, "limit", mContextLimit);
        IOXML.writeAttrNameValue(aPW, "total", mContextTotal);
        aPW.printf("/>%n");
    }
    DataBag dataBag = new DataBag(mDataTable.getColumnBag());
    if (mSaveFieldsWithoutValues)
        dataBag.setAssignedFlagAll(true);
    DataBagXML dataBagXML = new DataBagXML(dataBag);
    dataBagXML.save(aPW, "Columns", anIndentAmount + 2);
    if (rowCount > 0) {
        IOXML.indentLine(aPW, anIndentAmount + 2);
        aPW.printf("<Rows");
        IOXML.writeAttrNameValue(aPW, "count", rowCount);
        aPW.printf(">%n");
        for (int row = 0; row < rowCount; row++) {
            IOXML.indentLine(aPW, anIndentAmount + 3);
            aPW.printf("<Row>%n");
            IOXML.indentLine(aPW, anIndentAmount + 4);
            for (int col = 0; col < columnCount; col++) {
                dataField = mDataTable.getFieldByRowCol(row, col);
                cellValue = dataField.collapse();
                if (StringUtils.isEmpty(cellValue))
                    aPW.printf("<C/>");
                else
                    aPW.printf("<C>%s</C>", StringEscapeUtils.escapeXml10(cellValue));
            }
            aPW.printf("%n");
            IOXML.indentLine(aPW, anIndentAmount + 3);
            aPW.printf("</Row>%n");
        }
        IOXML.indentLine(aPW, anIndentAmount + 2);
        aPW.printf("</Rows>%n");
    }
    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("</%s>%n", tagName);
}

From source file:es.tid.cep.esperanza.Rules.java

/**
 * Handles the HTTP <code>DELETE</code> method.
 *
 * @param request servlet request/*from ww  w . j  a  v a2  s.c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("application/json;charset=UTF-8");
    try {
        String ruleName = request.getPathInfo();
        ruleName = ruleName == null ? "" : ruleName.substring(1);
        logger.debug("rule asked for " + ruleName);
        EPAdministrator epa = epService.getEPAdministrator();

        if (ruleName.length() != 0) {
            EPStatement st = epa.getStatement(ruleName);
            if (st == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                out.printf("{\"error\":\"%s not found\"}\n", ruleName);
            } else {
                st.destroy();
                out.println(Utils.Statement2JSONObject(st));
            }
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            out.println("{\"error\":\"not rule specified for deleting\"}");
        }

    } catch (EPException epe) {
        logger.error("deleting statement", epe);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage()));
    } finally {
        out.close();
    }
}

From source file:es.tid.cep.esperanza.Rules.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*w ww  . j  a  va  2 s.  co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("application/json;charset=UTF-8");
    try {
        String ruleName = request.getPathInfo();
        ruleName = ruleName == null ? "" : ruleName.substring(1);
        logger.debug("rule asked for " + ruleName);
        EPAdministrator epa = epService.getEPAdministrator();

        if (ruleName.length() != 0) {
            EPStatement st = epa.getStatement(ruleName);
            if (st == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                out.printf("{\"error\":\"%s not found\"}\n", ruleName);
            } else {
                out.println(Utils.Statement2JSONObject(st));
            }
        } else {
            String[] sttmntNames = epa.getStatementNames();
            JSONArray ja = new JSONArray();
            for (String name : sttmntNames) {
                logger.debug("getting rule " + name);
                EPStatement st = epa.getStatement(name);
                ja.put(Utils.Statement2JSONObject(st));
            }
            out.println(ja.toString());
        }

    } catch (EPException epe) {
        logger.error("getting statement", epe);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage()));
    } finally {
        out.close();
    }
}