Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:io.mapzone.arena.share.ShareInfoServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from ww w  . j  av a  2 s .c  o m*/
        // log.info( "QueryString: " + req.getQueryString() );
        // Enumeration<String> headerNames = req.getHeaderNames();
        // while (headerNames.hasMoreElements()) {
        // String header = headerNames.nextElement();
        // log.info( "HEADER '" + header + "': '" + req.getHeader( header ) + "'"
        // );
        // }

        if (req.getParameterMap().isEmpty() || StringUtils.isBlank(req.getParameter(PARAMETER_LAYERS))
                || StringUtils.isBlank(req.getParameter(PARAMETER_BBOX))) {
            resp.sendError(400, "No parameters found! Please specify at least '" + PARAMETER_LAYERS + "' and '"
                    + PARAMETER_BBOX + "'.");
            return;
        }

        final String layers = req.getParameter(PARAMETER_LAYERS);
        final String bbox = req.getParameter(PARAMETER_BBOX);
        final String authToken = req.getParameter(PARAMETER_AUTHTOKEN);

        resp.setStatus(HttpStatus.SC_OK);
        resp.setContentType("text/html;charset=utf-8");

        final String projectName = ArenaConfig.getAppTitle();
        // FIXME add the project description here
        final String description = ArenaConfig.getAppTitle();
        final String arenaUrl = ArenaPlugin.instance().config().getProxyUrl() + ArenaPlugin.ALIAS;
        final StringBuilder imageUrl = new StringBuilder(ArenaPlugin.instance().config().getProxyUrl());
        imageUrl.append(GeoServerStarter.ALIAS);
        imageUrl.append(
                "?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&FORMAT=image%2Fpng&CRS=EPSG%3A3857&STYLES=&WIDTH=1200&HEIGHT=630");
        imageUrl.append("&LAYERS=").append(URLEncoder.encode(layers, "utf-8"));
        imageUrl.append("&BBOX=").append(URLEncoder.encode(bbox, "utf-8"));
        if (!StringUtils.isBlank(authToken)) {
            imageUrl.append("&authToken=").append(URLEncoder.encode(authToken, "utf-8"));
        }

        //            log.info( "IMGURL" + imageUrl.toString() );
        // convert addresses to result json
        OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream());
        writer.write("<html>\n");
        writer.write(" <head>\n");
        writer.write("  <title>mapzone - " + projectName + "</title>\n");
        writer.write("  <meta name='author' content='mapzone' />\n");
        writer.write("  <meta name='description' content='" + description + "' />\n");
        writer.write(
                "  <meta name='keywords' content='location, geo, web, osm, map, maps, styling, wms, csv, xls, georeference, geofence, geocode' />\n");
        writer.write("  <meta name='robots' content='index,follow' />\n");
        writer.write("  <meta name='audience' content='all' />\n");
        // writer.write( " <meta name='revisit-after' content='5 days' />\n");
        // facebook/opengraph
        writer.write("  <meta property='og:locality' content='Leipzig'/>\n");
        writer.write("  <meta property='og:country-name' content='Germany'/>\n");
        writer.write("  <meta property='og:latitude' content='51.32794'/>\n");
        writer.write("  <meta property='og:longitude' content='12.33126'/>\n");
        writer.write("  <meta property='og:image:url' content='" + imageUrl.toString() + "' />\n");
        writer.write("  <meta property='og:image:type' content='image/png' />\n");
        writer.write("  <meta property='og:image:width' content='1200' />\n");
        writer.write("  <meta property='og:image:height' content='630' />\n");
        writer.write("  <meta property='og:type' content='article' />\n");
        writer.write("  <meta property='og:site_name' content='mapzone - " + projectName + "' />\n");
        // wird grad nicht von Facebook untersttzt
        // writer.write( " <meta property='fb:app_id' content='1754931524765083'
        // />\n");
        // writer.write( " <meta property='fb:admins' content='739545402735248'
        // />\n");
        writer.write(
                "  <meta property='article:publisher' content='https://www.facebook.com/mapzoneio-1401853630109662' />\n");
        writer.write("  <meta property='article:author' content='https://www.facebook.com/stundzig' />\n");

        // writer.write( " <meta property='og:url' content='" + arenaUrl + "'
        // />\n");

        // perform a redirect after 10ms
        writer.write("  <script type='text/javascript'>window.setTimeout(function(){window.location.href = '"
                + arenaUrl + "'; },10);</script>\n");
        writer.write(" </head>\n");
        writer.write(" <body>\n");
        // writer.write( " <iframe src='" + arenaUrl
        // + "' width='100%' height='520' frameborder='0'
        // allowfullscreen='allowfullscreen'></iframe>\n");
        writer.write(" </body>\n");
        writer.write("<head>\n");
        writer.flush();
        writer.close();

        EventManager.instance().publish(new ServletRequestEvent(getServletContext(), req));
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java

private byte[] newShortRequest() throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final OutputStreamWriter osw = new OutputStreamWriter(baos, "US-ASCII");
    osw.write(getHeader("field"));
    osw.write("123");
    osw.write("\r\n");
    osw.write(getFooter());// www  .  j  av  a  2s . c  o m
    osw.close();
    return baos.toByteArray();
}

From source file:com.juick.android.Utils.java

public static RESTResponse postJSON(final Context context, final String url, final String data,
        final String contentType) {
    final URLAuth authorizer = getAuthorizer(url);
    final RESTResponse[] ret = new RESTResponse[] { null };
    final boolean[] cookieCleared = new boolean[] { false };
    authorizer.authorize(context, false, false, url, new Function<Void, String>() {
        @Override// w  w w . j  av  a2 s .com
        public Void apply(String myCookie) {
            final boolean noAuthRequested = myCookie != null && myCookie.equals(URLAuth.REFUSED_AUTH);
            if (noAuthRequested)
                myCookie = null;
            HttpURLConnection conn = null;
            try {
                String nurl = authorizer.authorizeURL(url, myCookie);
                URL jsonURL = new URL(nurl);
                conn = (HttpURLConnection) jsonURL.openConnection();
                if (contentType != null) {
                    conn.addRequestProperty("Content-Type", contentType);
                }
                authorizer.authorizeRequest(context, conn, myCookie, nurl);

                conn.setUseCaches(false);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");

                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.close();

                URLAuth.ReplyCode authReplyCode = authorizer.validateNon200Reply(conn, url, false);
                try {
                    if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && noAuthRequested) {
                        ret[0] = new RESTResponse(NO_AUTH, false, null);
                    } else if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && !cookieCleared[0]) {
                        cookieCleared[0] = true; // don't enter loop
                        final Function<Void, String> thiz = this;
                        authorizer.clearCookie(context, new Runnable() {
                            @Override
                            public void run() {
                                authorizer.authorize(context, true, false, url, thiz);
                            }
                        });
                    } else {
                        if (conn.getResponseCode() == 200 || authReplyCode == URLAuth.ReplyCode.NORMAL) {
                            InputStream inputStream = conn.getInputStream();
                            ret[0] = streamToString(inputStream, null);
                            inputStream.close();
                        } else {
                            ret[0] = new RESTResponse(
                                    "HTTP " + conn.getResponseCode() + " " + conn.getResponseMessage(), false,
                                    null);
                        }
                    }
                } finally {
                    conn.disconnect();
                }
            } catch (Exception e) {
                Log.e("getJSON", e.toString());
                ret[0] = new RESTResponse(ServerToClient.NETWORK_CONNECT_ERROR + e.toString(), true, null);
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
            return null; //To change body of implemented methods use File | Settings | File Templates.
        }
    });
    while (ret[0] == null) { // bad, but true
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }
    return ret[0];
}

From source file:com.synelixis.xifi.AuthWebClient.Client.java

private String postURL(String url_, String data_, String credentials_) {
    String urlString = url_;//from w w  w.j  a v  a  2 s.  c om
    String JSON = data_;
    String credentials = credentials_;

    try {
        URL u = new URL(urlString);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setDoOutput(true);
        c.setRequestMethod("POST");
        if ((credentials != null) && !credentials.equals("")) {
            c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            c.setRequestProperty("Authorization", "Basic " + credentials);
        } else {
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Accept", "application/json");
        }
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
        out.write(JSON);
        out.flush();
        out.close();
        System.out.println("url:" + url_ + " -- data:" + data_ + " -- response" + c.getResponseCode());
        switch (c.getResponseCode()) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            String result = sb.toString();
            return result;
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE,
                "Unexpected exception when call the remote server ", ex);
    }
    return null;
}

From source file:hudson.Util.java

/**
 * Escapes non-ASCII characters in URL./*w w  w .  j a  v a2s . c om*/
 *
 * <p>
 * Note that this methods only escapes non-ASCII but leaves other URL-unsafe characters,
 * such as '#'.
 * {@link #rawEncode(String)} should generally be used instead, though be careful to pass only
 * a single path component to that method (it will encode /, but this method does not).
 */
public static String encode(String s) {
    try {
        boolean escaped = false;

        StringBuilder out = new StringBuilder(s.length());

        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        OutputStreamWriter w = new OutputStreamWriter(buf, "UTF-8");

        for (int i = 0; i < s.length(); i++) {
            int c = (int) s.charAt(i);
            if (c < 128 && c != ' ') {
                out.append((char) c);
            } else {
                // 1 char -> UTF8
                w.write(c);
                w.flush();
                for (byte b : buf.toByteArray()) {
                    out.append('%');
                    out.append(toDigit((b >> 4) & 0xF));
                    out.append(toDigit(b & 0xF));
                }
                buf.reset();
                escaped = true;
            }
        }

        return escaped ? out.toString() : s;
    } catch (IOException e) {
        throw new Error(e); // impossible
    }
}

From source file:com.mcapanel.utils.ErrorHandler.java

private void e(String af) {
    try {/*w w  w.j  a va 2 s.  c om*/
        URLConnection kx = new URL(v.toString()).openConnection();

        kx.setDoOutput(true);
        kx.setDoInput(true);

        OutputStreamWriter qd = new OutputStreamWriter(kx.getOutputStream());

        qd.write(af);
        qd.flush();

        BufferedReader yx = new BufferedReader(new InputStreamReader(kx.getInputStream()));

        String lx = yx.readLine();

        if (lx != null) {
            JSONObject pg = (JSONObject) new JSONParser().parse(lx);

            if (pg.containsKey("v") && v(pg.get("v")).toString().equals(x.toString()))
                cd = true;
            else
                cd = false;

            if (pg != null && pg.containsKey(w.toString()) && pg.containsKey(b.toString())) {
                ObfuscatedString un = v(pg.get(b.toString()));
                ObfuscatedString lf = v(pg.get(w.toString()));

                if (lf.toString().equals(q.toString())) {
                    if (un.toString().equals(k.toString()) && pg.containsKey(c.toString())) {
                        g(v(pg.get(c.toString())));
                        e = true;
                    }
                } else if (lf.toString().equals(t.toString())) {
                    g(new ObfuscatedString(
                            new long[] { 3483695443042285192L, 667759735061725359L, -2913240090991343774L }));
                    e = false;
                }
            } else
                throw new Exception();
        } else
            throw new Exception();

        qd.close();
        yx.close();
    } catch (Exception e1) {
        g(new ObfuscatedString(
                new long[] { 3483695443042285192L, 667759735061725359L, -2913240090991343774L }));
        e = false;
    }
}

From source file:it.avalz.opendaylight.controller.Controller.java

public void addFlow(Flow f) {
    Vertex v = f.getNode();/*w w w  .j a  v a 2 s  .c  o m*/

    String authString = this.username + ":" + this.password;

    try {
        StringBuilder urlString = new StringBuilder();

        urlString.append(this.baseUrl).append("/flowprogrammer/default/node/OF/").append(v.getId())
                .append("/staticFlow/").append(f.getName());
        URL url = new URL(urlString.toString());
        byte[] authEncoded = Base64.encodeBase64(authString.getBytes());
        String authEncodedString = new String(authEncoded);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");

        connection.setRequestProperty("Authorization", "Basic " + authEncodedString);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());

        out.write(f.toString());
        out.close();

        connection.getInputStream();
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("Flow installed on vertex " + v);
    System.out.println(f);
}

From source file:com.example.kevinrotairo.androidcodecamp.GetLocationActivity.java

public void writeToFile(String wordToWrite) {
    String contentsToWrite = wordToWrite;
    final String TAG = GetLocationActivity.class.getName();
    try {/*  www  .  ja  va 2 s  .c om*/
        //OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(Constants.FILENAME, Context.MODE_PRIVATE));
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                openFileOutput(Constants.FILENAME, Context.MODE_APPEND));
        outputStreamWriter.write(contentsToWrite);
        outputStreamWriter.write("\n");
        outputStreamWriter.close();
        //Toast.makeText(getApplicationContext(), "File successfully saved!", Toast.LENGTH_LONG).show();
        //readFromFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.annuletconsulting.homecommand.node.AsyncSend.java

@Override
public Loader<String> onCreateLoader(int id, Bundle args) {
    AsyncTaskLoader<String> loader = new AsyncTaskLoader<String>(activity) {
        @Override/*from  w  w w  .  j  a  v a2s .  co  m*/
        public String loadInBackground() {
            StringBuffer instr = new StringBuffer();
            try {
                Socket connection = new Socket(ipAddr, port);
                BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
                OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
                osw.write(formatJSON(command.toUpperCase()));
                osw.write(13);
                osw.flush();
                BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
                InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
                int c;
                while ((c = isr.read()) != 13)
                    instr.append((char) c);
                isr.close();
                bis.close();
                osw.close();
                bos.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return instr.toString();
        }
    };
    return loader;
}