Commit eaa6de41 authored by ccottier's avatar ccottier

Methods created for getting address from other microservice

parent d0603b01
......@@ -34,6 +34,7 @@ dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-config'
implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap:3.0.2'
implementation "io.springfox:springfox-boot-starter:3.0.0"
compile 'org.json:json:20210307'
}
dependencyManagement {
......
......@@ -2,9 +2,17 @@ package com.student.details.services;
import com.student.details.exceptions.ResourceNotFoundException;
import com.student.details.models.Student;
import com.student.details.repositories.StudentRepository;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
......@@ -16,7 +24,6 @@ public class StudentService {
@Autowired
StudentRepository studentRepository;
public List<Student> findAllStudents() {
return studentRepository.findAll();
}
......@@ -55,4 +62,76 @@ public class StudentService {
response.put("deleted", true);
return response;
}
public Student getStudentAddressFromEmail(Student student){
//get students email for api call
String email = student.getEmail();
String apiUrl = String.format("url/students/%s", email);
//make API call other microservice's Rest API
JSONObject response = getJSONObjectFromAPICall(apiUrl);
//make new address object with JSON response object
/*
Address address;
address.setStreet(res.get("street"));
...
*/
//add it to our student's address field!
/*
student.setAddress(address);
*/
return student;
}
public JSONObject getJSONObjectFromAPICall(String apiUrl){
HttpURLConnection connection;
StringBuffer responseContent = new StringBuffer();
BufferedReader reader;
String line;
try {
URL url = new URL(apiUrl);
connection = (HttpURLConnection) url.openConnection();
//setup
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int status = connection.getResponseCode();
//read and write
if (status > 299) {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}
while((line = reader.readLine()) != null){
responseContent.append(line);
}
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject res = new JSONObject(responseContent.toString());
return res;
}
}
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