public static String getShowString(String current, String then) { try { Date c = formatter.parse(current); Date t = formatter.parse(then); MDebug.log("|" + (c.getTime() - t.getTime()) + "|"); } catch (Exception ex) { } return "right"; }
void test2() { Locale defaultLocale = Locale.getDefault(); TimeZone reservedTimeZone = TimeZone.getDefault(); Date d = new Date(2005 - 1900, Calendar.DECEMBER, 22); String formatted; TimeZone tz; SimpleDateFormat df; try { for (int i = 0; i < TIMEZONES.length; i++) { tz = TimeZone.getTimeZone(TIMEZONES[i]); TimeZone.setDefault(tz); df = new SimpleDateFormat(pattern, DateFormatSymbols.getInstance(OSAKA)); Locale.setDefault(defaultLocale); System.out.println(formatted = df.format(d)); if (!formatted.equals(DISPLAY_NAMES_OSAKA[i])) { throw new RuntimeException( "TimeZone " + TIMEZONES[i] + ": formatted zone names mismatch. " + formatted + " should match with " + DISPLAY_NAMES_OSAKA[i]); } df.parse(DISPLAY_NAMES_OSAKA[i]); Locale.setDefault(KYOTO); df = new SimpleDateFormat(pattern, DateFormatSymbols.getInstance()); System.out.println(formatted = df.format(d)); if (!formatted.equals(DISPLAY_NAMES_KYOTO[i])) { throw new RuntimeException( "Timezone " + TIMEZONES[i] + ": formatted zone names mismatch. " + formatted + " should match with " + DISPLAY_NAMES_KYOTO[i]); } df.parse(DISPLAY_NAMES_KYOTO[i]); } } catch (ParseException pe) { throw new RuntimeException("parse error occured" + pe); } finally { // restore the reserved locale and time zone Locale.setDefault(defaultLocale); TimeZone.setDefault(reservedTimeZone); } }
public Object objectDone() { Object o = super.objectDone(); BSONObject b = (BSONObject) o; if (!_lastArray) { if (b.containsField("$oid")) { o = new ObjectId((String) b.get("$oid")); if (!isStackEmpty()) { gotObjectId(_lastName, (ObjectId) o); } else { setRoot(o); } } else if (b.containsField("$date")) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT"))); o = format.parse((String) b.get("$date"), new ParsePosition(0)); if (!isStackEmpty()) { cur().put(_lastName, o); } else { setRoot(o); } } else if (b.containsField("$regex")) { o = Pattern.compile((String) b.get("$regex"), BSON.regexFlags((String) b.get("$options"))); if (!isStackEmpty()) { cur().put(_lastName, o); } else { setRoot(o); } } } return o; }
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); }
public void setSelectedItem(Object anItem) { if (anItem == null) { return; } if (anItem instanceof Date) { try { selectedDate = this.dateFormat.format((Date) anItem); } catch (Exception ex) { ex.printStackTrace(); } } else { try { String strDate = anItem.toString().trim(); if (strDate.length() != 10 && strDate.length() != 19) { return; } String pattern = dateFormat.toPattern(); if (strDate.length() == 10 && pattern.length() == 19) { strDate = strDate + selectedDate.substring(10); } dateFormat.parse(strDate); selectedDate = strDate; } catch (Exception ex) { throw new UnsupportedOperationException( "Invalid datetime: string [" + anItem + "], format is [" + dateFormat.toPattern() + "]. "); } } fireContentsChanged(this, -1, -1); }
public static void main(String[] args) throws ParseException { // String dir = // "C:/Users/Joschka/Documents/shared-svn/projects/sustainability-w-michal-and-dlr/data/"; String dir = "d:/svn-vsp/sustainability-w-michal-and-dlr/data/"; // String taxisOverTimeFile = dir + // "taxi_berlin/2014_10_bahnstreik/VEH_IDs_2014-10/oct/oct_taxis.txt"; // String taxisOverTimeFile = dir + "taxi_berlin/2013/status/taxisovertime.csv"; String taxisOverTimeFile = dir + "taxi_berlin/2013/vehicles/taxisweekly.csv"; // String networkFile = dir + "scenarios/2015_02_basic_scenario_v6/berlin_brb.xml"; String networkFile = dir + "network/berlin.xml"; // only Berlin!!! String zoneShpFile = dir + "shp_merged/zones.shp"; String zoneXmlFile = dir + "shp_merged/zones.xml"; // String vehicleFile = dir + "scenarios/2015_02_basic_scenario_v6/taxis4to4_EV"; String vehicleFile = dir + "scenarios/2015_08_only_berlin_v1/taxis4to4_EV"; String statusMatrixFile = dir + "taxi_berlin/2013/status/statusMatrixAvg.xml"; BerlinTaxiVehicleCreatorV3 btv = new BerlinTaxiVehicleCreatorV3(); btv.evShare = 0.0; btv.minTime = 4.0 * 3600; btv.maxTime = 17.0 * 3600; btv.readTaxisOverTime(taxisOverTimeFile); // btv.createAverages(SDF.parse("2014-10-15 03:30:00")); btv.createAverages(SDF.parse("2013-04-16 03:30:00")); btv.prepareNetwork(networkFile, zoneShpFile, zoneXmlFile); btv.prepareMatrices(statusMatrixFile); btv.createVehicles(); btv.writeVehicles(vehicleFile); }
/** * Convert a string to date. * * @param s Given date string * @return Date object */ public static Date toDate(String s) { SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT); try { return df.parse(s); } catch (ParseException e) { return null; } }
public static Date stringToDate(String dateString) { try { MDebug.log("DATE: [|" + dateString + "|]"); return formatter.parse(dateString); } catch (Exception ex) { ex.printStackTrace(); return new Date(); } }
public void setFecha(String val) { try { fecha.setDate(sdf.parse(val)); } catch (Exception e) { omoikane.sistema.Dialogos.lanzarDialogoError( null, "Error en el registro: Fecha inválida", omoikane.sistema.Herramientas.getStackTraceString(e)); } }
public static void main(String[] args) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); List<OperatiuneContabila> operatiuni = new ArrayList<OperatiuneContabila>(); operatiuni.add(new OperatiuneContabila(1, format.parse("01/06/2009"))); operatiuni.add(new OperatiuneContabila(2, format.parse("01/03/2009"))); operatiuni.add(new OperatiuneContabila(3, format.parse("01/02/2009"))); operatiuni.add(new OperatiuneContabila(4, format.parse("01/04/2009"))); Collections.sort(operatiuni, new ComparatorOperatiuniDupaData()); System.out.println("Ordonare operatiuni dupa data :"); for (OperatiuneContabila o : operatiuni) System.out.println(o.getIdOperatiune() + " -- " + format.format(o.getDataContabilizare())); Collections.sort(operatiuni, new ComparatorOperatiuniDupaId()); System.out.println("Ordonare operatiuni dupa id :"); for (OperatiuneContabila o : operatiuni) System.out.println(o.getIdOperatiune() + " -- " + format.format(o.getDataContabilizare())); }
public static boolean isValidDate(String dob) { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date testDate = null; try { testDate = sdf.parse(dob); } catch (ParseException e) { return false; } if (!sdf.format(testDate).equals(dob)) { return false; } return true; }
// converts the XML date format to the SQL TIMESTAMP format // "Dec-03-01 18:38:23" => "0000-00-00 00:00:00" static String convertToSQLTime(String xmlTime) { SimpleDateFormat xmlFormat = new SimpleDateFormat("MMM-dd-yy HH:mm:ss"); SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date inputDate = null; try { inputDate = xmlFormat.parse(xmlTime); } catch (ParseException pe) { System.out.println("ERROR: could not parse \"" + xmlTime + "\""); System.exit(3); } return sqlFormat.format(inputDate); }
public static String getDateTaken(File file) { Directory exifDirectory = getMetaDirectory(file); try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd hh:mm:ss"); // original format if (exifDirectory != null) { String dateStr = exifDirectory.getString(ExifDirectory.TAG_DATETIME_ORIGINAL); Date date = formatter.parse(dateStr); formatter = new SimpleDateFormat("MM/dd/yyyy"); // desired format return formatter.format(date); } return "no date picture taken info"; } catch (ParseException e) { e.printStackTrace(); } return "error occurred while getting the date"; }
protected void load() throws IOException { BufferedReader is = new BufferedReader(new FileReader("ReminderService.txt")); SimpleDateFormat formatter = new SimpleDateFormat("yyyy MM dd hh mm"); String aLine; while ((aLine = is.readLine()) != null) { ParsePosition pp = new ParsePosition(0); Date date = formatter.parse(aLine, pp); if (date == null) { message("Invalid date in " + aLine); continue; } String mesg = aLine.substring(pp.getIndex()); l.add(new Item(date, mesg)); } }
public static void main(String[] args) { Scanner in = new Scanner(System.in); String time = in.next(); // Set format for input and output SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ssa"); SimpleDateFormat out = new SimpleDateFormat("HH:mm:ss"); try { Date inTime = sdf.parse(time); System.out.println(out.format(inTime)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
protected Calendar formatStringAsCalendar(String calendarString) { try { String dateOnly = calendarString.substring(0, 19); String timeZoneStr = calendarString.substring(20, calendarString.length()); TimeZone timeZone = TimeZone.getTimeZone(timeZoneStr); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); simpleDateFormat.setTimeZone(timeZone); Date referenceDate = simpleDateFormat.parse(dateOnly.toUpperCase()); Calendar referenceCalendar = new GregorianCalendar(timeZone); referenceCalendar.setTime(referenceDate); simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); simpleDateFormat.setTimeZone(timeZone); return referenceCalendar; } catch (ParseException p) { throw new TestErrorException("Could not parse Calendar String: " + calendarString); } }
/** Sets the time of the next scheduled raid */ private void setNextRaid(Info info) { String raidTime = info.getMessage().substring(13); raidTime = substituteTimeZone(raidTime); try { SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm z"); Date date = parser.parse(raidTime); TimeZone z = parser.getTimeZone(); GregorianCalendar cal = new GregorianCalendar(z); cal.setTime(date); raids.put(info.getChannel(), cal); saveRaids(); info.sendMessage("Raid time set."); } catch (ParseException e) { info.sendMessage( "Date format was bad. Date format is like \"2008-11-26 21:45 EST\". You entered " + raidTime); } }
/** * Searches for contact ids in history of recent messages. * * @param provider * @param after * @return */ List<String> getRecentContactIDs(String provider, Date after) { List<String> res = new ArrayList<String>(); try { History history = getHistory(); if (history != null) { Iterator<HistoryRecord> recs = history.getReader().findLast(NUMBER_OF_MSGS_IN_HISTORY); SimpleDateFormat sdf = new SimpleDateFormat(HistoryService.DATE_FORMAT); while (recs.hasNext()) { HistoryRecord hr = recs.next(); String contact = null; String recordProvider = null; Date timestamp = null; for (int i = 0; i < hr.getPropertyNames().length; i++) { String propName = hr.getPropertyNames()[i]; if (propName.equals(STRUCTURE_NAMES[0])) recordProvider = hr.getPropertyValues()[i]; else if (propName.equals(STRUCTURE_NAMES[1])) contact = hr.getPropertyValues()[i]; else if (propName.equals(STRUCTURE_NAMES[2])) { try { timestamp = sdf.parse(hr.getPropertyValues()[i]); } catch (ParseException e) { timestamp = new Date(Long.parseLong(hr.getPropertyValues()[i])); } } } if (recordProvider == null || contact == null) continue; if (after != null && timestamp != null && timestamp.before(after)) continue; if (recordProvider.equals(provider)) res.add(contact); } } } catch (IOException ex) { logger.error("cannot create recent_messages history", ex); } return res; }
public static Date to_date(CompiledValue cv1, CompiledValue cv2, ExecutionContext context) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException { Object value1 = cv1.evaluate(context); Object value2 = cv2.evaluate(context); if (!(value1 instanceof String) || !(value2 instanceof String)) { throw new QueryInvalidException( LocalizedStrings .Functions_PARAMETERS_TO_THE_TO_DATE_FUNCTION_SHOULD_BE_STRICTLY_SIMPLE_STRINGS .toLocalizedString()); } String dateStr = (String) value1; String format = (String) value2; Date dt = null; try { // Removed the following line so that to data format conforms to // SimpleDateFormat exactly (bug 39144) // format = ((format.replaceAll("Y", "y")).replaceAll("m", "M")).replaceAll("D", "d"); /*if((format.indexOf("MM") == -1 && format.indexOf("M") == -1) || (format. indexOf("dd") == -1 && format.indexOf("d") == -1) || (format.indexOf("yyyy") == -1 && format.indexOf("yy") == -1)) { throw new QueryInvalidException("Malformed date format string"); } if(format.indexOf("MMM") != -1 || format.indexOf("ddd") != -1 || format.in dexOf("yyyyy") != -1) { throw new QueryInvalidException("Malformed date format string"); } */ SimpleDateFormat sdf1 = new SimpleDateFormat(format); dt = sdf1.parse(dateStr); } catch (Exception ex) { throw new QueryInvalidException( LocalizedStrings.Functions_MALFORMED_DATE_FORMAT_STRING_AS_THE_FORMAT_IS_0 .toLocalizedString(format), ex); } return dt; }
/*========================================================== * public methods *==========================================================*/ public Vector parse(Object entry) throws ParseException { String logEntry = (String) entry; // parsing the log Entry and return segments // Debug.println("LogDataModel: DefaultLogParser: parse() -" +logEntry); int x = logEntry.indexOf("["); if (x == -1) throw new ParseException(logEntry, 0); String temp = logEntry.substring(x + 1); x = temp.indexOf("]"); if (x == -1) throw new ParseException(logEntry, 0); String dateStr = temp.substring(0, x); // Debug.println("LogDataModel: DefaultLogParser: parse() -"+dateStr+" "+temp); SimpleDateFormat format = new SimpleDateFormat(DATE_PATTERN); Date date = format.parse(dateStr); String dateColumn = DateFormat.getDateInstance().format(date); String timeColumn = DateFormat.getTimeInstance().format(date); // Debug.println("LogDataModel: DefaultLogParser: parse() -"+dateColumn+" "+timeColumn); temp = temp.substring(x + 2); x = temp.indexOf("]"); if (x == -1) throw new ParseException(logEntry, 0); String source = temp.substring(1, x); temp = temp.substring(x + 2); x = temp.indexOf("]"); if (x == -1) throw new ParseException(logEntry, 0); String level = temp.substring(1, x); temp = temp.substring(x + 2); Vector row = new Vector(); row.addElement(getSourceString(source)); row.addElement(getLevelString(level)); row.addElement(dateColumn); row.addElement(timeColumn); JLabel detail = new JLabel(temp); detail.setToolTipText(temp); row.addElement(detail); return row; }
public List<UploadLog> uploadInvoice(String fileName) { // upload products to database String line; List<String> dataHolder = pdfExtractorUtility.extractOrder(fileName); // extract data from given fileName int lineNum = 1; List<VendorInventory> inventory = new ArrayList<VendorInventory>(); List<VendorInventory> insertionErrors = new ArrayList<VendorInventory>(); List<UploadLog> errorLogs = new ArrayList<UploadLog>(); VendorOrder vendorOrder; Product product; String[] splitLine; String vendorId; int quantity; double weight = 0; double price; double credit = 0; double deliveryFee = 0; double totalPrice = 0; Date orderDate = null; Date deliveryDate = null; Date currentDate = null; String vendorOrderId = null; String weightString; SimpleDateFormat dateFormat; boolean found = false; boolean firstDate = true; for (int i = 0; i < dataHolder.size(); i++) { // for each row in sheet line = dataHolder.get(i).trim(); // get current row log.debug(line); splitLine = line.split("^" + lineNum + "\\s{4}"); if (splitLine.length > 1) { // this is an item line lineNum++; if (line.contains(" 8338 ")) { // ignore line for Oma's info packet continue; } if (line.contains(" SRVCRG ")) { // add this charge to order charges table splitLine = line.split("^.+?(?=\\d+\\.\\d{2}$)"); deliveryFee = Double.parseDouble(splitLine[1]); continue; } line = splitLine[1]; // set line equal to everything after line number splitLine = line.split("(?<=\\d{2,4}\\w{0,2})\\s+", 2); vendorId = splitLine[0]; // set vendor id to first piece of split line = splitLine[1]; // set line equal to rest of split splitLine = line.split("\\d+\\.\\d{2}\\s+", 2); line = splitLine[1]; // remove quantity ordered splitLine = line.split("(?<=\\d+\\.\\d{2})\\s", 2); quantity = (int) Double.parseDouble(splitLine[0]); // set quantity received to first piece of split line = splitLine[1]; // set line equal to rest of split splitLine = line.split("^.+?(?=\\d+\\.?\\d*\\s+-?\\d+\\.\\d{2})", 2); line = splitLine[1]; // remove bill by label and product name along with trailing spaces splitLine = line.split("\\s+(?=-?\\d+\\.\\d{2}\\s+-?\\d+\\.\\d{2}$)", 2); weightString = splitLine[0]; // number representing either quantity or exact weight if (weightString.contains(".")) { // this is an exact weight weight = Double.parseDouble(weightString); } else { weight = 0; } line = splitLine[1]; splitLine = line.split("(?<=\\d+\\.\\d{2})\\s+", 2); price = Double.parseDouble(splitLine[0]); // set price each if (price < 0) { // this is a credit, add to credits if (weight != 0) { credit = credit + (new BigDecimal(price * weight) .setScale(2, BigDecimal.ROUND_HALF_UP) .doubleValue()); } else { credit = credit + (new BigDecimal(price * quantity) .setScale(2, BigDecimal.ROUND_HALF_UP) .doubleValue()); } continue; } else { // this is a billed item, add to total bill if (weight != 0) { totalPrice = totalPrice + (new BigDecimal(price * weight) .setScale(2, BigDecimal.ROUND_HALF_UP) .doubleValue()); log.debug( "item price so far: " + (new BigDecimal(price * weight).setScale(2, BigDecimal.ROUND_HALF_UP))); } else { totalPrice = totalPrice + (new BigDecimal(price * quantity) .setScale(2, BigDecimal.ROUND_HALF_UP) .doubleValue()); log.debug( "item price so far: " + (new BigDecimal(price * quantity).setScale(2, BigDecimal.ROUND_HALF_UP))); } } log.debug("total price so far: " + totalPrice); product = new Product(); product.setVendorId(vendorId); inventory.add(new VendorInventory(product, quantity, weight, price, false)); } else { if (line.contains("JPEELE") && !found) { // this is line than contains order and delivery dates and order id dateFormat = new SimpleDateFormat("M/d/yy"); found = true; splitLine = line.trim().split("\\s+"); for (String split : splitLine) { log.debug(split); if (split.contains("/")) { try { currentDate = dateFormat.parse(split); } catch (ParseException pe) { log.error("Unable to parse date", pe); } if (firstDate) { firstDate = false; orderDate = currentDate; } else { deliveryDate = currentDate; } } else if (!firstDate) { // this is order id vendorOrderId = split; } } log.debug( "Order Date= " + orderDate + "Delivery Date= " + deliveryDate + "Vendor Order Id= " + vendorOrderId); } } } String logDescription; List<String> headers; List<List<String>> logData; String orderId; log.debug("credit: " + credit); log.debug("total price: " + (totalPrice + deliveryFee + credit)); vendorOrder = new VendorOrder( credit * -1, deliveryFee, totalPrice + deliveryFee + credit, ProductGroup.OMAS, "Received", orderDate, deliveryDate, vendorOrderId); if ((vendorOrder = orderUtility.updateVendorOrder(vendorOrder)) == null) { logDescription = "Unable to upload vendor order information."; headers = Arrays.asList("Credit", "Delivery Fee", "Total Cost", "Status"); logData = new ArrayList<List<String>>(); logData.add( Arrays.asList( String.format("$%.2f", credit), String.format("$%.2f", deliveryFee), String.format("$%.2f", totalPrice), "Received")); errorLogs.add(new UploadLog(logDescription, headers, logData)); } else if (vendorOrder.getId() == null) { logDescription = "You are attempting to upload a duplicate order."; headers = Arrays.asList("Vendor Order Id"); logData = new ArrayList<List<String>>(); logData.add(Arrays.asList(vendorOrderId)); errorLogs.add(new UploadLog(logDescription, headers, logData)); } else { orderId = vendorOrder.getId(); for (VendorInventory vendorInventory : inventory) { if (productUtility.updateVendorInventoryItems( Arrays.asList(vendorInventory), Integer.parseInt(orderId), null, VendorOrder.STATUS.get("Received")) == null) { insertionErrors.add(vendorInventory); } } if (insertionErrors.size() > 0) { logDescription = "Vendor order items that were not uploaded properly."; headers = Arrays.asList("Vendor Id", "Quantity", "Weight", "Cost"); logData = new ArrayList<List<String>>(); for (VendorInventory vendorInventory : insertionErrors) { logData.add( Arrays.asList( vendorInventory.getProduct().getVendorId(), Double.toString(vendorInventory.getQuantity()), vendorInventory.getCostFormatted())); } errorLogs.add(new UploadLog(logDescription, headers, logData)); } log.debug(credit + ", " + deliveryFee); } return errorLogs; // this should be report of orphaned products/inventory }
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 Date parseDate(String dateStr) { ParsePosition pp = new ParsePosition(0); return dateFormat.parse(dateStr, pp); }
public List getIterationList(String projectId) { List<Map> list = new ArrayList<Map>(); try { String apiUrl = rallyApiHost + "/iteration?" + "project=" + rallyApiHost + "/project/" + projectId + "&fetch=true&order=Name%20desc&start=1&pagesize=100"; String checkProjectRef = rallyApiHost + "/project/" + projectId; log.info("rallyApiUrl:" + apiUrl); log.info("checkProjectRef:" + checkProjectRef); String responseXML = getRallyXML(apiUrl); SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); Date currentDate = new Date(); org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder(); org.jdom.Document doc = bSAX.build(new StringReader(responseXML)); Element root = doc.getRootElement(); XPath xpath = XPath.newInstance("//Object"); List xlist = xpath.selectNodes(root); Iterator iter = xlist.iterator(); while (iter.hasNext()) { Map map = new HashMap(); Element item = (Element) iter.next(); String objId = item.getChildText("ObjectID"); String name = item.getChildText("Name"); String state = item.getChildText("State"); String startDateStr = item.getChildText("StartDate"); String endDateStr = item.getChildText("EndDate"); Date startDate = ISO8601FORMAT.parse(startDateStr); Date endDate = ISO8601FORMAT.parse(endDateStr); boolean isCurrent = false; int startCheck = startDate.compareTo(currentDate); int endCheck = endDate.compareTo(currentDate); if (startCheck < 0 && endCheck > 0) { isCurrent = true; } log.info("name=" + name + " isCurrent=" + isCurrent); String releaseRef = item.getAttribute("ref").getValue(); // In child project, parent object have to be filiered Element projectElement = item.getChild("Project"); String projectRef = projectElement.getAttributeValue("ref"); if (projectRef.equals(checkProjectRef)) { map.put("objId", objId); map.put("rallyRef", releaseRef); map.put("name", name); map.put("state", state); map.put("isCurrent", "" + isCurrent); list.add(map); } } log.info("-----------"); } catch (Exception ex) { log.error("ERROR: ", ex); } return list; }
public void parse(Path file) throws IOException { clear(); try (BufferedReader inp = Files.newBufferedReader(file)) { String line; while ((line = inp.readLine()) != null) { if (line.startsWith("Cpu ")) { PerfKey key = new PerfKey(); PerfData data = new PerfData(); // Cpu 0 NSE-AB Init Lock Pgs 19 Mem Pages 4194304 key.cpu = Integer.parseInt(line.substring(4, 6).trim()); data.memPages = Integer.parseInt(line.substring(62).trim()); line = inp.readLine(); // Memory MB 65536 PCBs 12100 Pg Size 16384 Bytes if (line == null || !line.startsWith("Memory MB")) { throw new IOException("Строка должна начинаться с 'Memory MB': " + line); } line = inp.readLine(); // IPUs 4 if (line == null || !line.startsWith("IPUs")) { throw new IOException("Строка должна начинаться с 'IPUs': " + line); } line = inp.readLine(); // Format Version: H07 Data Version: H07 Subsystem Version: 3 if (line == null || !line.startsWith("Format Version:")) { throw new IOException("Строка должна начинаться с 'Format Version:': " + line); } line = inp.readLine(); // Local System \KHAFE1 From 1 Oct 2016, 0:00:01 For 5.1 Minutes if (line == null || !line.startsWith("Local System")) { throw new IOException("Строка должна начинаться с 'Local System:': " + line); } key.system = line.substring(13, 21).trim(); String str = line.substring(28, 49); try { key.date = DATETIME_SDF.parse(str); data.duration = parseDuration(line.substring(56).trim()); } catch (ParseException e) { throw new IOException( "Ошибка декодирования строки (Позиция. " + e.getErrorOffset() + "): " + str + ". Строка:" + line, e); } catch (NumberFormatException e) { throw new IOException("Ошибка декодирования строки : " + str + ". Строка:" + line, e); } line = inp.readLine(); // ---------------------------------------------------------------------------- if (line == null || !line.startsWith("---------")) { throw new IOException("Строка должна начинаться с '---------:': " + line); } line = inp.readLine(); // Cpu-Busy-Time 79.99 % Dispatches 115,637 /s if (line == null || !line.startsWith("Cpu-Busy-Time")) { throw new IOException("Строка должна начинаться с 'Cpu-Busy-Time': " + line); } str = line.substring(25, 33).trim(); try { data.cpuBusyTime = DF.parse(str).floatValue(); } catch (ParseException e) { throw new IOException("Ошибка декодирования Cpu-Busy-Time: " + str, e); } line = inp.readLine(); // Cpu-Qtime 13.89 AQL Intr-Busy-Time 14.41 % if (line == null || !line.startsWith("Cpu-Qtime")) { throw new IOException("Строка должна начинаться с 'Cpu-Qtime': " + line); } line = inp.readLine(); // Starting-Free-Mem 3,267,922 # Ending-Free-Mem 3,267,951 # if (line == null || !line.startsWith("Starting-Free-Mem")) { throw new IOException("Строка должна начинаться с 'Starting-Free-Mem': " + line); } str = line.substring(55, 73).trim(); try { data.endingFreeMem = DF.parse(str).intValue(); } catch (ParseException e) { throw new IOException("Ошибка декодирования Ending-Free-Mem: " + str, e); } line = inp.readLine(); // Swaps 1.10 /s Page-Requests 2.19 /s if (line == null || !line.startsWith("Swaps")) { throw new IOException("Строка должна начинаться с 'Swaps': " + line); } line = inp.readLine(); // Disc-IOs 49.79 /s Cache-Hits 946.87 /s if (line == null || !line.startsWith("Disc-IOs")) { throw new IOException("Строка должна начинаться с 'Disc-IOs': " + line); } this.stat.addPerfData(key, data); } } } }
/** Creates new form frmAsignarTransporte */ public frmAsignarTransporte() { initComponents(); gestorH.actualizarUsuario(labelusuario); txtFecha.setEditable(false); txtFecha.setEnabled(false); txtHora.setEditable(false); txtHora.setEnabled(false); // setear el campo de fecha con la del sistema GregorianCalendar gc = new GregorianCalendar(); GregorianCalendar.getInstance(); gc.setTimeZone(TimeZone.getTimeZone("GMT-3")); gc.get(Calendar.DAY_OF_WEEK); gc.get(Calendar.MONTH); gc.get(Calendar.YEAR); SimpleDateFormat formateador = new SimpleDateFormat("dd-MM-yyyy"); txtFecha.setText(formateador.format(gc.getTime())); // setear el campo de hora con la del sistema GregorianCalendar calendario = new GregorianCalendar(); GregorianCalendar.getInstance(); gc.setTimeZone(TimeZone.getTimeZone("GMT-3")); calendario.get(Calendar.HOUR); calendario.get(Calendar.MINUTE); SimpleDateFormat formateadorHora = new SimpleDateFormat("HH:mm"); txtHora.setText(formateadorHora.format(calendario.getTime())); // Las siguientes lineas son para dar a la pantalla el tamaño requerido y luego centrarla en la // pantalla. Toolkit kit = Toolkit.getDefaultToolkit(); Dimension tamanioPantalla = kit.getScreenSize(); int ancho = 820; int alto = 570; // int posX = (int) ((tamanioPantalla.width - ancho) / 2); // int posY = (int) ((tamanioPantalla.height - alto) / 2); this.setSize(ancho, alto); this.setLocation(260, 30); // redimensionar columnas tabla tblViaje.getColumnModel().getColumn(0).setPreferredWidth(50); tblViaje.getColumnModel().getColumn(1).setPreferredWidth(50); tblViaje.getColumnModel().getColumn(2).setPreferredWidth(100); tblVehiculo.getColumnModel().getColumn(0).setPreferredWidth(100); tblVehiculo.getColumnModel().getColumn(1).setPreferredWidth(100); // centrar cabecera jtable DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) tblVehiculo.getTableHeader().getDefaultRenderer(); renderer.setHorizontalAlignment(0); DefaultTableCellRenderer renderer2 = (DefaultTableCellRenderer) tblViaje.getTableHeader().getDefaultRenderer(); renderer2.setHorizontalAlignment(0); Iterator ite = gestorH.listarClase(Viaje.class).iterator(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy"); SimpleDateFormat sdfguion = new SimpleDateFormat("dd-MM-yyyy"); while (ite.hasNext()) { Viaje viaje = (Viaje) ite.next(); Date fecha1 = sdf.parse(viaje.getFecha(), new ParsePosition(0)); Date fecha3 = sdfguion.parse(txtFecha.getText(), new ParsePosition(0)); if (viaje.getEstado().equalsIgnoreCase("En Proceso") && (viaje.getTipoViaje().getNombreTipoViaje().equalsIgnoreCase("Traslado a Puerto") || viaje .getTipoViaje() .getNombreTipoViaje() .equalsIgnoreCase("Traslado a Establecimiento"))) { if (fecha1.before(fecha3)) { viaje.setEstado("Finalizado"); viaje.getVehiculo().setEstado("Disponible"); } } } gestorA.RellenarTablaViajes(tblViaje); }