/** * Returns JPicEdt's install directory w/o trailing "/", provided the command line looks like : * * <p><code>java -classpath other-class-paths:jpicedt-install-dir/lib/jpicedt.jar jpicedt.JPicEdt * </code> (where <code>/</code> may be replaced by the actual respective separator for files on * the underlying platform). * * <p>For Windows platform, the install directory is tried to be detected 1st with the MSWindows * file-separator (<code>\</code>), and if this does not work, a subsequent trial is made with * <code>/</code>. * * <p>That is, the old way (java -jar jpicedt.jar) won't work. However, classpath can contain * relative pathname (then user.dir get prepended). * * <p>Code snippet was adapted from jEdit/JEdit.java (http://www.jedit.org). * * @return the value of the "user.dir" Java property if "lib/jpicedt.jar" wasn't found in the * command line. */ public static String getJPicEdtHome() { String classpath = System.getProperty("java.class.path"); // e.g. // "/usr/lib/java/jre/lib/rt.jar:/home/me/jpicedt/1.3.2/lib/jpicedt.jar" // File.separator = "/" on Unix, "\\" on Windows,... String fileSeparator = File.separator; int index; // File.pathSeparator = ":" on Unix/MacOS-X platforms, ";" on Windows // search ":" backward starting from // "/usr/lib/java/jre/lib/rt.jar:/home/me/jpicedt/1.3.2/^lib/jpicedt.jar" String homeDir = null; int trials = 2; do { index = classpath.toLowerCase().indexOf("lib" + fileSeparator + "jpicedt.jar"); int start = classpath.lastIndexOf(File.pathSeparator, index); if (start == -1) start = 0; // File.pathSeparator not found => lib/jpicedt.jar probably at beginning of classpath else start += File.pathSeparator.length(); // e.g. ":^/home..." if (index >= start) { homeDir = classpath.substring(start, index); if (homeDir.endsWith(fileSeparator)) homeDir = homeDir.substring(0, homeDir.length() - 1); } switch (trials) { case 2: if (File.pathSeparator.equals(";") && homeDir == null) { // MS-Windows case, this must work both with / and \ trials = 1; fileSeparator = "/"; } else trials = 0; break; case 1: if (homeDir != null && !fileSeparator.equals(File.separator)) { homeDir.replace(fileSeparator, File.separator); } trials = 0; break; default: trials = 0; break; } } while (trials != 0); if (homeDir != null) { if (homeDir.equals("")) homeDir = System.getProperty("user.dir"); else if (!new File(homeDir).isAbsolute()) homeDir = System.getProperty("user.dir") + File.separator + homeDir; } else { homeDir = System.getProperty("user.dir"); if (homeDir.endsWith( "lib")) // this is the case if jpicedt run as "java -jar jpicedt.jar" from inside lib/ dir homeDir = homeDir.substring(0, homeDir.lastIndexOf("lib")); } // System.out.println("JPicEdt's home = " + homeDir); return homeDir; }
/** * @return the clipboard content as a String (DataFlavor.stringFlavor) Code snippet adapted from * jEdit (Registers.java), http://www.jedit.org. Returns null if clipboard is empty. */ public static String getClipboardStringContent(Clipboard clipboard) { // Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); try { String selection = (String) (clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor)); if (selection == null) return null; boolean trailingEOL = (selection.endsWith("\n") || selection.endsWith(System.getProperty("line.separator"))); // Some Java versions return the clipboard contents using the native line separator, // so have to convert it here , see jEdit's "registers.java" BufferedReader in = new BufferedReader(new StringReader(selection)); StringBuffer buf = new StringBuffer(); String line; while ((line = in.readLine()) != null) { buf.append(line); buf.append('\n'); } // remove trailing \n if (!trailingEOL) buf.setLength(buf.length() - 1); return buf.toString(); } catch (Exception e) { e.printStackTrace(); return null; } }
/** Return the platform standard tmp dir, or null if none is standardly defined. */ public static File getOSTmpDir() { // Note : default tmp dir can be obtained through : // System.getProperty("java.io.tmp") String tmp = System.getProperty("java.io.tmp"); if (tmp == null) return null; else return new File(tmp); }
/** * A {@link Formatter} that writes each entry onto a single line. No longer be necessary in Java 7, * which supports setting a log format on the built-in <code>SimpleFormatter</code>. */ public class SingleLineFormatter extends Formatter { private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z "); private static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n"); @Override public synchronized String format(LogRecord record) { StringBuilder sb = new StringBuilder(); sb.append(dateFormat.format(new Date(record.getMillis()))); sb.append(' '); sb.append(record.getLevel().getLocalizedName()); sb.append(": "); sb.append(formatMessage(record)); sb.append(LINE_SEPARATOR); if (record.getThrown() != null) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); record.getThrown().printStackTrace(pw); pw.close(); sb.append(sw.toString()); } catch (Exception e) { // ignore } } return sb.toString(); } }
public static void main(String args[]) throws Exception { long begin, end; begin = System.currentTimeMillis(); String logConfig = System.getProperty("log-config"); if (logConfig == null) logConfig = "log-config.txt"; PropertyConfigurator.configure(logConfig); if (args.length != 6) { System.err.println( "java -mx512M org.itc.irst.tcc.sre.util.StatisticalSignificance gold baseline preferred iterations confidence-level stat"); System.exit(0); } String g = args[0]; String b = args[1]; String p = args[2]; int n = Integer.parseInt(args[3]); double c = Double.parseDouble(args[4]); String s = args[5]; new StatisticalSignificance(new File(g), new File(b), new File(p), n, c, s); // end = System.currentTimeMillis(); logger.info("evaluation done in " + (end - begin) + " ms"); } // end main
static { MLevel dflt = null; String dfltName = MLogConfig.getProperty("com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL"); if (dfltName != null) dflt = MLevel.fromSeverity(dfltName); if (dflt == null) dflt = MLevel.INFO; DEFAULT_CUTOFF_LEVEL = dflt; SEP = System.getProperty("line.separator"); }
/** * Return an ArrayList of all paths contained int the path list given as an argument. * * @param p a list of path names deparated byte the path separator character. * @return an ArrayList which contains a list of path strings. */ public static ArrayList pathList(String p) { ArrayList a = new ArrayList(); if (nonEmpty(p)) { StringTokenizer st = new StringTokenizer(p, System.getProperty("path.separator")); while (st.hasMoreTokens()) { a.add(st.nextToken()); } } return (a); }
/** Initialize an instance of a <tt>HammerStats</tt> with the default stats directory path. */ public HammerStats() { /* this( System.getProperty(Main.PNAME_SC_HOME_DIR_LOCATION) + File.separator + System.getProperty(Main.PNAME_SC_HOME_DIR_NAME) + File.separator + HammerStats.STATS_DIR_NAME); */ this(System.getProperty("user.home") + "/Desktop/stats"); }
public List<MarketSnapshot> load(ProgressListener progressListener) throws JBookTraderException { String line = ""; int lineSeparatorSize = System.getProperty("line.separator").length(); long sizeRead = 0, lineNumber = 0; List<MarketSnapshot> snapshots = new ArrayList<MarketSnapshot>(); try { while ((line = reader.readLine()) != null) { if (lineNumber % 50000 == 0) { progressListener.setProgress(sizeRead, fileSize, "Loading historical data file"); if (progressListener.isCancelled()) { break; } } lineNumber++; sizeRead += line.length() + lineSeparatorSize; boolean isComment = line.startsWith("#"); boolean isProperty = line.contains("="); boolean isBlankLine = (line.trim().length() == 0); boolean isMarketDepthLine = !(isComment || isProperty || isBlankLine); if (isMarketDepthLine) { MarketSnapshot marketSnapshot = toMarketDepth(line); if (filter == null || filter.contains(time)) { snapshots.add(marketSnapshot); } previousTime = time; } else if (isProperty) { if (line.startsWith("timeZone")) { setTimeZone(line); } } } if (sdf == null) { String msg = "Property " + "\"timeZone\"" + " is not defined in the data file." + LINE_SEP; throw new JBookTraderException(msg); } } catch (IOException ioe) { throw new JBookTraderException("Could not read data file"); } catch (Exception e) { String errorMsg = "Problem parsing line #" + lineNumber + ": " + line + LINE_SEP; String description = e.getMessage(); if (description == null) { description = e.toString(); } errorMsg += description; throw new RuntimeException(errorMsg); } return snapshots; }
protected String replace(String key, Link link) { if (link != null && link.contains(key)) return "${infinite:" + link.toString() + "}"; if (key != null) { key = key.trim(); if (key.length() > 0) { Processor source = domain; String value = null; if (key.indexOf(';') < 0) { Instruction ins = new Instruction(key); if (!ins.isLiteral()) { SortedList<String> sortedList = SortedList.fromIterator(domain.iterator()); StringBuilder sb = new StringBuilder(); String del = ""; for (String k : sortedList) { if (ins.matches(k)) { String v = replace(k, new Link(source, link, key)); if (v != null) { sb.append(del); del = ","; sb.append(v); } } } return sb.toString(); } } while (value == null && source != null) { value = source.getProperties().getProperty(key); source = source.getParent(); } if (value != null) return process(value, new Link(source, link, key)); value = doCommands(key, link); if (value != null) return process(value, new Link(source, link, key)); if (key != null && key.trim().length() > 0) { value = System.getProperty(key); if (value != null) return value; } if (!flattening && !key.equals("@")) domain.warning("No translation found for macro: " + key); } else { domain.warning("Found empty macro key"); } } else { domain.warning("Found null macro key"); } return "${" + key + "}"; }
private String generateOverviewText() throws InsufficientDataException { StringBuilder sb = new StringBuilder(); final String team = config.getTeam(); double total = checkTotal(); final String nl = System.getProperty("line.separator"); for (Entry<String, Row> entry : rows.entrySet()) { double hours = Double.parseDouble(entry.getValue().hoursTF.getText()); double fraction = hours / total; if (fraction < 0.004) continue; String line = team + ", " + decimalFormat.format(fraction) + ", " + entry.getKey(); sb.append(line + nl); } return sb.toString(); }
public static String getHomePath() { String home = System.getProperty("HOME"); if (home == null) { try { String thisPath = SystemUtils.class.getResource("SystemUtils.class").getPath(); String thisPkg = SystemUtils.class.getPackage().getName(); home = thisPath.substring(0, thisPath.indexOf(thisPkg.substring(0, thisPkg.indexOf('.')))); } catch (Exception e) { e.printStackTrace(); } } if (home == null) home = ""; return home; }
public void restartApplication() { try { final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "javaw"; final File currentJar = new File(network.class.getProtectionDomain().getCodeSource().getLocation().toURI()); System.out.println("javaBin " + javaBin); System.out.println("currentJar " + currentJar); System.out.println("currentJar.getPath() " + currentJar.getPath()); /* is it a jar file? */ // if(!currentJar.getName().endsWith(".jar")){return;} try { // xmining = 0; // systemx.shutdown(); } catch (Exception e) { e.printStackTrace(); } /* Build command: java -jar application.jar */ final ArrayList<String> command = new ArrayList<String>(); command.add(javaBin); command.add("-jar"); command.add("-Xms256m"); command.add("-Xmx1024m"); command.add(currentJar.getPath()); final ProcessBuilder builder = new ProcessBuilder(command); builder.start(); // try{Thread.sleep(10000);} catch (InterruptedException e){} // close and exit SystemTray.getSystemTray().remove(network.icon); System.exit(0); } // try catch (Exception e) { JOptionPane.showMessageDialog(null, e.getCause()); } } // ******************************
public static void main(String[] args) throws Exception { // set up our flags and our input and output streams based on the // command-line arguments (exceptions generated here will propagate out // to the environment) BufferedReader in = null; PrintWriter out = null; boolean writeNewFile = false; boolean doThrow = true; for (int i = 0; i < args.length; i++) { if (args[i].equals("-w")) { writeNewFile = true; doThrow = false; } else if (args[i].equals("-nothrow")) doThrow = false; else if (args[i].equals("-s") && in == null) in = new BufferedReader(new EscapeReader(new InputStreamReader(System.in, "ISO8859_1"))); else if (!args[i].startsWith("-") && in == null) in = new BufferedReader( new EscapeReader(new InputStreamReader(new FileInputStream(args[i]), "ISO8859_1"))); } if (in == null) { File localeData = new File(System.getProperty("test.src", "."), "LocaleData"); in = new BufferedReader( new EscapeReader( new InputStreamReader(new FileInputStream(localeData), "ISO8859_1"))); } out = new PrintWriter(new EscapeWriter(new OutputStreamWriter(System.out, "ISO8859_1")), true); // perform the actual test int errorCount = doTest(in, out, writeNewFile); // write out the error count, and throw an exception out into the environment // if there were any errors if (errorCount != 0) { if (!writeNewFile) out.println("Test failed. " + errorCount + " errors."); if (doThrow) throw new Exception("Test failed. " + errorCount + " errors."); } else if (!writeNewFile) out.println("Test passed."); in.close(); out.close(); }
public browse_jsp() { myUtil = new ewebeditor.server.util(); sFileSeparator = System.getProperty("file.separator"); }
/** * Takes a vector full of property lists and generates a report. * * @param args Command line arguments. args[0] should be the config filename. */ public static void main(String[] args) { // Load the database properties from properties file Properties properties = new Properties(); // Load config file String configFile = null; if (args.length > 0) configFile = args[0]; try { if (configFile == null) { System.out.println("Database config file not set."); return; } else properties.load(new FileInputStream(configFile)); } catch (IOException e) { System.out.println("Error opening config file."); } String url = properties.getProperty("databaseUrl"); String username = properties.getProperty("username"); String password = properties.getProperty("password"); String dir = System.getProperty("user.dir"); // Current working directory Connection con = null; // Try to open file containing javac output String output = ""; try { BufferedReader outputReader = new BufferedReader(new FileReader(dir + "/CompileOut.txt")); while (outputReader.ready()) output += outputReader.readLine() + '\n'; // Close file outputReader.close(); } catch (FileNotFoundException e) { System.out.println("Error opening compilation output file."); return; } catch (IOException e) { System.out.println("I/O Exception Occured."); return; } boolean hasDriver = false; // Create class for the driver try { Class.forName("com.mysql.jdbc.Driver"); hasDriver = true; } catch (Exception e) { System.out.println("Failed to load MySQL JDBC driver class."); } // Create connection to database if the driver was found if (hasDriver) { try { con = DriverManager.getConnection(url, username, password); } catch (SQLException e) { System.out.println("Couldn't get connection!"); } } // Check that a connection was made if (con != null) { long userEventId = -1; // Store results from the report into the database try { BufferedReader rd = new BufferedReader( new FileReader(dir + "/userId.txt")); // Read userId.txt to get userId String userId = rd.readLine(); // Store userId from text file rd.close(); // Insert the report into the table and get the auto_increment id for it Statement stmt = con.createStatement(); stmt.executeUpdate("INSERT INTO userEvents (userId) VALUES ('" + userId + "')"); ResultSet result = stmt.getGeneratedKeys(); result.next(); userEventId = result.getLong(1); // Close the statement stmt.close(); // Prepare statement for adding the compilation error to the userEvent PreparedStatement compErrorPrepStmt = con.prepareStatement( "INSERT INTO userEventCompilationErrors(userEventId, output) VALUES (?, ?)"); // Insert userEventId and docletId into the database compErrorPrepStmt.setLong(1, userEventId); compErrorPrepStmt.setString(2, output); compErrorPrepStmt.executeUpdate(); // Close the prepare statements compErrorPrepStmt.close(); } catch (Exception e) { System.out.println("Exception Occurred"); System.out.println(e); } // Store the java files for the report try { // Prepare statement for storing files PreparedStatement filePrepStmt = con.prepareStatement( "INSERT INTO files(userEventId, filename, contents) VALUES (" + userEventId + ", ?, ?)"); // Get the list of files from source.txt BufferedReader rd = new BufferedReader( new FileReader(dir + "/source.txt")); // Read userId.txt to get userId while (rd.ready()) { String filename = rd.readLine(); // Store userId from text file // Remove the "src/" from the beginning to get the real file name String realname = filename.substring(4); filePrepStmt.setString(1, realname); // Read in the contents of the files String contents = ""; File javaFile = new File(dir + "/" + filename); int length = (int) javaFile.length(); // Add parameter for file contents to the prepared statement and execute it filePrepStmt.setCharacterStream(2, new BufferedReader(new FileReader(javaFile)), length); filePrepStmt.executeUpdate(); } rd.close(); } catch (IOException e) { System.err.println("I/O Exception Occured."); } catch (SQLException e) { System.err.println("SQL Exception Occured."); } } }
public static void contactBookOperations(String contactBookName) throws IOException, ParseException { FileWriter fr = new FileWriter(contactBookName, true); BufferedReader fileReader = new BufferedReader(new FileReader(contactBookName)); BufferedWriter fileWriter = new BufferedWriter(fr); String address = ""; String name = ""; boolean validName = false; String dateOfBirth = ""; boolean dateValid = false; String petName = ""; int tag = 0; String contactType = ""; boolean invalidTag = false; boolean moreEmail = false; String email = ""; String emailChoice = ""; boolean morePhone = true; String phoneChoice = ""; String phoneList = ""; String contactAdded = ""; long phoneNum = 0; int choice = 0; ArrayList<String> nameList = new ArrayList<String>(); // arrayList to hold names of contacts in the file... Scanner sc = new Scanner(System.in); String searchString = ""; Scanner stringReader = new Scanner(System.in); String line = ""; String totalDetails = ""; // System.out.println(fileReader); while (choice != 6) { System.out.println("\nTO ADD CONTACT->PRESS 1 "); System.out.println("TO EDIT CONTACT->PRESS 2 "); System.out.println("TO REMOVE CONTACT->PRESS 3 "); System.out.println("TO LIST CONTACTS->PRESS 4 "); System.out.println("TO SEARCH CONTACT->PRESS 5 "); System.out.println("TO GO BACK TO PREVIOUS MENU->PRESS 6 "); while (!sc.hasNextInt()) { System.out.println("\nENTER ONLY NUMBERS RANGED FROM 0 - 6"); sc.next(); } choice = sc.nextInt(); switch (choice) { // ADD A NEW CONTACT........ case 1: // add contact option............. // add name dateValid = false; invalidTag = true; moreEmail = true; morePhone = true; email = ""; phoneList = ""; nameList.clear(); System.out.println("\nENTER NAME OF THE PERSON(Ex: Aditya Dey)"); validName = false; fileReader = new BufferedReader(new FileReader(contactBookName)); while (!validName) { name = stringReader.nextLine(); // read contact name from user name = name.trim(); if (name.equals("")) { System.out.println( "\nNAME OF THE PERSON CANNOT BE BLANK\nENTER NAME OF THE PERSON(Ex: Aditya Dey)"); continue; } while (((line = fileReader.readLine()) != null)) // read till end of file { String s = line.substring(0, line.indexOf('=')); // add each name that exists in the file if (!nameList.contains(s)) { nameList.add(s); } } // System.out.println(nameList); if (nameList.contains(name)) // if name already exists, print error message { System.out.println("\nA CONTACT NAMED " + name + " ALREADY EXISTS."); System.out.println("\nPLEASE ADD ANOTHER NAME(Ex: Aditya Dey)"); } else { validName = true; nameList.add(name); } } // date of birth System.out.println( "\nENTER DOB OF THE PERSON IN DD/MM/YYYY FORMAT Ex: 12/05/1992 OR PRESS ENTER TO SKIP"); while (!dateValid) { dateOfBirth = stringReader.nextLine(); if (dateOfBirth.trim().compareTo("") == 0) dateValid = true; else // doubt? next() skips next scan... dateValid = isValidDate(dateOfBirth); if (!dateValid) { System.out.println( "\nINVALID DATE...\nENTER DOB OF THE PERSON IN DD/MM/YYYY FORMAT Ex: 12/05/1992"); } } // System.out.println(dateOfBirth); // add contact type System.out.println("\nENTER PET NAME OF THE PERSON OR ENTER TO SKIP"); petName = stringReader.nextLine(); System.out.println("\nCHOOSE CONTACT TYPE..."); System.out.println("\nFOR FAMILY->PRESS 1 "); System.out.println("FOR FRIENDS->PRESS 2 "); System.out.println("FOR ASSOCIATES->PRESS 3 "); System.out.println("FOR OTHERS->PRESS 4 "); while (!sc.hasNextInt()) { System.out.println("\nENTER ONLY NUMBERS RANGED FROM 1 - 4"); sc.nextLine(); } tag = sc.nextInt(); while (invalidTag) { switch (tag) { case 1: contactType = "Family"; invalidTag = false; break; case 2: contactType = "Friend"; invalidTag = false; break; case 3: contactType = "Associate"; invalidTag = false; break; case 4: contactType = "Others"; invalidTag = false; break; default: System.out.println("\nENTER ONLY NUMBERS RANGED FROM 1-4"); invalidTag = true; break; } } // System.out.println(contactType); System.out.println("\nENTER ADDRESS IN ONE LINE OR PRESS ENTER TO SKIP"); address = stringReader.nextLine(); // System.out.println(address); while (moreEmail) { System.out.println("\nENTER EMAIL ADDRESS OR PRESS ENTER TO SKIP"); email = email + "," + stringReader.nextLine(); // System.out.println(email); if (!(email.trim()).equals(",")) { System.out.println( "\nTO ADD EMAIL ADRESS->PRESS 'Y' OR 'y'..TO STOP ADDING EMAIL PRESS ANY OTHER KEY"); emailChoice = stringReader.nextLine(); if (emailChoice.equals("y") || emailChoice.equals("Y")) { moreEmail = true; } else { moreEmail = false; } } else { moreEmail = false; } } email = email.substring(1, email.length()); // System.out.println(email); while (morePhone) { System.out.println("\nENTER CONTACT NUMBER"); while (!sc.hasNextLong()) { System.out.println("\nINVALID CONTACT NUMBER.\nENTER A VALID CONTACT NUMBER"); sc.next(); } phoneNum = sc.nextLong(); phoneList = phoneList + "," + phoneNum; sc.nextLine(); // doubt? not included: doesnt read phonechoice..... System.out.println( "\nTO ADD MORE PHONE NUMBERS->PRESS 'Y' OR 'y' \nOTHERWISE PRESS ANY OTHER KEY"); phoneChoice = sc.nextLine(); if (phoneChoice.equals("y") || phoneChoice.equals("Y")) { morePhone = true; } else { morePhone = false; } } phoneList = phoneList.substring(1, phoneList.length()); System.out.println("FOLLOWING DETAILS HAS BEEN SAVED IN THE PHONEBOOK"); System.out.println("---------------------------------------------------"); System.out.println( "[" + name + "," + petName + "," + contactType + "," + address + "," + dateOfBirth + "," + email + "," + phoneList + "]"); totalDetails = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + new Date(); fileWriter.write(totalDetails); fileWriter.newLine(); fileWriter.flush(); break; // EDITING A CONTACT case 2: String editName = ""; String details = ""; String line3 = ""; String[] detailParts; String newDob = ""; String newPetName = ""; String newAddress = ""; String newContactType = ""; String newEmail = ""; String newPhone = ""; String newString = ""; String name3 = ""; choice = 0; nameList.clear(); String[] parts; fileReader = new BufferedReader(new FileReader(contactBookName)); while (((line = fileReader.readLine()) != null)) // read till end of file { String s = line.substring(0, line.indexOf('=')); // add each name that exists in the file if (!nameList.contains(s)) { nameList.add(s); } } BufferedReader editReader = new BufferedReader(new FileReader(contactBookName)); dateValid = false; invalidTag = true; String editContact = ""; System.out.println("\nENTER THE CONTACT TO BE EDITED"); editName = stringReader.nextLine(); if (!nameList.contains(editName)) { System.out.println("\nA CONTACT NAMED " + editName + " DOES NOT EXIST"); } else { while ((line3 = editReader.readLine()) != null) { // System.out.println(line3); name3 = line3.substring(0, line3.indexOf("=")); if (!name3.equals(editName)) { newString = newString + line3 + System.getProperty("line.separator"); } else { editContact = line3; } } details = editContact.substring(editContact.indexOf("=") + 1, editContact.length()); detailParts = details.split(":"); newDob = detailParts[0]; newPetName = detailParts[1]; newContactType = detailParts[2]; newAddress = detailParts[3]; newEmail = detailParts[4]; newPhone = detailParts[5]; while (choice != 7) { System.out.println("\nTO EDIT DATE OF BIRTH->PRESS 1"); System.out.println("TO EDIT PET NAME->PRESS 2 "); System.out.println("TO EDIT CONTACT TYPE->PRESS 3 "); System.out.println("TO EDIT ADDRESS->PRESS 4 "); System.out.println("TO ADD EMAIL->PRESS 5 "); System.out.println("TO ADD PHONE NUMBER->PRESS 6 "); System.out.println("TO GO BACK TO THE PREVIOUS MENU->PRESS 7 "); System.out.print("ENTER YOUR CHOICE::\t"); while (!sc.hasNextInt()) { System.out.println("ENTER ONLY INTEGERS IN THE RANGE 1-7"); sc.nextLine(); } choice = sc.nextInt(); switch (choice) { case 1: System.out.println( "\nENTER DOB OF THE PERSON IN DD/MM/YYYY FORMAT EG: 12/05/1992"); while (!dateValid) { newDob = stringReader.nextLine(); // doubt? next() skips next scan... dateValid = isValidDate(newDob); if (!dateValid) { System.out.println( "\nINVALID DATE...ENTER DOB OF THE PERSON IN DD/MM/YYYY FORMAT EG: 12/05/1992"); } } break; case 2: System.out.println("\nENTER NEW PET NAME OF THE PERSON OR ENTER TO SKIP"); newPetName = stringReader.nextLine(); break; case 3: System.out.println("\nCHOOSE CONTACT TYPE..."); System.out.println("\nFOR FAMILY->PRESS 1 "); System.out.println("FOR FRIENDS->PRESS 2 "); System.out.println("FOR ASSOCIATES->PRESS 3 "); System.out.println("FOR OTHERS->PRESS 4 "); while (!sc.hasNextInt()) { System.out.println("\nENTER ONLY NUMBERS IN THE RANGE 1 - 3"); sc.nextLine(); } tag = sc.nextInt(); while (invalidTag) { switch (tag) { case 1: newContactType = "Family"; invalidTag = false; break; case 2: newContactType = "Friend"; invalidTag = false; break; case 3: newContactType = "Associate"; invalidTag = false; break; case 4: newContactType = "Others"; invalidTag = false; break; default: System.out.println("\nENTER ONLY NUMBERS RANGED FROM 1-4"); invalidTag = true; break; } } break; case 4: System.out.println("\nENTER NEW ADDRESS IN ONE LINE"); newAddress = stringReader.nextLine(); break; case 5: moreEmail = true; while (moreEmail) { System.out.println("\nENTER EMAIL ADDRESS OR PRESS ENTER TO SKIP"); newEmail = newEmail + "," + stringReader.nextLine(); // System.out.println(email); if (!(newEmail.trim()).equals(",")) { System.out.println( "TO ADD EMAIL->PRESS 'Y' OR 'y'..TO STOP ADDING EMAIL PRESS ANY OTHER KEY"); emailChoice = stringReader.nextLine(); if (emailChoice.equals("y") || emailChoice.equals("Y")) { moreEmail = true; } else { moreEmail = false; } } else { moreEmail = false; } } break; case 6: morePhone = true; while (morePhone) { System.out.println("\nENTER PHONE NUMBER"); while (!sc.hasNextLong()) { System.out.println("\nONLY VALID PHONE NUMBERS ALLOWED"); sc.next(); } phoneNum = sc.nextLong(); newPhone = phoneNum + ","; sc.nextLine(); // doubt? not included: doesnt read phonechoice..... System.out.println( "\nTO ADD MORE PHONE NUMBERS->PRESS 'y' or 'Y'\nOTHERWISE PRESS ANY OTHER KEY"); phoneChoice = sc.nextLine(); if (phoneChoice.equals("y") || phoneChoice.equals("Y")) { morePhone = true; } else { morePhone = false; } } phoneList = newPhone; phoneList = phoneList.substring(1, phoneList.length()); break; case 7: System.out.println( "[" + editName + "," + newPetName + "," + newContactType + "," + newAddress + "," + newDob + "," + newEmail + "," + newPhone + "]"); String newDetails = editName + "=" + newDob + ":" + newPetName + ":" + newContactType + ":" + newAddress + ":" + newEmail + ":" + newPhone + ":" + new Date(); newString = newString + newDetails + System.getProperty("line.separator"); BufferedWriter editWriter = new BufferedWriter(new FileWriter(contactBookName)); editWriter.write(newString); editWriter.close(); break; default: System.out.println("\nENTER ONLY NUMBERS RANGED FROM 1-7"); break; } } } // dob:petname:tag:address:email1,email2,email3..:ph1,ph2,...:crtdate break; case 3: // REMOVING A CONTACT BufferedReader removalReader = new BufferedReader(new FileReader(contactBookName)); String name2 = ""; String line2 = ""; String nameRemoved = ""; String finalString = ""; System.out.println("\nENTER THE NAME TO BE REMOVED"); nameRemoved = stringReader.nextLine(); if (!nameList.contains(nameRemoved)) { System.out.println("\nA CONTACT WITH NAME " + nameRemoved + " DOES NOT EXIST\n"); } else { while ((line2 = removalReader.readLine()) != null) { name2 = line2.substring(0, line2.indexOf("=")); if (!name2.equals(nameRemoved)) { finalString = finalString + line2 + System.getProperty("line.separator"); } } BufferedWriter removalWriter = new BufferedWriter(new FileWriter(contactBookName)); removalWriter.write(finalString); removalWriter.close(); System.out.println("CONTACT " + nameRemoved + " REMOVED "); } break; // LISTING ELEMENTS case 4: int listChoice = 0; BufferedReader listReader = new BufferedReader(new FileReader(contactBookName)); parts = null; TreeMap<String, String> nameDetailMap = new TreeMap<String, String>(); String line4 = ""; while (listChoice != 4) { System.out.println("\nTO DISPLAY CONTACTS BY ALPHABETICAL ORDERING OF NAMES->PRESS 1 "); System.out.println("TO DISPLAY CONTACTS BY CREATED DATE->PRESS 2 "); System.out.println("TO DISPLAY CONTACTS BY TAG->PRESS 3 "); System.out.println("TO GO BACK TO PREVIOUS MENU->PRESS 4 "); System.out.print("ENTER CHOICE::\t"); while (!sc.hasNextInt()) { System.out.println("ENTER ONLY INTEGERS IN THE RANGE 1-4"); sc.next(); } listChoice = sc.nextInt(); switch (listChoice) { // ORDERING CONTACTS BY ALPHABETICAL ORDERING OF NAMES.............. case 1: listReader = new BufferedReader(new FileReader(contactBookName)); line4 = ""; parts = null; while ((line4 = listReader.readLine()) != null) { parts = line4.split("="); nameDetailMap.put(parts[0], parts[1]); } Collection<String> c = nameDetailMap.keySet(); Iterator<String> it = c.iterator(); if (it.hasNext()) { System.out.println( "\nCONTACTS BELOW ARE LISTED IN ALPHABETICAL ORDERING OF NAMES"); System.out.println("-----------------------------------------------------------"); } else { System.out.println("NO CONTACTS AVAILABLE"); } while (it.hasNext()) { String s = (String) it.next(); System.out.println("\n\n" + s); System.out.println("---------------------------------"); String[] contactDetail = nameDetailMap.get(s).split(":"); for (int i = 0; i < contactDetail.length; i++) { if (contactDetail[i].trim().compareTo("") == 0) { contactDetail[i] = "Unavailable"; } } System.out.println("Date of Birth::\t" + contactDetail[0]); System.out.println("Pet name::\t" + contactDetail[1]); System.out.println("Contact Type::\t" + contactDetail[2]); System.out.println("Address::\t" + contactDetail[3]); System.out.println("Email Address::\t" + contactDetail[4]); System.out.println("Phone No::\t" + contactDetail[5]); System.out.println("Contact added::\t" + contactDetail[6]); } break; // ORDERING CONTACTS BY CREATED DATE.............. case 2: BufferedReader br = new BufferedReader(new FileReader(contactBookName)); line4 = ""; String date = ""; String[] part; TreeMap<Date, String> tm = new TreeMap<Date, String>(); while ((line4 = br.readLine()) != null) { part = line4.split(":"); SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd H:m"); String h = (part[6] + ":" + part[7]); Date d = formatter.parse(h); tm.put(d, line4); } Collection<Date> c1 = tm.keySet(); // System.out.println(c1); Iterator<Date> it1 = c1.iterator(); if (it1.hasNext()) { System.out.println("\nCONTACTS BELOW ARE LISTED IN ORDER OF CREATED DATES"); System.out.println("--------------------------------------------------------"); } else { System.out.println("NO CONTACTS AVAILABLE"); } while (it1.hasNext()) { String s = it1.next().toString() + ""; // System.out.println(s); System.out.println("\n\n" + s); SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd H:m"); Date d = formatter.parse(s); System.out.println("---------------------------------"); String[] nameContact = tm.get(d).split("="); System.out.println(nameContact[0]); String[] contactDetail = nameContact[1].split(":"); for (int i = 0; i < contactDetail.length; i++) { if (contactDetail[i].trim().compareTo("") == 0) { contactDetail[i] = "Unavailable"; } } System.out.println("Date of Birth::\t" + contactDetail[0]); System.out.println("Pet name::\t" + contactDetail[1]); System.out.println("Contact Type::\t" + contactDetail[2]); System.out.println("Address::\t" + contactDetail[3]); System.out.println("Email Address::\t" + contactDetail[4]); System.out.println("Phone No::\t" + contactDetail[5]); } break; //// ORDERING CONTACTS BY TAG.............. // dob:petname:tag:address:email1,email2,email3..:ph1,ph2,...:crtdate case 3: ArrayList<String> familyList = new ArrayList<String>(); ArrayList<String> friendsList = new ArrayList<String>(); ArrayList<String> colleaguesList = new ArrayList<String>(); ArrayList<String> othersList = new ArrayList<String>(); line4 = ""; parts = null; br = new BufferedReader(new FileReader(contactBookName)); while ((line4 = br.readLine()) != null) { parts = line4.split(":"); String relation = parts[2]; if (relation.equals("Family")) { familyList.add(line4); } else if (relation.equals("Friend")) { friendsList.add(line4); } else if (relation.equals("Associate")) { colleaguesList.add(line4); } else { othersList.add(line4); } } if (familyList.isEmpty() && friendsList.isEmpty() && colleaguesList.isEmpty() && othersList.isEmpty()) { System.out.println("NO CONTACTS AVAILABLE."); } else { System.out.println("\nCONTACTS BELOW ARE LISTED ACCORDING TO TAGS"); System.out.println("--------------------------------------------------------"); } if (!familyList.isEmpty()) { System.out.println("\nFAMILY CONTACTS\n----------------------------"); for (Object s : familyList) { String[] nameContact = s.toString().split("="); System.out.println(nameContact[0] + "\n"); String[] contactDetail = nameContact[1].split(":"); for (int i = 0; i < contactDetail.length; i++) { if (contactDetail[i].trim().compareTo("") == 0) { contactDetail[i] = "Unavailable"; } } System.out.println(" Date of Birth::\t" + contactDetail[0]); System.out.println(" Pet name::\t\t" + contactDetail[1]); System.out.println(" Address::\t\t" + contactDetail[3]); System.out.println(" Email Address::\t" + contactDetail[4]); System.out.println(" Phone No::\t\t" + contactDetail[5]); System.out.println(" Contact added::\t" + contactDetail[6]); } } if (!friendsList.isEmpty()) { System.out.println("\nFRIEND CONTACTS\n----------------------------"); for (Object s : friendsList) { String[] nameContact = s.toString().split("="); System.out.println(nameContact[0] + "\n"); String[] contactDetail = nameContact[1].split(":"); for (int i = 0; i < contactDetail.length; i++) { if (contactDetail[i].trim().compareTo("") == 0) { contactDetail[i] = "Unavailable"; } } System.out.println(" Date of Birth::\t" + contactDetail[0]); System.out.println(" Pet name::\t\t" + contactDetail[1]); System.out.println(" Address::\t\t" + contactDetail[3]); System.out.println(" Email Address::\t" + contactDetail[4]); System.out.println(" Phone No::\t\t" + contactDetail[5]); System.out.println(" Contact added::\t" + contactDetail[6]); } } if (!colleaguesList.isEmpty()) { System.out.println("\nASSOCIATE CONTACTS\n----------------------------"); for (Object s : colleaguesList) { String[] nameContact = s.toString().split("="); System.out.println(nameContact[0] + "\n"); String[] contactDetail = nameContact[1].split(":"); for (int i = 0; i < contactDetail.length; i++) { if (contactDetail[i].trim().compareTo("") == 0) { contactDetail[i] = "Unavailable"; } } System.out.println(" Date of Birth::\t" + contactDetail[0]); System.out.println(" Pet name::\t\t" + contactDetail[1]); System.out.println(" Address::\t\t" + contactDetail[3]); System.out.println(" Email Address::\t" + contactDetail[4]); System.out.println(" Phone No::\t\t" + contactDetail[5]); System.out.println(" Contact added::\t" + contactDetail[6]); } } if (!othersList.isEmpty()) { System.out.println("\nOTHER CONTACTS\n----------------------------"); for (Object s : othersList) { String[] nameContact = s.toString().split("="); System.out.println(nameContact[0] + "\n"); String[] contactDetail = nameContact[1].split(":"); for (int i = 0; i < contactDetail.length; i++) { if (contactDetail[i].trim().compareTo("") == 0) { contactDetail[i] = "Unavailable"; } } System.out.println(" Date of Birth::\t" + contactDetail[0]); System.out.println(" Pet name::\t\t" + contactDetail[1]); System.out.println(" Address::\t\t" + contactDetail[3]); System.out.println(" Email Address::\t" + contactDetail[4]); System.out.println(" Phone No::\t\t" + contactDetail[5]); System.out.println(" Contact added::\t" + contactDetail[6]); } } break; case 4: break; default: System.out.println("\nENTER ONLY INTEGERS IN THE RANGE 1-5"); break; } } break; // SEARCH CONTACTS BOOK... case 5: String[] details1 = null; line4 = ""; searchString = ""; parts = null; String addedDetails = ""; fileReader = new BufferedReader(new FileReader(contactBookName)); System.out.println("ENTER THE STRING TO BE SERCHED FOR IN THE CONTACTS BOOK"); searchString = stringReader.nextLine(); ArrayList<String> nameMatchList = new ArrayList<String>(); ArrayList<String> emailMatchList = new ArrayList<String>(); ArrayList<String> tagMatchList = new ArrayList<String>(); ArrayList<String> addressMatchList = new ArrayList<String>(); ArrayList<String> dobMatchList = new ArrayList<String>(); ArrayList<String> phoneMatchList = new ArrayList<String>(); ArrayList<String> petNameMatchList = new ArrayList<String>(); String addedString = ""; while ((line4 = fileReader.readLine()) != null) { parts = line4.split("="); name = parts[0]; details1 = parts[1].split(":"); dateOfBirth = details1[0]; petName = details1[1]; contactType = details1[2]; address = details1[3]; email = details1[4]; phoneList = details1[5]; contactAdded = details1[6]; addedString = ""; // System.out.println("name = "+name+" dateOfbirth = "+dateOfBirth+" petName // ="+petName+" contactType ="+contactType+"address ="+address+"email // ="+email+"phoneList ="+phoneList); if (name.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; nameMatchList.add(addedString); } if (dateOfBirth.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; dobMatchList.add(addedString); } if (petName.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; petNameMatchList.add(addedString); } if (contactType.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; tagMatchList.add(addedString); } if (address.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; addressMatchList.add(addedString); } if (email.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; emailMatchList.add(addedString); } if (phoneList.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; phoneMatchList.add(addedString); } } System.out.println( "\nTOTAL NUMBER OF MATCHES = " + (nameMatchList.size() + dobMatchList.size() + petNameMatchList.size() + tagMatchList.size() + addressMatchList.size() + emailMatchList.size() + phoneMatchList.size())); if (!nameMatchList.isEmpty()) { System.out.println( "\nTOTAL " + nameMatchList.size() + " NAMES MATCH WITh " + searchString + "\n"); System.out.println( "\nTHE NAMES OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : nameMatchList) { showContactByType(s, 2); } } if (!dobMatchList.isEmpty()) { System.out.println( "\nTOTAL " + dobMatchList.size() + " DOBS' MATCH WITH " + searchString + "\n"); System.out.println( "\nTHE DOB'S OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : dobMatchList) { showContactByType(s, 2); } } if (!petNameMatchList.isEmpty()) { System.out.println( "\nTOTAL " + petNameMatchList.size() + " PET NAMES MATCH WITH " + searchString + "\n"); System.out.println( "\nTHE PET NAMES OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : petNameMatchList) { showContactByType(s, 2); } } if (!tagMatchList.isEmpty()) { System.out.println( "\nTOTAL " + tagMatchList.size() + " CONTACT TYPES MATCH WITH THE " + searchString + "\n"); System.out.println( "\nTHE TAGS OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : tagMatchList) { showContactByType(s, 2); } } if (!addressMatchList.isEmpty()) { System.out.println( "\nTOTAL " + addressMatchList.size() + " ADDRESSES MATCH WITH " + searchString + "\n"); System.out.println( "\nTHE ADDRESSES OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : addressMatchList) { showContactByType(s, 2); } } if (!emailMatchList.isEmpty()) { System.out.println( "\nTOTAL " + emailMatchList.size() + " EMAILS MATCH WITH " + searchString + "\n"); System.out.println( "\nTHE EMAIL'S OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : emailMatchList) { showContactByType(s, 2); } } if (!phoneMatchList.isEmpty()) { System.out.println( "\nTOTAL " + phoneMatchList.size() + " CONTACT NUMBERS MATCH WITH " + searchString + "\n"); System.out.println( "\nTHE PHONE NUMBERS OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : phoneMatchList) { showContactByType(s, 2); } } break; case 6: break; default: System.out.println("\nENTER ONLY NUMBERS RANGED FROM 1-6"); break; } } // fileReader.close(); // fileWriter.close(); // stringReader.close(); // sc.close(); }
public static void main(String[] args) { Scanner sc = null; Scanner stringReader = null; try { int ch = 0; sc = new Scanner(System.in); boolean validFile = false; stringReader = new Scanner(System.in); System.out.println("\n\t\t\tCONTACTS APP"); System.out.println( "--------------------------------------------------------------------------------"); while (ch != 5) { System.out.println("\nTO CREATE PHONEBOOK->PRESS 1"); System.out.println("TO LOAD A CREATED PHONEBOOK->PRESS 2"); System.out.println("TO DELETE CREATED PHONEBOOK->PRESS 3"); System.out.println("TO LIST ALL PHONEBOOKS->PRESS 4"); System.out.println("TO EXIT->PRESS 5"); while (!sc.hasNextInt()) { System.out.println("\nONLY NUMBERS RANGED FROM 1 - 5 SHOULD BE ENTERED..RETRY"); sc.nextLine(); } ch = sc.nextInt(); switch (ch) { case 1: System.out.println( "\nENTER NAME OF PHONEBOOK(Ex MyPhoneBook).DONT GIVE ANY EXTENSION."); validFile = false; String contactBookName = ""; while (!validFile) { contactBookName = stringReader.nextLine(); if (contactBookName.equals("")) { System.out.println("\nPHONEBOOK NAME MUST NOT BE EMPTY"); System.out.println( "\nENTER NAME OF PHONEBOOK(Ex MyPhoneBook).DONT GIVE ANY EXTENSION."); continue; } if (!(contactBookName.contains("/") || contactBookName.contains("\\") || contactBookName.contains(":") || contactBookName.contains("*") || contactBookName.contains("?") || contactBookName.contains("/") || contactBookName.contains("\"") || contactBookName.contains("<") || contactBookName.contains(">") || contactBookName.contains("|"))) { String extension[] = contactBookName.split("."); contactBookName = contactBookName + ".txt"; File contactBook = new File(contactBookName); if (!contactBook.exists()) { System.out.println("\nNEW PHONEBOOK CREATED::" + contactBookName); validFile = true; } else { System.out.println( "\nTHIS PHONEBOOK NAMED " + contactBookName + " ALREADY EXISTS\nPLEASE ENTER A DIFFERENT NAME"); } } else { System.out.println("\nFILE NAME CANNOT CONTAIN : /,\\,\",*,?,<,>,|"); System.out.println( "\nENTER NAME OF CONTACTS BOOK TO CREATE WITHOUT FILE EXTENSION "); } } contactBookOperations(contactBookName); break; case 2: contactBookName = ""; System.out.println( "\nENTER NAME OF PHONEBOOK(Ex MyPhoneBook) TO LOAD.DONT GIVE ANY EXTENSION."); contactBookName = stringReader.nextLine(); while (true) { if (contactBookName.equals("")) { System.out.println("\nPHONEBOOK NAME MUST NOT BE EMPTY "); } else { break; } } contactBookName += ".txt"; File contactBook = new File(contactBookName); if (!contactBook.exists()) { System.out.println("\nA PHONEBOOK WITH NAME " + contactBookName + " DOES NOT EXIST"); } else { contactBookOperations(contactBookName); } break; case 3: contactBookName = ""; System.out.println("\nENTER NAME OF PHONEBOOK WITHOUT EXTENSION TO DELETE"); contactBookName = stringReader.nextLine(); if (contactBookName.equals("")) { System.out.println("\nPHONEBOOK NAME CANNOT BE EMPTY "); } contactBookName += ".txt"; contactBook = new File(contactBookName); if (!contactBook.exists()) { System.out.println("\nA PHONEBOOK WITH NAME " + contactBookName + " DOES NOT EXIST"); } else { contactBook.delete(); System.out.println("\nA PHONEBOOK " + contactBookName + " DELETED"); } break; case 4: String curDirectory = System.getProperty("user.dir"); listPhoneBooks(curDirectory); break; case 5: System.out.println("\nSUCCESSFULLY EXITED"); break; default: System.out.println("\nENTER ONLY NUMBERS RANGED FROM 1 - 5"); break; } } } catch (Exception e) { System.out.println("AN ERROR OCCURED!!"); e.printStackTrace(); } finally { if (sc != null) sc.close(); if (stringReader != null) stringReader.close(); } }
/** * The constructor for this class has a bunch of arguments: The frame argument is required for all * printing in Java. The jobname appears left justified at the top of each printed page. The font * size is specified in points, as on-screen font sizes are. The margins are specified in inches * (or fractions of inches). */ public HardcopyWriter( Frame frame, String jobname, int fontsize, double leftmargin, double rightmargin, double topmargin, double bottommargin) throws HardcopyWriter.PrintCanceledException { // Get the PrintJob object with which we'll do all the printing. // The call is synchronized on the static printprops object, which // means that only one print dialog can be popped up at a time. // If the user clicks Cancel in the print dialog, throw an exception. Toolkit toolkit = frame.getToolkit(); // get Toolkit from Frame synchronized (printprops) { job = toolkit.getPrintJob(frame, jobname, printprops); } if (job == null) throw new PrintCanceledException("User cancelled print request"); pagesize = job.getPageDimension(); // query the page size pagedpi = job.getPageResolution(); // query the page resolution // Bug Workaround: // On windows, getPageDimension() and getPageResolution don't work, so // we've got to fake them. if (System.getProperty("os.name").regionMatches(true, 0, "windows", 0, 7)) { // Use screen dpi, which is what the PrintJob tries to emulate, anyway pagedpi = toolkit.getScreenResolution(); System.out.println(pagedpi); // Assume a 8.5" x 11" page size. A4 paper users have to change this. pagesize = new Dimension((int) (8.5 * pagedpi), 11 * pagedpi); System.out.println(pagesize); // We also have to adjust the fontsize. It is specified in points, // (1 point = 1/72 of an inch) but Windows measures it in pixels. fontsize = fontsize * pagedpi / 72; System.out.println(fontsize); System.out.flush(); } // Compute coordinates of the upper-left corner of the page. // I.e. the coordinates of (leftmargin, topmargin). Also compute // the width and height inside of the margins. x0 = (int) (leftmargin * pagedpi); y0 = (int) (topmargin * pagedpi); width = pagesize.width - (int) ((leftmargin + rightmargin) * pagedpi); height = pagesize.height - (int) ((topmargin + bottommargin) * pagedpi); // Get body font and font size font = new Font("Monospaced", Font.PLAIN, fontsize); metrics = toolkit.getFontMetrics(font); lineheight = metrics.getHeight(); lineascent = metrics.getAscent(); charwidth = metrics.charWidth('0'); // Assumes a monospaced font! // Now compute columns and lines will fit inside the margins chars_per_line = width / charwidth; lines_per_page = height / lineheight; // Get header font information // And compute baseline of page header: 1/8" above the top margin headerfont = new Font("SansSerif", Font.ITALIC, fontsize); headermetrics = toolkit.getFontMetrics(headerfont); headery = y0 - (int) (0.125 * pagedpi) - headermetrics.getHeight() + headermetrics.getAscent(); // Compute the date/time string to display in the page header DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT); df.setTimeZone(TimeZone.getDefault()); time = df.format(new Date()); this.jobname = jobname; // save name this.fontsize = fontsize; // save font size }
private void register() throws IOException { Log.info("Registering with " + registrar); FromHeader fromHeader = getFromHeader(); Address fromAddress = fromHeader.getAddress(); // Request URI SipURI requestURI = null; try { requestURI = addressFactory.createSipURI(null, registrar); } catch (ParseException e) { throw new IOException("Bad registrar address:" + registrar + " " + e.getMessage()); } // requestURI.setPort(registrarPort); try { requestURI.setTransportParam(sipProvider.getListeningPoint().getTransport()); } catch (ParseException e) { throw new IOException( sipProvider.getListeningPoint().getTransport() + " is not a valid transport! " + e.getMessage()); } CallIdHeader callIdHeader = sipProvider.getNewCallId(); CSeqHeader cSeqHeader = null; try { cSeqHeader = headerFactory.createCSeqHeader(1, Request.REGISTER); } catch (ParseException e) { // Should never happen throw new IOException("Corrupt Sip Stack " + e.getMessage()); } catch (InvalidArgumentException e) { // Should never happen throw new IOException("The application is corrupt "); } ToHeader toHeader = null; try { String proxyWorkAround = System.getProperty("com.sun.mc.softphone.REGISTRAR_WORKAROUND"); if (proxyWorkAround != null && proxyWorkAround.toUpperCase().equals("TRUE")) { SipURI toURI = (SipURI) (requestURI.clone()); toURI.setUser(System.getProperty("user.name")); toHeader = headerFactory.createToHeader(addressFactory.createAddress(toURI), null); } else { toHeader = headerFactory.createToHeader(fromAddress, null); } } catch (ParseException e) { throw new IOException( "Could not create a To header for address:" + fromHeader.getAddress() + " " + e.getMessage()); } ArrayList viaHeaders = getLocalViaHeaders(); MaxForwardsHeader maxForwardsHeader = getMaxForwardsHeader(); Request request = null; try { request = messageFactory.createRequest( requestURI, Request.REGISTER, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwardsHeader); } catch (ParseException e) { throw new IOException("Could not create the register request! " + e.getMessage()); } ExpiresHeader expHeader = null; for (int retry = 0; retry < 2; retry++) { try { expHeader = headerFactory.createExpiresHeader(expires); } catch (InvalidArgumentException e) { if (retry == 0) { continue; } throw new IOException( "Invalid registrations expiration parameter - " + expires + " " + e.getMessage()); } } request.addHeader(expHeader); ContactHeader contactHeader = getRegistrationContactHeader(); request.addHeader(contactHeader); try { SipURI routeURI = (SipURI) addressFactory.createURI("sip:" + proxyCredentials.getProxy() + ";lr"); RouteHeader routeHeader = headerFactory.createRouteHeader(addressFactory.createAddress(routeURI)); request.addHeader(routeHeader); } catch (Exception e) { Log.error("Creating registration route error ", e); } ClientTransaction regTrans = null; try { regTrans = sipProvider.getNewClientTransaction(request); } catch (TransactionUnavailableException e) { throw new IOException( "Could not create a register transaction!\n" + "Check that the Registrar address is correct! " + e.getMessage()); } try { sipCallId = callIdHeader.getCallId(); sipServerCallback.addSipListener(sipCallId, this); registerRequest = request; regTrans.sendRequest(); Log.debug("Sent register request " + registerRequest); if (expires > 0) { scheduleReRegistration(); } } catch (Exception e) { throw new IOException("Could not send out the register request! " + e.getMessage()); } this.registerRequest = request; }
/** * Reads and validates a data file containing historical market depth records. The data file is used * for back testing and optimization of trading strategies. */ public class BackTestFileReader { public static final int COLUMNS = 5; private static final String LINE_SEP = System.getProperty("line.separator"); private final BufferedReader reader; private final MarketSnapshotFilter filter; private final long fileSize; private long previousTime, time; private SimpleDateFormat sdf; private String previousDateTimeWithoutSeconds; public BackTestFileReader(String fileName, MarketSnapshotFilter filter) throws JBookTraderException { this.filter = filter; previousDateTimeWithoutSeconds = ""; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); fileSize = new File(fileName).length(); } catch (FileNotFoundException fnfe) { throw new JBookTraderException("Could not find file " + fileName); } } private void setTimeZone(String line) throws JBookTraderException { String timeZone = line.substring(line.indexOf('=') + 1); TimeZone tz = TimeZone.getTimeZone(timeZone); if (!tz.getID().equals(timeZone)) { String msg = "The specified time zone " + "\"" + timeZone + "\"" + " does not exist." + LINE_SEP; msg += "Examples of valid time zones: " + " America/New_York, Europe/London, Asia/Singapore."; throw new JBookTraderException(msg); } sdf = new SimpleDateFormat("MMddyyHHmmss"); // Enforce strict interpretation of date and time formats sdf.setLenient(false); sdf.setTimeZone(tz); } public List<MarketSnapshot> load(ProgressListener progressListener) throws JBookTraderException { String line = ""; int lineSeparatorSize = System.getProperty("line.separator").length(); long sizeRead = 0, lineNumber = 0; List<MarketSnapshot> snapshots = new ArrayList<MarketSnapshot>(); try { while ((line = reader.readLine()) != null) { if (lineNumber % 50000 == 0) { progressListener.setProgress(sizeRead, fileSize, "Loading historical data file"); if (progressListener.isCancelled()) { break; } } lineNumber++; sizeRead += line.length() + lineSeparatorSize; boolean isComment = line.startsWith("#"); boolean isProperty = line.contains("="); boolean isBlankLine = (line.trim().length() == 0); boolean isMarketDepthLine = !(isComment || isProperty || isBlankLine); if (isMarketDepthLine) { MarketSnapshot marketSnapshot = toMarketDepth(line); if (filter == null || filter.contains(time)) { snapshots.add(marketSnapshot); } previousTime = time; } else if (isProperty) { if (line.startsWith("timeZone")) { setTimeZone(line); } } } if (sdf == null) { String msg = "Property " + "\"timeZone\"" + " is not defined in the data file." + LINE_SEP; throw new JBookTraderException(msg); } } catch (IOException ioe) { throw new JBookTraderException("Could not read data file"); } catch (Exception e) { String errorMsg = "Problem parsing line #" + lineNumber + ": " + line + LINE_SEP; String description = e.getMessage(); if (description == null) { description = e.toString(); } errorMsg += description; throw new RuntimeException(errorMsg); } return snapshots; } private MarketSnapshot toMarketDepth(String line) throws JBookTraderException, ParseException { List<String> tokens = fastSplit(line); if (tokens.size() != COLUMNS) { String msg = "The line should contain exactly " + COLUMNS + " comma-separated columns."; throw new JBookTraderException(msg); } String dateTime = tokens.get(0) + tokens.get(1); String dateTimeWithoutSeconds = dateTime.substring(0, 10); if (dateTimeWithoutSeconds.equals(previousDateTimeWithoutSeconds)) { // only seconds need to be set int milliSeconds = 1000 * Integer.parseInt(dateTime.substring(10)); long previousMilliSeconds = previousTime % 60000; time = previousTime + (milliSeconds - previousMilliSeconds); } else { time = sdf.parse(dateTime).getTime(); previousDateTimeWithoutSeconds = dateTimeWithoutSeconds; } if (time <= previousTime) { String msg = "Timestamp of this line is before or the same as the timestamp of the previous line."; throw new JBookTraderException(msg); } double balance = Double.parseDouble(tokens.get(2)); double price = Double.parseDouble(tokens.get(3)); int volume = Integer.parseInt(tokens.get(4)); return new MarketSnapshot(time, balance, price, volume); } private List<String> fastSplit(String s) { ArrayList<String> tokens = new ArrayList<String>(); int index, lastIndex = 0; while ((index = s.indexOf(',', lastIndex)) != -1) { tokens.add(s.substring(lastIndex, index)); lastIndex = index + 1; } tokens.add(s.substring(lastIndex)); return tokens; } }
/** * Writes historical market data to a file which is used for backtesting and optimization of trading * strategies. */ public class BackTestFileWriter { private static final String FILE_SEP = System.getProperty("file.separator"); private static final String LINE_SEP = System.getProperty("line.separator"); private static final String MARKET_DATA_DIR = JArbitrager.getAppPath() + FILE_SEP + "marketData"; private final DecimalFormat decimalFormat; private final SimpleDateFormat dateFormat; private PrintWriter writer; public BackTestFileWriter(Strategy strategy) throws JArbitragerException { decimalFormat = NumberFormatterFactory.getNumberFormatter(5); dateFormat = new SimpleDateFormat("MMddyy,HHmmss"); dateFormat.setTimeZone(strategy.getTradingSchedule().getTimeZone()); File marketDataDir = new File(MARKET_DATA_DIR); if (!marketDataDir.exists()) { marketDataDir.mkdir(); } String fullFileName = MARKET_DATA_DIR + FILE_SEP + strategy.getName() + ".txt"; try { boolean fileExisted = new File(fullFileName).exists(); writer = new PrintWriter(new BufferedWriter(new FileWriter(fullFileName, true))); if (!fileExisted) { StringBuilder header = getHeader( strategy.getInstrument1().getContract().m_symbol, strategy.getInstrument2().getContract().m_symbol); writer.println(header); } } catch (IOException ioe) { throw new JArbitragerException("Could not write to file " + strategy.getName()); } } public void write(long time, Instrument instrument1, Instrument instrument2) { double bid1 = instrument1.getBid(); double ask1 = instrument1.getAsk(); double bid2 = instrument2.getBid(); double ask2 = instrument2.getAsk(); if (bid1 > 0 && ask1 > 0 && bid2 > 0 && ask2 > 0) { StringBuilder sb = new StringBuilder(); sb.append(dateFormat.format(new Date(time))).append(","); sb.append(decimalFormat.format(bid1)).append(","); sb.append(decimalFormat.format(ask1)).append(","); sb.append(decimalFormat.format(bid2)).append(","); sb.append(decimalFormat.format(ask2)); writer.println(sb); writer.flush(); } } public void close() { writer.close(); } private StringBuilder getHeader(String symbol1, String symbol2) { StringBuilder header = new StringBuilder(); String appInfo = JArbitrager.APP_NAME + ", version " + JArbitrager.VERSION; header.append("# This historical data file was created by ").append(appInfo).append(LINE_SEP); header .append("# Each line represents a 1-second snapshot of the market and contains ") .append(BackTestFileReader.COLUMNS) .append(" columns:") .append(LINE_SEP); header.append("# 1. date in the MMddyy format").append(LINE_SEP); header.append("# 2. time in the HHmmss format").append(LINE_SEP); header.append("# 3. best bid for the first instrument").append(LINE_SEP); header.append("# 4. best ask for the first instrument").append(LINE_SEP); header.append("# 5. best bid for the second instrument").append(LINE_SEP); header.append("# 6. best ask for the second instrument").append(LINE_SEP); header.append(LINE_SEP); header.append("instruments=").append(symbol1).append(",").append(symbol2).append(LINE_SEP); header.append("timeZone=").append(dateFormat.getTimeZone().getID()).append(LINE_SEP); return header; } }
public static boolean isJava7() { return System.getProperty("java.version").startsWith("1.7"); }
/** * Try to determine whether this application is running under Windows or some other platform by * examining the "os.name" property. */ static { String os = System.getProperty("os.name"); // String version = System.getProperty("os.version"); // for Win7, reports "6.0" on JDK7, should // be "6.1"; for Win8, reports "6.2" as of JDK7u17 if (SystemUtils.startsWithIgnoreCase(os, "windows 7")) isWin7 = true; // reports "Windows Vista" on JDK7 else if (SystemUtils.startsWithIgnoreCase(os, "windows 8")) isWin7 = true; // reports "Windows 8" as of JDK7u17 else if (SystemUtils.startsWithIgnoreCase(os, "windows vista")) isVista = true; else if (SystemUtils.startsWithIgnoreCase(os, "windows xp")) isWinXP = true; else if (SystemUtils.startsWithIgnoreCase(os, "windows 2000")) isWin2k = true; else if (SystemUtils.startsWithIgnoreCase(os, "windows nt")) isWinNT = true; else if (SystemUtils.startsWithIgnoreCase(os, "windows")) isWin9X = true; // win95 or win98 (what about WinME?) else if (SystemUtils.startsWithIgnoreCase(os, "mac")) isMac = true; else if (SystemUtils.startsWithIgnoreCase(os, "so")) isSolaris = true; // sunos or solaris else if (os.equalsIgnoreCase("linux")) isLinux = true; else isUnix = true; // assume UNIX, e.g. AIX, HP-UX, IRIX String osarch = System.getProperty("os.arch"); String arch = (osarch != null && osarch.contains("64")) ? "_x64" /* eg. 'amd64' */ : "_x32"; String syslib = SYSLIB + arch; try { // loading a native lib in a static initializer ensures that it is available before any // method in this class is called: System.loadLibrary(syslib); System.out.println( "Done loading '" + System.mapLibraryName(syslib) + "', PID=" + getProcessID()); } catch (Error e) { System.err.println( "Native library '" + System.mapLibraryName(syslib) + "' not found in 'java.library.path': " + System.getProperty("java.library.path")); throw e; // re-throw } if (isWinPlatform()) { System.setProperty( "line.separator", "\n"); // so we won't have to mess with DOS line endings ever again comSpec = getEnv( "comSpec"); // use native method here since getEnvironmentVariable() needs to know // comSpec comSpec = (comSpec != null) ? comSpec + " /c " : ""; try (BufferedReader br = new BufferedReader( new InputStreamReader( RUNTIME.exec(comSpec + "ver").getInputStream()))) { // fix for Win7,8 for (String line = null; (line = br.readLine()) != null; ) { if (isVista && (line.contains("6.1" /*Win7*/) || line.contains("6.2" /*Win8*/))) { isVista = false; isWin7 = true; } } } catch (IOException e) { e.printStackTrace(); } String cygdir = getEnv("cygdir"); // this is set during CygWin install to "?:/cygwin/bin" isCygWin = (cygdir != null && !cygdir.equals("%cygdir%")); cygstartPath = cygdir + "/cygstart.exe"; // path to CygWin's cygutils' "cygstart" binary if (getDebug() && Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); for (Desktop.Action action : Desktop.Action.values()) System.out.println( "Desktop action " + action + " supported? " + desktop.isSupported(action)); } } }
String getInfo() { return System.getProperty("java.version"); }