<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by chiang-sh on Medium]]></title>
        <description><![CDATA[Stories by chiang-sh on Medium]]></description>
        <link>https://medium.com/@chiang-sh?source=rss-c52d9577a762------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*03AiqwMM2Yos-XtuUHSW8A.png</url>
            <title>Stories by chiang-sh on Medium</title>
            <link>https://medium.com/@chiang-sh?source=rss-c52d9577a762------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:42:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chiang-sh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[LeetCode Notes #42: Trapping Rain Water]]></title>
            <link>https://medium.com/@chiang-sh/leetcode-notes-42-trapping-rain-water-035aa96a49b5?source=rss-c52d9577a762------2</link>
            <guid isPermaLink="false">https://medium.com/p/035aa96a49b5</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[chiang-sh]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 15:39:47 GMT</pubDate>
            <atom:updated>2026-08-24T15:46:25.651Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*oLVyUXno0uhUATSv5yhgvg.png" /></figure><p>By observing the picture from the leftmost bar to the rightmost, we can see that if there is a bar on the right side that is equal to or taller than the current highest bar, the amount of trapped rain is the difference in height. I use a temp variable to store the trapped amount and only add it to total when the condition is met.</p><pre>int total = 0;<br>int temp = 0;<br>int curHeight = 0;<br>for (int i = 0; i &lt; height.length; i++) {<br>    int diff = curHeight - height[i];<br>    if (diff &gt; 0) {<br>        temp += diff;<br>    }<br>    if (height[i] &gt;= curHeight) {<br>        total += temp;<br>        temp = 0;<br>    }<br>    curHeight = Math.max(height[i], curHeight);<br>}</pre><p>But what if there is no bar on the right side that is as tall as or taller than the current highest bar? There is still some trapped rain that needs to be counted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*9f31X8GSLlt5NcQ635uzZQ.png" /></figure><p>So we can reverse the loop and start from the rightmost bar. Since the area between bars of the same height has already been counted, we only need to add the area when there is a taller bar on the left side. Here is my final solution.</p><ul><li><em>Time Complexity: O(n)</em></li><li><em>Space Complexity: O(1)</em></li></ul><pre>class Solution {<br>    public int trap(int[] height) {<br>        int total = 0;<br>        int temp = 0;<br>        int curHeight = 0;<br>        for (int i = 0; i &lt; height.length; i++) {<br>            int diff = curHeight - height[i];<br>            if (diff &gt; 0) {<br>                temp += diff;<br>            }<br>            if (height[i] &gt;= curHeight) {<br>                total += temp;<br>                temp = 0;<br>            }<br>            curHeight = Math.max(height[i], curHeight);<br>        }<br><br>        temp = 0;<br>        curHeight = 0;<br>        for (int i = height.length - 1; i &gt;= 0; i--) {<br>            int diff = curHeight - height[i];<br>            if (diff &gt; 0) {<br>                temp += diff;<br>            }<br>            if (height[i] &gt; curHeight) {<br>                total += temp;<br>                temp = 0;<br>            }<br>            curHeight = Math.max(height[i], curHeight);<br>        }<br>        return total;<br>    }<br>}</pre><p>I tried hard not to search for any hints and solutions, so I wrote this article to celebrate finally figuring it out myself :P</p><p>The two-pointer method is more efficient since it only needs one loop. However, since the overall time and space complexities are the same, the solution in this article is still reasonable, and I think it is easier for me to remember.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=035aa96a49b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Notes: Heap]]></title>
            <link>https://medium.com/@chiang-sh/leetcode-notes-heap-8cab87be344d?source=rss-c52d9577a762------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cab87be344d</guid>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[chiang-sh]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 11:48:37 GMT</pubDate>
            <atom:updated>2026-06-12T11:52:38.258Z</atom:updated>
            <content:encoded><![CDATA[<h3>#23 Merge k Sorted Lists</h3><p>We can use a priority queue to solve this problem. I used a default min heap and added all nodes from each linked list into the priority queue. Then, I built a new linked list by polling elements from the top of the queue to guarantee the sorted order.</p><ul><li><em>Time Complexity: O(n log n)</em></li><li><em>Space Complexity: O(n)</em></li></ul><pre>public ListNode mergeKLists(ListNode[] lists) {<br>    Queue&lt;Integer&gt; queue = new PriorityQueue&lt;&gt;();<br>    for (ListNode list : lists) {<br>        while (list != null) {<br>            queue.add(list.val);<br>            list = list.next;<br>        }<br>    }<br><br>    if (queue.peek() == null) {<br>        return null;<br>    }<br><br>    ListNode head = new ListNode(queue.poll());<br>    ListNode current = head;<br>    while (queue.peek() != null) {<br>        current.next = new ListNode(queue.poll());<br>        current = current.next;<br>    }<br><br>    return head;<br>}</pre><h3>#973 K Closest Points to Origin</h3><p>At first, I tried using a min heap and returned the first k points from the heap. However, I used this approach together with some other inefficient solutions, which resulted in a memory limited exceed error. After searching for some solutions, I found that using a max heap is more efficient.</p><p>So I implemented a max heap using priority queue with a custom comparator based on the point’s distance from the origin. The heap maintains at most k elements. Whenever the heap size exceeds k, the max value should be removed. After processing all points, we have the k closest points to origin.</p><ul><li><em>Time Complexity: O(n log k)</em></li><li><em>Space Complexity: O(k)</em></li></ul><pre>public int[][] kClosest(int[][] points, int k) {<br>    PriorityQueue&lt;int[]&gt; queue = new PriorityQueue&lt;&gt;(<br>            (p1, p2) -&gt; Integer.compare(p2[0] * p2[0] + p2[1] * p2[1], p1[0] * p1[0] + p1[1] * p1[1]));<br><br>    for (int[] point : points) {<br>        queue.add(point);<br>        if (queue.size() &gt; k) {<br>            queue.poll();<br>        }<br>    }<br><br>    int[][] result = new int[k][2];<br>    for (int i = 0; i &lt; result.length; i++) {<br>        result[i] = queue.poll();<br>    }<br>    return result;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cab87be344d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Updating JTextArea synchronously while a process is running]]></title>
            <link>https://medium.com/@chiang-sh/updating-jtextarea-synchronously-while-a-process-is-running-c4316b3159de?source=rss-c52d9577a762------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4316b3159de</guid>
            <category><![CDATA[java-swing]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[chiang-sh]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 09:42:30 GMT</pubDate>
            <atom:updated>2026-02-05T10:12:46.155Z</atom:updated>
            <content:encoded><![CDATA[<p>We have a Java Swing application that converts PDF to TIFF. The Swing frame contains a log block, which is a JTextArea, and new messages are appended to it. However, the logs are sometimes displayed after the conversion process finishes, instead of appearing synchronously.</p><p>This happens because both the conversion process and the UI updates run on the Event Dispatch Thread (EDT). As a result, UI updates may start after the conversion process is complete.</p><p>We can fix this by running the conversion process in a separate thread.</p><p>Since I don’t want the user to perform other actions while the conversion is running, I added a glass pane to the frame and control its visibility before and after conversion.</p><pre>public void setGlassPane() {<br>    JPanel glassPane = new JPanel();<br>    glassPane.addMouseListener(new MouseAdapter() {<br>    });<br>    glassPane.setOpaque(false);<br>    this.setGlassPane(glassPane);<br>}</pre><p>Then used a SwingWorker for the thread management:</p><pre>private SwingWorker&lt;Void, Void&gt; getConvertWorker() {<br>    Component glassPane = this.getGlassPane();<br>    return new SwingWorker&lt;Void, Void&gt;() {<br>        @Override<br>        public Void doInBackground() throws Exception {<br>            Converter.execute();<br>            return null;<br>        }<br><br>        @Override<br>        protected void done() {<br>            // The method runs on the EDT, so we can update UI here.<br>            glassPane.setVisible(false);<br>        }<br>    };<br>}</pre><p><em>*Note:</em> After execution, the status of a SwingWorker object becomes DONE. If we try to call execute() on the same object again, nothing will happen. Therefore, we create a new object every time.</p><p>Instead of calling the execute() function directly in the action listener:</p><pre>convertBtn.addActionListener(e -&gt; Converter.execute());</pre><p>We can use the SwingWorker like this:</p><pre>convertBtn.addActionListener(e -&gt; {<br>    getGlassPane().setVisible(true);<br>    getConvertWorker().execute();<br>});</pre><p><em>*Note:</em> We update the UI (glass pane) on the EDT instead of in the background thread.</p><p>Since we call the log() function in the background thread, we use invokeLater() to safely update the UI and prevent potential race conditions or conflicts.</p><pre>public static void log(String message) {<br>    if (textArea != null) {<br>        SwingUtilities.invokeLater(() -&gt; textArea.append(message + &quot;\n&quot;));<br>    }<br>}</pre><p>We can then call the log() function during the conversion process to display messages in the UI.</p><pre>UiLogger.log(message);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4316b3159de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Notes: Recursion]]></title>
            <link>https://medium.com/@chiang-sh/leetcode-notes-recursion-e0bcc67d1cf2?source=rss-c52d9577a762------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0bcc67d1cf2</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[chiang-sh]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 09:46:49 GMT</pubDate>
            <atom:updated>2026-01-13T09:26:29.485Z</atom:updated>
            <content:encoded><![CDATA[<h3>#22 Generate Parentheses</h3><p>We use recursion to solve this problem. The recursive function takes the remaining number of left and right parentheses, a temporary string, and the result list. The logic is as follows:</p><ol><li>If both left and right are 0, all parentheses have been used, so add the temporary string to the result list.</li><li>If there are left parenthese remaining, append ( to the temporary string and continue recurson. Then backtrack by removing the left parenthesis and returning to the previos state.</li><li>If there are more right parenthese than left (a valid state), do the same for ).</li></ol><p>The main function initializes the recursion and returns the result list.</p><ul><li><em>Time Complexity: O(</em>Cₙ<em>)</em></li><li><em>Space Complexity: O(n)</em></li></ul><pre>class Solution {<br>    public List&lt;String&gt; generateParenthesis(int n) {<br>        List&lt;String&gt; result = new ArrayList&lt;&gt;();<br>        backtrack(n, n, new StringBuilder(), result);<br>        return result;<br>    }<br><br>    public void backtrack(int left, int right, StringBuilder current, List&lt;String&gt; result) {<br>        if (left == 0 &amp;&amp; right == 0) {<br>            result.add(current.toString());<br>            return;<br>        }<br>        if (left &gt; 0) {<br>            backtrack(left - 1, right, current.append(&quot;(&quot;), result);<br>            current.deleteCharAt(current.length() - 1);<br>        }<br>        if (right &gt; left) {<br>            backtrack(left, right - 1, current.append(&quot;)&quot;), result);<br>            current.deleteCharAt(current.length() - 1);<br>        }<br>    }<br>}</pre><h3>#77 Combinations</h3><p>We can use a similar recursive approach as in the previous solution, tracking the current state with three variables:</p><ol><li>n: the total number</li><li>k: the number of elements left to choose</li><li>start: the current starting point</li></ol><p>We also use a temporary list to build each combination and a result list to store all combinations.</p><p>When the remaining number reaches 0, we add a copy of the temporary list to the result list. We use a copy because lists are mutable, and modifying the temporary list directly would affect previously stored results.</p><p>For each candidate number i, we add it to the temporary list and recurse with start = i + 1. After recursion, we backtrack by removing the last element to restore the previous state.</p><ul><li><em>Time Complexity: O(k * C(n, k))</em></li><li><em>Space Complexity: O(k * C(n, k))</em></li></ul><pre>class Solution {<br>    public List&lt;List&lt;Integer&gt;&gt; combine(int n, int k) {<br>        List&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;&gt;();<br>        backtrack(n, k, 1, new ArrayList&lt;&gt;(), result);<br>        return result;<br>    }<br><br>    public void backtrack(int n, int k, int start, List&lt;Integer&gt; cur, List&lt;List&lt;Integer&gt;&gt; result) {<br>        if (k == 0) {<br>            result.add(new ArrayList(cur));<br>            return;<br>        }<br><br>        for (int i = start; i &lt;= n - k + 1; i++) {<br>            cur.add(i);<br>            backtrack(n, k - 1, ++start, cur, result);<br>            cur.remove(cur.size() - 1);<br>        }<br>    }<br>}</pre><h3>#78 Subsets</h3><p>Here we go with similar recursive logic again! This time, we keep track of the state using the original array and the current starting index. Instead of specifying an endpoint, we add a copy of the temporary list at every recursive call, ensuring all subsets are included.</p><ul><li><em>Time Complexity: O(2ⁿ)</em></li><li><em>Space Complexity: O(2ⁿ)</em></li></ul><pre>class Solution {<br>    public List&lt;List&lt;Integer&gt;&gt; subsets(int[] nums) {<br>        List&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;&gt;();<br>        backtrack(nums, 0, new ArrayList&lt;&gt;(), result);<br>        return result;<br>    }<br><br>    public void backtrack(int[] nums, int start, List&lt;Integer&gt; cur, List&lt;List&lt;Integer&gt;&gt; result) {<br>        result.add(new ArrayList&lt;&gt;(cur));<br>        for (int i = start; i &lt; nums.length; i++) {<br>            cur.add(nums[i]);<br>            backtrack(nums, i + 1, cur, result);<br>            cur.remove(cur.size() - 1);<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0bcc67d1cf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Notes: String]]></title>
            <link>https://medium.com/@chiang-sh/leetcode-notes-string-dc74ee903fda?source=rss-c52d9577a762------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc74ee903fda</guid>
            <category><![CDATA[string]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[chiang-sh]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 01:31:00 GMT</pubDate>
            <atom:updated>2026-09-13T15:06:26.723Z</atom:updated>
            <content:encoded><![CDATA[<h3>#242 Valid Anagram</h3><p>An anagram is a string formed by rearranging the characters of another string. We can use an array to store the frequency of each ASCII character. First, iterate through the first string and increment the count for each character in the array. Then, iterate through the second string and decrement the corresponding counts. Finally, check the array: if all values are 0, the two strings are anagrams.</p><ul><li><em>Time Complexity: O(n)</em></li><li><em>Space Complexity: O(1)</em></li></ul><pre>class Solution {<br>    public boolean isAnagram(String s, String t) {<br>        int[] alphabets = new int[26];<br>        for (int i = 0; i &lt; s.length(); i++) {<br>            alphabets[s.charAt(i) - &#39;a&#39;]++;<br>        }<br>        for (int i = 0; i &lt; t.length(); i++) {<br>            alphabets[t.charAt(i) - &#39;a&#39;]--;<br>        }<br>        for (int i : alphabets) {<br>            if (i != 0) {<br>                return false;<br>            }<br>        }<br>        return true;<br>    }<br>}</pre><h3>#125 Valid Palindrome</h3><p>A palindrome is a string that reads the same forward and backward. This problem requires additional logic because the input string may contain non-alphanumeric characters and mixed casing. We can use two pointers to track the characters. When we met a non-alphanumeric character in the loop, skip it. Once both pointers are pointing to alphanumeric characters, we can compare them (ignoring case).</p><ul><li><em>Time Complexity: O(n)</em></li><li><em>Space Complexity: O(1)</em></li></ul><pre>class Solution {<br>    public boolean isPalindrome(String s) {<br>        int left = 0;<br>        int right = s.length() - 1;<br><br>        while (left &lt; right) {<br>            if (!Character.isLetterOrDigit(s.charAt(left))) {<br>                left++;<br>                continue;<br>            }<br>            if (!Character.isLetterOrDigit(s.charAt(right))) {<br>                right--;<br>                continue;<br>            }<br>            if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {<br>                return false;<br>            }<br>            left++;<br>            right--;<br>        }<br>        return true;<br>    }<br>}</pre><h3>#3 Longest Substring Without Repeating Characters</h3><p>We can use an array to record the last seen index of each character, and a pointer to track the start index of the substring. During the iteration, if a character has appeared before and its recorded index is greater than or equal to the start index, it means that the current substring contains a duplicate. In this case, we update the start index. We then calculate the current substring length and compare it to the current maximum length found so far, and update it if needed.</p><ul><li><em>Time Complexity: O(n)</em></li><li><em>Space Complexity: O(1)</em></li></ul><pre>class Solution {<br>    public int lengthOfLongestSubstring(String s) {<br>        int[] array = new int[128];<br>        Arrays.fill(array, -1);<br>        int maxLen = 0;<br>        int start = 0;<br>        for (int i = 0; i &lt; s.length(); i++) {<br>            char c = s.charAt(i);<br>            start = array[c] + 1 &gt; start ? array[c] + 1 : start;<br>            if (i - start + 1 &gt; maxLen) {<br>                maxLen = i - start + 1;<br>            }<br>            array[c] = i;<br>        }<br>        return maxLen;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc74ee903fda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Notes: Array]]></title>
            <link>https://medium.com/@chiang-sh/leetcode-notes-array-36cc472764e0?source=rss-c52d9577a762------2</link>
            <guid isPermaLink="false">https://medium.com/p/36cc472764e0</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[chiang-sh]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 07:34:34 GMT</pubDate>
            <atom:updated>2025-12-23T08:18:39.956Z</atom:updated>
            <content:encoded><![CDATA[<p>Here are some small notes for the following LeetCode solutions:</p><h3><strong>#1 Two Sum</strong></h3><p>We can iterate through the array and use a map (key: array value; value: array index) to store the values we’ve encountered. During the iteration, we check if we find the complement (target-current value) in the map. If it exists, we’ve found the answer; otherwise, we add the current value and its index to the map.</p><ul><li><em>Time Complexity: O(n)</em></li><li><em>Space Complexity: O(n)</em></li></ul><pre>class Solution {<br>    public int[] twoSum(int[] nums, int target) {<br>        Map&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();<br>        for (int i = 0; i &lt; nums.length; i++) {<br>            if (map.get(target - nums[i]) != null) {<br>                return new int[] {i, map.get(target - nums[i])};<br>            }<br>            map.put(nums[i], i);<br>        }<br>        return new int[] {};<br>    }<br>}</pre><h3><strong>#121 Best Time to Buy and Sell Stock</strong></h3><p>We can use one variable to track the minimum buy price and another for the max profit. While iterating, if the current price is lower than the buy price, we update it. Otherwise, we can calculate the potential profit by subtracting buy price from the current price and update the max profit if it is higher than our current record.</p><ul><li><em>Time Complexity: O(n)</em></li><li><em>Space Complexity: O(1)</em></li></ul><pre>class Solution {<br>    public int maxProfit(int[] prices) {<br>        int buy = 0;<br>        int profit = 0;<br>        for (int i = 0; i &lt; prices.length; i++) {<br>            if (i == 0 || prices[i] &lt; buy) {<br>                buy = prices[i];<br>            }<br>            if (prices[i] - buy &gt; profit) {<br>                profit = prices[i] - buy;<br>            }<br>        }<br>        return profit;<br>    }<br>}</pre><h3><strong>#238 Product of Array Except Self</strong></h3><p><strong>Basic Approach:</strong> The key idea is to use two arrays to store the needed information: one for storing the products of elements on the left-hand side, and the other for the right-hand side. Finally, we can generate a new array by multiplying the values from these two arrays.</p><p><strong>Optimized Approach:</strong> We can optimize this by using only one array for the left-hand side products and a single variable for the right-hand side.</p><ol><li>First loop: Generate the products of all elements to the left.</li><li>Second loop: Use a variable to keep track of the right-hand side product and calculate the final result directly in the same array.</li></ol><p>By using this approach, we can reduce the extra space complexity to O(1).</p><ul><li><em>Time Complexity: O(n)</em></li><li><em>Space Complexity: O(1)</em></li></ul><pre>class Solution {<br>    public int[] productExceptSelf(int[] nums) {<br>        int n = nums.length;<br>        int[] answer = new int[n];<br>        answer[0] = 1;<br>        for (int i = 1; i &lt; n; i++) {<br>            answer[i] = answer[i - 1] * nums[i - 1];<br>        }<br><br>        int right = 1;<br>        for (int i = n - 1; i &gt;= 0; i--) {<br>            answer[i] *= right;<br>            right *= nums[i];<br>        }<br>        return answer;<br>    }<br>}</pre><h3><strong>#53 Maximum Subarray</strong></h3><p>We can iterate through the array while maintaining the current sum. For each element, we add it to the current sum. If the current sum becomes negative, we reset it to 0 because a negative prefix will only decrease the sum of any subsequent subarray. Throughout the process, we keep track of and update the max sum whenever the current sum exceeds it.</p><ul><li><em>Time Complexity: O(n)</em></li><li><em>Space Complexity: O(1)</em></li></ul><pre>class Solution {<br>    public int maxSubArray(int[] nums) {<br>        int max = nums[0];<br>        int total = 0;<br><br>        for (int num : nums) {<br>            if (total &lt; 0) {<br>                total = 0;<br>            }<br><br>            total += num;<br>            if (total &gt; max) {<br>                max = total;<br>            }<br>        }<br>        <br>        return max;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36cc472764e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving the Image-to-PDF Conversion Process]]></title>
            <link>https://medium.com/@chiang-sh/improving-the-image-to-pdf-conversion-process-486ff26538e5?source=rss-c52d9577a762------2</link>
            <guid isPermaLink="false">https://medium.com/p/486ff26538e5</guid>
            <category><![CDATA[pdfbox]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[chiang-sh]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 08:34:51 GMT</pubDate>
            <atom:updated>2025-11-20T08:35:31.346Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@b228103049/to-descrypt-an-image-file-and-convert-it-into-a-pdf-file-ac95649b9470">previous post</a>, we used a function to decrypt image files and convert them into PDF files.</p><p>It works fine for TIF files. However, when processing JPEG files, the size of the PDF file becomes several times larger than the sum of the JPEG files. This is because JPEG is a compressed format, so its size increases when the data is decompressed. In contrast, TIF files are not a compressed format, so they don’t cause this problem.</p><p>I decided to improve the function in two parts:</p><ol><li>Processing JPEG files direclty from the InputStream instead of generating a BufferedImage object</li><li>Splitting the function into three sub-functions to make it easier to read and modify</li></ol><p>First, I wrote a addImagePage function to add a PDImageXObject to the PDDocument:</p><pre>private static void addImagePage(PDDocument document, PDImageXObject pdImage) throws IOException {<br>    float pageWidthInPoints = (float) (pdImage.getWidth() * 72.0 / DEFAULT_RESOLUTION);<br>    float pageHeightInPoints = (float) (pdImage.getHeight() * 72.0 / DEFAULT_RESOLUTION);<br>    PDRectangle pageSize = new PDRectangle(pageWidthInPoints, pageHeightInPoints);<br><br>    PDPage page = new PDPage(pageSize);<br>    document.addPage(page);<br>    try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {<br>        contentStream.drawImage(pdImage, 0, 0, pageSize.getWidth(), pageSize.getHeight());<br>    }<br>}</pre><p>Then I wrote two processing functions, one for JPEG files and the other for general files:</p><pre><br>private static void processJpeg(File imageFile, Cipher cipher, PDDocument document) throws IOException {<br>    try (InputStream fileInputStream = Files.newInputStream(imageFile.toPath());<br>            InputStream cipherInputStream = new CipherInputStream(fileInputStream, cipher)) {<br>        PDImageXObject pdImage = JPEGFactory.createFromStream(document, cipherInputStream);<br>        addImagePage(document, pdImage);<br>    }<br>}</pre><pre>private static void processGeneral(File imageFile, Cipher cipher, PDDocument document) throws IOException {<br>    try (InputStream fileInputStream = Files.newInputStream(imageFile.toPath());<br>            InputStream cipherInputStream = new CipherInputStream(fileInputStream, cipher);<br>            ImageInputStream imageInputStream = ImageIO.createImageInputStream(cipherInputStream)) {<br>        Iterator&lt;ImageReader&gt; readers = ImageIO.getImageReaders(imageInputStream);<br>        if (!readers.hasNext()) {<br>            throw new IOException(&quot;Unsupported image format&quot;);<br>        }<br><br>        ImageReader reader = readers.next();<br>        reader.setInput(imageInputStream);<br><br>        int numPages = reader.getNumImages(true);<br>        for (int i = 0; i &lt; numPages; i++) {<br>            BufferedImage image = reader.read(i);<br>            PDImageXObject pdImage = LosslessFactory.createFromImage(document, image);<br>            addImagePage(document, pdImage);<br>        }<br>        reader.dispose();<br>    }<br>}</pre><p>Then I added a determining logic in the original function:</p><pre>if (filename.endsWith(&quot;.jpg&quot;) || filename.endsWith(&quot;.jpeg&quot;)) {<br>    processJpeg(imageFile, cipher, document);<br>} else {<br>    processGeneral(imageFile, cipher, document);<br>}</pre><p>The PDF size generated from JPEG files become more reasonable. I haven’t tested the performance thoroughly yet, but after manually processing the conversion several times, it is faster than before.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=486ff26538e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[To descrypt an image file and convert it into a PDF file]]></title>
            <link>https://medium.com/@chiang-sh/to-descrypt-an-image-file-and-convert-it-into-a-pdf-file-ac95649b9470?source=rss-c52d9577a762------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac95649b9470</guid>
            <category><![CDATA[imageio]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[pdfbox]]></category>
            <dc:creator><![CDATA[chiang-sh]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 08:25:50 GMT</pubDate>
            <atom:updated>2025-11-20T08:38:52.607Z</atom:updated>
            <content:encoded><![CDATA[<p>One of our customer’s systems is going to be deprecated, so they want a small program to extract the images from the system easily. Most of the images are encrypted and stored in <strong>.tif</strong> or <strong>.jpg</strong> format. I am developing a Java executable JAR to decrypt them and convert them into PDF files.</p><p>There are some Maven dependencies needed in the program. One is <strong>jai-imageio</strong> for reading the TIF files, and another is <strong>PDFBox</strong> for generating the PDF files.</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.github.jai-imageio&lt;/groupId&gt;<br>    &lt;artifactId&gt;jai-imageio-core&lt;/artifactId&gt;<br>    &lt;version&gt;1.4.0&lt;/version&gt;<br>&lt;/dependency&gt;<br><br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.apache.pdfbox&lt;/groupId&gt;<br>    &lt;artifactId&gt;pdfbox&lt;/artifactId&gt;<br>    &lt;version&gt;2.0.27&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>The process can be simplified as follows:</p><ol><li>Read the image file from the given path and convert it into an InputStream</li><li>Decrypt the InputStream into another InputStream using a Cipher object (which contains the key for decryption)</li><li>Create an ImageInputStream object from the decrypted stream using ImageIO, and get an ImageReader from it</li><li>Get a BufferedImage object and calculate the width and height of the image</li><li>Get a PDImageXObject from the BufferedImage</li><li>Use PDPageContentStream to draw the image onto a PDF page, and add it to the document</li></ol><p>Here’s the implementation:</p><pre>try (PDDocument document = new PDDocument(); OutputStream outputStream = Files.newOutputStream(outputPath)) {<br>    for (File imageFile : imageFiles) {<br>        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY, ALGORITHM);<br>        Cipher cipher = Cipher.getInstance(TRANSFORMATION);<br>        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);<br><br>        try (InputStream fileInputStream = Files.newInputStream(imageFile.toPath());<br>                InputStream cipherInputStream = new CipherInputStream(fileInputStream, cipher);<br>                ImageInputStream imageInputStream = ImageIO.createImageInputStream(cipherInputStream)) {<br>            Iterator&lt;ImageReader&gt; readers = ImageIO.getImageReaders(imageInputStream);<br>            if (!readers.hasNext()) {<br>                throw new IOException(&quot;Unsupported image format&quot;);<br>            }<br><br>            ImageReader reader = readers.next();<br>            reader.setInput(imageInputStream);<br><br>            int numPages = reader.getNumImages(true);<br>            for (int i = 0; i &lt; numPages; i++) {<br>                BufferedImage image = reader.read(i);<br><br>                float pageWidthInPoints = (float) (image.getWidth() * 72.0 / DEFAULT_RESOLUTION);<br>                float pageHeightInPoints = (float) (image.getHeight() * 72.0 / DEFAULT_RESOLUTION);<br>                PDRectangle pageSize = new PDRectangle(pageWidthInPoints, pageHeightInPoints);<br><br>                PDPage page = new PDPage(pageSize);<br>                document.addPage(page);<br><br>                PDImageXObject pdImage = LosslessFactory.createFromImage(document, image);<br>                try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {<br>                    contentStream.drawImage(pdImage, 0, 0, pageSize.getWidth(), pageSize.getHeight());<br>                }<br>            }<br>            reader.dispose();<br>        }<br>    }<br>    document.save(outputStream);<br>}</pre><p>I know that we can get a PDImageXObject directly from JPEGFactory, which is easier and faster because it does not require creating a BufferedImage. However, there are TIF files, and possibly some unknown image formats in our system. So even if this solution does not offer the best performance, it is still acceptable. I am going to look for other ways to improve it.</p><p>*Update: See <a href="https://medium.com/@b228103049/improving-the-image-to-pdf-conversion-process-486ff26538e5">this post</a> for process improvements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac95649b9470" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ImageIO does not close the InputStream argument automatically]]></title>
            <link>https://medium.com/@chiang-sh/imageio-does-not-close-the-inputstream-argument-automatically-1181ba0fd0cc?source=rss-c52d9577a762------2</link>
            <guid isPermaLink="false">https://medium.com/p/1181ba0fd0cc</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[imageio]]></category>
            <dc:creator><![CDATA[chiang-sh]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 06:24:04 GMT</pubDate>
            <atom:updated>2025-10-16T06:37:23.114Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a barcode reader function in our app. It reads barcodes from image files, mainly .tiff files. After reading the barcode and storing the information in the database, the file is moved to an archive location, and the original file should be deleted. However, deleting the files sometimes causes an error because they are still in use.</p><p>I tried to implement a retry mechanism. That is, if the file was not deleted successfully, the app would wait for a few seconds and try deleting it again. It seemed to work sometimes, but around 70% of the deletions still failed.</p><p>I think the problem may be caused by the file-reading process. The original code created a new FileInputStream object from the file, then called the read() method from ImageIO to get the content of the file.</p><pre>BinaryBitmap binaryBitmap = new BinaryBitmap(<br>    new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(file))))); </pre><p>After checking the source code of the ImageIO.read(InputStream) method, I found that it creates an ImageInputStream from the InputStream and closes it automatically after reading. However, the method does not close the original InputStream.</p><pre>public static BufferedImage read(InputStream input) throws IOException {<br>    if (input == null) {<br>        throw new IllegalArgumentException(&quot;input == null!&quot;);<br>    }<br><br>    ImageInputStream stream = createImageInputStream(input);<br>    if (stream == null) {<br>        throw new IIOException(&quot;Can&#39;t create an ImageInputStream!&quot;);<br>    }<br>    BufferedImage bi = read(stream);<br>    if (bi == null) {<br>        stream.close();<br>    }<br>    return bi;<br>}</pre><p>I think it is reasonable, because the InputStream may be used elsewhere. The specification also clearly notes that “it is the responsibility of the caller to close the stream, if desired.” Without reading the specification carefully, I had used this method incorrectly, which caused the problem.</p><p>There is an overload method that accepts a File argument, which internally manages the ImageInputStream object and closes it after use.</p><pre>public static BufferedImage read(File input) throws IOException {<br>    if (input == null) {<br>        throw new IllegalArgumentException(&quot;input == null!&quot;);<br>    }<br>    if (!input.canRead()) {<br>        throw new IIOException(&quot;Can&#39;t read input file!&quot;);<br>    }<br><br>    ImageInputStream stream = createImageInputStream(input);<br>    if (stream == null) {<br>        throw new IIOException(&quot;Can&#39;t create an ImageInputStream!&quot;);<br>    }<br>    BufferedImage bi = read(stream);<br>    if (bi == null) {<br>        stream.close();<br>    }<br>    return bi;<br>}</pre><p>So I changed my code to use it.</p><pre>BinaryBitmap binaryBitmap = new BinaryBitmap(<br>    new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(file))));</pre><p>The file-locking problem disappeared, and we can now successfully delete the files after reading them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1181ba0fd0cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Presigned URLs for File Downloads]]></title>
            <link>https://medium.com/@chiang-sh/there-is-a-download-pdf-function-in-the-project-which-can-merge-several-images-and-generate-a-pdf-6296d42c5c86?source=rss-c52d9577a762------2</link>
            <guid isPermaLink="false">https://medium.com/p/6296d42c5c86</guid>
            <category><![CDATA[presigned-url]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[download]]></category>
            <dc:creator><![CDATA[chiang-sh]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 08:11:32 GMT</pubDate>
            <atom:updated>2025-11-13T08:37:29.120Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a PDF download function in the project, which can merge several images and generate a PDF file. We use POST to send the file binary to the frontend and then trigger the download. However, an out-of-memory error occurred in the browser when the file was too large. So we searched for a new solution…</p><p>We want to trigger the download directly by URL, without loading the data into browser memory. At the same time, we also want to validate the user’s identity to prevent anyone from downloading the file easily.</p><p>So we decided to use a presigned URL, which is a temporary link generated by the backend containing expiration and authentication info. The frontend will call the POST API to get the download URL. Since it’s a POST call, the project’s authentication mechanism will validate the user identity. Then the frontend can use the URL to call the GET API to download without loading the file into memory.</p><p>The flow is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UmxaWADfH187GN5Re5I7bQ.png" /></figure><p>The backend code consists of two parts: the controller and the service.</p><p>First, I wrote a PresignedUrlService to generate the signing info.</p><pre>public class PresignedUrlService {<br><br>    private static final long ALLOWED_TTL_MILLIS = 30 * 1000;<br>    private static final String ALGORITHM = &quot;xxx&quot;;<br>    private static final String SECRET = &quot;xxx&quot;; // Base64-encoded key generated via Keys.secretKeyFor(HS512)<br>    private static final Mac MAC;<br><br>    static {<br>        try {<br>            byte[] decoded = Base64.getDecoder().decode(SECRET);<br>            SecretKey originalKey = new SecretKeySpec(decoded, ALGORITHM);<br>            MAC = Mac.getInstance(ALGORITHM);<br>            MAC.init(originalKey);<br>        } catch (Exception e) {<br>            throw new RuntimeException(&quot;Failed to initialize secret key&quot;, e);<br>        }<br>    }<br><br>    public static PresignedUrl generatePresignedUrl(String downloadId) {<br>        String expiration = generateExpiration();<br>        String sign = generateSign(downloadId, expiration);<br>        return new PresignedUrl(downloadId, expiration, sign); // PresignedUrl is a simple POJO that stores the presigned info<br>    }<br><br>    public static boolean isValid(String downloadId, String expiration, String sign) {<br>        try {<br>            long expiresAt = Long.parseLong(expiration);<br>            long now = System.currentTimeMillis();<br>            if (expiresAt &lt; now) {<br>                return false;<br>            }<br><br>            byte[] expected = Base64.getUrlDecoder().decode(generateSign(downloadId, expiration));<br>            byte[] provided = Base64.getUrlDecoder().decode(sign);<br>            return MessageDigest.isEqual(expected, provided);<br>        } catch (Exception e) {<br>            return false;<br>        }<br>    }<br><br>    private static String generateExpiration() {<br>        long expiresAt = System.currentTimeMillis() + ALLOWED_TTL_MILLIS;<br>        return String.valueOf(expiresAt);<br>    }<br><br>    private static String generateSign(String downloadId, String expiration) {<br>        try {<br>            String message = downloadId + &quot;:&quot; + expiration;<br><br>            byte[] rawHmac;<br>            synchronized (MAC) {<br>                rawHmac = MAC.doFinal(message.getBytes(StandardCharsets.UTF_8));<br>            }<br><br>            return Base64.getUrlEncoder().withoutPadding().encodeToString(rawHmac);<br>        } catch (Exception e) {<br>            throw new RuntimeException(&quot;Failed to generate sign&quot;, e);<br>        }<br>    }<br>}</pre><p>Then there are two APIs in the controller. The POST API will return a presigned URL string:</p><pre>@PostMapping(&quot;/getDownloadUrl&quot;)<br>@ResponseBody<br>public JSONObject getDownloadUrl(@RequestBody JSONObject request) {<br>    JSONObject data = new JSONObject();<br>    String downloadId = request.getString(&quot;downloadId&quot;);<br><br>    PresignedUrl presignedUrl = PresignedUrlService.generatePresignedUrl(downloadId);<br>    UriComponents downloadUri = UriComponentsBuilder.fromUriString(&quot;/downloadPdf&quot;)<br>            .queryParam(&quot;downloadId&quot;, presignedUrl.getDownloadId())<br>            .queryParam(&quot;expiration&quot;, presignedUrl.getExpiration()).queryParam(&quot;sign&quot;, presignedUrl.getSign())<br>            .build();<br><br>    data.put(&quot;downloadUrl&quot;, downloadUri.toUriString());<br>    return data;<br>}</pre><p>And the GET API will return the binary data of the download file:</p><pre>@GetMapping(&quot;/downloadPdf&quot;)<br>@ResponseBody<br>public ResponseEntity&lt;?&gt; downloadPdf(@RequestParam(&quot;downloadId&quot;) String downloadId,<br>        @RequestParam(&quot;expiration&quot;) String expiration, @RequestParam(&quot;sign&quot;) String sign) throws Exception {<br>    if (!PresignedUrlService.isValid(downloadId, expiration, sign)) {<br>        return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.TEXT_PLAIN)<br>                .body(&quot;Failed to download.&quot;);<br>    }<br><br>    File file = imageService.getDownloadFile(downloadId);<br>    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));<br><br>    return ResponseEntity.ok().header(&quot;Access-Control-Expose-Headers&quot;, &quot;Content-Disposition&quot;)<br>            .header(&quot;Content-Disposition&quot;, &quot;attachment; filename=\&quot;&quot; + file.getName() + &quot;\&quot;&quot;)<br>            .contentType(MediaType.APPLICATION_OCTET_STREAM).contentLength(file.length()).body(resource);<br>}</pre><p>In this way, we can solve the memory issue while keeping the download secure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6296d42c5c86" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>