Select specific Calendar when using Java API to create calendar entry - java

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");

Related

Trying to pull logs from Github using Java JGit

I'm trying to use JGit to pull a log of commits done by developers using a Github security token. I tried googling a lot, but the documentation is scarce on this. The code that I am currently tinkering with looks like this:
public class GitIntegration {
public GitIntegration() {
}
public Iterable<RevCommit> getCommits() throws IOException, InvalidRefNameException, GitAPIException {
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
repositoryBuilder.setMustExist( true );
repositoryBuilder.setGitDir( new File ("https://oauth2:xyzxyzTOKENxyzxyz#github.com/myuser/myrepo.git"));
Repository repository = repositoryBuilder.build();
try (Git git = new Git(repository)) {
Iterable<RevCommit> commits = git.log().all().call();
int count = 0;
for (RevCommit commit : commits) {
System.out.println("LogCommit: " + commit);
count++;
}
System.out.println(count);
return commits;
}
}
}
But I am getting the following error:
java.nio.file.InvalidPathException: Illegal char <:> at index 5:
https:\oauth2:xyzxyzTOKENxyzxyz#github.com\myuser\myrepo.git\config
sun.nio.fs.WindowsPathParser.normalize(Unknown Source)
It doesn't work to throw git syntax in the File constructor like that at all. Does anyone know of a way to authenticate with tokens and then be able to use the git.log() method?
Thanks!
After digging around a bit, I decided to go with the Kohsuke github library instead. When doing that it was quite straightforward. Posting basic code example for reference. (Please note that this if for Enterprise Git. If you are doing it for "normal" Git, look into the Kohsuke documentation, you will need to use another method instead of connectToEnterpriseWithOAuth.)
import org.kohsuke.github.*;
public class GitIntegration {
public GitIntegration() {
}
public String getCommits(String repo) {
String retval = "";
try {
GitHub gitHub = GitHub.connectToEnterpriseWithOAuth("https://git.our.company.com/api/v3", "my.email#ourcompany.com", "xyzxyzTokenxyzxyz");
GHMyself me = gitHub.getMyself();
GHRepository repository = gitHub.getRepository("Gituser/"+repo);
Calendar cal = Calendar.getInstance();
cal.set(2020, 10, 4);
Date since = cal.getTime();
GHCommitQueryBuilder queryBuilder = repository.queryCommits().since(since).until(new Date());
PagedIterable<GHCommit> commits = queryBuilder.list();
Iterator<GHCommit> iterator = commits.iterator();
while (iterator.hasNext()) {
GHCommit commit = iterator.next();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
GHUser user = commit.getAuthor();
String name = "";
if(user != null) name = user.getName();
String message = commit.getCommitShortInfo().getMessage();
retval = retval.concat(message + " | " + name + " | " + sdf.format(commit.getCommitDate()) + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
retval = e.getCause().getMessage();
e.printStackTrace();
}
return retval;
}
}

Meet in Google Calendar API

How can I add google meet in google calendar api in java?
Please help me. I haven't understood the google documentation.
https://developers.google.com/calendar/create-events. The source code is given here. Here, I want to create event using users gmail account. I have not any G-suite account
Event event = new Event()
.setSummary(title)
.setLocation(location)
.setDescription(description);
DateTime startDateTime = new DateTime( date +"T"+startTime+"+06:00" );//"2020-05-05T11:00:00+06:00");
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone("Asia/Dhaka");
event.setStart(start);
DateTime endDateTime = new DateTime(date +"T"+endTime+"+06:00");//"2020-05-05T12:00:00+06:00");
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime)
.setTimeZone("Asia/Dhaka");
event.setEnd(end);
String[] recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=1"};
event.setRecurrence(Arrays.asList(recurrence));
EventAttendee attendees[];
attendees = new EventAttendee[allAttendees.size()];
for(int i=0; i<allAttendees.size(); i++){
// System.out.println(allAttendees.get(i));
attendees[i] = new EventAttendee().setEmail(allAttendees.get(i));
}
event.setAttendees(Arrays.asList(attendees));
EventReminder[] reminderOverrides = new EventReminder[] {
new EventReminder().setMethod("email").setMinutes(24 * 60),
new EventReminder().setMethod("popup").setMinutes(10),
};
Event.Reminders reminders = new Event.Reminders()
.setUseDefault(false)
.setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);
String calendarId = "primary";
try {
abc = service.events().insert(calendarId, event);
} catch (IOException e) {
e.printStackTrace();
}
try {
event = service.events().insert(calendarId, event).execute();
} catch (IOException e) {
e.printStackTrace();
}
String meetingId = event.getHangoutLink();
System.out.println("What is meeting ID? = "+meetingId);
Answer
You will need to use the JAVA API Documentation for Google Calendar
You have to create a new Meet request and then append it to the current event and before that, enable the conferenceDataVersion by setting it to 1. Before using the following code make sure that you have this setup.
Code
Event event = new Event()
.setSummary(title)
.setLocation(location)
.setDescription(description);
// Your previous code
/* The code needed - START */
ConferenceSolutionKey conferenceSKey = new ConferenceSolutionKey();
conferenceSKey.setType("eventHangout"); // Non-G suite user
CreateConferenceRequest createConferenceReq = new CreateConferenceRequest();
createConferenceReq.setRequestId("3whatisup3"); // ID generated by you
createConferenceReq.setConferenceSolutionKey(conferenceSKey);
ConferenceData conferenceData = new ConferenceData();
conferenceData.setCreateRequest(createConferenceReq);
event.setConferenceData(conferenceData); // attach the meeting to your event
/* The code needed - END */
String calendarId = "primary";
// There’s no need to declare the try-catch block twice
try {
/* Code changes - START */
// .setConferenceDataVersion(1) enables the creation of new meetings
event = service.events().insert(calendarId, event).setConferenceDataVersion(1).execute();
/* Code changes - END */
} catch (IOException e) {
e.printStackTrace();
}
String meetingId = event.getHangoutLink();
System.out.println("What is meeting ID? = "+meetingId);
References
Google Calendar JAVA API: Event.setConferenceData
Google Calendar JAVA API: ConferenceData.setCreateRequest
Google Calendar JAVA API: CreateConferenceRequest.setRequestId
Google Calendar JAVA API: ConferenceSolutionKey.setType
Google Calendar JAVA API: Calendar.Events.Insert.setConferenceDataVersion The most important
The final workable code for me is given below.
Event event = new Event()
.setSummary(title)
.setLocation(location)
.setDescription(description);
DateTime startDateTime = new DateTime( date +"T"+startTime+"+06:00" );//"2020-05-05T11:00:00+06:00");
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone("Asia/Dhaka");
event.setStart(start);
DateTime endDateTime = new DateTime(date +"T"+endTime+"+06:00");//"2020-05-05T12:00:00+06:00");
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime)
.setTimeZone("Asia/Dhaka");
event.setEnd(end);
String[] recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=1"};
event.setRecurrence(Arrays.asList(recurrence));
/* s1 = "abc#gmail.com";
s2 = "xyz#gmail.com";
EventAttendee[] attendees = new EventAttendee[] {
new EventAttendee().setEmail(s1),
new EventAttendee().setEmail(s2),
};*/
EventAttendee attendees[];
attendees = new EventAttendee[allAttendees.size()];
for(int i=0; i<allAttendees.size(); i++){
// System.out.println(allAttendees.get(i));
attendees[i] = new EventAttendee().setEmail(allAttendees.get(i));
}
event.setAttendees(Arrays.asList(attendees));
EventReminder[] reminderOverrides = new EventReminder[] {
new EventReminder().setMethod("email").setMinutes(24 * 60),
new EventReminder().setMethod("popup").setMinutes(10),
};
Event.Reminders reminders = new Event.Reminders()
.setUseDefault(false)
.setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);
ConferenceSolutionKey conferenceSKey = new ConferenceSolutionKey();
conferenceSKey.setType("hangoutsMeet"); // Non-G suite user
CreateConferenceRequest createConferenceReq = new CreateConferenceRequest();
createConferenceReq.setRequestId("3whatisup3"); // ID generated by you
createConferenceReq.setConferenceSolutionKey(conferenceSKey);
ConferenceData conferenceData = new ConferenceData();
conferenceData.setCreateRequest(createConferenceReq);
event.setConferenceData(conferenceData);
String calendarId = "primary";
try {
event = service.events().insert(calendarId, event).setConferenceDataVersion(1).execute();
} catch (IOException e) {
e.printStackTrace();
}
System.out.printf("Event created: %s\n", event.getHtmlLink());
System.out.printf("Hangout Link %s\n", event.getHangoutLink());
#Jose Vasquez's answer is right except for one thing.
I changed this line
conferenceSKey.setType("eventHangout");
to this
conferenceSKey.setType("hangoutsMeet");
and then everything works fine.

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}")

Filtering current event iCal4j

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.

Hot to get last modified credit memo record from netsuite

I am using Java and NetSuite webserivces to get the last modified credit memo transactions or refund transactions for all customers but there is no any kind of searchBasic class to do it. If anyone done it before then please provide your suggestion or absolute answer as I am new to netsuite I don't know all the thing.
If you know about the balance rather than credit memo then also it will be helpful for me.
public ArrayList<CreditMemo> searchRecentCreditMemos()
throws Exception {
TransactionSearch transactionsSearch = new TransactionSearch();
TransactionSearchBasic transactionSearchBasic = new TransactionSearchBasic();
CustomerSearchBasic custSearchBasic = new CustomerSearchBasic();
Calendar startDate = Calendar.getInstance();
startDate.add(Calendar.DAY_OF_MONTH, -1);
Calendar endDate = Calendar.getInstance();
// Create criteria
com.netsuite.webservices.platform.core_2014_1.SearchDateField searchDateField = new com.netsuite.webservices.platform.core_2014_1.SearchDateField();
searchDateField
.setOperator(com.netsuite.webservices.platform.core_2014_1.types.SearchDateFieldOperator.within);
searchDateField.setSearchValue(startDate);
searchDateField.setSearchValue2(endDate);
transactionSearchBasic.setLastModifiedDate(searchDateField);
transactionsSearch.setBasic(transactionSearchBasic);
transactionsSearch.setCustomerJoin(custSearchBasic);
SearchResult result = port.search(transactionsSearch);
ArrayList<CreditMemo> creditMemoList = new ArrayList<>();
if (result.getStatus().isIsSuccess()) {
RecordList recordList = result.getRecordList();
Record[] records = recordList.getRecord();
if (records != null && records.length != 0) {
for (int i = 0; i < records.length; i++) {
if (records[i] instanceof CreditMemo) {
CreditMemo creditMemo = (CreditMemo) records[i];
creditMemoList.add(creditMemo);
}
}
}
}
return creditMemoList;
}

Categories