<?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 George Chou on Medium]]></title>
        <description><![CDATA[Stories by George Chou on Medium]]></description>
        <link>https://medium.com/@georgechmr?source=rss-3a8d32f50ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QbI8mMv-FV56YzVGHSLLZQ.jpeg</url>
            <title>Stories by George Chou on Medium</title>
            <link>https://medium.com/@georgechmr?source=rss-3a8d32f50ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:05:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@georgechmr/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[Sending Daily Messages to Telegram Channel via GitHub Actions]]></title>
            <link>https://medium.com/@georgechmr/sending-daily-messages-to-telegram-channel-via-github-actions-8fa4dccb3786?source=rss-3a8d32f50ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fa4dccb3786</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[daily-update]]></category>
            <dc:creator><![CDATA[George Chou]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 22:15:15 GMT</pubDate>
            <atom:updated>2024-06-13T14:16:57.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DdHRGYf1Qj8zo9TaPGa81A.jpeg" /><figcaption>Bot</figcaption></figure><p>Automating tasks can save time and ensure consistency, and GitHub Actions provides a powerful way to automate workflows directly from your GitHub repositories. In this guide, we’ll learn how to send daily messages to a Telegram channel using GitHub Actions. This can be useful for daily updates, reminders, or any routine communication you’d like to automate.</p><h3><strong>Prerequisites</strong></h3><ol><li><strong>Telegram Bot</strong>: You need a Telegram bot to send messages.</li><li><strong>GitHub Account</strong>: A GitHub account with a repository where you can set up your GitHub Actions workflow.</li></ol><h3>Step1: Create a Telegram Bot</h3><ol><li>Open Telegram and search for @BotFather</li><li>Start a conversation with BotFather and send the /newbot command.</li><li>Follow the instructions to set up your bot and get the API token.</li></ol><h3>Step2: Add Telegram Bot to your channel</h3><ol><li>Open your Telegram channel info page</li><li>Click Add Admin and add your bot to this channel</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rW5j_Vs1jM5T2gYsz8ba6g.png" /></figure><h3>Step3: Get your channel Chat Id</h3><ol><li>Log in under your account at the web version of Telegram: <a href="https://web.telegram.org/">https://web.telegram.org</a></li><li>Find your channel. See to your URL. It should be like: <a href="https://web.telegram.org/z/#-1001543515057">https://web.telegram.org/z/#-1001543515057</a></li><li>Grab “-1001543515057” from it, it’s your channel’s chat id</li></ol><h3>Step4: Create the GitHub Actions Workflow</h3><ol><li>Inside the .github/workflows directory, create a new file named run_daily.yml</li><li>Add the following content to the run_daily.yml file:</li></ol><pre>name: Daily Bot<br><br>on:<br>    schedule:<br>        - cron: &#39;0 8 * * *&#39;<br>    push:<br>        branches:<br>            - main<br><br>jobs:<br>    run-bot:<br>        runs-on: ubuntu-latest<br><br>        steps:<br>            - name: Checkout<br>              uses: actions/checkout@v2<br><br>            - name: Set up Python<br>              uses: actions/setup-python@v2<br>              with:<br>                  python-version: &#39;3.x&#39;<br><br>            - name: Install dependencies<br>              run: |<br>                  python -m pip install --upgrade pip<br>                  pip install -r requirements.txt<br><br>            - name: Run bot<br>              env:<br>                TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}<br>                TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}<br>                WEATHER_API_KEY: ${{ secrets.WEATHER_API_KEY }}<br>                CITY_NAME: ${{ secrets.CITY_NAME }}<br>                WORKER_AI_API: ${{ secrets.WORKER_AI_API }}<br>                CLOUDFLARE_API_KEY: ${{ secrets.CLOUDFLARE_API_KEY }}<br>              run: python daily_bot.py</pre><h3>Step5: Create the Send Message Python</h3><pre>import os<br>import requests<br>from telegram import Bot<br>import asyncio<br>import hmac<br>import base64<br>import time<br>import urllib.parse<br>from hashlib import sha256<br><br>TELEGRAM_BOT_TOKEN = os.getenv(&#39;TELEGRAM_BOT_TOKEN&#39;)<br>TELEGRAM_CHAT_ID = os.getenv(&#39;TELEGRAM_CHAT_ID&#39;)<br>WEATHER_API_KEY = os.getenv(&#39;WEATHER_API_KEY&#39;)<br>CITY_NAME = os.getenv(&#39;CITY_NAME&#39;)<br>WORKER_AI_API = os.getenv(&#39;WORKER_AI_API&#39;)<br>CLOUDFLARE_API_KEY = os.getenv(&#39;CLOUDFLARE_API_KEY&#39;)<br><br>ICON_MAP = {<br>    &#39;01d&#39;: &#39;☀️&#39;,<br>    &#39;02d&#39;: &#39;⛅️&#39;,<br>    &#39;03d&#39;: &#39;☁️&#39;,<br>    &#39;04d&#39;: &#39;☁️&#39;,<br>    &#39;09d&#39;: &#39;🌧&#39;,<br>    &#39;10d&#39;: &#39;🌦&#39;,<br>    &#39;11d&#39;: &#39;🌩&#39;,<br>    &#39;13d&#39;: &#39;❄️&#39;,<br>    &#39;50d&#39;: &#39;🌫&#39;,<br>}<br><br>def get_weather_icon(icon_id):<br>    return ICON_MAP.get(icon_id)<br><br>def generate_weather_img(weather):<br>    message = &quot;/text2img&quot;<br>    # utc 0 时区<br>    timestamp = time.time()<br>    timestamp = str(int(time.time()))<br>    digest = hmac.new(CLOUDFLARE_API_KEY.encode(&#39;utf8&#39;), &quot;{}{}&quot;.format(message, timestamp).encode(&#39;utf8&#39;), sha256)<br>    token = urllib.parse.quote_plus(base64.b64encode(digest.digest()))<br>    url = f&#39;{WORKER_AI_API}/text2img?prompt={weather}&amp;verify={timestamp}-{token}&#39;<br>    response = requests.get(url)<br>    return response.content<br><br>def get_weather():<br>    url = f&#39;http://api.openweathermap.org/data/2.5/weather?q={CITY_NAME}&amp;appid={WEATHER_API_KEY}&amp;units=metric&#39;<br>    response = requests.get(url)<br>    weather_data = response.json()<br><br>    if response.status_code == 200:<br>        weather_description = weather_data[&#39;weather&#39;][0][&#39;description&#39;]<br>        temperature = weather_data[&#39;main&#39;][&#39;temp&#39;]<br>        icon_id = weather_data[&#39;weather&#39;][0][&#39;icon&#39;]<br>        weather_report = f&quot;Weather in {CITY_NAME}: {get_weather_icon(icon_id)} {weather_description}, Temperature: {temperature}°C&quot;<br>        weather_img = generate_weather_img(weather_description)<br>    else:<br>        weather_report = &quot;Unable to fetch weather data at the moment.&quot;<br>    <br>    return {&#39;text&#39;: weather_report, &#39;img&#39;: weather_img}<br><br>def get_exchange_rate():<br>    url = f&#39;https://fin.paas.cmbchina.com/fininfo/api/calculator/getFxRealRate?bsflag=buy&amp;chflag=XH&amp;currency=39&#39;<br>    response = requests.get(url)<br>    exchange_data = response.json()<br><br>    if response.status_code == 200:<br>        exchange_report = f&quot;今日招行加币🇨🇦汇率：{exchange_data[&#39;body&#39;][&#39;rate&#39;]}🇨🇳&quot;<br>    else:<br>        exchange_report = &#39;获取汇率失败&#39;<br><br>    return exchange_report<br><br>async def send_message(message):<br>    bot = Bot(token=TELEGRAM_BOT_TOKEN)<br>    response = await bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=message)<br>    print(response)<br><br>async def send_photo(photo, caption):<br>    bot = Bot(token=TELEGRAM_BOT_TOKEN)<br>    response = await bot.send_photo(chat_id=TELEGRAM_CHAT_ID, photo=photo, caption=caption)<br><br>async def main():<br>    weather = get_weather()<br>    exchange_rate = get_exchange_rate()<br>    if weather[&#39;img&#39;]:<br>        await send_photo(weather[&#39;img&#39;], f&quot;{weather[&#39;text&#39;]}\n{exchange_rate}&quot;)<br>    else:<br>        message = f&quot;{weather}\n{exchange_rate}&quot;<br>        await send_message(message)<br><br>if __name__ == &#39;__main__&#39;:<br>    asyncio.run(main())</pre><p><strong>Code Explanation</strong></p><ul><li>get_weather : Search the CITY_NAME weather via openweathermap API.</li><li>get_weather_img : Generate the weather image by Cloudflare Worker AI (Will write a blog about how to build the Worker AI).</li><li>send_message : Send a message to the Telegram Channel.</li><li>send_photo : Send a photo to the Telegram Channel.</li></ul><p><em>You can add other methods to send a customized message.</em></p><h3>Step6: Add Secrets to your GitHub Repository</h3><ul><li>Go to your GitHub repository and click on Settings.</li><li>In the left sidebar, click on Secrets and then New repository secret.</li><li>Add the following secrets:</li><li>TELEGRAM_BOT_TOKEN: Your Telegram bot API token.</li><li>TELEGRAM_CHAT_ID: The chat ID of the Telegram channel or group where you want to send the message.</li></ul><h3>Step 7: Test the Workflow</h3><ol><li>After setting up the secrets and committing the workflow file, go to the Actions tab in your repository.</li><li>You should see your Daily Botworkflow listed. Click on it.</li><li>Click the Run workflow button to manually trigger the workflow and test if everything is set up correctly.</li></ol><h3>Conclusion</h3><p>With this setup, you now have a GitHub Actions workflow that sends a daily message to your Telegram channel. This automation can be extended and customized further to suit your specific needs. For example, you could integrate data from other APIs, including dynamic content, or send messages at different times.</p><p>GitHub Actions is a versatile tool for automation, and integrating it with Telegram opens up many possibilities for seamless communication and updates. Happy automating!</p><p>You can check my code in my <a href="https://github.com/GeorgeCh2/george_tg_bot">GitHub Repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fa4dccb3786" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Try To Use `savepoint` In Spring JPA/Hibernate]]></title>
            <link>https://medium.com/javarevisited/try-to-use-savepoint-in-spring-jpa-hibernate-29d073e3dc9b?source=rss-3a8d32f50ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/29d073e3dc9b</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[George Chou]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 20:57:47 GMT</pubDate>
            <atom:updated>2024-02-28T14:43:17.290Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ug7_-kSuztfoInuZmdswOg.jpeg" /><figcaption>savepoint</figcaption></figure><p>This article describes my failed attempt to use the <strong><em>PostgreSQL SAVEPOINT</em></strong> in Spring JPA.<br>About <a href="https://www.postgresql.org/docs/current/tutorial-transactions.html">PostgreSQL SAVEPOINT</a>.</p><h4>EntityManager</h4><pre>@PersistenceContext  <br>private EntityManager entityManager;<br><br>@Transactional(propagation=NESTED, isolation= READ_UNCOMMITTED)  <br>public void transferWithSavePoint(String fromAccount, String toAccount, String anotherAccount,  <br>                                  double amount) throws SQLException {  <br>    // step 1  <br>    Account from = accountRepository.findByName(fromAccount);  <br>    Branch fromBranch = branchRepository.findByName(from.getBranchName());  <br>  <br>    from.setBalance(from.getBalance().subtract(BigDecimal.valueOf(amount)));  <br>    fromBranch.setBalance(fromBranch.getBalance().subtract(BigDecimal.valueOf(amount)));  <br>  <br>    accountRepository.save(from);  <br>    branchRepository.save(fromBranch);  <br>  <br>    Connection connection = entityManager.unwrap(SessionImpl.class).connection();  <br>    Savepoint savepoint = connection.setSavepoint();  <br>  <br>    // step 2  <br>    Account to = accountRepository.findByName(toAccount);  <br>    Branch toBranch = branchRepository.findByName(to.getBranchName());  <br>  <br>    to.setBalance(to.getBalance().add(BigDecimal.valueOf(amount)));  <br>    toBranch.setBalance(toBranch.getBalance().add(BigDecimal.valueOf(amount)));  <br>  <br>    accountRepository.save(to);  <br>    branchRepository.save(toBranch);  <br>  <br>    connection.rollback(savepoint);  <br>  <br>    // final step  <br>    Account finalAccount = accountRepository.findByName(anotherAccount);  <br>    Branch finalBranch = branchRepository.findByName(to.getBranchName());  <br>  <br>    finalAccount.setBalance(finalAccount.getBalance().add(BigDecimal.valueOf(amount)));  <br>    finalBranch.setBalance(finalBranch.getBalance().add(BigDecimal.valueOf(amount)));  <br>  <br>    accountRepository.save(finalAccount);  <br>    branchRepository.save(finalBranch);  <br>}</pre><p>I use Connection Pool in this project, so the <strong>connection</strong> created by <strong>EntityManager</strong> is different <strong>@Transactional</strong> method’s connection</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QmWii2wPKM0OWIDDhzALJA.png" /></figure><ul><li><strong>savepoint</strong>: is before <strong><em>transferWithSavePoint</em></strong></li><li><strong>rollback</strong>: rollback to all of the operations before, so `<strong>STEP1</strong>` is rollback, but `<strong>STEP2</strong>` and `<strong>Final STEP</strong>` is done.</li></ul><h4>Next Try: AbstractTransactionStatus</h4><pre>@Autowired  <br>private JdbcTemplate jdbcTemplate;  <br>  <br>@Autowired  <br>private TransactionTemplate transactionTemplate;<br><br>public void transferWithSavePoint(String fromAccount, String toAccount, String anotherAccount,  <br>                                  double amount) {  <br>    transactionTemplate.execute(status -&gt; {  <br>        Account from = accountRepository.findByName(fromAccount);  <br>        Branch fromBranch = branchRepository.findByName(from.getBranchName());  <br>  <br>        from.setBalance(from.getBalance().subtract(BigDecimal.valueOf(amount)));  <br>        fromBranch.setBalance(fromBranch.getBalance().subtract(BigDecimal.valueOf(amount)));  <br>  <br>        accountRepository.save(from);  <br>        branchRepository.save(fromBranch);  <br>  <br>        Object savepoint = status.createSavepoint();  <br>  <br>        // step 2  <br>        Account to = accountRepository.findByName(toAccount);  <br>        Branch toBranch = branchRepository.findByName(to.getBranchName());  <br>  <br>        to.setBalance(to.getBalance().add(BigDecimal.valueOf(amount)));  <br>        toBranch.setBalance(toBranch.getBalance().add(BigDecimal.valueOf(amount)));  <br>  <br>        accountRepository.save(to);  <br>        branchRepository.save(toBranch);  <br>  <br>        status.rollbackToSavepoint(savepoint);  <br>  <br>        // final step  <br>        Account finalAccount = accountRepository.findByName(anotherAccount);  <br>        Branch finalBranch = branchRepository.findByName(to.getBranchName());  <br>  <br>        finalAccount.setBalance(finalAccount.getBalance().add(BigDecimal.valueOf(amount)));  <br>        finalBranch.setBalance(finalBranch.getBalance().add(BigDecimal.valueOf(amount)));  <br>  <br>        accountRepository.save(finalAccount);  <br>        branchRepository.save(finalBranch);  <br>  <br>        status.releaseSavepoint(savepoint);  <br>  <br>        return null;    });  <br>}</pre><p>Also failed:</p><pre>JpaDialect does not support savepoints — check your JPA provider’s capabilities</pre><p>Then I start to search ‘<strong><em>How to use savepoint in Hibernate</em></strong>’ online:</p><blockquote>Please note that this is not a recommended way to use Spring JPA. It’s better to structure your transactions in such a way that you don’t need to use savepoints or nested transactions. If you find yourself needing them, it might be a sign that your transactions are too complex and should be broken down into smaller parts.</blockquote><p>Maybe I’m wrong from the beginning, indeed, I won’t encounter it in real application scenarios, but I’m just trying to figure out how to implement it, so let me know if you have any good ideas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29d073e3dc9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/try-to-use-savepoint-in-spring-jpa-hibernate-29d073e3dc9b">Try To Use `savepoint` In Spring JPA/Hibernate</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Map PostgreSQL `point` Data Type To Java PGpoint Data Type?]]></title>
            <link>https://medium.com/javarevisited/how-to-map-postgresql-point-data-type-to-java-pgpoint-data-type-d74cc7f49734?source=rss-3a8d32f50ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/d74cc7f49734</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[George Chou]]></dc:creator>
            <pubDate>Sun, 25 Feb 2024 19:33:26 GMT</pubDate>
            <atom:updated>2024-02-28T14:46:01.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z6ljxmZzShh8UL2XZGjz9w.jpeg" /><figcaption>Location</figcaption></figure><p>This article describes using PostgreSQL <strong>point</strong> data in Spring Boot &amp; Spring JPA/Hibernate projects.</p><ul><li>Which Java Data Type should be used for the <strong><em>point</em></strong> Data Type mapped?</li><li>Why can’t you use PGpoint directly?</li><li>How to Use Data Types Not Supported in JPA?</li></ul><h4>Technology</h4><ul><li>Java 11</li><li>Spring Boot 2.x</li><li>Spring JPA 2.x</li><li>PostgreSQL</li><li>Maven</li></ul><h4>`point` Mapped TO `PGpoint`</h4><p>The official PostgreSQL library provides definitions of some special data that we can use directly in our projects.</p><p>For example`PGpoint.class`:</p><pre>public class PGpoint extends PGobject implements PGBinaryObject, Serializable, Cloneable {  <br>    public double x;  <br>    public double y;  <br>    public boolean isNull;  <br>}</pre><p>Then for columns of type point in Table, you can use `PGpoint` in Java Model Class:</p><pre>@Data  <br>@Entity  <br>@Table(name = &quot;cities&quot;)  <br>public class City implements Serializable {  <br>  <br>    @Id  <br>    @GeneratedValue(strategy = GenerationType.IDENTITY)  <br>    private Long id;  <br>  <br>    private String name;  <br>   <br>    private PGpoint location;  <br>}</pre><p>However, when querying the city data, an exception occurs:</p><pre>Caused by: org.hibernate.type.SerializationException: could not deserialize<br> at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:243) ~[hibernate-core-5.6.15.Final.jar:5.6.15.Final]<br> at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:287) ~[hibernate-core-5.6.15.Final.jar:5.6.15.Final]<br> at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:138) ~[hibernate-core-5.6.15.Final.jar:5.6.15.Final]<br> at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:113) ~[hibernate-core-5.6.15.Final.jar:5.6.15.Final]<br> at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:29) ~[hibernate-core-5.6.15.Final.jar:5.6.15.Final]<br> at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:60) ~[hibernate-core-5.6.15.Final.jar:5.6.15.Final]<br> at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47) ~[hibernate-core-5.6.15.Final.jar:5.6.15.Final]<br> at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257) ~[hibernate-core-5.6.15.Final.jar:5.6.15.Final]<br> at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253) ~[hibernate-core-5.6.15.Final.jar:5.6.15.Final]<br> at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:243) ~[hibernate-core-5.6.15.Final.jar:5.6.15.Final]<br> at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:329) ~[hibernate-core-5.6.15.Final.jar:5.6.15.Final]<br> at ...</pre><h4>Reason for Exception</h4><p>According to the StackCause of the above exception, it fails to deserialize the query result to a Java object. It&#39;s using the default <strong><em>AbstractStandardBasicType</em></strong> in <strong><em>Hibernate</em></strong> because there is no type implementation of PGpoint in BasicType, so it can’t do serialization and deserialization.</p><h4>How to fix this Exception</h4><p>Hibernate provides an interface for <strong><em>UserType</em></strong> user-defined types.<br>This interface should be implemented by user-defined “types”. A “type” class is _not_ the actual property type — it is a class that knows how to serialize instances of another class to and from JDBC.</p><p><strong>PGpointType</strong></p><pre>package com.example.demo;  <br>  <br>import org.hibernate.HibernateException;  <br>import org.hibernate.engine.spi.SharedSessionContractImplementor;  <br>import org.hibernate.usertype.UserType;  <br>import org.postgresql.geometric.PGpoint;  <br>import org.springframework.util.ObjectUtils;  <br>  <br>import java.io.Serializable;  <br>import java.sql.PreparedStatement;  <br>import java.sql.ResultSet;  <br>import java.sql.SQLException;  <br>import java.sql.Types;  <br>  <br>public class PGpointType implements UserType {  <br>  <br>    /**  <br>     * Return the SQL type codes for the columns mapped by this type.     <br>     * @return int[]  <br>     */<br>    @Override  <br>    public int[] sqlTypes() {  <br>        return new int[] {  <br>                Types.VARCHAR  <br>        };  <br>    }  <br>  <br>    /**  <br>     * The class returned by nullSafeGet().<br>     * @return Class  <br>     */<br>    @Override  <br>    public Class returnedClass() {  <br>        return PGpoint.class;  <br>    }  <br>  <br>    @Override  <br>    public boolean equals(Object o, Object o1) throws HibernateException {  <br>        return ObjectUtils.nullSafeEquals(o, o1);  <br>    }  <br>  <br>    @Override  <br>    public int hashCode(Object o) throws HibernateException {  <br>        return ObjectUtils.nullSafeHashCode(o);  <br>    }  <br>  <br>    /**  <br>     * Retrieve an instance of the mapped class from a JDBC resultset.<br>     */<br>    @Override  <br>    public Object nullSafeGet(ResultSet resultSet, String[] names, SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException, SQLException {  <br>        if (names.length == 1) {  <br>            if (resultSet.wasNull() || resultSet.getObject(names[0]) == null) {  <br>                return null;  <br>            } else {  <br>                return new PGpoint(resultSet.getObject(names[0]).toString());  <br>            }  <br>        }  <br>        return null;  <br>    }  <br>  <br>    /**  <br>     * Write an instance of the mapped class to a prepared statement.     <br>     */<br>    @Override  <br>    public void nullSafeSet(PreparedStatement preparedStatement, Object o, int i, SharedSessionContractImplementor sharedSessionContractImplementor) throws HibernateException, SQLException {  <br>        if (o == null) {  <br>            preparedStatement.setNull(i, Types.OTHER);  <br>        } else {  <br>            preparedStatement.setObject(i, o.toString(), Types.OTHER);  <br>        }  <br>    }  <br>  <br>    @Override  <br>    public Object deepCopy(Object o) throws HibernateException {  <br>        return o;  <br>    }  <br>  <br>    @Override  <br>    public boolean isMutable() {  <br>        return false;  <br>    }  <br>  <br>    @Override  <br>    public Serializable disassemble(Object o) throws HibernateException {  <br>        return (Serializable) o;  <br>    }  <br>  <br>    @Override  <br>    public Object assemble(Serializable serializable, Object o) throws HibernateException {  <br>        return serializable;  <br>    }  <br>  <br>    @Override  <br>    public Object replace(Object o, Object o1, Object o2) throws HibernateException {  <br>        return o;  <br>    }  <br>}</pre><h4>Conclusion</h4><p>The above is how to use the PostgreSQL <strong><em>point</em></strong> Data Type in a Spring Boot project, if there are other custom data types, you can also follow this way to implement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d74cc7f49734" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/how-to-map-postgresql-point-data-type-to-java-pgpoint-data-type-d74cc7f49734">How To Map PostgreSQL `point` Data Type To Java PGpoint Data Type?</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing an Email Delivery Service with Cloudflare Workers]]></title>
            <link>https://medium.com/@georgechmr/implementing-an-email-delivery-service-with-cloudflare-workers-c141422109d0?source=rss-3a8d32f50ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/c141422109d0</guid>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[George Chou]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 19:21:52 GMT</pubDate>
            <atom:updated>2024-02-24T19:21:52.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qlg-e_QZDSmN4rznDHBKaQ.jpeg" /><figcaption>Email Delivery</figcaption></figure><p>Without using the STMP server, without using three-party mail forwarding services, only through Cloudflare Workers and Email Routing, free to implement a mail delivery service.</p><p>Cloudflare Workers and Email Routing are both on a free plan, which is more than enough for individual users.</p><h4>Prepare</h4><p>Register for a Cloudflare account</p><h4>Enable Cloudflare Email Routing</h4><p>Refer to the <a href="https://developers.cloudflare.com/email-routing">official document</a> to enable it.</p><h4>Deploy Workers</h4><ol><li>clone/download <a href="https://github.com/alivefree/cf-email-workers">https://github.com/alivefree/cf-email-workers</a></li></ol><pre> import { Hono } from &quot;hono&quot;<br> import { cors } from &quot;hono/cors&quot;<br> import { EmailMessage } from &quot;cloudflare:email&quot;<br> import { createMimeMessage } from &quot;mimetext&quot;<br> <br> const worker = new Hono();<br><br> // cors <br> worker.use(&#39;*&#39;, (c, next) =&gt; {<br>   const origins = c.env.ALLOWED_ORIGINS == &#39;*&#39; ? &#39;*&#39; : c.env.ALLOWED_ORIGINS.split(&#39;,&#39;);<br>   const corsMiddleware = cors(origins);<br>   return corsMiddleware(c, next);<br> });<br><br> // Mail sending interface, can be modified to any api you want<br> worker.post(&#39;/send&#39;, async (c) =&gt; {<br>   const text = await c.req.text();<br>   const body = JSON.parse(text);<br>   if (!body[&#39;subject&#39;] || !body[&#39;body&#39;]) {<br>     c.status(400)<br>     return c.json({<br>         &quot;status&quot;: &quot;error&quot;,<br>         &quot;message&quot;: &quot;Missing subject or body&quot;<br>     })<br>   }<br> <br>   const msg = createMimeMessage()<br>   msg.setSender({ name: c.env.SENDER_NAME, addr: c.env.SENDER_ADDRESS })<br>   msg.setRecipient(c.env.RECIPIENT_ADDRESS)<br>   msg.setSubject(body[&#39;subject&#39;])<br>   msg.addMessage({<br>       contentType: &#39;text/html&#39;,<br>       data: body[&#39;body&#39;]<br>   })<br> <br>   var message = new EmailMessage(<br>       c.env.SENDER_ADDRESS,<br>       c.env.RECIPIENT_ADDRESS,<br>       msg.asRaw()<br>   );<br> <br>   try {<br>       // The SEB here comes from the send_email configuration in wrangler.toml<br>       await c.env.SEB.send(message)<br>   } catch (e) {<br>       c.status(500)<br>       return c.json({<br>           &quot;status&quot;: &quot;error&quot;,<br>           &quot;message&quot;: &quot;Email failed to send&quot;,<br>           &quot;error_details&quot;: e.message<br>       });<br>   }<br> <br>   return c.json({<br>       &quot;status&quot;: &quot;success&quot;,<br>       &quot;message&quot;: &quot;Email sent successfully&quot;<br>   });<br>   <br> });<br> <br> export default worker;</pre><p>2. Modifying Custom Configurations(<em>wrangler.toml</em>)</p><pre> # The name configuration here corresponds to c.env.SEB.send in the code, which needs to be synchronized.<br> send_email = [<br>     {type = &quot;send_email&quot;, name = &quot;SEB&quot;, destination_address = &quot;xxx&quot;},<br> ]<br> <br> [vars]<br> ALLOWED_ORIGINS = &quot;*&quot;<br> RECIPIENT_ADDRESS = &quot;*&quot;<br> SENDER_ADDRESS = &quot;*&quot;<br> SENDER_NAME = &quot;*&quot;</pre><p>3. deploy to Cloudflare Workers</p><pre>npm install -g wrangler<br>wrangler login<br>wrangler deploy</pre><h4>Call</h4><p>After successful deployment, you can call the API to send emails to other projects<br>API: worker domain/API</p><pre>fetch(&#39;https://example.workers.dev/send&#39;, {<br>  method: &#39;POST&#39;,<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;<br>  },<br>  body: JSON.stringify({<br>    subject: &#39;subject&#39;,<br>    body: &#39;email content&#39;<br>  })<br>})</pre><p>You can modify the content of the body to customize the email content and make it more aesthetically pleasing.</p><p>The Email Worker code deployed in this article has been opened on <a href="https://github.com/alivefree/cf-email-workers">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c141422109d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot + Hibernate + PostgreSQL Example]]></title>
            <link>https://medium.com/javarevisited/spring-boot-hibernate-postgresql-example-4e580ec2020b?source=rss-3a8d32f50ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e580ec2020b</guid>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[George Chou]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 00:24:33 GMT</pubDate>
            <atom:updated>2024-02-28T14:43:59.174Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*Zb9eyCj_jstgxEiG9W8NDA.png" /><figcaption>PostgreSQL</figcaption></figure><p>This tutorial will build a Spring Boot CRUD Rest API example with Maven that uses Spring Data JPA/Hibernate to interact with the PostgreSQL database.</p><p>You’ll know:</p><ul><li>How to configure Spring Data, JPA, and Hibernate to work with PostgreSQL Database</li><li>Way to use Spring Data JPA to interact with PostgreSQL Database</li></ul><h3>Technology</h3><ul><li>Java 11</li><li>Spring Boot 2.x</li><li>PostgreSQL</li><li>Maven</li></ul><h3>PostgreSQL Set up</h3><ol><li>Install PostgreSQL in Debian</li></ol><pre>sudo apt-get -y install postgresql</pre><p>The latter step requires that you first run the <em>psql</em> command.</p><p>2. Create a new DB</p><pre>createdb mydb</pre><p>3. Create a new user</p><pre>CREATE USER newuser WITH PASSWORD &#39;xxxxxx&#39;;</pre><p>4. Create Table</p><pre>CREATE TABLE weather (<br> id              serial primary key,<br>    city            varchar(80),<br>    temp_lo         int,           -- low temperature<br>    temp_hi         int,           -- high temperature<br>    prcp            real,          -- precipitation<br>    date            date,<br>    is_del          int default 0<br>);<br>ALTER TABLE weather OWNER TO newuser;<br><br>CREATE TABLE cities (<br>    id              serial primary key,<br>    name            varchar(80),<br>    location        point<br>);<br>ALTER TABLE cities OWNER TO newuser;</pre><p>Or, use my <a href="https://github.com/GeorgeCh2/spring-boot-postgresql/blob/main/test.sql">test.sql</a> initial Table:</p><pre>mydb=&gt; \i test.sql</pre><h3>Create Spring Boot Project</h3><p>Use <a href="https://start.spring.io/">Spring Initializr</a> to create a Maven Spring Boot Project<br>Add some dependencies to `pom.xml`:</p><pre>&lt;dependency&gt;  <br>    &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;  <br>    &lt;artifactId&gt;lombok&lt;/artifactId&gt;  <br>    &lt;scope&gt;provided&lt;/scope&gt;  <br>&lt;/dependency&gt;  <br>  <br>&lt;dependency&gt;  <br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;  <br>    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;  <br>&lt;/dependency&gt;  <br>  <br>&lt;dependency&gt;  <br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;  <br>    &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;  <br>&lt;/dependency&gt;  <br>  <br>&lt;dependency&gt;  <br>    &lt;groupId&gt;org.postgresql&lt;/groupId&gt;  <br>    &lt;artifactId&gt;postgresql&lt;/artifactId&gt;  <br>&lt;/dependency&gt;  <br>  <br>&lt;dependency&gt;  <br>    &lt;groupId&gt;javax.persistence&lt;/groupId&gt;  <br>    &lt;artifactId&gt;javax.persistence-api&lt;/artifactId&gt;  <br>&lt;/dependency&gt;</pre><h4>PostgreSQL Configuration</h4><pre>spring.datasource.url=jdbc:postgresql://localhost:5432/mydb  <br>spring.datasource.username=newuser  <br>spring.datasource.password=xxxxxx <br>  <br># connection timeout  <br>spring.datasource.hikari.connection-timeout=20000  <br># min idle connections  <br>spring.datasource.hikari.minimum-idle=5  <br># max pool size  <br>spring.datasource.hikari.maximum-pool-size=12  <br>spring.datasource.hikari.idle-timeout=300000  <br>spring.datasource.hikari.max-lifetime=1200000  <br>spring.datasource.hikari.auto-commit=true</pre><p>For production environments, a single database connection is not enough to solve the real demand, so we need to configure the connection pool here.<br>By default, <em>jpa-data</em> uses <em>hikari</em> connection pooling, so it only needs to be configured in the <em>application.properties</em> file, no other dependencies are needed.</p><h4>Define Model Class</h4><p><strong>Weather.java</strong></p><pre>package com.example.demo.model;  <br>  <br>  <br>import lombok.Data;  <br>  <br>import javax.persistence.*;  <br>import java.io.Serializable;  <br>import java.time.LocalDate;  <br>  <br>@Data  <br>@Entity  <br>@Table(name = &quot;weather&quot;)  <br>public class Weather implements Serializable {  <br>  <br>    @Id  <br>    @GeneratedValue(strategy = GenerationType.IDENTITY)  <br>    private Long id;  <br>  <br>    private String city;  <br>  <br>    private Integer temp_hi;  <br>  <br>    private Integer temp_lo;  <br>  <br>    private Float prcp;  <br>  <br>    private Integer is_del;  <br>  <br>    private LocalDate date;  <br>}</pre><p><strong>City.java</strong></p><pre>package com.example.demo.model;  <br>  <br>import com.example.demo.PGpointType;  <br>import org.hibernate.annotations.Type;  <br>import org.hibernate.annotations.TypeDef;  <br>import org.postgresql.geometric.PGpoint;  <br>import lombok.Data;  <br>  <br>import javax.persistence.*;  <br>import java.io.Serializable;  <br>  <br>@Data  <br>@Entity  <br>@TypeDef(name = &quot;point&quot;, typeClass = PGpointType.class)  <br>@Table(name = &quot;cities&quot;)  <br>public class City implements Serializable {  <br>  <br>    @Id  <br>    @GeneratedValue(strategy = GenerationType.IDENTITY)  <br>    private Long id;  <br>  <br>    private String name;  <br>  <br>    @Type(type = &quot;point&quot;)  <br>    private PGpoint location;  <br>}</pre><ul><li>For auto increment id, you need to use `GeneratedValue` annotate, and the user `IDENTITY` strategy</li><li>Because in hibernate, its do not support PGpoint data type, need to create a customer `PGpointType` Class</li></ul><h4>Create Repository Interface</h4><pre>package com.example.demo.repository;  <br>  <br>import com.example.demo.model.Weather;  <br>import org.springframework.data.domain.Pageable;  <br>import org.springframework.data.jpa.repository.JpaRepository;  <br>import org.springframework.data.jpa.repository.Query;  <br>import org.springframework.data.repository.query.Param;  <br>  <br>import java.util.List;  <br>  <br>public interface WeatherRepository extends JpaRepository&lt;Weather, Long&gt; {  <br>  <br>    @Query(&quot;SELECT w FROM Weather w &quot; +  <br>            &quot; WHERE (:city is NULL OR :city = &#39;&#39; OR w.city = :city)&quot; +  <br>            &quot; AND w.is_del = 0&quot;)  <br>    List&lt;Weather&gt; listWeather(@Param(&quot;city&quot;) String city, Pageable pageable);  <br>}</pre><p>If use `<em>SELECT id, city, temp_hi, temp_lo, prcp, is_del, date FROM weather</em>`, the result will be `<em>Object[]</em>`, can’t convert to `<em>Weather.class</em>`, So I use `<em>SELECT w FROM Weather w`</em></p><h4>Create Controller &amp; Service</h4><p><strong>Controller</strong></p><pre>@RestController  <br>@RequestMapping(&quot;/api&quot;)  <br>public class DemoController {<br> @Autowired  <br> private DemoService demoService;<br> //...<br>}</pre><pre>@Service  <br>public class DemoService {  <br>  <br>    @Autowired  <br>    private WeatherRepository weatherRepository;  <br>  <br>    @Autowired  <br>    private CityRepository cityRepository;<br> <br> //...<br>}</pre><h4>Api Test</h4><p>Import <a href="https://github.com/GeorgeCh2/spring-boot-postgresql/blob/main/postgresql-rest-api.json">api-test.json</a> to Postman for API test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*lSjgN9uAKOOdfbR-0Fac9g.png" /></figure><h3>Conclusion</h3><p>Above are the steps for building a Spring Boot + Hibernate + PostgreSQL example with REST API.</p><p>The Source is open on <a href="https://github.com/GeorgeCh2/spring-boot-postgresql">Github</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e580ec2020b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/spring-boot-hibernate-postgresql-example-4e580ec2020b">Spring Boot + Hibernate + PostgreSQL Example</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why can’t the Lists created by Arrays.asList() and Collections.singletonList() add elements?]]></title>
            <link>https://medium.com/javarevisited/why-cant-the-lists-created-by-arrays-aslist-and-collections-singletonlist-add-elements-e9cbc78b368f?source=rss-3a8d32f50ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9cbc78b368f</guid>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[collections-in-java]]></category>
            <category><![CDATA[collection]]></category>
            <dc:creator><![CDATA[George Chou]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 16:34:13 GMT</pubDate>
            <atom:updated>2024-02-28T14:43:57.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xSgZOsT4t0ZYtKs70y6bUA.jpeg" /></figure><h3>UnsupportedOperationException</h3><p>List collections created by <em>Arrays.asList()</em> and <em>Collections.singletonList()</em> cannot call their add method (<strong>ImmutableList</strong>) or an <strong>UnsupportedOperationException</strong> will be reported.</p><h4>Arrays.asList()</h4><pre>List&lt;Integer&gt; list = Arrays.asList(1, 2, 3); <br>list.add(4);</pre><h4>Collections.singletonList()</h4><pre>List&lt;Integer&gt; list = Collections.singletonList(1); <br>list.add(2);</pre><p>Throw an exception:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gA_C1-KQnpbrtADb6nWMkg.png" /></figure><h3>Reason</h3><p>As you can see from the exception stack above, both are calling the <em>AbstractList.add()</em> method, which causes an exception.<br>Let’s take a look at the implementation of Arrays and Collections:</p><h4>Arrays</h4><p>Implementation of asList(T..a)：</p><pre>@SafeVarargs <br>@SuppressWarnings(&quot;varargs&quot;) <br>public static &lt;T&gt; List&lt;T&gt; asList(T… a) { <br> return new ArrayList&lt;&gt;(a); <br>}</pre><p>An ArrayList object is constructed, but here <em>ArrayList</em> belongs to the inner class of Arrays, not <em>java.util.ArrayList</em>.</p><p>Since <em>Arrays#ArrayList</em> does not implement the <em>add(E e)</em> method, it can only call the <em>add</em> method of its parent class <em>AbstractList</em>.</p><p>Let’s look at Collections</p><h4>Collections</h4><p>Implementation of singletonList(T o)：</p><pre>public static &lt;T&gt; List&lt;T&gt; singletonList(T o) { <br> return new SingletonList&lt;&gt;(o); <br>}</pre><p>A <em>SingletonList</em> object is constructed, which also does not implement the <em>add(E e)</em> method, and needs to call the `add` method of the parent class <em>AbstractList</em>.<br>As you can see from the previous <strong>UnsupportedOperationException</strong>, which was thrown from the <em>AbstractList.add(E e)</em> method, let’s take a look at the implementation of this parent method:</p><h4>AbstractList.add(E e)</h4><pre>public boolean add(E e) { <br> add(size(), e); <br> return true;<br>}</pre><p>add(int index, E element):</p><pre>public void add(int index, E element) { <br> throw new UnsupportedOperationException(); <br>}</pre><p>As you can see here the exception is thrown directly and needs to be reimplemented by subclass inheritance</p><h3>How to fix it</h3><p>Before the add, use `new ArrayList` to reconstruct a new List.</p><pre>List&lt;Integer&gt; list = Collections.singletonList(1); <br>list = new ArrayList&lt;&gt;(list); <br>list.add(2);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9cbc78b368f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/why-cant-the-lists-created-by-arrays-aslist-and-collections-singletonlist-add-elements-e9cbc78b368f">Why can’t the Lists created by Arrays.asList() and Collections.singletonList() add elements?</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Unique ID(Java Version)]]></title>
            <link>https://medium.com/javarevisited/distributed-unique-id-java-version-e74ee36d23bd?source=rss-3a8d32f50ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/e74ee36d23bd</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[George Chou]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 21:13:26 GMT</pubDate>
            <atom:updated>2024-02-28T14:43:55.417Z</atom:updated>
            <content:encoded><![CDATA[<p>In distributed systems, some scenarios require the use of globally unique IDs, both as business identifiers and to satisfy the idempotency design of interfaces. <br>In the case of a single table, we can directly use the database’s self-incremented ID, but after the library and table can not meet the demand, we need to find ways to achieve this through other means.</p><p>For a globally unique ID, the characteristics needed are:</p><ul><li>Globally unique</li><li>Incremental</li><li>Highly available</li><li>Autonomous</li><li>Security (will not be exposed)</li></ul><h3>Database AUTO_INCREMENT id</h3><h4>Implementation</h4><p>1. Use the MySQL database’s AUTO_INCREMENT id feature to get a sequence.<br> 2. When the server gets the sequence, it sets a threshold of `max=sequence * step`.<br> 3. Immediately after obtaining an ID, it is accumulated until it reaches the maximum threshold.</p><pre>private static final Long STEP = 1000L;<br><br>private Long curId = 0L;<br><br>public synchronized Long generateId() {  <br>    if (curId &gt;= max) {  <br>        Sequence sequence = new Sequence();  <br>        mapper.sequence(sequence);  <br>        curId = sequence.getId();  <br>  <br>        max = id * STEP;;  <br>    }  <br>  <br>    return curId++;  <br>}</pre><p><strong>Pros</strong></p><ul><li>id incremental</li><li>simple to implement</li></ul><p><strong>Cons</strong></p><ul><li>Database dependency required</li><li>Server reboot will lead to id discontinuity</li></ul><h3>UUID</h3><h4>Implementation</h4><pre>UUID uuid = UUID.randomUUID();<br>String uuidAsString = uuid.toString();</pre><p><strong>Pros</strong></p><ul><li>No need to rely on middleware or third-party services can be generated independently</li><li>Highly concurrent</li><li>There are implementation libraries for each language that can be used directly</li></ul><p><strong>Cons</strong></p><ul><li>String storage, space-consuming, poor DB query, and indexing efficiency.</li><li>Not self-incrementing IDs, poor readability.</li><li>Different implementations may leak information</li></ul><h3>Redis</h3><h4>Implementation</h4><p>Use incr or increby to generate IDs using the single-threaded nature of Redis.</p><p><strong>Dependency</strong></p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;<br>    &lt;version&gt;2.7.2&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p><strong>Java Configuration</strong></p><pre>@Bean<br>JedisConnectionFactory jedisConnectionFactory() {<br>    JedisConnectionFactory jedisConFactory = new JedisConnectionFactory();<br>    jedisConFactory.setHostName(&quot;localhost&quot;); <br>    jedisConFactory.setPort(6379); <br>    return jedisConFactory;<br>}<br><br>@Bean<br>public RedisTemplate&lt;String, Object&gt; redisTemplate() {<br>    RedisTemplate&lt;String, Object&gt; template = new RedisTemplate&lt;&gt;();<br>    template.setConnectionFactory(jedisConnectionFactory());<br>    return template;<br>}</pre><p><strong>Generate Id</strong></p><pre>@Autowired<br>private RedisTemplate&lt;String, Object&gt; redisTemplate;<br><br>private static final String ID_KEY = &quot;key:id&quot;;<br><br>public Long generateId() {<br> if (!redisTemplate.hasKey(ID_KEY)) {<br>  redisTemplate.opsForValue().set(ID_KEY, 0);<br> }<br> <br> return redisTemplate.opsForValue().increment(ID_KEY, 1);<br>}</pre><p><strong>Pros</strong></p><ul><li>Much better performance than databases</li><li>Can be deployed in clusters</li><li>Generated IDs can have time information</li></ul><p><strong>Cons</strong></p><ul><li>Requires the introduction of middleware, which increases the complexity of the system</li><li>The service that sends the IDs is also a single point.</li></ul><h3>Twitter Snowflake</h3><p><a href="https://github.com/twitter/snowflake/tree/snowflake-2010">Twitter Snowflake</a> is a dedicated network service for generating 64-bit unique IDs at high scale. The IDs generated by this service are roughly time-sorted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ziZQGfPFyXZirqXSsdXN-Q.png" /></figure><p>The IDs are made up of the following components:</p><ul><li>Epoch timestamp in millisecond precision — 41 bits (gives us 69 years with a custom epoch)</li><li>Configured machine ID — 10 bits (gives us up to 1024 machines)</li><li>Sequence number — 12 bits (A local counter per machine that rolls over every 4096)</li></ul><p><strong>Implementation</strong><br>Here is the Java version of the snowflake, from <a href="https://github.com/callicoder/java-snowflake">github</a>.</p><pre>import java.net.NetworkInterface;<br>import java.security.SecureRandom;<br>import java.time.Instant;<br>import java.util.Enumeration;<br><br>/**<br> * Distributed Sequence Generator.<br> * Inspired by Twitter snowflake: https://github.com/twitter/snowflake/tree/snowflake-2010<br> *<br> * This class should be used as a Singleton.<br> * Make sure that you create and reuse a Single instance of Snowflake per node in your distributed system cluster.<br> */<br>public class Snowflake {<br>    private static final int UNUSED_BITS = 1; // Sign bit, Unused (always set to 0)<br>    private static final int EPOCH_BITS = 41;<br>    private static final int NODE_ID_BITS = 10;<br>    private static final int SEQUENCE_BITS = 12;<br><br>    private static final long maxNodeId = (1L &lt;&lt; NODE_ID_BITS) - 1;<br>    private static final long maxSequence = (1L &lt;&lt; SEQUENCE_BITS) - 1;<br><br>    // Custom Epoch (January 1, 2015 Midnight UTC = 2015-01-01T00:00:00Z)<br>    private static final long DEFAULT_CUSTOM_EPOCH = 1420070400000L;<br><br>    private final long nodeId;<br>    private final long customEpoch;<br><br>    private volatile long lastTimestamp = -1L;<br>    private volatile long sequence = 0L;<br><br>    // Create Snowflake with a nodeId and custom epoch<br>    public Snowflake(long nodeId, long customEpoch) {<br>        if(nodeId &lt; 0 || nodeId &gt; maxNodeId) {<br>            throw new IllegalArgumentException(String.format(&quot;NodeId must be between %d and %d&quot;, 0, maxNodeId));<br>        }<br>        this.nodeId = nodeId;<br>        this.customEpoch = customEpoch;<br>    }<br><br>    // Create Snowflake with a nodeId<br>    public Snowflake(long nodeId) {<br>        this(nodeId, DEFAULT_CUSTOM_EPOCH);<br>    }<br><br>    // Let Snowflake generate a nodeId<br>    public Snowflake() {<br>        this.nodeId = createNodeId();<br>        this.customEpoch = DEFAULT_CUSTOM_EPOCH;<br>    }<br><br>    public synchronized long nextId() {<br>        long currentTimestamp = timestamp();<br><br>        if(currentTimestamp &lt; lastTimestamp) {<br>            throw new IllegalStateException(&quot;Invalid System Clock!&quot;);<br>        }<br><br>        if (currentTimestamp == lastTimestamp) {<br>            sequence = (sequence + 1) &amp; maxSequence;<br>            if(sequence == 0) {<br>                // Sequence Exhausted, wait till next millisecond.<br>                currentTimestamp = waitNextMillis(currentTimestamp);<br>            }<br>        } else {<br>            // reset sequence to start with zero for the next millisecond<br>            sequence = 0;<br>        }<br><br>        lastTimestamp = currentTimestamp;<br><br>        long id = currentTimestamp &lt;&lt; (NODE_ID_BITS + SEQUENCE_BITS)<br>                | (nodeId &lt;&lt; SEQUENCE_BITS)<br>                | sequence;<br><br>        return id;<br>    }<br><br><br>    // Get current timestamp in milliseconds, adjust for the custom epoch.<br>    private long timestamp() {<br>        return Instant.now().toEpochMilli() - customEpoch;<br>    }<br><br>    // Block and wait till next millisecond<br>    private long waitNextMillis(long currentTimestamp) {<br>        while (currentTimestamp == lastTimestamp) {<br>            currentTimestamp = timestamp();<br>        }<br>        return currentTimestamp;<br>    }<br><br>    private long createNodeId() {<br>        long nodeId;<br>        try {<br>            StringBuilder sb = new StringBuilder();<br>            Enumeration&lt;NetworkInterface&gt; networkInterfaces = NetworkInterface.getNetworkInterfaces();<br>            while (networkInterfaces.hasMoreElements()) {<br>                NetworkInterface networkInterface = networkInterfaces.nextElement();<br>                byte[] mac = networkInterface.getHardwareAddress();<br>                if (mac != null) {<br>                    for(byte macPort: mac) {<br>                        sb.append(String.format(&quot;%02X&quot;, macPort));<br>                    }<br>                }<br>            }<br>            nodeId = sb.toString().hashCode();<br>        } catch (Exception ex) {<br>            nodeId = (new SecureRandom().nextInt());<br>        }<br>        nodeId = nodeId &amp; maxNodeId;<br>        return nodeId;<br>    }<br><br>    public long[] parse(long id) {<br>        long maskNodeId = ((1L &lt;&lt; NODE_ID_BITS) - 1) &lt;&lt; SEQUENCE_BITS;<br>        long maskSequence = (1L &lt;&lt; SEQUENCE_BITS) - 1;<br><br>        long timestamp = (id &gt;&gt; (NODE_ID_BITS + SEQUENCE_BITS)) + customEpoch;<br>        long nodeId = (id &amp; maskNodeId) &gt;&gt; SEQUENCE_BITS;<br>        long sequence = id &amp; maskSequence;<br><br>        return new long[]{timestamp, nodeId, sequence};<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Snowflake Settings [EPOCH_BITS=&quot; + EPOCH_BITS + &quot;, NODE_ID_BITS=&quot; + NODE_ID_BITS<br>                + &quot;, SEQUENCE_BITS=&quot; + SEQUENCE_BITS + &quot;, CUSTOM_EPOCH=&quot; + customEpoch<br>                + &quot;, NodeId=&quot; + nodeId + &quot;]&quot;;<br>    }<br>}</pre><p><strong>Pros</strong></p><ul><li>Local generation, no network consumption, no need to introduce middleware</li><li>Highly concurrent</li><li>Contains time information</li></ul><p><strong>Cons</strong></p><ul><li>Depending on the machine clock, there is a risk of duplicate IDs being generated for the same machine if the time is dialed back</li></ul><p>These schemes do not satisfy all the global ID characteristics, just like the CAP characteristics of a distributed system, we can only try to satisfy as many of them as possible.</p><p><strong><em>There is no best solution, only the most suitable one.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e74ee36d23bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/distributed-unique-id-java-version-e74ee36d23bd">Distributed Unique ID(Java Version)</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Skipping black frame when generating video thumbnail with FFmpeg]]></title>
            <link>https://medium.com/@georgechmr/skipping-black-frame-when-generating-video-thumbnail-with-ffmpeg-9e26bf2f67e3?source=rss-3a8d32f50ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e26bf2f67e3</guid>
            <category><![CDATA[ffmpeg]]></category>
            <category><![CDATA[thumbnail]]></category>
            <category><![CDATA[videos]]></category>
            <dc:creator><![CDATA[George Chou]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 17:02:22 GMT</pubDate>
            <atom:updated>2023-11-26T17:02:22.453Z</atom:updated>
            <content:encoded><![CDATA[<p>In some video websites, a preview image is shown before the video is played, this preview image is called thumbnail, by default the first frame of the video is taken as the thumbnail.</p><p>In this article, I’ll show how to generate a video thumbnail using the FFmpeg command line and skip the black frame.</p><h4>What is FFmpeg</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vuvG3go6v8FPb1-h_qV-sA.png" /><figcaption>FFmpeg</figcaption></figure><p>FFmpeg is a complete, cross-platform solution to record, convert, and stream audio and video. It can decode, encode, transcode, mux, demux, stream, filter, and play pretty much any media file in any format. It is also highly portable as it compiles and runs in a wide variety of build environments, machine architectures, and configurations like Linux, Mac OS X, Microsoft Windows, etc.</p><p>It contains multiple tools for end-users to convert, play, and analyze media files and libraries for developers to use in different applications. In this tutorial, we will be using the FFmpeg command-line tool.</p><h4>Generating a Thumbnail from the Video</h4><p>The basic command to capture a frame from the video using FFmpeg is:</p><pre>ffmpeg -i input.mp4 -frames:v 1 screenshot.png</pre><p>The command above will capture the first frame of the video.</p><p>Normally, we wouldn’t want to use the first frame of a video as the thumbnail as it might be a black screen or something insignificant.</p><h4>Skip black frame</h4><p>The filter in FFmpeg supports filtering black frames.</p><pre>ffmpeg -ss 0 -i input.mp4 -vframes 1 -f image2 -vf &quot;blackframe=0,metadata=select:key=lavfi.blackframe.pblack:value=50:function=less&quot; out.jpg</pre><ul><li>blackframe to get infromation about the percentage of black pixels in all video frames</li><li>metadata filters out video frames with more than 50% black pixels</li></ul><p><strong>blackframe</strong></p><p>Determine the black frame, the output includes index of the frame, percentage of black pixels, offset in the file, timestamp, frame type, index of the last keyframe.</p><p><strong>metadata</strong></p><p>Processing frame metadata.</p><p>Parameters:</p><p><strong>mode</strong></p><ul><li>select: if both key and value are set, rotate matching frames. If only the kye is set, select the frames that contain the key in the metadata</li><li>add</li><li>modify</li><li>delete</li><li>print</li></ul><p><strong>key</strong></p><p><strong>value</strong></p><p><strong>function</strong></p><p>For comparing value values in metadata</p><ul><li>same_str</li><li>starts_with</li><li>less</li><li>equal</li><li>greater</li><li>expr</li></ul><p>So, how to filter frames with less than 50% of black pixels:</p><pre>metadata=select:key=lavfi.blackframe.pblack:value=50:function=less</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e26bf2f67e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>