NewServiceCall.java [src/cokeyconverter] Revision: default Date:
/*
* 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 cokeyconverter;
import static cokeyconverter.ModelArchive.FAILED_MESSAGE;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author <a href="mailto:shaun.case@colostate.edu">Shaun Case</a>
*/
public class NewServiceCall implements Runnable {
String URI;
ModelArchive model;
File csvFile;
NewServiceCall(String URI, ModelArchive model, File csvFile) {
this.URI = URI;
this.model = model;
this.csvFile = csvFile;
}
@Override
public void run() {
Client newRequest = new Client();
try {
model.setNewResponse(newRequest.doPOST(URI, model.getNewRequest()));
String[] result = model.getRusle2CompareSLOPE_DEGRAD();
String outLine = model.getSUID() + "," + model.getLatitude() + "," + model.getLongitude() + "," + model.getOldCokey() + "," + result[0] + "," + model.getNewCokey() + "," + result[1] + "\n";
AppendCSVFile(outLine);
if (result[0].equalsIgnoreCase(FAILED_MESSAGE) || result[1].equalsIgnoreCase(FAILED_MESSAGE)) {
writeFile(model.getSUID() + ".json", model.getNewRequest().toString());
writeFile(model.getSUID() + "-original" + ".json", model.getOriginalRequest().toString());
writeFile(model.getSUID() + "-response.json", model.getNewResponse().toString());
writeFile(model.getSUID() + "-original-response" + ".json", model.getOriginalResponse().toString());
}
model.clearStorage();
} catch (Exception ex) {
System.err.println("Failed to call: " + URI + ", and receive results for new data for SUID: " + model.getSUID());
Logger.getLogger(NewServiceCall.class.getName()).log(Level.SEVERE, null, ex);
}
}
private synchronized void AppendCSVFile(String outLine) {
try (FileWriter fileWriter = new FileWriter(csvFile.getAbsoluteFile(), true);
BufferedWriter buffWriter = new BufferedWriter(fileWriter);) {
buffWriter.write(outLine);
} catch (IOException ex) {
Logger.getLogger(NewServiceCall.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void writeFile(String filename, String data) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filename), "utf-8"))) {
writer.write(data);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(CokeyConverter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(CokeyConverter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}