Saturday, December 24, 2016

An useful util to handle nested collection in Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
 
public class CommonUtil {
 
    public static <K, V, O extends V> V getAndCreateIfNotExist(K key, Map<K, V> map, Class<O> c) {
        V result = map.get(key);
        if (result == null) {
            synchronized (map) {
                result = map.get(key);
                if (result == null) {
                    try {
                        result = c.newInstance();
                    } catch (Exception e) {
                        throw new RuntimeException("Error in getAndCreateIfNotExist", e);
                    }
 
                    map.put(key, result);
                }
            }
        }
        return result;
    }
    // Test
    public static void main(String[] args) {
        Map<String, Set<String>> phoneNumbersPerName = new HashMap<>();
        String personName = "Alex";
        Set<String> phoneNumbers = getAndCreateIfNotExist(personName, phoneNumbersPerName, HashSet.class);
        phoneNumbers.add("01234567891");
        phoneNumbers.add("09090909090");
        System.out.println(phoneNumbersPerName);
        // {Alex=[09090909090, 01234567891]}
    }
}

An useful util to separate a list to multiple sublist in Java

Assume that you need to group/separate a List of object to multiple sublist with an specified size, below use should be useful.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.LinkedList;
import java.util.List;
 
public class CommonUtil {
    public static <T> List<List<T>> group(List<T> input, int bulkSize) {
        List<List<T>> result = new LinkedList<>();
        int from = 0;
        int to = bulkSize;
        int size = input.size();
 
        while (to < size) {
            result.add(input.subList(from, to));
            from = to;
            to += bulkSize;
        }
 
        if (from < size) {
            result.add(input.subList(from, size));
        }
        return result;
    }
 
}

Saturday, December 17, 2016

Java Send HTTP POST Request with x-www-form-urlencoded Format

The key thing is that we need to use the util URLEncoder to encode parameter name and its value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
 
public class HttpRequestSender {
    public static int requestSender(String url, Map<String, Object> params, int connectionTimeout, int readTimeout, StringBuilder response) throws IOException {
        int responseCode = 0;
        if (params != null) {
            StringBuilder postData = new StringBuilder();
            String paramSeparator = "";
            for (Entry<String, Object> entry : params.entrySet()) {
                postData.append(paramSeparator);
                postData.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
                paramSeparator = "&";
            }
            byte[] postDataBytes = postData.toString().getBytes("UTF-8");
            URL urlObj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
            conn.setRequestMethod("POST");
            conn.setInstanceFollowRedirects(false);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("charset", "UTF-8");
            conn.setRequestProperty("content-length", String.valueOf(postDataBytes.length));
            conn.setDoOutput(true);
            conn.setConnectTimeout(connectionTimeout);
            conn.setReadTimeout(readTimeout);
            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.write(postDataBytes);
                wr.flush();
            }
            responseCode = conn.getResponseCode();
            if (response != null) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                    String line = reader.readLine();
                    while (line != null) {
                        response.append(line);
                        line = reader.readLine();
                    }
                }
            }
        }
        return responseCode;
    }
}