Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:org.apache.flume.instrumentation.zabbix.ZabbixSender.java

private void send(final String key, final String value) throws IOException {
    final StringBuilder message = new StringBuilder(head);
    // message.append(Base64.encode(key));
    message.append(base64Encode(key));//from w ww .  j  a  v  a 2 s.  co  m
    message.append(middle);
    // message.append(Base64.encode(value == null ? "" : value));
    message.append(base64Encode(value == null ? "" : value));
    message.append(tail);

    logger.trace("sending " + message);

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;

    for (Map.Entry<String, Integer> zabbixServer : zabbixServers.entrySet()) {

        try {

            zabbix = new Socket(zabbixServer.getKey(), zabbixServer.getValue());
            zabbix.setSoTimeout(TIMEOUT);

            out = new OutputStreamWriter(zabbix.getOutputStream());
            out.write(message.toString());
            out.flush();

            in = zabbix.getInputStream();
            final int read = in.read(response);
            logger.trace("received " + new String(response));
            if (read != 2 || response[0] != 'O' || response[1] != 'K') {
                logger.warn(
                        "received unexpected response '" + new String(response) + "' for key '" + key + "'");
            }
        } catch (Exception ex) {
            logger.warn("Error contacting Zabbix server " + zabbixServer.getKey() + "  on port "
                    + zabbixServer.getValue());
        }

        finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (zabbix != null) {
                zabbix.close();
            }

        }
    }
}

From source file:com.gu.management.switching.SwitchboardServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html");

    String switchToShow = request.getParameter("switch");

    OutputStreamWriter fileWriter = new OutputStreamWriter(response.getOutputStream());

    fileWriter.write(MANAGEMENT_PAGE_HEAD);

    for (Switchable switchable : switches) {

        if (StringUtils.isEmpty(switchToShow) || switchToShow.equals(switchable.getWordForUrl())) {
            fileWriter.write(String.format(SWITCH_TABLE_ROW, switchable.getWordForUrl(),
                    switchable.getDescription(), getButtonsFor(switchable)));
        }//from  ww  w .  j a  va 2  s .  c  o m
    }

    fileWriter.write(MANAGEMENT_PAGE_FOOT);

    fileWriter.flush();
}

From source file:connection.HttpReq.java

@Override
protected String doInBackground(HttpReqPkg... params) {

    URL url;/*  w w w.ja  v a  2  s  .  c  om*/
    BufferedReader reader = null;

    String username = params[0].getUsername();
    String password = params[0].getPassword();
    String authStringEnc = null;

    if (username != null && password != null) {
        String authString = username + ":" + password;

        byte[] authEncBytes;
        authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT);
        authStringEnc = new String(authEncBytes);
    }

    String uri = params[0].getUri();

    if (params[0].getMethod().equals("GET")) {
        uri += "?" + params[0].getEncodedParams();
    }

    try {
        StringBuilder sb;
        // create the HttpURLConnection
        url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        if (authStringEnc != null) {
            connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        }

        if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")
                || params[0].getMethod().equals("DELETE")) {
            // enable writing output to this url
            connection.setDoOutput(true);
        }

        if (params[0].getMethod().equals("POST")) {
            connection.setRequestMethod("POST");
        } else if (params[0].getMethod().equals("GET")) {
            connection.setRequestMethod("GET");
        } else if (params[0].getMethod().equals("PUT")) {
            connection.setRequestMethod("PUT");
        } else if (params[0].getMethod().equals("DELETE")) {
            connection.setRequestMethod("DELETE");
        }

        // give it x seconds to respond
        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setRequestProperty("Content-Type", contentType);

        for (int i = 0; i < headerMap.size(); i++) {
            connection.setRequestProperty(headerMap.keyAt(i), headerMap.valueAt(i));
        }

        connection.setRequestProperty("Content-Length", "" + params[0].getEncodedParams().getBytes().length);

        connection.connect();
        if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            String httpParams = params[0].getEncodedParams();

            if (contentType.equals(OptimusHTTP.CONTENT_TYPE_JSON)) {
                httpParams = httpParams.replace("=", " ");
            }

            writer.write(httpParams);
            writer.flush();
            writer.close();
        }

        // read the output from the server
        InputStream in;
        resCode = connection.getResponseCode();
        resMsg = connection.getResponseMessage();
        if (resCode != HttpURLConnection.HTTP_OK) {
            in = connection.getErrorStream();
        } else {
            in = connection.getInputStream();
        }
        reader = new BufferedReader(new InputStreamReader(in));
        sb = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        sb.append(resCode).append(" : ").append(resMsg);
        return sb.toString();
    } catch (Exception e) {
        listener.onFailure(Integer.toString(resCode) + " : " + resMsg);
        e.printStackTrace();
    } finally {
        // close the reader; this can throw an exception too, so
        // wrap it in another try/catch block.
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    return null;
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * {@code connect} is for forming the secure connection between server and
 * android, sending and receiving of the data.
 * /*from   www .j  ava 2 s .  co m*/
 * @param arg0
 *            data which is to be sent to server.
 * 
 * @return data in string format, received from the server.
 */
public String connect(String... arg0) {

    int nrOfDataToSendToServer = arg0.length;
    nrOfDataToSendToServer = nrOfDataToSendToServer - 1;
    boolean valid = false;
    String dataFromServer = "unverified", serverPublicKeySigStr, serverDataSig;

    try {
        //Creating the server certificate
        Certificate serverCertificate = getServerCertificate();

        KeyStore keyStore = getKeyStore(serverCertificate);

        TrustManagerFactory tmf = getTrustManager(keyStore);

        SSLContext sslContext = getSSLContext(tmf);

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection urlConnection = getURLConnection(sslContext, hostnameVerifier);

        // Converting the data into JSONObject
        JSONObject obj = new JSONObject();
        for (int i = 0; i <= nrOfDataToSendToServer; i++) {
            obj.put("param" + i, arg0[i]);
        }

        // Converting the JSONObject into string
        String dataToSend = obj.toString();

        KeyPairGenerator keyGen = getKeyPairGenerator();

        KeyPair keyPair = keyGen.generateKeyPair();
        //Public key for verifying the digital signature
        PublicKey clientPublicKeySig = keyPair.getPublic();
        //Private key for signing the data
        PrivateKey clientPrivateKeySig = keyPair.getPrivate();

        // Get signed data
        String sigData = getDataSig(clientPrivateKeySig, dataToSend);

        // Creating URL Format
        String urlData = URLEncoder.encode("clientPublicKeySig", "UTF-8") + "=" + URLEncoder
                .encode(Base64.encodeToString(clientPublicKeySig.getEncoded(), Base64.DEFAULT), "UTF-8");
        urlData += "&" + URLEncoder.encode("clientData", "UTF-8") + "="
                + URLEncoder.encode(dataToSend, "UTF-8");
        urlData += "&" + URLEncoder.encode("clientDataSig", "UTF-8") + "="
                + URLEncoder.encode(sigData, "UTF-8");

        // Sending the data to the server
        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(urlData);
        wr.flush();
        wr.close();

        // Receiving the data from server
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
            // sb.append(line);
        }
        String text = sb.toString();
        reader.close();

        // Extracting the data, public key and signature received from
        // server
        Vector<String> storeExtractedValues = new Vector<String>();

        storeExtractedValues = extractDataFromJson(text, "data");
        dataFromServer = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverPublicKeySig");
        serverPublicKeySigStr = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverDataSig");
        serverDataSig = storeExtractedValues.get(0);

        // Converting the Server Public key format to Java compatible from
        PublicKey serverPublicKeySig = getServerPublicKey(serverPublicKeySigStr);

        // Verify the received data
        valid = getDataValidity(serverPublicKeySig, dataFromServer, serverDataSig);

        // Disconnect the url connection
        urlConnection.disconnect();

        if (dataFromServer.equalsIgnoreCase("unverified")) {
            CExceptionHandling.ExceptionState = ExceptionSet.SENT_DATA_UNVERIFIED;
            return "-1";
        } else if (valid == false) {
            CExceptionHandling.ExceptionState = ExceptionSet.RECEIVED_DATA_UNVERIFIED;
            return "-1";
        } else {
            return dataFromServer;
        }

    } catch (Exception e) {
        CExceptionHandling.ExceptionMsg = e.getMessage();

        if (e.toString().equals("java.net.SocketException: Network unreachable")) {
            CExceptionHandling.ExceptionState = ExceptionSet.NO_DATA_CONNECTION;
        } else if (e.toString().equals(
                "java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 443) after 10000ms")) {
            CExceptionHandling.ExceptionState = ExceptionSet.CONNECTION_TIMEOUT;
        } else {
            CExceptionHandling.ExceptionState = ExceptionSet.OTHER_EXCEPTIONS;
        }
        return "-1";
    }

}

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

@Override
public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException {

    try {//from  w w  w. j a  v a2s. c  o m
        final GVBufferPropertyFormatter formatter = new GVBufferPropertyFormatter(gvBuffer);

        String expandedUrl = formatter.format(url);
        String querystring = "";

        if (!params.isEmpty()) {

            querystring = params.entrySet().stream().map(
                    e -> formatter.formatAndEncode(e.getKey()) + "=" + formatter.formatAndEncode(e.getValue()))
                    .collect(Collectors.joining("&"));

            expandedUrl = expandedUrl.concat("?").concat(querystring);
        }

        StringBuffer callDump = new StringBuffer();
        callDump.append("Performing RestCallOperation " + name).append("\n        ").append("URL: ")
                .append(expandedUrl);

        URL requestUrl = new URL(expandedUrl);

        HttpURLConnection httpURLConnection;
        if (truststorePath != null && expandedUrl.startsWith("https://")) {
            httpURLConnection = openSecureConnection(requestUrl);
        } else {
            httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
        }
        callDump.append("\n        ").append("Method: " + method);

        callDump.append("\n        ").append("Connection timeout: " + connectionTimeout);
        callDump.append("\n        ").append("Read timeout: " + readTimeout);

        httpURLConnection.setRequestMethod(method);
        httpURLConnection.setConnectTimeout(connectionTimeout);
        httpURLConnection.setReadTimeout(readTimeout);

        for (Entry<String, String> header : headers.entrySet()) {
            String k = formatter.format(header.getKey());
            String v = formatter.format(header.getValue());
            httpURLConnection.setRequestProperty(k, v);
            callDump.append("\n        ").append("Header: " + k + "=" + v);
            if ("content-type".equalsIgnoreCase(k) && "application/x-www-form-urlencoded".equalsIgnoreCase(v)) {
                body = querystring;
            }

        }

        if (sendGVBufferObject && gvBuffer.getObject() != null) {
            byte[] requestData;
            if (gvBuffer.getObject() instanceof byte[]) {
                requestData = (byte[]) gvBuffer.getObject();
            } else {
                requestData = gvBuffer.getObject().toString().getBytes();

            }
            httpURLConnection.setRequestProperty("Content-Length", Integer.toString(requestData.length));
            callDump.append("\n        ").append("Content-Length: " + requestData.length);
            callDump.append("\n        ").append("Request body: binary");
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(requestData);

            dataOutputStream.flush();
            dataOutputStream.close();

        } else if (Objects.nonNull(body) && body.length() > 0) {

            String expandedBody = formatter.format(body);
            callDump.append("\n        ").append("Request body: " + expandedBody);
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
            outputStreamWriter.write(expandedBody);
            outputStreamWriter.flush();
            outputStreamWriter.close();

        }

        httpURLConnection.connect();

        InputStream responseStream = null;

        try {
            httpURLConnection.getResponseCode();
            responseStream = httpURLConnection.getInputStream();
        } catch (IOException connectionFail) {
            responseStream = httpURLConnection.getErrorStream();
        }

        for (Entry<String, List<String>> header : httpURLConnection.getHeaderFields().entrySet()) {
            if (Objects.nonNull(header.getKey()) && Objects.nonNull(header.getValue())) {
                gvBuffer.setProperty(RESPONSE_HEADER_PREFIX.concat(header.getKey().toUpperCase()),
                        header.getValue().stream().collect(Collectors.joining(";")));
            }
        }

        if (responseStream != null) {

            byte[] responseData = IOUtils.toByteArray(responseStream);
            String responseContentType = Optional
                    .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse("");

            if (responseContentType.startsWith("application/json")
                    || responseContentType.startsWith("application/javascript")) {
                gvBuffer.setObject(new String(responseData, "UTF-8"));
            } else {
                gvBuffer.setObject(responseData);
            }

        } else { // No content
            gvBuffer.setObject(null);
        }

        gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(httpURLConnection.getResponseCode()));
        gvBuffer.setProperty(RESPONSE_MESSAGE,
                Optional.ofNullable(httpURLConnection.getResponseMessage()).orElse("NULL"));

        httpURLConnection.disconnect();

    } catch (Exception exc) {
        throw new CallException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                        { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } },
                exc);
    }
    return gvBuffer;
}

From source file:com.intranet.intr.inbox.SupControllerInbox.java

@RequestMapping("Inboxphp.htm")
public ModelAndView Inboxphp(ModelAndView mav, Principal principal) {
    String name = principal.getName();
    List<correoNoLeidos> lta = null;
    int numTodoscorreosNum = 0;
    Map<String, String> datosEnv = new HashMap<String, String>();
    datosEnv.put("nombre", "pepe");
    datosEnv.put("apellido", "Gonzalez");
    Gson gson = new Gson();
    String jsonOutput = gson.toJson(datosEnv);
    try {/*from w  ww. jav a2  s.  c o  m*/
        //Usamos URLencode para poder enviar la cadena
        jsonOutput = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(jsonOutput, "UTF-8");
        //Establecemos la conexion y enviamos los datos
        URL url = new URL("http://localhost/php/index.php");
        URLConnection con = (URLConnection) url.openConnection();
        con.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
        wr.write(jsonOutput);
        wr.flush();
        //Recibimos los datos
        BufferedReader recv = new BufferedReader(new InputStreamReader(con.getInputStream()));
        //Los mostramos por pantalla
        String s = recv.readLine();
        while (s != null) {
            System.out.println(s);
            s = recv.readLine();
        }
    } catch (Exception ex) {
    }
    //ModelAndView mav=new ModelAndView();
    String r = validaInterfacesRoles.valida();
    mav.addObject("menu", r);
    mav.addObject("numCT", numTodoscorreosNum);
    mav.addObject("lta", lta);
    mav.setViewName("Inbox");
    return mav;
}

From source file:org.apache.james.postage.result.PostageRunnerResultImpl.java

private void writeMatchedMailResults(OutputStreamWriter outputStreamWriter) throws IOException {
    Map<String, MailProcessingRecord> writeResults = this.matchedMailResults; // keep current results for writing
    this.matchedMailResults = initMatchedMailResultContainer(); // establish new map for further unwritten results
    writeMailResults(writeResults, outputStreamWriter);
    outputStreamWriter.flush();
}

From source file:com.zoffcc.applications.aagtl.FieldnotesUploader.java

public String SendPost(String httpURL, String data, String _cookie) throws IOException {
    URL url = new URL(httpURL);
    //URL url = new URL("http://zoff.cc/xx.cgi");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);//from   www. j av a2  s .c o m
    connection.setRequestProperty("Connection", "Keep-Alive");

    //System.out.println("C=" + _cookie);
    connection.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.10) Gecko/20071115 Firefox/2.0.0.10");
    connection.setRequestProperty("Cookie", _cookie);
    connection.connect();

    if (data != "") {
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(data);
        out.flush();
        out.close();
    }

    // Save Cookie
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()),
            HTMLDownloader.default_buffer_size);
    String headerName = null;
    //_cookies.clear();
    if (_cookie == "") {
        for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equalsIgnoreCase("Set-Cookie")) {
                String cookie = connection.getHeaderField(i);
                _cookie += cookie.substring(0, cookie.indexOf(";")) + "; ";
            }
        }
    }

    // Get HTML from Server
    String getData = "";
    String decodedString;
    while ((decodedString = in.readLine()) != null) {
        getData += decodedString + "\n";
    }
    in.close();

    return getData;
}

From source file:com.example.kjpark.smartclass.NoticeTab.java

@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK)
        return;/*from w w w  .  ja  v  a 2s  .c om*/

    switch (requestCode) {
    case BOARD_NOTICE: {
        Log.d(TAG, "BOARD_NOTICE called");
        loadBoards();
        ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() {
            String title = data.getStringExtra("title");

            @Override
            protected Boolean doInBackground(String... params) {
                URL obj = null;
                try {
                    obj = new URL("http://165.194.104.22:5000/send_gcm");
                    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

                    //implement below code if token is send to server
                    con = ConnectServer.getInstance().setHeader(con);

                    con.setDoOutput(true);

                    String parameter = URLEncoder.encode("title", "UTF-8") + "="
                            + URLEncoder.encode(title, "UTF-8");
                    parameter += "&" + URLEncoder.encode("board_type", "UTF-8") + "="
                            + URLEncoder.encode("notice", "UTF-8");

                    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
                    wr.write(parameter);
                    wr.flush();

                    if (con.getResponseCode() == 200) {
                        Log.d(TAG, "---- success ----");
                    } else {
                        Log.d(TAG, "---- failed ----");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Boolean value) {
            }

        });
        ConnectServer.getInstance().execute();

    }
    }
}

From source file:URLEncoder.java

public String encode(String path) {
    int maxBytesPerChar = 10;
    int caseDiff = ('a' - 'A');
    StringBuffer rewrittenPath = new StringBuffer(path.length());
    ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
    OutputStreamWriter writer = null;
    try {/*w w w  .j  a  v  a2  s. c  om*/
        writer = new OutputStreamWriter(buf, "UTF8");
    } catch (Exception e) {
        e.printStackTrace();
        writer = new OutputStreamWriter(buf);
    }

    for (int i = 0; i < path.length(); i++) {
        int c = (int) path.charAt(i);
        if (safeCharacters.get(c)) {
            rewrittenPath.append((char) c);
        } else {
            // convert to external encoding before hex conversion
            try {
                writer.write((char) c);
                writer.flush();
            } catch (IOException e) {
                buf.reset();
                continue;
            }
            byte[] ba = buf.toByteArray();
            for (int j = 0; j < ba.length; j++) {
                // Converting each byte in the buffer
                byte toEncode = ba[j];
                rewrittenPath.append('%');
                int low = (int) (toEncode & 0x0f);
                int high = (int) ((toEncode & 0xf0) >> 4);
                rewrittenPath.append(hexadecimal[high]);
                rewrittenPath.append(hexadecimal[low]);
            }
            buf.reset();
        }
    }
    return rewrittenPath.toString();
}