I want to load JSON data from a link at the beginning of an application.
I need to be a little bit about clear the following code.
And also want to ask about another opinions that what could be the best approach if I need to read from a URL and want to read data from this resource.
package com.app;
import com.app.entity.Event;
import com.app.service.EventCommandService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
@SpringBootApplication
public class Application {
static HttpURLConnection connection;
Logger logger = LoggerFactory.getLogger(Application.class);
@Value("${url.path}")
String urlValue;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner runner(CommandService CommandService) {
return args -> {
BufferedReader reader;
String line;
StringBuilder responseContent = new StringBuilder();
// read json and write to db
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Event>> typeReference = new TypeReference<>() {
};
try {
URL url = new URL(urlValue);
connection = (HttpURLConnection) url.openConnection();
// Request setup
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
int index = responseContent.toString().indexOf("[{");
byte[] bytes = responseContent.substring(index).getBytes();
InputStream inputStream = new ByteArrayInputStream(bytes);
try {
List<Event> events = mapper.readValue(inputStream, typeReference);
// Save events to h2 db
CommandService.save(events);
logger.info("Events Saved");
} catch (IOException e) {
logger.info("Unable to save events: {}", e.getMessage());
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
};
}
}