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:carnero.cgeo.original.libs.Base.java

public String requestJSONgc(String host, String path, String params) {
    int httpCode = -1;
    String httpLocation = null;//from w ww . j  a  v  a2s .c  o m

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

    if (cookiesDone == null) {
        cookiesDone = "";
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(Settings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            // POST
            final URL u = new URL("http://" + host + path);
            uc = u.openConnection();

            uc.setRequestProperty("Host", host);
            uc.setRequestProperty("Cookie", cookiesDone);
            uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
            uc.setRequestProperty("Referer", host + "/" + path);

            if (settings.asBrowser == 1) {
                uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                uc.setRequestProperty("Accept-Language", "en-US");
                uc.setRequestProperty("User-Agent", idBrowser);
                uc.setRequestProperty("Connection", "keep-alive");
                uc.setRequestProperty("Keep-Alive", "300");
            }

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(timeout);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(params);
            wr.flush();
            wr.close();

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            Log.i(Settings.tag + " | JSON",
                    "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                            + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path + "?"
                            + paramsLog);

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(Settings.tag, "cgeoBase.requestJSONgc.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(Settings.tag, "cgeoBase.requestJSONgc: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:carnero.cgeo.original.libs.Base.java

public Response request(boolean secure, String host, String path, String method, String params, int requestId,
        Boolean xContentType) {/*ww w. jav  a 2s. c o  m*/
    URL u = null;
    int httpCode = -1;
    String httpMessage = null;
    String httpLocation = null;

    if (requestId == 0) {
        requestId = (int) (Math.random() * 1000);
    }

    if (method == null
            || (method.equalsIgnoreCase("GET") == false && method.equalsIgnoreCase("POST") == false)) {
        method = "POST";
    } else {
        method = method.toUpperCase();
    }

    // https
    String scheme = "http://";
    if (secure) {
        scheme = "https://";
    }

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null && !cookies.isEmpty() && cookies.keySet().size() > 0) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0 && prefsValues.keySet().size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

    if (cookiesDone == null) {
        cookiesDone = "";
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    StringBuffer buffer = null;

    for (int i = 0; i < 5; i++) {
        if (i > 0) {
            Log.w(Settings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer = new StringBuffer();
        timeout = 30000 + (i * 10000);

        try {
            if (method.equals("GET")) {
                // GET
                u = new URL(scheme + host + path + "?" + params);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);
            } else {
                // POST
                u = new URL(scheme + host + path);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                final OutputStream out = connection.getOutputStream();
                final OutputStreamWriter wr = new OutputStreamWriter(out);
                wr.write(params);
                wr.flush();
                wr.close();
            }

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpMessage = connection.getResponseMessage();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            if (buffer != null && connection != null) {
                Log.i(Settings.tag + "|" + requestId,
                        "[" + method + " " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + scheme + host + path + "?"
                                + paramsLog);
            } else {
                Log.i(Settings.tag + "|" + requestId, "[" + method + " | " + httpCode + "] Failed to download "
                        + scheme + host + path + "?" + paramsLog);
            }

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(Settings.tag, "cgeoBase.request.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(Settings.tag, "cgeoBase.request: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    Response response = new Response();
    String data = null;

    try {
        if (httpCode == 302 && httpLocation != null) {
            final Uri newLocation = Uri.parse(httpLocation);
            if (newLocation.isRelative() == true) {
                response = request(secure, host, path, "GET", new HashMap<String, String>(), requestId, false,
                        false, false);
            } else {
                boolean secureRedir = false;
                if (newLocation.getScheme().equals("https")) {
                    secureRedir = true;
                }
                response = request(secureRedir, newLocation.getHost(), newLocation.getPath(), "GET",
                        new HashMap<String, String>(), requestId, false, false, false);
            }
        } else {
            if (buffer != null && buffer.length() > 0) {
                data = replaceWhitespace(buffer);
                buffer = null;

                if (data != null) {
                    response.setData(data);
                } else {
                    response.setData("");
                }
                response.setStatusCode(httpCode);
                response.setStatusMessage(httpMessage);
                response.setUrl(u.toString());
            }
        }
    } catch (Exception e) {
        Log.e(Settings.tag, "cgeoBase.page: " + e.toString());
    }

    return response;
}

From source file:carnero.cgeo.cgBase.java

public void postTweet(cgeoapplication app, cgSettings settings, String status, Double latitude,
        Double longitude) {//from  w  ww .  j ava 2  s . com
    if (app == null) {
        return;
    }
    if (settings == null || settings.tokenPublic == null || settings.tokenPublic.length() == 0
            || settings.tokenSecret == null || settings.tokenSecret.length() == 0) {
        return;
    }

    try {
        HashMap<String, String> parameters = new HashMap<String, String>();

        parameters.put("status", status);
        if (latitude != null && longitude != null) {
            parameters.put("lat", String.format("%.6f", latitude));
            parameters.put("long", String.format("%.6f", longitude));
            parameters.put("display_coordinates", "true");
        }

        final String paramsDone = cgOAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false,
                parameters, settings.tokenPublic, settings.tokenSecret);

        HttpURLConnection connection = null;
        try {
            final StringBuffer buffer = new StringBuffer();
            final URL u = new URL("http://api.twitter.com/1/statuses/update.json");
            final URLConnection uc = u.openConnection();

            uc.setRequestProperty("Host", "api.twitter.com");

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(30000);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(true);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(paramsDone);
            wr.flush();
            wr.close();

            Log.i(cgSettings.tag,
                    "Twitter.com: " + connection.getResponseCode() + " " + connection.getResponseMessage());

            InputStream ins;
            final String encoding = connection.getContentEncoding();

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }

            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
            connection.disconnect();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.IO: " + connection.getResponseCode() + ": "
                    + connection.getResponseMessage() + " ~ " + e.toString());

            final InputStream ins = connection.getErrorStream();
            final StringBuffer buffer = new StringBuffer();
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.inner: " + e.toString());
        }

        connection.disconnect();
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.postTweet: " + e.toString());
    }
}

From source file:carnero.cgeo.cgBase.java

public String requestJSON(String scheme, String host, String path, String method, String params) {
    int httpCode = -1;
    String httpLocation = null;// w w  w.  ja  v a2  s  .  c om

    if (method == null) {
        method = "GET";
    } else {
        method = method.toUpperCase();
    }

    boolean methodPost = false;
    if (method.equalsIgnoreCase("POST")) {
        methodPost = true;
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            try {
                URL u = null;
                if (methodPost) {
                    u = new URL(scheme + host + path);
                } else {
                    u = new URL(scheme + host + path + "?" + params);
                }

                if (u.getProtocol().toLowerCase().equals("https")) {
                    trustAllHosts();
                    HttpsURLConnection https = (HttpsURLConnection) u.openConnection();
                    https.setHostnameVerifier(doNotVerify);
                    uc = https;
                } else {
                    uc = (HttpURLConnection) u.openConnection();
                }

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
                if (methodPost) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    uc.setRequestProperty("Content-Length", Integer.toString(params.length()));
                    uc.setRequestProperty("X-HTTP-Method-Override", "GET");
                } else {
                    uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                }
                uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
                connection.setDoInput(true);
                if (methodPost) {
                    connection.setDoOutput(true);

                    final OutputStream out = connection.getOutputStream();
                    final OutputStreamWriter wr = new OutputStreamWriter(out);
                    wr.write(params);
                    wr.flush();
                    wr.close();
                } else {
                    connection.setDoOutput(false);
                }

                final String encoding = connection.getContentEncoding();
                InputStream ins;

                if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                    ins = new GZIPInputStream(connection.getInputStream());
                } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                    ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
                } else {
                    ins = connection.getInputStream();
                }
                final InputStreamReader inr = new InputStreamReader(ins);
                final BufferedReader br = new BufferedReader(inr);

                readIntoBuffer(br, buffer);

                httpCode = connection.getResponseCode();

                final String paramsLog = params.replaceAll(passMatch, "password=***");
                Log.i(cgSettings.tag + " | JSON",
                        "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path
                                + "?" + paramsLog);

                connection.disconnect();
                br.close();
                ins.close();
                inr.close();
            } catch (IOException e) {
                httpCode = connection.getResponseCode();

                Log.e(cgSettings.tag, "cgeoBase.requestJSON.IOException: " + httpCode + ": "
                        + connection.getResponseMessage() + " ~ " + e.toString());
            }
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSON: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }

        if (httpCode == 403) {
            // we're not allowed to download content, so let's move
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:carnero.cgeo.cgBase.java

public String requestJSONgc(String host, String path, String params) {
    int httpCode = -1;
    String httpLocation = null;//from w  w w  .  j  a  v  a  2s. c o  m

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

    if (cookiesDone == null) {
        cookiesDone = "";
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            // POST
            final URL u = new URL("http://" + host + path);
            uc = u.openConnection();

            uc.setRequestProperty("Host", host);
            uc.setRequestProperty("Cookie", cookiesDone);
            uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
            uc.setRequestProperty("Referer", host + "/" + path);

            if (settings.asBrowser == 1) {
                uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                uc.setRequestProperty("Accept-Language", "en-US");
                uc.setRequestProperty("User-Agent", idBrowser);
                uc.setRequestProperty("Connection", "keep-alive");
                uc.setRequestProperty("Keep-Alive", "300");
            }

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(timeout);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(params);
            wr.flush();
            wr.close();

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            Log.i(cgSettings.tag + " | JSON",
                    "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                            + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path + "?"
                            + paramsLog);

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSONgc.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSONgc: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:carnero.cgeo.cgBase.java

public cgResponse request(boolean secure, String host, String path, String method, String params, int requestId,
        Boolean xContentType) {/*  w w  w  .j a va  2s. co m*/
    URL u = null;
    int httpCode = -1;
    String httpMessage = null;
    String httpLocation = null;

    if (requestId == 0) {
        requestId = (int) (Math.random() * 1000);
    }

    if (method == null
            || (method.equalsIgnoreCase("GET") == false && method.equalsIgnoreCase("POST") == false)) {
        method = "POST";
    } else {
        method = method.toUpperCase();
    }

    // https
    String scheme = "http://";
    if (secure) {
        scheme = "https://";
    }

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null && !cookies.isEmpty() && cookies.keySet().size() > 0) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0 && prefsValues.keySet().size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

    if (cookiesDone == null) {
        cookiesDone = "";
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    StringBuffer buffer = null;

    for (int i = 0; i < 5; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer = new StringBuffer();
        timeout = 30000 + (i * 10000);

        try {
            if (method.equals("GET")) {
                // GET
                u = new URL(scheme + host + path + "?" + params);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);
            } else {
                // POST
                u = new URL(scheme + host + path);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                final OutputStream out = connection.getOutputStream();
                final OutputStreamWriter wr = new OutputStreamWriter(out);
                wr.write(params);
                wr.flush();
                wr.close();
            }

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpMessage = connection.getResponseMessage();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            if (buffer != null && connection != null) {
                Log.i(cgSettings.tag + "|" + requestId,
                        "[" + method + " " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + scheme + host + path + "?"
                                + paramsLog);
            } else {
                Log.i(cgSettings.tag + "|" + requestId, "[" + method + " | " + httpCode
                        + "] Failed to download " + scheme + host + path + "?" + paramsLog);
            }

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgeoBase.request.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.request: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    cgResponse response = new cgResponse();
    String data = null;

    try {
        if (httpCode == 302 && httpLocation != null) {
            final Uri newLocation = Uri.parse(httpLocation);
            if (newLocation.isRelative() == true) {
                response = request(secure, host, path, "GET", new HashMap<String, String>(), requestId, false,
                        false, false);
            } else {
                boolean secureRedir = false;
                if (newLocation.getScheme().equals("https")) {
                    secureRedir = true;
                }
                response = request(secureRedir, newLocation.getHost(), newLocation.getPath(), "GET",
                        new HashMap<String, String>(), requestId, false, false, false);
            }
        } else {
            if (buffer != null && buffer.length() > 0) {
                data = replaceWhitespace(buffer);
                buffer = null;

                if (data != null) {
                    response.setData(data);
                } else {
                    response.setData("");
                }
                response.setStatusCode(httpCode);
                response.setStatusMessage(httpMessage);
                response.setUrl(u.toString());
            }
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgeoBase.page: " + e.toString());
    }

    return response;
}

From source file:net.jotel.ws.client.WebSocketClient.java

private void handshake() throws IOException {
    OutputStreamWriter writer = new OutputStreamWriter(outputStream, Charset.forName("UTF8"));

    // Once a connection to the server has been established (including a
    // connection via a proxy or over a TLS-encrypted tunnel), the client
    // MUST send an opening handshake to the server. The handshake consists
    // of an HTTP upgrade request, along with a list of required and
    // optional headers. The requirements for this handshake are as
    // follows.//from  w  w w .j  a va  2s  . co  m

    // 1. The handshake MUST be a valid HTTP request as specified by
    // [RFC2616].

    // 2. The Method of the request MUST be GET and the HTTP version
    // MUST be at least 1.1.

    log.debug("Upgrade request");
    // 3. The request MUST contain a "Request-URI" as part of the GET
    // method. This MUST match the /resource name/ Section 3 (a
    // relative URI), or be an absolute URI that, when parsed, has a
    // matching /resource name/ as well as matching /host/, /port/, and
    // appropriate scheme (ws or wss).
    writer.write("GET ");
    writer.write(resourceName);
    writer.write(" HTTP/1.1\r\n");

    // 4. The request MUST contain a "Host" header whose value is equal to
    // /host/.
    writer.write(HOST_HEADER);
    writer.write(": ");
    writer.write(host);
    writer.write(CRLF);

    // 5. The request MUST contain an "Upgrade" header whose value is
    // equal to "websocket".
    writer.write(UPGRADE_HEADER);
    writer.write(": websocket\r\n");

    // 6. The request MUST contain a "Connection" header whose value MUST
    // include the "Upgrade" token.
    writer.write(CONNECTION_HEADER);
    writer.write(": Upgrade\r\n");

    // 7. The request MUST include a header with the name "Sec-WebSocket-
    // Key". The value of this header MUST be a nonce consisting of a
    // randomly selected 16-byte value that has been base64-encoded
    // [RFC3548]. The nonce MUST be selected randomly for each
    // connection.

    SecWebSocketKey key = generateSecWebSocketKey();

    writer.write(SEC_WEB_SOCKET_KEY_HEADER);
    writer.write(": ");
    writer.write(key.getKey());
    writer.write(CRLF);

    // 8. The request MUST include a header with the name "Sec-WebSocket-
    // Origin" if the request is coming from a browser client. If the
    // connection is from a non-browser client, the request MAY include
    // this header if the semantics of that client match the use-case
    // described here for browser clients. The value of this header
    // MUST be the ASCII serialization of origin of the context in
    // which the code establishing the connection is running, and MUST
    // be lower-case. The value MUST NOT contain letters in the range
    // U+0041 to U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL
    // LETTER Z) [I-D.ietf-websec-origin]. The ABNF is as defined in
    // Section 6.1 of [I-D.ietf-websec-origin].
    writer.write(ORIGIN_HEADER);
    writer.write(": ");
    writer.write(origin);
    writer.write(CRLF);

    // 9. The request MUST include a header with the name "Sec-WebSocket-
    // Version". The value of this header MUST be 8.
    writer.write(SEC_WEB_SOCKET_VERSION_HEADER);
    writer.write(": 8\r\n");

    // 10. The request MAY include a header with the name "Sec-WebSocket-
    // Protocol". If present, this value indicates the subprotocol(s)
    // the client wishes to speak, ordered by preference. The elements
    // that comprise this value MUST be non-empty strings with
    // characters in the range U+0021 to U+007E not including separator
    // characters as defined in [RFC2616], and MUST all be unique
    // strings. The ABNF for the value of this header is 1#token,
    // where the definitions of constructs and rules are as given in
    // [RFC2616].
    //
    if (!StringUtils.isBlank(protocol)) {
        writer.write(SEC_WEB_SOCKET_PROTOCOL_HEADER);
        writer.write(": ");
        writer.write(protocol);
        writer.write(CRLF);
    }

    // 11. The request MAY include a header with the name "Sec-WebSocket-
    // Extensions". If present, this value indicates the protocol-
    // level extension(s) the client wishes to speak. The
    // interpretation and format of this header is described in
    // Section 9.1.

    // TODO

    // 12. The request MAY include headers associated with sending cookies,
    // as defined by the appropriate specifications
    // [I-D.ietf-httpstate-cookie]. These headers are referred to as
    // _Headers to Send Appropriate Cookies_.
    //

    // TODO

    // extra headers
    for (Map.Entry<String, String> entry : extraHeaders.entrySet()) {
        writer.write(entry.getKey());
        writer.write(": ");
        writer.write(entry.getValue());
        writer.write(CRLF);
    }

    writer.write(CRLF);
    writer.flush();

    // Once the client's opening handshake has been sent, the client MUST
    // wait for a response from the server before sending any further data.

    String code = readStatusCode(inputStream);

    log.debug("Server response code {}", code);
    // The client MUST validate the server's response as follows:

    // 1. If the status code received from the server is not 101, the
    // client handles the response per HTTP procedures. Otherwise,
    // proceed as follows.

    if (!"101".equals(code)) {
        throw new WebSocketException("Invalid handshake response");
    }

    Map<String, List<String>> fieldMap = readFields(inputStream);

    String value;

    // 2. If the response lacks an "Upgrade" header or the "Upgrade" header
    // contains a value that is not an ASCII case-insensitive match for
    // the value "websocket", the client MUST _Fail the WebSocket
    // Connection _.

    value = getFieldValue(fieldMap, "upgrade");
    if (!"WebSocket".equalsIgnoreCase(value)) {
        throw new WebSocketException("Expected WebSocket as Updgrade field value!");
    }

    // 3. If the response lacks a "Connection" header or the "Connection"
    // header contains a value that is not an ASCII case-insensitive
    // match for the value "Upgrade", the client MUST _Fail the
    // WebSocket Connection_.
    value = getFieldValue(fieldMap, "connection");
    if (!UPGRADE_HEADER.equalsIgnoreCase(value)) {
        throw new WebSocketException("Expected Upgrade as Connection field value!");
    }

    // 4. If the response lacks a "Sec-WebSocket-Accept" header or the
    // "Sec-WebSocket-Accept" contains a value other than the base64-
    // encoded SHA-1 of the concatenation of the "Sec-WebSocket-Key" (as
    // a string, not base64-decoded) with the string "258EAFA5-E914-
    // 47DA-95CA-C5AB0DC85B11", the client MUST _Fail the WebSocket
    // Connection_
    value = getFieldValue(fieldMap, "sec-websocket-accept");

    if (!key.isServerKeyValid(value)) {
        throw new WebSocketException("Server key doesn't match an expected response");
    }

    // 5. If the response includes a "Sec-WebSocket-Extensions" header, and
    // this header indicates the use of an extension that was not
    // present in the client' handshake (the server has indicated an
    // extension not requested by the client), the client MUST _Fail the
    // WebSocket Connection_. (The parsing of this header to determine
    // which extensions are requested is discussed in Section 9.1.)

    value = getFieldValue(fieldMap, "sec-websocket-extensions");
    if (!StringUtils.isEmpty(value)) {
        throw new WebSocketException("The server has indicated an extension not request by the client!");
    }

    if (fieldMap.containsKey("")) {
        throw new WebSocketException("Empty field name found in field list!");
    }

    // If the server's response is validated as provided for above, it is
    // said that _The WebSocket Connection is Established_ and that the
    // WebSocket Connection is in the OPEN state. The _Extensions In Use_
    // is defined to be a (possibly empty) string, the value of which is
    // equal to the value of the |Sec-WebSocket-Extensions| header supplied
    // by the server's handshake, or the null value if that header was not
    // present in the server's handshake. The _Subprotocol In Use_ is
    // defined to be the value of the |Sec-WebSocket-Protocol| header in the
    // server's handshake, or the null value if that header was not present
    // in the server's handshake. Additionally, if any headers in the
    // server's handshake indicate that cookies should be set (as defined by
    // [I-D.ietf-httpstate-cookie]), these cookies are referred to as
    // _Cookies Set During the Server's Opening Handshake_.
}

From source file:Admin_Thesaurus.ImportData.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (SystemIsLockedForAdministrativeJobs(request, response)) {
        return;//  w ww .ja  va  2  s  .  c om
    }
    String basePath = request.getSession().getServletContext().getRealPath("");

    // ---------------------- LOCK SYSTEM ----------------------
    ConfigDBadmin config = new ConfigDBadmin(basePath);
    DBAdminUtilities dbAdminUtils = new DBAdminUtilities();
    dbAdminUtils.LockSystemForAdministrativeJobs(config);

    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    HttpSession session = request.getSession();
    ServletContext context = session.getServletContext();
    SessionWrapperClass sessionInstance = new SessionWrapperClass();
    init(request, response, sessionInstance);

    PrintWriter out = response.getWriter();

    OutputStreamWriter logFileWriter = null;

    try {

        // check for previous logon but because of ajax usage respond with Session Invalidate str
        UserInfoClass SessionUserInfo = (UserInfoClass) sessionInstance.getAttribute("SessionUser");

        if (SessionUserInfo == null || !SessionUserInfo.servletAccessControl(this.getClass().getName())) {
            out.println("Session Invalidate");
            response.sendRedirect("Index");
            return;
        }

        //tools
        Utilities u = new Utilities();
        DBGeneral dbGen = new DBGeneral();
        DBImportData dbImport = new DBImportData();
        DBMergeThesauri dbMerge = new DBMergeThesauri();
        StringObject translatedMsgObj = new StringObject("");

        Vector<String> thesauriNames = new Vector<String>();

        CommonUtilsDBadmin common_utils = new CommonUtilsDBadmin(config);
        StringObject resultObj = new StringObject("");

        String initiallySelectedThesaurus = SessionUserInfo.selectedThesaurus;

        //Parameters
        String xmlFilePath = request.getParameter("importXMLfilename");

        //String importSchemaName    = request.getParameter("schematype");
        String importSchemaName = ConstantParameters.xmlschematype_THEMAS;
        String importThesaurusName = request.getParameter("Import_Thesaurus_NewName_NAME");
        String importMethodChoice = request.getParameter("ImportThesaurusMode");//thesaurusImport or bulkImport
        String importHierarchyName = u
                .getDecodedParameterValue(request.getParameter("Import_Thesaurus_HierarchyName"));
        String pathToErrorsXML = context.getRealPath("/translations/Consistencies_Error_Codes.xml");
        String language = context.getInitParameter("LocaleLanguage");
        String country = context.getInitParameter("LocaleCountry");
        String WebAppUsersFileName = request.getSession().getServletContext()
                .getRealPath("/" + UsersClass.WebAppUsersXMLFilePath);

        String logPath = context.getRealPath("/" + ConstantParameters.LogFilesFolderName);
        String logFileNamePath = logPath;
        String webAppSaveResults_Folder = Parameters.Save_Results_Folder;
        String pathToSaveScriptingAndLocale = context
                .getRealPath("/translations/SaveAll_Locale_And_Scripting.xml");
        Locale targetLocale = new Locale(language, country);

        if ((importMethodChoice.equals("thesaurusImport") && (importThesaurusName != null))
                || (importMethodChoice.equals("bulkImport") && importHierarchyName != null)) {
            UpDownFiles fup = new UpDownFiles();
            String[] formData = new String[10];
            FileItem[] dom = fup.prepareToUpBinary(request, formData);
            //Hashtable initParams = UpDownFiles.uploadParams;

            if (dom[0] != null) {

                String filename = xmlFilePath;
                ///String caption = (String) initParams.get("caption");

                filename = filename.substring(filename.lastIndexOf(File.separator) + 1);

                String fileType = filename.substring(filename.lastIndexOf(".") + 1);
                String userFileName = filename.substring(0, filename.lastIndexOf("."));

                filename = userFileName + "(" + getDate() + " " + getTime() + ")." + fileType;

                String fullPath = getServletContext().getRealPath("/Uploads") + "/" + filename;
                xmlFilePath = fullPath;
                if (fup.writeBinary(dom[0], fullPath)) {
                    //mode = 1;
                } else {
                    //mode = -1;
                }
            } else {
                //mode = -1;
            }
        }

        QClass Q = new QClass();
        TMSAPIClass TA = new TMSAPIClass();
        IntegerObject sis_session = new IntegerObject();
        IntegerObject tms_session = new IntegerObject();

        //open connection and start transaction
        if (dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, null, null,
                true) == QClass.APIFail) {
            Utils.StaticClass
                    .webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName());
            return;
        }

        dbGen.GetExistingThesaurus(false, thesauriNames, Q, sis_session);

        if (importMethodChoice.equals("thesaurusImport")) {

            //Format Name Of import Thesaurus
            importThesaurusName = importThesaurusName.trim();
            importThesaurusName = importThesaurusName.replaceAll(" ", "_");
            importThesaurusName = importThesaurusName.toUpperCase();

            if (thesauriNames.contains(importThesaurusName)) {

                resultObj.setValue(u.translateFromMessagesXML("root/ImportData/importThesaurusNameFailure",
                        new String[] { importThesaurusName }));
                //resultObj.setValue("Thesaurus '" + importThesaurusName + "' already exists in database. Please choose a different name for the Thesaurus.");

                Vector<String> allHierarchies = new Vector<String>();
                Vector<String> allGuideTerms = new Vector<String>();
                dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session,
                        allHierarchies, allGuideTerms);

                //end query and close connection
                Q.free_all_sets();
                Q.TEST_end_query();
                //Q.TEST_abort_transaction();
                dbGen.CloseDBConnection(Q, null, sis_session, null, false);

                StringBuffer xml = new StringBuffer();
                xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI));
                xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms,
                        targetLocale));

                xml.append(getXMLMiddle(thesauriNames,
                        u.translateFromMessagesXML("root/ImportData/ImportFunctionFailure", null)
                                + resultObj.getValue(),
                        importMethodChoice));
                xml.append(u.getXMLUserInfo(SessionUserInfo));
                xml.append(u.getXMLEnd());
                u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl");

                // ---------------------- UNLOCK SYSTEM ----------------------
                dbAdminUtils.UnlockSystemForAdministrativeJobs();
                return;
            }
        } else if (importMethodChoice.equals("bulkImport")) {
            importThesaurusName = SessionUserInfo.selectedThesaurus;
            if (thesauriNames.contains(importThesaurusName) == false) {

                //String pathToMessagesXML = context.getRealPath("/translations/Messages.xml");
                //StringObject resultMessageObj = new StringObject();
                StringObject resultMessageObj_2 = new StringObject();
                //Vector<String> errorArgs = new Vector<String>();

                resultObj.setValue(u.translateFromMessagesXML("root/ImportData/ThesaurusDoesNotExist",
                        new String[] { importThesaurusName }));

                //resultObj.setValue("Thesaurus '" + importThesaurusName + "' does not exist in database. Please choose a different thesaurus if this one still exists.");
                Vector<String> allHierarchies = new Vector<String>();
                Vector<String> allGuideTerms = new Vector<String>();
                dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session,
                        allHierarchies, allGuideTerms);

                //end query and close connection
                Q.free_all_sets();
                Q.TEST_end_query();
                //Q.TEST_abort_transaction();
                dbGen.CloseDBConnection(Q, null, sis_session, null, false);

                StringBuffer xml = new StringBuffer();
                xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI));
                xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms,
                        targetLocale));

                resultMessageObj_2
                        .setValue(u.translateFromMessagesXML("root/ImportData/InsertionFailure", null));
                xml.append(getXMLMiddle(thesauriNames, resultMessageObj_2.getValue() + resultObj.getValue(),
                        importMethodChoice));
                //xml.append(getXMLMiddle(thesauriNames, "Data insertion failure. " + resultObj.getValue(),importMethodChoice));
                xml.append(u.getXMLUserInfo(SessionUserInfo));
                xml.append(u.getXMLEnd());
                u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl");

                // ---------------------- UNLOCK SYSTEM ----------------------
                dbAdminUtils.UnlockSystemForAdministrativeJobs();
                return;
            }
        }

        //end query and close connection
        Q.free_all_sets();
        Q.TEST_end_query();
        dbGen.CloseDBConnection(Q, null, sis_session, null, false);
        Utils.StaticClass.closeDb();

        StringObject DBbackupFileNameCreated = new StringObject("");

        long startTime = Utilities.startTimer();
        String time = Utilities.GetNow();
        String Filename = "Import_Thesaurus_" + importThesaurusName + "_" + time;
        logFileNamePath += "/" + Filename + ".xml";

        try {
            OutputStream fout = new FileOutputStream(logFileNamePath);
            OutputStream bout = new BufferedOutputStream(fout);
            logFileWriter = new OutputStreamWriter(bout, "UTF-8");
            logFileWriter.append(ConstantParameters.xmlHeader);//+ "\r\n"

            //logFileWriter.append("<?xml-stylesheet type=\"text/xsl\" href=\"../" + webAppSaveResults_Folder + "/ImportCopyMergeThesaurus_Report.xsl" + "\"?>\r\n");
            logFileWriter.append("<page language=\"" + Parameters.UILang + "\" primarylanguage=\""
                    + Parameters.PrimaryLang.toLowerCase() + "\">\r\n");
            logFileWriter.append("<title>"
                    + u.translateFromMessagesXML("root/ImportData/ReportTitle",
                            new String[] { importThesaurusName, time })
                    + "</title>\r\n" + "<pathToSaveScriptingAndLocale>" + pathToSaveScriptingAndLocale
                    + "</pathToSaveScriptingAndLocale>\r\n");
            //logFileWriter.append("<!--"+time + " LogFile for data import in thesaurus: " + importThesaurusName +".-->\r\n");
            Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + time
                    + " LogFile for data import in thesaurus: " + importThesaurusName + ".");

        } catch (Exception exc) {
            Utils.StaticClass.webAppSystemOutPrintln(
                    Parameters.LogFilePrefix + "Error in opening file: " + exc.getMessage());
            Utils.StaticClass.handleException(exc);
        }

        if (importMethodChoice.equals("thesaurusImport")) {

            if (dbImport.thesaurusImportActions(SessionUserInfo, common_utils, config, targetLocale,
                    pathToErrorsXML, xmlFilePath, importSchemaName, importThesaurusName,
                    "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated,
                    resultObj, logFileWriter) == false) {
                abortActions(request, sessionInstance, context, targetLocale, common_utils,
                        initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj,
                        out);
                return;
            }
        } else if (importMethodChoice.equals("bulkImport")) {
            /*
             //open connection and start Transaction
             if(dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, tms_session, SessionUserInfo.selectedThesaurus, false)==QClass.APIFail)
             {
             Utils.StaticClass.webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName());
             return;
             }
             */
            if (dbImport.bulkImportActions(sessionInstance, context, common_utils, config, targetLocale,
                    pathToErrorsXML, xmlFilePath, importThesaurusName, importHierarchyName,
                    "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated,
                    resultObj, logFileWriter) == false) {
                abortActions(request, sessionInstance, context, targetLocale, common_utils,
                        initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj,
                        out);
                return;
            }

        }

        commitActions(request, WebAppUsersFileName, sessionInstance, context, targetLocale, importThesaurusName,
                out, Filename.concat(".html"));

        //ReportSuccessMessage            
        logFileWriter
                .append("\r\n<creationInfo>"
                        + u.translateFromMessagesXML("root/ImportData/ReportSuccessMessage",
                                new String[] { importThesaurusName, xmlFilePath,
                                        ((Utilities.stopTimer(startTime)) / 60) + "" })
                        + "</creationInfo>\r\n");

        if (logFileWriter != null) {
            logFileWriter.append("</page>");
            logFileWriter.flush();
            logFileWriter.close();
        }

        //Now XSL should be found and java xsl transformation should be performed
        String XSL = context.getRealPath("/" + webAppSaveResults_Folder)
                + "/ImportCopyMergeThesaurus_Report.xsl";

        u.XmlFileTransform(logFileNamePath, XSL, logPath + "/" + Filename.concat(".html"));

    } catch (Exception e) {

        Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + ".Exception catched in servlet "
                + getServletName() + ". Message:" + e.getMessage());
        Utils.StaticClass.handleException(e);
        if (logFileWriter != null) {
            logFileWriter.append("</page>");
            logFileWriter.flush();
            logFileWriter.close();
        }
    } finally {
        out.flush();
        out.close();
        sessionInstance.writeBackToSession(session);
    }
}

From source file:org.apache.openaz.xacml.std.dom.DOMResponse.java

/**
 * Do the work of converting the {@link org.apache.openaz.xacml.api.Response} object to a string, allowing
 * for pretty-printing if desired./*from  www . ja  v  a 2s . com*/
 *
 * @param response
 * @param outputStream
 * @param prettyPrint
 * @throws java.io.IOException
 * @throws DOMStructureException
 */
public static void convert(Response response, OutputStream outputStream, boolean prettyPrint)
        throws IOException, DOMStructureException {

    OutputStreamWriter osw = new OutputStreamWriter(outputStream);

    if (response == null) {
        throw new DOMStructureException("No Request in convert");
    }

    if (response.getResults() == null || response.getResults().size() == 0) {
        // must be at least one result
        throw new DOMStructureException("No Result in Response");
    }

    StringBuilder sb = new StringBuilder();

    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

    if (prettyPrint)
        sb.append("\n");

    // response with attributes
    sb.append("<Response");

    // TODO include all Namespace info
    // Currently this is hard-coded for just the standard XACML namespaces, but ideally should use
    // Namespaces from incoming Request to get non-standard ones.
    sb.append(" xmlns=\"urn:oasis:names:tc:xacml:3.0:core:schema:wd-17\"");
    sb.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
    sb.append(" xsi:schemaLocation=\"urn:oasis:names:tc:xacml:3.0:core:schema:wd-17");
    sb.append(" http://docs.oasis-open.org/xacml/3.0/xacml-core-v3-schema-wd-17.xsd\"");

    // end of <Response>
    sb.append(">");

    // for each Result...
    for (Result result : response.getResults()) {

        if (prettyPrint)
            sb.append("\n\t");

        sb.append("<Result>");

        // Decision
        if (prettyPrint)
            sb.append("\n\t\t");

        if (result.getDecision() == null) {
            throw new DOMStructureException("Result missing Decision");
        }
        sb.append("<Decision>" + result.getDecision().toString() + "</Decision>");

        // Status
        Status status = result.getStatus();
        if (status != null) {
            if (prettyPrint)
                sb.append("\n\t\t");
            sb.append("<Status>");

            // status code
            StatusCode statusCode = status.getStatusCode();
            Identifier statusCodeId;
            if (statusCode == null) {
                throw new DOMStructureException("Status must have StatusCode");
            } else {
                statusCodeId = statusCode.getStatusCodeValue();
                // if there is a status code, it must agree with the decision
                // Permit/Deny/NotAllowed must all be OK
                // Indeterminate must not be OK
                if (statusCodeId.equals(StdStatusCode.STATUS_CODE_OK.getStatusCodeValue())
                        && !(result.getDecision() == Decision.DENY || result.getDecision() == Decision.PERMIT
                                || result.getDecision() == Decision.NOTAPPLICABLE)
                        || !statusCodeId.equals(StdStatusCode.STATUS_CODE_OK.getStatusCodeValue())
                                && !(result.getDecision() == Decision.INDETERMINATE
                                        || result.getDecision() == Decision.INDETERMINATE_DENY
                                        || result.getDecision() == Decision.INDETERMINATE_DENYPERMIT
                                        || result.getDecision() == Decision.INDETERMINATE_PERMIT)) {
                    throw new DOMStructureException("StatusCode '" + statusCodeId.stringValue()
                            + "' does not match Decision '" + result.getDecision().toString());
                }

                outputStatusCode(sb, statusCode, 3, prettyPrint);
            }

            // status message
            if (status.getStatusMessage() != null) {

                if (prettyPrint)
                    sb.append("\n\t\t\t");
                sb.append("<StatusMessage>" + status.getStatusMessage() + "</StatusMessage>");

            }

            // status detail
            StatusDetail statusDetail = status.getStatusDetail();
            if (statusDetail != null) {
                // cross-check that rules defined in XACML Core spec section 5.5.7 re: when StatusDetail
                // may/may-not be included have been followed
                if (status.isOk()) {
                    throw new DOMStructureException(
                            "Status '" + statusCodeId.stringValue() + "' must not return StatusDetail");
                } else if (statusCodeId.stringValue().equals(XACML3.ID_STATUS_MISSING_ATTRIBUTE.stringValue())
                        && status.getStatusDetail().getMissingAttributeDetails() == null) {
                    throw new DOMStructureException("Status '" + statusCodeId.stringValue()
                            + "' has StatusDetail without MissingAttributeDetail");
                } else if (statusCodeId.stringValue().equals(XACML3.ID_STATUS_SYNTAX_ERROR.stringValue())) {
                    throw new DOMStructureException(
                            "Status '" + statusCodeId.stringValue() + "' must not return StatusDetail");
                } else if (statusCodeId.stringValue().equals(XACML3.ID_STATUS_PROCESSING_ERROR.stringValue())) {
                    throw new DOMStructureException(
                            "Status '" + statusCodeId.stringValue() + "' must not return StatusDetail");
                }

                // if included, StatusDetail is handled differently for each type of detail message and
                // the contents are formatted into escaped XML rather than objects

                if (result.getStatus().getStatusDetail().getMissingAttributeDetails() != null) {
                    if (prettyPrint)
                        sb.append("\n\t\t\t");
                    sb.append("<StatusDetail>");

                    for (MissingAttributeDetail mad : statusDetail.getMissingAttributeDetails()) {
                        if (mad.getAttributeId() == null || mad.getCategory() == null
                                || mad.getDataTypeId() == null) {
                            throw new DOMStructureException(
                                    "MissingAttributeDetail is missing required AttributeId, Category or DataTypeId");
                        }
                        if (prettyPrint)
                            sb.append("\n\t\t\t\t");
                        sb.append("<MissingAttributeDetail");
                        sb.append(" Category=\"" + mad.getCategory().stringValue() + "\"");
                        sb.append(" AttributeId=\"" + mad.getAttributeId().stringValue() + "\"");
                        sb.append(" DataTypeId=\"" + mad.getDataTypeId().stringValue() + "\"");
                        if (mad.getIssuer() != null) {
                            sb.append(" Issuer=\"" + mad.getIssuer() + "\"");
                        }
                        sb.append(">");
                        if (mad.getAttributeValues() != null) {
                            for (AttributeValue<?> value : mad.getAttributeValues()) {
                                if (prettyPrint) {
                                    sb.append("\n\t\t\t\t\t");
                                }
                                sb.append("<AttributeValue" + getNamespaces(value.getValue()) + ">"
                                        + outputValueValue(value.getValue()) + "</AttributeValue>");
                            }
                        }
                        if (prettyPrint) {
                            sb.append("\n\t\t\t\t");
                        }
                        sb.append("</MissingAttributeDetail>");
                    }

                    if (prettyPrint) {
                        sb.append("\n\t\t\t");
                    }
                    sb.append("</StatusDetail>");
                }
            }

            if (prettyPrint)
                sb.append("\n\t\t");
            sb.append("</Status>");
        }

        // Obligations
        if (result.getObligations() != null && result.getObligations().size() > 0) {
            if (prettyPrint)
                sb.append("\n\t\t");
            sb.append("<Obligations>");

            for (Obligation obligation : result.getObligations()) {
                if (obligation.getId() == null) {
                    throw new DOMStructureException("Obligation must have ObligationId");
                }
                if (prettyPrint)
                    sb.append("\n\t\t\t");
                sb.append("<Obligation ObligationId=\"" + obligation.getId().stringValue() + "\">");

                for (AttributeAssignment aa : obligation.getAttributeAssignments()) {
                    if (prettyPrint)
                        sb.append("\n\t\t\t\t");
                    sb.append("<AttributeAssignment");

                    if (aa.getAttributeId() == null) {
                        throw new DOMStructureException("Obligation AttributeAssignment must have AttributeId");
                    }
                    sb.append(" AttributeId=\"" + aa.getAttributeId().stringValue() + "\"");
                    if (aa.getDataTypeId() == null || aa.getAttributeValue() == null
                            || aa.getAttributeValue().getValue() == null) {
                        throw new DOMStructureException("Obligation AttributeAssignment '"
                                + aa.getAttributeId().stringValue() + "' must have DataType and Value");
                    }
                    sb.append(" DataType=\"" + aa.getDataTypeId().stringValue() + "\""
                            + getNamespaces(aa.getAttributeValue().getValue()) + ">");
                    sb.append(outputValueValue(aa.getAttributeValue().getValue()));

                    sb.append("</AttributeAssignment>");
                }

                if (prettyPrint)
                    sb.append("\n\t\t\t");
                sb.append("</Obligation>");
            }

            if (prettyPrint)
                sb.append("\n\t\t");
            sb.append("</Obligations>");
        }

        // AssociatedAdvice
        if (result.getAssociatedAdvice() != null && result.getAssociatedAdvice().size() > 0) {
            if (prettyPrint)
                sb.append("\n\t\t");
            sb.append("<AssociatedAdvice>");

            for (Advice advice : result.getAssociatedAdvice()) {
                if (advice.getId() == null) {
                    throw new DOMStructureException("Advice must have AdviceId");
                }
                if (prettyPrint)
                    sb.append("\n\t\t\t");
                sb.append("<Advice AdviceId=\"" + advice.getId().stringValue() + "\">");

                for (AttributeAssignment aa : advice.getAttributeAssignments()) {
                    if (prettyPrint)
                        sb.append("\n\t\t\t\t");
                    sb.append("<AttributeAssignment");

                    if (aa.getAttributeId() == null) {
                        throw new DOMStructureException("Advice AttributeAssignment must have AttributeId");
                    }
                    sb.append(" AttributeId=\"" + aa.getAttributeId().stringValue() + "\"");
                    if (aa.getDataTypeId() == null || aa.getAttributeValue() == null
                            || aa.getAttributeValue().getValue() == null) {
                        throw new DOMStructureException("Advice AttributeAssignment '"
                                + aa.getAttributeId().stringValue() + "' must have DataType and Value");
                    }
                    sb.append(" DataType=\"" + aa.getDataTypeId().stringValue() + "\""
                            + getNamespaces(aa.getAttributeValue().getValue()) + ">");
                    sb.append(outputValueValue(aa.getAttributeValue().getValue()));

                    sb.append("</AttributeAssignment>");
                }

                if (prettyPrint)
                    sb.append("\n\t\t\t");
                sb.append("</Advice>");
            }

            if (prettyPrint)
                sb.append("\n\t\t");
            sb.append("</AssociatedAdvice>");
        }

        // Attributes
        if (result.getAttributes() != null && result.getAttributes().size() > 0) {
            // this may include attributes with IncludeInResult=false!

            for (AttributeCategory category : result.getAttributes()) {
                if (prettyPrint)
                    sb.append("\n\t\t");
                if (category.getCategory() == null) {
                    throw new DOMStructureException("Attributes must have Category");
                }
                sb.append("<Attributes Category=\"" + category.getCategory().stringValue() + "\">");

                for (Attribute attr : category.getAttributes()) {
                    if (!attr.getIncludeInResults()) {
                        // skip this one - do not include in results
                        continue;
                    }
                    if (prettyPrint)
                        sb.append("\n\t\t\t");
                    sb.append("<Attribute IncludeInResult=\"" + attr.getIncludeInResults() + "\"");
                    if (attr.getAttributeId() == null) {
                        throw new DOMStructureException("Attribute inf Category '"
                                + category.getCategory().stringValue() + "' must have AttributeId");
                    }
                    sb.append(" AttributeId=\"" + attr.getAttributeId().stringValue() + "\"");
                    if (attr.getIssuer() == null) {
                        sb.append(">");
                    } else {
                        sb.append(" Issuer=\"" + attr.getIssuer() + "\">");
                    }

                    if (attr.getValues().size() == 0) {
                        throw new DOMStructureException(
                                "Attribute '" + attr.getAttributeId() + "' must have at least one value");
                    }
                    for (AttributeValue<?> value : attr.getValues()) {
                        if (value.getDataTypeId() == null || value.getValue() == null) {
                            throw new DOMStructureException("Attribute '" + attr.getAttributeId()
                                    + "' has AttributeValue missing either DataType or Value");
                        }
                        if (prettyPrint)
                            sb.append("\n\t\t\t\t");
                        sb.append("<AttributeValue DataType=\"" + value.getDataTypeId().stringValue() + "\"");
                        if (value.getXPathCategory() != null) {
                            sb.append(" XPathCategory=\"" + value.getXPathCategory().stringValue() + "\"");
                        }
                        sb.append(">");

                        sb.append(outputValueValue(value.getValue()));

                        sb.append("</AttributeValue>");
                    }

                    if (prettyPrint)
                        sb.append("\n\t\t\t");
                    sb.append("</Attribute>");
                }

                if (prettyPrint)
                    sb.append("\n\t\t");
                sb.append("</Attributes>");
            }

        }

        // PolicyIdentifierList
        Collection<IdReference> policyIds = result.getPolicyIdentifiers();
        Collection<IdReference> policySetIds = result.getPolicySetIdentifiers();
        if (policyIds != null && policyIds.size() > 0 || policySetIds != null && policySetIds.size() > 0) {
            if (prettyPrint)
                sb.append("\n\t\t\t");
            sb.append("<PolicyIdentifierList>");

            // individual Ids
            for (IdReference idReference : policyIds) {
                if (idReference == null) {
                    throw new DOMStructureException("PolicyIdentifiers has null IdReference");
                }
                if (prettyPrint)
                    sb.append("\n\t\t\t\t");
                sb.append("<PolicyIdReference");
                if (idReference.getVersion() != null) {
                    sb.append(" Version=\"" + idReference.getVersion().stringValue() + "\">");
                } else {
                    sb.append(">");
                }
                sb.append(idReference.getId().stringValue());
                sb.append("</PolicyIdReference>");
            }
            // Set Ids
            for (IdReference idReference : policySetIds) {
                if (idReference == null) {
                    throw new DOMStructureException("PolicySetIdentifiers has null IdReference");
                }
                if (prettyPrint)
                    sb.append("\n\t\t\t\t");
                sb.append("<PolicySetIdReference");
                if (idReference.getVersion() != null) {
                    sb.append(" Version=\"" + idReference.getVersion().stringValue() + "\">");
                } else {
                    sb.append(">");
                }
                sb.append(idReference.getId().stringValue());
                sb.append("</PolicySetIdReference>");
            }

            if (prettyPrint)
                sb.append("\n\t\t\t");
            sb.append("</PolicyIdentifierList>");
        }

        // end of Result
        if (prettyPrint)
            sb.append("\n\t");
        sb.append("</Result>");
    }

    if (prettyPrint)
        sb.append("\n");

    sb.append("</Response>");

    // all done

    osw.write(sb.toString());

    // force output
    osw.flush();

}