cal4j - Unexpected end of file Exception - java

I have currently no idea what´s here the issue and I asked kindly for help.
I´m generating a ics - File.
But if I would like to open the ics - File to get the Calender, I got the following error message:
net.fortuna.ical4j.data.ParserException: Error at line 1:Unexpected end of file
Here my information:
ical4j Version 3.0.1
Java: 8 Build 181
My output from the ics - File:
BEGIN:VCALENDAR PRODID:-//Ben Fortuna//iCal4j 1.0//EN VERSION:2.0
CALSCALE:GREGORIAN BEGIN:VEVENT DTSTAMP:20180826T165052Z
DTSTART:01180905T000000 DTEND:01180905T000000 SUMMARY:ddd
TZID:Europe/Berlin
UID:1535302250819-9ed0489f-0320-4a66-8f9c-4af0e62cdedd END:VEVENT
END:VCALENDAR
Here my code for generation the calender.ics - File:
public void createEvent(BookingDate bookingDate, Mandatory mandatory, Employee employee)
throws FileNotFoundException, IOException, ParserException, ConstraintViolationException {
// Create a TimeZone
System.setProperty("net.fortuna.ical4j.timezone.cache.impl", MapTimeZoneCache.class.getName());
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
TimeZone timezone = registry.getTimeZone("Europe/Berlin");
VTimeZone tz = timezone.getVTimeZone();
String pathMandatoryFile = null;
String pathEmployeeFile = null;
// Reading the file and creating the calendar
Calendar icsCalendar = null;
FileOutputStream fout = null;
if (bookingDate.isCreateCalendarMandatoryEntry()) {
// timezone = registry.getTimeZone(mandatory.getTimeZone());
pathMandatoryFile = "calendar.ics";
fout = new FileOutputStream(pathMandatoryFile);
try {
FileInputStream fin = new FileInputStream(pathMandatoryFile);
CalendarBuilder builder = new CalendarBuilder();
icsCalendar = builder.build(fin);
} catch (Exception e) {
}
if (icsCalendar == null) {
icsCalendar = createNewCalender(pathMandatoryFile);
}
}
// Creating an event
java.util.Calendar startCal = java.util.Calendar.getInstance(timezone);
startCal.set(java.util.Calendar.YEAR, bookingDate.getStartDate().getYear());
startCal.set(java.util.Calendar.MONTH, bookingDate.getStartDate().getMonth());
startCal.set(java.util.Calendar.DAY_OF_MONTH, bookingDate.getStartDate().getDate());
startCal.set(java.util.Calendar.HOUR_OF_DAY, bookingDate.getStartDate().getHours());
startCal.clear(java.util.Calendar.MINUTE);
startCal.clear(java.util.Calendar.SECOND);
java.util.Calendar endCal = java.util.Calendar.getInstance(timezone);
endCal.set(java.util.Calendar.YEAR, bookingDate.getEndDate().getYear());
endCal.set(java.util.Calendar.MONTH, bookingDate.getEndDate().getMonth());
endCal.set(java.util.Calendar.DAY_OF_MONTH, bookingDate.getEndDate().getDate());
endCal.set(java.util.Calendar.HOUR_OF_DAY, bookingDate.getEndDate().getHours());
endCal.clear(java.util.Calendar.MINUTE);
endCal.clear(java.util.Calendar.SECOND);
net.fortuna.ical4j.model.DateTime dtStart = new DateTime(startCal.getTime());
net.fortuna.ical4j.model.DateTime dtEnd = new DateTime(endCal.getTime());
String eventName = bookingDate.getName();
VEvent meeting = new VEvent(dtStart, dtEnd, eventName);
// add timezone info..
meeting.getProperties().add(tz.getTimeZoneId());
String uidValue = bookingDate.getIdHash();
meeting.getProperties().add(new Uid(uidValue));
// Add the event and print
icsCalendar.getComponents().add(meeting);
CalendarOutputter outputter = new CalendarOutputter();
outputter.output(icsCalendar, fout);
}
private Calendar createNewCalender(String filePath) throws ValidationException, IOException {
// Saving an iCalendar file
FileOutputStream fout = new FileOutputStream(filePath);
Calendar calendar = new Calendar();
calendar.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
calendar.getProperties().add(Version.VERSION_2_0);
calendar.getProperties().add(CalScale.GREGORIAN);
return calendar;
}
Can anybody help me, please.

Related

How to write a junit test case for fetching a file and reading it from Amazon S3 bucket

Here is my code :
public String getDate() throws IOException {
StringBuilder fileURI = new StringBuilder(locationName);
fileURI.append(fileName);
S3ObjectInputStream ts = null;
ts = (S3ObjectInputStream) s3Services.getResourceStream(fileURI.toString());
String timeStamp;
String onlyDate = null;
LocalDate mydate;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(ts))) {
timeStamp = reader.readLine();
onlyDate = timeStamp.substring(0, 10);
LocalDate date = LocalDate.parse(onlyDate);
mydate= date.minusDays(1);
}
return mydate.toString();
}
I am working on junit for the first time.
I need to mock s3Services and test that getResourceStream() is called with the expected value.
I am trying to mock out S3ObjectInputStream and make sure the correct methods on it are called.
#Test
public void testgetDate() throws IOException {
Mockito.mock(Service.class);
StringBuilder fileURI = new StringBuilder("test");
fileURI.append("testFile.txt");
Mockito.mock(S3ObjectInputStream .class);
S3ObjectInputStream ts = null;
Mockito.when(s3Services.getResourceStream(fileURI.toString())).thenReturn(ts);
service.getDate();
}

How do I parse a Reader into a Calendar?

I've tried to parse a reader from an InputStreamReader return into a Calendar with custom events but I got an URISyntaxException due to my icalendar file content. But I can't modify it because my purpose is to get an iCalendar data only (online file.ics) and parse them into a Calendar with iCal4j library: https://github.com/ical4j/ical4j.
So my question is how can I solve or bypass this problem?
My code :
public class AccesHTTP extends AsyncTask<String, String, String> {
private Controle controle;
private String urlServ = null;
public AsyncResponse delegate = null;
public AccesHTTP(String servaddr) {
controle = Controle.getInstance(null);
urlServ = servaddr;
}
#Override
protected String doInBackground(String... strings) {
// Create a TimeZone
System.setProperty("net.fortuna.ical4j.timezone.cache.impl", MapTimeZoneCache.class.getName());
URL url = null;
try {
url = new URL(urlServ);
Reader r = null;
r = new InputStreamReader(url.openStream(), "ISO-8859-15");
CalendarBuilder builder = new CalendarBuilder();
Calendar thisCalendar = builder.build(r);
controle.refreshEdt(thisCalendar);
} catch (IOException | ParserException e) {
e.printStackTrace();
}
return "Completed";
}
#Override
protected void onPostExecute(String s){
Log.d("Return","************ " + s + " ************");
if(s!=null){
delegate.processFinish(s);
};
}
}
My icalendar content format:
BEGIN:VCALENDAR
BEGIN:VEVENT
ATTENDEE;ROLE=CHAIR:CN=LASTNAME Forename :MAILTO:edt-noreply#domain.fr
ATTENDEE;ROLE=REQ-PARTICIPANT:CN=S5A-01_ANG :MAILTO:edt-noreply#domain.fr
SUMMARY:- ang
DESCRIPTION:Professeur:LASTNAME Forename \nGroupe:S5A-01_ANG
DTSTART;TZID=Europe/Paris:20191211T080500
DTEND;TZID=Europe/Paris:20191211T093500
DTSTAMP:20200527T104154
LOCATION:B213
STATUS:CONFIRMED
UID:47468078
END:VEVENT
BEGIN:VEVENT
ATTENDEE;ROLE=CHAIR:CN=LASTNAME Forename :MAILTO:edt-noreply#domain.fr
ATTENDEE;ROLE=REQ-PARTICIPANT:CN=S5A-01_ANG :MAILTO:edt-noreply#domain.fr
...
END:VEVENT
END:VCALENDAR
The error code :
java.net.URISyntaxException: Illegal character in scheme name at index 2: CN=LASTNAME Forename :MAILTO:edt-noreply#domain.fr
at java.net.URI$Parser.fail(URI.java:2875)
at java.net.URI$Parser.checkChars(URI.java:3048)
at java.net.URI$Parser.parse(URI.java:3075)
at java.net.URI.<init>(URI.java:583)
at net.fortuna.ical4j.util.Uris.create(Uris.java:121)
at net.fortuna.ical4j.model.property.Attendee.setValue(Attendee.java:109)
at net.fortuna.ical4j.model.property.Attendee.<init>(Attendee.java:85)
at net.fortuna.ical4j.model.property.Attendee$Factory.createProperty(Attendee.java:175)
at net.fortuna.ical4j.model.PropertyBuilder.build(PropertyBuilder.java:48)
at net.fortuna.ical4j.data.DefaultContentHandler.endProperty(DefaultContentHandler.java:123)
at net.fortuna.ical4j.data.CalendarParserImpl$PropertyParser.parse(CalendarParserImpl.java:292)
at net.fortuna.ical4j.data.CalendarParserImpl$PropertyParser.access$1100(CalendarParserImpl.java:224)
at net.fortuna.ical4j.data.CalendarParserImpl$PropertyListParser.parse(CalendarParserImpl.java:211)
at net.fortuna.ical4j.data.CalendarParserImpl$ComponentParser.parse(CalendarParserImpl.java:427)
at net.fortuna.ical4j.data.CalendarParserImpl$ComponentParser.access$900(CalendarParserImpl.java:404)
at net.fortuna.ical4j.data.CalendarParserImpl$PropertyListParser.parse(CalendarParserImpl.java:209)
at net.fortuna.ical4j.data.CalendarParserImpl.parseCalendar(CalendarParserImpl.java:115)
at net.fortuna.ical4j.data.CalendarParserImpl.parseCalendarList(CalendarParserImpl.java:180)
at net.fortuna.ical4j.data.CalendarParserImpl.parse(CalendarParserImpl.java:149)
... 10 more
There is a syntax error in your iCalendar data.
A semicolon must come after the ROLE parameter, not a colon. For example:
Incorrect: ATTENDEE;ROLE=CHAIR:CN=LASTNAME Forename :MAILTO:edt-noreply#domain.fr
Correct: ATTENDEE;ROLE=CHAIR;CN=LASTNAME Forename :MAILTO:edt-noreply#domain.fr
Thank you #Michael for your help! Here it's my code which works in my situation :
#Override
protected String doInBackground(String... strings) {
// Create a TimeZone
System.setProperty("net.fortuna.ical4j.timezone.cache.impl", MapTimeZoneCache.class.getName());
URL url = null;
try {
url = new URL(urlServ);
Reader r = null;
r = new InputStreamReader(url.openStream(), "ISO-8859-15");
BufferedReader reader = new BufferedReader(r);
String str;
StringBuilder sb = new StringBuilder();
while((str = reader.readLine()) != null){
if(!(str.startsWith("ATTENDEE")))
sb.append(str + "\n");
}
r = new StringReader(sb.toString());
CalendarBuilder builder = new CalendarBuilder();
Calendar thisCalendar = builder.build(r);
controle.refreshEdt(thisCalendar);
} catch (IOException | ParserException e) {
e.printStackTrace();
}
return "Completed";
}

MS ExchangeService - get custom calendar (OR calendars list)

Using ExchangeService I need to get Calendar folder and retrieve all events there
It's done by this piece of code
private List getRoomCalendar() throws Exception {
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
ExchangeCredentials credentials = new WebCredentials(username, password);
service.setCredentials(credentials);
service.setUrl(new URI(msExchangeUrl));
FolderView fv = new FolderView(100);
fv.setTraversal(FolderTraversal.Deep);
FolderId confRoomFolderId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(username));
System.out.println(confRoomFolderId.getFolderName());
List events = new ArrayList();
Date date = new Date();
try {
CalendarFolder calendarFolder = CalendarFolder.bind(service, confRoomFolderId);
CalendarView cView = new CalendarView(new DateTime(date).minusDays(1).toDate(),
new DateTime(date).plusDays(1).toDate(), 100);
cView.setPropertySet(new PropertySet(AppointmentSchema.Subject,
AppointmentSchema.Start,
AppointmentSchema.End));
// we can set other properties as well depending upon our need.
FindItemsResults appointments = calendarFolder.findAppointments(cView);
List<Appointment> appList = appointments.getItems();
for (Appointment appointment : appList) {
Map event = readEvent(appointment);
events.add(event);
}
} catch (Exception e) {
e.printStackTrace();
}
return events;
}
private Map readEvent(Appointment appointment) {
Map appointmentData = new HashMap();
try {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
appointmentData.put("appointmentSubject", appointment.getSubject());
appointmentData.put("appointmentStartTime", df.format(appointment.getStart()));
appointmentData.put("appointmentEndTime", df.format(appointment.getEnd()));
} catch (ServiceLocalException e) {
e.printStackTrace();
}
return appointmentData;
}
Cool, it's working and returns these data
default MS Calendar
The question is: how can I get events for MY CUSTOM CALENDAR called name
see here
custom MS calendar
The solution is to create the folderView first. Afterwards, apply a search filter, find it using FindFolderResults.
PropertySet psPropset = new PropertySet(BasePropertySet.FirstClassProperties);
FolderView fvFolderView = new FolderView(1);
fvFolderView.setPropertySet(psPropset);
SearchFilter SfSearchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName,"name");
FindFoldersResults findFoldersResults = service.findFolders(confRoomFolderId, SfSearchFilter, fvFolderView);
System.out.println(findFoldersResults.getFolders().get(0).getDisplayName());

Buffered Writer not writing to txt file from ArrayList

I am having a spot of bother getting BufferedWriter to write output to a txt file I have.
When I compile the program, I do not get any errors but the txt file arrives in my project blank.
I have looked on here at similar questions and tried a few of the proposed solutions to resolve it without success, like closing the stream etc
public void storeToDoItemsOntoTxtFile () throws IOException {
Path path = Paths.get(fileName);
BufferedWriter buffyWriter = Files.newBufferedWriter(path);
try {
Iterator<ToDoItem> bigIterator = toDoItems.iterator();
while (bigIterator.hasNext()) {
ToDoItem item = bigIterator.next();
buffyWriter.write(String.format("%s\t%S\t%s", item.getShortDescription(), item.getDetails(), item.getDeadline().format(formatter)));
buffyWriter.newLine();
}
} finally {
if (buffyWriter !=null) {
buffyWriter.close();// when we are done working with the writer
}
}
}
BufferedReader
public void loadToDoItemsFromTxtFile() throws IOException {
toDoItems = FXCollections.observableArrayList();
Path path = Paths.get(fileName);
BufferedReader buffyReader = Files.newBufferedReader(path);
String buffyInput;
try {
while ((buffyInput = buffyReader.readLine()) !=null) {
String [] itemPieces = buffyInput.split("\t");
String shortDescription = itemPieces[0];
String details = itemPieces[1]; //
String dateString = itemPieces [2];
LocalDate date = LocalDate.parse(dateString, formatter);
ToDoItem toDoItem = new ToDoItem(shortDescription,details,date);
toDoItems.add(toDoItem);
}
} finally {
if (buffyReader != null) {// ie the buffy reader states that there is a toDoItem" in the txt file
buffyReader.close();
}
}
}

Screenshots of error page in selenium web driver with date of its occurence and page or link on which it has occured

My scenario is I'm getting same error page on few button/link click on my website.I have a sample of code for taking screenshot according to the date timestamp, but I also want to fetch its occurence on which button or link click event it occured and want to append that event name to the screenshot file.
Please help out.
Thanks in advance
As of now this is what I have.
try{
My code where the error occures on button click
}
catch(Exception ex)
{
File scrn=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// extracting date for folder name.
SimpleDateFormat sdfDate1 = new SimpleDateFormat("yyyy-MM-dd");//dd/MM/yyyy
Date now1 = new Date();
String strDate1 = sdfDate1.format(now1);
// extracting date and time for snapshot file
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
String filefolder="D:/Home/Snapshot/"+strDate1+"/"; // create a folder as snapshot in your project directory
// Creating folders and files
File f = new File(filefolder+strDate+".jpeg");
FileUtils.copyFile(scrn, new File(f.getPath()));
}
Put the entire code for the screenshot in a method, like take_screenshot and put it in a common place like and pass it one argument with the name of the even where it occurred.
try {
// some action which causes an error
}
catch(Exception ex)
{
MyLib.TakeScreenshot("click button") // argument name, 'action' for example
// do other things for error handling
}
And MyLib.TakeScreenshot has the code you've put above. For the line
// Creating folders and files
File f = new File(filefolder+strDate+".jpeg");
Change that to:
File f = new File(filefolder + strDate + action + ".jpeg"); //action name added to filename
/**
* Define path for Screenshot file.
*/
public String getScreenshotSavePath() {
String className = this.getClass().getName();
File dir = new File(System.getProperty("user.dir")+File.separator+"screenshots"+File.separator + className + File.separator);
dir.mkdirs();
return dir.getAbsolutePath();
}
/**
* Take Screenshot on failure.
*/
public void getScreenshot() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String date = sdf.format(new Date());
String url = driver.getCurrentUrl().replaceAll("[\\/:*\\?\"<>\\|]", "_");
String ext = ".png";
String path = getScreenshotSavePath().toString()+ File.separator + date + "_" + url + ext;
try {
if (driver instanceof TakesScreenshot) {
File tmpFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
org.openqa.selenium.io.FileHandler.copy(tmpFile, new File(path));
auto_logs.error("Captured Screenshot for Failure: "+path);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
One way to do this is to create a proxy class that implements the WebDriver interface (or only the methods you need) and has the real WebDriver object as a constructor argument. This way you can use the methods of the proxy object, which will take a screenshot with information about the event that threw the exception.
public class WebDriverProxy {
private WebDriver driver;
public WebDriverProxy(WebDriver driver) {
this.driver = driver;
}
public void clickLink (String linkText) {
try{
driver.click(By.linkText(linkText);
} catch (Exception e) {
this.takeScreenshot(linkText);
throw e;
}
}
private void takeScreenshot(String event) {
/** take the screenshot and save it with String event in the filename **/
}
}

Categories