Example usage for java.io DataOutputStream flush

List of usage examples for java.io DataOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this data output stream.

Usage

From source file:org.jongo.mocks.JongoClient.java

private JongoResponse doRequest(final String url, final String method, final String jsonParameters) {
    JongoResponse response = null;//from w w  w  .  j a v a  2s. c  om

    try {
        HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection();
        con.setRequestMethod(method);
        con.setRequestProperty("Accept", MediaType.APPLICATION_XML);
        con.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);
        con.setRequestProperty("Content-Length", "" + Integer.toString(jsonParameters.getBytes().length));
        con.setDoOutput(true);
        con.setDoInput(true);

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(jsonParameters);
        wr.flush();
        wr.close();

        //            BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream()));

        BufferedReader r = null;
        if (con.getResponseCode() != Response.Status.OK.getStatusCode()
                && con.getResponseCode() != Response.Status.CREATED.getStatusCode()) {
            r = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        } else {
            r = new BufferedReader(new InputStreamReader(con.getInputStream()));
        }

        StringBuilder rawresponse = new StringBuilder();
        String strLine = null;
        while ((strLine = r.readLine()) != null) {
            rawresponse.append(strLine);
            rawresponse.append("\n");
        }

        try {
            response = XmlXstreamTest.successFromXML(rawresponse.toString());
        } catch (Exception e) {
            response = XmlXstreamTest.errorFromXML(rawresponse.toString());
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return response;
}

From source file:mendhak.teamcity.stash.api.StashClient.java

private String PostBuildStatusToStash(String targetURL, String body, String authHeader) {

    HttpURLConnection connection = null;
    try {/*from   w  w w .  j ava  2  s . c  o m*/

        Logger.LogInfo("Sending build status to " + targetURL);
        Logger.LogInfo("With body: " + body);
        Logger.LogInfo("Auth header: " + authHeader);

        connection = GetConnection(targetURL);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        connection.setRequestProperty("Content-Length", String.valueOf(body.getBytes().length));
        connection.setRequestProperty("Authorization", "Basic " + authHeader);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(body);
        wr.flush();
        wr.close();

        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append("\r\n");
        }
        rd.close();
        return response.toString();

    } catch (Exception e) {

        Logger.LogError("Could not send data to Stash. ", e);
    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }

    return null;

}

From source file:be.fedict.eid.idp.protocol.openid.StatelessServerAssociationStore.java

private Association setHandle(Association association) throws AssociationException, IOException,
        NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException {
    ByteArrayOutputStream encodedAssociation = new ByteArrayOutputStream();
    String type = association.getType();
    if (type == Association.TYPE_HMAC_SHA1) {
        encodedAssociation.write(1);// w w w . ja v a 2  s.  c  o m
    } else if (type == Association.TYPE_HMAC_SHA256) {
        encodedAssociation.write(2);
    } else {
        throw new AssociationException("unknown type: " + type);
    }
    SecretKey macKey = association.getMacKey();
    byte[] macKeyBytes = macKey.getEncoded();
    encodedAssociation.write(macKeyBytes);
    Date expiry = association.getExpiry();
    Long time = expiry.getTime();
    DataOutputStream dos = new DataOutputStream(encodedAssociation);
    dos.writeLong(time);
    dos.flush();
    Cipher cipher = Cipher.getInstance(CIPHER_ALGO);
    byte[] iv = new byte[16];
    this.secureRandom.nextBytes(iv);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, this.secretKeySpec, ivParameterSpec);
    byte[] handleValue = cipher.doFinal(encodedAssociation.toByteArray());
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    result.write(iv);
    result.write(handleValue);
    if (null != this.macSecretKeySpec) {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(this.macSecretKeySpec);
        byte[] toBeSigned = result.toByteArray();
        byte[] signature = mac.doFinal(toBeSigned);
        result = new ByteArrayOutputStream();
        result.write(signature);
        result.write(iv);
        result.write(handleValue);
    }
    String handle = Base64.encodeBase64URLSafeString(result.toByteArray());
    this.secureRandom.setSeed(result.toByteArray());
    if (handle.getBytes().length > 255) {
        throw new AssociationException("handle size > 255");
    }
    if (type == Association.TYPE_HMAC_SHA1) {
        return Association.createHmacSha1(handle, macKeyBytes, expiry);
    } else if (type == Association.TYPE_HMAC_SHA256) {
        return Association.createHmacSha256(handle, macKeyBytes, expiry);
    }
    throw new AssociationException("unknown type: " + type);
}

From source file:com.microsoft.speech.tts.OxfordAuthentication.java

private void HttpPost(String AccessTokenUri, String requestDetails) {
    InputStream inSt = null;/*  w w w  .j  a  v a 2 s  .  c om*/
    HttpsURLConnection webRequest = null;

    this.token = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        webRequest.setRequestMethod("POST");

        byte[] bytes = requestDetails.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        // parse the access token from the json format
        String result = strBuffer.toString();
        JSONObject jsonRoot = new JSONObject(result);
        this.token = new OxfordAccessToken();

        if (jsonRoot.has("access_token")) {
            this.token.access_token = jsonRoot.getString("access_token");
        }

        if (jsonRoot.has("token_type")) {
            this.token.token_type = jsonRoot.getString("token_type");
        }

        if (jsonRoot.has("expires_in")) {
            this.token.expires_in = jsonRoot.getString("expires_in");
        }

        if (jsonRoot.has("scope")) {
            this.token.scope = jsonRoot.getString("scope");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:com.microsoft.valda.oms.OmsAppender.java

private void sendLog(LoggingEvent event)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, HTTPException {
    //create JSON message
    JSONObject obj = new JSONObject();
    obj.put("LOGBACKLoggerName", event.getLoggerName());
    obj.put("LOGBACKLogLevel", event.getLevel().toString());
    obj.put("LOGBACKMessage", event.getFormattedMessage());
    obj.put("LOGBACKThread", event.getThreadName());
    if (event.getCallerData() != null && event.getCallerData().length > 0) {
        obj.put("LOGBACKCallerData", event.getCallerData()[0].toString());
    } else {//from  w  w w.  j  av a  2  s .com
        obj.put("LOGBACKCallerData", "");
    }
    if (event.getThrowableProxy() != null) {
        obj.put("LOGBACKStackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
    } else {
        obj.put("LOGBACKStackTrace", "");
    }
    if (inetAddress != null) {
        obj.put("LOGBACKIPAddress", inetAddress.getHostAddress());
    } else {
        obj.put("LOGBACKIPAddress", "0.0.0.0");
    }
    String json = obj.toJSONString();

    String Signature = "";
    String encodedHash = "";
    String url = "";

    // Todays date input for OMS Log Analytics
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String timeNow = dateFormat.format(calendar.getTime());

    // String for signing the key
    String stringToSign = "POST\n" + json.length() + "\napplication/json\nx-ms-date:" + timeNow + "\n/api/logs";
    byte[] decodedBytes = Base64.decodeBase64(sharedKey);
    Mac hasher = Mac.getInstance("HmacSHA256");
    hasher.init(new SecretKeySpec(decodedBytes, "HmacSHA256"));
    byte[] hash = hasher.doFinal(stringToSign.getBytes());

    encodedHash = DatatypeConverter.printBase64Binary(hash);
    Signature = "SharedKey " + customerId + ":" + encodedHash;

    url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";
    URL objUrl = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Log-Type", logType);
    con.setRequestProperty("x-ms-date", timeNow);
    con.setRequestProperty("Authorization", Signature);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(json);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
        throw new HTTPException(responseCode);
    }
}

From source file:edu.uci.ics.hyracks.hdfs.dataflow.DataflowTest.java

/**
 * Start the HDFS cluster and setup the data files
 * //from  w ww . ja  va 2s  .c o  m
 * @throws IOException
 */
private void startHDFS() throws IOException {
    conf.addResource(new Path(PATH_TO_HADOOP_CONF + "/core-site.xml"));
    conf.addResource(new Path(PATH_TO_HADOOP_CONF + "/mapred-site.xml"));
    conf.addResource(new Path(PATH_TO_HADOOP_CONF + "/hdfs-site.xml"));

    FileSystem lfs = FileSystem.getLocal(new Configuration());
    lfs.delete(new Path("build"), true);
    System.setProperty("hadoop.log.dir", "logs");
    dfsCluster = new MiniDFSCluster(conf, numberOfNC, true, null);
    FileSystem dfs = FileSystem.get(conf);
    Path src = new Path(DATA_PATH);
    Path dest = new Path(HDFS_INPUT_PATH);
    Path result = new Path(HDFS_OUTPUT_PATH);
    dfs.mkdirs(dest);
    dfs.mkdirs(result);
    dfs.copyFromLocalFile(src, dest);

    DataOutputStream confOutput = new DataOutputStream(new FileOutputStream(new File(HADOOP_CONF_PATH)));
    conf.writeXml(confOutput);
    confOutput.flush();
    confOutput.close();
}

From source file:admincommands.Unishell.java

@Override
public void executeCommand(Player admin, String[] params) {
    if (admin.getAccessLevel() < 3) {
        PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
        return;// www . j av a 2 s. c o m
    }

    if (params.length < 2) {
        PacketSendUtility.sendMessage(admin, "Syntax: //unishell <useradd|show> <values...>");
        PacketSendUtility.sendMessage(admin, "//unishell useradd username password");
        PacketSendUtility.sendMessage(admin, "//unishell show users");
        return;
    }

    if (params[0].equals("adduser")) {
        if (params.length < 3) {
            PacketSendUtility.sendMessage(admin, "Syntax; //unishell useradd username password");
            return;
        }

        String username = params[1];
        String password = params[2];
        String hashedPassword = CryptoHelper.encodeSHA1(password);

        Map<String, String> actualAuthorizedKeys = AuthorizedKeys.loadAuthorizedKeys();
        Iterator<Entry<String, String>> actualAuthorizedEntries = actualAuthorizedKeys.entrySet().iterator();
        boolean checkResult = false;
        while (actualAuthorizedEntries.hasNext()) {
            if (username.equals(actualAuthorizedEntries.next().getKey())) {
                checkResult = true;
            }
        }

        if (checkResult) {
            PacketSendUtility.sendMessage(admin, "Error: username already exists.");
            return;
        }

        try {
            FileOutputStream file = new FileOutputStream("./config/network/unishell.passwd", true);
            DataOutputStream out = new DataOutputStream(file);
            out.writeBytes(username + ":" + hashedPassword + "\n");
            out.flush();
            out.close();
            PacketSendUtility.sendMessage(admin, "Unishell user '" + username + "' successfully added !");
            return;
        } catch (FileNotFoundException fnfe) {
            log.error("Cannot open unishell password file for writing at ./config/network/unishell.passwd",
                    fnfe);
            PacketSendUtility.sendMessage(admin, "Error: cannot open password file.");
            return;
        } catch (IOException ioe) {
            log.error("Cannot write to unishell password file for writing at ./config/network/unishell.passwd",
                    ioe);
            PacketSendUtility.sendMessage(admin, "Error: cannot write to password file.");
            return;
        }

    } else if (params[0].equals("show")) {
        if (params.length < 2) {
            PacketSendUtility.sendMessage(admin, "Syntax: //unishell show users");
            return;
        }

        if (params[1].equals("users")) {
            Iterator<Entry<String, String>> authorizedKeys = AuthorizedKeys.loadAuthorizedKeys().entrySet()
                    .iterator();
            while (authorizedKeys.hasNext()) {
                Entry<String, String> current = authorizedKeys.next();
                PacketSendUtility.sendMessage(admin,
                        "user: " + current.getKey() + " | password: " + current.getValue());
            }
        }

    } else {
        PacketSendUtility.sendMessage(admin, "Syntax: //unishell <useradd|> <values...>");
        PacketSendUtility.sendMessage(admin, "//unishell useradd username password");
        return;
    }

}

From source file:com.cbagroup.sit.CreditTransfer.java

public String sendPOST() throws IOException, NoSuchAlgorithmException {
    String key = "api_key=cbatest123";
    //String url = "http://developer.cbagroup.com/api/CreditTransfer?api_key=cbatest123";
    String url = "http://developer.cbagroup.com/api/CreditTransfer?" + key;
    URL object = new URL(url);
    HttpURLConnection con = (HttpURLConnection) object.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    //con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept", "application/json");

    String urlParameters = "BankCode=Kenya&" + "BranchCode=COMBAPI&" + "Country=COMBAPI&"
            + "TranType=CreditTransfer&" + "Reference=Impalapay&" + "Currency=10.25&" + "Account=pay&"
            + "Amount=10.22&" + "Narration=payment&" + "Transaction Date=1.2.2017&";

    // Send post request
    con.setDoOutput(true);/*  ww w .  j  av  a2s  . co  m*/
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }

    in.close();

    //print result
    System.out.println(response.toString());

    //////////start  ////////////////////
    String result = response.toString();

    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(result);

        JSONObject jsonObject = (JSONObject) obj;
        //System.out.println(jsonObject);

        long ResCode = (long) jsonObject.get("Response Code");
        System.out.println();
        System.out.println("Response Code : " + ResCode);
        System.out.println();

        if (ResCode == 1) {

            System.out.println("#########################################################");
            System.out.println("Fred hack Fail");
            System.out.println();

            long ResCode1 = (long) jsonObject.get("Response Code");
            System.out.println();
            System.out.println("Response Code : " + ResCode1);
            System.out.println();

            String Ref = (String) jsonObject.get("Reference");
            System.out.println();
            System.out.println("Reference : " + Ref);
            System.out.println();

            String Des = (String) jsonObject.get("Description");
            System.out.println();
            System.out.println("Description : " + Des);
            System.out.println();

        } else {

            System.out.println("#########################################################");
            System.out.println("Fred hack Success");
            System.out.println();

            long ResCode1 = (long) jsonObject.get("Response Code");
            System.out.println();
            System.out.println("Response Code : " + ResCode1);
            System.out.println();

            String Ref = (String) jsonObject.get("Reference");
            System.out.println();
            System.out.println("Reference : " + Ref);
            System.out.println();

            String Des = (String) jsonObject.get("Description");
            System.out.println();
            System.out.println("Description : " + Des);
            System.out.println();

        }

        //         long age = (Long) jsonObject.get("Description");
        //         System.out.println(age);

        // loop array
        //         JSONArray msg = (JSONArray) jsonObject.get("messages");
        //         Iterator<String> iterator = msg.iterator();
        //         while (iterator.hasNext()) {
        //             System.out.println(iterator.next());
        //}

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return response.toString();
}

From source file:jackwu.com.gasprice.GCMService.RegistrationIntentService.java

/**
 * Persist registration to third-party servers.
 *
 * Modify this method to associate the user's GCM registration token with any server-side account
 * maintained by your application.//www  . j  ava2  s.c o m
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token, String device_id) throws Exception {
    // Add custom implementation, as needed.
    HttpURLConnection urlConnection = null;
    URL url = null;
    String parameter = "device_id=" + device_id;
    String parameter2 = "gcm_regid=" + token;
    try {
        url = new URL(getString(R.string.server_address_register));
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/x-www.form-urlencoded");
        urlConnection.setRequestProperty("Content-Language", "en-US");
        urlConnection.setUseCaches(false);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
        dos.writeBytes(parameter);
        dos.writeBytes(parameter2);
        dos.flush();
        dos.close();

        int responseCode = urlConnection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            if (!response.toString().equals("success")) {
                throw new Exception("not success");
            }
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.cbagroup.sit.Transact.java

public String sendPOST() throws IOException, NoSuchAlgorithmException {

    String key = "api_key=cbatest123";
    //String url = "http://developer.cbagroup.com/api/CreditTransfer?api_key=cbatest123";
    String url = "http://developer.cbagroup.com/api/Transact?" + key;
    URL object = new URL(url);
    HttpURLConnection con = (HttpURLConnection) object.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    //con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept", "application/json");

    String urlParameters = "Country=Kenya&" + "TranType=Transact&" + "Reference=COMBAPI&" + "Currency=kes&"
            + "Account=1.2.2013&" + "Amount=10.25&" + "Narration=pay&" + "TransactionDate=1.2.2013&";

    // Send post request
    con.setDoOutput(true);/*from   w ww.j av  a2 s  . c  o m*/
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }

    in.close();

    //print result
    System.out.println(response.toString());

    ////////// start  ////////////////////
    String result = response.toString();

    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(result);

        JSONObject jsonObject = (JSONObject) obj;
        //System.out.println(jsonObject);

        long ResCode = (long) jsonObject.get("Response Code");
        System.out.println();
        System.out.println("Response Code : " + ResCode);
        System.out.println();

        if (ResCode == 1) {

            System.out.println("#########################################################");
            System.out.println("Fred hack Fail");
            System.out.println();

            long ResCode1 = (long) jsonObject.get("Response Code");
            System.out.println();
            System.out.println("Response Code : " + ResCode1);
            System.out.println();

            String Ref = (String) jsonObject.get("Reference");
            System.out.println();
            System.out.println("Reference : " + Ref);
            System.out.println();

            String Des = (String) jsonObject.get("Description");
            System.out.println();
            System.out.println("Description : " + Des);
            System.out.println();

        } else {

            System.out.println("#########################################################");
            System.out.println("Fred hack Success");
            System.out.println();

            long ResCode1 = (long) jsonObject.get("Response Code");
            System.out.println();
            System.out.println("Response Code : " + ResCode1);
            System.out.println();

            String Ref = (String) jsonObject.get("Reference");
            System.out.println();
            System.out.println("Reference : " + Ref);
            System.out.println();

            String Des = (String) jsonObject.get("Description");
            System.out.println();
            System.out.println("Description : " + Des);
            System.out.println();

        }

        //            long age = (Long) jsonObject.get("Description");
        //            System.out.println(age);

        // loop array
        //            JSONArray msg = (JSONArray) jsonObject.get("messages");
        //            Iterator<String> iterator = msg.iterator();
        //            while (iterator.hasNext()) {
        //                System.out.println(iterator.next());
        //}

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return response.toString();
}