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 iplantappssplitter; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.json.*; /** * IPlantAppsSplitter class takes an inputfile from the RESTful endpoint * https://foundation.iplantc.org/apps-v1/apps/list and splits into separate * tool JSON objects then writes each one to the specified output folder * * @author Bill Conn <Bill.Conn@usd.edu> */ public class IPlantAppsSplitter { private final static Args myArgs = new Args(); //default file and output directory private final static String defaultFile = "iplant_tool_list_12-14.json"; private final static String defaultDir = "outputs/"; /** * @param args the command line arguments */ public static void main(String[] args) { //setup some stuff CheckArgs(args); SetupInputOutput(); //splitty splitty sittin pretty String JsonString = ReadFile(myArgs.getInputFile()); try { if (isJSONValid(JsonString)) { SplitJsonFile(JsonString); } else { System.out.println("Not a valid JSON file"); } } catch (JSONException e) { System.out.println(e.getMessage()); } } /** * SplitJsonFile takes a string of Json and splits it based on a list of * iPlant tools specified by the 'result' key. This works for iPlant * foundation API JSON only. It works on the JSON from the RESTful * endpoint https://foundation.iplantc.org/apps-v1/apps/list * @param JsonFile * @throws JSONException */ public static void SplitJsonFile(String JsonFile) throws JSONException { JSONObject array = new JSONObject(JsonFile); JSONArray tools = new JSONArray(array.getString("result")); System.out.println("Splitting " + tools.length() + " tools..."); for (int i = 0; i < tools.length(); i++) { JSONObject tool = tools.getJSONObject(i); WriteFile(tool.getString("id") + ".json", tool.toString(4)); } } /** * ReadFile reads the file specified by filename and then returns a string * with the entire contents of the file. * @param filename * @return */ public static String ReadFile(String filename) { String Json = null; try { byte[] encoded = Files.readAllBytes(Paths.get(filename)); Json = new String(encoded); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } return Json; } /** * WriteFile writes the string jsonToWrite to the file filename * @param filename * @param jsonToWrite */ public static void WriteFile(String filename, String jsonToWrite) { try { Files.write(Paths.get(myArgs.getOutputDirectory() + filename), jsonToWrite.getBytes()); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } } /** * SetupInputOutput checks to see that we can find both the inputfile and * then makes the output directory. If something goes wrong with IO then * this function will exit. */ private static void SetupInputOutput() { File infile = new File(myArgs.getInputFile()); try { if (!infile.exists()) { throw new IOException("Input File: " + myArgs.getInputFile() + " not found."); } } catch (Exception e) { System.err.println(e.getMessage()); System.err.println("Exiting..."); System.exit(-1); } File dir = new File(myArgs.getOutputDirectory()); try { if (!dir.exists()) { Boolean status = dir.mkdir(); if (!status) { throw new IOException("Could not create directory: " + myArgs.getOutputDirectory()); } } } catch (Exception e) { System.err.println(e.getMessage()); System.err.println("Exiting..."); System.exit(-1); } } /** * CheckArgs checks the args array for the args listed in the Args subclass * when it finds input, it sets the input, if it finds the output directory * it sets that. If it finds a request for help, or no inputs it will * default to the default input and output directory. * default input: iplant_tool_list_12-14.json * default dir: outputs * @param localArgs */ private static void CheckArgs(String[] localArgs) { List<String> listArgs = Arrays.asList(localArgs); for (int i = 0; i < listArgs.size(); i++) { if (myArgs.getInputFileFlags().contains(listArgs.get(i))) { i++; //move to the next arg if (i < listArgs.size()) { myArgs.setInputFile(listArgs.get(i)); } continue; } if (myArgs.getOutputDirectoryFlags().contains(listArgs.get(i))) { i++; //move to the next arg if (i < listArgs.size()) { myArgs.setOutputDirectory(listArgs.get(i)); } continue; } if (myArgs.getHelpFlags().contains(listArgs.get(i))) { printHelp(); System.exit(0); } } if (myArgs.getInputFile() == null) { System.err.println("No input file specified, using default: " + defaultFile); myArgs.setInputFile(defaultFile); } if (myArgs.getOutputDirectory() == null) { System.err.println("No output directory specified, using default: " + defaultDir); myArgs.setOutputDirectory(defaultDir); } } /** * isJSONValid checks to see if a particular string is valid json or not * returns true if it is, false if it is not, checks both json objects and * json arrays. * @param test * @return */ public static boolean isJSONValid(String test) { try { new JSONObject(test); } catch (JSONException ex) { try { new JSONArray(test); } catch (JSONException ex1) { return false; } } return true; } /** * printHelp simply prints the help information to std out. */ private static void printHelp() { StringBuilder sb = new StringBuilder(); sb.append(" iPlant App JSON Converter - V1.0\n"); sb.append("-------------------------------------------------------------\n"); sb.append(" input file: ").append(myArgs.getInputFileFlags()).append("\n"); sb.append(" ouput directory: ").append(myArgs.getOutputDirectoryFlags()).append("\n"); sb.append("\n"); sb.append(" Defaults"); sb.append(" input: ").append(defaultFile).append("\n"); sb.append(" directory: ").append(defaultDir).append("\n"); sb.append("\n"); sb.append(" This help: ").append(myArgs.getHelpFlags()).append("\n"); System.out.println(sb); } // <editor-fold defaultstate="collapsed" desc="Args subclass."> private static class Args { private String inputFile; private List<String> inputFileFlags; private String outputDirectory; private List<String> outputDirectoryFlags; private List<String> helpFlags; public Args() { inputFileFlags = new ArrayList(); inputFileFlags.add("-i"); inputFileFlags.add("--input-file"); outputDirectoryFlags = new ArrayList(); outputDirectoryFlags.add("-o"); outputDirectoryFlags.add("--output-directory"); helpFlags = new ArrayList(); helpFlags.add("-h"); helpFlags.add("--help"); } // <editor-fold defaultstate="collapsed" desc="getters and setters."> public String getInputFile() { return inputFile; } public void setInputFile(String inputFile) { this.inputFile = inputFile; } public String getOutputDirectory() { return outputDirectory; } public void setOutputDirectory(String outputDirectory) { this.outputDirectory = outputDirectory; } public List<String> getInputFileFlags() { return inputFileFlags; } public List<String> getOutputDirectoryFlags() { return outputDirectoryFlags; } public List<String> getHelpFlags() { return helpFlags; } // </editor-fold> } // </editor-fold> }