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:Main.java

public static String RunExecCmd(StringBuilder sb, Boolean su) {

    String shell;// w w  w  . j av  a2 s  . c  om
    if (su) {
        shell = "su";
    } else {
        shell = "sh";
    }

    Process process = null;

    DataOutputStream processOutput = null;
    InputStream processInput = null;
    String outmsg = new String();

    try {

        process = Runtime.getRuntime().exec(shell);
        processOutput = new DataOutputStream(process.getOutputStream());
        processOutput.writeBytes(sb.toString() + "\n");
        processOutput.writeBytes("exit\n");
        processOutput.flush();
        processInput = process.getInputStream();
        outmsg = inputStream2String(processInput, "UTF-8");
        process.waitFor();

    } catch (Exception e) {
        //Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
        //return;
    }

    finally {
        try {
            if (processOutput != null) {
                processOutput.close();
            }
            process.destroy();
        } catch (Exception e) {
        }

    }
    return outmsg;
}

From source file:gov.nasa.arc.geocam.geocam.HttpPost.java

public static int post(String url, Map<String, String> vars, String fileKey, String fileName,
        InputStream istream, String username, String password) throws IOException {
    HttpURLConnection conn = createConnection(url, username, password);

    try {//from w w  w  .  j ava 2  s. c o  m
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        Log.d("HttpPost", vars.toString());

        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        assembleMultipart(out, vars, fileKey, fileName, istream);
        istream.close();
        out.flush();

        InputStream in = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in), 2048);

        // Set postedSuccess to true if there is a line in the HTTP response in
        // the form "GEOCAM_SHARE_POSTED <file>" where <file> equals fileName.
        // Our old success condition was just checking for HTTP return code 200; turns
        // out that sometimes gives false positives.
        Boolean postedSuccess = false;
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            //Log.d("HttpPost", line);
            if (!postedSuccess && line.contains("GEOCAM_SHARE_POSTED")) {
                String[] vals = line.trim().split("\\s+");
                for (int i = 0; i < vals.length; ++i) {
                    //String filePosted = vals[1];
                    if (vals[i].equals(fileName)) {
                        Log.d(GeoCamMobile.DEBUG_ID, line);
                        postedSuccess = true;
                        break;
                    }
                }
            }
        }
        out.close();

        int responseCode = 0;
        responseCode = conn.getResponseCode();
        if (responseCode == 200 && !postedSuccess) {
            // our code for when we got value 200 but no confirmation
            responseCode = -3;
        }
        return responseCode;
    } catch (UnsupportedEncodingException e) {
        throw new IOException("HttpPost - Encoding exception: " + e);
    }

    // ??? when would this ever be thrown?
    catch (IllegalStateException e) {
        throw new IOException("HttpPost - IllegalState: " + e);
    }

    catch (IOException e) {
        try {
            return conn.getResponseCode();
        } catch (IOException f) {
            throw new IOException("HttpPost - IOException: " + e);
        }
    }
}

From source file:Main.java

public static String uploadFile(String filePath, String requestURL) {

    String result = "";
    File file = new File(filePath);

    try {/* ww  w .j a  v a  2  s  . co  m*/
        HttpURLConnection connection = initHttpURLConn(requestURL);

        if (filePath != null) {
            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            StringBuffer sb = new StringBuffer();
            InputStream is = new FileInputStream(filePath);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            dos.flush();
            is.close();
            int res = connection.getResponseCode();
            Log.e(TAG, "response code:" + res);
            if (res == 200) {
                Log.e(TAG, "request success");
                InputStream input = connection.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }

                result = sb1.toString();
                Log.d(TAG, "result: " + result);

                input.close();
            }
        }

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

    return result;

}

From source file:Main.java

public static BufferedReader shellExecute(String[] commands, boolean requireRoot) {
    Process shell = null;// www .  j  ava2  s. com
    DataOutputStream out = null;
    BufferedReader reader = null;
    String startCommand = requireRoot ? "su" : "sh";
    try {
        shell = Runtime.getRuntime().exec(startCommand);
        out = new DataOutputStream(shell.getOutputStream());
        reader = new BufferedReader(new InputStreamReader(shell.getInputStream()));
        for (String command : commands) {
            out.writeBytes(command + "\n");
            out.flush();
        }
        out.writeBytes("exit\n");
        out.flush();
        shell.waitFor();
    } catch (Exception e) {
        Log.e(TAG, "ShellRoot#shExecute() finished with error", e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {

        }
    }
    return reader;
}

From source file:io.lavagna.model.ProjectMetadata.java

private static String hash(SortedMap<Integer, CardLabel> labels,
        SortedMap<Integer, LabelListValueWithMetadata> labelListValues,
        Map<ColumnDefinition, BoardColumnDefinition> columnsDefinition) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream daos = new DataOutputStream(baos);

    try {/*from w w w . j  a  v  a 2s.c om*/

        for (CardLabel cl : labels.values()) {
            hash(daos, cl);
        }

        for (LabelListValueWithMetadata l : labelListValues.values()) {
            hash(daos, l);
        }

        for (BoardColumnDefinition b : columnsDefinition.values()) {
            hash(daos, b);
        }

        daos.flush();
        return DigestUtils.sha256Hex(new ByteArrayInputStream(baos.toByteArray()));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.dbay.apns4j.tools.ApnsTools.java

@Deprecated
public final static byte[] generateData(int id, int expire, byte[] token, byte[] payload) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream os = new DataOutputStream(bos);
    try {//from  w  w w  . ja  v  a2  s . c  om
        os.writeByte(Command.SEND);
        os.writeInt(id);
        os.writeInt(expire);
        os.writeShort(token.length);
        os.write(token);
        os.writeShort(payload.length);
        os.write(payload);
        os.flush();
        return bos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new RuntimeException();
}

From source file:com.microsoft.office365.msgraphsnippetapp.SnippetsUnitTests.java

@BeforeClass
public static void getAccessTokenUsingPasswordGrant()
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException {
    URL url = new URL(TOKEN_ENDPOINT);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    String urlParameters = String.format(
            "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s", GRANT_TYPE,
            URLEncoder.encode(ServiceConstants.AUTHENTICATION_RESOURCE_ID, "UTF-8"), clientId, username,
            password);/*from ww  w  . j a va 2  s. c o m*/

    connection.setRequestMethod(REQUEST_METHOD);
    connection.setRequestProperty("Content-Type", CONTENT_TYPE);
    connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length));

    connection.setDoOutput(true);
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes(urlParameters);
    dataOutputStream.flush();
    dataOutputStream.close();

    connection.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();

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

    JsonParser jsonParser = new JsonParser();
    JsonObject grantResponse = (JsonObject) jsonParser.parse(response.toString());
    accessToken = grantResponse.get("access_token").getAsString();

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            request = request.newBuilder().addHeader("Authorization", "Bearer " + accessToken)
                    // This header has been added to identify this sample in the Microsoft Graph service.
                    // If you're using this code for your project please remove the following line.
                    .addHeader("SampleID", "android-java-snippets-rest-sample").build();

            return chain.proceed(request);
        }
    }).addInterceptor(logging).build();

    Retrofit retrofit = new Retrofit.Builder().baseUrl(ServiceConstants.AUTHENTICATION_RESOURCE_ID)
            .client(client).addConverterFactory(GsonConverterFactory.create()).build();

    contactService = retrofit.create(MSGraphContactService.class);
    drivesService = retrofit.create(MSGraphDrivesService.class);
    eventsService = retrofit.create(MSGraphEventsService.class);
    groupsService = retrofit.create(MSGraphGroupsService.class);
    mailService = retrofit.create(MSGraphMailService.class);
    meService = retrofit.create(MSGraphMeService.class);
    userService = retrofit.create(MSGraphUserService.class);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.US);
    dateTime = simpleDateFormat.format(new Date());
}

From source file:Main.java

public static void post(String actionUrl, String file) {
    try {//  w w w.  j  a v a 2  s. co m
        URL url = new URL(actionUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****");
        DataOutputStream ds = new DataOutputStream(con.getOutputStream());
        FileInputStream fStream = new FileInputStream(file);
        int bufferSize = 1024; // 1MB
        byte[] buffer = new byte[bufferSize];
        int bufferLength = 0;
        int length;
        while ((length = fStream.read(buffer)) != -1) {
            bufferLength = bufferLength + 1;
            ds.write(buffer, 0, length);
        }
        fStream.close();
        ds.flush();
        InputStream is = con.getInputStream();
        int ch;
        StringBuilder b = new StringBuilder();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        new String(b.toString().getBytes("ISO-8859-1"), "utf-8");
        ds.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:fr.zcraft.zbanque.network.PacketSender.java

private static HTTPResponse makeRequest(String url, PacketPlayOut.PacketType method, String data)
        throws Throwable {
    // ***  REQUEST  ***

    final URL urlObj = new URL(url);
    final HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();

    connection.setRequestMethod(method.name());
    connection.setRequestProperty("User-Agent", USER_AGENT);

    authenticateRequest(connection);/* www . j a v a  2 s.  c om*/

    connection.setDoOutput(true);

    try {
        try {
            connection.connect();
        } catch (IOException ignored) {
        }

        if (method == PacketPlayOut.PacketType.POST) {
            DataOutputStream out = null;
            try {
                out = new DataOutputStream(connection.getOutputStream());
                if (data != null)
                    out.writeBytes(data);
                out.flush();
            } finally {
                if (out != null)
                    out.close();
            }
        }

        // ***  RESPONSE  ***

        int responseCode;
        boolean failed = false;

        try {
            responseCode = connection.getResponseCode();
        } catch (IOException e) {
            // HttpUrlConnection will throw an IOException if any 4XX
            // response is sent. If we request the status again, this
            // time the internal status will be properly set, and we'll be
            // able to retrieve it.
            // Thanks to Iigo.
            responseCode = connection.getResponseCode();
            failed = true;
        }

        BufferedReader in = null;
        String body = "";
        try {
            InputStream stream;
            try {
                stream = connection.getInputStream();
            } catch (IOException e) {
                // Same as before
                stream = connection.getErrorStream();
                failed = true;
            }

            in = new BufferedReader(new InputStreamReader(stream));
            StringBuilder responseBuilder = new StringBuilder();

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

            body = responseBuilder.toString();
        } finally {
            if (in != null)
                in.close();
        }

        HTTPResponse response = new HTTPResponse();
        response.setResponseCode(responseCode, failed);
        response.setResponseBody(body);

        int i = 0;
        String headerName, headerContent;
        while ((headerName = connection.getHeaderFieldKey(i)) != null) {
            headerContent = connection.getHeaderField(i);
            response.addHeader(headerName, headerContent);
        }

        // ***  REDIRECTION  ***

        switch (responseCode) {
        case 301:
        case 302:
        case 307:
        case 308:
            if (response.getHeaders().containsKey("Location")) {
                response = makeRequest(response.getHeaders().get("Location"), method, data);
            }
        }

        // ***  END  ***

        return response;
    } finally {
        connection.disconnect();
    }
}

From source file:BihuHttpUtil.java

public static String doHttpPost(String xmlInfo, String URL) {
    System.out.println("??:" + xmlInfo);
    byte[] xmlData = xmlInfo.getBytes();
    InputStream instr = null;/*from  w  w w . j  a  va 2 s  . c  om*/
    java.io.ByteArrayOutputStream out = null;
    try {
        URL url = new URL(URL);
        URLConnection urlCon = url.openConnection();
        urlCon.setDoOutput(true);
        urlCon.setDoInput(true);
        urlCon.setUseCaches(false);
        urlCon.setRequestProperty("Content-Type", "text/xml");
        urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
        System.out.println(String.valueOf(xmlData.length));
        DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
        printout.write(xmlData);
        printout.flush();
        printout.close();
        instr = urlCon.getInputStream();
        byte[] bis = IOUtils.toByteArray(instr);
        String ResponseString = new String(bis, "UTF-8");
        if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
            System.out.println("");
        }
        System.out.println("?:" + ResponseString);
        return ResponseString;

    } catch (Exception e) {
        e.printStackTrace();
        return "0";
    } finally {
        try {
            out.close();
            instr.close();
        } catch (Exception ex) {
            return "0";
        }
    }
}