Google calendar get events - events

I am using this code and getting the events from the calendar and it is working fine but, I want to get the events from google accounts calendar .For example, I want to get the (deepakcando90#gmail.com )google calendar accounts events also? I know it is possible but do not know how to implement it?
public static void readCalendarEvent(Context context) throws ParseException {
ContentResolver contentResolver = context.getContentResolver();
Calendar calendar = Calendar.getInstance();
String dtstart = "dtstart";
String dtend = "dtend";
SimpleDateFormat displayFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
stime=displayFormatter.format(calendar.getTime());
SimpleDateFormat startFormatter = new SimpleDateFormat("MM/dd/yy");
String dateString = startFormatter.format(calendar.getTime());
long after = calendar.getTimeInMillis();
SimpleDateFormat formatterr = new SimpleDateFormat("hh:mm:ss MM/dd/yy");
Calendar endOfDay = Calendar.getInstance();
Date dateCCC = formatterr.parse("47:59:59 " + dateString);
endOfDay.setTime(dateCCC);
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"), (new String[] { "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation" }), "(" + dtstart + ">" + after + " and " + dtend + "<" + endOfDay.getTimeInMillis() + ")", null, "dtstart ASC");
gCalendar = new ArrayList<GoogleCalendar>();
try {
System.out.println("Count=" + cursor.getCount());
if (cursor.getCount() > 0) {
System.out.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
gCalendar.add(googleCalendar);
int calendar_id = cursor.getInt(0);
googleCalendar.setCalendar_id(calendar_id);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String description = cursor.getString(2);
googleCalendar.setDescription(description);
String dtstart1 = cursor.getString(3);
googleCalendar.setDtstart(dtstart1);
String dtend1 = cursor.getString(4);
googleCalendar.setDtend(dtend1);
String eventlocation = cursor.getString(5);
googleCalendar.setEventlocation(eventlocation);
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

You can try OAuth 2.0 service accounts to properly access the user accounts. Using a service account lets you impersonate users and perform operation on their behalf.
Accessing domain calendars as an app
An app can access domain-owned calendars without requiring user credentials if it authenticates using a service account. The service account must have the necessary access using domain-wide authority delegation. In order to impersonate a user account, specify the email address of the user account with the setServiceAccountUser method of the GoogleCredential factory.
I hope it helps. Goodluck :)

Related

"The caller does not have permission", when adding teacher to a course through the Google Classroom API

I'm trying to create assignments for students through the google classroom api. However, I've learned admins can not do that, only teachers. So in our code, after creating a new course we're then setting the teacher's email, which is the same as for the admin and adding it to the . However, the code fails when attempting to add the teacher to the course. It says "The caller does not have permission". I'm not sure what extra permissions would be needed and am stuck on this error message.
private static final List<String> SCOPES =
Arrays.asList(ClassroomScopes.CLASSROOM_COURSES,
ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS,
ClassroomScopes.CLASSROOM_COURSEWORK_ME,
ClassroomScopes.CLASSROOM_PROFILE_EMAILS,
ClassroomScopes.CLASSROOM_PROFILE_PHOTOS,
ClassroomScopes.CLASSROOM_ROSTERS);
Course course = new Course()
.setName("10th Grade Biology")
.setSection("Period 2")
.setDescriptionHeading("Welcome to 10th Grade Biology")
.setDescription("We'll be learning about about the structure of living creatures "
+ "from a combination of textbooks, guest lectures, and lab work. Expect "
+ "to be excited!")
.setRoom("301")
.setOwnerId("me")
.setCourseState("PROVISIONED");
course = service.courses().create(course).execute();
System.out.printf("Course created: %s (%s)\n", course.getName(), course.getId());
String courseId = course.getId();
String teacherEmail = "admin#gmail.com";
Teacher teacher = new Teacher().setUserId(teacherEmail);
try {
teacher = service.courses().teachers().create(courseId, teacher).execute();
System.out.printf("User '%s' was added as a teacher to the course with ID '%s'.\n",
teacher.getProfile().getName().getFullName(), courseId);
} catch (GoogleJsonResponseException e) {
GoogleJsonError error = e.getDetails();
if (error.getCode() == 409) {
System.out.printf("User '%s' is already a member of this course.\n", teacherEmail);
} else {
throw e;
}
}
public class ClassroomQuickstart {
private static final String APPLICATION_NAME = "Google Classroom API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
private static final List<String> SCOPES =
Arrays.asList(ClassroomScopes.CLASSROOM_COURSES,
ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS,
ClassroomScopes.CLASSROOM_COURSEWORK_ME,
ClassroomScopes.CLASSROOM_ROSTERS);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = ClassroomQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public static void main(String... args) throws IOException,
GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT =
GoogleNetHttpTransport.newTrustedTransport();
Classroom service = new Classroom.Builder(HTTP_TRANSPORT, JSON_FACTORY,
getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
// List the first 10 courses that the user has access to.
ListCoursesResponse response = service.courses().list()
.setPageSize(10)
.execute();
List<Course> courses = response.getCourses();
if (courses == null || courses.size() == 0) {
System.out.println("No courses found.");
} else {
System.out.println("Courses:");
for (Course course : courses) {
System.out.printf("%s\n", course.getName());
}
}
Course course = new Course()
.setName("10th Grade Biology")
.setSection("Period 2")
.setDescriptionHeading("Welcome to 10th Grade Biology")
.setDescription("We'll be learning about about the structure of living creatures "
+ "from a combination of textbooks, guest lectures, and lab work. Expect "
+ "to be excited!")
.setRoom("301")
.setOwnerId("me")
.setCourseState("PROVISIONED");
course = service.courses().create(course).execute();
System.out.printf("Course created: %s (%s)\n", course.getName(), course.getId());
String courseId = course.getId();
String teacherEmail = "admin#gmail.com";
Teacher teacher = new Teacher().setUserId(teacherEmail);
try {
teacher = service.courses().teachers().create(courseId, teacher).execute();
System.out.printf("User '%s' was added as a teacher to the course with ID '%s'.\n",
teacher.getProfile().getName().getFullName(), courseId);
} catch (GoogleJsonResponseException e) {
GoogleJsonError error = e.getDetails();
if (error.getCode() == 409) {
System.out.printf("User '%s' is already a member of this course.\n", teacherEmail);
} else {
throw e;
}
}
// CourseWork courseWork = new CourseWork()
// .setCourseId(course.getId())
// .setTitle("title")
// .setWorkType("ASSIGNMENT")
// .setDescription("desc");
// service.courses().courseWork().create(course.getId(), courseWork).execute();
}
}
Thank you.
If I'm not mistaken, the requesting user must be a domain administrator or super admin to be able to create a teacher.
Non-super admin users can only access courses they are part of (as teachers, or students), not all courses in the domain.
They can remove students and other teachers from courses they own directly via courses.teachers.delete and courses.students.delete, but they cannot directly add new students and teachers to their courses via courses.teachers.create and courses.students.create. Only domain administrators (Super Admins) can do that. Non-admins must first send an invitation via invitations.create(), and obtain the user's consent.
Although you should be able to impersonate a super admin by using a service account. Samples can be found here
Reference:
https://stackoverflow.com/a/60832262/14606045

Google Drive Api (.Net) return error after multiple folder creation

I'm developing a web app in MVC .Net (VS 2019 + Google Drive Api v3). We are using a service account consuming a shared folder from a simple google account.
We need to create a folder for each task of our students. We have 2000 students and they have average of 10 tasks per month. So We will have a lot of folders in our Google drive. Because of that I decided to make some tests with a console application and realized some errors after creating multiple folders. Someone know if Google Drive Api has a kind of limit on creation multiple folders?
Below is a console application to prove that with a print image.
namespace DriveQuickstart
{
class Program
{
static void Main(string[] args)
{
string[] Scopes = { DriveService.Scope.DriveReadonly, DriveService.Scope.DriveFile };
ServiceAccountCredential credential;
using (var stream =
new FileStream("key.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(Scopes)
.UnderlyingCredential as ServiceAccountCredential;
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Test App",
});
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
for (int i = 0; i < 50; i++)
{
body.Name = "Test_" + Guid.NewGuid().ToString();
body.Description = "Created by me!";
body.MimeType = "application/vnd.google-apps.folder";
body.Parents = new List<string> { "1hLsDTub8bhlVS2ax34P8wGx5RsD0n8MA" };
try
{
service.Files.Create(body).Execute();
Console.WriteLine("Folder " + (i+1).ToString() + " created.");
}
catch (Exception e)
{
Console.WriteLine("Error = " + e.InnerException.Message);
}
}
}
}
}
The inner exception Error: "Unable to read data from transport connection. It was forced to cancel by remote server".
Print2

Error when accessing outlook emails that need SSO login, using javax mail

I am trying to read outlook emails within my organization using javax mail, but I keep getting the error - "javax.mail.AuthenticationFailedException: Logon failure: unknown user name or bad password."
One thing to note is that there is a Single Sign On required while logging into outlook. So you have to enter the same credentials (emailID/password) twice.
The following is my code -
public static void main(String[] args) {
String host = "pop.outlook.com";
String mailStoreType = "pop3";
String username = "firstname.lastname#companyName.com";
String password = "password";
check(host, mailStoreType, username, password);
}
public static void check(String host, String mailStoreType, String user, String password)
{
try {
//create properties field
Properties props = new Properties();
props.setProperty("mail.pop3.ssl.enable", "true");
props.setProperty("mail.pop3.auth.plain.disable", "true");
props.put("mail.pop3.host", host);
props.put("mail.pop3.port", "995");
props.setProperty("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(props);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore(mailStoreType);
store.connect(host, user, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
Logger.logConsoleMessage("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
Logger.logConsoleMessage("---------------------------------");
Logger.logConsoleMessage("Email Number " + (i + 1));
Logger.logConsoleMessage("Subject: " + message.getSubject());
Logger.logConsoleMessage("From: " + message.getFrom()[0]);
Logger.logConsoleMessage("Text: " + message.getContent().toString());
}
//close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
After tweaking the above code a little, i am able to access a gmail account, which leads me to believe that the error above is because of the extra authentication required by SSO. Has anyone encountered this ever ? Any inputs would be greatly appreciated, Thanks!

Spring Security authentication ignoring password

In my project I have implemented Spring Security. It's checking whether username and password is correct or not. I want to authenticate only username but not password. How can I achieve this?
public UserDetails loadUserByUsername(String username) {
if (lan == null) {
// loadPasswordRules();
}
List<UserDetails> users = loadUsersByUsername(username);
if (users.size() == 0) {
throw new AuthenticationServiceException("Username " + username + " is invalid ");
}
UserDetails user = users.get(0); // contains no IRole[]
/** Raising exception since start and expiry of user is not valid. */
/** Raising exception since start and expiry of user is not valid. */
Date todayDate = new Date();
if ( !((todayDate).after(((User) user).getStartDate()) && (todayDate).before(((User) user).getExpiryDate())) ) {
throw new AuthenticationServiceException("User " + username + " account is expired.");
/* throw new LockedException("User " + username + " account is expired.");
throw new UsernameNotFoundException("User {" + username + "} account is expired."); SPRING_SECURITY_LAST_EXCEPTION.message */
}
/*if ( ((User) user).getLastSuccessLogin() != null) {
Calendar newDate = Calendar.getInstance();
newDate.setTime( todayDate );
newDate.add(Calendar.DAY_OF_YEAR, - lan.intValue());
Calendar oldDate = Calendar.getInstance();
oldDate.setTime( ((User) user).getLastSuccessLogin() );
if (newDate.after(oldDate)) {
lockUserAccount(username);
throw new AuthenticationServiceException("User " + username + " account is expired.");
}
}*/
Set<IRole> dbAuthsSet = new HashSet<IRole>();
if (enableAuthorities) {
dbAuthsSet.addAll(loadUserAuthorities(user.getUsername()));
}
List<IRole> dbAuths = new ArrayList<IRole>(dbAuthsSet);
if (dbAuths.size() == 0) {
throw new AuthenticationServiceException("Username " + username + " has no assigned roles.");
}
((User) user).setRoles(dbAuths);
return user;
}
You should be able to accomplish this creating a custom AuthenticationProvider implementation and configure your AuthenticationManager to use that.
You should create a Custom Filter to due with this. The Filter should extends class AbstractAuthenticationProcessingFilter and return a Custom Authentication object. Then the Authentication Provider will see it and do check only username which is return by the Filter. After completing everything, you must do configure the Filter to Spring Security context to make it works.
You also can see my complete example here : http://phuonghuynh.github.io/java/spring/security/2015/09/06/spring-security-multiple-authentication-providers.html

Google Contacts API v3 - How to update gender using C#.net?

I'm using Google Contacts API v3, I'm unable to update gender information for a contact
public static Contact UpdateContactName(ContactsRequest cr, Uri contactURL)
{
// First, retrieve the contact to update.
Contact contact = cr.Retrieve<Contact>(contactURL);
contact.Name.FullName = "New Name";
contact.Name.GivenName = "New";
contact.Name.FamilyName = "Name";
contact.ContactEntry.AddExtension(new Gender("male"));
try
{
Contact updatedContact = cr.Update(contact);
Console.WriteLine("Updated: " + updatedEntry.Updated.ToString())
return updatedContact;
}
catch (GDataVersionConflictException e)
{
// Etags mismatch: handle the exception.
}
return null;
}

Resources