Example usage for java.io PrintWriter append

List of usage examples for java.io PrintWriter append

Introduction

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

Prototype

public PrintWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:org.kalypso.model.hydrology.internal.preprocessing.writer.LzsimWriter.java

private static void writeLzsFile(final File lzsFile, final Catchment iniCatchment, final String iniDate,
        final IniHyd[] iniHyds) throws SimulationException {
    PrintWriter writer = null;

    try {/*  www  .  jav a  2s.  c  o m*/
        writer = new PrintWriter(lzsFile);

        // snow
        final Double h = iniCatchment.getH();
        final Double ws = iniCatchment.getWS();
        writer.format(Locale.US, LZS_FORMAT_STRING, iniDate, "snow", h, ws); //$NON-NLS-1$

        // groundwater
        final Double hgws = iniCatchment.getHwgs();
        final Double qb = iniCatchment.getQb();
        writer.format(Locale.US, LZS_FORMAT_STRING, iniDate, "gwsp", hgws, qb); //$NON-NLS-1$

        // hydrotops (interception storage content& soil moisture)
        writer.format(Locale.US, "%s h  %4d bodf\n", iniDate, iniHyds.length); //$NON-NLS-1$

        for (int i = 0; i < iniHyds.length; i++) {
            final IniHyd iniHyd = iniHyds[i];

            final Double bi = iniHyd.getBi();

            writer.format(Locale.US, "%4d%7.2f", i + 1, bi); //$NON-NLS-1$

            final List<Double> bofs = iniHyd.getBofs();
            for (final Double bof : bofs)
                writer.format(Locale.US, "%7.2f", bof); //$NON-NLS-1$

            writer.append("\n"); //$NON-NLS-1$
        }
        writer.close();
    } catch (final Throwable e) {
        final String msg = String.format(Messages.getString("LzsimWriter.7"), iniCatchment.getNaCatchmentID()); //$NON-NLS-1$
        throw new SimulationException(msg, e);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:org.wso2.carbon.analytics.servlet.AnalyticsSearchProcessor.java

/**
 * Search the table/*from  www  .  j a va  2 s  .co  m*/
 *
 * @param req  HttpRequest which has the required parameters to do the operation.
 * @param resp HttpResponse which returns the result of the intended operation.
 * @throws ServletException
 * @throws IOException
 */
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String sessionId = req.getHeader(AnalyticsAPIConstants.SESSION_ID);
    if (sessionId == null || sessionId.trim().isEmpty()) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
    } else {
        try {
            ServiceHolder.getAuthenticator().validateSessionId(sessionId);
        } catch (AnalyticsAPIAuthenticationException e) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
        }
        String operation = req.getParameter(AnalyticsAPIConstants.OPERATION);
        boolean securityEnabled = Boolean
                .parseBoolean(req.getParameter(AnalyticsAPIConstants.ENABLE_SECURITY_PARAM));
        int tenantIdParam = MultitenantConstants.INVALID_TENANT_ID;
        if (!securityEnabled)
            tenantIdParam = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.TENANT_ID_PARAM));
        String userName = req.getParameter(AnalyticsAPIConstants.USERNAME_PARAM);
        String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
        String query = req.getParameter(AnalyticsAPIConstants.QUERY);
        if (operation != null && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.SEARCH_OPERATION)) {
            int start = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.START_PARAM));
            int count = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.COUNT_PARAM));
            Type sortByFieldType = new TypeToken<List<SortByField>>() {
            }.getType();
            Gson gson = new Gson();
            List<SortByField> sortByFields = gson
                    .fromJson(req.getParameter(AnalyticsAPIConstants.SORT_BY_FIELDS_PARAM), sortByFieldType);
            try {
                List<SearchResultEntry> searchResult;
                if (!securityEnabled)
                    searchResult = ServiceHolder.getAnalyticsDataService().search(tenantIdParam, tableName,
                            query, start, count, sortByFields);
                else
                    searchResult = ServiceHolder.getSecureAnalyticsDataService().search(userName, tableName,
                            query, start, count, sortByFields);
                //Have to do this because there is possibility of getting sublist which cannot be serialized
                searchResult = new ArrayList<>(searchResult);
                resp.getOutputStream().write(GenericUtils.serializeObject(searchResult));
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.SEARCH_COUNT_OPERATION)) {
            try {
                int count;
                if (!securityEnabled)
                    count = ServiceHolder.getAnalyticsDataService().searchCount(tenantIdParam, tableName,
                            query);
                else
                    count = ServiceHolder.getSecureAnalyticsDataService().searchCount(userName, tableName,
                            query);
                PrintWriter output = resp.getWriter();
                output.append(AnalyticsAPIConstants.SEARCH_COUNT).append(AnalyticsAPIConstants.SEPARATOR)
                        .append(String.valueOf(count));
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.SEARCH_WITH_AGGREGATES_OPERATION)) {
            try {
                Gson gson = new Gson();
                AnalyticsIterator<Record> iterator;
                String groupByField = req.getParameter(AnalyticsAPIConstants.GROUP_BY_FIELD_PARAM);
                Type aggregateFieldsMapType = new TypeToken<List<AggregateField>>() {
                }.getType();
                List<AggregateField> fields = gson.fromJson(
                        req.getParameter(AnalyticsAPIConstants.AGGREGATING_FIELDS), aggregateFieldsMapType);
                String parentPathAsString = req.getParameter(AnalyticsAPIConstants.AGGREGATE_PARENT_PATH);
                Type aggregateParentPath = new TypeToken<List<String>>() {
                }.getType();
                List<String> parentPath = gson.fromJson(parentPathAsString, aggregateParentPath);
                int aggregateLevel = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.AGGREGATE_LEVEL));
                int noOfRecords = Integer
                        .parseInt(req.getParameter(AnalyticsAPIConstants.AGGREGATE_NO_OF_RECORDS));
                AggregateRequest aggregateRequest = new AggregateRequest();
                aggregateRequest.setTableName(tableName);
                aggregateRequest.setQuery(query);
                aggregateRequest.setFields(fields);
                aggregateRequest.setGroupByField(groupByField);
                aggregateRequest.setAggregateLevel(aggregateLevel);
                aggregateRequest.setParentPath(parentPath);
                aggregateRequest.setNoOfRecords(noOfRecords);
                if (!securityEnabled)
                    iterator = ServiceHolder.getAnalyticsDataService().searchWithAggregates(tenantIdParam,
                            aggregateRequest);
                else
                    iterator = ServiceHolder.getSecureAnalyticsDataService().searchWithAggregates(userName,
                            aggregateRequest);
                while (iterator.hasNext()) {
                    Record record = iterator.next();
                    GenericUtils.serializeObject(record, resp.getOutputStream());
                }
                iterator.close();
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "unsupported operation performed with get request!");
            log.error("unsupported operation performed : " + operation + " with get request!");
        }
    }
}

From source file:org.emergent.plumber.StorageServlet.java

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String username = (String) req.getAttribute(ATTRIB_USERNAME_KEY);
    String colname = (String) req.getAttribute(ATTRIB_COLNAME_KEY);
    String entryid = (String) req.getAttribute(ATTRIB_ENTRYID_KEY);

    boolean singleton = !MiscUtil.isEmpty(entryid);
    String idlist = req.getParameter("ids");
    boolean deleteall = !singleton && MiscUtil.isEmpty(idlist);

    Connection conn = null;//from   w  ww .java  2  s  . co m
    PreparedStatement st = null;
    ResultSet rs = null;
    try {
        conn = getDatabaseConnection(req);
        int userid = DbUtil.getUserId(conn, username);

        String selectStr = "DELETE FROM EngineWbo" + " WHERE userid = ?" + " AND engine = ?";

        if (!deleteall) {
            selectStr += " AND nodeid = ?";
        }

        st = conn.prepareStatement(selectStr);

        int modCnt = 0;

        if (!deleteall) {

            ArrayList<String> ids = new ArrayList<String>();
            if (singleton) {
                ids.add(entryid);
            } else {
                String[] idarray = idlist.split(",");
                if (idarray != null) {
                    for (String idval : idarray) {
                        if (!MiscUtil.isEmpty(idval))
                            ids.add(idval);
                    }
                }
            }

            for (String idval : ids) {
                st.setInt(1, userid);
                st.setString(2, colname);
                st.setString(3, idval);
                modCnt += st.executeUpdate();
            }
        } else {
            st.setInt(1, userid);
            st.setString(2, colname);
            modCnt = st.executeUpdate();
        }

    } catch (SQLException e) {
        log(e.getMessage(), e);
    } finally {
        MiscUtil.close(rs);
        MiscUtil.close(st);
        MiscUtil.close(conn);
    }

    resp.setContentType("application/json");
    String weaveTimestamp = getServerTimestampString(req);
    PrintWriter writer = resp.getWriter();
    writer.append(String.format("{\"modified\":%s}", weaveTimestamp));
}

From source file:org.apache.sling.dynamicinclude.IncludeTagFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
    final String resourceType = slingRequest.getResource().getResourceType();

    final Configuration config = configurationWhiteboard.getConfiguration(slingRequest, resourceType);
    if (config == null) {
        chain.doFilter(request, response);
        return;//from   w  w  w.j av  a  2s  .c om
    }

    final IncludeGenerator generator = generatorWhiteboard.getGenerator(config.getIncludeTypeName());
    if (generator == null) {
        LOG.error("Invalid generator: " + config.getIncludeTypeName());
        chain.doFilter(request, response);
        return;
    }

    final PrintWriter writer = response.getWriter();
    final String url = getUrl(config, slingRequest);
    if (url == null) {
        chain.doFilter(request, response);
        return;
    }

    if (config.getAddComment()) {
        writer.append(String.format(COMMENT, StringEscapeUtils.escapeHtml(url), resourceType));
    }

    // Only write the includes markup if the required, configurable request
    // header is present
    if (shouldWriteIncludes(config, slingRequest)) {
        String include = generator.getInclude(url);
        LOG.debug(include);
        writer.append(include);
    } else {
        chain.doFilter(request, response);
    }
}

From source file:org.nuxeo.ecm.jsf2.migration.impl.MigrationServiceImpl.java

@Override
public void analyzeProject(File report, List<File> listFiles, boolean doMigration, boolean format)
        throws IOException {
    // If the file does not exist, it is created
    if (!report.exists()) {
        report.createNewFile();//w  w w. j ava2s . c  o  m
    }

    PrintWriter printWriter = new PrintWriter(report);
    printWriter.append("##############################\n");
    printWriter.append("# Migration report for JSF 2 #\n");
    printWriter.append("##############################\n\n");

    List<FileReport> listReports = new ArrayList<FileReport>();
    for (File file : listFiles) {
        try {
            listReports.add(analyzeFile(file, true, doMigration, format));
        } catch (DocumentException ex) {
            System.out.println(String.format("Error while reading file %s.", file.getName()));
            System.out.println(ex.getMessage());
        } catch (JaxenException jex) {
            System.out.println(String.format("Error while parsing file %s.", file.getName()));
            System.out.println(jex.getMessage());
        }
    }

    // Generate the content report
    generateReport(listReports, printWriter);

    printWriter.close();
}

From source file:de.openali.odysseus.chart.ext.base.layer.TooltipFormatter.java

public String format() {
    final StringWriter out = new StringWriter();
    final PrintWriter pw = new PrintWriter(out);

    if (m_header != null) {
        pw.println(m_header);//from   w  w w .  j av  a2 s .  c o  m
        pw.println();
    }

    for (final String[] texts : m_lines) {
        for (int i = 0; i < texts.length; i++) {
            final String alignedText = alignText(texts, i);
            pw.append(alignedText);

            /* one space between columns */
            if (i != texts.length - 1)
                pw.append(' ');
        }

        pw.println();
    }

    for (String footer : m_footer)
        pw.println(footer);

    pw.flush();
    return StringUtils.chomp(out.toString());
}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.ImportBatchClassUploadServlet.java

private void printWriterMethod(PrintWriter printWriter, String zipWorkFlowName, String tempOutputUnZipDir,
        String systemFolderPath, List<String> uncList, boolean isWorkflowDeployed, boolean isWorkflowEqual) {
    printWriter.write("workFlowName:" + zipWorkFlowName);
    printWriter.append("|");
    printWriter.append("filePath:").append(tempOutputUnZipDir);
    printWriter.append("|");
    printWriter.write("workflowDeployed:" + isWorkflowDeployed);
    printWriter.append("|");
    printWriter.write("workflowEqual:" + isWorkflowEqual);
    printWriter.append("|");
    printWriter.write("workflowExistInBatchClass:" + ((uncList == null || uncList.size() == 0) ? false : true));
    printWriter.append("|");
    printWriter.write("systemFolderPath:" + systemFolderPath);
    printWriter.append("|");
    printWriter.flush();/*from ww  w . java  2  s  . c o  m*/
}

From source file:org.nuxeo.ecm.jsf2.migration.impl.MigrationServiceImpl.java

/**
 * Generate the summary part of the report.
 *
 * @param listResults List of result of analyze of each file.
 * @param report The text output stream of the report to complete.
 * @param reportProp Properties file containing the message to display.
 * @throws IOException//ww w .j  av  a  2  s . co  m
 */
@SuppressWarnings("boxing")
private void generateSummaryReport(List<FileReport> listResults, PrintWriter report, Properties reportProp)
        throws IOException {

    report.append("Summary\n");
    report.append("#######\n");
    report.append("Number of files analyzed : " + listResults.size() + "\n");

    for (EnumTypeMigration type : EnumTypeMigration.values()) {
        int occurence = 0;
        for (FileReport fileReport : listResults) {
            if (fileReport.getListMigrations().containsKey(type)) {
                occurence += fileReport.getListMigrations().get(type);
            }
        }

        // If the type of migration is present, it's added to the report
        if (occurence > 0) {
            report.append(" * [" + type.getSeverity() + "] ");
            String key = type.getKeyMessage() + SUFFIX_SUMMARIZED_MESSAGE;
            report.append(MessageFormat.format(reportProp.getProperty(key), occurence));
            report.append('\n');
        }
    }

    report.append("\n");
}

From source file:org.nuxeo.ecm.jsf2.migration.impl.MigrationServiceImpl.java

/**
 * Generate the summary part of the report.
 *
 * @param listResults List of result of analyze of each file.
 * @param report The text output stream of the report to complete.
 * @param reportProp Properties file containing the message to display.
 * @throws IOException/*from ww  w  . j  a  va 2 s  .com*/
 */
private void generateDetailedReport(List<FileReport> listResults, PrintWriter report, Properties reportProp)
        throws IOException {
    report.append("Details\n");
    report.append("#######");
    for (FileReport result : listResults) {
        report.append('\n');
        // Create a section for the file
        report.append(result.getAttachedFile().getName());
        report.append("\n-----------------------\n");

        // If nothing was reported, display a generic message
        if (result.getListMigrations().size() == 0) {
            report.append(reportProp.getProperty(NOTHING_MESSAGE));
            report.append('\n');
        }

        // Get the actions to do for the migration
        for (EnumTypeMigration type : result.getListMigrations().keySet()) {
            List<String> listParams = result.getListParams().get(type);
            String key = type.getKeyMessage() + SUFFIX_DETAILED_MESSAGE;
            if (!reportProp.containsKey(key)) {
                key = type.getKeyMessage() + SUFFIX_SUMMARIZED_MESSAGE;
            }
            String messageReport = MessageFormat.format(reportProp.getProperty(key), listParams.toArray());
            report.append("[" + type.getSeverity() + "] ");
            report.append(messageReport);
            report.append('\n');
        }
    }
}

From source file:quickforms.controller.UpdateLookup.java

/**
 * Handles the HTTP/*w  w w.ja  v a 2 s .c om*/
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Map<String, String[]> inParams = request.getParameterMap();
    Map<String, String[]> params = new HashMap<String, String[]>(inParams);//inParams is read only
    System.out.println("Updating Lookup");
    response.setContentType("text/html;charset=UTF-8");
    String application = request.getParameter("app");
    String lookup = request.getParameter("lookup");
    String values = request.getParameter("values");
    System.out.println(values);
    Database db = null;
    String json = null;
    PrintWriter out = response.getWriter();
    try {
        InitialContext cxt = new InitialContext();
        DataSource ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/" + application);
        db = new Database(ds);

        db.updateLookup(application, lookup, jsonToHashMap(values), new ArrayList<LookupPair>());

    } catch (Exception e) {
        Logger.log(application, e);
        out.append(e.toString());
        db.disconnect();
    }

    out.close();
}