Skip to content

Home

Registering Sling Servlets in Adobe Experience Manager

In Adobe Experience Manager (AEM), a Sling servlet can be utilized to handle certain RESTful request-response AJAX calls. Written in the Java programming language, these servlets can be registered as OSGi (Open Services Gateway Initiative) services. There are two methods to register a servlet in AEM: 1) By Path, and 2) By resourceType. Details for both are explained below:

1. Register by Path

For instance, if you want to execute a form POST request to the path /bin/payment from the client-side to the Sling servlet class, you can use the annotation below:

@SlingServlet(
    metatype = true,
    methods = { "POST" },
    paths = "/bin/payment"
)
public class YourServlet extends SlingSafeMethodsServlet {

    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException {
        // Perform your tasks here
    }
}

When there's a POST request to http://localhost:4502/bin/payment, the servlet will be triggered, and the doPost method will be invoked.

Prerequisites include having a local AEM instance up and running on port 4502 and installing the bundle module via the Maven bundle plugin. You can verify the installation of the bundle by navigating to http://localhost:4502/system/console/bundles. If it's not installed, you can manually upload the JAR file.

If you encounter a "forbidden" error and cannot serve the request to /bin/payment, follow these steps:

  1. Go to http://localhost:4502/system/console/configMgr.
  2. Search for 'Apache Sling Referrer Filter'.
  3. Remove the POST method from the filter. This will allow you to trigger the POST method from any source.
  4. Locate Adobe Granite CSRF Filter.
  5. Remove POST from the filter methods.
  6. Save the changes and test the servlet again.

The servlet should now trigger as expected.

2. Register by resourceType

To avoid the issues mentioned above, a better approach is to register the servlet by resourceType. Refactor the servlet as follows:

@SlingServlet(
    metatype = true,
    methods = { "POST" },
    resourceTypes = "services/payment"
)
public class YourServlet extends SlingSafeMethodsServlet {

    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException {
        // Perform your tasks here
    }
}

Next, you'll need to create a page to trigger this resource:

  1. Go to CRXDE Lite at http://localhost:4502/crx/de/index.jsp.
  2. Inside the /content folder, create a page (e.g., http://localhost:4502/content/submitPage.html).
  3. In the resourceType properties, enter services/payment or whatever matches your servlet above.
  4. Save your changes and test the POST request to http://localhost:4502/content/submitPage.html. It should work as expected.

Extra Tips: You can also use the Apache Sling Resource Resolver to verify if the servlet has been registered successfully at http://localhost:4502/system/console/jcrresolver.

Feel free to leave any questions in the comments below.

Registering Sling Servlets in Adobe Experience Manager

Hello, and welcome to "Continuous Improvement," the podcast that provides tips, insights, and strategies for enhancing your skills in software development. I'm your host, Victor.

In today's episode, we'll dive into the world of Adobe Experience Manager and explore how to handle RESTful request-response AJAX calls using Sling servlets. We'll discuss two methods to register these servlets in AEM - by path and by resourceType. So, let's get started!

Sling servlets, written in Java, are designed to handle specific AJAX calls within AEM applications. They can be registered as OSGi services and are useful for executing various tasks based on incoming requests.

Let's begin with the first method - registering a servlet by path. Imagine you want to handle a form POST request at the path /bin/payment. To do this, you'll need to annotate your servlet class using the following code:

[Code Mention]

This annotation ensures that your servlet is triggered when a POST request is sent to http://localhost:4502/bin/payment. The doPost method within the servlet class will be invoked, allowing you to perform your desired tasks.

It's important to have a local AEM instance running on port 4502 and install the bundle module using the Maven bundle plugin before registering your servlet. You can check if the bundle is installed by navigating to http://localhost:4502/system/console/bundles. If it's not installed, you can manually upload the JAR file.

Now, what happens if you encounter a "forbidden" error when trying to serve a request to /bin/payment? Don't worry; I've got you covered!

Here's what you can do:

  1. Go to http://localhost:4502/system/console/configMgr.
  2. Search for 'Apache Sling Referrer Filter'.
  3. Remove the POST method from the filter. This step allows triggering the POST method from any source.
  4. Locate Adobe Granite CSRF Filter.
  5. Remove the POST method from the filter methods as well.
  6. Save the changes and give your servlet another try.

By following these steps, you should be able to resolve the "forbidden" error and successfully trigger your servlet.

Now, let's move on to the second method - registering a servlet by resourceType. This approach is more flexible and avoids the aforementioned issues. Here's how you can do it:

[Code Mention]

Refactor your servlet by using this annotation and specify the desired resourceType. For example, services/payment or any other resourceType that matches your servlet. This way, your servlet will be triggered by requests to pages with the specified resourceType.

To test your servlet, you'll need to create a page that triggers its resourceType:

  1. Go to CRXDE Lite at http://localhost:4502/crx/de/index.jsp.
  2. Inside the /content folder, create a page, for example, http://localhost:4502/content/submitPage.html.
  3. In the resourceType properties, enter services/payment or the corresponding resourceType from your servlet.
  4. Save your changes and test the POST request by visiting http://localhost:4502/content/submitPage.html. It should work as expected.

An extra tip for you! You can use the Apache Sling Resource Resolver at http://localhost:4502/system/console/jcrresolver to verify if your servlet has been successfully registered.

And that wraps up today's episode of "Continuous Improvement." We explored the world of Sling servlets in Adobe Experience Manager, discussing how to register them by both path and resourceType.

Thank you for joining me, Victor, your host, on this journey of continuous improvement. I hope you found today's episode valuable in expanding your skills as a software developer.

If you have any questions or comments, feel free to reach out in the comments section of the associated blog post.

Don't forget to subscribe to "Continuous Improvement" for more insightful episodes and updates. Until next time, keep striving for excellence and embracing the world of continuous improvement.

在Adobe Experience Manager中註冊Sling Servlets

在Adobe Experience Manager (AEM) 中,Sling servlet可以被用來處理某些RESTful的請求-回應的AJAX調用。寫在Java編程語言中的Servlets可以被註冊為OSGi(開放服務網關協議)服務。在AEM中註冊servlet有兩種方法:1) 通過路徑,和 2) 通過資源類型。以下是兩種方法的詳細說明:

1. 通過路徑註冊

例如,如果您希望從客戶端發送一個表單POST請求到路徑/bin/payment 到Sling servlet類,您可以使用以下的註解:

@SlingServlet(
    metatype = true,
    methods = { "POST" },
    paths = "/bin/payment"
)
public class YourServlet extends SlingSafeMethodsServlet {

    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException {
        // 在這裡執行你的任務
    }
}

當有一個POST請求到 http://localhost:4502/bin/payment 時,servlet將被觸發,並調用 doPost 方法。

前提條件包括在端口4502上運行本地AEM實例,並通過Maven Bundle插件安裝bundle模組。您可以通過導航到 http://localhost:4502/system/console/bundles來驗證bundle的安裝。如果沒有安裝,您可以手動上傳JAR文件。

如果您遭遇“禁止”的錯誤,無法服務 /bin/payment 的請求,請按照以下步驟操作:

  1. 轉到 http://localhost:4502/system/console/configMgr
  2. 搜索 'Apache Sling Referrer Filter'。
  3. 從篩選器中刪除POST方法。這將允許您從任何來源觸發POST方法。
  4. 搜索Adobe Granite CSRF Filter。
  5. 從篩選方法中刪除POST。
  6. 保存更改並再次測試servlet。

Servlet現在應該按預期觸發。

2. 通過資源類型註冊

為了避免上述問題,更好的方法是通過資源類型註冊servlet。重構servlet如下:

@SlingServlet(
    metatype = true,
    methods = { "POST" },
    resourceTypes = "services/payment"
)
public class YourServlet extends SlingSafeMethodsServlet {

    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException {
        // 在這裡執行你的任務
    }
}

接下來,您需要創建一個頁面來觸發此資源:

  1. 轉到 http://localhost:4502/crx/de/index.jsp的CRXDE Lite。
  2. /content資料夾內,創建一個頁面(例如,http://localhost:4502/content/submitPage.html)。
  3. 在resourceType屬性中,輸入 services/payment 或其他匹配您上述的servlet。
  4. 保存更改並測試POST請求到 http://localhost:4502/content/submitPage.html。 應該可以按预期工作。

額外提示: 您也可以使用Apache Sling Resource Resolver來驗證servlet是否已成功註冊在http://localhost:4502/system/console/jcrresolver

如果有任何問題,可以在下面的評論中留言。

Installing Nextcloud on AWS EC2 with S3 Storage

In an effort to enhance my privacy, I've decided to minimize the use of Google products. I've replaced Chrome with Firefox, switched from Gmail to ProtonMail, and am now using Nextcloud instead of Google Drive. Nextcloud allows for self-hosting of cloud storage and provides control over my own data. Below are the steps to install Nextcloud on AWS EC2 and configure it to use S3 storage.

  1. Install Nextcloud using the Snap package manager:
sudo snap install nextcloud
  1. Create an admin user account:
sudo nextcloud.manual-install <admin_username> <admin_password>
  1. Add your trusted domain:
sudo nextcloud.occ config:system:set trusted_domains 1 --value=<your-domain>
  1. Using AWS Route 53, create an A record that points to the IP address of your Nextcloud server.

  2. Set up an SSL certificate with Let's Encrypt:

sudo nextcloud.enable-https lets-encrypt

  1. Navigate to your domain, and you should now be able to log in to your Nextcloud instance.

  1. Click on "Apps" and enable "Default encryption module" and "External storage support."

  2. Open AWS IAM (Identity and Access Management) and create a new user with programmatic access.

  3. Create a new policy using the JSON code below, replacing NAMEOFYOURBUCKET with the name of your S3 bucket. Attach this policy to the newly created user.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:GetBucketLocation", "s3:ListAllMyBuckets"],
      "Resource": "arn:aws:s3:::*"
    },
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::NAMEOFYOURBUCKET",
        "arn:aws:s3:::NAMEOFYOURBUCKET/*"
      ]
    }
  ]
}
  1. In Nextcloud settings, select "External Storage." Fill in the "Bucket" field with NAMEOFYOURBUCKET. Check "Enable SSL" and "Enable Path Style," then fill in the required information using the credentials of the user you created.

  2. You're done! Navigate to your d3 folder, and you should now be able to upload files.

Installing Nextcloud on AWS EC2 with S3 Storage

Welcome to another episode of Continuous Improvement! I'm your host, Victor, and today we're diving into the world of privacy and data control. In a recent blog post, I shared my journey of minimizing the use of Google products and opting for alternatives that provide more control over our personal data. One of the key changes I made was switching from Google Drive to Nextcloud, a self-hosted cloud storage solution. So, if you're interested in learning how to install Nextcloud on AWS EC2 and configuring it to use S3 storage, you're in the right place! Let's get started.

The first step is to install Nextcloud, and to do that, we'll be using the Snap package manager. Open your terminal and enter the command: sudo snap install nextcloud. This will initiate the installation process. Once completed, move on to the next step.

Now that we have Nextcloud installed, let's create an admin user account. In your terminal, simply type: sudo nextcloud.manual-install, followed by your desired username and password. Make sure to remember these login credentials!

With our admin account set up, we need to add our trusted domain. This allows Nextcloud to verify incoming requests from a specific domain. In your terminal, execute the command: sudo nextcloud.occ config:system:set trusted_domains 1 --value=. Remember to replace with your actual domain.

Next, we need to create an A record on AWS Route 53 that points to the IP address of our Nextcloud server. This ensures that when we navigate to our domain, it will correctly link to our Nextcloud instance.

Security is important, so let's set up an SSL certificate with Let's Encrypt to enable secure communication between our Nextcloud server and clients. In your terminal, type: sudo nextcloud.enable-https lets-encrypt. This will initiate the SSL certificate creation process and ensure that your data remains encrypted.

Now, it's time to put our setup to the test. Open your browser and navigate to your domain. You should now see the Nextcloud login page. Enter your admin username and password that we set up earlier, and voila! You're now logged in to your Nextcloud instance.

To enhance the functionality of Nextcloud, we can enable some useful apps. In your Nextcloud dashboard, click on "Apps" and enable both the "Default encryption module" and "External storage support." These additions will provide added security and allow us to integrate external storage options.

Speaking of external storage, let's set up Nextcloud to use S3 storage on AWS. We'll start by creating a new user with programmatic access in the AWS Identity and Access Management (IAM) console. This will generate a set of access keys that we'll need later.

After creating the user, it's time to define a policy that grants our Nextcloud instance access to the S3 bucket. In your IAM console, create a new policy using the provided JSON code in our blog post. Replace NAMEOFYOURBUCKET with the name of your S3 bucket and attach this policy to the newly created user.

Now that our AWS setup is complete, let's configure Nextcloud to connect with our S3 storage. In the Nextcloud settings, select "External Storage." Fill in the "Bucket" field with NAMEOFYOURBUCKET. Check "Enable SSL" and "Enable Path Style," and enter the required information using the access keys of the user we created earlier.

And that's it! You've successfully installed Nextcloud on AWS EC2 and configured it to use S3 storage. You can now navigate to your designated folder and start uploading files securely. Enjoy the control and peace of mind that Nextcloud brings to your personal data management.

Thank you for tuning in to this episode of Continuous Improvement. I hope you found the information helpful and empowering. If you enjoyed this podcast, please subscribe and leave us a review. And remember, continuous improvement is the key to unlocking our full potential. Until next time!

在AWS EC2上安裝Nextcloud,並使用S3儲存空間

為了提高我的隱私,我決定減少使用Google產品。我用Firefox取代了Chrome,從Gmail轉到ProtonMail,現在正在使用Nextcloud而非Google Drive。Nextcloud允許自託管雲存儲並對我的數據進行控制。以下是在AWS EC2上安裝Nextcloud並配置它以使用S3存儲的步驟。

  1. 使用Snap套件管理器安裝Nextcloud:
sudo snap install nextcloud
  1. 創建一個管理員用戶賬號:
sudo nextcloud.manual-install <admin_username> <admin_password>
  1. 添加你的信任域:
sudo nextcloud.occ config:system:set trusted_domains 1 --value=<your-domain>
  1. 使用AWS Route 53,創建一個指向您的Nextcloud服務器的IP地址的A記錄。

  2. 設置Let's Encrypt的SSL證書:

sudo nextcloud.enable-https lets-encrypt

  1. 導航到您的域名,您現在應該能夠登錄到您的Nextcloud實例。

  1. 點擊“Apps”並啟用“Default encryption module”和“External storage support”。

  2. 打開AWS IAM(Identity and Access Management)並創建一個具有程序化訪問的新用戶。

  3. 使用下面的JSON代碼創建一個新的策略,將NAMEOFYOURBUCKET替換為您的S3桶的名稱。將此策略附加到新創建的用戶。

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:GetBucketLocation", "s3:ListAllMyBuckets"],
      "Resource": "arn:aws:s3:::*"
    },
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::NAMEOFYOURBUCKET",
        "arn:aws:s3:::NAMEOFYOURBUCKET/*"
      ]
    }
  ]
}
  1. 在Nextcloud設置中,選擇“External Storage”。在“Bucket”字段中填入NAMEOFYOURBUCKET。選中“Enable SSL”和“Enable Path Style”,然後使用您創建的用戶的憑證填入所需的信息。

  2. 你已經完成了!導航到你的d3文件夾,你現在應該能夠上傳文件了。

Debugging PHP Code in the Browser

In JavaScript, you can use console.log('whatever') for troubleshooting directly in your browser. However, when working with PHP, a little trick is required to accomplish the same thing. Here are the steps:

  1. Create a function named debug_to_console to handle the output to the console. Add this code to your PHP file:
function debug_to_console($data) {
    $output = $data;
    if (is_array($output)) {
        $output = implode(',', $output);
    }

    echo "<script>console.log('Debug Objects: " . $output . "');</script>";
}
  1. On the line where you need to output to the console, insert the following code:
debug_to_console("Test");
  1. If you need to debug an object, you can log it like this:
debug_to_console(json_encode($foo));

After following these steps, open your browser's developer tools. You should be able to see the PHP object displayed in the console using console.log.

Debugging PHP Code in the Browser

Welcome to "Continuous Improvement," the podcast where we explore different techniques and strategies for continuously improving our coding skills. I'm your host, Victor, and in today's episode, we'll be diving into a helpful trick for outputting to the console in PHP.

Hey there, fellow developers! Have you ever found yourself in a troubleshooting situation when working with PHP? You know, that moment where you just wished you could use a simple console.log like in JavaScript. Well, today I have a neat little trick to share with you.

In JavaScript, debugging directly in the browser console is a breeze. But when it comes to PHP, things can get a bit tricky. However, fear not! With this technique, you'll be able to accomplish the same thing. So, let's dive into the steps.

Step one, create a function named debug_to_console. This function will handle the output to the console. You can add the following code to your PHP file:

function debug_to_console($data) {
    $output = $data;
    if (is_array($output)) {
        $output = implode(',', $output);
    }

    echo "<script>console.log('Debug Objects: " . $output . "');</script>";
}

Step two, when you need to output something to the console, insert the following code:

debug_to_console("Test");

And voila! You should see the desired output in your browser's developer tools console.

But wait, there's more. Step three allows you to go even further by debugging objects logged as JSON strings. Here's how you can do it:

debug_to_console(json_encode($foo));

By encoding the object as a JSON string, you can easily log complex objects and analyze their contents in the console.

And there you have it! A nifty little trick to output to the console while working with PHP. Remember, continuous improvement is key to becoming a better developer.

That's all for today's episode of "Continuous Improvement." I hope you found this PHP console logging technique helpful. Stay tuned for more coding tips and tricks in our future episodes.

If you have any suggestions for topics you'd like us to cover or any questions you'd like me to answer, feel free to reach out on our website, continuousimprovement.com. Keep coding and keep improving!

在瀏覽器中調試PHP代碼

在JavaScript中,你可以直接在瀏覽器中使用console.log('whatever')進行故障排查。然而,當使用PHP時,需要一些小技巧才能達到同樣的效果。以下是操作步驟:

  1. 創建一個名為debug_to_console的函數來處理輸出到控制台的內容。將此代碼添加到你的PHP文件中:
function debug_to_console($data) {
    $output = $data;
    if (is_array($output)) {
        $output = implode(',', $output);
    }

    echo "<script>console.log('Debug Objects: " . $output . "');</script>";
}
  1. 在你需要輸出到控制台的行處,插入以下程式碼:
debug_to_console("Test");
  1. 如果你需要偵錯一個物件,您可以這樣記錄它:
debug_to_console(json_encode($foo));

按照這些步驟操作後,打開你的瀏覽器的開發者工具。您應該能夠看到在控制台使用console.log顯示的PHP物件。

Installing Ubuntu 19.10 on a MacBook Pro 13,1

I became frustrated with macOS Catalina and decided to switch to Ubuntu as the primary operating system on my 13-inch MacBook Pro without a touch bar. As a software developer, I found that macOS bundles many tools with Xcode, which takes up to 10GB of disk space. While disk space wasn't my primary concern, sometimes the network can be slow for downloads, and updates can get stuck. Losing an hour to such issues is an unnecessary obstacle when trying to get work done.

I was initially concerned about whether the proprietary hardware would be compatible with an open-source Linux distribution. To my surprise, many features work right out of the box with a fresh install, thanks to the community's efforts. This includes the screen, keyboard, touchpad, and Wi-Fi. The only feature that doesn't work is the audio, but this can be circumvented using my USB Type-C headphones or an HDMI external monitor with speakers. This GitHub page offers excellent documentation on the compatibility of different MacBook hardware with Linux: MacBook Hardware Support on Linux.

If you're interested in trying Ubuntu on your MacBook Pro, here are the simple steps to follow:

  1. Download Ubuntu 19.10 from the official Ubuntu site.
  2. Create a bootable USB stick using Etcher by following the steps in this guide: Create a USB Stick on macOS.
  3. Restart your MacBook and press the Option key to select the USB stick as the boot device.
  4. Try Ubuntu and proceed with installation if it suits you.

That's it! As a developer, you can quickly set up essential tools like Git by running sudo apt install git. This is more straightforward than on macOS, which restricts your freedom in various ways. It's good not to become too comfortable with a single platform, as you can't always trust big corporations to act in your best interest—such as protecting your personal data from government surveillance. Embrace the open-source community and appreciate the freedom to choose an alternative operating system.

P.S. 1: To get Bluetooth working, run the script found in this repository:

MacBook Bluetooth Driver

P.S. 2: To get the camera working, install the driver by following this guide:

Camera Driver Guide