Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package service; import com.csvreader.CsvWriter; import exception.GoEuroException; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import model.GoEuroModel; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * * @author NrapendraKumar */ public class GoEuroServiceImpl implements GoEuroService { private static final Logger logger = Logger.getLogger(GoEuroServiceImpl.class.getName()); private static final String URL_SOURCE = "http://api.goeuro.com/api/v2/position/suggest/en/"; private static final String ID = "_id"; private static final String NAME = "name"; private static final String TYPE = "type"; private static final String GEO_POSITION = "geo_position"; private static final int ZERO_INDEX_POSITION = 0; private static final int ONE_INDEX_POSITION = 1; private static final String COMMA = ","; private static final String COLON = ":"; private static final String CLOSING_CURLY_BRACE = "}"; private static final String FILE_DIRECTORY_NAME = "goEuroDirectory"; private static final String FILE_NAME = "goEuroFile"; private static final String FILE_TYPE = ".csv"; private static final String REMOVABLE_CHARACTERS = "[^\\d.]"; private static final String ID_HEADER = "_id"; private static final String NAME_HEADER = "name"; private static final String TYPE_HEADER = "type"; private static final String LATITUDE_HEADER = "latitude"; private static final String LONGITUDE_HEADER = "longitude"; @Override public List<GoEuroModel> convertJsonDataToModel(String cityName) { String completeUrl = URL_SOURCE + cityName; List<GoEuroModel> goEuroModels = new LinkedList<>(); try { URL url = new URL(completeUrl); URLConnection urlConnection = url.openConnection(); urlConnection.setDoInput(true); if (url.getContent() != null) { InputStream is = url.openStream(); String jsonData = getJsonData(new BufferedReader(new InputStreamReader(is))); JSONArray jsonArray = new JSONArray(jsonData); int jsonArrayLength = jsonArray.length(); for (int i = 0; i < jsonArrayLength; i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); GoEuroModel goEuroModel = new GoEuroModel(); goEuroModel.set_id(Long.parseLong(jsonObject.get(ID).toString())); goEuroModel.setName(jsonObject.get(NAME).toString()); goEuroModel.setType(jsonObject.get(TYPE).toString()); goEuroModel.setLatitude(Double .parseDouble(jsonObject.get(GEO_POSITION).toString().split(COMMA)[ZERO_INDEX_POSITION] .split(COLON)[ONE_INDEX_POSITION])); goEuroModel.setLongitude(Double .parseDouble(jsonObject.get(GEO_POSITION).toString().split(COMMA)[ONE_INDEX_POSITION] .split(COLON)[ONE_INDEX_POSITION] .split(CLOSING_CURLY_BRACE)[ZERO_INDEX_POSITION])); goEuroModels.add(goEuroModel); } } } catch (MalformedURLException e) { throw new GoEuroException(e.getMessage()); } catch (IOException | JSONException e) { throw new GoEuroException(e.getMessage()); } return goEuroModels; } @Override public String getCsvFilePath() { String filePath = null; File file = new File(FILE_DIRECTORY_NAME); if (!file.exists()) { file.mkdirs(); } String fileName = FILE_NAME; File requiredFile = new File(file, fileName + FILE_TYPE); if (!requiredFile.exists()) { try { requiredFile.createNewFile(); setHeadersToCsvFile(); filePath = requiredFile.getAbsolutePath(); } catch (IOException e) { throw new GoEuroException(e.getMessage()); } } else { filePath = requiredFile.getAbsolutePath(); } return filePath; } private void setHeadersToCsvFile() { try { CsvWriter csvWriter = new CsvWriter( new OutputStreamWriter(new FileOutputStream(new File(this.getCsvFilePath()), true)), ','); csvWriter.write(ID_HEADER); csvWriter.write(NAME_HEADER); csvWriter.write(TYPE_HEADER); csvWriter.write(LATITUDE_HEADER); csvWriter.write(LONGITUDE_HEADER); csvWriter.endRecord(); csvWriter.close(); } catch (IOException e) { throw new GoEuroException(e.getMessage()); } } @Override public void writeModeltoCsvFile(List<GoEuroModel> goEuroModels) { try { CsvWriter csvWriter = new CsvWriter( new OutputStreamWriter(new FileOutputStream(new File(this.getCsvFilePath()), true)), ','); List<Long> currentGoEuroModelIds = new LinkedList<>(); List<Long> csvFileIds = getIds(this.getCsvFilePath()); long goEuroModelId; for (GoEuroModel goEuroModel : goEuroModels) { goEuroModelId = goEuroModel.get_id(); if (!csvFileIds.contains(goEuroModelId) && !currentGoEuroModelIds.contains(goEuroModel.get_id())) { currentGoEuroModelIds.add(goEuroModelId); csvWriter.write(((Long) goEuroModelId).toString()); csvWriter.write(goEuroModel.getName()); csvWriter.write(goEuroModel.getType()); csvWriter.write(((Double) goEuroModel.getLatitude()).toString()); csvWriter.write(((Double) goEuroModel.getLongitude()).toString()); csvWriter.endRecord(); } } csvWriter.close(); } catch (IOException e) { throw new GoEuroException(e.getMessage()); } } private String getJsonData(BufferedReader br) { String line; String jsonData = ""; try { while ((line = br.readLine()) != null) { jsonData = jsonData + line; } } catch (IOException e) { throw new GoEuroException(e.getMessage()); } return jsonData.trim(); } private List<Long> getIds(String filePath) { List<Long> longList = new LinkedList<>(); String line; try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { while ((line = br.readLine()) != null) { logger.log(Level.INFO, "Line value is : {0}", line); if (!line.contains(ID_HEADER)) { longList.add(Long.parseLong(convertCsvLineToGoEuroModelId(line))); } } } catch (FileNotFoundException e) { throw new GoEuroException(e.getMessage()); } catch (IOException ex) { Logger.getLogger(GoEuroServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } return longList; } private String convertCsvLineToGoEuroModelId(String csvLine) { String goEuroModelId = csvLine.trim().split(COMMA)[ZERO_INDEX_POSITION]; goEuroModelId = goEuroModelId.replaceAll(REMOVABLE_CHARACTERS, "") != null ? goEuroModelId.replaceAll(REMOVABLE_CHARACTERS, "") : goEuroModelId; logger.log(Level.INFO, "Id Value is : {0}", goEuroModelId); return goEuroModelId; } }