List of usage examples for java.io IOException getMessage
public String getMessage()
From source file:at.ac.tuwien.inso.subcat.ui.ViewFactory.java
public static void main(String[] args) { Options options = new Options(); options.addOption("h", "help", false, "Show this options"); options.addOption("d", "db", true, "The database to process (required)"); options.addOption("p", "project", true, "The project ID to process"); options.addOption("P", "list-projects", false, "List all registered projects"); options.addOption("C", "config", true, "A configuration file including reports"); options.addOption("c", "commit-dictionary", true, "The commit dictionary ID to use"); options.addOption("b", "bug-dictionary", true, "The bug dictionary ID to use"); options.addOption("D", "list-dictionaries", false, "List all dictionaries"); options.addOption("e", "db-extension", true, "Sqlite extension"); options.addOption("v", "verbose", false, "Show details"); Reporter reporter = new Reporter(false); String[] extensions = new String[0]; ModelPool pool = null;/*from w ww .jav a2s. co m*/ Model model = null; CommandLineParser parser = new PosixParser(); boolean printDetails = false; try { CommandLine cmd = parser.parse(options, args); printDetails = cmd.hasOption("verbose"); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("postprocessor", options); return; } if (cmd.hasOption("db-extension")) { extensions = cmd.getOptionValues("db-extension"); } if (cmd.hasOption("db") == false) { reporter.error("explorer", "Option --db is required"); reporter.printSummary(); return; } if (cmd.hasOption("config") == false) { reporter.error("explorer", "Option --config is required"); reporter.printSummary(); return; } Configuration config = new Configuration(); Parser configParser = new Parser(); try { configParser.parse(config, new File(cmd.getOptionValue("config"))); } catch (IOException e) { reporter.error("explorer", "Could not read configuration file: " + e.getMessage()); reporter.printSummary(); return; } catch (ParserException e) { reporter.error("explorer", "Could not parse configuration file: " + e.getMessage()); reporter.printSummary(); return; } File dbf = new File(cmd.getOptionValue("db")); if (dbf.exists() == false || dbf.isFile() == false) { reporter.error("explorer", "Invalid database file path"); reporter.printSummary(); return; } pool = new ModelPool(cmd.getOptionValue("db"), 2, extensions); pool.setPrintTemplates(printDetails); model = pool.getModel(); if (cmd.hasOption("list-projects")) { for (Project proj : model.getProjects()) { System.out.println(" " + proj.getId() + ": " + proj.getDate()); } return; } Integer projId = null; if (cmd.hasOption("project") == false) { reporter.error("explorer", "Option --project is required"); reporter.printSummary(); return; } else { try { projId = Integer.parseInt(cmd.getOptionValue("project")); } catch (NumberFormatException e) { reporter.error("explorer", "Invalid project ID"); reporter.printSummary(); return; } } Project project = model.getProject(projId); if (project == null) { reporter.error("explorer", "Invalid project ID"); reporter.printSummary(); return; } if (cmd.hasOption("list-dictionaries")) { List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project); for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) { System.out.println(" (" + dict.getId() + ") " + dict.getContext() + " " + dict.getName()); } return; } int bugDictId = -1; if (cmd.hasOption("bug-dictionary")) { try { bugDictId = Integer.parseInt(cmd.getOptionValue("bug-dictionary")); List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project); boolean valid = false; for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) { if (dict.getId() == bugDictId) { valid = true; break; } } if (valid == false) { reporter.error("explorer", "Invalid bug dictionary ID"); reporter.printSummary(); return; } } catch (NumberFormatException e) { reporter.error("explorer", "Invalid bug dictionary ID"); reporter.printSummary(); return; } } else { List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project); for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) { if (dict.getContext().equals("bug")) { bugDictId = dict.getId(); break; } } } int commitDictId = -1; if (cmd.hasOption("commit-dictionary")) { try { commitDictId = Integer.parseInt(cmd.getOptionValue("commit-dictionary")); List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project); boolean valid = false; for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) { if (dict.getId() == commitDictId) { valid = true; break; } } if (valid == false) { reporter.error("explorer", "Invalid commit dictionary ID"); reporter.printSummary(); return; } } catch (NumberFormatException e) { reporter.error("explorer", "Invalid commit dictionary ID"); reporter.printSummary(); return; } } else { List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project); for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) { if (dict.getContext().equals("src")) { commitDictId = dict.getId(); break; } } } // UI: Display display = new Display(); final Shell shell = new Shell(display); final StackLayout stack = new StackLayout(); shell.setLayout(stack); Composite _projectControl = null; Composite _teamControl = null; Composite _userControl = null; if (config.getProjectViewConfig() != null) { ViewFactory factory = new ViewFactory(model, config); _projectControl = factory.createProjectViewComposite(shell, SWT.NONE, project, commitDictId, bugDictId, config.getProjectViewConfig()); } if (config.getTeamViewConfig() != null) { ViewFactory factory = new ViewFactory(model, config); _teamControl = factory.createTeamViewComposite(shell, SWT.NONE, project, commitDictId, bugDictId, config.getTeamViewConfig()); } if (config.getUserViewConfig() != null) { ViewFactory factory = new ViewFactory(model, config); _userControl = factory.createUserViewComposite(shell, SWT.NONE, project, commitDictId, bugDictId, config.getUserViewConfig()); } final Composite projectControl = _projectControl; final Composite teamControl = _teamControl; final Composite userControl = _userControl; // Menu: Menu menu = new Menu(shell, SWT.BAR); shell.setMenuBar(menu); MenuItem mntmNewSubmenu = new MenuItem(menu, SWT.CASCADE); mntmNewSubmenu.setText("Views"); Menu viewMenu = new Menu(shell, SWT.DROP_DOWN); mntmNewSubmenu.setMenu(viewMenu); Composite defaultView = null; if (projectControl != null) { MenuItem projectRadio = new MenuItem(viewMenu, SWT.RADIO); projectRadio.setText("Project View"); projectRadio.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent arg0) { stack.topControl = projectControl; shell.layout(); } @Override public void widgetSelected(SelectionEvent arg0) { stack.topControl = projectControl; shell.layout(); } }); defaultView = projectControl; projectRadio.setSelection(true); } if (teamControl != null) { MenuItem teamRadio = new MenuItem(viewMenu, SWT.RADIO); teamRadio.setText("Team View"); teamRadio.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent arg0) { stack.topControl = teamControl; shell.layout(); } @Override public void widgetSelected(SelectionEvent arg0) { stack.topControl = teamControl; shell.layout(); } }); if (defaultView == null) { defaultView = teamControl; teamRadio.setSelection(true); } } if (userControl != null) { MenuItem userRadio = new MenuItem(viewMenu, SWT.RADIO); userRadio.setText("User View"); userRadio.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent arg0) { stack.topControl = userControl; shell.layout(); } @Override public void widgetSelected(SelectionEvent arg0) { stack.topControl = userControl; shell.layout(); } }); if (defaultView == null) { defaultView = userControl; userRadio.setSelection(true); } } stack.topControl = defaultView; // Display: shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } display.dispose(); /*/ UI: Display display = new Display (); Shell teamShell = new Shell (display, SWT.CLOSE); teamShell.setLayout (new FillLayout ()); Shell projectShell = new Shell (display, SWT.CLOSE); projectShell.setLayout (new FillLayout ()); projectShell.setText ("Project View"); teamShell.setText ("Team View"); if (config.getTeamViewConfig () != null) { ViewFactory factory = new ViewFactory (model, config); factory.createTeamViewComposite (teamShell, SWT.NONE, project, commitDictId, bugDictId, config.getTeamViewConfig ()); teamShell.pack(); teamShell.open (); } else { teamShell.dispose (); } if (config.getProjectViewConfig () != null) { ViewFactory factory = new ViewFactory (model, config); factory.createProjectViewComposite (projectShell, SWT.NONE, project, commitDictId, bugDictId, config.getProjectViewConfig ()); projectShell.pack(); projectShell.open (); } else { projectShell.dispose (); } teamShell.addListener (SWT.CLOSE, new Listener () { @Override public void handleEvent (Event event) { teamShell.dispose (); } }); projectShell.addListener (SWT.CLOSE, new Listener () { @Override public void handleEvent (Event event) { projectShell.dispose (); } }); while (!display.isDisposed ()) { if (teamShell.isDisposed () && projectShell.isDisposed ()) { break; } if (!display.readAndDispatch ()) { display.sleep (); } } display.dispose(); */ } catch (ParseException e) { reporter.error("explorer", "Parsing failed: " + e.getMessage()); if (printDetails == true) { e.printStackTrace(); } } catch (ClassNotFoundException e) { reporter.error("explorer", "Failed to create a database connection: " + e.getMessage()); if (printDetails == true) { e.printStackTrace(); } } catch (SQLException e) { reporter.error("explorer", "Failed to create a database connection: " + e.getMessage()); if (printDetails == true) { e.printStackTrace(); } } catch (SemanticException e) { reporter.error("explorer", "Semantic Error: " + e.getMessage()); if (printDetails == true) { e.printStackTrace(); } } finally { if (model != null) { model.close(); } if (pool != null) { pool.close(); } } reporter.printSummary(); }
From source file:codeswarm.code_swarm.java
/** * code_swarm Entry point.//from w w w. j ava 2 s. c o m * @param args : should be the path to the config file */ public static void main(String args[]) { try { if (args.length > 0) { System.out.println("code_swarm is free software: you can redistribute it and/or modify"); System.out.println("it under the terms of the GNU General Public License as published by"); System.out.println("the Free Software Foundation, either version 3 of the License, or"); System.out.println("(at your option) any later version."); System.out.flush(); start(new CodeSwarmConfig(args[0])); } else { logger.error("Specify a config file."); } } catch (IOException e) { logger.error("Failed due to exception: " + e.getMessage(), e); } }
From source file:edu.vassar.cs.cmpu331.tvi.Main.java
public static void main(String[] args) { Options options = new Options().addOption("t", "trace", false, "Enable tracing.") .addOption("d", "debug", false, "Enable debug output.") .addOption("s", "size", true, "Sets amount of memory available.") .addOption("v", "version", false, "Prints the TVI version number.") .addOption("r", "renumber", true, "Renumbers the lines in a files.") .addOption("h", "help", false, "Prints this help message"); CommandLineParser parser = new DefaultParser(); try {//from ww w .java 2 s .c o m CommandLine opts = parser.parse(options, args); if (opts.hasOption('h')) { help(options); return; } if (opts.hasOption('v')) { System.out.println(); System.out.println("The Vassar Interpreter v" + Version.getVersion()); System.out.println(COPYRIGHT); System.out.println(); return; } if (opts.hasOption('r')) { int returnCode = 0; try { renumber(opts.getOptionValue('r')); } catch (IOException e) { e.printStackTrace(); returnCode = 1; } System.exit(returnCode); } files = opts.getArgs(); if (files.length == 0) { System.out.println("ERROR: No file names given."); help(options); System.exit(1); } if (opts.hasOption('s')) { try { memory = Integer.parseInt(opts.getOptionValue('s')); } catch (NumberFormatException e) { System.out.println("ERROR: Invalid --size parameter."); help(options); System.exit(1); } } if (opts.hasOption('t')) { tracing = true; } if (opts.hasOption('d')) { debugging = true; } } catch (ParseException e) { System.out.println(e.getMessage()); help(options); System.exit(1); } Main app = new Main(); Arrays.stream(files).forEach(app::run); }
From source file:BGrep.java
public static void main(String[] args) { String encodingName = "UTF-8"; // Default to UTF-8 encoding int flags = Pattern.MULTILINE; // Default regexp flags try { // Fatal exceptions are handled after this try block // First, process any options int nextarg = 0; while (args[nextarg].charAt(0) == '-') { String option = args[nextarg++]; if (option.equals("-e")) { encodingName = args[nextarg++]; } else if (option.equals("-i")) { // case-insensitive matching flags |= Pattern.CASE_INSENSITIVE; } else if (option.equals("-s")) { // Strict Unicode processing flags |= Pattern.UNICODE_CASE; // case-insensitive Unicode flags |= Pattern.CANON_EQ; // canonicalize Unicode } else { System.err.println("Unknown option: " + option); usage();/*w w w . j av a 2 s . c om*/ } } // Get the Charset for converting bytes to chars Charset charset = Charset.forName(encodingName); // Next argument must be a regexp. Compile it to a Pattern object Pattern pattern = Pattern.compile(args[nextarg++], flags); // Require that at least one file is specified if (nextarg == args.length) usage(); // Loop through each of the specified filenames while (nextarg < args.length) { String filename = args[nextarg++]; CharBuffer chars; // This will hold complete text of the file try { // Handle per-file errors locally // Open a FileChannel to the named file FileInputStream stream = new FileInputStream(filename); FileChannel f = stream.getChannel(); // Memory-map the file into one big ByteBuffer. This is // easy but may be somewhat inefficient for short files. ByteBuffer bytes = f.map(FileChannel.MapMode.READ_ONLY, 0, f.size()); // We can close the file once it is is mapped into memory. // Closing the stream closes the channel, too. stream.close(); // Decode the entire ByteBuffer into one big CharBuffer chars = charset.decode(bytes); } catch (IOException e) { // File not found or other problem System.err.println(e); // Print error message continue; // and move on to the next file } // This is the basic regexp loop for finding all matches in a // CharSequence. Note that CharBuffer implements CharSequence. // A Matcher holds state for a given Pattern and text. Matcher matcher = pattern.matcher(chars); while (matcher.find()) { // While there are more matches // Print out details of the match System.out.println(filename + ":" + // file name matcher.start() + ": " + // character pos matcher.group()); // matching text } } } // These are the things that can go wrong in the code above catch (UnsupportedCharsetException e) { // Bad encoding name System.err.println("Unknown encoding: " + encodingName); } catch (PatternSyntaxException e) { // Bad pattern System.err.println("Syntax error in search pattern:\n" + e.getMessage()); } catch (ArrayIndexOutOfBoundsException e) { // Wrong number of arguments usage(); } }
From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.spss.SPSSFileReader.java
public static void main(String[] args) { BufferedInputStream spssCardStream = null; SDIOData processedCard = null;//from w ww . ja v a 2 s . c o m SPSSFileReader spssReader = null; String testCardFile = args[0]; String csvRawDataFile = args[1]; try { spssCardStream = new BufferedInputStream(new FileInputStream(testCardFile)); spssReader = new SPSSFileReader(null); processedCard = spssReader.read(spssCardStream, new File(csvRawDataFile)); } catch (IOException ex) { System.out.println("exception caught: "); System.out.println(ex.getMessage()); if (spssReader == null) { System.out.println("failed to create an SPSS file reader."); } } }
From source file:PVGraph.java
public static void main(String[] args) { loadProperties();//from w w w . j a va 2 s.c o m try { Class.forName("com.mysql.jdbc.Driver").newInstance(); getDatabaseConnection(); } catch (SQLException e) { System.err.println("Cannot establish database connection: " + e.getMessage()); } catch (Exception e) { System.err.println(e.getMessage()); } if (conn != null) { // create first window new PVGraph(); int smatoolPeriod = Integer.decode(props.getProperty("smatool.period", "0")); while (smatoolPeriod > 0) { loadProperties(); smatoolPeriod = Integer.decode(props.getProperty("smatool.period", "0")); int smatoolStartHour = Integer.decode(props.getProperty("smatool.starthour", "0")); int smatoolEndHour = Integer.decode(props.getProperty("smatool.endhour", "24")); GregorianCalendar now = new GregorianCalendar(); int nowHour = now.get(Calendar.HOUR_OF_DAY); if (nowHour >= smatoolStartHour && nowHour < smatoolEndHour) { try { runSmatool(); synchronized (graphs) { for (PVGraph g : graphs) g.updateView(); } } catch (IOException ioe) { System.err.println(ioe.getMessage()); } } try { Thread.sleep(smatoolPeriod * 60 * 1000); } catch (InterruptedException ie) { // break; } } } }
From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java
/** * main() method, for testing/*w ww . ja v a 2 s . com*/ * usage: java edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator testfile.tab varcount casecount column type * make sure the CLASSPATH contains ... * */ public static void main(String[] args) { String tabFileName = args[0]; int varcount = new Integer(args[1]).intValue(); int casecount = new Integer(args[2]).intValue(); int column = new Integer(args[3]).intValue(); String type = args[4]; File tabFile = new File(tabFileName); File rotatedImageFile = null; TabularSubsetGenerator subsetGenerator = new TabularSubsetGenerator(); /* try { rotatedImageFile = subsetGenerator.getRotatedImage(tabFile, varcount, casecount); } catch (IOException ex) { System.out.println(ex.getMessage()); } */ //System.out.println("\nFinished generating \"rotated\" column image file."); //System.out.println("\nOffsets:"); MathContext doubleMathContext = new MathContext(15, RoundingMode.HALF_EVEN); String FORMAT_IEEE754 = "%+#.15e"; try { //subsetGenerator.reverseRotatedImage(rotatedImageFile, varcount, casecount); //String[] columns = subsetGenerator.subsetStringVector(tabFile, column, varcount, casecount); if ("string".equals(type)) { String[] columns = subsetGenerator.subsetStringVector(tabFile, column, varcount, casecount); for (int i = 0; i < casecount; i++) { System.out.println(columns[i]); } } else { Double[] columns = subsetGenerator.subsetDoubleVector(tabFile, column, varcount, casecount); for (int i = 0; i < casecount; i++) { if (columns[i] != null) { BigDecimal outBigDecimal = new BigDecimal(columns[i], doubleMathContext); System.out.println(String.format(FORMAT_IEEE754, outBigDecimal)); } else { System.out.println("NA"); } //System.out.println(columns[i]); } } } catch (IOException ex) { System.out.println(ex.getMessage()); } }
From source file:AdminExample.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String accessToken = "";//Insert your access token here. Note this must be from an account that is an Admin of an account. String user1Email = ""; //You need access to these two email account. String user2Email = ""; //Note Gmail and Hotmail allow email aliasing. //joe@gmail.com will get email sent to joe+user1@gmail.com try {/*from www. j ava2s . co m*/ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Adding user " + user1Email); //Add the users: User user = new User(); user.setEmail(user1Email); user.setAdmin(false); user.setLicensedSheetCreator(true); connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), user); Result<User> newUser1Result = mapper.readValue(connection.getInputStream(), new TypeReference<Result<User>>() { }); System.out.println( "User " + newUser1Result.result.email + " added with userId " + newUser1Result.result.getId()); user = new User(); user.setEmail(user2Email); user.setAdmin(true); user.setLicensedSheetCreator(true); connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), user); Result<User> newUser2Result = mapper.readValue(connection.getInputStream(), new TypeReference<Result<User>>() { }); System.out.println( "User " + newUser2Result.result.email + " added with userId " + newUser2Result.result.getId()); System.out.println("Please visit the email inbox for the users " + user1Email + " and " + user2Email + " and confirm membership to the account."); System.out.print("Press Enter to continue"); in.readLine(); //List all the users of the org connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); List<User> users = mapper.readValue(connection.getInputStream(), new TypeReference<List<User>>() { }); System.out.println("The following are members of your account: "); for (User orgUser : users) { System.out.println("\t" + orgUser.getEmail()); } //Create a sheet as the admin Sheet newSheet = new Sheet(); newSheet.setName("Admin's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //Create a sheet as user1 newSheet = new Sheet(); newSheet.setName("User 1's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); //Here is where the magic happens - Any action performed in this call will be on behalf of the //user provided. Note that this person must be a confirmed member of your org. //Also note that the email address is url-encoded. connection.addRequestProperty("Assume-User", URLEncoder.encode(user1Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //Create a sheet as user2 newSheet = new Sheet(); newSheet.setName("User 2's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //List all the sheets in the org: System.out.println("The following sheets are owned by members of your account: "); connection = (HttpURLConnection) new URL(USERS_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); List<Sheet> allSheets = mapper.readValue(connection.getInputStream(), new TypeReference<List<Sheet>>() { }); for (Sheet orgSheet : allSheets) { System.out.println("\t" + orgSheet.getName() + " - " + orgSheet.getOwner()); } //Now delete user1 and transfer their sheets to user2 connection = (HttpURLConnection) new URL(USER_URL.replace(ID, newUser1Result.getResult().getId() + "") + "?transferTo=" + newUser2Result.getResult().getId()).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setRequestMethod("DELETE"); Result<Object> resultObject = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Object>>() { }); System.out.println("Sheets transferred : " + resultObject.getSheetsTransferred()); } catch (IOException e) { InputStream is = connection == null ? null : ((HttpURLConnection) connection).getErrorStream(); if (is != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result<?> result = mapper.readValue(response.toString(), Result.class); System.err.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } e.printStackTrace(); } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }
From source file:net.sf.freecol.FreeCol.java
/** * The entrypoint./* w ww. j a va 2 s. com*/ * * @param args The command-line arguments. * @throws IOException * @throws FontFormatException */ public static void main(String[] args) throws FontFormatException, IOException { freeColRevision = FREECOL_VERSION; JarURLConnection juc; try { juc = getJarURLConnection(FreeCol.class); } catch (IOException ioe) { juc = null; System.err.println("Unable to open class jar: " + ioe.getMessage()); } if (juc != null) { try { String revision = readVersion(juc); if (revision != null) { freeColRevision += " (Revision: " + revision + ")"; } } catch (Exception e) { System.err.println("Unable to load Manifest: " + e.getMessage()); } try { splashStream = getDefaultSplashStream(juc); } catch (Exception e) { System.err.println("Unable to open default splash: " + e.getMessage()); } } // Java bug #7075600 causes BR#2554. The workaround is to set // the following property. Remove if/when they fix Java. System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); // We can not even emit localized error messages until we find // the data directory, which might have been specified on the // command line. String dataDirectoryArg = findArg("--freecol-data", args); String err = FreeColDirectories.setDataDirectory(dataDirectoryArg); if (err != null) fatal(err); // This must not fail. // Now we have the data directory, establish the base locale. // Beware, the locale may change! String localeArg = findArg("--default-locale", args); if (localeArg == null) { locale = Locale.getDefault(); } else { int index = localeArg.indexOf('.'); // Strip encoding if present if (index > 0) localeArg = localeArg.substring(0, index); locale = Messages.getLocale(localeArg); } Messages.loadMessageBundle(locale); // Now that we can emit error messages, parse the other // command line arguments. handleArgs(args); // Do the potentially fatal system checks as early as possible. if (javaCheck && JAVA_VERSION_MIN.compareTo(JAVA_VERSION) > 0) { fatal(StringTemplate.template("main.javaVersion").addName("%version%", JAVA_VERSION) .addName("%minVersion%", JAVA_VERSION_MIN)); } if (memoryCheck && MEMORY_MAX < MEMORY_MIN * 1000000) { fatal(StringTemplate.template("main.memory").addAmount("%memory%", MEMORY_MAX).addAmount("%minMemory%", MEMORY_MIN)); } // Having parsed the command line args, we know where the user // directories should be, so we can set up the rest of the // file/directory structure. String userMsg = FreeColDirectories.setUserDirectories(); // Now we have the log file path, start logging. final Logger baseLogger = Logger.getLogger(""); final Handler[] handlers = baseLogger.getHandlers(); for (Handler handler : handlers) { baseLogger.removeHandler(handler); } String logFile = FreeColDirectories.getLogFilePath(); try { baseLogger.addHandler(new DefaultHandler(consoleLogging, logFile)); Logger freecolLogger = Logger.getLogger("net.sf.freecol"); freecolLogger.setLevel(logLevel); } catch (FreeColException e) { System.err.println("Logging initialization failure: " + e.getMessage()); e.printStackTrace(); } Thread.setDefaultUncaughtExceptionHandler((Thread thread, Throwable e) -> { baseLogger.log(Level.WARNING, "Uncaught exception from thread: " + thread, e); }); // Now we can find the client options, allow the options // setting to override the locale, if no command line option // had been specified. // We have users whose machines default to Finnish but play // FreeCol in English. // If the user has selected automatic language selection, do // nothing, since we have already set up the default locale. if (localeArg == null) { String clientLanguage = ClientOptions.getLanguageOption(); Locale clientLocale; if (clientLanguage != null && !Messages.AUTOMATIC.equalsIgnoreCase(clientLanguage) && (clientLocale = Messages.getLocale(clientLanguage)) != locale) { locale = clientLocale; Messages.loadMessageBundle(locale); logger.info("Loaded messages for " + locale); } } // Now we have the user mods directory and the locale is now // stable, load the mods and their messages. Mods.loadMods(); Messages.loadModMessageBundle(locale); // Report on where we are. if (userMsg != null) logger.info(Messages.message(userMsg)); logger.info(getConfiguration().toString()); // Ready to specialize into client or server. if (standAloneServer) { startServer(); } else { startClient(userMsg); } startYourAddition(); }
From source file:SheetStructure.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String accessToken = "";//Insert your access token here. try {//w w w .j ava2s. c om System.out.println("Starting HelloSmartsheet2: Betty's Bake Sale..."); //First Create a new sheet. String sheetName = "Betty's Bake Sale"; //We will be using POJOs to represent the REST request objects. We will convert these to and from JSON using Jackson JSON. //Their structure directly relates to the JSON that gets passed through the API. //Note that these POJOs are included as static inner classes to keep this to one file. Normally they would be broken out. Sheet newSheet = new Sheet(); newSheet.setName(sheetName); newSheet.setColumns(Arrays.asList(new Column("Baked Goods", "TEXT_NUMBER", null, true, null), new Column("Baker", "CONTACT_LIST", null, null, null), new Column("Price Per Item", "TEXT_NUMBER", null, null, null), new Column("Gluten Free?", "CHECKBOX", "FLAG", null, null), new Column("Status", "PICKLIST", null, null, Arrays.asList("Started", "Finished", "Delivered")))); connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); Result<Sheet> newSheetResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); newSheet = newSheetResult.getResult(); System.out.println("Sheet " + newSheet.getName() + " created, id: " + newSheet.getId()); //Now add a column: String columnName = "Delivery Date"; System.out.println("Adding column " + columnName + " to " + sheetName); Column newColumn = new Column(columnName, "DATE", 5); connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newColumn); Result<Column> newColumnResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Column>>() { }); System.out.println( "Column " + newColumnResult.getResult().getTitle() + " added to " + newSheet.getName()); //Next, we will get the list of Columns from the API. We could figure this out based on what the server has returned in the result, but we'll just ask the API for it. System.out.println("Fetching " + newSheet.getName() + " sheet columns..."); connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); List<Column> allColumns = mapper.readValue(connection.getInputStream(), new TypeReference<List<Column>>() { }); System.out.println("Fetched."); //Now we will be adding rows System.out.println("Inserting rows into " + newSheet.getName()); List<Row> rows = new ArrayList<Row>(); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Brownies"), new Cell(allColumns.get(1).id, "julieann@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Snickerdoodles"), new Cell(allColumns.get(1).id, "stevenelson@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"), new Cell(allColumns.get(5).id, "2013-09-04")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Rice Krispy Treats"), new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Started")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Muffins"), new Cell(allColumns.get(1).id, "sandrassmart@example.com"), new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Finished")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Chocolate Chip Cookies"), new Cell(allColumns.get(1).id, "janedaniels@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"), new Cell(allColumns.get(5).id, "2013-09-05")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Ginger Snaps"), new Cell(allColumns.get(1).id, "nedbarnes@example.com"), new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Unknown", false)))); //Note that this one is strict=false. This is because "Unknown" was not one of the original options when the column was created. RowWrapper rowWrapper = new RowWrapper(); rowWrapper.setToBottom(true); rowWrapper.setRows(rows); connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), rowWrapper); Result<List<Row>> newRowsResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Added " + newRowsResult.getResult().size() + " rows to " + newSheet.getName()); //Move a row to the top. System.out.println("Moving row 6 to the top."); RowWrapper moveToTop = new RowWrapper(); moveToTop.setToTop(true); connection = (HttpURLConnection) new URL( ROW_URL.replace(ID, "" + newRowsResult.getResult().get(5).getId())).openConnection(); connection.setRequestMethod("PUT"); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), moveToTop); mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Row 6 moved to top."); //Insert empty rows for spacing rows = new ArrayList<Row>(); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Delivered")))); rowWrapper = new RowWrapper(); rowWrapper.setToBottom(true); rowWrapper.setRows(rows); connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), rowWrapper); Result<List<Row>> spacerRowsResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Added " + spacerRowsResult.getResult().size() + " rows to " + newSheet.getName()); //Move Delivered rows to be children of the last spacer row. System.out.println("Moving delivered rows to Delivered section..."); Long[] deliveredRowIds = new Long[] { newRowsResult.result.get(1).getId(), newRowsResult.result.get(4).getId() }; RowWrapper parentRowLocation = new RowWrapper(); parentRowLocation.setParentId(spacerRowsResult.getResult().get(1).getId()); for (Long deliveredId : deliveredRowIds) { System.out.println("Moving " + deliveredId + " to Delivered."); connection = (HttpURLConnection) new URL(ROW_URL.replace(ID, "" + deliveredId)).openConnection(); connection.setRequestMethod("PUT"); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), parentRowLocation); mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Row id " + deliveredId + " moved."); } System.out.println("Appending additional rows to items in progress..."); List<Row> siblingRows = new ArrayList<Row>(); siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Scones"), new Cell(allColumns.get(1).id, "tomlively@example.com"), new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished")))); siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Lemon Bars"), new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Started")))); rowWrapper = new RowWrapper(); rowWrapper.setSiblingId(newRowsResult.getResult().get(3).getId()); rowWrapper.setRows(siblingRows); connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), rowWrapper); Result<List<Row>> siblingRowsResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Added " + siblingRowsResult.getResult().size() + " rows to " + newSheet.getName()); System.out.println("Moving Status column to index 1..."); Column statusColumn = allColumns.get(4); Column moveColumn = new Column(); moveColumn.setIndex(1); moveColumn.setTitle(statusColumn.title); moveColumn.setSheetId(newSheet.getId()); moveColumn.setType(statusColumn.getType()); connection = (HttpURLConnection) new URL(COLUMN_URL.replace(ID, "" + statusColumn.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); connection.setRequestMethod("PUT"); mapper.writeValue(connection.getOutputStream(), moveColumn); Result<Column> movedColumnResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Column>>() { }); System.out.println("Moved column " + movedColumnResult.getResult().getId()); System.out.println("Completed Hellosmartsheet2: Betty's Bake Sale."); } catch (IOException e) { InputStream is = ((HttpURLConnection) connection).getErrorStream(); if (is != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result<?> result = mapper.readValue(response.toString(), Result.class); System.err.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } e.printStackTrace(); } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }