Filtering current event iCal4j - java

I'm trying to use the ical4j library to find the current event (or at least events occurring today) in an ical file that contains recurring events. I've managed to build and print all events in the calendar but I have been getting
java.lang.IllegalArgumentException: Range start must be before range end
at runtime. This is strange because my period rule clearly starts before it ends. I have done a lot of reading and trying different things but I'm clueless. Here's the gist of what I'm trying to achieve:
private class CurrentShow extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
//params come from execute() call, params[0] is url
InputStream is = null;
net.fortuna.ical4j.model.Calendar calendar = new net.fortuna.ical4j.model.Calendar();
try {
is = new URL(urls[0]).openStream();
CalendarBuilder builder = new CalendarBuilder();
try {
calendar = builder.build(is);
} catch (Exception e) {
}
for (Iterator i = calendar.getComponents().iterator(); i.hasNext(); ) {
Component component = (Component) i.next();
System.out.println("Component [" + component.getName() + "]");
for (Iterator j = component.getProperties().iterator(); j.hasNext(); ) {
Property property = (Property) j.next();
System.out.println("Property [" + property.getName() + ", " + property.getValue() + "]");
}
}
java.util.Calendar today = java.util.Calendar.getInstance();
today.set(java.util.Calendar.HOUR_OF_DAY, 0);
today.clear(java.util.Calendar.MINUTE);
today.clear(java.util.Calendar.SECOND);
// create a period starting now with a duration of one (1) day..
Period period = new Period(new DateTime(today.getTime()), new Dur(1, 0, 0, 0));
Filter filter = new Filter(new Rule[] {new PeriodRule(period)}, Filter.MATCH_ALL);
Collection eventsToday = filter.filter(calendar.getComponents(Component.VEVENT));
Any help would be appreciated. Thanks.

Related

unable to redirect response in rest controller

I made two RestController apis. On response of second api I wanted first api's response (which is a json response), so I tried to use HttpServletResponse.redirect. I also set required content type to it. But on second api response I got Unsupported Media Type Content type 'null' not supported.
first API
#GetMapping(value="checkStatus/{msisdn}",consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CoreResponseHandler> fetchOcsByDate2(#PathVariable(value="msisdn",required=true)String msisdn){
long l_time_start = System.currentTimeMillis();
List<Object[]> list = repository.getSingleCallDetail(msisdn);
if(list==null || list.size()==0) {
System.out.println("NO RECORD FOUND");
}
JSONObject objMain = new JSONObject();
for(Object[] objArr: list) {
JSONObject obj = new JSONObject();
String msisdn_ = objArr[0]==null?null:objArr[0].toString();
String songId = objArr[1]==null?null:objArr[1].toString();
String songName = objArr[2]==null?null:objArr[2].toString();
String status = objArr[3]==null?null:objArr[3].toString();
String lang = objArr[4]==null?null:objArr[4].toString();
String startDate = objArr[5]==null?null:objArr[5].toString();
objMain.put("status", status);
objMain.put("language", lang);
obj.put("id", songId);
obj.put("msisdn", msisdn);
obj.put("songName", songName);
objMain.put("subscription", obj);
}
long l_time_end = System.currentTimeMillis();
long l_diff = l_time_end-l_time_start;
if(list!=null && list.size()>0) {
return new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.OK, ResponseStatusEnum.SUCCESSFUL, ApplicationResponse.SUCCESSFUL, objMain,l_diff+" ms"),HttpStatus.OK);
}
if(list==null || list.size()==0) {
return new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.NOT_FOUND, ResponseStatusEnum.FAILED, ApplicationResponse.Failed, "not found",l_diff+" ms"),HttpStatus.NOT_FOUND);
}
return new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.BAD_REQUEST, ResponseStatusEnum.FAILED, ApplicationResponse.Failed," > Bad request",l_diff+" ms"),HttpStatus.BAD_REQUEST);
}
no problem in output. ran smooth
second API
#GetMapping(value="verifyOtp/{msisdn}/{otp}",consumes=MediaType.APPLICATION_JSON_VALUE)
public void verifyOtp(#PathVariable(value="msisdn",required=true)String msisdn,
#PathVariable(value="otp",required=true)String otp,HttpServletResponse response) throws Exception{
long l_time_start = System.currentTimeMillis();
long l_time_end = System.currentTimeMillis();
long l_diff = l_time_end-l_time_start;
List<Object[]> list = repository.verifyOtp(msisdn,otp);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
if(list!=null && list.size()>0) {
for(Object[] obj:list) {
String strDate = obj[3]==null?null:obj[3].toString();
Date dtDb = sdf.parse(strDate);
Date dtNow = new Date();
String strDtNow = sdf.format(dtNow);
dtNow = sdf.parse(strDtNow);
long ldtDb = dtDb.getTime();
long ldtNow = dtNow.getTime();
if(ldtDb>ldtNow) {
System.out.println("success within time");
int ii = repository.updateIsActive(msisdn);
response.setContentType("application/json");
response.sendRedirect("http://localhost:9393/crbt/api/subscriber/ivr/checkStatus/"+msisdn);
}
else {
System.out.println("failure time over!");
}
}
}
else {
}
}
second Api Response in postman
What I expected was first API's response. But its giving me some 415 content type error
How can I get first API's success json response from second api's response.. I even tried org.springframework.http.HttpHeaders but couldn't get desired output. What changes I had to do in order to get first Api's response in my second api response.
I have a strange feeling answering your questions, because I dislike the solution I'll provided. But it might help, so I'll give a try.
Basically, your Controller are just Spring beans, which means you can do is having a dependency, and second controller will call first controller. This will also change your method verifyOtp to make it change the return type.
Something like that:
...
#Autowired
private FirstController firstController;
...
#GetMapping(value="verifyOtp/{msisdn}/{otp}",consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CoreResponseHandler> verifyOtp(#PathVariable(value="msisdn",required=true)String msisdn,
#PathVariable(value="otp",required=true)String otp,HttpServletResponse response) throws Exception{
long l_time_start = System.currentTimeMillis();
long l_time_end = System.currentTimeMillis();
long l_diff = l_time_end-l_time_start;
List<Object[]> list = repository.verifyOtp(msisdn,otp);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
if(list!=null && list.size()>0) {
for(Object[] obj:list) {
String strDate = obj[3]==null?null:obj[3].toString();
Date dtDb = sdf.parse(strDate);
Date dtNow = new Date();
String strDtNow = sdf.format(dtNow);
dtNow = sdf.parse(strDtNow);
long ldtDb = dtDb.getTime();
long ldtNow = dtNow.getTime();
if(ldtDb>ldtNow) {
System.out.println("success within time");
int ii = repository.updateIsActive(msisdn);
return firstController.fetchOcsByDate2(msidn);
}
else {
System.out.println("failure time over!");
return null;
}
}
}
else {
return null;
}
}
I think you are trying to achieve something uncommon, and to avoid having this dependency between controller, consider:
Change your use case. Make the second controller returning a HttpStatus.OK, and make the client do the next call to the first controller
Create a service in charge of loading the msidn, which will avoid duplicate code, and keep you in a more standard position to make our evolutions.
The issue occurred due to GetMapping .
#GetMapping(value="checkStatus/{msisdn}",consumes=MediaType.APPLICATION_JSON_VALUE)
replace with below in first Api:
#GetMapping(value="checkStatus/{msisdn}")

Select specific Calendar when using Java API to create calendar entry

I have successfully created calendar entries using the Java .jar files for Google Calendar API. They always go into the "Rifle" calendar even though I have the calendars shown below. I need to know how to specify the calendar that entry falls under. For example, where would I specify "Meetings" or "Shotgun"
I'm not seeing anything or any examples of how to specify a particular calendar.
public void create() {
try {
CalendarService myService = new CalendarService("My Service");
myService.setUserCredentials("mycalendar", "mypassword");
URL postUrl = new URL("http://www.google.com/calendar/feeds/myurl#junk.com/private/full");
CalendarEventEntry myEntry = new CalendarEventEntry();
//myEntry.setIcalUID("Rec Fire");
DateTime startTime = DateTime.parseDateTime("2014-06-22T09:00:00");
DateTime endTime = DateTime.parseDateTime("2014-06-22T13:00:00");
When eventTimes = new When();
eventTimes.setStartTime(startTime);
eventTimes.setEndTime(endTime);
myEntry.addTime(eventTimes);
Where eventLocation = new Where();
eventLocation.setLabel("R-4");
eventLocation.setValueString("value string");
eventLocation.setRel("REL");
myEntry.addLocation(eventLocation);
EventWho eventWho = new EventWho();
eventWho.setAttendeeStatus("attendee status");
eventWho.setAttendeeType("Meetings");
eventWho.setValueString("who value string");
eventWho.setEmail("myemailt#email.com");
eventWho.setRel("who rel");
myEntry.addParticipant(eventWho);
myEntry.setTitle(new PlainTextConstruct("R-4 Rifles Only"));
myEntry.setContent(new PlainTextConstruct("Paragraph HURST MULLINS"));
CalendarEventEntry insertedEntry = myService.insert(postUrl, myEntry);
} catch (Exception e) {
e.printStackTrace();
}
I figured this out. First you have to get the IDs of your secondary calendars
public void retrieve() {
try {
CalendarService myService = new CalendarService("QuanticoShootingclub");
myService.setUserCredentials("calendar#quanticoshootingclub.com", "washington13");
URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full");
CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);
System.out.println("Your calendars:");
System.out.println();
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
System.out.println("\t\t" + entry.getId());
}
} catch (Exception e) {
e.printStackTrace();
}
}
You can also do this by goign to your Google Calendar on the web. Click the drop-down and then Calendar Settings > Calendar Address: (Calendar ID: #group.calendar.google.com)
Then, when you're creating the new calendar entry, you substitute this ID for the primary ID.
NOTE: From the original code
URL postUrl = new URL("http://www.google.com/calendar/feeds/***<secondary calendar ID>***/private/full");

Android - Output List of events from Google calendar

I would ask You for a help. Now I am writing an app, which takes current events from Google calendars. But problem is there, when I'm trying to output events from more than one calendar. I know, that I'm doing something wrong, but really, can't get in the problem..
public class Main extends Activity {
//TextView mInfo;
TextView mEvents;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//mInfo = (TextView)findViewById(R.id.info);
mEvents = (TextView)findViewById(R.id.events);
String[] calendarName = {"Calendar1", "Calendar2", "Calendar3", "Calendar4", "Calendar5"};
readCalendars(calendarName);
}
private void readCalendars(String[] calendarName)
{
String[] projection =
new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.NAME,
CalendarContract.Calendars.ACCOUNT_NAME,
CalendarContract.Calendars.ACCOUNT_TYPE};
Cursor calCursor =
getContentResolver().
query(CalendarContract.Calendars.CONTENT_URI,
projection,
CalendarContract.Calendars.VISIBLE + " = 1",
null,
CalendarContract.Calendars._ID + " ASC");
long calId = -1;
//String calendarAccount = "";
for(int i = 0; i 0)
{
if(cursor.moveToFirst())
{
do
{
long eventId = cursor.getLong(3);
events += getEventInfo(eventId,cursor.getLong(1),cursor.getLong(2),cursor.getString(4),cursor.getString(5),cursor.getString(6)) + "\n";
} while(cursor.moveToNext());
}
}
mEvents.setText(events);
}
}
#SuppressLint("SimpleDateFormat")
private String getEventInfo(long eventId,long startTime, long endTime,String description, String location,String title)
{
String eventInfo = "";
{
DateFormat df = new SimpleDateFormat("HH:mm");
String start = df.format( new Date(startTime));
String end = df.format( new Date(endTime));
eventInfo = start + "-" + end + " Class: "+ location + "\nLecture: " + title + "\nLecturer: " + description;
}
return eventInfo;
}
}
Tried to output all events with loop, but does not helps. If I pass in calendarName[i], where i is one of existing calendars, I get output of calendar, which I asked for, but that's only one calendar, but for example, I need to output 5 calendars.
Tried to do anything with ListView - failure again.
Hope, You would help with this problem or help somehow how to resolve it..
The CalendarContract.Calendars.CONTENT_URI can be used to retrieve calendars, but not actual events for those calendars. Once you have the calendar id, you must use either of the following URIs for event information:
CalendarContract.Events.CONTENT_URI
CalendarContract.Instances.CONTENT_URI

Java String Parsing and Evaluating

All,
I am in the process or rewriting some code that I wrote a while back. The objective of the code was to calcualte a date and time based on a string in the following formats:
DayStart+2Hour+1Day-2Minutes
NOW+20Day
MonthStart+1Month
Which would take the start of the day (in local time), e.g. 2011-09-15 00:00:00 BST (2011-09-15 23:00 GMT) then add 2 hours, add 1 day, and subtract 2 minutes.
The implementation is in Java and the original algorithm was pretty basic. It iterated through each character in the string and appended to a buffer. The buffer was then checked to see if it ended with the strings I was looking (date specifier e.g MINUTE, HOUR, DAYSTART, etc.) for then extracted the number and added to an ArrayList where DateOffset was a simple class with a int and String which was date specifier. Here is some sample code:
// hard coded for sample
String s = "DayStart+2Hour+1Day-2Minutes";
StringBuilder sbBuffer = new StringBuilder();
String buffer;
// iterate through date string
for (char c : s.toCharArray()) {
sbBuffer.append(c);
buffer = sbBuffer.toString();
// check to see the end of the buffer string is what we expect
if (buffer.endsWith("DAYSTART")) {
offsets.add(new DateOffset(0, "DAYSTART"));
sbBuffer = new StringBuilder();
} else if (buffer.endsWith("DAY") && buffer.length() > 3) {
String numberStringPart = buffer.substring(0, buffer.length() - 3);
numberStringPart = numberStringPart.replaceAll("[+]", "").trim(); // need as parseInt does not like the +.
offsets.add(new DateOffset(Integer.parseInt(numberStringPart), "DAY"));
sbBuffer = new StringBuilder();
} ... and so on ...
else {
}
}
After the string was parsed I iterated through ArrayList to calculate my datetime.
The problem with the above is probably not efficient although we have experienced no problems. It also does not pick up any errors so you could enter DayStart+2GKGKER.
I'm just trying to come up with some fresh and neat ideas on what to use to rewrite it. I have done a little regex but not too sure if this would be the best route.
Any thoughts?
Thanks,
Andez
Define a grammar for your expressions. Take a look at the ANTLR framework to help you construct a grammar and process your expressions.
Woohoo, that was fun! Thank you! :-)
public class DateExpressions {
private Map<String, Date> dateVariables;
private Map<String, Integer> temporalUnits;
private Map<Character, Integer> temporalOperations;
public static DateExpressions createInstance() {
DateExpressions de = new DateExpressions();
Calendar c = Calendar.getInstance();
de.setVariable("NOW", c.getTime());
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
de.setVariable("DayStart", c.getTime());
c.set(Calendar.DAY_OF_MONTH, 1);
de.setVariable("MonthStart", c.getTime());
return de;
}
public DateExpressions() {
this.dateVariables = new HashMap<String, Date>();
this.temporalUnits = new HashMap<String, Integer>();
this.temporalUnits.put("Second", Calendar.SECOND);
this.temporalUnits.put("Minute", Calendar.MINUTE);
this.temporalUnits.put("Hour", Calendar.HOUR_OF_DAY);
this.temporalUnits.put("Day", Calendar.DATE);
this.temporalUnits.put("Month", Calendar.MONTH);
this.temporalUnits.put("Year", Calendar.YEAR);
this.temporalOperations = new HashMap<Character, Integer>();
this.temporalOperations.put('+', 1);
this.temporalOperations.put('-', -1);
}
public void setVariable(String key, Date value) {
this.dateVariables.put(key, value);
}
public Date parseExpression(String expr) throws IOException {
StringReader sr = new StringReader(expr);
String s;
int n;
char c;
int offset;
int unit;
int op = 1;
Calendar base = null;
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
while ((n = sr.read()) != -1) {
c = (char) n;
if (base == null && temporalOperations.containsKey(c)) {
s = sb2.toString();
if (!dateVariables.containsKey(s)) {
throw new IOException("Unknown variable '" + s + "' used");
}
base = Calendar.getInstance();
base.setTime(dateVariables.get(sb2.toString()));
op = temporalOperations.get(c);
sb1.setLength(0);
sb2.setLength(0);
} else if (temporalOperations.containsKey(c)) {
if (!temporalUnits.containsKey(sb2.toString())) {
throw new IOException(
"Parse error: unknown temporal unit used '"
+ sb2.toString() + "'");
}
offset = Integer.parseInt(sb1.toString());
unit = temporalUnits.get(sb2.toString());
base.add(unit, op * offset);
op = temporalOperations.get(c);
sb1.setLength(0);
sb2.setLength(0);
} else if (Character.isDigit(c)) {
sb1.append(c);
} else {
sb2.append(c);
}
}
if (!temporalUnits.containsKey(sb2.toString())) {
throw new IOException("Parse error: unknown temporal unit used '"
+ sb2.toString() + "'");
}
offset = Integer.parseInt(sb1.toString());
unit = temporalUnits.get(sb2.toString());
base.add(unit, op * offset);
return base.getTime();
}
public static void main(String[] args) throws IOException {
DateExpressions de = DateExpressions.createInstance();
System.out.println(de.parseExpression("DayStart+2Hour+1Day-2Minute"));
System.out.println(de.parseExpression("NOW+20Day"));
System.out.println(de.parseExpression("MonthStart+1Month"));
}
}
If you're after rapid experimentation, sometimes a literate API combined with on the fly compilation is an easy way to go.
So, your example could look like (given appropriate static imports)
daystart().plus()
.hours(2).plus()
.days(1).minutes(2)
or even (given milliseconds as the basic units)
daystart() + hours(2) + days(1) - minutes(2)
Regex seems to be the best bet for such a scenario. Although, I'm puzzled why would you want to interpret strings in this manner, rather than having sophisticated APIs.

google Calendar API (Java)

How to get the Date/time for an Event I retrieve ?
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("username#gmail.com", "pwd");
URL feedUrl = new URL("https://www.google.com/calendar/feeds/username#gmail.com/public/full");
CalendarQuery myQuery = new CalendarQuery(feedUrl);
myQuery.setFullTextQuery("Query");
CalendarEventFeed myResultsFeed = myService.query(myQuery,
CalendarEventFeed.class);
for (int i=0; i < myResultsFeed.getEntries().size(); i++)
{
CalendarEventEntry firstMatchEntry = (CalendarEventEntry) myResultsFeed.getEntries().get(i);
String myEntryTitle = firstMatchEntry.getTitle().getPlainText();
System.out.println(myEntryTitle + " " + firstMatchEntry.getPlainTextContent());
System.out.println(""+firstMatchEntry.getAuthors().get(0).getEmail());
System.out.println(""+firstMatchEntry.getPublished());
System.out.println(""+firstMatchEntry.getHtmlLink().getHref());
System.out.println(""+firstMatchEntry.getStatus().getValue());
}
I couldn't find a way to get any more useful info from a CalendarEventEntry.
LE: problem solved; after seeing this:
http://code.google.com/apis/calendar/data/1.0/developers_guide_php.html#RetrievingEvents
I got to this:
System.out.println("start time = "+firstMatchEntry.getTimes().get(0).getStartTime());
System.out.println("start time = "+firstMatchEntry.getTimes().get(0).getEndTime());
Good thing the examples are different depending on language.
Problem solved; after seeing this:
http://code.google.com/apis/calendar/data/1.0/developers_guide_php.html#RetrievingEvents
I got to this:
System.out.println("start time = "+firstMatchEntry.getTimes().get(0).getStartTime());
System.out.println("start time = "+firstMatchEntry.getTimes().get(0).getEndTime());

Categories