Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:org.opendatakit.odktables.entity.serialization.SimpleHTMLMessageWriter.java

@Override
public void writeTo(T o, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> map, OutputStream rawStream)
        throws IOException, WebApplicationException {
    String encoding = getCharsetAsString(mediaType);
    try {/*from  ww  w.j  a v a 2  s.  co m*/
        if (!encoding.equalsIgnoreCase(DEFAULT_ENCODING)) {
            throw new IllegalArgumentException("charset for the response is not utf-8");
        }
        // write it to a byte array
        ByteArrayOutputStream bas = new ByteArrayOutputStream(8192);
        OutputStreamWriter w = new OutputStreamWriter(bas, Charset.forName(ApiConstants.UTF8_ENCODE));
        w.write("<html><head></head><body>");
        w.write(mapper.writeValueAsString(o));
        w.write("</body></html>");
        w.flush();
        w.close();
        // get the array
        byte[] bytes = bas.toByteArray();
        map.putSingle(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION);
        map.putSingle("Access-Control-Allow-Origin", "*");
        map.putSingle("Access-Control-Allow-Credentials", "true");

        rawStream.write(bytes);
        rawStream.flush();
        rawStream.close();

    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:com.vmware.identity.HealthStatusController.java

/**
 * Handle GET request for the health status
 *///  w w w.  j ava2  s  .  com
@RequestMapping(value = "/HealthStatus", method = RequestMethod.GET)
public void getHealthStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    Validate.notNull(request, "HttpServletRequest should not be null.");
    Validate.notNull(response, "HttpServletResponse should not be null.");

    // we are going to be very simple in this request processing for now
    // and just report if we are "reachable"
    // we also do not worry about the sender's identity
    // (in reality CM will include the SAML token in the header,
    // and so generally it means they successfully obtained it through sso ...)
    logger.debug("Handling getHealthStatus HTTP request; method:{} url:{}", request.getMethod(),
            request.getRequestURL());

    try {
        response.setHeader("Content-Type", "application/xml; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), UTF8);
        try {
            osw.write(healthStatusXml);
        } finally {
            osw.close();
        }

        logger.debug("Handled getHealthStatus HTTP request; method:{} url:{}", request.getMethod(),
                request.getRequestURL());
    } catch (Exception e) {
        logger.error("Failed to return Health Status with [%s]." + e.toString(), e);
        throw new ServletException(e); // let the exception bubble up and show in the response since this is not user-facing
    }
}

From source file:net.facework.core.http.ModInternationalization.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }/*from  ww  w .j  a v  a2  s  .  co m*/

    final EntityTemplate body = new EntityTemplate(new ContentProducer() {
        @Override
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            writer.write(mJSON);
            writer.flush();
        }
    });

    response.setStatusCode(HttpStatus.SC_OK);
    body.setContentType("text/json; charset=UTF-8");
    response.setEntity(body);

}

From source file:com.aylien.textapi.HttpSender.java

public String post(String url, Map<String, String> parameters, Map<String, String> headers)
        throws IOException, TextAPIException {
    try {/*w  w w  . ja  va 2 s .co  m*/
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        for (Map.Entry<String, String> header : headers.entrySet()) {
            connection.setRequestProperty(header.getKey(), header.getValue());
        }
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", USER_AGENT);

        StringBuilder payload = new StringBuilder();
        for (Map.Entry<String, String> e : parameters.entrySet()) {
            if (payload.length() > 0) {
                payload.append('&');
            }
            payload.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=')
                    .append(URLEncoder.encode(e.getValue(), "UTF-8"));
        }

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(payload.toString());
        writer.close();

        responseHeaders = connection.getHeaderFields();

        InputStream inputStream = connection.getResponseCode() == 200 ? connection.getInputStream()
                : connection.getErrorStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        if (connection.getResponseCode() >= 300) {
            extractTextAPIError(response.toString());
        }

        return response.toString();
    } catch (MalformedURLException e) {
        throw new IOException(e);
    }
}

From source file:com.gu.management.logging.Log4JManagerServlet.java

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

    response.setContentType("text/html");
    OutputStreamWriter fileWriter = new OutputStreamWriter(response.getOutputStream());

    fileWriter.write(MANAGEMENT_PAGE_HEAD);

    @SuppressWarnings({ "unchecked" })
    List<Logger> loggers = sortLoggers(LogManager.getCurrentLoggers());

    for (Logger logger : loggers) {
        fileWriter.write(String.format(LOGGER_TABLE_ROW, logger.getName(), generateOptionsFor(logger),
                logger.getEffectiveLevel()));
    }/*from  w w w . j a v  a  2  s  .c  o  m*/

    fileWriter.write(MANAGEMENT_PAGE_FOOT);

    fileWriter.flush();
}

From source file:com.gu.management.switching.SwitchboardServlet.java

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

    response.setContentType("text/html");

    String switchToShow = request.getParameter("switch");

    OutputStreamWriter fileWriter = new OutputStreamWriter(response.getOutputStream());

    fileWriter.write(MANAGEMENT_PAGE_HEAD);

    for (Switchable switchable : switches) {

        if (StringUtils.isEmpty(switchToShow) || switchToShow.equals(switchable.getWordForUrl())) {
            fileWriter.write(String.format(SWITCH_TABLE_ROW, switchable.getWordForUrl(),
                    switchable.getDescription(), getButtonsFor(switchable)));
        }/* w  ww  .  j a va2  s  .  co  m*/
    }

    fileWriter.write(MANAGEMENT_PAGE_FOOT);

    fileWriter.flush();
}

From source file:de.elggconnect.elggconnectclient.webservice.AuthGetToken.java

@Override
/**/* w  w w . ja v  a2 s.c  o  m*/
 * Run the AuthGetTokeb Web API Method
 */
public Long execute() {

    //Build url Parameter String
    String urlParameters = APIMETHOD + "&username=" + this.username + "&password=" + this.password;

    //Try to execute the API Method
    try {

        URL url = new URL(userAuthentication.getBaseURL());
        URLConnection conn = url.openConnection();

        //add user agent to the request header
        conn.setRequestProperty("User-Agent", USER_AGENT);

        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(urlParameters);
        writer.flush();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        //Read the response JSON
        StringBuilder text = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            text.append(line).append("\n");
        }

        JSONObject json = (JSONObject) new JSONParser().parse(text.toString());

        this.status = (Long) json.get("status");
        if (this.status != -1L) {
            this.authToken = (String) json.get("result");

            //Save the AuthToken
            userAuthentication.setAuthToken((String) json.get("result"));
        }

        writer.close();
        reader.close();

    } catch (Exception e) {
        System.err.println(e.getMessage());

    }

    return this.status;
}

From source file:net.mindengine.oculus.frontend.web.controllers.trm.tasks.AjaxTaskSearchController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    verifyPermissions(request);// www. j  a  va  2 s. co  m

    OutputStream os = response.getOutputStream();
    response.setContentType("text/xml");

    String rId = request.getParameter("id");

    OutputStreamWriter w = new OutputStreamWriter(os);

    w.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    w.write("<tree id=\"" + rId + "\" >");

    if (rId.equals("0")) {
        w.write("<item text=\"My Tasks\" " + "id=\"mytasks\" "
                + "im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" child=\"1\" "
                + " nocheckbox=\"1\" >");
        w.write("</item>");
        w.write("<item text=\"Shared Tasks\" " + "id=\"shared\" "
                + "im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" child=\"1\" "
                + " nocheckbox=\"1\" >");
        w.write("</item>");
    } else {
        User user = getUser(request);

        Collection<TrmTask> tasks = null;
        Long projectId = null;
        String strProject = request.getParameter("projectId");
        if (strProject != null) {
            projectId = Long.parseLong(strProject);
        }

        if (rId.equals("mytasks")) {
            tasks = trmDAO.getUserTasks(user.getId(), projectId);

        } else if (rId.equals("shared")) {
            Collection<User> users = trmDAO.getUsersWithSharedTasks(user.getId(), projectId);
            for (User u : users) {
                w.write("<item text=\"" + XmlUtils.escapeXml(u.getName()) + "\" " + "id=\"u" + u.getId() + "\" "
                        + "im0=\"workflow-icon-user.png\" im1=\"workflow-icon-user.png\" im2=\"workflow-icon-user.png\" child=\"1\" "
                        + " nocheckbox=\"1\" >");
                w.write("</item>");
            }
        } else if (rId.startsWith("u")) {
            Long userId = Long.parseLong(rId.substring(1));
            tasks = trmDAO.getUserSharedTasks(userId, projectId);
        }

        if (tasks != null) {
            for (TrmTask task : tasks) {
                w.write("<item text=\"" + XmlUtils.escapeXml(task.getName()) + "\" " + "id=\"t" + task.getId()
                        + "\" " + "im0=\"iconTask.png\" im1=\"iconTask.png\" im2=\"iconTask.png\" child=\"0\" "
                        + " >");
                w.write("</item>");
            }
        }

    }

    w.write("</tree>");
    w.flush();
    os.flush();
    os.close();
    return null;
}

From source file:com.athena.chameleon.engine.utils.FileUtil.java

/**
 * /* w  w  w  .j  av  a 2  s .  co m*/
 * ? ??  .
 *
 * @param zipFilePath ? 
 * @param unzipDirPath ?   
 * @param declaredEncoding ?  
 * @return String  ?  
 * @throws IOException
 */
public static String extract(String zipFilePath, String unzipDirPath, String declaredEncoding)
        throws IOException {
    ZipFile zipFile = null;

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("[ZipUtil] zipFilePath :" + zipFilePath);
        }

        String unZipDir = (unzipDirPath == null)
                ? zipFilePath.substring(0, zipFilePath.lastIndexOf('.')) + File.separator
                : unzipDirPath + File.separator;
        if (logger.isDebugEnabled()) {
            logger.debug("[ZipUtil] unzipDirPath :" + unZipDir);
        }

        zipFile = new ZipFile(zipFilePath, "EUC-KR");

        Enumeration<?> e = zipFile.getEntries();
        for (; e.hasMoreElements();) {
            FileOutputStream output = null;
            InputStream input = null;
            String entryName;

            try {
                byte[] data;
                ZipEntry entry = (ZipEntry) e.nextElement();

                if (logger.isDebugEnabled()) {
                    logger.debug("[ZipUtil] current entry:" + entry.getName());
                }

                entryName = entry.getName().replace('\\', '/');
                if (entry.isDirectory()) {
                    File dir = new File(unZipDir + entry.getName());
                    if (!dir.exists() && !dir.mkdirs()) {
                        throw new IOException("[ZipUtil] make directory fail");
                    }
                } else {
                    File outputFile = null;

                    try {
                        outputFile = new File(unZipDir + entry.getName());

                        if (entry.getSize() == 0 && entry.getName().indexOf('.') == -1) {
                            throw new Exception("[ZipUtil] This file may be a directory");
                        }

                        File parentDir = outputFile.getParentFile();
                        if (!parentDir.exists() && !parentDir.mkdirs()) {
                            throw new IOException("[ZipUtil] make directory fail");
                        }

                        input = zipFile.getInputStream(entry);
                        output = new FileOutputStream(outputFile);

                        String changeTarget = PropertyUtil.getProperty("unzip.change.target");

                        if (changeTarget.indexOf(
                                entryName.substring(entryName.lastIndexOf(".") + 1, entryName.length())) > -1) {

                            OutputStreamWriter osr = new OutputStreamWriter(output, declaredEncoding);

                            CharsetDetector detector = new CharsetDetector();
                            data = IOUtils.toByteArray(input, entry.getSize());
                            IOUtils.closeQuietly(input);
                            detector.setDeclaredEncoding(declaredEncoding);
                            detector.setText(data);
                            Reader reader = detector.detect().getReader();

                            int buffer = 0;
                            while (true) {
                                buffer = reader.read();
                                if (buffer == -1)
                                    break;

                                osr.write(buffer);
                            }
                            osr.close();

                        } else {
                            int len = 0;
                            byte buffer[] = new byte[1024];
                            while ((len = input.read(buffer)) > 0)
                                output.write(buffer, 0, len);
                        }

                    } catch (Exception ex2) {
                        ex2.printStackTrace();
                        if (!outputFile.exists() && !outputFile.mkdirs()) {
                            throw new IOException("[ZipUtil] make directory fail");
                        }
                    }
                }
            }

            catch (IOException ex) {
                throw ex;
            }

            catch (Exception ex) {
                throw new IOException("[ZipUtil] extract fail", ex);
            }

            finally {
                if (input != null) {
                    input.close();
                }
                if (output != null) {
                    output.close();
                }
            }
        }
        return unZipDir;
    }

    catch (IOException e) {
        e.printStackTrace();
        throw e;
    }

    finally {
        if (zipFile != null) {
            zipFile.close();
        }
    }
}

From source file:musite.io.xml.XMLEscapeWriter.java

public void write(OutputStream os, Object fieldValue) throws IOException {
    if (os == null || fieldValue == null)
        return;//from   w w  w.ja  va 2  s . com

    OutputStreamWriter osw = new OutputStreamWriter(os);

    String str = StringEscapeUtils.escapeXml(fieldValue.toString());

    for (int i = 0; i < getIndent(); i++)
        osw.write("\t");

    osw.write(str);
    osw.flush();
}