9 .Write a java program to create an array list collection.
import java.util.*;
class TestJavaCollection1 {
public static void main(String args[]) {
ArrayList<String> list = new ArrayList<String>(); // Creating arraylist
list.add("Ravi"); // Adding objects to arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
// Traversing list through Iterator
Iterator<String> itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
10. Write a java program to create a stack collection
import java.util.*;
public class TestJavaCollection4 {
public static void main(String args[]) {
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop(); // Removes "Garima"
Iterator<String> itr = stack.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
11 .Write a java program to create a queue list collection
import java.util.*;
class TestCollection12 {
public static void main(String args[]) {
PriorityQueue<String> queue = new PriorityQueue<String>();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head: " + queue.element()); // throws exception if empty
System.out.println("head: " + queue.peek()); // returns null if empty
System.out.println("iterating the queue elements:");
Iterator itr = queue.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
queue.remove(); // removes head
queue.poll(); // removes next head
System.out.println("after removing two elements:");
Iterator<String> itr2 = queue.iterator();
while (itr2.hasNext()) {
System.out.println(itr2.next());
}
}
}
12 .Write a java program to create an Hash set collection
import java.util.*;
class HashSet1 {
public static void main(String args[]) {
// Creating HashSet and adding elements
HashSet<String> set = new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i = set.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
13.Write a java program to create an Tree set collection import java.util.*;
import java.util.*;
class TreeSet1 {
public static void main(String args[]) {
// Creating and adding elements
TreeSet<String> al = new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi"); // duplicate entry
al.add("Ajay");
// Traversing elements
Iterator<String> itr = al.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Spring Framework
14. Implement a spring framework based project entitled “ Health and Fitness App”
Create Your First Spring MVC Application
Consider the following example:
Step 0: Setup your project with maven use the required archtype to get the required folders directory
and configure the server with your project.
Step 1: Load the spring jar files or add the dependencies if Maven is used. Add the following
dependencies in pom.xml
pom.xml XML
Step 2: Defining a Controller
Let us Create the Controller Class
HelloGeek.java Java
Step 3: Provide the name of the controller in the web.xml file as follows: DispatcherServlet is the
front controller in Spring Web MVC. Incoming requests for the HTML file are forwarded to the
DispatcherServlet.
web.xml XML
Step 4: We have to define the bean in a separate XML file. We have specified the view components in
this file. It is located in the WEB-INF directory.
spring-servlet.xml XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-
mvc.xsd">
<!-- This element defines the base-package where DispatcherServlet will search the controller class. --
>
<context:component-scan base-package="com.geek" />
<!--Provide support for conversion, formatting and also for validation -->
<mvc:annotation-driven/>
</beans>
Step 5: Use JSP to display the message
index.jsp HTML
Step 6: Start the server and run the project. The output is displayed as follows:
Spring MVC Tutorial!!
Building a RESTful Web Service with Spring Boot Actuator package com.example.actuatorservice;
public class Greeting {
private final long id; private final String content;
public Greeting(long id, String content) { this.id = id;
this.content = content;
}
public long getId() { return id;
}
public String getContent() { return content;
}
}
Now that you need to create the endpoint controller that will serve the representation class.
Create a Resource Controller
In Spring, REST endpoints are Spring MVC controllers. The following Spring MVC controller (from
src/main/java/com/example/actuatorservice/HelloWorldController.java) handles a GET request for the
/hello-world endpoint and returns the Greeting resource:
package com.example.actuatorservice;
import java.util.concurrent.atomic.AtomicLong; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; import
org.springframework.web.bind.annotation.RequestParam; import
org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloWorldController {
private static final String template = "Hello, %s!"; private final AtomicLong counter = new
AtomicLong();
@GetMapping("/hello-world") @ResponseBody
public Greeting sayHello(@RequestParam(name="name", required=false,
defaultValue="Stranger") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
The key difference between a human-facing controller and a REST endpoint controller is in how the
response is created. Rather than rely on a view (such as JSP) to render model data in HTML, an
endpoint controller returns the data to be written directly to the body of the response.
The @ResponseBody annotation tells Spring MVC not to render a model into a view but, rather, to
write the returned object into the response body. It does so by using one of Spring’s message
converters. Because Jackson 2 is in the classpath, MappingJackson2HttpMessageConverter will
handle the conversion of a Greeting object to JSON if the request’s Accept header specifies that JSON
should be returned.
How do you know Jackson 2 is on the classpath? Either run mvn dependency:tree or ./gradlew
dependencies, and you get a detailed tree of dependencies that includes Jackson 2.x. You can also see
that it comes from /spring-boot-starter-json, itself imported by spring-boot-starter-web.
Run the Application
You can run the application from a custom main class or directly from one of the configuration
classes. For this simple example, you can use the SpringApplication helper class. Note that this is the
application class that the Spring Initializr created for you, and you need not even modify it for it to
work for this simple application. The following listing (from
src/main/java/com/example/actuatorservice/HelloWorldApplication.java) shows the application class:
package com.example.actuatorservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloWorldApplication {
public static void main(String[] args) { SpringApplication.run(HelloWorldApplication.class, args);
}
}
In a conventional Spring MVC application, you would add @EnableWebMvc to turn on key
behaviors, including configuration of a DispatcherServlet. But Spring Boot turns on this annotation
automatically when it detects spring-webmvc on your classpath. This sets you up to build a controller
in an upcoming step.
The @SpringBootApplication annotation also brings in a @ComponentScan annotation, which tells
Spring to scan the com.example.actuatorservice package for those controllers (along with any other
annotated component classes).
Build an executable JAR
You can run the application from the command line with Gradle or Maven. You can also build a
single executable JAR file that contains all the necessary dependencies, classes, and resources and run
that. Building an executable jar makes it easy to ship, version, and deploy the service as an application
throughout the development lifecycle, across different environments, and so forth.
If you use Gradle, you can run the application by using ./gradlew bootRun. Alternatively, you can
build the JAR file by using ./gradlew build and then run the JAR file, as follows:
java -jar build/libs/gs-actuator-service-0.1.0.jar
If you use Maven, you can run the application by using ./mvnw spring-boot:run. Alternatively, you
can build the JAR file with ./mvnw clean package and then run the JAR file, as follows:
java -jar target/gs-actuator-service-0.1.0.jar
The steps described here create a runnable JAR. You can also build a classic WAR file.
Once the service is running (because you ran spring-boot:run in a terminal), you can test it by running
the following command in a separate terminal:
$ curl localhost:8080/hello-world
{"id":1,"content":"Hello, Stranger!"} Switch to a Different Server Port
Spring Boot Actuator defaults to running on port 8080. By adding an application.properties file, you
can override that setting. The following listing (from src/main/resources/application.properties)shows
that file with the necessary changes:
server.port: 9000
management.server.port: 9001
management.server.address: 127.0.0.1
Run the server again by running the following command in a terminal:
$ ./gradlew clean build && java -jar build/libs/gs-actuator-service-0.1.0.jar The service now starts on
port 9000.
You can test that it is working on port 9000 by running the following commands in a terminal:
$ curl localhost:8080/hello-world curl: (52) Empty reply from server
$ curl localhost:9000/hello-world
{"id":1,"content":"Hello, Stranger!"}
$ curl localhost:9001/actuator/health
{"status":"UP"}
Test Your Application
To check whether your application works, you should write unit and integration tests for your
application. The test class in
src/test/java/com/example/actuatorservice/HelloWorldApplicationTests.java ensures that
Your controller is responsive.
Your management endpoint is responsive.
Note that the tests start the application on a random port. The following listing shows the test class:
/*
package com.example.actuatorservice; import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import
org.springframework.beans.factory.annotation.Value; import
org.springframework.boot.test.context.SpringBootTest; import
org.springframework.boot.test.web.client.TestRestTemplate; import
org.springframework.boot.test.web.server.LocalServerPort; import
org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource; import static
org.assertj.core.api.BDDAssertions.then;
/**
* Basic integration tests for service demo application.
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = {"management.port=0"})
public class HelloWorldApplicationTests {
@LocalServerPort private int port;
@Value("${local.management.port}") private int mgt;
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void shouldReturn200WhenSendingRequestToController() throws Exception
{ @SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.testRestTemplate.getForEntity( "http://localhost:" + this.port +
"/hello-world", Map.class);
then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void shouldReturn200WhenSendingRequestToManagementEndpoint() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.testRestTemplate.getForEntity( "http://localhost:" + this.mgt +
"/actuator", Map.class);
then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}