Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:dev.ukanth.ufirewall.Api.java

public static boolean saveSharedPreferencesToFile(Context ctx) {
    boolean res = false;
    File sdCard = Environment.getExternalStorageDirectory();
    if (isExternalStorageWritable()) {
        File dir = new File(sdCard.getAbsolutePath() + "/afwall/");
        dir.mkdirs();/*from   w  w w . j ava 2  s .com*/
        File file = new File(dir, "backup.json");
        try {
            FileOutputStream fOut = new FileOutputStream(file);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);

            //default Profile - current one
            JSONObject obj = new JSONObject(getCurrentRulesAsMap(ctx));
            JSONArray jArray = new JSONArray("[" + obj.toString() + "]");

            myOutWriter.append(jArray.toString());
            res = true;
            myOutWriter.close();
            fOut.close();
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getLocalizedMessage());
        } catch (JSONException e) {
            Log.e(TAG, e.getLocalizedMessage());
        } catch (IOException e) {
            Log.e(TAG, e.getLocalizedMessage());
        }
    }

    return res;
}

From source file:au.org.ala.layers.dao.LayerIntersectDAOImpl.java

ArrayList<String> remoteSampling(IntersectionFile[] intersectionFiles, double[][] points,
        IntersectCallback callback) {/*from   w ww  .j  a  v  a2 s . c om*/
    logger.info("begin REMOTE sampling, number of threads " + intersectConfig.getThreadCount()
            + ", number of layers=" + intersectionFiles.length + ", number of coordinates=" + points.length);

    ArrayList<String> output = null;

    try {
        long start = System.currentTimeMillis();
        URL url = new URL(intersectConfig.getLayerIndexUrl() + "/intersect/batch");
        URLConnection c = url.openConnection();
        c.setDoOutput(true);

        OutputStreamWriter out = null;
        try {
            out = new OutputStreamWriter(c.getOutputStream());
            out.write("fids=");
            for (int i = 0; i < intersectionFiles.length; i++) {
                if (i > 0) {
                    out.write(",");
                }
                out.write(intersectionFiles[i].getFieldId());
            }
            out.write("&points=");
            for (int i = 0; i < points.length; i++) {
                if (i > 0) {
                    out.write(",");
                }
                out.write(String.valueOf(points[i][1]));
                out.write(",");
                out.write(String.valueOf(points[i][0]));
            }
            out.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        JSONObject jo = JSONObject.fromObject(IOUtils.toString(c.getInputStream()));

        String checkUrl = jo.getString("statusUrl");

        //check status
        boolean notFinished = true;
        String downloadUrl = null;
        while (notFinished) {
            //wait 5s before querying status
            Thread.sleep(5000);

            jo = JSONObject.fromObject(IOUtils.toString(new URI(checkUrl).toURL().openStream()));

            if (jo.containsKey("error")) {
                notFinished = false;
            } else if (jo.containsKey("status")) {
                String status = jo.getString("status");

                if ("finished".equals(status)) {
                    downloadUrl = jo.getString("downloadUrl");
                    notFinished = false;
                } else if ("cancelled".equals(status) || "error".equals(status)) {
                    notFinished = false;
                }
            }
        }

        ZipInputStream zis = null;
        CSVReader csv = null;
        InputStream is = null;
        ArrayList<StringBuilder> tmpOutput = new ArrayList<StringBuilder>();
        long mid = System.currentTimeMillis();
        try {
            is = new URI(downloadUrl).toURL().openStream();
            zis = new ZipInputStream(is);
            ZipEntry ze = zis.getNextEntry();
            csv = new CSVReader(new InputStreamReader(zis));

            for (int i = 0; i < intersectionFiles.length; i++) {
                tmpOutput.add(new StringBuilder());
            }
            String[] line;
            int row = 0;
            csv.readNext(); //discard header
            while ((line = csv.readNext()) != null) {
                //order is consistent with request
                for (int i = 2; i < line.length && i - 2 < tmpOutput.size(); i++) {
                    if (row > 0) {
                        tmpOutput.get(i - 2).append("\n");
                    }
                    tmpOutput.get(i - 2).append(line[i]);
                }
                row++;
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (csv != null) {
                try {
                    csv.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        output = new ArrayList<String>();
        for (int i = 0; i < tmpOutput.size(); i++) {
            output.add(tmpOutput.get(i).toString());
            tmpOutput.set(i, null);
        }

        long end = System.currentTimeMillis();

        logger.info("sample time for " + 5 + " layers and " + 3 + " coordinates: get response=" + (mid - start)
                + "ms, write response=" + (end - mid) + "ms");

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

From source file:gdsc.smlm.ij.plugins.BenchmarkFilterAnalysis.java

private void saveFilter(Filter filter) {
    // Save the filter to file
    String filename = Utils.getFilename("Best_Filter_File", filterFilename);
    if (filename != null) {
        List<Filter> filters = new LinkedList<Filter>();
        filters.add(filter);/*from  w w  w  . ja v  a 2 s .  c  o m*/
        FilterSet set = new FilterSet(filter.getName(), filters);
        List<FilterSet> list = new LinkedList<FilterSet>();
        list.add(set);

        OutputStreamWriter out = null;
        try {
            filterFilename = filename;
            // Append .xml if no suffix
            if (filename.lastIndexOf('.') < 0)
                filterFilename += ".xml";

            FileOutputStream fos = new FileOutputStream(filterFilename);
            out = new OutputStreamWriter(fos, "UTF-8");
            out.write(XmlUtils.prettyPrintXml(XmlUtils.toXML(list)));
        } catch (Exception e) {
            IJ.log("Unable to save the filter sets to file: " + e.getMessage());
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // Ignore
                }
            }
        }
    }
}

From source file:eionet.cr.web.util.TriplesToOutputStream.java

/**
 *
 * @param out/*w  w w  .  jav a2s  .c o  m*/
 * @param subjectUri
 * @param triples
 */
public static void triplesToRdf(OutputStream out, String subjectUri, List<SubjectDTO> triples) {
    OutputStreamWriter writer = new OutputStreamWriter(out);
    try {
        if (triples != null) {
            writer.append(RDF_HEADER);
            writer.append("<rdf:RDF xmlns=\"").append(subjectUri + "#").append("\" xmlns:rdf=\"")
                    .append(RDF_NAMESPACE).append("\" ").append("xmlns:rdfs=\"").append(RDFS_NAMESPACE)
                    .append("\">");
            for (SubjectDTO subject : triples) {

                writer.append("<rdf:Description rdf:about=\"")
                        .append(StringEscapeUtils.escapeXml(subject.getUri())).append("\">");
                Map<String, Collection<ObjectDTO>> predicates = subject.getPredicates();
                if (predicates != null) {
                    for (String predicateUri : predicates.keySet()) {
                        Collection<ObjectDTO> objects = predicates.get(predicateUri);

                        // Shorten predicate URIs
                        if (predicateUri.startsWith(RDF_NAMESPACE)) {
                            predicateUri = predicateUri.replace(RDF_NAMESPACE, "rdf:");
                        } else if (predicateUri.startsWith(RDFS_NAMESPACE)) {
                            predicateUri = predicateUri.replace(RDFS_NAMESPACE, "rdfs:");
                        } else if (predicateUri.startsWith(subjectUri)) {
                            predicateUri = predicateUri.replace(subjectUri + "#", "");
                        }

                        if (objects != null) {
                            for (ObjectDTO object : objects) {
                                if (object.isLiteral()) {
                                    writer.append("<").append(predicateUri).append(">")
                                            .append(StringEscapeUtils.escapeXml(object.getValue())).append("</")
                                            .append(predicateUri).append(">");
                                } else {
                                    writer.append("<").append(predicateUri).append(" rdf:resource=\"")
                                            .append(StringEscapeUtils.escapeXml(object.getValue()))
                                            .append("\"/>");
                                }
                            }
                        }
                    }
                }
                writer.append("</rdf:Description>");
            }
            writer.append("</rdf:RDF>");
            writer.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            writer.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

public String doRedirect(String urlRedirect, boolean useTim) {
    // android.os.Debug.waitForDebugger();
    try {//from   ww  w . ja  v  a  2 s  . c  o  m
        // with server phpOIDC, check for '#'
        if ((urlRedirect.startsWith(mOcp.m_redirect_uri + "?"))
                || (urlRedirect.startsWith(mOcp.m_redirect_uri + "#"))) {
            String[] params = urlRedirect.substring(mOcp.m_redirect_uri.length() + 1).split("&");
            String code = "";
            String state = "";
            String state_key = "state";
            for (int i = 0; i < params.length; i++) {
                String param = params[i];
                int idxEqual = param.indexOf('=');
                if (idxEqual >= 0) {
                    String key = param.substring(0, idxEqual);
                    String value = param.substring(idxEqual + 1);
                    if (key.startsWith("code"))
                        code = value;
                    if (key.startsWith("state"))
                        state = value;
                    if (key.startsWith("session_state")) {
                        state = value;
                        state_key = "session_state";
                    }
                }
            }

            // display code and state
            Logd(TAG, "doRedirect => code: " + code + " / state: " + state);

            // doRepost(code,state);
            if (code.length() > 0) {

                // get token_endpoint endpoint
                String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url);
                if (isEmpty(token_endpoint)) {
                    Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url);
                    return null;
                }

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                HttpURLConnection huc = getHUC(token_endpoint);
                huc.setInstanceFollowRedirects(false);

                if (useTim) {
                    if (mUsePrivateKeyJWT) {
                        nameValuePairs.add(new BasicNameValuePair("client_assertion_type",
                                "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"));
                        String client_assertion = secureStorage.getPrivateKeyJwt(token_endpoint);
                        Logd(TAG, "client_assertion: " + client_assertion);
                        nameValuePairs.add(new BasicNameValuePair("client_assertion", client_assertion));
                    } else {
                        huc.setRequestProperty("Authorization",
                                "Basic " + secureStorage.getClientSecretBasic());
                    }
                } else {
                    String authorization = (mOcp.m_client_id + ":" + mOcp.m_client_secret);
                    authorization = Base64.encodeToString(authorization.getBytes(), Base64.DEFAULT);
                    huc.setRequestProperty("Authorization", "Basic " + authorization);
                }

                huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                huc.setDoOutput(true);
                huc.setChunkedStreamingMode(0);

                OutputStream os = huc.getOutputStream();
                OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8");
                BufferedWriter writer = new BufferedWriter(out);

                nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
                nameValuePairs.add(new BasicNameValuePair("code", code));
                nameValuePairs.add(new BasicNameValuePair("redirect_uri", mOcp.m_redirect_uri));
                if (state != null && state.length() > 0)
                    nameValuePairs.add(new BasicNameValuePair(state_key, state));

                // write URL encoded string from list of key value pairs
                writer.write(getQuery(nameValuePairs));
                writer.flush();
                writer.close();
                out.close();
                os.close();

                Logd(TAG, "doRedirect => before connect");
                huc.connect();
                int responseCode = huc.getResponseCode();
                System.out.println("2 - code " + responseCode);
                Log.d(TAG, "doRedirect => responseCode " + responseCode);
                InputStream in = null;
                try {
                    in = new BufferedInputStream(huc.getInputStream());
                } catch (IOException ioe) {
                    sysout("io exception: " + huc.getErrorStream());
                }
                if (in != null) {
                    String result = convertStreamToString(in);
                    // now you have the string representation of the HTML request
                    in.close();

                    Logd(TAG, "doRedirect: " + result);

                    // save as static for now
                    return result;

                } else {
                    Logd(TAG, "doRedirect null");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.sun.faces.systest.ant.SystestClient.java

/**
 * Validate the response against the golden file (if any), skipping the
 * comparison on any golden file line that is also in the ignore file
 * (if any).  Return <code>null</code> for no problems, or an error
 * message./*from  w  ww  .  j  av  a2  s  . co  m*/
 */
protected String validateGolden() {

    if (golden == null) {
        return (null);
    }
    boolean ok = true;
    if (saveGolden.size() != saveResponse.size()) {
        ok = false;
    }
    if (ok) {
        for (int i = 0, size = saveGolden.size(); i < size; i++) {
            String golden = (String) saveGolden.get(i);
            String response = (String) saveResponse.get(i);
            if (!validateIgnore(golden) && !golden.equals(response)) {
                response = stripJsessionidFromLine(response);
                golden = stripJsessionidFromLine(golden);
                if (!golden.equals(response)) {
                    ok = false;
                    break;
                }
            }
        }
    }
    if (ok) {
        return (null);
    }
    System.out.println("EXPECTED: ======================================");
    for (int i = 0, size = saveGolden.size(); i < size; i++) {
        System.out.println((String) saveGolden.get(i));
    }
    System.out.println("================================================");
    if (saveIgnore.size() >= 1) {
        System.out.println("IGNORED: =======================================");
        for (int i = 0, size = saveIgnore.size(); i < size; i++) {
            System.out.println((String) saveIgnore.get(i));
        }
        System.out.println("================================================");
    }
    System.out.println("RECEIVED: ======================================");
    for (int i = 0, size = saveResponse.size(); i < size; i++) {
        System.out.println((String) saveResponse.get(i));
    }
    System.out.println("================================================");

    // write the goldenfile if the GF size from the server was 0
    // and the goldenfile doesn't already exist on the local filesystem.
    if (recordGolden != null) {
        File gf = new File(recordGolden);
        if (!gf.exists()) {
            System.out.println("[INFO] RECORDING GOLDENFILE: " + recordGolden);
            // write the goldenfile using the encoding specified in the response.
            // if there is no encoding available, default to ISO-8859-1
            String encoding = "ISO-8859-1";
            if (saveHeaders.containsKey("content-type")) {
                List vals = (List) saveHeaders.get("content-type");
                if (vals != null) {
                    String val = (String) vals.get(0);
                    int charIdx = val.indexOf('=');
                    if (charIdx > -1) {
                        encoding = val.substring(charIdx + 1).trim();
                    }
                }
            }
            OutputStreamWriter out = null;
            try {
                out = new OutputStreamWriter(new FileOutputStream(gf), encoding);
                for (int i = 0, size = saveResponse.size(); i < size; i++) {
                    out.write((String) saveResponse.get(i));
                    out.write('\n');
                }
                out.flush();
            } catch (Throwable t) {
                System.out.println("[WARNING] Unable to write goldenfile: " + t.toString());
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ioe) {
                    ; // do nothing
                }
            }
        }
    }
    return ("Failed Golden File Comparison");

}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

private String uploadMetaData(final Activity activity, final Handler handler, String filePath, String title,
        String description, boolean retry, long sdrecord_id) throws IOException {
    String uploadUrl = INITIAL_UPLOAD_URL;

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);//from  w  ww. j a v a2s  .  c o m
    urlConnection.setRequestProperty("Content-Type", "application/atom+xml");
    // urlConnection.setRequestProperty("Content-Length", newValue);
    urlConnection.setRequestProperty("Slug", filePath);
    String atomData = null;

    String category = DEFAULT_VIDEO_CATEGORY;
    this.tags = DEFAULT_VIDEO_TAGS;

    String template = readFile(activity, R.raw.gdata).toString();

    // Workarounds for corner cases. Youtube doesnt like empty titles
    if (title == null || title.length() == 0) {
        title = "Untitled";
    }
    if (description == null || description.length() == 0) {
        description = "No description";
    }

    // Check user preference to see if YouTube videos should be private by
    // default.
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
    Boolean ytPrivate = prefs.getBoolean("defaultYouTubePrivatePreference", true);

    String private_or_not = "<yt:private />";
    if (!ytPrivate) {
        private_or_not = "";
    }

    atomData = String.format(template, title, description, category, this.tags, private_or_not);

    OutputStreamWriter outStreamWriter = null;
    int responseCode = -1;

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

        /*
         * urlConnection.connect(); InputStream is =
         * urlConnection.getInputStream(); BufferedReader in = new
         * BufferedReader(new InputStreamReader(is)); String inputLine;
         * 
         * while ((inputLine = in.readLine()) != null) {
         * Log.d(TAG,inputLine); } in.close();
         */

        responseCode = urlConnection.getResponseCode();

        // ERROR LOGGING
        InputStream is = urlConnection.getErrorStream();
        if (is != null) {
            Log.e(TAG, " Error stream from Youtube available!");
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                Log.d(TAG, inputLine);
            }
            in.close();

            Map<String, List<String>> hfs = urlConnection.getHeaderFields();
            for (Entry<String, List<String>> hf : hfs.entrySet()) {
                Log.d(TAG, " entry : " + hf.getKey());
                List<String> vals = hf.getValue();
                for (String s : vals) {
                    Log.d(TAG, "vals:" + s);
                }
            }
        }

    } catch (IOException e) {
        //
        // Catch IO Exceptions here, like UnknownHostException, so we can
        // detect network failures, and send a notification
        //
        Log.d(TAG, " Error occured in uploadMetaData! ");
        e.printStackTrace();
        responseCode = -1;
        outStreamWriter = null;

        mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT);

        // Use the handler to execute a Runnable on the
        // main thread in order to have access to the
        // UI elements.
        handler.postDelayed(new Runnable() {
            public void run() {
                // Update UI

                // Indicate back to calling activity the result!
                // update uploadInProgress state also.

                ((VidiomActivity) activity).finishedUploading(false);
                ((VidiomActivity) activity)
                        .createNotification(res.getString(R.string.upload_to_youtube_host_failed_));

            }
        }, 0);

        // forward it on!
        throw e;
    }

    if (responseCode < 200 || responseCode >= 300) {
        // The response code is 40X
        if ((responseCode + "").startsWith("4") && retry) {
            Log.d(TAG, "retrying to fetch auth token for " + youTubeName);
            this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken);
            // Try again with fresh token
            return uploadMetaData(activity, handler, filePath, title, description, false, sdrecord_id);
        } else {

            mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT);

            // Probably not authorised!

            // Need to setup a Youtube account.

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((VidiomActivity) activity).finishedUploading(false);
                    ((VidiomActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_youtube_host_failed_));

                }
            }, 0);

            throw new IOException(String.format("response code='%s' (code %d)" + " for %s",
                    urlConnection.getResponseMessage(), responseCode, urlConnection.getURL()));

        }
    }

    return urlConnection.getHeaderField("Location");
}

From source file:eu.comvantage.dataintegration.SparulSimulationServlet.java

private void simulateEvent(String eventID, String endpoint) {
    //container for the final SPARUL update command including header information
    String body = "";
    //additional body information for the SPARUL update command

    //try to encode the SPARUL update command string with UTF-8
    String temp = "";
    Gson gson = new Gson();

    //simulation of a correct request
    if (eventID.equalsIgnoreCase("sparul1")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket0070071239swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn00110011\"}]" + "}";
    }//w w w . j  av a2s . co m
    //simulation of invalid template id for client
    else if (eventID.equalsIgnoreCase("sparul2")) {
        temp = "{ " + "\"Template\" : 8, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket008008123swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn1234567\"}]" + "}";
    }
    //simulation of invalid client id
    else if (eventID.equalsIgnoreCase("sparul3")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 3, "
                + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket000000000swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn55555\"}]" + "}";
    }
    //simulation of invalid parameter for specified template
    else if (eventID.equalsIgnoreCase("sparul4")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"bla\", \"value\":\"ex:Ticket98761234swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn223344\"}]" + "}";
    }
    //simulation of invalid parameter for specified template
    else if (eventID.equalsIgnoreCase("sparul5")) {
        temp = "{ " + "\"Templates\" : 1, " + "\"Clients\" : 1, "
                + "\"Param\" : [{\"name\":\"bla\", \"value\":\"ex:Ticket98761234swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn223344\"}]" + "}";
    }
    //malformed json
    else if (eventID.equalsIgnoreCase("sparul6")) {
        temp = "blabla";
    }
    //simulation of a correct request
    else if (eventID.equalsIgnoreCase("sparul7")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"templateId\", \"value\":\"tee:Ticket0070071239swd\"}], " + "}";
        //test of the long statement parameters of file client1_test0
    } else if (eventID.equalsIgnoreCase("sparul8")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"templateId\", \"value\":\"tee:test1\"}, "
                + "{\"name\":\"reportId\", \"value\":\"1\"},"
                + "{\"name\":\"device1\", \"value\":\"tee:test2\"},"
                + "{\"name\":\"device2\", \"value\":\"tee:test3\"},"
                + "{\"name\":\"device3\", \"value\":\"tee:test4\"}]" + "}";

    }
    //body = gson.toJson(temp);
    body = temp;

    //try to execute the SPARUL update command
    try {
        //insertion is done by a manual HTTP post
        HttpPost httpPost = new HttpPost(endpoint);

        //put SPARUL update command to output stream
        ByteArrayOutputStream b_out = new ByteArrayOutputStream();
        OutputStreamWriter wr = new OutputStreamWriter(b_out);
        wr.write(body);
        wr.flush();

        //transform output stream and modify header information for HTTP post             
        byte[] bytes = b_out.toByteArray();
        AbstractHttpEntity reqEntity = new ByteArrayEntity(bytes);
        reqEntity.setContentType("application/x-www-form-urlencoded");
        reqEntity.setContentEncoding(HTTP.UTF_8);
        httpPost.setEntity(reqEntity);
        httpPost.setHeader("role", "http://www.comvantage.eu/ontologies/ac-schema/cv_wp6_comau_employee");

        HttpClient httpclient = new DefaultHttpClient();

        //          //set proxy if defined
        //            if(System.getProperty("http.proxyHost") != null) {
        //               HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost"), Integer.valueOf(System.getProperty("http.proxyPort")), "http");
        //                httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        //            }

        try {
            //execute the HTTP put
            System.out.println(
                    "SparulSimulationServlet: Event '" + eventID + "' simulated at endpoint " + endpoint);
            HttpResponse response = httpclient.execute(httpPost);

            //handle different server responses and failures
            int responseCode = response.getStatusLine().getStatusCode();
            String responseMessage = response.getStatusLine().getReasonPhrase();
            System.out.println("SparulSimulationServlet: Response = " + responseCode + ", " + responseMessage);
            //close the output stream
            wr.close();
        } catch (IOException ex) {
            throw new Exception(ex);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.extrahardmode.config.messages.MessageConfig.java

/**
 * Set the header of the file before writing to it with bukkit yaml implementation
 *
 * @param file file to write the header to
 *///ww  w  .j  a  va  2  s. c om
private void setHeader(File file) {
    try {
        //Write header to a new file
        ByteArrayOutputStream memStream = new ByteArrayOutputStream();
        OutputStreamWriter memWriter = new OutputStreamWriter(memStream, Charset.forName("UTF-8").newEncoder());
        String[] header = { "Messages sent by ExtraHardMode",
                "Messages are only sent for modules that are activated",
                "Modes (has to match exactly, ignores case)",
                "Disabled: Message won't be sent even if feature that would sent the message is active",
                "One_Time: Will be sent to every player only once",
                "Notification: Gets sent every time with a timeout to prevent spamming chat",
                "Tutorial: Sent a limited number of times and not displayed after 3 times",
                "Broadcast: Shown to whole server. Only few messages make sense to be broadcasted",
                "Variables:", "$ALLCAPS is a variable and will be filled in for some messages",
                "$PLAYER: Affected player", "$PLAYERS: If multiple players are affected",
                "$DEATH_MSG: Death message if someone dies", "$ITEMS: a player lost" };
        StringBuilder sb = new StringBuilder();
        sb.append(StringUtils.repeat("#", 100));
        sb.append("%n");
        for (String line : header) {
            sb.append('#');
            sb.append(StringUtils.repeat(" ", 100 / 2 - line.length() / 2 - 1));
            sb.append(line);
            sb.append(StringUtils.repeat(" ", 100 / 2 - line.length() / 2 - 1 - line.length() % 2));
            sb.append('#');
            sb.append(String.format("%n"));
        }
        sb.append(StringUtils.repeat("#", 100));
        sb.append(String.format("%n"));
        //String.format: %n as platform independent line seperator
        memWriter.write(sb.toString());
        memWriter.close();

        IoHelper.writeHeader(file, memStream);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}