Example usage for java.io Writer write

List of usage examples for java.io Writer write

Introduction

In this page you can find the example usage for java.io Writer write.

Prototype

public void write(String str) throws IOException 

Source Link

Document

Writes a string.

Usage

From source file:com.nominanuda.web.http.BaseHttpTest.java

protected void dumpFailures(Writer w) throws IOException {
    for (String f : failures) {
        w.write("failure:" + f + "\n");
    }//from w w w .  j a v a  2 s.co  m
    w.flush();
}

From source file:com.adito.util.Utils.java

private static void stringEscape(String source, Writer out, boolean escapeSingleQuote) throws IOException {
    char[] chars = source.toCharArray();
    for (int i = 0; i < chars.length; ++i) {
        char ch = chars[i];
        switch (ch) {
        case '\b': // backspace (ASCII 8)
            out.write("\\b");
            break;
        case '\t': // horizontal tab (ASCII 9)
            out.write("\\t");
            break;
        case '\n': // newline (ASCII 10)
            out.write("\\n");
            break;
        case 11: // vertical tab (ASCII 11)
            out.write("\\v");
            break;
        case '\f': // form feed (ASCII 12)
            out.write("\\f");
            break;
        case '\r': // carriage return (ASCII 13)
            out.write("\\r");
            break;
        case '"': // double-quote (ASCII 34)
            out.write("\\\"");
            break;
        case '\'': // single-quote (ASCII 39)
            if (escapeSingleQuote)
                out.write("\\'");
            else/*w w w.java  2  s . co m*/
                out.write("'");
            break;
        case '\\': // literal backslash (ASCII 92)
            out.write("\\\\");
            break;
        default:
            if ((int) ch < 32 || (int) ch > 127) {
                out.write("\\u");
                zeropad(out, Integer.toHexString(ch).toUpperCase(), 4);
            } else {
                out.write(ch);
            }
            break;
        }
    }
}

From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Create a new file upload handler
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();

        try {/*from   ww w  .  jav a  2s .  c  om*/
            // Parse the request
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    System.out.println(
                            "Form field " + name + " with value " + Streams.asString(stream) + " detected.");
                } else {
                    System.out
                            .println("File field " + name + " with file name " + item.getName() + " detected.");
                    DataSource source = createDataSource(item);
                    SessionManager.get().getCurrentComposeMessage().addComposeAttachment(source);
                }

                JSONObject jsonResponse = null;
                try {
                    jsonResponse = new JSONObject();
                    jsonResponse.put("success", true);
                    jsonResponse.put("error", "Upload successful");
                } catch (Exception e) {

                }

                Writer w = new OutputStreamWriter(response.getOutputStream());
                w.write(jsonResponse.toString());
                w.close();

                stream.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.ikon.util.impexp.JcrRepositoryChecker.java

/**
 * Read document contents./*  w w  w .  ja  v a2s .com*/
 */
private static ImpExpStats readDocument(String token, String docPath, boolean versions, Writer out,
        InfoDecorator deco) throws PathNotFoundException, AccessDeniedException, RepositoryException,
        DatabaseException, IOException {
    log.debug("readDocument({})", docPath);
    DocumentModule dm = ModuleManager.getDocumentModule();
    File fsPath = new File(Config.NULL_DEVICE);
    ImpExpStats stats = new ImpExpStats();
    Document doc = dm.getProperties(token, docPath);

    try {
        FileOutputStream fos = new FileOutputStream(fsPath);
        InputStream is = dm.getContent(token, docPath, false);
        IOUtils.copy(is, fos);
        is.close();

        if (versions) { // Check version history
            for (Version ver : dm.getVersionHistory(token, docPath)) {
                is = dm.getContentByVersion(token, docPath, ver.getName());
                IOUtils.copy(is, fos);
                IOUtils.closeQuietly(is);
            }
        }

        fos.close();
        out.write(deco.print(docPath, doc.getActualVersion().getSize(), null));
        out.flush();

        // Stats
        stats.setSize(stats.getSize() + doc.getActualVersion().getSize());
        stats.setDocuments(stats.getDocuments() + 1);
    } catch (RepositoryException e) {
        log.error(e.getMessage());
        stats.setOk(false);
        out.write(deco.print(docPath, doc.getActualVersion().getSize(), e.getMessage()));
        out.flush();
    }

    return stats;
}

From source file:com.apress.prospringintegration.customadapters.outbound.ShellMessageWritingMessageEndpoint.java

protected int writeToShellCommand(String[] cmds, String msg) {
    try {//from   w ww . j a  v  a 2  s  .  c  o  m
        ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(cmds));
        Process proc = processBuilder.start();

        Writer streamWriter = null;

        try {
            streamWriter = new OutputStreamWriter(proc.getOutputStream());
            streamWriter.write(msg);
        } finally {
            IOUtils.closeQuietly(streamWriter);
        }

        int retVal = proc.waitFor();

        if (retVal != 0) {
            throw new RuntimeException("couldn't write message to 'write'");
        }

        return retVal;
    } catch (Throwable th) {
        throw new RuntimeException(th);
    }
}

From source file:com.amazonaws.codedeploy.AWSClients.java

private File createTestFile() throws IOException {
    File file = File.createTempFile("codedeploy-jenkins-plugin", ".txt");
    file.deleteOnExit();/*  w  w  w.  j av  a  2 s  . c  o  m*/

    Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
    writer.write("");
    writer.close();

    return file;
}

From source file:com.streamsets.datacollector.http.TestLogServlet.java

private String startServer() throws Exception {
    try {/*from   w  ww .j  a va 2s. c  om*/
        logFile = new File(baseDir, "test.log");
        Writer writer = new FileWriter(logFile);
        writer.write("hello\n");
        writer.close();
        Thread.sleep(1000); // for log files to have different lastModified timestamp
        oldLogFile = new File(baseDir, "test.log.1");
        writer = new FileWriter(oldLogFile);
        writer.write("bye\n");
        writer.close();
        File log4fConfig = new File(baseDir, "log4j.properties");
        writer = new FileWriter(log4fConfig);
        writer.write(LogUtils.LOG4J_APPENDER_STREAMSETS_FILE_PROPERTY + "=" + logFile.getAbsolutePath() + "\n");
        writer.write(LogUtils.LOG4J_APPENDER_STREAMSETS_LAYOUT_CONVERSION_PATTERN + "=" + CONVERSION_PATTERN);
        writer.close();

        int port = getRandomPort();
        Configuration conf = new Configuration();
        conf.set(WebServerTask.HTTP_PORT_KEY, port);
        conf.set(WebServerTask.AUTHENTICATION_KEY, "none");
        writer = new FileWriter(
                new File(System.getProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR),
                        "sdc.properties"));
        conf.save(writer);
        writer.close();
        ObjectGraph dagger = ObjectGraph.create(MainStandalonePipelineManagerModule.class);
        RuntimeInfo runtimeInfo = dagger.get(RuntimeInfo.class);
        runtimeInfo.setAttribute(RuntimeInfo.LOG4J_CONFIGURATION_URL_ATTR,
                new URL("file://" + baseDir + "/log4j.properties"));
        server = dagger.get(TaskWrapper.class);

        server.init();
        server.run();
        return "http://127.0.0.1:" + port;
    } catch (Exception e) {
        System.out.println("Got exception " + e);
        return null;
    }
}

From source file:net.cit.tetrad.resource.LoginResource.java

@RequestMapping(value = "/registLicensekey.do")
public void registLicensekey(HttpServletRequest request, HttpServletResponse response) {
    String licensekey = request.getParameter("licensekey");
    int resultCode = ColumnConstent.REGIST_FAIL_INVALID;
    try {/*from ww  w .  j  ava  2  s. co m*/
        String useros = System.getProperty("os.name");
        String userencoding = System.getProperty("file.encoding");
        String userlanguage = System.getProperty("user.language");

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("version", PropertiesNames.RELEASEVERSIONINFO);
        jsonObj.put("useros", useros);
        jsonObj.put("userencoding", userencoding);
        jsonObj.put("userlanguage", userlanguage);
        jsonObj.put("licensekey", licensekey);

        try {
            if (DistrCommunication.isCommercial("mongobird", jsonObj)) {
                resultCode = licenseManager.registLicensekey(licensekey);
                if (resultCode == ColumnConstent.REGIST_SUCCESS) {
                    Config.LICENSETYPE = licenseManager.getLicenseType(licensekey);
                    Config.LICENSEKEY = licenseManager.convertLicensekey(licensekey);
                }
            }
        } catch (DistrCommunicationException.CannotConnectServer e) {
            resultCode = ColumnConstent.REGIST_FAIL_CANNOTCONNECT;
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "no-cache");
        Writer writer = response.getWriter();
        writer.write(Integer.toString(resultCode));
        writer.flush();
    } catch (IOException e) {
        e.printStackTrace();
        log.error(e, e);
    }
}

From source file:com.evolveum.midpoint.cli.ninja.action.ExportAction.java

private void writeFooter(Writer writer) throws IOException {
    writer.write("</c:objects>\n");
}

From source file:com.intel.cosbench.controller.repository.RAMWorkloadRepository.java

private void appendToStops(WorkloadContext workload) throws IOException {
    String id = workload.getId();
    Writer writer = new BufferedWriter(new FileWriter(stops, true));
    try {// w  w  w . j  a va  2  s  . com
        writer.write(id);
        writer.write('\n');
        writer.flush();
    } finally {
        writer.close();
    }
    String path = stops.getAbsolutePath();
    LOGGER.debug("workload {} has been appened to {}", id, path);
}