Trying to use Date(int, int, int) constructor - java

I am trying to use the Date(int, int, int) constructor (per instructor requirements) and I am coming into some difficulty.
Initially I'm getting warnings because apparently this constructor is deprecated and additionally I am getting errors due to my usage of code.
I'll attach my code below. I tried using fileRead.nextInt() for the file Scanner and I also tried the method you see below with Integer.parseInt(fileRead.next()).
This is reading from a file that has text in the format:
firstName lastName, 4, 24, 2016, aStringOfTextPossiblyMultipleWords...
Where 4 is month, 24 is day, 2016 is year.
The errors I'm getting are...
Exception in thread "main" java.lang.NumberFormatException: For input string: " 4"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at BlogEntryTester.main(BlogEntryTester.java:59)
/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 6 seconds)
And here is the code. The error is during runtime near the end of the code.
import java.util.Date;
import java.util.Scanner;
import java.io.*;
public class BlogEntryTester {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
Date newDate = new Date();
BlogEntry BE1 = new BlogEntry();
BlogEntry BE2 = new BlogEntry("firstName", newDate, "This is the body of "
+ "blog entry number two. This is the last sentence.");
BlogEntry BE3 = new BlogEntry(BE2);
BE1.setUsername("randFirstName");
BE1.setDateOfBlog(newDate);
BE1.setBlog("This is less than 10 words...");
System.out.println(BE1.toString());
System.out.println(BE2.toString());
System.out.println(BE3.toString());
Scanner keyboard = new Scanner(System.in);
Scanner fileRead = null;
String fileName;
System.out.print("Enter the name of the file you wish to read from: ");
fileName = keyboard.next();
try{
fileRead = new Scanner(new FileInputStream(fileName));
System.out.println("> File opened successfully.");
fileRead.useDelimiter(",|\\n");
}
catch(FileNotFoundException e){
System.out.println("> File not found.");
System.exit(0);
}
BlogEntry newBlog = new BlogEntry();
newBlog.setUsername(fileRead.next()); // Reads username from file.
if(newBlog.getUsername().length() > 20){
System.out.println("> Error: Username read from file exceeds 20 "
+ "characters.");
}
newBlog.setDateOfBlog(new Date(Integer.parseInt(fileRead.next()),
Integer.parseInt(fileRead.next()),
Integer.parseInt(fileRead.next())));
newBlog.setBlog(fileRead.next()); // Reads the text of the blog.
System.out.println(newBlog.toString()); // Prints the data gathered from file.
}
}

Trim whitespace
As comments said, you must trim the SPACE character appearing in front of your digit 4. You could call replace( " " , "" ) on the String. Or use the Google Guava library for clearing whitespace.
sql vs util
Be aware of the java.sql.Date class which is intended to represent a date-only value. In contrast the java.util.Date class you are using represents a date plus a time-of-day.
For a date-only value, the sql.Date class is more appropriate if you cannot use java.time framework described next. But also know that class is a bad hack, extending from util.Date while instructing you to ignore that fact of inheritance and to ignore its embedded time-of-day that is adjusted to 00:00:00 UTC. Confusing? Yes. These old date-time classes are a bloody mess.
java.time
You said your instructor is requiring the Date class, but you should know that class is notoriously troublesome and not recommended.
You are using an old outmoded class, java.util.Date, that has been supplanted by the java.time framework built into Java 8 and later.
Instead use LocalDate for a date-only value with no time-of-day and no time zone.
LocalDate localDate = LocalDate.of( 2016 , 4 , 24 );

Related

How do I set the date to the current day in Korea or anywhere else?

So, I got the time to be in Korean time with this code:
formatClock = new SimpleDateFormat("hh:mm:ss a");
formatClock.setTimeZone(TimeZone.getTimeZone("Asia/Seoul"));
However, how do I set the date to the current day in Korean?
For instance, I want it to output Sunday 7/23/2017.
Old API
Use another SimpleDateFormat with the desired format, and use java.util.Locale to explicity uses the English names for days of the week:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE M/dd/yyyy", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Seoul"));
System.out.println(sdf.format(new Date()));
The output will be:
Sunday 7/23/2017
If you don't specify the locale, it uses the system's default, which is not guaranteed to always be English (and it can also be changed without notice, even at runtime, so it's always better to make it explicit in your code by using a proper Locale, if you always want the days of the week in English - or in any other language).
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
To get the current date in a timezone, you can use a LocalDate (a date with day/month/year) with a ZoneId (a timezone), and you use a DateTimeFormatter to format it:
// Korean timezone
ZoneId zone = ZoneId.of("Asia/Seoul");
// current date in Korea timezone
LocalDate currentDateInKorea = LocalDate.now(zone);
// formatter (use English locale to correctly use English name for day of week)
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEEE M/dd/yyyy", Locale.ENGLISH);
System.out.println(fmt.format(currentDateInKorea));
The output will be:
Sunday 7/23/2017
Note: a java.util.Date itself has no format, it just represents the number of milliseconds since epoch (1970-01-01T00:00Z). What we're doing here is just changing the representation of this value in a specific format, for a specific timezone.
suppose you should try like this.
This should display 'Sun 7/23/2017':
new SimpleDateFormat("EEE dd/MM/yyyy").format(new Date());
This should display 'Sunday 7/23/2017':
new SimpleDateFormat("EEEE dd/MM/yyyy").format(new Date());
If you want leading zero in month then use MM else use M.
NOTE: View all valid time zones by TimeZone.getAvailableIDs()
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.TimeZone;
public class Time {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
// Day month/date/year
SimpleDateFormat formatClock = new SimpleDateFormat("EEEE MM/dd/yyyy");
formatClock.setTimeZone(TimeZone.getTimeZone("Asia/Seoul"));
System.out.println(formatClock.format(new Date()));
System.out.println();
// FYI You can check Available TimeZones as follows
System.out.println(Arrays.toString(TimeZone.getAvailableIDs()));
}
}
Sample Run
Sunday 07/23/2017
[Etc/GMT+12, Etc/GMT+11, Pacific/Midway, Pacific/Niue, Pacific/Pago_Pago, Pacific/Samoa, US/Samoa, America/Adak, America/Atka, Etc/GMT+10, HST, Pacific/Honolulu, Pacific/Johnston, Pacific/Rarotonga, Pacific/Tahiti, SystemV/HST10, US/Aleutian, US/Hawaii, Pacific/Marquesas, AST, America/Anchorage, America/Juneau, America/Nome, America/Sitka, America/Yakutat, Etc/GMT+9, Pacific/Gambier, SystemV/YST9, SystemV/YST9YDT, US/Alaska, America/Dawson, America/Ensenada, America/Los_Angeles, America/Metlakatla, America/Santa_Isabel, America/Tijuana, America/Vancouver, America/Whitehorse, Canada/Pacific, Canada/Yukon, Etc/GMT+8, Mexico/BajaNorte, PST, PST8PDT, Pacific/Pitcairn, SystemV/PST8, SystemV/PST8PDT, US/Pacific, US/Pacific-New, America/Boise, America/Cambridge_Bay, America/Chihuahua, America/Creston, America/Dawson_Creek, America/Denver, America/Edmonton, America/Hermosillo, America/Inuvik, America/Mazatlan, America/Ojinaga, America/Phoenix, America/Shiprock, America/Yellowknife, Canada/Mountain, Etc/GMT+7, MST, MST7MDT, Mexico/BajaSur, Navajo, PNT, SystemV/MST7, SystemV/MST7MDT, US/Arizona, US/Mountain, America/Bahia_Banderas, America/Belize, America/Cancun, America/Chicago, America/Costa_Rica, America/El_Salvador, America/Guatemala, America/Indiana/Knox, America/Indiana/Tell_City, America/Knox_IN, America/Managua, America/Matamoros, America/Menominee, America/Merida, America/Mexico_City, America/Monterrey, America/North_Dakota/Beulah, America/North_Dakota/Center, America/North_Dakota/New_Salem, America/Rainy_River, America/Rankin_Inlet, America/Regina, America/Resolute, America/Swift_Current, America/Tegucigalpa, America/Winnipeg, CST, CST6CDT, Canada/Central, Canada/East-Saskatchewan, Canada/Saskatchewan, Chile/EasterIsland, Etc/GMT+6, Mexico/General, Pacific/Easter, Pacific/Galapagos, SystemV/CST6, SystemV/CST6CDT, US/Central, US/Indiana-Starke, America/Atikokan, America/Bogota, America/Cayman, America/Coral_Harbour, America/Detroit, America/Fort_Wayne, America/Grand_Turk, America/Guayaquil, America/Havana, America/Indiana/Indianapolis, America/Indiana/Marengo, America/Indiana/Petersburg, America/Indiana/Vevay, America/Indiana/Vincennes, America/Indiana/Winamac, America/Indianapolis, America/Iqaluit, America/Jamaica, America/Kentucky/Louisville, America/Kentucky/Monticello, America/Lima, America/Louisville, America/Montreal, America/Nassau, America/New_York, America/Nipigon, America/Panama, America/Pangnirtung, America/Port-au-Prince, America/Thunder_Bay, America/Toronto, Canada/Eastern, Cuba, EST, EST5EDT, Etc/GMT+5, IET, Jamaica, SystemV/EST5, SystemV/EST5EDT, US/East-Indiana, US/Eastern, US/Michigan, America/Caracas, America/Anguilla, America/Antigua, America/Argentina/San_Luis, America/Aruba, America/Asuncion, America/Barbados, America/Blanc-Sablon, America/Boa_Vista, America/Campo_Grande, America/Cuiaba, America/Curacao, America/Dominica, America/Eirunepe, America/Glace_Bay, America/Goose_Bay, America/Grenada, America/Guadeloupe, America/Guyana, America/Halifax, America/Kralendijk, America/La_Paz, America/Lower_Princes, America/Manaus, America/Marigot, America/Martinique, America/Moncton, America/Montserrat, America/Port_of_Spain, America/Porto_Acre, America/Porto_Velho, America/Puerto_Rico, America/Rio_Branco, America/Santiago, America/Santo_Domingo, America/St_Barthelemy, America/St_Kitts, America/St_Lucia, America/St_Thomas, America/St_Vincent, America/Thule, America/Tortola, America/Virgin, Antarctica/Palmer, Atlantic/Bermuda, Brazil/Acre, Brazil/West, Canada/Atlantic, Chile/Continental, Etc/GMT+4, PRT, SystemV/AST4, SystemV/AST4ADT, America/St_Johns, CNT, Canada/Newfoundland, AGT, America/Araguaina, America/Argentina/Buenos_Aires, America/Argentina/Catamarca, America/Argentina/ComodRivadavia, America/Argentina/Cordoba, America/Argentina/Jujuy, America/Argentina/La_Rioja, America/Argentina/Mendoza, America/Argentina/Rio_Gallegos, America/Argentina/Salta, America/Argentina/San_Juan, America/Argentina/Tucuman, America/Argentina/Ushuaia, America/Bahia, America/Belem, America/Buenos_Aires, America/Catamarca, America/Cayenne, America/Cordoba, America/Fortaleza, America/Godthab, America/Jujuy, America/Maceio, America/Mendoza, America/Miquelon, America/Montevideo, America/Paramaribo, America/Recife, America/Rosario, America/Santarem, America/Sao_Paulo, Antarctica/Rothera, Atlantic/Stanley, BET, Brazil/East, Etc/GMT+3, America/Noronha, Atlantic/South_Georgia, Brazil/DeNoronha, Etc/GMT+2, America/Scoresbysund, Atlantic/Azores, Atlantic/Cape_Verde, Etc/GMT+1, Africa/Abidjan, Africa/Accra, Africa/Bamako, Africa/Banjul, Africa/Bissau, Africa/Casablanca, Africa/Conakry, Africa/Dakar, Africa/El_Aaiun, Africa/Freetown, Africa/Lome, Africa/Monrovia, Africa/Nouakchott, Africa/Ouagadougou, Africa/Sao_Tome, Africa/Timbuktu, America/Danmarkshavn, Atlantic/Canary, Atlantic/Faeroe, Atlantic/Faroe, Atlantic/Madeira, Atlantic/Reykjavik, Atlantic/St_Helena, Eire, Etc/GMT, Etc/GMT+0, Etc/GMT-0, Etc/GMT0, Etc/Greenwich, Etc/UCT, Etc/UTC, Etc/Universal, Etc/Zulu, Europe/Belfast, Europe/Dublin, Europe/Guernsey, Europe/Isle_of_Man, Europe/Jersey, Europe/Lisbon, Europe/London, GB, GB-Eire, GMT, GMT0, Greenwich, Iceland, Portugal, UCT, UTC, Universal, WET, Zulu, Africa/Algiers, Africa/Bangui, Africa/Brazzaville, Africa/Ceuta, Africa/Douala, Africa/Kinshasa, Africa/Lagos, Africa/Libreville, Africa/Luanda, Africa/Malabo, Africa/Ndjamena, Africa/Niamey, Africa/Porto-Novo, Africa/Tripoli, Africa/Tunis, Africa/Windhoek, Arctic/Longyearbyen, Atlantic/Jan_Mayen, CET, ECT, Etc/GMT-1, Europe/Amsterdam, Europe/Andorra, Europe/Belgrade, Europe/Berlin, Europe/Bratislava, Europe/Brussels, Europe/Budapest, Europe/Busingen, Europe/Copenhagen, Europe/Gibraltar, Europe/Ljubljana, Europe/Luxembourg, Europe/Madrid, Europe/Malta, Europe/Monaco, Europe/Oslo, Europe/Paris, Europe/Podgorica, Europe/Prague, Europe/Rome, Europe/San_Marino, Europe/Sarajevo, Europe/Skopje, Europe/Stockholm, Europe/Tirane, Europe/Vaduz, Europe/Vatican, Europe/Vienna, Europe/Warsaw, Europe/Zagreb, Europe/Zurich, Libya, MET, Poland, ART, Africa/Blantyre, Africa/Bujumbura, Africa/Cairo, Africa/Gaborone, Africa/Harare, Africa/Johannesburg, Africa/Kigali, Africa/Lubumbashi, Africa/Lusaka, Africa/Maputo, Africa/Maseru, Africa/Mbabane, Asia/Amman, Asia/Beirut, Asia/Damascus, Asia/Gaza, Asia/Hebron, Asia/Istanbul, Asia/Jerusalem, Asia/Nicosia, Asia/Tel_Aviv, CAT, EET, Egypt, Etc/GMT-2, Europe/Athens, Europe/Bucharest, Europe/Chisinau, Europe/Helsinki, Europe/Istanbul, Europe/Kiev, Europe/Mariehamn, Europe/Nicosia, Europe/Riga, Europe/Simferopol, Europe/Sofia, Europe/Tallinn, Europe/Tiraspol, Europe/Uzhgorod, Europe/Vilnius, Europe/Zaporozhye, Israel, Turkey, Africa/Addis_Ababa, Africa/Asmara, Africa/Asmera, Africa/Dar_es_Salaam, Africa/Djibouti, Africa/Juba, Africa/Kampala, Africa/Khartoum, Africa/Mogadishu, Africa/Nairobi, Antarctica/Syowa, Asia/Aden, Asia/Baghdad, Asia/Bahrain, Asia/Kuwait, Asia/Qatar, Asia/Riyadh, EAT, Etc/GMT-3, Europe/Kaliningrad, Europe/Minsk, Indian/Antananarivo, Indian/Comoro, Indian/Mayotte, Asia/Riyadh87, Asia/Riyadh88, Asia/Riyadh89, Mideast/Riyadh87, Mideast/Riyadh88, Mideast/Riyadh89, Asia/Tehran, Iran, Asia/Baku, Asia/Dubai, Asia/Muscat, Asia/Tbilisi, Asia/Yerevan, Etc/GMT-4, Europe/Moscow, Europe/Samara, Europe/Volgograd, Indian/Mahe, Indian/Mauritius, Indian/Reunion, NET, W-SU, Asia/Kabul, Antarctica/Mawson, Asia/Aqtau, Asia/Aqtobe, Asia/Ashgabat, Asia/Ashkhabad, Asia/Dushanbe, Asia/Karachi, Asia/Oral, Asia/Samarkand, Asia/Tashkent, Etc/GMT-5, Indian/Kerguelen, Indian/Maldives, PLT, Asia/Calcutta, Asia/Colombo, Asia/Kolkata, IST, Asia/Kathmandu, Asia/Katmandu, Antarctica/Vostok, Asia/Almaty, Asia/Bishkek, Asia/Dacca, Asia/Dhaka, Asia/Qyzylorda, Asia/Thimbu, Asia/Thimphu, Asia/Yekaterinburg, BST, Etc/GMT-6, Indian/Chagos, Asia/Rangoon, Indian/Cocos, Antarctica/Davis, Asia/Bangkok, Asia/Ho_Chi_Minh, Asia/Hovd, Asia/Jakarta, Asia/Novokuznetsk, Asia/Novosibirsk, Asia/Omsk, Asia/Phnom_Penh, Asia/Pontianak, Asia/Saigon, Asia/Vientiane, Etc/GMT-7, Indian/Christmas, VST, Antarctica/Casey, Asia/Brunei, Asia/Choibalsan, Asia/Chongqing, Asia/Chungking, Asia/Harbin, Asia/Hong_Kong, Asia/Kashgar, Asia/Krasnoyarsk, Asia/Kuala_Lumpur, Asia/Kuching, Asia/Macao, Asia/Macau, Asia/Makassar, Asia/Manila, Asia/Shanghai, Asia/Singapore, Asia/Taipei, Asia/Ujung_Pandang, Asia/Ulaanbaatar, Asia/Ulan_Bator, Asia/Urumqi, Australia/Perth, Australia/West, CTT, Etc/GMT-8, Hongkong, PRC, Singapore, Australia/Eucla, Asia/Dili, Asia/Irkutsk, Asia/Jayapura, Asia/Pyongyang, Asia/Seoul, Asia/Tokyo, Etc/GMT-9, JST, Japan, Pacific/Palau, ROK, ACT, Australia/Adelaide, Australia/Broken_Hill, Australia/Darwin, Australia/North, Australia/South, Australia/Yancowinna, AET, Antarctica/DumontDUrville, Asia/Khandyga, Asia/Yakutsk, Australia/ACT, Australia/Brisbane, Australia/Canberra, Australia/Currie, Australia/Hobart, Australia/Lindeman, Australia/Melbourne, Australia/NSW, Australia/Queensland, Australia/Sydney, Australia/Tasmania, Australia/Victoria, Etc/GMT-10, Pacific/Chuuk, Pacific/Guam, Pacific/Port_Moresby, Pacific/Saipan, Pacific/Truk, Pacific/Yap, Australia/LHI, Australia/Lord_Howe, Antarctica/Macquarie, Asia/Sakhalin, Asia/Ust-Nera, Asia/Vladivostok, Etc/GMT-11, Pacific/Efate, Pacific/Guadalcanal, Pacific/Kosrae, Pacific/Noumea, Pacific/Pohnpei, Pacific/Ponape, SST, Pacific/Norfolk, Antarctica/McMurdo, Antarctica/South_Pole, Asia/Anadyr, Asia/Kamchatka, Asia/Magadan, Etc/GMT-12, Kwajalein, NST, NZ, Pacific/Auckland, Pacific/Fiji, Pacific/Funafuti, Pacific/Kwajalein, Pacific/Majuro, Pacific/Nauru, Pacific/Tarawa, Pacific/Wake, Pacific/Wallis, NZ-CHAT, Pacific/Chatham, Etc/GMT-13, MIT, Pacific/Apia, Pacific/Enderbury, Pacific/Fakaofo, Pacific/Tongatapu, Etc/GMT-14, Pacific/Kiritimati]
Below is the code to do it
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
SimpleDateFormat format = new SimpleDateFormat("E, dd/MM/yyyy");
// DateToStr = format.format(new Date());
System.out.println(format.format(new Date()));
}
}
Link for different formats https://examples.javacodegeeks.com/core-java/text/java-simpledateformat-example/

Conversion from "datetime-local" to java.sql.Timestamp

I have a form with input of type "datetime-local" on a jsp page, the data is passed to a servlet:
String resetTimeString = request.getParameter(RequestParameterName.RESET_TIME);
How to convert the input to java.sql.Timestamp?
EDIT:
Well, I found something new!
You can use Timestamp.valueOf() to format a time-string with the value of yyyy-[m]m-[d]d hh:mm:ss[.f...]
So it can also handle micro/nano seconds. The only thing you need to do is replace the T with a space.
This works:
String datetimeLocal = "1985-04-12T23:20:50.52";
System.out.println(Timestamp.valueOf(datetimeLocal.replace("T"," ")));
The output:
1985-04-12 23:20:50.52
According to this site your resetTimeString looks like this: '1985-04-12T23:20:50.52' (a string)
I couldn't find a method to convert this to a timestamp directly, but you could just split it up manually:
String[] dateTime = datetimeLocal.split("T");
String[] date = dateTime[0].split("-");
String[] time = dateTime[1].split(":");
This will print:
System.out.println("DateTime: " + Arrays.toString(dateTime));
System.out.println("Date: " + Arrays.toString(date));
System.out.println("Time: " + Arrays.toString(time));
>>> DateTime: [1985-04-12, 23:20:50]
>>> Date: [1985, 04, 12]
>>> Time: [23, 20, 50]
After that you could just create a new Timestamp: (This is deprecated!)
Timestamp stamp = new Timestamp(Integer.valueOf(date[0]).intValue() - 1900,
Integer.valueOf(date[1]).intValue(),
Integer.valueOf(date[2]).intValue(),
Integer.valueOf(time[0]).intValue(),
Integer.valueOf(time[1]).intValue(),
Integer.valueOf(time[2].split("\\.")[0]).intValue(),
Integer.valueOf(time[2].split("\\.")[1]).intValue());
Note that, if you use this you need to subtract '1900' from the year and split dots with \\.
Also, you'd need to handle nanoseconds (In my example I'm using the value 50.52 as seconds, but the string returned from your server might not contain the nanoseconds)
You could also calculate a long from the date and use new Timestamp(<long>)
I hope this helps :)
Cyphrags' answer won't work if seconds are set to "00", because Chrome won't send the seconds part resulting in a java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff] when calling Timestamp.valueOf().
Therefore a more complete answer could be:
String datetimeLocal = "1985-04-12T23:20";
// make sure the seconds are set before parsing
if (StringUtils.countMatches(datetimelocal, ":") == 1) {
datetimelocal += ":00";
}
Timestamp value = Timestamp.valueOf(datetimeLocal.replace("T", " "));

Pig - Unhandled internal error NoClassDefFoundException

I had a specific filtering problem (described here: Pig - How to manipulate and compare dates?), so as we told me, I decided to write my own filtering UDF. Here is the code:
import java.io.IOException;
import org.apache.pig.FilterFunc;
import org.apache.pig.data.Tuple;
import org.joda.time.*;
import org.joda.time.format.*;
public class DateCloseEnough extends FilterFunc {
int nbmois;
/*
* #param nbMois: if the number of months between two dates is inferior to this variable, then we consider that these two dates are close
*/
public DateCloseEnough(String nbmois_) {
nbmois = Integer.valueOf(nbmois_);
}
public Boolean exec(Tuple input) throws IOException {
// We're getting the date
String date1 = (String)input.get(0);
// We convert it into date
final DateTimeFormatter dtf = DateTimeFormat.forPattern("MM yyyy");
LocalDate d1 = new LocalDate();
d1 = LocalDate.parse(date1, dtf);
d1 = d1.withDayOfMonth(1);
// We're getting today's date
DateTime today = new DateTime();
int mois = today.getMonthOfYear();
String real_mois;
if(mois >= 1 && mois <= 9) real_mois = "0" + mois;
else real_mois = "" + mois;
LocalDate d2 = new LocalDate();
d2 = LocalDate.parse(real_mois + " " + today.getYear(), dtf);
d2 = d2.withDayOfMonth(1);
// Number of months between these two dates
String nb_months_between = "" + Months.monthsBetween(d1,d2);
return (Integer.parseInt(nb_months_between) <= nbmois);
}
}
I created a Jar file of this code from Eclipse.
I'm filtering my data with these lines of piglatin code:
REGISTER Desktop/myUDFs.jar
DEFINE DateCloseEnough DateCloseEnough('12');
experiences1 = LOAD '/home/training/Desktop/BDD/experience.txt' USING PigStorage(',') AS (id_cv:int, id_experience:int, date_deb:chararray, date_fin:chararray, duree:int, contenu_experience:chararray);
experiences = FILTER experiences1 BY DateCloseEnough(date_fin);
I'm launching my program with this linux command:
pig -x local "myScript.pig"
And I get this error:
2013-06-19 07:27:17,253 [main] INFO org.apache.pig.Main - Logging error messages to: /home/training/pig_1371652037252.log
2013-06-19 07:27:17,933 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 2998: Unhandled internal error. org/joda/time/ReadablePartial Details at logfile: /home/training/pig_1371652037252.log
I checked into the log file and I saw this:
Pig Stack Trace
ERROR 2998: Unhandled internal error. org/joda/time/ReadablePartial
java.lang.NoClassDefFoundError: org/joda/time/ReadablePartial
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at org.apache.pig.impl.PigContext.resolveClassName(PigContext.java:441)
at org.apache.pig.impl.PigContext.instantiateFuncFromSpec(PigContext.java:471)
at org.apache.pig.impl.PigContext.instantiateFuncFromAlias(PigContext.java:544)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.EvalFuncSpec(QueryParser.java:4834)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.PUnaryCond(QueryParser.java:1949)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.PAndCond(QueryParser.java:1790)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.POrCond(QueryParser.java:1734)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.PCond(QueryParser.java:1700)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.FilterClause(QueryParser.java:1548)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.BaseExpr(QueryParser.java:1276)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.Expr(QueryParser.java:893)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.Parse(QueryParser.java:682)
at org.apache.pig.impl.logicalLayer.LogicalPlanBuilder.parse(LogicalPlanBuilder.java:63)
at org.apache.pig.PigServer$Graph.parseQuery(PigServer.java:1031)
at org.apache.pig.PigServer$Graph.registerQuery(PigServer.java:981)
at org.apache.pig.PigServer.registerQuery(PigServer.java:383)
at org.apache.pig.tools.grunt.GruntParser.processPig(GruntParser.java:717)
at org.apache.pig.tools.pigscript.parser.PigScriptParser.parse(PigScriptParser.java:273)
at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:166)
at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:142)
at org.apache.pig.tools.grunt.Grunt.exec(Grunt.java:89)
at org.apache.pig.Main.main(Main.java:320)
Caused by: java.lang.ClassNotFoundException: org.joda.time.ReadablePartial
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 24 more
I tried to modify my PIG_CLASSPATH variable but i figured out that this variable doesn't exist at all (some other pig scripts are working though).
Do you have an idea to solve te problem ?
Thanks.
At first, you need to tell Pig which jar you are using. See this answer: how to include external jar file using PIG. Configure build path to add it in eclipse is not enough. Eclipse will not help you generate the correct jar.
Secondly, String nb_months_between = "" + Months.monthsBetween(d1,d2); is wrong. You can use int nb_months_between = Months.monthsBetween(d1,d2).getMonths();. If you read the Months.toString, it returns "P" + String.valueOf(getValue()) + "M";. So you can not use this value and want to convert it to a int.
u need this package: org/joda/time/ReadablePartial
can find here: jarfinder
download the joda-time-1.5.jar. Add to your project, this to should resolve.

retry open files in directory

I am trying the following code to open files in a certain directory. The name of the files are assigned by date but some dates are missing. I want to iterate through the dates to get the files and make the code go back 1 day every time it fails to find a file until it finally finds one (currentdate is a global variable and the strange xml element is because I'm using processing).
What I think the code should do is:
try to open the file with the given date.
on error, it goes to catch and gets a new date.
the process is repeated until a valid date is found.
when a valid date is found it goes to the line where break is and exits the loop.
But for some reason it does weird stuff like EDIT # sometimes it jumps too much, especially near the first month #
Is my logic not working for some reason?
Thanks
String strdate=getdatestring(counter);
int counter=0;
while(true){
try{
xmldata = new XMLElement(this, "dir/" + strdate + "_filename.xml" );
break;
}catch(NullPointerException e){
counter +=1;
strdate=getdatestring(counter);
}}
String getdatestring(int counter) {
Date firstdate=new Date();
int daystosum=0;
String strcurrentdate="";
if(keyPressed && key=='7'){
daystosum=-7;
}
daystosum=daystosum-counter;
Calendar c=Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try{
firstdate=formatter.parse("2012-04-13");//first day of the database
}catch(ParseException e){
println(e);
}
c.setTime(currentdate);
c.add(Calendar.DATE,daystosum);
currentdate=c.getTime();
if(currentdate.before(firstdate)){
currentdate=firstdate;
}
strcurrentdate=formatter.format(currentdate);
return strcurrentdate;
}
I believe once you do this,
daystosum=daystosum-counter;
you need to reset the counter as
counter = 0;
otherwise next time it will subtract more bigger number e.g. to start, say daystosum is 0 and counter is 5, after the daystosum=daystosum-counter;, daystosum will become -5. Again you go in the while loop and file is not found then count will increase to 6. In that case you would be getting `daystosum=daystosum-counter; as -5-6 = -11, but you would want it to move to -6. Resetting the counter should ix your issue.
On the other note, I think you can list down the files using file.listFiles() from the parent directory and perform the search on the file names. In that case, you are not attempting to open files again and again.

non standard locale with java.util.Calendar

We have a customer in Sweden, using the software in English. So we set the Locale(en, SV). We did hope the Calendar class would adhere to the country settings, but it uses the language and with this locale it assumes US settings.
So I am now searching for a way to let the calendar get to know the new firstDayOfWeek and minimumDayinFirstWeek settings preferred by a standard way other than setting it manually and thus hardcoded.
For clarification: The 29. August 2010 is in Sweden in CW 34 (also in Germany and Great Britain) but in the US it is reported as CW 36. The different results from the fact that the 01.01.2010 is a Friday and the 29.08.2010 a Sunday.
I cannot change the language setting itself to Swedish and use the English fallback since we do not support Swedish as language, but Sun/Oracle/.. does, so the Swing UI would have a mixture of Swedish and English texts, which not acceptable.
And just adding a properties file named "sun.util.resources.CalendarData_en_SV.properties" does not work out: it does not get read! Manually as a ResourceBundle that's possible. Somehow LocaleData.getCalendarData(Locale) does its own magic in reading the resourcfiles which i cannot find out since the source of it is not available. The method is called here: java.util.Calendar.setWeekCountData(Locale).
I also found the java.util.spi package but it does not provide access to the firstDayOfWeek and minimumDaysInFirstWeek settings.
Perhaps I can try to intercept the calls to the resourcebundles and use the default fallback to English and only let the calls to CalendarData proceed!? But that sounds hacky.
package de.drews.i18n;
import java.util.Calendar;
import java.util.Locale;
import java.util.ResourceBundle;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
// en_GB = 34
// en_US = 36
// sv_SV = 34
// en_SV = 36 --> wrong
printTest("en", "GB", 34);
printTest("en", "US", 36);
printTest("sv", "SV", 34);
printTest("en", "SV", 34);
}
private static void printTest(String language, String country, int expected) {
Locale locale = new Locale(language, country);
Calendar cal = Calendar.getInstance(locale);
cal.set(Calendar.YEAR, 2010);
cal.set(Calendar.MONTH, Calendar.AUGUST);
cal.set(Calendar.DATE, 29);
int actual = cal.get(Calendar.WEEK_OF_YEAR);
System.out.println(actual + "\t" + expected + "\t"
+ ((actual == expected) ? "Yeah!" : "-") + "\t" + language
+ "\t" + country);
}
}
How about using getInstance(TimeZone zone, Locale aLocale) providing a timezone to select calendar behaviour and locale to define language?
One ugly workaround that I can offer is to reflectively obtain the cachedLocaleData static field of the Calendar class, and put there the following:
key = new Locale(..); // your english-swedish locale
value = new int[] {firstDayOfWeek, minimalDaysInFirstWeek};
This can be done at init-time and will work for the entire application

Categories