Example usage for java.io DataOutputStream DataOutputStream

List of usage examples for java.io DataOutputStream DataOutputStream

Introduction

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

Prototype

public DataOutputStream(OutputStream out) 

Source Link

Document

Creates a new data output stream to write data to the specified underlying output stream.

Usage

From source file:info.fetter.logstashforwarder.protocol.LumberjackClient.java

public LumberjackClient(String keyStorePath, String server, int port, int timeout) throws IOException {
    this.server = server;
    this.port = port;

    try {/*w ww  . j  a v a 2 s . c om*/
        if (keyStorePath == null) {
            throw new IOException("Key store not configured");
        }
        if (server == null) {
            throw new IOException("Server address not configured");
        }

        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(keyStorePath), null);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(keyStore);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        SSLSocketFactory socketFactory = context.getSocketFactory();
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(server), port), timeout);
        socket.setSoTimeout(timeout);
        sslSocket = (SSLSocket) socketFactory.createSocket(socket, server, port, true);
        sslSocket.setUseClientMode(true);
        sslSocket.startHandshake();

        output = new DataOutputStream(new BufferedOutputStream(sslSocket.getOutputStream()));
        input = new DataInputStream(sslSocket.getInputStream());

        logger.info("Connected to " + server + ":" + port);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.reactivetechnologies.jaxrs.RestServerTest.java

static String sendPost(String url, String content) throws IOException {

    StringBuilder response = new StringBuilder();
    HttpURLConnection con = null;
    BufferedReader in = null;//from   w w w  .  j a  v  a2s .  c  om
    try {
        URL obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("POST");

        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeUTF(content);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } else {
            throw new IOException("Response Code: " + responseCode);
        }

        return response.toString();
    } catch (IOException e) {
        throw e;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {

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

}

From source file:eu.crushedpixel.littlstar.api.upload.S3Uploader.java

/**
 * Executes a multipart form upload to the S3 Bucket as described in
 * <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTExamples.html">the AWS Documentation</a>.
 * @param s3UploadProgressListener An S3UploadProgressListener which is called whenever
 *                               bytes are written to the outgoing connection. May be null.
 * @throws IOException in case of a problem or the connection was aborted
 * @throws ClientProtocolException in case of an http protocol error
 *//*ww w .  j av a  2s  . co m*/
public void uploadFileToS3(S3UploadProgressListener s3UploadProgressListener)
        throws IOException, ClientProtocolException {
    //unfortunately, we can't use Unirest to execute the call, because there is no support
    //for Progress listeners (yet). See https://github.com/Mashape/unirest-java/issues/26

    int bufferSize = 1024;

    //opening a connection to the S3 Bucket
    HttpURLConnection urlConnection = (HttpURLConnection) new URL(s3_bucket).openConnection();
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setChunkedStreamingMode(bufferSize);
    urlConnection.setRequestProperty("Connection", "Keep-Alive");
    urlConnection.setRequestProperty("Cache-Control", "no-cache");
    String boundary = "*****";
    urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    //writing the request headers
    DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());

    String newline = "\r\n";
    String twoHyphens = "--";
    dos.writeBytes(twoHyphens + boundary + newline);

    String attachmentName = "file";
    String attachmentFileName = "file";

    dos.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\""
            + attachmentFileName + "\"" + newline);
    dos.writeBytes(newline);

    //sending the actual file
    byte[] buf = new byte[bufferSize];

    FileInputStream fis = new FileInputStream(file);
    long totalBytes = fis.getChannel().size();
    long writtenBytes = 0;

    int len;
    while ((len = fis.read(buf)) != -1) {
        dos.write(buf);
        writtenBytes += len;

        s3UploadProgressListener.onProgressUpdated(new S3UpdateProgressEvent(writtenBytes, totalBytes,
                (float) ((double) writtenBytes / totalBytes)));

        if (interrupt) {
            fis.close();
            dos.close();
            return;
        }
    }

    fis.close();

    //finish the call
    dos.writeBytes(newline);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + newline);

    dos.close();

    urlConnection.disconnect();
}

From source file:com.linkedin.cubert.io.text.TextTeeWriter.java

@Override
public void open(Configuration conf, JsonNode json, BlockSchema schema, Path root, String filename)
        throws IOException {

    String separator = "\t";
    if (json.has("params") && !json.get("params").isNull() && json.get("params").has("separator")) {
        separator = JsonUtils.getText(json.get("params"), "separator");
    }// w w  w . j  a v a  2  s  . co  m

    separator = StringEscapeUtils.unescapeJava(separator);
    byte[] bytes = separator.getBytes("UTF-8");

    if (bytes.length > 1) {
        throw new RuntimeException(String.format("Invalid separator in text output format %s", separator));
    }

    final TaskAttemptContext context = PhaseContext.isMapper() ? PhaseContext.getMapContext()
            : PhaseContext.getRedContext();

    String extension = "";
    CompressionCodec codec = null;
    final boolean isCompressed = FileOutputFormat.getCompressOutput(context);
    if (isCompressed) {
        Class<? extends CompressionCodec> codecClass = FileOutputFormat.getOutputCompressorClass(context,
                GzipCodec.class);

        codec = ReflectionUtils.newInstance(codecClass, conf);
        extension = codec.getDefaultExtension();
    }

    out = FileSystem.get(conf).create(new Path(root, filename + extension));
    if (isCompressed) {
        out = new DataOutputStream(codec.createOutputStream(out));
    }

    delegate = new Delegate(out, bytes[0]);
}

From source file:au.org.ala.spatial.util.RecordsSmall.java

private void makeSmallFile(String filename) throws Exception {
    FileWriter outputSpecies = new FileWriter(filename + "records.csv.small.species");
    DataOutputStream outputPoints = new DataOutputStream(
            new BufferedOutputStream(new FileOutputStream(filename + "records.csv.small.points")));
    DataOutputStream outputPointsToSpecies = new DataOutputStream(
            new BufferedOutputStream(new FileOutputStream(filename + "records.csv.small.pointsToSpecies")));

    Map<String, Integer> lsidMap = new HashMap<String, Integer>(200000);
    byte start = 0;
    BufferedReader br = new BufferedReader(new FileReader(filename + "records.csv"));
    int[] header = new int[3];
    int row = start;
    int currentCount = 0;
    String[] line = new String[3];

    String rawline;//from   w w  w .  ja  va2 s.c  o m
    while ((rawline = br.readLine()) != null) {
        currentCount++;
        int p1 = rawline.indexOf(44);
        int p2 = rawline.indexOf(44, p1 + 1);
        if (p1 >= 0 && p2 >= 0) {
            line[0] = rawline.substring(0, p1);
            line[1] = rawline.substring(p1 + 1, p2);
            line[2] = rawline.substring(p2 + 1, rawline.length());
            if (currentCount % 100000 == 0) {
                System.out.print("\rreading row: " + currentCount);
            }

            if (row == 0) {
                for (int e = 0; e < line.length; e++) {
                    if (line[e].equals("names_and_lsid")) {
                        header[0] = e;
                    }

                    if (line[e].equals("longitude")) {
                        header[1] = e;
                    }

                    if (line[e].equals("latitude")) {
                        header[2] = e;
                    }
                }

                logger.debug("header: " + header[0] + "," + header[1] + "," + header[2]);
            } else if (line.length >= 3) {
                try {
                    double lat = Double.parseDouble(line[header[2]]);
                    double lng = Double.parseDouble(line[header[1]]);

                    String species = line[header[0]];

                    Integer idx = lsidMap.get(species);
                    if (idx == null) {
                        idx = lsidMap.size();
                        lsidMap.put(species, idx);

                        outputSpecies.write(species);
                        outputSpecies.write("\n");
                    }

                    outputPoints.writeDouble(lat);
                    outputPoints.writeDouble(lng);

                    outputPointsToSpecies.writeInt(idx);
                } catch (Exception e) {
                    logger.error("failed to read records.csv row: " + row, e);
                }
            }

            row++;
        }
    }

    br.close();

    outputPointsToSpecies.flush();
    outputPointsToSpecies.close();
    outputPoints.flush();
    outputPoints.close();
    outputSpecies.flush();
    outputSpecies.close();

    FileUtils.writeStringToFile(new File(filename + "records.csv.small.speciesCount"),
            String.valueOf(lsidMap.size()));
}

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 w ww. j  a  v  a2s. com*/

    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:com.cisco.gerrit.plugins.slack.client.WebhookClient.java

/**
 * Initiates an HTTP POST to the provided Webhook URL.
 *
 * @param message The message payload.//from   w ww .j ava2 s.c o  m
 * @param webhookUrl The URL to post to.
 * @return The response payload from Slack.
 */
private String postRequest(String message, String webhookUrl) {
    String response;

    HttpURLConnection connection;
    connection = null;
    try {
        connection = openConnection(webhookUrl);
        try {
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");

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

            DataOutputStream request;
            request = new DataOutputStream(connection.getOutputStream());

            request.write(message.getBytes(StandardCharsets.UTF_8));
            request.flush();
            request.close();
        } catch (IOException e) {
            throw new RuntimeException("Error posting message to Slack: [" + e.getMessage() + "].", e);
        }

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

    return response;
}

From source file:com.eTilbudsavis.etasdk.network.impl.HttpURLNetwork.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException {
    byte[] body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);//  w  w w.  j  a v a2  s  .c o  m
        connection.addRequestProperty(HeaderUtils.CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}

From source file:com.skubit.bitid.loaders.SignInAsyncTaskLoader.java

private void writeRequest(String message) throws IOException {
    DataOutputStream dos = new DataOutputStream(mConnection.getOutputStream());
    dos.write(message.getBytes());/*from   w  w w.j  a v a 2 s. co  m*/
    dos.close();
}

From source file:lk.appzone.client.MchoiceAventuraSmsSender.java

private void sendRequest(String urlParameters, HttpURLConnection connection) throws IOException {

    if (logger.isDebugEnabled()) {
        logger.debug("sending the request: " + urlParameters);
    }/*w w  w  .  j av  a2  s .  c o m*/
    //Send request
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
}