Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:org.exist.xquery.modules.httpclient.PUTFunction.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence response = null;//from   ww w  . j  av  a 2  s  .com

    // must be a URL
    if (args[0].isEmpty()) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    //get the url
    String url = args[0].itemAt(0).getStringValue();

    //get the payload
    Item payload = args[1].itemAt(0);

    //get the persist state
    boolean persistState = args[2].effectiveBooleanValue();

    String indentLevel = (args.length >= 5 && !args[4].isEmpty()) ? args[4].itemAt(0).toString() : null;

    RequestEntity entity = null;

    if (Type.subTypeOf(payload.getType(), Type.NODE)) {
        //serialize the node to SAX
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        OutputStreamWriter osw = new OutputStreamWriter(baos, UTF_8);

        IndentingXMLWriter xmlWriter = new IndentingXMLWriter(osw);
        Properties outputProperties = new Properties();
        outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8");
        if (indentLevel != null) {
            outputProperties.setProperty(OutputKeys.INDENT, "yes");
            outputProperties.setProperty(EXistOutputKeys.INDENT_SPACES, indentLevel);
        } else {
            outputProperties.setProperty(OutputKeys.INDENT, "no");
        }
        xmlWriter.setOutputProperties(outputProperties);

        SAXSerializer sax = new SAXSerializer();

        sax.setReceiver(xmlWriter);

        try {
            payload.toSAX(context.getBroker(), sax, new Properties());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            throw new XPathException(this, e);
        }
        entity = new ByteArrayRequestEntity(baos.toByteArray(), "application/xml; charset=utf-8");

    } else if (Type.subTypeOf(payload.getType(), Type.BASE64_BINARY)) {

        entity = new ByteArrayRequestEntity(payload.toJavaObject(byte[].class));

    } else {

        try {
            entity = new StringRequestEntity(payload.getStringValue(), "text/text; charset=utf-8", "UTF-8");
        } catch (UnsupportedEncodingException uee) {
            uee.printStackTrace();
        }
    }

    //setup PUT request
    PutMethod put = new PutMethod(url);

    put.setRequestEntity(entity);

    //setup PUT Request Headers
    if (!args[3].isEmpty()) {
        setHeaders(put, ((NodeValue) args[3].itemAt(0)).getNode());
    }

    try {

        //execute the request
        response = doRequest(context, put, persistState, null, null);

    } catch (IOException ioe) {
        throw (new XPathException(this, ioe.getMessage(), ioe));
    } finally {
        put.releaseConnection();
    }

    return (response);
}

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 {/*from   w w w .  j  a  v  a  2s  . c o  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");

}

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) {// www .  j a  v a 2  s .  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);
            }
        }
    }
}

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/*from   w  ww  .  j a v a  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:org.eclipse.rdf4j.http.client.RDF4JProtocolSession.java

protected void upload(final Reader contents, String baseURI, final RDFFormat dataFormat, boolean overwrite,
        boolean preserveNodeIds, Action action, Resource... contexts)
        throws IOException, RDFParseException, RepositoryException, UnauthorizedException {
    final Charset charset = dataFormat.hasCharset() ? dataFormat.getCharset() : Charset.forName("UTF-8");

    HttpEntity entity = new AbstractHttpEntity() {

        private InputStream content;

        public long getContentLength() {
            return -1; // don't know
        }/*from w  w  w . ja va2s. c  om*/

        public Header getContentType() {
            return new BasicHeader("Content-Type",
                    dataFormat.getDefaultMIMEType() + "; charset=" + charset.name());
        }

        public boolean isRepeatable() {
            return false;
        }

        public boolean isStreaming() {
            return true;
        }

        public synchronized InputStream getContent() throws IOException, IllegalStateException {
            if (content == null) {
                ByteArrayOutputStream buf = new ByteArrayOutputStream();
                writeTo(buf);
                content = new ByteArrayInputStream(buf.toByteArray());
            }
            return content;
        }

        public void writeTo(OutputStream out) throws IOException {
            try {
                OutputStreamWriter writer = new OutputStreamWriter(out, charset);
                IOUtil.transfer(contents, writer);
                writer.flush();
            } finally {
                contents.close();
            }
        }
    };

    upload(entity, baseURI, overwrite, preserveNodeIds, action, contexts);
}

From source file:biblivre3.cataloging.bibliographic.BiblioBO.java

private File createIsoFile(Database database) {
    try {//  w  w w . ja  va  2  s.  c  o m
        File file = File.createTempFile("bib3_", null);
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
        BiblioDAO biblioDao = new BiblioDAO();
        int limit = 100;
        int recordCount = biblioDao.countAll(database);

        for (int offset = 0; offset < recordCount; offset += limit) {
            ArrayList<RecordDTO> records = biblioDao.list(database, MaterialType.ALL, offset, limit, false);
            for (RecordDTO dto : records) {
                writer.write(dto.getIso2709());
                writer.write(ApplicationConstants.LINE_BREAK);
            }
        }
        writer.flush();
        writer.close();
        return file;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return null;
}

From source file:net.sourceforge.squirrel_sql.fw.datasetviewer.cellcomponent.DataTypeBigDecimal.java

/**
 * Construct an appropriate external representation of the object
 * and write it to a file.//from   ww w  . j av a  2 s . c om
 * Errors are returned by throwing an IOException containing the
 * cause of the problem as its message.
 * <P>
 * DataType is responsible for validating that the given text
 * text from a Popup JTextArea can be converted to an object.
 * This text-to-object conversion is the same as validateAndConvertInPopup,
 * which may be used internally by the object to do the validation.
 * <P>
 * The DataType object must flush and close the output stream before returning.
 * Typically it will create another object (e.g. an OutputWriter), and
 * that is the object that must be flushed and closed.
 * 
 * <P>
 * File is assumed to be and ASCII string of digits
 * representing a value of this data type.
 */
public void exportObject(FileOutputStream outStream, String text) throws IOException {

    OutputStreamWriter outWriter = new OutputStreamWriter(outStream);

    // check that the text is a valid representation
    StringBuffer messageBuffer = new StringBuffer();
    validateAndConvertInPopup(text, null, messageBuffer);
    if (messageBuffer.length() > 0) {
        // there was an error in the conversion
        throw new IOException(new String(messageBuffer));
    }

    // just send the text to the output file
    outWriter.write(text);
    outWriter.flush();
    outWriter.close();
}

From source file:com.netscape.cms.servlet.connector.ConnectorServlet.java

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

    boolean running_state = CMS.isInRunningState();

    if (!running_state)
        throw new IOException("CMS server is not ready to serve.");

    HttpServletRequest req = request;/*from   www . ja va  2  s.  c om*/
    HttpServletResponse resp = response;

    CMSRequest cmsRequest = newCMSRequest();

    // set argblock
    cmsRequest.setHttpParams(CMS.createArgBlock(toHashtable(request)));

    // set http request
    cmsRequest.setHttpReq(request);

    // set http response
    cmsRequest.setHttpResp(response);

    // set servlet config.
    cmsRequest.setServletConfig(mConfig);

    // set servlet context.
    cmsRequest.setServletContext(mConfig.getServletContext());

    char[] content = null;
    String encodedreq = null;
    String method = null;
    int len = -1;
    IPKIMessage msg = null;
    IPKIMessage replymsg = null;

    // NOTE must read all bufer before redoing handshake for
    // ssl client auth for client auth to work.

    // get request method
    method = req.getMethod();

    // get content length
    len = request.getContentLength();

    // get content, a base 64 encoded serialized request.
    if (len > 0) {
        InputStream in = request.getInputStream();
        InputStreamReader inreader = new InputStreamReader(in, "UTF8");
        BufferedReader reader = new BufferedReader(inreader, len);

        content = new char[len];
        int done = reader.read(content, 0, len);
        int total = done;

        while (done >= 0 && total < len) {
            done = reader.read(content, total, len - total);
            total += done;
        }
        reader.close();
        encodedreq = new String(content);
    }

    // force client auth handshake, validate RA and get RA's Id.
    // NOTE must do this after all contents are read for ssl
    // redohandshake to work

    X509Certificate peerCert;

    try {
        peerCert = getPeerCert(req);
    } catch (EBaseException e) {
        mAuthority.log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT"));
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    if (peerCert == null) {
        // XXX log something here.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // authenticate RA

    String RA_Id = null;
    String raUserId = null;
    IAuthToken token = null;

    try {
        token = authenticate(request);
        raUserId = token.getInString("userid");
        RA_Id = peerCert.getSubjectDN().toString();
    } catch (EInvalidCredentials e) {
        // already logged.
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } catch (EBaseException e) {
        // already logged.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    mAuthority.log(ILogger.LL_INFO, "Remote Authority authenticated: " + peerCert.getSubjectDN());

    // authorize
    AuthzToken authzToken = null;

    try {
        authzToken = authorize(mAclMethod, token, mAuthzResourceName, "submit");
    } catch (Exception e) {
        // do nothing for now
    }

    if (authzToken == null) {
        cmsRequest.setStatus(ICMSRequest.UNAUTHORIZED);
        return;
    }

    // after cert validated, check http request.
    if (!method.equalsIgnoreCase("POST")) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }
    if (len <= 0) {
        resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED);
        return;
    }

    // now process request.

    CMS.debug("ConnectorServlet: process request RA_Id=" + RA_Id);
    try {
        // decode request.
        msg = (IPKIMessage) mReqEncoder.decode(encodedreq);
        // process request
        replymsg = processRequest(RA_Id, raUserId, msg, token);
    } catch (IOException e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
        mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } catch (EBaseException e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
        mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } catch (Exception e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
    }

    CMS.debug("ConnectorServlet: done processRequest");

    // encode reply
    try {
        String encodedrep = mReqEncoder.encode(replymsg);

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("text/html");
        resp.setContentLength(encodedrep.length());

        // send reply
        OutputStream out = response.getOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF8");

        writer.write(encodedrep);
        writer.flush();
        writer.close();
        out.flush();
    } catch (Exception e) {
        CMS.debug("ConnectorServlet: error writing e=" + e.toString());
    }
    CMS.debug("ConnectorServlet: send response RA_Id=" + RA_Id);
}

From source file:com.truebanana.http.HTTPRequest.java

/**
 * Executes this {@link HTTPRequest} asynchronously. To hook to events or listen to the server response, you must provide an {@link HTTPResponseListener} using {@link HTTPRequest#setHTTPResponseListener(HTTPResponseListener)}.
 *
 * @return This {@link HTTPRequest}//w ww.j  a  v  a 2  s . c om
 */
public HTTPRequest executeAsync() {
    Async.executeAsync(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection urlConnection = buildURLConnection();

            // Get request body now if there's a provider
            if (bodyProvider != null) {
                body = bodyProvider.getRequestBody();
            }

            // Update socket factory as needed
            if (urlConnection instanceof HttpsURLConnection) {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection;

                try {
                    httpsURLConnection.setSSLSocketFactory(new FlexibleSSLSocketFactory(trustStore,
                            trustStorePassword, keyStore, keyStorePassword, !verifySSL));
                } catch (GeneralSecurityException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.SECURITY_EXCEPTION);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.KEYSTORE_INVALID);
                    onRequestTerminated();
                    return; // Terminate now
                }

                if (!verifySSL) {
                    httpsURLConnection.setHostnameVerifier(new NoVerifyHostnameVerifier());
                    log("SSL Verification Disabled", "**********");
                }
            }

            log("Endpoint", urlConnection.getURL().toString());
            Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> pair = (Map.Entry) iterator.next();
                urlConnection.addRequestProperty(pair.getKey(), pair.getValue());
                log("Request Header", pair.getKey() + ": " + pair.getValue());
            }
            if (multiPartContent != null) {
                log("Multipart Request Boundary", multiPartContent.getBoundary());
                int counter = 1;
                for (MultiPartContent.Part part : multiPartContent.getParts()) {
                    log("Request Body Part " + counter,
                            "Name: " + part.getName() + "; File Name: " + part.getFileName());

                    Iterator<Map.Entry<String, String>> it = part.getHeaders().entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> pair = (Map.Entry) it.next();
                        log("Request Body Part " + counter + " Header", pair.getKey() + ": " + pair.getValue());
                    }
                }
            } else {
                log("Request Body", body);
            }

            if (mockResponse == null) {
                // Trigger pre-execute since preparations are complete
                onPreExecute();

                // Write our request body
                try {
                    if (multiPartContent != null) {
                        multiPartContent.write(urlConnection.getOutputStream());
                    } else if (body != null) {
                        OutputStream os = urlConnection.getOutputStream();
                        OutputStreamWriter writer = new OutputStreamWriter(os);
                        writer.write(body);
                        writer.flush();
                        writer.close();
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Get the response
                InputStream content;
                try {
                    content = urlConnection.getInputStream();
                    onPostExecute();
                } catch (SocketTimeoutException e) { // Timeout
                    e.printStackTrace();
                    onPostExecute();
                    onRequestError(HTTPRequestError.TIMEOUT);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) { // All other exceptions
                    e.printStackTrace();
                    content = urlConnection.getErrorStream();
                    onPostExecute();
                }

                // Pre-process the response
                final HTTPResponse response = HTTPResponse.from(HTTPRequest.this, urlConnection, content);

                if (response.isConnectionError()) {
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Log response
                log("Response Message", response.getResponseMessage());
                log("Response Content", response.getStringContent());

                // Trigger request completed and return the response
                onRequestCompleted(response);

                // Terminate the connection
                urlConnection.disconnect();

                onRequestTerminated();
            } else {
                onPreExecute();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                onPostExecute();
                log("Response Message", mockResponse.getResponseMessage());
                log("Response Content", mockResponse.getStringContent());
                onRequestCompleted(mockResponse);
                urlConnection.disconnect();
                onRequestTerminated();
            }
        }
    });
    return this;
}

From source file:net.subclient.subsonic.SubsonicConnection.java

/**
 * Performs a connection to the server executing specified method and passing provided parameters.
 * @param method One of the supported methods
 * @param parameters Parametters to be passed to server
 * @param isJson Defines if JSON is expected. It won't be JSON on any method returning binary contents
 * @return The performed HTTP connection InputStream
 * @throws IOException/*from   www .j av a 2  s . co  m*/
 * @throws InvalidResponseException If the Subsonic servers returns a non parseable response 
 * @throws HTTPException If the server response code is other than 200
 * @throws CompatibilityException 
 */
private InputStream connect(ApiMethod method, List<HttpParameter> parameters, boolean isJson)
        throws IOException, InvalidResponseException, HTTPException, CompatibilityException {
    // Generate URL object
    URL url = new URL(this.serverURL.toString() + method.toString());
    // Append version param to parameters array
    parameters.add(new HttpParameter("v", this.getVersionCompatible(method.getVersion()).toString(true)));

    // Open HTTP/HTTPS Connection
    HttpURLConnection conn = (this.isSSL) ? (HttpsURLConnection) url.openConnection()
            : (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);

    // Add parameters to be sent
    OutputStreamWriter connOut = new OutputStreamWriter(conn.getOutputStream());
    StringBuilder auxParams = new StringBuilder(this.parametersString);
    for (HttpParameter parameter : parameters)
        auxParams.append(String.format("&%s", parameter.toString()));
    //Send parameters to outer connection
    connOut.write(auxParams.toString());
    connOut.flush();
    connOut.close();

    // Check the response code is 200
    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
        throw new HTTPException(conn.getResponseCode());
    // Check the content type is application/json
    if (isJson && conn.getContentType().indexOf(JSON_CONTENT_TYPE) == -1)
        throw new InvalidResponseException(conn.getContentType());

    // Return the connection InputStream
    return conn.getInputStream();
}