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:edu.utsa.sifter.IndexResource.java

@Path("exportDocFeatures")
@GET/*from  www  .  ja v a  2  s  . c  o m*/
@Produces({ "text/csv" })
public StreamingOutput getDocExportFeatures(@QueryParam("id") final String searchID) throws IOException {
    final SearchResults results = searchID != null ? State.Searches.get(searchID) : null;

    //    System.err.println("exporting results for query " + searchID);

    if (results != null) {
        final IndexInfo info = State.IndexLocations.get(results.IndexID);
        final IndexSearcher searcher = getCommentsSearcher(results.IndexID + "comments-idx", info.Path);
        final BookmarkSearcher markStore = searcher == null ? null : new BookmarkSearcher(searcher, null);

        final ArrayList<Result> docs = results.retrieve(0, results.TotalHits);

        // System.err.println("query export has " + results.TotalHits + " items, size of array is " + hits.size());
        final StreamingOutput stream = new StreamingOutput() {
            public void write(OutputStream output) throws IOException, WebApplicationException {
                final OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");
                try {
                    writer.write(
                            "ID,Score,Name,Path,Extension,Size,Modified,Accessed,Created,Cell,CellDistance,Bookmark Created,Bookmark Comment\n");
                    int n = 0;
                    for (Result doc : docs) {
                        for (double feat : feats) {
                            if (markStore != null) {
                                markStore.executeQuery(parseQuery(doc.ID, "Docs"));
                                final ArrayList<Bookmark> marks = markStore.retrieve();

                                if (marks == null) {
                                    writeDocRecordFeatures(doc, null, writer, feat);
                                    ++n;
                                } else {
                                    for (Bookmark mark : marks) {
                                        writeDocRecordFeatures(doc, mark, writer, feat);
                                        ++n;
                                    }
                                }
                            } else {
                                writeDocRecordFeatures(doc, null, writer, feat);
                                ++n;
                            }
                        } // feature loop
                    }
                    // System.err.println("Streamed out " + n + " items");
                    writer.flush();
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
        return stream;
        //      return Response.ok(stream, "text/csv").header("content-disposition","attachment; filename=\"export.csv\"").build();
    } else {
        HttpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }
}

From source file:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java

private void fillExecutionReqBody() throws IOException, SrfException {
    _con.setDoOutput(true);// w ww. jav  a2s . c  o m
    JSONObject data = new JSONObject();
    JSONObject testParams = new JSONObject();
    JSONObject ciParameters = new JSONObject();
    if (srfTestId != null && srfTestId.length() > 0) {
        data.put("testYac", applyJobParams(srfTestId));
    } else if (srfTagNames != null && !srfTagNames.isEmpty()) {
        String[] tagNames = normalizeTags();
        data.put("tags", tagNames);
    } else
        throw new SrfException("Both test id and test tags are empty");

    if (srfTunnelName != null && srfTunnelName.length() > 0) {
        data.put("tunnelName", srfTunnelName);
    }

    if (data.size() == 0) {
        throw new IOException("Wrong filter");
    }

    testParams.put("filter", data);
    Properties ciProps = new Properties();
    Properties props = new Properties();
    String buildNumber = applyJobParams(srfBuildNumber);
    String releaseNumber = applyJobParams(srfReleaseNumber);
    if (buildNumber != null && buildNumber.length() > 0) {
        data.put("build", buildNumber);
    }
    if (releaseNumber != null && releaseNumber.length() > 0)
        data.put("release", releaseNumber);

    this.logger.print(String.format("Required build & release: %1s %2s\n\r", buildNumber, releaseNumber));
    HashMap<String, String> paramObj = new HashMap<String, String>();
    int cnt = 0;

    if (srfTestParameters != null && !srfTestParameters.isEmpty()) {
        cnt = srfTestParameters.size();
        if (cnt > 0)
            logger.print("Parameters: \n\r");
        for (int i = 0; i < cnt; i++) {
            String name = srfTestParameters.get(i).getName();
            String val = applyJobParams(srfTestParameters.get(i).getValue());
            paramObj.put(name, val);
            logger.print(String.format("%1s : %2s\n\r", name, val));
        }
    }

    if (cnt > 0)
        data.put("params", paramObj);
    //add request header

    //     con.setRequestProperty("session-context", context);
    try {
        OutputStream out = _con.getOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(out);
        writer.write(data.toString());
        writer.flush();
        out.flush();
        out.close();
    } catch (ProtocolException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    }
}

From source file:com.google.ytd.SubmitActivity.java

private String uploadMetaData(String filePath, boolean retry) throws IOException {
    String uploadUrl = INITIAL_UPLOAD_URL;

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);//from  w  w  w  .ja  v  a 2  s .  c  om
    urlConnection.setRequestProperty("Content-Type", "application/atom+xml");
    urlConnection.setRequestProperty("Slug", filePath);
    String atomData;

    String title = getTitleText();
    String description = getDescriptionText();
    String category = DEFAULT_VIDEO_CATEGORY;
    this.tags = DEFAULT_VIDEO_TAGS;

    if (!Util.isNullOrEmpty(this.getTagsText())) {
        this.tags = this.getTagsText();
    }

    if (this.videoLocation == null) {
        String template = Util.readFile(this, R.raw.gdata).toString();
        atomData = String.format(template, title, description, category, this.tags);
    } else {
        String template = Util.readFile(this, R.raw.gdata_geo).toString();
        atomData = String.format(template, title, description, category, this.tags, videoLocation.getLatitude(),
                videoLocation.getLongitude());
    }

    OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
    outStreamWriter.write(atomData);
    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();
    if (responseCode < 200 || responseCode >= 300) {
        // The response code is 40X
        if ((responseCode + "").startsWith("4") && retry) {
            Log.d(LOG_TAG, "retrying to fetch auth token for " + youTubeName);
            this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken);
            // Try again with fresh token
            return uploadMetaData(filePath, false);
        } else {
            throw new IOException(String.format("response code='%s' (code %d)" + " for %s",
                    urlConnection.getResponseMessage(), responseCode, urlConnection.getURL()));
        }
    }

    return urlConnection.getHeaderField("Location");
}

From source file:com.cellbots.httpserver.HttpCommandServer.java

public void handle(final HttpServerConnection conn, final HttpContext context)
        throws HttpException, IOException {
    HttpRequest request = conn.receiveRequestHeader();
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");

    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST") && !method.equals("PUT")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }//from  w w  w.  jav  a 2  s. com

    // Get the requested target. This is the string after the domain name in
    // the URL. If the full URL was http://mydomain.com/test.html, target
    // will be /test.html.
    String target = request.getRequestLine().getUri();
    //Log.w(TAG, "*** Request target: " + target);

    // Gets the requested resource name. For example, if the full URL was
    // http://mydomain.com/test.html?x=1&y=2, resource name will be
    // test.html
    final String resName = getResourceNameFromTarget(target);
    UrlParams params = new UrlParams(target);
    //Log.w(TAG, "*** Request LINE: " + request.getRequestLine().toString());
    //Log.w(TAG, "*** Request resource: " + resName);
    if (method.equals("POST") || method.equals("PUT")) {
        byte[] entityContent = null;
        // Gets the content if the request has an entity.
        if (request instanceof HttpEntityEnclosingRequest) {
            conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            if (entity != null) {
                entityContent = EntityUtils.toByteArray(entity);
            }
        }
        response.setStatusCode(HttpStatus.SC_OK);
        if (serverListener != null) {
            serverListener.onRequest(resName, params.keys, params.values, entityContent);
        }
    } else if (dataMap.containsKey(resName)) { // The requested resource is
                                               // a byte array
        response.setStatusCode(HttpStatus.SC_OK);
        response.setHeader("Content-Type", dataMap.get(resName).contentType);
        response.setEntity(new ByteArrayEntity(dataMap.get(resName).resource));
    } else { // Resource is a file recognized by the app
        String fileName = resourceMap.containsKey(resName) ? resourceMap.get(resName).resource : resName;
        String contentType = resourceMap.containsKey(resName) ? resourceMap.get(resName).contentType
                : "text/html";
        Log.d(TAG, "*** mapped resource: " + fileName);
        Log.d(TAG, "*** checking for file: " + rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName);
        response.setStatusCode(HttpStatus.SC_OK);
        final File file = new File(rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName);
        if (file.exists() && !file.isDirectory()) {
            response.setStatusCode(HttpStatus.SC_OK);
            FileEntity body = new FileEntity(file, URLConnection.guessContentTypeFromName(fileName));
            response.setHeader("Content-Type", URLConnection.guessContentTypeFromName(fileName));
            response.setEntity(body);
        } else if (file.isDirectory()) {
            response.setStatusCode(HttpStatus.SC_OK);
            EntityTemplate body = new EntityTemplate(new ContentProducer() {
                public void writeTo(final OutputStream outstream) throws IOException {
                    OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                    ArrayList<String> fileList = getDirListing(file);
                    String resp = "{ \"list\": [";
                    for (String fl : fileList) {
                        resp += "\"" + fl + "\",";
                    }
                    resp = resp.substring(0, resp.length() - 1);
                    resp += "]}";
                    writer.write(resp);
                    writer.flush();
                }
            });
            body.setContentType(contentType);
            response.setEntity(body);
        } else if (resourceMap.containsKey(resName)) {
            EntityTemplate body = new EntityTemplate(new ContentProducer() {
                public void writeTo(final OutputStream outstream) throws IOException {
                    OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                    writer.write(resourceMap.get(resName).resource);
                    writer.flush();
                }
            });
            body.setContentType(contentType);
            response.setEntity(body);
        } else {
            response.setStatusCode(HttpStatus.SC_NOT_FOUND);
            response.setEntity(new StringEntity("Not Found"));
        }
    }
    conn.sendResponseHeader(response);
    conn.sendResponseEntity(response);
    conn.flush();
    conn.shutdown();
}

From source file:CloudManagerAPI.java

private void writePayload(HttpURLConnection connection, final String payload) throws IOException {
    OutputStreamWriter writer = null;
    try {//from w ww .j a  va2  s.com
        final String contentLength = String.valueOf(payload.length());
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Length", contentLength);

        // construct the writer and write request
        writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(payload);
        writer.flush();
    } finally {
        closeStream(writer);
    }
}

From source file:com.akop.bach.parser.Parser.java

protected void writeToSd(String filename, String text) {
    java.io.OutputStreamWriter osw = null;
    File root = Environment.getExternalStorageDirectory();

    try {//from www.j a  v  a 2  s  .co m
        java.io.FileOutputStream fOut = new FileOutputStream(root + "/" + filename);
        osw = new java.io.OutputStreamWriter(fOut);
        osw.write(text);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (osw != null) {
            try {
                osw.flush();
                osw.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:TimestreamsTests.java

/**
 * Performs HTTP post for a given URL/*ww w.  j  a  va2 s  .c  om*/
 * 
 * @param url
 *            is the URL to get
 * @param params
 *            is a URL encoded string in the form x=y&a=b...
 * @return a String with the contents of the get
 */
private Map<String, List<String>> doPut(URL url, String params) {
    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));

        connection.setDoInput(true);
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(params);
        out.close();
        Map<String, List<String>> responseHeaderFields = connection.getHeaderFields();
        System.out.println(responseHeaderFields);
        if (responseHeaderFields.get(null).get(0).equals("HTTP/1.1 200 OK")) {
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            System.out.println(response);
        }
        return responseHeaderFields;
    } catch (IOException e1) {
        fail("Post " + url + " failed: " + e1.getLocalizedMessage());
    }

    return null;
}

From source file:eu.elf.license.LicenseQueryHandler.java

/**
 * Performs HTTP GET or POST query to the backend server
 *
 * @param queryURL       The request string that is to be sent to the server
 * @param queryType      - Type of the query (get || post)
 * @param payloadForPost - POST payload, empty string for GET queries
 * @return The response of the server/*ww w.  j  a  va 2s.  c om*/
 * @throws IOException
 */
public StringBuffer doHTTPQuery(URL queryURL, String queryType, String payloadForPost,
        Boolean useBasicAuthentication) throws IOException {
    StringBuffer sbuf = new StringBuffer();
    URLConnection uc = null;
    HttpURLConnection httpuc;
    HttpsURLConnection httpsuc;
    String WFSResponseLine = "";
    String userPassword = "";
    String encoding = "";

    //System.out.println("queryURL: "+queryURL.toString());
    //System.out.println("PayloadForPost: "+payloadForPost);

    try {

        httpuc = (HttpURLConnection) queryURL.openConnection();
        httpuc.setDoInput(true);
        httpuc.setDoOutput(true);

        if (useBasicAuthentication == true) {
            userPassword = this.username + ":" + this.password;
            encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
            httpuc.setRequestProperty("Authorization", "Basic " + encoding);
        }

        if (queryType.equals("get")) {
            //System.out.println("queryURL: "+queryURL);

            BufferedReader buf = new BufferedReader(new InputStreamReader(httpuc.getInputStream(), "utf-8"));

            while ((WFSResponseLine = buf.readLine()) != null) {
                sbuf.append(WFSResponseLine);
            }

            buf.close();
        } else if (queryType.equals("post")) {
            //System.out.println("PayloadForPost"+payloadForPost);

            httpuc.setRequestMethod("POST");
            httpuc.setRequestProperty("Content-Type", "text/xml;charset=UTF8");
            httpuc.setRequestProperty("Content-Type", "text/plain");

            OutputStreamWriter osw = new OutputStreamWriter(httpuc.getOutputStream(), Charset.forName("UTF-8"));
            osw.write(URLDecoder.decode(payloadForPost, "UTF-8"));

            osw.flush();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpuc.getInputStream(), Charset.forName("UTF8")));

            while ((WFSResponseLine = in.readLine()) != null) {
                //System.out.println("WFSResponseLine: "+WFSResponseLine);

                sbuf.append(WFSResponseLine);
            }

            in.close();
            osw.close();
        }

    } catch (IOException ioe) {
        throw ioe;
    }

    return sbuf;
}

From source file:com.qualogy.qafe.gwt.server.RPCServiceImpl.java

public String getUI(String xmlUI) throws GWTServiceException {
    String url = null;/* ww  w. ja v a 2 s  .c  om*/
    if (service.isValidXML(xmlUI)) {
        logger.fine("XML Send by client : \n" + xmlUI);

        try {

            String urlBase = ApplicationCluster.getInstance()
                    .getConfigurationItem(Configuration.FLEX_DEMO_WAR_URL);
            if (urlBase == null || urlBase.length() == 0) {
                urlBase = getThreadLocalRequest().getScheme() + "://" + getThreadLocalRequest().getServerName()
                        + ":" + getThreadLocalRequest().getServerPort() + "/qafe-web-flex";
            }

            String urlStore = urlBase + "/store";
            logger.fine("URL Store is =" + urlStore);

            OutputStreamWriter wr = null;
            BufferedReader rd = null;

            try {
                // Send data
                URL requestURL = new URL(urlStore);
                URLConnection conn = requestURL.openConnection();
                conn.setDoOutput(true);
                wr = new OutputStreamWriter(conn.getOutputStream());
                String data = "xml" + "=" + xmlUI;
                wr.write(data);
                wr.flush();

                // Get the response
                rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = rd.readLine()) != null) {
                    url = urlBase + "/index.jsp?uuid=" + line;
                    logger.fine(url);
                }
            } finally {
                wr.close();
                rd.close();
            }
        } catch (Exception e) {
            throw handleException(e);
        }
    } else {
        try {
            service.getUIFromXML(xmlUI, null, null, getLocale());
        } catch (Exception e) {
            throw handleException(e);
        }
    }
    return url;
}

From source file:com.denimgroup.threadfix.service.defects.utils.RestUtilsImpl.java

@Nonnull
private InputStream postUrl(String urlString, String data, String username, String password,
        String contentType) {//from w w w  . java2s.  c  o  m
    URL url;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        LOG.warn("URL used for POST was bad: '" + urlString + "'");
        throw new RestUrlException(e, "Received a malformed server URL.");
    }

    HttpURLConnection httpConnection = null;
    OutputStreamWriter outputWriter = null;
    try {
        if (proxyService == null) {
            httpConnection = (HttpURLConnection) url.openConnection();
        } else {
            httpConnection = proxyService.getConnectionWithProxyConfig(url, classToProxy);
        }

        setupAuthorization(httpConnection, username, password);

        httpConnection.addRequestProperty("Content-Type", contentType);
        httpConnection.addRequestProperty("Accept", contentType);

        httpConnection.setDoOutput(true);
        outputWriter = new OutputStreamWriter(httpConnection.getOutputStream());
        outputWriter.write(data);
        outputWriter.flush();

        InputStream is = httpConnection.getInputStream();

        return is;
    } catch (IOException e) {
        LOG.warn("IOException encountered trying to post to URL with message: " + e.getMessage());
        if (httpConnection == null) {
            LOG.warn(
                    "HTTP connection was null so we cannot do further debugging of why the HTTP request failed");
        } else {
            try {
                InputStream errorStream = httpConnection.getErrorStream();
                if (errorStream == null) {
                    LOG.warn("Error stream from HTTP connection was null");
                } else {
                    LOG.warn(
                            "Error stream from HTTP connection was not null. Attempting to get response text.");
                    setPostErrorResponse(IOUtils.toString(errorStream));
                    LOG.warn("Error text in response was '" + getPostErrorResponse() + "'");
                    throw new RestIOException(e, getPostErrorResponse(),
                            "Unable to get response from server. Error text was: " + getPostErrorResponse(),
                            getStatusCode(httpConnection));
                }
            } catch (IOException e2) {
                LOG.warn("IOException encountered trying to read the reason for the previous IOException: "
                        + e2.getMessage(), e2);
                throw new RestIOException(e2, "Unable to read response from server." + e2.getMessage(),
                        getStatusCode(httpConnection));
            }
        }
        throw new RestIOException(e, "Unable to read response from server." + e.toString());
    } finally {
        if (outputWriter != null) {
            try {
                outputWriter.close();
            } catch (IOException e) {
                LOG.warn("Failed to close output stream in postUrl.", e);
            }
        }
    }
}