Example usage for java.io StringWriter close

List of usage examples for java.io StringWriter close

Introduction

In this page you can find the example usage for java.io StringWriter close.

Prototype

public void close() throws IOException 

Source Link

Document

Closing a StringWriter has no effect.

Usage

From source file:org.eredlab.g4.ccl.net.nntp.NNTPClient.java

/***
 * List the command help from the server.
 * <p>//from   w  w w.  j a  v  a  2 s  . c  o m
 * @return The sever help information.
 * @exception NNTPConnectionClosedException
 *      If the NNTP server prematurely closes the connection as a result
 *      of the client being idle or some other reason causing the server
 *      to send NNTP reply code 400.  This exception may be caught either
 *      as an IOException or independently as itself.
 * @exception IOException  If an I/O error occurs while either sending a
 *      command to the server or receiving a reply from the server.
 ***/
public String listHelp() throws IOException {
    StringWriter help;
    Reader reader;

    if (!NNTPReply.isInformational(help()))
        return null;

    help = new StringWriter();
    reader = new DotTerminatedMessageReader(_reader_);
    Util.copyReader(reader, help);
    reader.close();
    help.close();
    return help.toString();
}

From source file:com.kncwallet.wallet.ui.WalletActivity.java

private void exportPrivateKeys(@Nonnull final String password) {
    try {/*from  w w  w  .ja  v  a  2s. c o m*/
        Constants.EXTERNAL_WALLET_BACKUP_DIR.mkdirs();
        final DateFormat dateFormat = Iso8601Format.newDateFormat();
        dateFormat.setTimeZone(TimeZone.getDefault());
        final File file = new File(Constants.EXTERNAL_WALLET_BACKUP_DIR,
                Constants.EXTERNAL_WALLET_KEY_BACKUP + "-" + dateFormat.format(new Date()));

        final List<ECKey> keys = new LinkedList<ECKey>();
        for (final ECKey key : wallet.getKeys())
            if (!wallet.isKeyRotating(key))
                keys.add(key);

        final StringWriter plainOut = new StringWriter();
        WalletUtils.writeKeys(plainOut, keys);
        plainOut.close();
        final String plainText = plainOut.toString();

        final String cipherText = Crypto.encrypt(plainText, password.toCharArray());

        final Writer cipherOut = new OutputStreamWriter(new FileOutputStream(file), Constants.UTF_8);
        cipherOut.write(cipherText);
        cipherOut.close();

        final AlertDialog.Builder dialog = new KnCDialog.Builder(this).setInverseBackgroundForced(true)
                .setMessage(getString(R.string.export_keys_dialog_success, file));
        dialog.setPositiveButton(R.string.export_keys_dialog_button_archive, new OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, final int which) {
                mailPrivateKeys(file);
            }
        });
        dialog.setNegativeButton(R.string.button_dismiss, null);
        dialog.show();

        log.info("exported " + keys.size() + " private keys to " + file);
    } catch (final IOException x) {
        new KnCDialog.Builder(this).setInverseBackgroundForced(true).setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle(R.string.import_export_keys_dialog_failure_title)
                .setMessage(getString(R.string.export_keys_dialog_failure, x.getMessage()))
                .setNeutralButton(R.string.button_dismiss, null).show();

        log.error("problem writing private keys", x);
    }
}

From source file:com.norconex.commons.lang.map.Properties.java

/**
 * Writes this property list (key and element pairs) in this
 * <code>Properties</code> table to the output stream as UTF-8 in a format 
 * suitable for loading into a <code>Properties</code> table using the
 * {@link #load(InputStream) load} method.
 * Otherwise, the same considerations as
 * {@link #store(OutputStream, String)} apply.
 * @param   comments   a description of the property list.
 * @return the properties as string/*from  w ww  .  j  av a 2s  . c o m*/
 * @throws IOException problem storing to string
 */
public String storeToString(String comments) throws IOException {
    StringWriter writer = new StringWriter();
    store(writer, comments);
    String str = writer.toString();
    writer.close();
    return str;
}

From source file:com.xmlcalabash.library.HttpRequest.java

private void doPutOrPostMultipart(EntityEnclosingMethod method, XdmNode multipart) {
    // The Apache HTTP libraries just don't handle this case...we treat it as a "single part"
    // and build the body ourselves, using the boundaries etc.

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Check for consistency of content-type
    contentType = multipart.getAttributeValue(_content_type);
    if (contentType == null) {
        contentType = "multipart/mixed";
    }/*  www . java 2s  .c o  m*/

    if (headerContentType != null && !headerContentType.equals(contentType.toLowerCase())) {
        throw XProcException.stepError(20);
    }

    if (!contentType.startsWith("multipart/")) {
        throw new UnsupportedOperationException("Multipart content-type must be multipart/...");
    }

    for (Header header : headers) {
        method.addRequestHeader(header);
    }

    String boundary = multipart.getAttributeValue(_boundary);

    if (boundary == null) {
        throw new XProcException(step.getNode(), "A boundary value must be specified on c:multipart");
    }

    if (boundary.startsWith("--")) {
        throw XProcException.stepError(2);
    }

    String q = "\"";
    if (boundary.contains(q)) {
        q = "'";
    }
    if (boundary.contains(q)) {
        q = "";
    }

    String multipartContentType = contentType + "; boundary=" + q + boundary + q;

    // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it
    MessageBytes byteContent = new MessageBytes();
    byteContent.append("This is a multipart message.\r\n");
    //String postContent = "This is a multipart message.\r\n";
    for (XdmNode body : new RelevantNodes(runtime, multipart, Axis.CHILD)) {
        if (!XProcConstants.c_body.equals(body.getNodeName())) {
            throw new XProcException(step.getNode(), "A c:multipart may only contain c:body elements.");
        }

        String bodyContentType = body.getAttributeValue(_content_type);
        if (bodyContentType == null) {
            throw new XProcException(step.getNode(), "Content-type on c:body is required.");
        }

        String bodyId = body.getAttributeValue(_id);
        String bodyDescription = body.getAttributeValue(_description);
        String bodyDisposition = body.getAttributeValue(_disposition);

        String bodyCharset = HttpUtils.getCharset(bodyContentType);

        if (bodyContentType.contains(";")) {
            int pos = bodyContentType.indexOf(";");
            bodyContentType = bodyContentType.substring(0, pos);
        }

        String bodyEncoding = body.getAttributeValue(_encoding);
        if (bodyEncoding != null && !"base64".equals(bodyEncoding)) {
            throw new UnsupportedOperationException("The '" + bodyEncoding + "' encoding is not supported");
        }

        if (bodyCharset != null) {
            bodyContentType += "; charset=" + bodyCharset;
        } else {
            // Is utf-8 the right default? What about the image/ case? 
            bodyContentType += "; charset=utf-8";
        }

        //postContent += "--" + boundary + "\r\n";
        //postContent += "Content-Type: " + bodyContentType + "\r\n";
        byteContent.append("--" + boundary + "\r\n");
        byteContent.append("Content-Type: " + bodyContentType + "\r\n");

        if (bodyDescription != null) {
            //postContent += "Content-Description: " + bodyDescription + "\r\n";
            byteContent.append("Content-Description: " + bodyDescription + "\r\n");
        }
        if (bodyId != null) {
            //postContent += "Content-ID: " + bodyId + "\r\n";
            byteContent.append("Content-ID: " + bodyId + "\r\n");
        }
        if (bodyDisposition != null) {
            //postContent += "Content-Disposition: " + bodyDisposition + "\r\n";
            byteContent.append("Content-Disposition: " + bodyDisposition + "\r\n");
        }
        if (bodyEncoding != null) {
            //postContent += "Content-Transfer-Encoding: " + bodyEncoding + "\r\n";
            if (encodeBinary) {
                byteContent.append("Content-Transfer-Encoding: " + bodyEncoding + "\r\n");
            }
        }
        //postContent += "\r\n";
        byteContent.append("\r\n");

        try {
            if (xmlContentType(bodyContentType)) {
                Serializer serializer = makeSerializer();

                Vector<XdmNode> content = new Vector<XdmNode>();
                XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
                while (iter.hasNext()) {
                    XdmNode node = (XdmNode) iter.next();
                    content.add(node);
                }

                // FIXME: set serializer properties appropriately!
                StringWriter writer = new StringWriter();
                serializer.setOutputWriter(writer);
                S9apiUtils.serialize(runtime, content, serializer);
                writer.close();
                //postContent += writer.toString();
                byteContent.append(writer.toString());
            } else if (jsonContentType(contentType)) {
                byteContent.append(XMLtoJSON.convert(body));
            } else if (!encodeBinary && "base64".equals(bodyEncoding)) {
                byte[] decoded = Base64.decode(body.getStringValue());
                byteContent.append(decoded, decoded.length);
            } else {
                StringWriter writer = new StringWriter();
                XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
                while (iter.hasNext()) {
                    XdmNode node = (XdmNode) iter.next();
                    if (node.getNodeKind() != XdmNodeKind.TEXT) {
                        throw XProcException.stepError(28);
                    }
                    writer.write(node.getStringValue());
                }
                writer.close();
                //postContent += writer.toString();
                byteContent.append(writer.toString());
            }

            //postContent += "\r\n";
            byteContent.append("\r\n");
        } catch (IOException ioe) {
            throw new XProcException(ioe);
        } catch (SaxonApiException sae) {
            throw new XProcException(sae);
        }
    }

    //postContent += "--" + boundary + "--\r\n";
    byteContent.append("--" + boundary + "--\r\n");

    ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(byteContent.content(),
            multipartContentType);
    //StringRequestEntity requestEntity = new StringRequestEntity(postContent, multipartContentType, null);
    method.setRequestEntity(requestEntity);
}

From source file:edu.rice.cs.bioinfo.programs.phylonet.algos.network.InferMLNetworkFromSequences.java

private String network2String(final DirectedGraphToGraphAdapter<String, PhyloEdge<String>> speciesNetwork) {
    Func1<String, String> _getNetworkNodeLabel = new Func1<String, String>() {
        public String execute(String node) {
            return node;
        }/*from  w  ww. jav  a  2 s.  c  om*/
    };

    Func1<String, Iterable<String>> _getDestinationNodes = new Func1<String, Iterable<String>>() {
        public Iterable<String> execute(String node) {
            return new GetDirectSuccessors<String, PhyloEdge<String>>().execute(speciesNetwork, node);
        }
    };

    Func2<String, String, String> _getNetworkDistanceForPrint = new Func2<String, String, String>() {
        public String execute(String parent, String child) {
            PhyloEdge<String> edge = speciesNetwork.getEdge(parent, child);
            if (edge.getBranchLength() == null) {
                return null;
            }
            return edge.getBranchLength() + "";
        }
    };

    Func2<String, String, String> _getProbabilityForPrint = new Func2<String, String, String>() {
        public String execute(String parent, String child) {
            PhyloEdge<String> edge = speciesNetwork.getEdge(parent, child);
            if (edge.getProbability() == null) {
                return null;
            }
            return edge.getProbability() + "";
        }
    };

    Func2<String, String, String> _getSupportForPrint = new Func2<String, String, String>() {
        public String execute(String parent, String child) {
            PhyloEdge<String> edge = speciesNetwork.getEdge(parent, child);
            if (edge.getSupport() == null) {
                return null;
            }
            return edge.getSupport() + "";
        }
    };

    Func1<String, HybridNodeType> _getHybridTypeForPrint = new Func1<String, HybridNodeType>() {
        public HybridNodeType execute(String node) {
            int inDegree = new GetInDegree<String, PhyloEdge<String>>().execute(speciesNetwork, node);
            return inDegree == 2 ? HybridNodeType.Hybridization : null;
        }
    };

    Func1<String, String> _getHybridNodeIndexForPrint = new Func1<String, String>() {
        List<String> hybridNodes = new ArrayList<String>();

        public String execute(String node) {
            int inDegree = new GetInDegree<String, PhyloEdge<String>>().execute(speciesNetwork, node);
            if (inDegree == 2) {
                int index = hybridNodes.indexOf(node) + 1;
                if (index == 0) {
                    hybridNodes.add(node);
                    return hybridNodes.size() + "";
                } else {
                    return index + "";
                }
            } else {
                return null;
            }
        }
    };

    try {
        StringWriter sw = new StringWriter();
        //   new RichNewickPrinterCompact<String>().print(true, "R", _getNetworkNodeLabel, _getDestinationNodes, _getNetworkDistanceForPrint, _getSupportForPrint, _getProbabilityForPrint, _getHybridNodeIndexForPrint, _getHybridTypeForPrint, sw);
        RichNewickPrinterCompact<String> printer = new RichNewickPrinterCompact<String>();
        printer.setGetBranchLength(_getNetworkDistanceForPrint);
        printer.setGetProbability(_getProbabilityForPrint);
        printer.setGetSupport(_getSupportForPrint);

        printer.print(true, new FindRoot<String>().execute(speciesNetwork), _getNetworkNodeLabel,
                _getDestinationNodes, _getHybridNodeIndexForPrint, _getHybridTypeForPrint, sw);
        sw.flush();
        sw.close();
        return sw.toString();
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.getStackTrace();
    }
    return null;
}

From source file:com.ichi2.libanki.sync.BasicHttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData,
        Connection.CancelCallback cancelCallback) {
    File tmpFileBuffer = null;/*  www  .  j av  a  2 s .  c  o m*/
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // compression flag and session key as post vars
        buf.write(bdry + "\r\n");
        buf.write("Content-Disposition: form-data; name=\"c\"\r\n\r\n" + (comp != 0 ? 1 : 0) + "\r\n");
        if (hkey) {
            buf.write(bdry + "\r\n");
            buf.write("Content-Disposition: form-data; name=\"k\"\r\n\r\n" + mHKey + "\r\n");
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Collection.SYNC_URL;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = url + "sync/" + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + AnkiDroidApp.getPkgVersion());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            return httpClient.execute(httpPost);
        } catch (SSLException e) {
            Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e);
            return null;
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e);
        return null;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:com.ichi2.libanki.sync.HttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, JSONObject registerData,
        Connection.CancelCallback cancelCallback) throws UnknownHttpResponseException {
    File tmpFileBuffer = null;/*from w  w  w.  j  a  v a 2s  .co m*/
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // post vars
        mPostVars.put("c", comp != 0 ? 1 : 0);
        for (String key : mPostVars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    mPostVars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Consts.SYNC_BASE;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = syncURL() + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + VersionUtils.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // we assume badAuthRaises flag from Anki Desktop always False
            // so just throw new RuntimeException if response code not 200 or 403
            assertOk(httpResponse);
            return httpResponse;
        } catch (SSLException e) {
            Timber.e(e, "SSLException while building HttpClient");
            throw new RuntimeException("SSLException while building HttpClient");
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Timber.e(e, "BasicHttpSyncer.sync: IOException");
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:website.openeng.libanki.sync.HttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, JSONObject registerData,
        Connection.CancelCallback cancelCallback) throws UnknownHttpResponseException {
    File tmpFileBuffer = null;//w  w  w.  ja v  a 2 s.com
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // post vars
        mPostVars.put("c", comp != 0 ? 1 : 0);
        for (String key : mPostVars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    mPostVars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(KanjiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Consts.SYNC_BASE;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = syncURL() + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "KanjiDroid-" + VersionUtils.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // we assume badAuthRaises flag from Anki Desktop always False
            // so just throw new RuntimeException if response code not 200 or 403
            assertOk(httpResponse);
            return httpResponse;
        } catch (SSLException e) {
            Timber.e(e, "SSLException while building HttpClient");
            throw new RuntimeException("SSLException while building HttpClient");
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Timber.e(e, "BasicHttpSyncer.sync: IOException");
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:org.jenkinsci.plugins.uithemes.model.UIThemeContribution.java

public Resource createUserLessResource(File userHome, UIThemeImplementation implementation) throws IOException {
    if (lessTemplate == null) {
        return null;
    }//from ww w.  ja v  a2s .  c o  m

    Map<String, String> userConfig = getUserThemeImplConfig(userHome);
    if (userConfig.isEmpty() && implementation != null) {
        UIThemeImplSpec themeImplSpec = implementation.getThemeImplSpec();
        if (themeImplSpec != null) {
            userConfig = themeImplSpec.getDefaultConfig();
        }
    }

    File lessFile = UIThemesProcessor.getUserThemeImplLESSFile(themeName, themeImplName, userHome);
    StringWriter writer = new StringWriter();

    try {
        lessTemplate.process(userConfig, writer);
        FileUtils.write(lessFile, writer.toString(), "UTF-8");
        return new URLResource(lessFile.toURI().toURL(), this);
    } catch (TemplateException e) {
        throw new IOException(String.format(
                "Error applying user theme impl configuration to LESS resource template. UserHome '%s', ThemeImpl '%s'.\n"
                        + "   > There seems to be an issue/mismatch between the variables used in the template and those provided in the theme implementation configuration.\n"
                        + "   > Check for mismatches/omissions between the template variables and the theme configuration variables:\n"
                        + "       > Template Contributor: %s\n" + "       > Template: %s\n"
                        + "       > Template Error Expression: ${%s} (Line %d, Column %d)\n"
                        + "       > Theme Implementation Config: %s\n",
                userHome.getAbsolutePath(), getQName().toString(), contributor.getName(), getTemplatePath(),
                e.getBlamedExpressionString(), e.getLineNumber(), e.getColumnNumber(),
                (userConfig.isEmpty() ? "{} !!EMPTY!!" : userConfig.toString())), e);
    } finally {
        writer.close();
    }
}

From source file:org.rhq.enterprise.server.sync.test.DeployedAgentPluginsValidatorTest.java

public void testCanExportAndImportState() throws Exception {
    final PluginManagerLocal pluginManager = context.mock(PluginManagerLocal.class);

    final DeployedAgentPluginsValidator validator = new DeployedAgentPluginsValidator(pluginManager);

    context.checking(new Expectations() {
        {/*from w w w  . j av a 2s. c  o  m*/
            oneOf(pluginManager).getInstalledPlugins();
            will(returnValue(new ArrayList<Plugin>(getDeployedPlugins())));
        }
    });

    validator.initialize(null, null);

    StringWriter output = new StringWriter();
    try {
        XMLOutputFactory ofactory = XMLOutputFactory.newInstance();

        XMLStreamWriter wrt = ofactory.createXMLStreamWriter(output);
        //wrap the exported plugins in "something" so that we produce
        //a valid xml
        wrt.writeStartDocument();
        wrt.writeStartElement("root");

        validator.exportState(new ExportWriter(wrt));

        wrt.writeEndDocument();

        wrt.close();

        StringReader input = new StringReader(output.toString());

        try {
            XMLInputFactory ifactory = XMLInputFactory.newInstance();
            XMLStreamReader rdr = ifactory.createXMLStreamReader(input);

            //push the reader to the start of the plugin elements
            //this is what is expected by the validators
            rdr.nextTag();

            validator.initializeExportedStateValidation(new ExportReader(rdr));

            rdr.close();

            assertEquals(validator.getPluginsToValidate(), getDeployedPlugins());
        } finally {
            input.close();
        }
    } catch (Exception e) {
        LOG.error("Test failed. Output generated so far:\n" + output, e);
        throw e;
    } finally {
        output.close();
    }
}