Commit b0d42e7f authored by Divisha Agarwal's avatar Divisha Agarwal

POC on Hateoas

parent af756a30
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
This diff is collapsed.
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.nisum</groupId>
<artifactId>hateoas</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hateoas</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<mockito-core.version>1.10.19</mockito-core.version>
<powermock-module-junit4.version>2.0.4</powermock-module-junit4.version>
<powermock-api-mockito.version>1.7.4</powermock-api-mockito.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.hateoas/spring-hateoas -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-hateoas -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-cassandra -->
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
<version>0.24.0.RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.26</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
<exclusion>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-core.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.objenesis</groupId>
<artifactId>objenesis</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock-module-junit4.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.powermock</groupId>
<artifactId>powermock-reflect</artifactId>
</exclusion>
<exclusion>
<groupId>org.objenesis</groupId>
<artifactId>objenesis</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock-api-mockito.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.nisum.Clients;
import com.nisum.HateoasApplication;
import com.nisum.constants.Constants;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class HttpClient {
@Autowired
HateoasApplication hateoasApplication;
//Using HTTP (Method 2)
public void getUsingHttpClient() throws IOException, ParseException {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(Constants.URL_EMPLOYEES);
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
} else {
int i = 0;
JSONObject obj = null;
do {
if (i == 0) {
System.out.println(response);
obj = getJsonObjectHttp(response, 0);
hateoasApplication.saveInFile(obj, i);
} else {
URL url = new URL(obj.get("next").toString());
HttpGet getRequestNew = new HttpGet(url.toString());
getRequestNew.addHeader("accept", "application/json");
HttpResponse responseNew = httpClient.execute(getRequestNew);
JSONObject objnew = getJsonObjectHttp(responseNew, i);
hateoasApplication.saveInFile(objnew, i);
obj = objnew;
}
i++;
} while (i <= Constants.no_of_pages - 1);
httpClient.getConnectionManager().shutdown();
}
}
catch(RuntimeException e){
e.getStackTrace();
}
}
//Method to get a json object from the content of a get call when using httpClient
public JSONObject getJsonObjectHttp(HttpResponse response, int i) throws IOException, ParseException {
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
output=br.readLine();
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(output);
return obj;
}
}
package com.nisum.Clients;
import com.nisum.HateoasApplication;
import com.nisum.constants.Constants;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class RestTemplateClient {
@Autowired
HateoasApplication hateoasApplication;
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
//using Spring Rest Template(Method 1)
public void getUsingRestTemplate() {
try {
int i = 0;
JSONObject obj = null;
do {
if (i == 0) {
obj = getJSONObject(Constants.URL_EMPLOYEES);
hateoasApplication.saveInFile(obj, 0);
} else {
JSONObject objnew = getJSONObject(obj.get("next").toString());
hateoasApplication.saveInFile(objnew, i);
obj = objnew;
}
i++;
} while (i <= Constants.no_of_pages - 1);
}
catch(ParseException e){
e.getStackTrace();
}
catch(IOException ex){
ex.getStackTrace();
}
}
//Method to get a json object from the content of a get call when using rest template
public JSONObject getJSONObject(String URL) throws ParseException {
String result = getRestTemplate().getForObject(URL, String.class);
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(result);
return obj;
}
}
package com.nisum;
import com.nisum.Clients.HttpClient;
import com.nisum.Clients.RestTemplateClient;
import com.nisum.constants.Constants;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import java.io.*;
import java.net.URL;
@SpringBootApplication
public class HateoasApplication {
@Autowired
RestTemplateClient restTemplateClient;
@Autowired
HttpClient httpClient;
//Get Calls using 2 clients:Rest client and HttpClient
public static void main(String[] args) {
try {
SpringApplication.run(HateoasApplication.class, args);
HateoasApplication ha = new HateoasApplication();
restTemplateClient.getUsingRestTemplate();
hhttpClient.getUsingHttpClient();
} catch (ParseException e) {
e.getStackTrace();
} catch (IOException ex) {
ex.getStackTrace();
}
catch(Exception et){
et.getStackTrace();
}
}
//Method to save the json object to different files with data of each page in separate file
public void saveInFile(JSONObject jsonObject, int i) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\Backup Folder\\hateoas" + (i + 1) + ".json"));
writer.newLine();
writer.write(jsonObject.toString());
writer.close();
}
}
package com.nisum.constants;
public class Constants {
public static final int page_size=5;
public static final int no_of_pages=4;
public static final String URL_EMPLOYEES = "http://localhost:8080/start/users/0";
}
package com.nisum.controller;
import com.nisum.model.FirstResponse;
import com.nisum.model.User;
import com.nisum.model.Users;
import com.nisum.service.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.file.ConfigurationSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.QueryParam;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
@Slf4j
@RestController
@RequestMapping(value = "/start")
public class UserController {
public int startOffset=0;
@Autowired
UserServiceImpl userServiceImpl;
@Autowired
private RestTemplate restTemplate;
@GetMapping("/users/firstpage")
public Resource<FirstResponse> getFirstPage() {
FirstResponse fr=new FirstResponse();
log.info("Getting all Users...");
Resource<FirstResponse> resource=new Resource<>(fr);
ControllerLinkBuilder linkTo=linkTo(ControllerLinkBuilder.methodOn(this.getClass()).getAllUsers(0));
resource.add(linkTo.withRel("all_users"));
return resource;
}
@GetMapping("/users/{startOffset}")
public Users getAllUsers(@PathVariable("startOffset") int startOffset) {
return userServiceImpl.getAllUsers(startOffset);
}
}
package com.nisum.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FirstResponse {
private int no_of_pages=4;
}
package com.nisum.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String place;
}
package com.nisum.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import java.net.URI;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Users {
private int page_no;
private List<User> users;
private URI next;
private URI previous;
}
package com.nisum.service;
import com.nisum.model.User;
import com.nisum.model.Users;
import org.springframework.hateoas.Resource;
import java.util.List;
import java.util.Map;
public interface UserService {
List<User> getList();
Users getAllUsers(int startOffset);
}
package com.nisum.service;
import com.nisum.constants.Constants;
import com.nisum.controller.UserController;
import com.nisum.model.User;
import com.nisum.model.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import static com.nisum.constants.Constants.page_size;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
//Server End Code
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserController userController;
private User buildUser(Integer id, String name, String place){
User user=new User(id,name,place);
return user;
}
public List<User> getList(){
List<User> UserList=new ArrayList<>();
UserList.add(buildUser(1,"Divisha","Udaipur"));
UserList.add(buildUser(2,"Ashwarya","Hyderabad"));
UserList.add(buildUser(3,"Vinit","Delhi"));
UserList.add(buildUser(4,"Deepika","Jaipur"));
UserList.add(buildUser(5,"Priyanka","Mumbai"));
UserList.add(buildUser(6,"Rahul","Pune"));
UserList.add(buildUser(7,"Dev","Bangalore"));
UserList.add(buildUser(8,"Kapil","Kochi"));
UserList.add(buildUser(9,"Sachin","Bhopal"));
UserList.add(buildUser(10,"Yuvraj","Indore"));
UserList.add(buildUser(11,"Virat","Ahmedabad"));
UserList.add(buildUser(12,"Rohit","Kozikhode"));
UserList.add(buildUser(13,"Virendra","Rohtak"));
UserList.add(buildUser(14,"Mithali","Ranchi"));
UserList.add(buildUser(15,"Shafali","Nagpur"));
UserList.add(buildUser(16,"Harmanpreet","Vishakhapatnam"));
UserList.add(buildUser(17,"Veda","Sambalpur"));
UserList.add(buildUser(18,"Smriti","Jamshedpur"));
UserList.add(buildUser(19,"Sania","Goa"));
UserList.add(buildUser(20,"Usha","Noida"));
return UserList;
}
@Override
public Users getAllUsers(int startOffset) {
int i ;
for (i = 0; i <= getList().size(); i = i + page_size) {
List<User> subList = getList().subList(startOffset, startOffset + page_size);
Users userList = new Users();
userList.setUsers(subList);
userList.setPage_no((startOffset/page_size)+1);
Resource<Users> resource = new Resource<Users>(userList);
ControllerLinkBuilder next = linkTo(ControllerLinkBuilder.methodOn(UserController.class).getAllUsers(startOffset + page_size));
ControllerLinkBuilder previous = linkTo(ControllerLinkBuilder.methodOn(UserController.class).getAllUsers(startOffset-page_size ));
if(startOffset==getList().size()-page_size) {
userList.setNext(null);
}
else {
userList.setNext(next.toUri());
}
if (startOffset == 0){
userList.setPrevious(null);
}
else
{
userList.setPrevious(previous.toUri());
}
resource.add(next.withRel("all_users"));
return userList;
}
return null;
}
}
spring:
data:
cassandra:
keyspace-name: userspace # We need to create keyspace manually from cassandra console
contact-points:
- 127.0.0.1 # IP Address where Cassandra is running
port: 9042
schema-action: create_if_not_exists
server:
port: 8080
package com.nisum;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.IOException;
import static org.mockito.Mockito.*;
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("jdk.internal.reflect.*")
@PrepareForTest({HateoasApplication.class,JSONObject.class})
public class HateoasApplicationTests {
@InjectMocks
HateoasApplication hateoasApplication;
@Mock
public JSONParser parser;
@Before()
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
JSONObject mock = Mockito.mock(JSONObject.class);
when(hateoasApplication.getRestTemplate().getForObject(anyString(),String.class)).thenReturn(anyString());
when(parser.parse(anyString())).thenReturn(mock);
when(hateoasApplication.getJSONObject(anyString())).thenReturn(mock);
}
@Test
public void getUsingRestTemplateTest() throws IOException, ParseException {
hateoasApplication.getUsingRestTemplate();
}
@Test
public void getUsingHttpClientTest() throws IOException, ParseException {
DefaultHttpClient httpClient = mock(DefaultHttpClient.class);
HttpGet getRequest = mock(HttpGet.class);
HttpResponse httpResponse = mock(HttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
when(statusLine.getStatusCode()).thenReturn(200);
when(httpResponse.getStatusLine()).thenReturn(statusLine);
when(httpClient.execute(getRequest)).thenReturn((CloseableHttpResponse) httpResponse);
Assert.assertEquals(statusLine.getStatusCode(),200);
hateoasApplication.getUsingHttpClient();
}
@Test
public void getUsingHttpClientExceptionTest() throws IOException, ParseException {
HttpClient httpClient = mock(HttpClient.class);
HttpGet httpGet = mock(HttpGet.class);
StatusLine statusLine = mock(StatusLine.class);
when(httpClient.execute(httpGet)).thenThrow(RuntimeException.class);
Assert.assertEquals(statusLine.getStatusCode(),0);
hateoasApplication.getUsingHttpClient();
}
@Test
public void getJSONObjectTest() throws ParseException, IOException {
verify(hateoasApplication.getJSONObject(anyString()), times(4));
}
@Test
public void getJSONObjectHttpTest() throws ParseException, IOException {
verify(hateoasApplication.getJsonObjectHttp(any(HttpResponse.class),anyInt()), times(4));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment