Skip to content

Commit

Permalink
Finished adding file handling support
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonathan Argo authored and Jonathan Argo committed Jan 14, 2017
1 parent d7c41ad commit 16dd4d4
Show file tree
Hide file tree
Showing 6 changed files with 132 additions and 62 deletions.
Binary file added output.xlsx
Binary file not shown.
9 changes: 4 additions & 5 deletions settings.ini
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
[settings]
key =
; If enabled, field names will be given as numeric keys. Useful if the input file does not have a header row
; Currently not supported
; useNumericFieldKeys = 1
outputField = location
overwrite = 0
fullLocationOutputField = full_location
latOutputField = latitude
lngOutputField = longitude
; If your address input field is all in one cell, use the fullAddressField. Otherwise set the individual parts.
fullAddressField =
streetField = street
cityField = city
Expand Down
181 changes: 127 additions & 54 deletions src/main/java/com/jargo/geolookup/GeoLookupController.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package com.jargo.geolookup;

import com.sun.javafx.tk.FileChooserType;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
Expand All @@ -28,19 +30,14 @@
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.ini4j.Wini;

/**
*
* @author jargo
*/

public class GeoLookupController implements Initializable {

@FXML
private Button selectFileButton;
@FXML
private Button okButton;
@FXML
private Button closeButton;
@FXML
private TextField singleAddressField;
@FXML
private TextField selectedFilePath;
Expand All @@ -51,6 +48,7 @@ public class GeoLookupController implements Initializable {

private File selectedFile;
private Wini options;
private List<String> badAddresses;

@Override
public void initialize(URL url, ResourceBundle rb) {
Expand All @@ -65,25 +63,18 @@ public void initialize(URL url, ResourceBundle rb) {
}

String key = options.get("settings", "key");
System.out.println(key);
if (!key.isEmpty()) {
if (key.compareToIgnoreCase("{your key here}") == 0) {
Output.handle("Please add your API key to settings.ini", AlertType.ERROR);
}
}

badAddresses = new ArrayList();
}

@FXML
private void selectFile(ActionEvent event) {
FileChooser fileChooser = new FileChooser();

List<String> extensionList = new ArrayList();
extensionList.add("*.xls");
extensionList.add("*.xlsx");
ExtensionFilter exFilter = new ExtensionFilter("XLS or XLSX", extensionList);
fileChooser.setSelectedExtensionFilter(exFilter);
selectedFile = fileChooser.showOpenDialog(null);
selectedFile = selectSpreadsheetFile(FileChooserType.OPEN, "Select Input File");
if (selectedFile != null) {
selectedFilePath.setText(selectedFile.getPath());
}
Expand All @@ -96,16 +87,21 @@ private void handleInputTypeChange(ActionEvent event) {

@FXML
private void handleOkAction(ActionEvent event) {
// Disable the buttons while we parse the file
okButton.setDisable(true);

// Keep track of the original state of this button
Boolean selectFileButtonDisabled = selectFileButton.isDisable();

if (singleAddressRadioButton.isSelected()) {
lookupSingleAddress(event);
} else if (fileImportRadioButton.isSelected()) {
lookupFromFile(event);
}
}

@FXML
private void handleCloseAction(ActionEvent event) {
// TODO

// Reset to initial value
selectFileButton.setDisable(selectFileButtonDisabled);
okButton.setDisable(false);
}

private void toggleInputType() {
Expand Down Expand Up @@ -161,40 +157,65 @@ private void lookupFromFile(ActionEvent event) {
}

if (wb != null) {
List<String> addresses = parseInputFile(wb);
makeLookups(addresses);
parseInputFile(wb);
try {
//Write the result
File outputFile = selectSpreadsheetFile(FileChooserType.SAVE, "Save Result");
FileOutputStream outputStream = new FileOutputStream(outputFile);
wb.write(outputStream);
outputStream.close();
} catch (IOException ex) {
Output.handle("Failed to write output file: " + ex.getMessage(), AlertType.ERROR);
}

if (!badAddresses.isEmpty()) {
String newLine = System.getProperty("line.separator");
String badAddressWarning = "The following addresses were unable to be converted:" + newLine;
for (String badAddress : badAddresses) {
badAddressWarning += badAddress + newLine;
}

Output.handle(badAddressWarning, AlertType.WARNING);
}
} else {
Output.handle("Failed to read workbook.", AlertType.ERROR);
}
}
inputStream.close();
} catch (FileNotFoundException ex) {
Output.handle("Selected input file not found.", AlertType.ERROR);
} catch (IOException ex) {
Output.handle("Failed to read input file: "+ex.getMessage(), AlertType.ERROR);
}
}

protected List<String> parseInputFile(Workbook wb) {
protected void parseInputFile(Workbook wb) {
List<String> addresses = new ArrayList<>();

Boolean headersSet = false;

// Input keys
int fullAddressKey = -1;
int streetKey = -1;
int cityKey = -1;
int stateKey = -1;
int zipKey = -1;

// Output keys
int latKey = -1;
int lngKey = -1;
int fullLocationKey = -1;

String fullAddressFieldName = options.get("settings", "fullAddressField");
String streetFieldName = options.get("settings", "streetField");
String cityFieldName = options.get("settings", "cityField");
String stateFieldName = options.get("settings", "stateField");
String zipFieldName = options.get("settings", "zipField");

String fullAddress = null;
String street = null;
String city = null;
String state = null;
String zip = null;
String fullAddress;
String street;
String city;
String state;
String zip;

// Go through our spreadsheet and parse the results.
try {
Expand All @@ -205,6 +226,7 @@ protected List<String> parseInputFile(Workbook wb) {
int i = 0;
for (Cell cell : row) {
// Does this field name match one of our input fields? If so, keep track of the key
// Probably a better way to do this...
String cellValue = cell.getStringCellValue();
if (cellValue.compareToIgnoreCase(fullAddressFieldName) == 0) {
fullAddressKey = i;
Expand All @@ -222,8 +244,28 @@ protected List<String> parseInputFile(Workbook wb) {

if (fullAddressKey == -1 && (streetKey == -1 && cityKey == -1 && stateKey == -1 && zipKey == -1)) {
Output.handle("Failed to find appropriate fields in input file.", AlertType.ERROR);
return null;
return;
}

// Get the output field headers
String latOutputField = options.get("settings", "latOutputField");
String lngOutputField = options.get("settings", "lngOutputField");
String fullLocationOutputField = options.get("settings", "fullLocationOutputField");

// Add headers as necessary
if (!latOutputField.isEmpty()) {
latKey = row.getLastCellNum();
row.createCell(latKey, CellType.STRING).setCellValue(latOutputField);
}
if (!lngOutputField.isEmpty()) {
lngKey = row.getLastCellNum();
row.createCell(lngKey, CellType.STRING).setCellValue(lngOutputField);
}
if (!fullLocationOutputField.isEmpty()) {
fullLocationKey = row.getLastCellNum();
row.createCell(fullLocationKey, CellType.STRING).setCellValue(fullLocationOutputField);
}

headersSet = true;
} else {
// Assemble the address and add it to the list
Expand All @@ -240,37 +282,68 @@ protected List<String> parseInputFile(Workbook wb) {

fullAddress = street + " " + city + " " + state + " " + zip;
}

ApiResponseResult responseResult = lookupAddress(fullAddress);
if (responseResult != null) {
// This result is going in our output. Add new columns as necessary.
// Todo - support overwriting file
String lat = String.valueOf(responseResult.getGeometry().getLocation().getLat());
String lng = String.valueOf(responseResult.getGeometry().getLocation().getLng());

if (latKey != -1) {
row.createCell(latKey, CellType.STRING).setCellValue(lat);
}
if (lngKey != -1) {
row.createCell(lngKey, CellType.STRING).setCellValue(lng);
}
if (fullLocationKey != -1) {
row.createCell(fullLocationKey, CellType.STRING).setCellValue(lat+","+lng);
}
} else {
// We'll deal with these later
badAddresses.add(fullAddress);
}
}
}
}
}
} catch (Exception ex) {
Output.handle("An unknown error occurred while parsing input file: "+ex.getMessage());
return null;
}
return addresses;
}

protected void makeLookups(List<String> addresses) {
for (String address : addresses) {
LookupConnector lookupConnector = new LookupConnector();
lookupConnector.setAddress(address);
lookupConnector.setKey(this.getKey());
ApiResponse apiResponse = ApiResponseBuilder.buildApiResponse(lookupConnector);

List<String> badAddresses = new ArrayList();
if (apiResponse.getResults().size() > 1 || apiResponse.getStatus().compareToIgnoreCase("OK") != 0) {
badAddresses.add(address);
} else {
ApiResponseResult result = apiResponse.getResults().get(0);

String newLine = System.getProperty("line.separator");
String outputText;
protected ApiResponseResult lookupAddress(String address) {
ApiResponseResult result = null;

LookupConnector lookupConnector = new LookupConnector();
lookupConnector.setAddress(address);
lookupConnector.setKey(this.getKey());
ApiResponse apiResponse = ApiResponseBuilder.buildApiResponse(lookupConnector);

outputText = "Status: " + apiResponse.getStatus() + newLine;
outputText += "Formatted address: " + result.getFormattedAdddress() + newLine;
System.out.println(address+" - "+result.getFormattedDegrees());
}
if (apiResponse.getResults().size() == 1 || apiResponse.getStatus().compareToIgnoreCase("OK") == 0) {
result = apiResponse.getResults().get(0);
}

return result;
}

protected File selectSpreadsheetFile(FileChooserType type, String title) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(title);

File result = null;
if (type == FileChooserType.OPEN) {
fileChooser.getExtensionFilters().add(new ExtensionFilter("Microsoft Excel Spreadsheet", "*.xls", "*.xlsx"));
result = fileChooser.showOpenDialog(null);
} else if (type == FileChooserType.SAVE) {
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Microsoft Excel 2007-2013 XML (.xlsx)", "*.xlsx"),
new ExtensionFilter("Microsoft Excel 97-2003 (.xls)", "*.xls")
);
result = fileChooser.showSaveDialog(null);
}

return result;

}

protected String getKey() {
Expand All @@ -287,10 +360,10 @@ protected String getKey() {
}

} catch (FileNotFoundException ex) {
System.out.println("Could not find file.");
Output.handle("Could not find file.", AlertType.ERROR);

} catch (IOException ex) {
System.out.println("IOException");
Output.handle("An error occurred while reading the key file: "+ex.getMessage(), AlertType.ERROR);
}
} else {
returnVal = key;
Expand Down
1 change: 0 additions & 1 deletion src/main/resources/fxml/GeoLookup.fxml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
<HBox alignment="CENTER_RIGHT" prefHeight="35.0" prefWidth="500.0" spacing="5.0">
<children>
<Button fx:id="okButton" mnemonicParsing="false" onAction="#handleOkAction" prefWidth="70.0" text="OK" />
<Button fx:id="closeButton" mnemonicParsing="false" onAction="#handleCloseAction" prefWidth="70.0" text="Close" />
</children>
<VBox.margin>
<Insets right="25.0" />
Expand Down
1 change: 0 additions & 1 deletion target/classes/fxml/GeoLookup.fxml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
<HBox alignment="CENTER_RIGHT" prefHeight="35.0" prefWidth="500.0" spacing="5.0">
<children>
<Button fx:id="okButton" mnemonicParsing="false" onAction="#handleOkAction" prefWidth="70.0" text="OK" />
<Button fx:id="closeButton" mnemonicParsing="false" onAction="#handleCloseAction" prefWidth="70.0" text="Close" />
</children>
<VBox.margin>
<Insets right="25.0" />
Expand Down
2 changes: 1 addition & 1 deletion target/maven-archiver/pom.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#Generated by Maven
#Fri Jan 13 00:52:03 EST 2017
#Sat Jan 14 01:03:35 EST 2017
version=1.0-SNAPSHOT
groupId=com.jargo
artifactId=GeoLookup

0 comments on commit 16dd4d4

Please sign in to comment.