DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Java Topics

article thumbnail
What Every Java Developer Should Know About Thread, Runnable, and Thread Pool
Most important information about Thread, Runnable, and Thread Pool notions in Java with clear examples, infographics, and explanations.
March 21, 2022
by Dmitry Egorov DZone Core CORE
· 25,396 Views · 22 Likes
article thumbnail
MQTT Messaging With Java and Raspberry Pi
In this article, learn how to send and visualize sensor data using multiple types of Raspberry Pi boards, MQTT, and HiveMQ. Includes video tutorials.
March 18, 2022
by Frank Delporte
· 11,081 Views · 6 Likes
article thumbnail
Blink a LED on a Raspberry Pi With Vaadin
Build a responsive website with Vaadin Flow to control electronic components connected to a Raspberry Pi with Pi4J
March 17, 2022
by Frank Delporte
· 8,567 Views · 9 Likes
article thumbnail
Polymorphism and Dynamic Binding in Java
Learn about polymorphism in Java and the two types: compile-time and runtime. Plus, we take a look at demonstrations of how to achieve static and dynamic binding.
March 17, 2022
by Ankit Dixit
· 10,972 Views · 2 Likes
article thumbnail
What's New With Java 17 and Containers?
Quarkus allows developers to start a new application development based on OpenJDK 17. Read the tutorial below to find out how!
March 16, 2022
by Daniel Oh DZone Core CORE
· 4,912 Views · 5 Likes
article thumbnail
How to Get Started With Vaadin Flow
In this blog, I will show you how I got started with Vaadin Flow. With Vaadin Flow, you can create web apps without HTML or JavaScript, but entirely with Java. Let’s get started! 1. Introduction For some time, I have been curious about Vaadin Flow. I am not very good in frontend developement but sometimes I try to get myself together and then I take a look at a frontend framework. In a previous post, I looked at React for example. Although the React introduction was a nice experience, I still did not think I could create a frontend with React before investing a serious amount of time. At Twitter, I often saw posts coming by about Vaadin and this took my interest. So, I put Vaadin on my blog todo list. A few weeks ago, I started to take a closer look at Vaadin, and more specifically at Vaadin Flow. Reading some blogs and examples, it reminded me about Java Swing but where Java Swing would create a traditional desktop application, Vaadin will create a web application for me. That sounds cool, because now I probably do not have a very steep learning curve and I can continue working in my Java IDE. Besides that, it also seems to integrate quite well with Spring, which I also already know. Enough prerequisites which should lead to a succes story for me. During my research I came up to the following interesting articles: Why I (still) love Vaadin, by Nicolas Fränkel; 5 Reasons Why Enterprises Use Vaadin For Their Web Application UI Needs, by Ankurman Shrestha Vaadin also takes care of the communication between frontend and backend. But when you are using a First API approach, you can call the API from the Vaadin backend part preventing duplication in your code. 2. Vaadin Flow Tutorial The easiest way to get started, is by following the Vaadin Flow Tutorial. Beware that you select the correct version of Vaadin Flow. At the time of writing, Vaadin 14 is the LTS version and is the one you should use when running in production, Vaadin 22 is the latest non-LTS version with new features to experiment with. I am most interested in the current production status and follow the Vaadin 14 Tutorial. The tutorial contains a basic project which you will enhance each time with code snippets which are provided. Also, the concepts and code snippets are clearly explained. Some basic components are used, login is added and it is also shown how you can write tests for the application. The latter is a great advantage because automated testing of a frontend application is always difficult to execute. It takes about 3-4 hours to complete the tutorial, but after that, you already have a good basis for creating your own project. The only disadvantage for me is that the tutorial is mainly copying of code snippets. This way, you miss certain details when trying to use Vaadin Flow yourself. 3. Own Project Let’s see whether I am able to create a frontend for a simple application. The application I create is quite basic and contains of a list of Shows for which ShowEvents can be created. A Show consists out of a title and a ShowEvent consists out of a date and the Show the event is for. The sources for this project can be found at GitHub. I will not explain the entire application, but I will mention some highlights how I built the application. 3.1 Get Started In order to get a quick start, I navigated to start.vaadin.com. Here you can configure the basic setup for the application. I chose an Empty template and added two views: one for the Shows and one for the ShowEvents. In the Settings tab, I changed the Project, the Group ID and decided to use Java 17. When ready configuring, I clicked the Download button and opened the project in my favorite IDE. In the pom, I changed the vaadin dependency to vaadin-core. Reason for this is that I only want to use free components and this should be more than enough for the basic application I want to build. XML com.vaadin vaadin-core ... Next, I wanted to run the application by running the main method of the Application class. Remember, Vaadin integrates well with Spring, so we are talking about a Spring Boot application here. However, this gave the following exception: Shell java.lang.IllegalStateException: The compatibility mode is explicitly set to 'false', but there are neither 'flow-build-info.json' nor 'webpack.config.js' file available in the project/work I was a little too enthusiastic, I had to build the application first. Shell $ mvn clean package After this, the application started successfully. 3.2 Creating the Application I started with creating the data package and copying the AbstractEntity of the tutorial into it. This required adding the spring-boot-starter-data-jpa dependency to the pom. OK, I know I wrote that by copying you miss some details and now I do it myself, but there is nothing wrong with a smart copy now and then. XML org.springframework.boot spring-boot-starter-data-jpa Next, I created the Show and ShowEvent entities and added the JPA repositories. Vaadin also provides a dependency for generating example data. This way, you can generate data into your application for testing purposes. Therefore, I added the exampledata dependency and created the DataGenerator class. XML com.vaadin exampledata 4.1.0 In order to get this working, I had to remove the NotEmpty annotation because of the following exception. I did not investigate this exception any further. Shell No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.time.LocalDate' Next, I created the ShowService and added the H2 database as a dependency to the pom. XML com.h2database h2 Building and starting the application was successfull again and after that, I implemented the ShowsView, ShowEventsView and the ShowEventForm. The first two are for displaying the Shows and ShowEvents into a grid and the ShowEventForm will allow us to change and delete a ShowEvent. To give you an impression, some screenshots are shown here. The Shows page. The ShowEvents page. The ShowEvent form. 3.3 Lazy Loading In the DataGenerator the number of ShowEvents was initially set to 50, but when I increase this to 1000, then a problem occurs in the ShowEvents page. The whole list of ShowEvents is retrieved and loaded into memory. This will get worse when the list grows even further. The solution is provided in the documentation. First, I needed to change to ShowEventRepository by extending it from PagingAndSortingRepository instead of JpaRepository. Java public interface ShowEventRepository extends PagingAndSortingRepository { } Following the instructions of the documentation worked just fine when I scrolled slowly through the list, but when I scrolled a bit faster an IndexOutOfBoundsException was thrown. Shell java.lang.IndexOutOfBoundsException: Index 50 out of bounds for length 50 In order to explain why this exception occurs, we need to take a look at the code for fetching the results. Java private void updateList() { DataProvider dataProvider = DataProvider.fromCallbacks( // First callback fetches items based on a query query -> { // The index of the first item to load int offset = query.getOffset(); // The number of items to load int limit = query.getLimit(); List showEvents = showService.fetchShowEvents(offset, limit); return showEvents.stream(); }, // Second callback fetches the total number of items currently in the Grid. // The grid can then use it to properly adjust the scrollbars. query -> showService.countShowEvents()); grid.setDataProvider(dataProvider); } The offset and the limit (number of items to load) are retrieved from the query provided by Vaadin. However, JPA pagination needs a page and a limit. Therefore, the page needs to be calculated by dividing the offset by the limit. Initially, I just used the offset directly for the page and this caused the error. Java public List fetchShowEvents(int offset, int limit) { return showEventRepository.findAll(PageRequest.of(offset / limit, limit)).stream().toList(); } 4. Conclusion My first experience with Vaadin is quite positive. In most cases, I just need a frontend for an administrator or a limited set of users. With Vaadin I can make use of my Java experience and still provide a fancy web application. Also, the idea that I am able to create tests appeals me a lot. The free components will be most of the time enough for these kind of applications and if not, also some more advanced components are provided by means of a license.
March 16, 2022
by Gunter Rotsaert DZone Core CORE
· 2,857 Views · 2 Likes
article thumbnail
Java on Raspberry Pi
In this post, follow an overview of resources with information and examples of Java projects to control electronic components on the Raspberry Pi.
March 16, 2022
by Frank Delporte
· 9,850 Views · 7 Likes
article thumbnail
Spring Boot: How To Use Java Persistence Query Language (JPQL)
In this Spring Boot video tutorial, take a closer look at how to use Java Persistence Query Language(JPQL), RESTful Web Services.
March 15, 2022
by Ram N
· 4,700 Views · 7 Likes
article thumbnail
How to Configure Selenium in Eclipse
This article discusses how to configure Selenium in Eclipse to use Selenium for Java.
March 11, 2022
by Garima Tiwari
· 4,252 Views · 2 Likes
article thumbnail
Spring Boot: JUnit Integration Test
In this Spring Boot video tutorial, take a closer look at the JUnit Integration Test and testing JWT Tokens and UserID (RESTful Web Services).
March 10, 2022
by Ram N
· 5,182 Views · 5 Likes
article thumbnail
Coordinating Threads Using CountDownLatch
This article illustrates with examples how to use the CountDownLatch in Java for handling coordination between threads in multi-threaded applications.
Updated March 9, 2022
by Karthik Viswanathan
· 14,573 Views · 4 Likes
article thumbnail
Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services
In this video tutorial, take a closer look at the Spring Boot Testing Service Layer Code with JUnit 5 and Mockito (RESTful Web Services).
March 8, 2022
by Ram N
· 5,762 Views · 4 Likes
article thumbnail
Testing REST Controller Methods With JUnit 5 [Video]
In this video tutorial about RESTful web services, learn more about Spring Boot and testing REST controller methods with JUnit 5.
March 7, 2022
by Ram N
· 4,425 Views · 3 Likes
article thumbnail
Going Beyond Java 8: Compact Strings
Compact strings are one of the most compelling reasons to move forward from Java 8. Here's why.
Updated March 7, 2022
by Claudio De Sio Cesari
· 16,314 Views · 20 Likes
article thumbnail
How to Estimate Object Memory Allocation in Java
This article shows three ways to estimate object memory allocation in Java. A comparison of all approaches and examples is included.
March 5, 2022
by Dmitry Egorov DZone Core CORE
· 13,566 Views · 11 Likes
article thumbnail
Method Builder With Lombok @Builder
In this tutorial, we are going to explore the various possibilities of generating method builders with Lombok's @Builder annotation to improve usability.
March 3, 2022
by Daniel Buza
· 14,581 Views · 10 Likes
article thumbnail
How to Use Native Image Kit With the Quarkus Framework
In this tutorial, learn how to use Liberica Native Image Kit, which is designed to support numerous platforms and programming languages, with Quarkus.
March 2, 2022
by Dmitry Chuyko
· 3,826 Views · 4 Likes
article thumbnail
An Introduction to AWS Serverless Application Model
In this blog, the AWS Serverless Application Model (AWS SAM) is introduced. You will learn what SAM is and where it can be used for. You will also get your hands dirty, because you will create an AWS SAM project from scratch. Enjoy! 1. Introduction AWS SAM is, according to the official documentation, a framework that you can use to build serverless applications on AWS . A serverless application consists of several lambda’s and other resources working together. In order to define all of these components, a SAM template is used. This SAM template is used to deploy the application to AWS. During deployment, the SAM template is converted to a CloudFormation template which will actually create the resources defined in the SAM template. An introduction to AWS CloudFormation is given in a previous post. SAM can be seen as a CloudFormation++ where less configuration is needed in the template itself. E.g. the Events property in a SAM template will create an API gateway for the Lambda but with less yaml than you would need in a CloudFormation template. You will see for yourself later on in this post. Another big advantage of SAM is that you can easily test it locally on your dev machine. Enough talking, let’s get started! In a previous post, a Java Lambda with an API gateway was created. You will use the code of that Lambda for deploying the application using SAM. The code for the Lambda is available at GitHub. The resulting SAM template and Lambda used in this blog, is also available at GitHub. The step-by-step guide is inspired by the AWS Getting Started tutorial. However, in this post you will use a Java Lambda instead of Python and you will see what you need to change to the Lambda created in a previous post in order to let it work with SAM. A prerequisite is that you have the SAM CLI installed, instructions can be found here. 2. Creating the SAM Application The easiest way to get started, is to start from an example application. Shell $ sam init Choose for AWS Quick Start Template. Shell Which template source would you like to use? 1 - AWS Quick Start Templates 2 - Custom Template Location Choice: 1 Choose for package type Zip. Shell What package type would you like to use? 1 - Zip (artifact is a zip uploaded to S3) 2 - Image (artifact is an image uploaded to an ECR image repository) Package type: 1 Choose Java11. Shell Which runtime would you like to use? 1 - nodejs14.x 2 - python3.8 3 - ruby2.7 4 - go1.x 5 - java11 6 - dotnetcore3.1 7 - nodejs12.x 8 - nodejs10.x 9 - python3.7 10 - python3.6 11 - python2.7 12 - ruby2.5 13 - java8.al2 14 - java8 15 - dotnetcore2.1 Runtime: 5 Choose Maven as build tool. Shell Which dependency manager would you like to use? 1 - maven 2 - gradle Dependency manager: 1 Choose myawssamplanet as project name. Shell Project name [sam-app]: myawssamplanet Choose the Hello World Example: Maven. Shell Cloning app templates from https://github.com/aws/aws-sam-cli-app-templates AWS quick start application templates: 1 - Hello World Example: Maven 2 - EventBridge Hello World: Maven 3 - EventBridge App from scratch (100+ Event Schemas): Maven 4 - Step Functions Sample App (Stock Trader): Maven Template selection: 1 The SAM project is created. Shell ----------------------- Generating application: ----------------------- Name: myawssamplanet Runtime: java11 Dependency Manager: maven Application Template: hello-world Output Directory: . Next steps can be found in the README file at ./myawssamplanet/README.md The generated application has the following contents: events directory: contains an event.json file which can be used to test the lambda locally; HelloWorldFunction: the sample application, you will replace this one; README.md: a readme file containing instructions what you can do with the sample application; template.yaml: this is the SAM template which contains the configuration of the resources that need to be created (similar as a CloudFormation template). 3. Customize SAM Project In this section, you will customize the generated application in order to use the Java Lambda created in a previous post. Create a directory MyAwsSamFunction next to the HelloWorldFunction and copy the contents of the Java Lambda in this directory. Remove the HelloWorldFunction directory. Change the template.yaml file in order that the references to the HelloWorldFunction are replaced with references to the MyAwsSamFunction. The resulting file is the following: YAML AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: > myawssamplanet Sample SAM Template for myawssamplanet Globals: Function: Timeout: 20 Resources: MyAwsSamFunction: Type: AWS::Serverless::Function Properties: CodeUri: MyAwsSamFunction Handler: com.mydeveloperplanet.myawslambdajavaplanet.LambdaJava::handleRequest Runtime: java11 MemorySize: 512 Environment: Variables: PARAM1: VALUE Events: MyAwsLambdaJavaGet: Type: Api Properties: Path: /myawslambdajava Method: get Outputs: MyAwsSamApi: Description: "API Gateway endpoint URL for Prod stage for LambdaJava function" Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/myawslambdajava/" MyAwsSamFunction: Description: "LambdaJava Lambda Function ARN" Value: !GetAtt MyAwsSamFunction.Arn MyAwsSamFunctionIamRole: Description: "Implicit IAM Role created for LambdaJava function" Value: !GetAtt MyAwsSamFunctionRole.Arn In the Resources section, the Lambda is defined and a MyAwsLambdaJavaGet Event of type Api. The latter will create an API Gateway containing a Rest resource where the Lambda can be invoked by means of a GET request. A complete overview of the different sections is described here. You also need to change the LambdaJava class. The current implementation makes us of the Lambda Integration type in the API Gateway. However, by default, SAM will make use of the Lambda Proxy Integration type. The difference is that the payload is sent differently from API Gateway to the Lambda function. If you do not change this, an Internal Server error will be sent as a response when you invoke the Rest resource. The current implementation is the following: Java public class LambdaJava implements RequestHandler, String> { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); @Override public String handleRequest(Map event, Context context) { LambdaLogger logger = context.getLogger(); String response = "Version 1"; ... return response; } } Instead, you need to implement the handleRequest which takes an APIGatewayProxyRequestEvent object. You also need to replace GSON.toJson(input) with input.getBody() and the response needs be formatted a little bit different. Besides that, also a null-check needs to be added in case the body is empty, otherwise a NullPointerException will be thrown. Java public class LambdaJava implements RequestHandler { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); @Override public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) { LambdaLogger logger = context.getLogger(); // log execution details logger.log("ENVIRONMENT VARIABLES: " + GSON.toJson(System.getenv()) + System.lineSeparator()); logger.log("CONTEXT: " + GSON.toJson(context) + System.lineSeparator()); // process event logger.log("EVENT: " + input.getBody() + System.lineSeparator()); logger.log("EVENT TYPE: " + input.getClass() + System.lineSeparator()); if (input.getBody() != null) { // Parse JSON into an object Car car = GSON.fromJson(input.getBody(), Car.class); logger.log("Car brand: " + car.getBrand() + System.lineSeparator()); logger.log("Car type: " + car.getType() + System.lineSeparator()); } Map headers = new HashMap<>(); headers.put("Content-Type", "application/text"); headers.put("X-Custom-Header", "application/text"); APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent() .withHeaders(headers); return response .withStatusCode(200) .withBody("Version 1"); } } 4. Build and Deploy Now it is time to build and deploy SAM. Navigate to the directory where the template.yaml exists and execute the build command: Shell $ sam build Building codeuri: /home/../myawssamplanet/MyAwsSamFunction runtime: java11 metadata: {} architecture: x86_64 functions: ['MyAwsSamFunction'] Running JavaMavenWorkflow:CopySource Running JavaMavenWorkflow:MavenBuild Running JavaMavenWorkflow:MavenCopyDependency Running JavaMavenWorkflow:MavenCopyArtifacts Build Succeeded Built Artifacts : .aws-sam/build Built Template : .aws-sam/build/template.yaml Commands you can use next ========================= [*] Invoke Function: sam local invoke [*] Test Function in the Cloud: sam sync --stack-name {stack-name} --watch [*] Deploy: sam deploy --guided After building the application, you deploy SAM. Choose myawssamplanet as stack name for CloudFormation. Shell $ sam deploy --guided Configuring SAM deploy ====================== Looking for config file [samconfig.toml] : Not found Setting default arguments for 'sam deploy' ========================================= Stack Name [sam-app]: myawssamplanet Leave the default of the AWS Region and enter y in order to confirm changes before deploy. Shell AWS Region [eu-west-3]: #Shows you resources changes to be deployed and require a 'Y' to initiate deploy Confirm changes before deploy [y/N]: y Choose Y to allow role creation. Shell #SAM needs permission to be able to create roles to connect to the resources in your template Allow SAM CLI IAM role creation [Y/n]: Y Do not disable rollback. Shell #Preserves the state of previously provisioned resources when an operation fails Disable rollback [y/N]: N The API will be publicly available, so choose y. Shell MyAwsSamFunction may not have authorization defined, Is this okay? [y/N]: y Save the arguments to a configuration file. Shell Save arguments to configuration file [Y/n]: Y Leave the defaults for the configuration file name and for the configuration environment. Shell SAM configuration file [samconfig.toml]: SAM configuration environment [default]: The CloudFormation stacks are created. Take a look at AWS CloudFormation in the AWS Management console. Choose y to deploy the application (at the bottom of the output below). Shell Looking for resources needed for deployment: Creating the required resources... Successfully created! Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-o08u00g288r9 A different default S3 bucket can be set in samconfig.toml Saved arguments to config file Running 'sam deploy' for future deployments will use the parameters saved above. The above parameters can be changed by modifying samconfig.toml Learn more about samconfig.toml syntax at https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html Uploading to myawssamplanet/8e80317f02e0baccb04761d59791c6ad 2667728 / 2667728 (100.00%) Deploying with following values =============================== Stack name : myawssamplanet Region : eu-west-3 Confirm changeset : True Disable rollback : False Deployment s3 bucket : aws-sam-cli-managed-default-samclisourcebucket-o08u00g288r9 Capabilities : ["CAPABILITY_IAM"] Parameter overrides : {} Signing Profiles : {} Initiating deployment ===================== Uploading to myawssamplanet/a0f8a035e37699e9be00c92f8d0d10fe.template 1308 / 1308 (100.00%) Waiting for changeset to be created.. CloudFormation stack changeset ------------------------------------------------------------------------------------------------------------------------------------------------------------- Operation LogicalResourceId ResourceType Replacement ------------------------------------------------------------------------------------------------------------------------------------------------------------- + Add MyAwsSamFunctionMyAwsLambdaJavaGetPer AWS::Lambda::Permission N/A missionProd + Add MyAwsSamFunctionRole AWS::IAM::Role N/A + Add MyAwsSamFunction AWS::Lambda::Function N/A + Add ServerlessRestApiDeployment4aeac94236 AWS::ApiGateway::Deployment N/A + Add ServerlessRestApiProdStage AWS::ApiGateway::Stage N/A + Add ServerlessRestApi AWS::ApiGateway::RestApi N/A ------------------------------------------------------------------------------------------------------------------------------------------------------------- Changeset created successfully. arn:aws:cloudformation:eu-west-3::changeSet/samcli-deploy1643551688/4b3d5e55-adc8-44d7-8011-e8b1e17d9b9f Previewing CloudFormation changeset before deployment ====================================================== Deploy this changeset? [y/N]: y All the resources are created by the CloudFormation stack. Shell 2022-01-30 15:11:17 - Waiting for stack create/update to complete CloudFormation events from stack operations ------------------------------------------------------------------------------------------------------------------------------------------------------------- ResourceStatus ResourceType LogicalResourceId ResourceStatusReason ------------------------------------------------------------------------------------------------------------------------------------------------------------- CREATE_IN_PROGRESS AWS::IAM::Role MyAwsSamFunctionRole - CREATE_IN_PROGRESS AWS::IAM::Role MyAwsSamFunctionRole Resource creation Initiated CREATE_COMPLETE AWS::IAM::Role MyAwsSamFunctionRole - CREATE_IN_PROGRESS AWS::Lambda::Function MyAwsSamFunction - CREATE_IN_PROGRESS AWS::Lambda::Function MyAwsSamFunction Resource creation Initiated CREATE_COMPLETE AWS::Lambda::Function MyAwsSamFunction - CREATE_IN_PROGRESS AWS::ApiGateway::RestApi ServerlessRestApi - CREATE_COMPLETE AWS::ApiGateway::RestApi ServerlessRestApi - CREATE_IN_PROGRESS AWS::ApiGateway::RestApi ServerlessRestApi Resource creation Initiated CREATE_IN_PROGRESS AWS::Lambda::Permission MyAwsSamFunctionMyAwsLambdaJavaGetPer - missionProd CREATE_IN_PROGRESS AWS::ApiGateway::Deployment ServerlessRestApiDeployment4aeac94236 - CREATE_IN_PROGRESS AWS::Lambda::Permission MyAwsSamFunctionMyAwsLambdaJavaGetPer Resource creation Initiated missionProd CREATE_IN_PROGRESS AWS::ApiGateway::Deployment ServerlessRestApiDeployment4aeac94236 Resource creation Initiated CREATE_COMPLETE AWS::ApiGateway::Deployment ServerlessRestApiDeployment4aeac94236 - CREATE_IN_PROGRESS AWS::ApiGateway::Stage ServerlessRestApiProdStage - CREATE_IN_PROGRESS AWS::ApiGateway::Stage ServerlessRestApiProdStage Resource creation Initiated CREATE_COMPLETE AWS::ApiGateway::Stage ServerlessRestApiProdStage - CREATE_COMPLETE AWS::Lambda::Permission MyAwsSamFunctionMyAwsLambdaJavaGetPer - missionProd CREATE_COMPLETE AWS::CloudFormation::Stack myawssamplanet - ------------------------------------------------------------------------------------------------------------------------------------------------------------- CloudFormation outputs from deployed stack ------------------------------------------------------------------------------------------------------------------------------------------------------------- Outputs ------------------------------------------------------------------------------------------------------------------------------------------------------------- Key MyAwsSamFunction Description LambdaJava Lambda Function ARN Value arn:aws:lambda:eu-west-3::function:myawssamplanet-MyAwsSamFunction-H9zkMo3NEWsn Key MyAwsSamApi Description API Gateway endpoint URL for Prod stage for LambdaJava function Value https://5w9uji7dag.execute-api.eu-west-3.amazonaws.com/Prod/myawslambdajava/ Key MyAwsSamFunctionIamRole Description Implicit IAM Role created for LambdaJava function Value arn:aws:iam:::role/myawssamplanet-MyAwsSamFunctionRole-XNX3QIEXXG93 ------------------------------------------------------------------------------------------------------------------------------------------------------------- Successfully created/updated stack - myawssamplanet in eu-west-3 Navigate to the API Gateway service and you notice that the API Gateway is created. Navigate to the Lambda service and you notice that the Lambda is created. The public URL for the API Gateway is shown in the console output. Try to access the URL. As expected, ‘Version 1’ is returned. Shell $ curl https://5w9uji7dag.execute-api.eu-west-3.amazonaws.com/Prod/myawslambdajava/ Version 1 5. Test Locally One of the main advantages of using SAM, is that you can test it locally. You can test the application including an API Gateway by using the local start-api command. Shell $ sam local start-api Mounting MyAwsSamFunction at http://127.0.0.1:3000/myawslambdajava [GET] You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template 2022-01-30 15:35:39 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit) Open a new Terminal and try to invoke the API Gateway resource. Shell $ curl http://127.0.0.1:3000/myawslambdajava Version 1 It might take some seconds before the response is returned. In the meanwhile, the terminal where you started the API, outputs the serverlogging. Here you notice that a Docker container is started. It is also possible to invoke the Lambda directly by simulating the event which is normally sent from the API Gateway to the Lambda. This is where the event.json file comes in handy. Shell $ sam local invoke "MyAwsSamPlanet" -e events/event.json 6. Add Post Request The Lambda which is used, actually takes a JSON body, converts JSON objects into Java objects and prints it to the logging. Add a MyAwsLambdaPost request to the template.yaml in order to test this behaviour. YAML Events: MyAwsLambdaJavaGet: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /myawslambdajava Method: get MyAwsLambdaJavaPost: Type: Api Properties: Path: /myawslambdajava Method: post Again, build and deploy SAM. Wait until the deployment has been finished and POST a request. Shell $ curl -i -X 'POST' \ > 'https://5w9uji7dag.execute-api.eu-west-3.amazonaws.com/Prod/myawslambdajava/' \ > -H 'accept: application/json' \ > -H 'Content-Type: application/json' \ > -d '{ > "brand": "FORD", > "type": "Kuga" > }' HTTP/2 200 content-type: application/text content-length: 9 date: Sun, 30 Jan 2022 14:54:22 GMT x-amzn-requestid: b9855126-b51e-4dc9-abea-97dee77b5168 x-amz-apigw-id: Mw74sG6AiGYFoRg= x-custom-header: application/text x-amzn-trace-id: Root=1-61f6a69d-02ca6ba1368061e864cb7d6f;Sampled=0 x-cache: Miss from cloudfront via: 1.1 415e8d76bf2c69e5e03b89ba8461cd7e.cloudfront.net (CloudFront) x-amz-cf-pop: AMS50-C1 x-amz-cf-id: q1c-8WZOIqEhllZhGBAFQP8auu54fX7E3B41S2DcZNhr-HxV5JZLSQ== Version 1 Navigate to the Lambda service and navigate to the Monitor tab. From here, you can open the CloudWatch logging for the Lambda. The logging shows you that the event is received in the Lambda and converted to a Java object. Shell EVENT: { "brand": "FORD", "type": "Kuga" } EVENT TYPE: class com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent Car brand: FORD Car type: Kuga 7. Unit Test For completeness, also a unit test is added to the git repository. It is not further explained in this blog, but the test can be viewed at GitHub. It is important to add the junit dependency to the pom. XML junit junit 4.13.1 test You also need to ensure that the context and the logger are not null. It is not a very beautiful unit test, but it just works :-) . 8. Cleanup As always, it is a good practice to clean up all the resources you have created after you are done experimenting with AWS services. Because CloudFormation is used, it is quite easy to delete all the resources by means of a single command. Shell $ aws cloudformation delete-stack --stack-name myawssamplanet --region eu-west-3 You can follow the progress in CloudFormation. SAM also created a S3 bucket, this one is not automatically deleted. Navigate to the S3 service. Select the created bucket and click the Empty button. Follow the instructions and click the Delete button in order to remove the S3 bucket. Now you can also delete the aws-sam-cli-managed-default stack which was created. Shell $ aws cloudformation delete-stack --stack-name aws-sam-cli-managed-default --region eu-west-3 9. Conclusion In this blog, you got an introduction of the Serverless Application Model of AWS. You also got your hands dirty and created by means of a SAM template an API Gateway and Java Lambda. You learnt how to build, deploy and test the application remotely and locally.
March 1, 2022
by Gunter Rotsaert DZone Core CORE
· 6,697 Views · 4 Likes
article thumbnail
Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
Read here to learn a DataWeave(DWL 1.0) function to help you perform a requirement where you want to resolve a wildcard using a set of parameters.
Updated March 1, 2022
by Bibek Gorain
· 8,766 Views · 4 Likes
article thumbnail
FOSDEM 2022 Conference Report
FOSDEM is one of the most significant gatherings worldwide focused on all things Open Source. Learn here about talks on Jakarta EE, and Diversity and Inclusion.
February 28, 2022
by Reza Rahman
· 6,377 Views · 4 Likes
  • Previous
  • ...
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×