Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .mvn/wrapper/maven-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.9.6/apache-maven-3.9.6-bin.zip
13 changes: 6 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# springboot-java8
The project is made on spring boot. The project summarize the new features present in Java 8.
# springboot-java15
The project is made on spring boot. The project summarizes the features present in Java 8 through Java 15.
It contain list of harcoded topics list. You can call the apis's with POSTMAN to add,delete,update Topic list
In addition, it uses
1) Java 8 NIO methods
Expand All @@ -13,6 +13,8 @@ In addition, it uses
9) Default and Static methods in interface
10) Java 8 LocalDateTime API
11) Pattern
12) Java 10+ local variable type inference (var)
13) Java 15 text blocks



Expand Down Expand Up @@ -76,13 +78,12 @@ GET /datetime

### Prerequisites

1) Java sdk
1) Java 15 SDK
2) POSTMAN

### Installing



```
1) Download or clone
2) Import the project
Expand Down Expand Up @@ -129,6 +130,4 @@ https://dzone.com/articles/java-8-friday-goodies-new-new

## Authors

* **Rehman Murad Ali**


* **Rehman Murad Ali**
17 changes: 9 additions & 8 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ buildscript {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.2.RELEASE")
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.7.18")
}
}

Expand All @@ -14,19 +14,20 @@ apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
baseName = 'gs-spring-boot'
version = '0.1.0'
archiveBaseName = 'gs-spring-boot'
archiveVersion = '0.1.0'
}

repositories {
mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8
sourceCompatibility = 15
targetCompatibility = 15

dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("junit:junit")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-jdbc")
runtimeOnly("com.h2database:h2")
testImplementation("junit:junit")
}

2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.4-bin.zip
Empty file modified gradlew
100644 → 100755
Empty file.
Empty file modified mvnw
100644 → 100755
Empty file.
14 changes: 11 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@

<groupId>org.springframework</groupId>
<artifactId>gs-spring-boot</artifactId>
<packaging>pom</packaging>
<packaging>jar</packaging>
<version>0.1.0</version>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<version>2.7.18</version>
</parent>

<dependencies>
Expand All @@ -35,12 +35,20 @@
</dependencies>

<properties>
<java.version>1.8</java.version>
<java.version>15</java.version>
</properties>


<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>15</release>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
Expand Down
53 changes: 34 additions & 19 deletions src/main/java/hello/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,25 @@ public class Application implements CommandLineRunner {

public static void main(String[] args) {

ApplicationContext ctx = SpringApplication.run(Application.class, args);
var ctx = SpringApplication.run(Application.class, args);

System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();

var beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
for (var beanName : beanNames) {
System.out.println(beanName);
}

RestTemplate restTemplate = new RestTemplate();
Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
try {
var restTemplate = new RestTemplate();
var quote = restTemplate.getForObject("https://dummyjson.com/quotes/random", Quote.class);
if (quote != null) {
log.info(quote.toString());
}
} catch (Exception e) {
log.warn("Could not fetch quote from external service: {}", e.getMessage());
}
}


Expand All @@ -49,9 +55,15 @@ public RestTemplate restTemplate(RestTemplateBuilder builder) {
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
Quote quote = restTemplate.getForObject(
"http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
try {
var quote = restTemplate.getForObject(
"https://dummyjson.com/quotes/random", Quote.class);
if (quote != null) {
log.info(quote.toString());
}
} catch (Exception e) {
log.warn("Could not fetch quote from external service: {}", e.getMessage());
}
};
}

Expand All @@ -64,23 +76,26 @@ public void run(String... args) throws Exception {
log.info("Creating tables");

jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
jdbcTemplate.execute("CREATE TABLE customers(id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");

// Split up the array of whole names into an array of first/last names
List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long")
jdbcTemplate.execute("""
CREATE TABLE customers(
id SERIAL,
first_name VARCHAR(255),
last_name VARCHAR(255)
)""");

List<Object[]> splitUpNames = List.of("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long")
.stream()
.map(name -> name.split(" "))
.map(name -> (Object[]) name.split(" "))
.collect(Collectors.toList());

// Use a Java 8 stream to print out each tuple of the list
splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));

// Uses JdbcTemplate's batchUpdate operation to bulk load data
jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames);

log.info("Querying for customer records where first_name = 'Josh':");
jdbcTemplate.query(
"SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[]{"Josh"},
"SELECT id, first_name, last_name FROM customers WHERE first_name = ?",
new Object[]{"Josh"},
(rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
).forEach(customer -> log.info(customer.toString()));

Expand Down
103 changes: 46 additions & 57 deletions src/main/java/hello/controller/HelloController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,100 +2,89 @@

import hello.declaration.TimeClient;
import hello.model.SimpleTimeClient;
import hello.model.Topic;
import hello.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.chrono.ChronoPeriod;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@RestController
public class HelloController {


String joinTemplate = "Joining All String ID's with JOIN method: ";
String makeDistinctAndSortCharactersTemplate = "-------------Get all ID characters, select distict and sort with ID= ";
String splitAllIdWithColonSelectIDWithJavaKeywordThenSortThenJoinTemplate = "-------------Split All Id With Colon," +
"Select ID With \"Java\" Keyword," +
" Then Sort Then Join ";
String findIdHavingCharacterTemplate = "-------------Return All ID having character \'g\' in it: ";
String findAllFilesInPathAndSortTemplate = "---------Find all files in path and sort: ";
String findParticularFileInPathAndSortTemplate = "----------Find File in present directory which strats with \"grad\",provided maximum depth=25 and sort : ";
String findParticularFileInPathAndSortWithWalkFunctionTemplate = "----------Find File in present directory which strats with \"grad\",provided maximum depth=25 and sort : with walk function";
String readFileWithStreamFunctionTemplate = "---------Read \"temp.txt\" file with stream functions, having \"print\" witin it: ";


@Autowired
private TopicService topicService;

/**
* Java 8 Date Time example
*
* @return
*/
@RequestMapping("/datetime")
public String index() {
TimeClient myTimeClient = new SimpleTimeClient();
LocalDateTime localDateTime = LocalDateTime.now();
return "Greetings from Spring Boot! ----------------------" +
"Datetime now is " + String.valueOf(myTimeClient.toString()) + "----------------------" +
"Datetime tomorrow will be " + String.valueOf(myTimeClient.getLocalDateTime().plusDays(1)) + "----------------------" +
"Datetime of previous month was " + String.valueOf(myTimeClient.getLocalDateTime().minus(1, ChronoUnit.MONTHS)) + "----------------------" +
"Is this a leap year ? " + String.valueOf(LocalDate.now().isLeapYear()) + "----------------------" +
"Default system zone id " + String.valueOf(ZoneId.systemDefault()) + "-------------------" +
"Time in California: " + myTimeClient.getZonedDateTime("Canada/Central").toString();

var myTimeClient = new SimpleTimeClient();
return """
Greetings from Spring Boot! ----------------------\
Datetime now is %s----------------------\
Datetime tomorrow will be %s----------------------\
Datetime of previous month was %s----------------------\
Is this a leap year ? %s----------------------\
Default system zone id %s-------------------\
Time in California: %s""".formatted(
myTimeClient,
myTimeClient.getLocalDateTime().plusDays(1),
myTimeClient.getLocalDateTime().minus(1, ChronoUnit.MONTHS),
LocalDate.now().isLeapYear(),
ZoneId.systemDefault(),
myTimeClient.getZonedDateTime("Canada/Central"));
}


/**
* String Operations in Java 8
*
* @return
*/
@RequestMapping("/topic/string/operation")
public String showStringOperation() {

String join = topicService.returnAllTopicIDWithStringSlicing();
String makeDistinctAndSortCharacters = topicService.makeDistinctAndSortCharacters(join);
String splitAllIdWithColonSelectIDWithJavaKeywordThenSortThenJoin = topicService
var join = topicService.returnAllTopicIDWithStringSlicing();
var makeDistinctAndSortCharacters = topicService.makeDistinctAndSortCharacters(join);
var splitResult = topicService
.splitAllIdWithColonSelectIDWithJavaKeywordThenSortThenJoin(join);
String findIdHavingCharacter = topicService.findIdHavingCharacter();

return joinTemplate + join
+ makeDistinctAndSortCharactersTemplate + makeDistinctAndSortCharacters
+ splitAllIdWithColonSelectIDWithJavaKeywordThenSortThenJoinTemplate + splitAllIdWithColonSelectIDWithJavaKeywordThenSortThenJoin
+ findIdHavingCharacterTemplate + findIdHavingCharacter;

var findIdHavingCharacter = topicService.findIdHavingCharacter();

return """
Joining All String ID's with JOIN method: %s\
-------------Get all ID characters, select distict and sort with ID= %s\
-------------Split All Id With Colon,\
Select ID With "Java" Keyword,\
Then Sort Then Join %s\
-------------Return All ID having character 'g' in it: %s""".formatted(
join,
makeDistinctAndSortCharacters,
splitResult,
findIdHavingCharacter);
}


/**
* File Operation in Java 8
* @return
*/
@RequestMapping("/topic/file/operation")
public String showFileOperation() {
String findAllFilesInPathAndSort = topicService.findAllFilesInPathAndSort();
String findParticularFileInPathAndSort = topicService.findParticularFileInPathAndSort();
String findParticularFileInPathAndSortWithWalkFunction = topicService.findParticularFileInPathAndSortWithWalkFunction();
String readFileWithStreamFunction = topicService.readFileWithStreamFunction();
return findAllFilesInPathAndSortTemplate + findAllFilesInPathAndSort
+ findParticularFileInPathAndSortTemplate + findParticularFileInPathAndSort
+ findParticularFileInPathAndSortWithWalkFunctionTemplate + findParticularFileInPathAndSortWithWalkFunction
+ readFileWithStreamFunctionTemplate + readFileWithStreamFunction;
var findAllFilesInPathAndSort = topicService.findAllFilesInPathAndSort();
var findParticularFileInPathAndSort = topicService.findParticularFileInPathAndSort();
var findWithWalk = topicService.findParticularFileInPathAndSortWithWalkFunction();
var readFile = topicService.readFileWithStreamFunction();
return """
---------Find all files in path and sort: %s\
----------Find File in present directory which strats with "grad",\
provided maximum depth=25 and sort : %s\
----------Find File in present directory which strats with "grad",\
provided maximum depth=25 and sort : with walk function%s\
---------Read "temp.txt" file with stream functions, having "print" witin it: %s""".formatted(
findAllFilesInPathAndSort,
findParticularFileInPathAndSort,
findWithWalk,
readFile);
}



}
Loading