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(String str, int off, int len) throws IOException 

Source Link

Document

Writes a portion of a string.

Usage

From source file:JLabelDragSource.java

public Object getTransferData(DataFlavor fl) {
    if (!isDataFlavorSupported(fl)) {
        return null;
    }/*from  ww  w. j av a 2  s.  c  o m*/

    if (fl.equals(DataFlavor.stringFlavor)) {
        // String - return the text as a String
        return label.getText() + " (DataFlavor.stringFlavor)";
    } else if (fl.equals(jLabelFlavor)) {
        // The JLabel itself - just return the label.
        return label;
    } else {
        // Plain text - return an InputStream
        try {
            String targetText = label.getText() + " (plain text flavor)";
            int length = targetText.length();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            OutputStreamWriter w = new OutputStreamWriter(os);
            w.write(targetText, 0, length);
            w.flush();
            byte[] bytes = os.toByteArray();
            w.close();
            return new ByteArrayInputStream(bytes);
        } catch (IOException e) {
            return null;
        }
    }
}

From source file:gov.medicaid.verification.BaseSOAPClient.java

/**
 * Invokes the web service using the request provided.
 *
 * @param serviceURL the end point reference
 * @param original the payload/*w w w  . j  ava 2 s. c o  m*/
 * @return the response
 * @throws IOException for IO errors while executing the request
 * @throws TransformerException for any transformation errors
 */
protected String invoke(String serviceURL, String original) throws IOException, TransformerException {
    URL url = new URL(serviceURL);
    HttpURLConnection rc = (HttpURLConnection) url.openConnection();
    rc.setRequestMethod("POST");
    rc.setDoOutput(true);
    rc.setDoInput(true);
    rc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");

    System.out.println("before transform:" + original);
    String request = transform(requestXSLT, original);
    System.out.println("after transform:" + request);

    int len = request.length();
    rc.setRequestProperty("Content-Length", Integer.toString(len));
    rc.connect();
    OutputStreamWriter out = new OutputStreamWriter(rc.getOutputStream());
    out.write(request, 0, len);
    out.flush();

    InputStreamReader read;
    try {
        read = new InputStreamReader(rc.getInputStream());
    } catch (IOException e) {
        read = new InputStreamReader(rc.getErrorStream());
    }

    try {
        String response = IOUtils.toString(read);
        System.out.println("actual result:" + response);
        String transformedResponse = transform(responseXSLT, response);
        System.out.println("transformed result:" + transformedResponse);
        return transformedResponse;
    } finally {
        read.close();
        rc.disconnect();
    }
}

From source file:com.cubusmail.server.services.CubusmailServlet.java

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

    String fileName = request.getSession().getServletContext().getRealPath(request.getServletPath());
    BufferedReader reader = new BufferedReader(new FileReader(fileName));

    OutputStream outputStream = response.getOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(outputStream);
    char[] inBuf = new char[1024];
    int len = 0;//from w  w w . java 2s.  c o m
    try {
        while ((len = reader.read(inBuf)) > 0) {
            writer.write(inBuf, 0, len);
        }
    } catch (Throwable e) {
        log.error(e.getMessage(), e);
    }

    writer.flush();
    writer.close();
    outputStream.flush();
    outputStream.close();
}

From source file:org.ala.preprocess.ColFamilyNamesProcessor.java

/**
 * Copy the raw file into the repository.
 * //from   w w w  . ja  v  a  2  s. c  o m
 * @param filePath
 * @param uri
 * @param infosourceUri
 * @param mimeType
 * @return
 * @throws FileNotFoundException
 * @throws Exception
 * @throws IOException
 */
private int copyRawFileToRepo(String filePath, String uri, String infosourceUri, String mimeType)
        throws FileNotFoundException, Exception, IOException {
    InfoSource infoSource = infoSourceDAO.getByUri(infosourceUri);

    Reader ir = new FileReader(filePath);
    DocumentOutputStream dos = repository.getDocumentOutputStream(infoSource.getId(), uri, mimeType);

    //write the file to RAW file in the repository
    OutputStreamWriter w = new OutputStreamWriter(dos.getOutputStream());

    //read into buffer
    char[] buff = new char[1000];
    int read = 0;
    while ((read = ir.read(buff)) > 0) {
        w.write(buff, 0, read);
    }
    w.flush();
    w.close();
    return dos.getId();
}

From source file:br.ufjf.taverna.core.TavernaClientBase.java

protected HttpURLConnection request(String endpoint, TavernaServerMethods method, int expectedResponseCode,
        String acceptData, String contentType, String filePath, String putData) throws TavernaException {
    HttpURLConnection connection = null;

    try {/* www  . jav a 2 s.  c o m*/
        String uri = this.getBaseUri() + endpoint;
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        String authorization = this.username + ":" + this.password;
        String encodedAuthorization = "Basic " + new String(Base64.encodeBase64(authorization.getBytes()));
        connection.setRequestProperty("Authorization", encodedAuthorization);
        connection.setRequestMethod(method.getMethod());

        if (acceptData != null) {
            connection.setRequestProperty("Accept", acceptData);
        }

        if (contentType != null) {
            connection.setRequestProperty("Content-Type", contentType);
        }

        if (TavernaServerMethods.GET.equals(method)) {

        } else if (TavernaServerMethods.POST.equals(method)) {
            FileReader fr = new FileReader(filePath);
            char[] buffer = new char[1024 * 10];
            int read;
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            while ((read = fr.read(buffer)) != -1) {
                writer.write(buffer, 0, read);
            }
            writer.flush();
            writer.close();
            fr.close();
        } else if (TavernaServerMethods.PUT.equals(method)) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(putData);
            writer.flush();
            writer.close();
        } else if (TavernaServerMethods.DELETE.equals(method)) {

        }

        int responseCode = connection.getResponseCode();
        if (responseCode != expectedResponseCode) {
            throw new TavernaException(
                    String.format("Invalid HTTP Response Code. Expected %d, actual %d, URL %s",
                            expectedResponseCode, responseCode, url));
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return connection;
}

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

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

    try {/*from  www .  j a  v a2  s .c  om*/
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                logger.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.cubusmail.server.services.ShowMessageSourceServlet.java

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

    try {//ww w .  j  av  a 2s. c om
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                log.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.sun.identity.console.user.model.UMChangeUserPasswordModelImpl.java

private byte[] getBytes(char[] charArr) {
    try {/*from   w w  w . j a  va 2s.  c  o m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStreamWriter outputStreamWriter = null;
        try {
            outputStreamWriter = new OutputStreamWriter(baos);
            outputStreamWriter.write(charArr, 0, charArr.length);
        } finally {
            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }
        }
        return baos.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException("Could not convert char[] to byte[]", ex);
    }
}

From source file:org.tellervo.desktop.wsi.JaxbResponseHandler.java

public T toDocument(final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }//from w w  w .  j  a  v a  2  s  . com

    InputStream instream = entity.getContent();
    if (instream == null) {
        return null;
    }

    String charset = EntityUtils.getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    /**
     * Methodology
     * 1) Save XML to disk temporarily (it can be big, 
     *       we might want to look at it as a raw file)
     * 2) If we can't write to disk, throw IOException
     * 3) Try to parse
     * 4) Throw error with the raw document (it's malformed XML)
     */

    File tempFile = null;
    OutputStreamWriter fileOut = null;
    boolean usefulFile = false; // preserve this file outside this local context?

    try {
        tempFile = File.createTempFile("tellervo", ".xml");
        fileOut = new OutputStreamWriter(new FileOutputStream(tempFile, false), charset);

        // ok, dump the webservice xml to a file
        BufferedReader webIn = new BufferedReader(new InputStreamReader(instream, charset));

        char indata[] = new char[8192];
        int inlen;

        // write the file out
        while ((inlen = webIn.read(indata)) >= 0)
            fileOut.write(indata, 0, inlen);

        fileOut.close();
    } catch (IOException ioe) {
        // File I/O failed (?!) Clean up and re-throw the IOE.
        if (fileOut != null)
            fileOut.close();
        if (tempFile != null)
            tempFile.delete();

        throw ioe;
    }

    try {
        Unmarshaller um = context.createUnmarshaller();
        ValidationEventCollector vec = new ValidationEventCollector();

        // validate against this schema
        um.setSchema(validateSchema);

        // collect events instead of throwing exceptions
        um.setEventHandler(vec);

        // do the magic!
        Object ret = um.unmarshal(tempFile);

        // typesafe way of checking if this is the right type!
        return returnClass.cast(ret);
    } catch (UnmarshalException ume) {
        usefulFile = true;
        throw new ResponseProcessingException(ume, tempFile);

    } catch (JAXBException jaxbe) {
        usefulFile = true;
        throw new ResponseProcessingException(jaxbe, tempFile);

    } catch (ClassCastException cce) {
        usefulFile = true;
        throw new ResponseProcessingException(cce, tempFile);

    } finally {
        // clean up and delete
        if (tempFile != null) {
            if (!usefulFile)
                tempFile.delete();
            else
                tempFile.deleteOnExit();
        }
    }

    /*
    try {
       um.un
    } catch (JDOMException jdome) {
    // this document must be malformed
    usefulFile = true;
    throw new XMLParsingException(jdome, tempFile);
       } 
    } catch (IOException ioe) {
       // well, something there failed and it was lower level than just bad XML...
       if(tempFile != null) {
    usefulFile = true;
    throw new XMLParsingException(ioe, tempFile);
       }
               
       throw new XMLParsingException(ioe);
               
    } finally {
       // make sure we closed our file
       if(fileOut != null)
    fileOut.close();
               
       // make sure we delete it, too
       if(tempFile != null)
       {
    if (!usefulFile)
       tempFile.delete();
    else
       tempFile.deleteOnExit();
       }
    }
    */
}

From source file:com.redhat.rhn.frontend.action.common.DownloadFile.java

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String path = "";
    Map params = (Map) request.getAttribute(PARAMS);
    String type = (String) params.get(TYPE);
    if (type.equals(DownloadManager.DOWNLOAD_TYPE_KICKSTART)) {
        return getStreamInfoKickstart(mapping, form, request, response, path);
    } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER)) {
        String url = ConfigDefaults.get().getCobblerServerUrl() + (String) params.get(URL_STRING);
        KickstartHelper helper = new KickstartHelper(request);
        String data = "";
        if (helper.isProxyRequest()) {
            data = KickstartManager.getInstance().renderKickstart(helper.getKickstartHost(), url);
        } else {//  w w  w  .  ja v a  2 s  .co  m
            data = KickstartManager.getInstance().renderKickstart(url);
        }
        setTextContentInfo(response, data.length());
        return getStreamForText(data.getBytes());
    } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER_API)) {
        // read data from POST body
        String postData = new String();
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            postData += line;
        }

        // Send data
        URL url = new URL(ConfigDefaults.get().getCobblerServerUrl() + "/cobbler_api");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        // this will write POST /download//cobbler_api instead of
        // POST /cobbler_api, but cobbler do not mind
        wr.write(postData, 0, postData.length());
        wr.flush();
        conn.connect();

        // Get the response
        String output = new String();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = rd.readLine()) != null) {
            output += line;
        }
        wr.close();

        KickstartHelper helper = new KickstartHelper(request);
        if (helper.isProxyRequest()) {
            // Search/replacing all instances of cobbler host with host
            // we pass in, for use with Spacewalk Proxy.
            output = output.replaceAll(ConfigDefaults.get().getCobblerHost(), helper.getForwardedHost());
        }

        setXmlContentInfo(response, output.length());
        return getStreamForXml(output.getBytes());
    } else {
        Long fileId = (Long) params.get(FILEID);
        Long userid = (Long) params.get(USERID);
        User user = UserFactory.lookupById(userid);
        if (type.equals(DownloadManager.DOWNLOAD_TYPE_PACKAGE)) {
            Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg());
            setBinaryContentInfo(response, pack.getPackageSize().intValue());
            path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + pack.getPath();
            return getStreamForBinary(path);
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_SOURCE)) {
            Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg());
            List<PackageSource> src = PackageFactory.lookupPackageSources(pack);
            if (!src.isEmpty()) {
                setBinaryContentInfo(response, src.get(0).getPackageSize().intValue());
                path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + src.get(0).getPath();
                return getStreamForBinary(path);
            }
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_REPO_LOG)) {
            Channel c = ChannelFactory.lookupById(fileId);
            ChannelManager.verifyChannelAdmin(user, fileId);
            StringBuilder output = new StringBuilder();
            for (String fileName : ChannelManager.getLatestSyncLogFiles(c)) {
                RandomAccessFile file = new RandomAccessFile(fileName, "r");
                long fileLength = file.length();
                if (fileLength > DOWNLOAD_REPO_LOG_LENGTH) {
                    file.seek(fileLength - DOWNLOAD_REPO_LOG_LENGTH);
                    // throw away text till end of the actual line
                    file.readLine();
                } else {
                    file.seek(0);
                }
                String line;
                while ((line = file.readLine()) != null) {
                    output.append(line);
                    output.append("\n");
                }
                file.close();
                if (output.length() > DOWNLOAD_REPO_LOG_MIN_LENGTH) {
                    break;
                }
            }

            setTextContentInfo(response, output.length());
            return getStreamForText(output.toString().getBytes());
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_CRASHFILE)) {
            CrashFile crashFile = CrashManager.lookupCrashFileByUserAndId(user, fileId);
            String crashPath = crashFile.getCrash().getStoragePath();
            setBinaryContentInfo(response, (int) crashFile.getFilesize());
            path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + crashPath + "/"
                    + crashFile.getFilename();
            return getStreamForBinary(path);

        }
    }

    throw new UnknownDownloadTypeException(
            "The specified download type " + type + " is not currently supported");

}