In Java the BufferedReader can’t read the InputStream without adapter. For this raison we need to use an adapter like InputStreamReader to convert bytes to characters format. For example:

// BufferedReader -> InputStreamReader -> InputStream
  BufferedReader br = new BufferedReader(
                          new InputStreamReader(inputStream, StandardCharsets.UTF_8));

1. Reads a file from the resources folder

This example read a file from the resources folder as InputStream; and we can use BufferedReader + InputStreamReader to read it line by line.

InputStreamToReaderExample.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class InputStreamToReaderExample {

    public static void main(String[] args) throws IOException {

        // loads a file from a resources folder
        InputStream is = InputStreamToReaderExample.class
                            .getClassLoader()
                            .getResourceAsStream("file/abc.txt");

        // BufferedReader -> InputStreamReader -> InputStream

        // try-with-resources, auto close
        String line;
        try (BufferedReader br = new BufferedReader(
                      new InputStreamReader(is, StandardCharsets.UTF_8))) {

            // read line by line
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

        }

    }
}

2. Send an Http post request to Cloudflare endpoints.

This example uses Apache HttpClient to send a POST request to the Cloudflare endpoints to block an IP address. The return is a JSON string in InputStream, and we can use the same BufferedReader + InputStreamReader to reads the bytes stream.

Pom.xml

 <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
  </dependency>

CloudFlareBanIP.java

import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

public class CloudFlareBanIP {

    private static final String CF_AUTH_EMAIL = PropertyUtils.getInstance().getValue("cf_auth_email");
    private static final String CF_AUTH_TOKEN = PropertyUtils.getInstance().getValue("cf_auth_token");
    private static final String JSON_TYPE = "application/json";
    private static Header[] HTTP_HEADERS = {
            new BasicHeader("X-Auth-Email", CF_AUTH_EMAIL),
            new BasicHeader("X-Auth-Key", CF_AUTH_TOKEN),
            new BasicHeader("content-type", JSON_TYPE)
    };

    private HttpClient httpClient = HttpClientBuilder.create()
            .setConnectionTimeToLive(10, TimeUnit.SECONDS)
            .build();

    public HttpClient getHttpClient() {
        return httpClient;
    }

    public static void main(String[] args) throws IOException {

        CloudFlareBanIP obj = new CloudFlareBanIP();
        String response = obj.banIp("52.249.189.81", "bad ip");

        System.out.println(response);

    }

    public String banIp(String ip, String note) throws IOException {

        StringBuilder json = new StringBuilder();
        json.append("{");
        json.append("\"mode\":\"block\",");
        json.append("\"configuration\":" + "{\"target\":\"ip\",\"value\":\"" + ip + "\"}" + ",");
        json.append("\"notes\":\"" + note + "\"");
        json.append("}");

        StringBuilder result = new StringBuilder();

        HttpPost post = new HttpPost("https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules");
        post.setHeaders(HTTP_HEADERS);
        post.setEntity(new StringEntity(json.toString()));

        // read response from the POST request
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(getHttpClient().execute(post).getEntity().getContent()))) {
            String line;
            while ((line = br.readLine()) != null) {
                result.append(line);
            }
        }

        return result.toString();

    }

}

Laisser un commentaire