com.google.api.client.util.DateTime Java Examples

The following examples show how to use com.google.api.client.util.DateTime. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void updateMetadata(SyncItem syncItem) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncItem.getLocalFile().get();
		File remoteFile = syncItem.getRemoteFile().get();
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		if (isGoogleAppsDocument(remoteFile)) {
			return;
		}
		LOGGER.log(Level.FINE, "Updating metadata of remote file " + remoteFile.getId() + " (" + syncItem.getPath() + ").");
		if (!options.isDryRun()) {
			File newRemoteFile = new File();
			newRemoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
			Drive.Files.Update updateRequest = drive.files().update(remoteFile.getId(), newRemoteFile).setFields("modifiedTime");
			File updatedFile = executeWithRetry(options, () -> updateRequest.execute());
			syncItem.setRemoteFile(Optional.of(updatedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example #2
Source File: BqIntegrationTest.java    From beast with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
public void shouldPushMessagesToBqActual() {
    TableId tableId = TableId.of("bqsinktest", "users");
    BqSink bqSink = new BqSink(authenticatedBQ(), tableId, new BQResponseParser(), gcsSinkHandler, bqRow);

    HashMap<String, Object> columns = new HashMap<>();
    columns.put("name", "someone_else");
    columns.put("age", 26);
    columns.put("location", 15123);
    columns.put("created_at", new DateTime(new Date()));

    HashMap<String, Object> route1 = new HashMap<>();
    route1.put("name", "route1");
    route1.put("position", "1");
    HashMap<String, Object> route2 = new HashMap<>();
    route2.put("name", "route2");
    route2.put("position", "2");

    columns.put("routes", Arrays.asList(route1, route2));

    Status push = bqSink.push(new Records(Arrays.asList(new Record(new OffsetInfo("default-topic", 0, 0, Instant.now().toEpochMilli()), columns))));

    assertTrue(push.isSuccess());
}
 
Example #3
Source File: StructuredData.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Override
protected com.google.api.services.cloudsearch.v1.model.Date doForward(Object a) {
  if (a instanceof com.google.api.services.cloudsearch.v1.model.Date) {
    return (com.google.api.services.cloudsearch.v1.model.Date) a;
  } else if (a instanceof Date) {
    return getApiDate((Date) a);
  } else if (a instanceof Long) {
    return getApiDate(new Date((long) a));
  } else if (a instanceof DateTime) {
    DateTime dt = (DateTime) a;
    Instant instant = Instant.ofEpochMilli(dt.getValue());
    ZoneOffset zone = ZoneOffset.ofTotalSeconds(checkedMultiply(dt.getTimeZoneShift(), 60));
    return getApiDate(instant.atZone(zone));
  } else if (a instanceof String) {
    return getApiDate(parseDateTime((String) a));
  }
  throw new NumberFormatException("Cannot convert \"" + a + "\" to Date");
}
 
Example #4
Source File: StructuredData.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Override
protected DateTime doForward(Object a) {
  if (a instanceof DateTime) {
    return (DateTime) a;
  }
  if (a instanceof Long) {
    return new DateTime((Long) a);
  }
  if (a instanceof String) {
    return toDateTime(parseDateTime((String) a));
  }
  if (a instanceof Date) {
    return new DateTime((Date) a);
  }
  throw new NumberFormatException("Cannot convert \"" + a + "\" to DateTime");
}
 
Example #5
Source File: ApiAsyncTask.java    From CalendarQuickStart with MIT License 6 votes vote down vote up
/**
 * Fetch a list of the next 10 events from the primary calendar.
 * @return List of Strings describing returned events.
 * @throws IOException
 */
private List<String> getDataFromApi() throws IOException {
    // List the next 10 events from the primary calendar.
    DateTime now = new DateTime(System.currentTimeMillis());
    List<String> eventStrings = new ArrayList<String>();
    Events events = mActivity.mService.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute();
    List<Event> items = events.getItems();

    for (Event event : items) {
        DateTime start = event.getStart().getDateTime();
        if (start == null) {
            // All-day events don't have start times, so just use
            // the start date.
            start = event.getStart().getDate();
        }
        eventStrings.add(
                String.format("%s (%s)", event.getSummary(), start));
    }
    return eventStrings;
}
 
Example #6
Source File: RowMapperTest.java    From beast with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnFieldsInColumnMapping() {
    ColumnMapping fieldMappings = new ColumnMapping();
    fieldMappings.put("1", "order_number_field");
    fieldMappings.put("2", "order_url_field");
    fieldMappings.put("3", "order_details_field");
    fieldMappings.put("4", "created_at");
    fieldMappings.put("5", "order_status");
    fieldMappings.put("14", getDateColumnMapping());

    Map<String, Object> fields = new RowMapper(fieldMappings).map(dynamicMessage);

    assertEquals("order-1", fields.get("order_number_field"));
    assertEquals("order-url", fields.get("order_url_field"));
    assertEquals("order-details", fields.get("order_details_field"));
    assertEquals(new DateTime(nowMillis), fields.get("created_at"));
    assertEquals("COMPLETED", fields.get("order_status"));
    Map dateFields = (Map) fields.get("order_date_field");
    assertEquals(1996, dateFields.get("year"));
    assertEquals(11, dateFields.get("month"));
    assertEquals(21, dateFields.get("day"));
    assertEquals(fieldMappings.size(), fields.size());
}
 
Example #7
Source File: CloudEntity.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
protected EntityDto getEntityDto() {
    EntityDto co = new EntityDto();
    co.setId(id);
    if (createdAt != null) {
        co.setCreatedAt(new DateTime(createdAt));
    }
    co.setCreatedBy(createdBy);
    co.setKindName(kindName);
    if (updatedAt != null) {
        co.setUpdatedAt(new DateTime(updatedAt));
    }
    co.setUpdatedBy(updatedBy);
    co.setProperties(properties);
    co.setOwner(owner);
    return co;
}
 
Example #8
Source File: YoutubeVideoDeserializer.java    From streams with Apache License 2.0 6 votes vote down vote up
/**
 * Given the raw JsonNode, construct a video snippet object.
 * @param node JsonNode
 * @return VideoSnippet
 */
private VideoSnippet buildSnippet(JsonNode node) {
  VideoSnippet snippet = new VideoSnippet();
  JsonNode snippetNode = node.get("snippet");

  snippet.setChannelId(snippetNode.get("channelId").asText());
  snippet.setChannelTitle(snippetNode.get("channelTitle").asText());
  snippet.setDescription(snippetNode.get("description").asText());
  snippet.setTitle(snippetNode.get("title").asText());
  snippet.setPublishedAt(new DateTime(snippetNode.get("publishedAt").get("value").asLong()));

  ThumbnailDetails thumbnailDetails = new ThumbnailDetails();
  for (JsonNode t : snippetNode.get("thumbnails")) {
    Thumbnail thumbnail = new Thumbnail();

    thumbnail.setHeight(t.get("height").asLong());
    thumbnail.setUrl(t.get("url").asText());
    thumbnail.setWidth(t.get("width").asLong());

    thumbnailDetails.setDefault(thumbnail);
  }

  snippet.setThumbnails(thumbnailDetails);

  return snippet;
}
 
Example #9
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void store(SyncDirectory syncDirectory) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncDirectory.getLocalFile().get();
		File remoteFile = new File();
		remoteFile.setName(localFile.getName());
		remoteFile.setMimeType(MIME_TYPE_FOLDER);
		remoteFile.setParents(createParentReferenceList(syncDirectory));
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		LOGGER.log(Level.FINE, "Inserting new directory '" + syncDirectory.getPath() + "'.");
		if (!options.isDryRun()) {
			File insertedFile = executeWithRetry(options, () -> drive.files().create(remoteFile).execute());
			syncDirectory.setRemoteFile(Optional.of(insertedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example #10
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void store(SyncDirectory syncDirectory) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncDirectory.getLocalFile().get();
		File remoteFile = new File();
		remoteFile.setName(localFile.getName());
		remoteFile.setMimeType(MIME_TYPE_FOLDER);
		remoteFile.setParents(createParentReferenceList(syncDirectory));
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		LOGGER.log(Level.FINE, "Inserting new directory '" + syncDirectory.getPath() + "'.");
		if (!options.isDryRun()) {
			File insertedFile = executeWithRetry(options, () -> drive.files().create(remoteFile).execute());
			syncDirectory.setRemoteFile(Optional.of(insertedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example #11
Source File: StructuredDataTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void dateConverter_fromDateTime() throws IOException {
  setupConfig.initConfig(new Properties());
  when(mockIndexingService.getSchema()).thenReturn(new Schema());
  StructuredData.initFromConfiguration(mockIndexingService);

  Date expected = new Date().setYear(2018).setMonth(8).setDay(8);

  Converter<Object, Date> converter = StructuredData.DATE_CONVERTER;
  for (String dateString : new String[] {
        // API Date class doesn't have a time zone, so anything will match.
        "2018-08-08T23:48:17-11:00", // 2018-08-09 in most local time zones.
        "2018-08-08T00:01:00+14:00", // 2018-08-07 in most local time zones.
        "2018-08-08",
      }) {
    try {
      collector.checkThat(dateString, converter.convert(new DateTime(dateString)),
          equalTo(expected));
    } catch (NumberFormatException e) {
      collector.addError(e);
    }
  }
}
 
Example #12
Source File: GCalPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a new Google Calendar Entry for each <code>item</code> and adds
 * it to the processing queue. The entries' title will either be the items
 * name or <code>alias</code> if it is <code>!= null</code>.
 *
 * The new Calendar Entry will contain a single command to be executed e.g.<br>
 * <p>
 * <code>send &lt;item.name&gt; &lt;item.state&gt;</code>
 * </p>
 *
 * @param item the item which state should be persisted.
 * @param alias the alias under which the item should be persisted.
 */
@Override
public void store(final Item item, final String alias) {
    if (initialized) {
        String newAlias = alias != null ? alias : item.getName();

        Event event = new Event();
        event.setSummary("[PresenceSimulation] " + newAlias);
        event.setDescription(String.format(executeScript, item.getName(), item.getState().toString()));
        Date now = new Date();
        Date startDate = new Date(now.getTime() + 3600000L * 24 * offset);
        Date endDate = startDate;
        DateTime start = new DateTime(startDate);
        event.setStart(new EventDateTime().setDateTime(start));
        DateTime end = new DateTime(endDate);
        event.setEnd(new EventDateTime().setDateTime(end));

        entries.offer(event);

        logger.trace("added new entry '{}' for item '{}' to upload queue", event.getSummary(), item.getName());
    } else {
        logger.debug(
                "GCal PresenceSimulation Service isn't initialized properly! No entries will be uploaded to your Google Calendar");
    }
}
 
Example #13
Source File: CheckupReminders.java    From Crimson with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch a list of the next 10 events from the primary calendar.
 *
 * @return List of Strings describing returned events.
 * @throws IOException
 */
private List<String> getDataFromApi() throws IOException {
    // List the next 10 events from the primary calendar.
    DateTime now = new DateTime(System.currentTimeMillis());
    List<String> eventStrings = new ArrayList<String>();
    Events events = mService.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute();
    List<Event> items = events.getItems();

    for (Event event : items) {
        DateTime start = event.getStart().getDateTime();
        if (start == null) {
            // All-day events don't have start times, so just use
            // the start date.
            start = event.getStart().getDate();
        }
        eventStrings.add(
                String.format("%s (%s)", event.getSummary(), start));
    }
    return eventStrings;
}
 
Example #14
Source File: AnnouncementThread.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
private List<Event> getEvents(GuildSettings gs, CalendarData cd, Calendar service, Announcement a) {
	if (!allEvents.containsKey(gs.getGuildID())) {
		Logger.getLogger().announcement("getting events for guild...", gs.getGuildID() + "", a.getAnnouncementId() + "", "N/a");
		try {
			Events events = service.events().list(cd.getCalendarAddress())
					.setMaxResults(15)
					.setTimeMin(new DateTime(System.currentTimeMillis()))
					.setOrderBy("startTime")
					.setSingleEvents(true)
					.setShowDeleted(false)
					.execute();
			List<Event> items = events.getItems();
			allEvents.put(gs.getGuildID(), items);
		} catch (IOException e) {
			Logger.getLogger().exception(null, "Failed to get events list! 01ae2304 | Guild: " + gs.getGuildID() + " | Announcement: " + a.getAnnouncementId(), e, true, this.getClass());
			return new ArrayList<>();
		}
	}
	return allEvents.get(gs.getGuildID());
}
 
Example #15
Source File: PubsubClient.java    From beam with Apache License 2.0 6 votes vote down vote up
/**
 * Return timestamp as ms-since-unix-epoch corresponding to {@code timestamp}. Return {@literal
 * null} if no timestamp could be found. Throw {@link IllegalArgumentException} if timestamp
 * cannot be recognized.
 */
@Nullable
private static Long asMsSinceEpoch(@Nullable String timestamp) {
  if (Strings.isNullOrEmpty(timestamp)) {
    return null;
  }
  try {
    // Try parsing as milliseconds since epoch. Note there is no way to parse a
    // string in RFC 3339 format here.
    // Expected IllegalArgumentException if parsing fails; we use that to fall back
    // to RFC 3339.
    return Long.parseLong(timestamp);
  } catch (IllegalArgumentException e1) {
    // Try parsing as RFC3339 string. DateTime.parseRfc3339 will throw an
    // IllegalArgumentException if parsing fails, and the caller should handle.
    return DateTime.parseRfc3339(timestamp).getValue();
  }
}
 
Example #16
Source File: GoogleCloudStorageMockitoTest.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
/**
 * Helper for the shared boilerplate of setting up the low-level "API objects" like
 * mockStorage.objects(), etc., that is common between test cases targeting {@code
 * GoogleCloudStorage.open(StorageResourceId)}.
 *
 * @param size {@link StorageObject} size
 * @param encoding {@link StorageObject} encoding
 */
private void setUpBasicMockBehaviorForOpeningReadChannel(long size, String encoding)
    throws IOException {
  when(mockStorage.objects()).thenReturn(mockStorageObjects);
  when(mockStorageObjects.get(eq(BUCKET_NAME), eq(OBJECT_NAME)))
      .thenReturn(mockStorageObjectsGet);
  when(mockClientRequestHelper.getRequestHeaders(eq(mockStorageObjectsGet)))
      .thenReturn(mockHeaders);
  when(mockStorageObjectsGet.execute())
      .thenReturn(
          new StorageObject()
              .setBucket(BUCKET_NAME)
              .setName(OBJECT_NAME)
              .setTimeCreated(new DateTime(11L))
              .setUpdated(new DateTime(12L))
              .setSize(BigInteger.valueOf(size))
              .setContentEncoding(encoding)
              .setGeneration(1L)
              .setMetageneration(1L));
}
 
Example #17
Source File: GoogleCalendarImporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private static EventDateTime getEventDateTime(CalendarEventModel.CalendarEventTime dateTime) {
  if (dateTime == null) {
    return null;
  }

  EventDateTime eventDateTime = new EventDateTime();

  // google's APIs want millisecond from epoch, and the timezone offset in minutes.
  if (dateTime.isDateOnly()) {
    eventDateTime.setDate(new DateTime(true,
        dateTime.getDateTime().toEpochSecond() * 1000,
        dateTime.getDateTime().getOffset().getTotalSeconds() / 60));
  } else {
    eventDateTime.setDateTime(new DateTime(
        dateTime.getDateTime().toEpochSecond() * 1000,
        dateTime.getDateTime().getOffset().getTotalSeconds() / 60));
  }

  return eventDateTime;
}
 
Example #18
Source File: SubscriptionsDb.java    From SkyTube with GNU General Public License v3.0 6 votes vote down vote up
private void setupRetrievalTimestamp(SQLiteDatabase db) {
    List<YouTubeVideo> videos = extractVideos(db.rawQuery(FIND_EMPTY_RETRIEVAL_TS, null), false);
    int count = 0;
    for (YouTubeVideo video : videos) {
        DateTime dateTime = video.getPublishDate();
        if (dateTime != null) {
            ContentValues values = new ContentValues();
            values.put(SubscriptionsVideosTable.COL_PUBLISH_TS, dateTime.getValue());
            values.put(SubscriptionsVideosTable.COL_RETRIEVAL_TS, dateTime.getValue());
            int updateCount = db.update(
                    SubscriptionsVideosTable.TABLE_NAME,
                    values,
                    SubscriptionsVideosTable.COL_YOUTUBE_VIDEO_ID_EQUALS_TO,
                    new String[]{video.getId()});
            Logger.i(this,"updating " + video.getId() + " with publish date:" + dateTime + " -> " + updateCount);
            count += updateCount;
        }
    }
    Logger.i(this, "From " + videos.size() + ", retrieval timestamp filled for " + count);
}
 
Example #19
Source File: GoogleDrive.java    From google-drive-ftp-adapter with GNU Lesser General Public License v3.0 6 votes vote down vote up
private File mkdir_impl(GFile gFile, int retry) {
    try {
        // New file
        logger.info("Creating new directory...");
        File file = new File();
        file.setMimeType("application/vnd.google-apps.folder");
        file.setName(gFile.getName());
        file.setModifiedTime(new DateTime(System.currentTimeMillis()));
        file.setParents(new ArrayList<>(gFile.getParents()));
        file = drive.files().create(file).setFields(REQUEST_FILE_FIELDS).execute();
        logger.info("Directory created successfully: " + file.getId());
        return file;
    } catch (IOException e) {
        if (retry > 0) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                throw new RuntimeException(e1);
            }
            logger.warn("Uploading file failed. Retrying... '" + gFile.getId());
            return mkdir_impl(gFile, --retry);
        }
        throw new RuntimeException("Exception uploading file " + gFile.getId(), e);
    }
}
 
Example #20
Source File: YouTubeVideo.java    From SkyTube with GNU General Public License v3.0 6 votes vote down vote up
public YouTubeVideo(String id, String title, String description, long durationInSeconds, YouTubeChannel channel, long viewCount,
Long publishDate, Boolean publishDateExact, String thumbnailUrl) {
     this.id = id;
     this.title = title;
     this.description = description;
     setDurationInSeconds((int) durationInSeconds);
     this.setViewCount(BigInteger.valueOf(viewCount));
     if (publishDate != null) {
         this.setPublishTimestamp(publishDate);
         this.publishDate = new DateTime(publishDate);
     }
     this.setPublishTimestampExact(publishDateExact);
     this.thumbnailMaxResUrl = thumbnailUrl;
     this.thumbnailUrl = thumbnailUrl;
     this.channel = channel;
     this.thumbsUpPercentage = -1;
 }
 
Example #21
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void updateFile(SyncItem syncItem) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncItem.getLocalFile().get();
		File remoteFile = syncItem.getRemoteFile().get();
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		if (isGoogleAppsDocument(remoteFile)) {
			return;
		}
		LOGGER.log(Level.INFO, "Updating file " + remoteFile.getId() + " (" + syncItem.getPath() + ").");
		if (!options.isDryRun()) {
			Drive.Files.Update updateRequest = drive.files().update(remoteFile.getId(), remoteFile, new FileContent(determineMimeType(localFile), localFile));
			//updateRequest.setModifiedDate(true);
			File updatedFile = executeWithRetry(options, () -> updateRequest.execute());
			syncItem.setRemoteFile(Optional.of(updatedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example #22
Source File: DriveImporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String importSingleFile(
    UUID jobId, Drive driveInterface, DigitalDocumentWrapper file, String parentId)
    throws IOException {
  InputStreamContent content =
      new InputStreamContent(
          null, jobStore.getStream(jobId, file.getCachedContentId()).getStream());
  DtpDigitalDocument dtpDigitalDocument = file.getDtpDigitalDocument();
  File driveFile = new File().setName(dtpDigitalDocument.getName());
  if (!Strings.isNullOrEmpty(parentId)) {
    driveFile.setParents(ImmutableList.of(parentId));
  }
  if (!Strings.isNullOrEmpty(dtpDigitalDocument.getDateModified())) {
    driveFile.setModifiedTime(DateTime.parseRfc3339(dtpDigitalDocument.getDateModified()));
  }
  if (!Strings.isNullOrEmpty(file.getOriginalEncodingFormat())
      && file.getOriginalEncodingFormat().startsWith("application/vnd.google-apps.")) {
    driveFile.setMimeType(file.getOriginalEncodingFormat());
  }
  return driveInterface.files().create(driveFile, content).execute().getId();
}
 
Example #23
Source File: GoogleCalendarEventModel.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private EventDateTime getEnd() {
    final EventDateTime end = new EventDateTime();

    if (endTime == null) {
        end.setDate(DateTime.parseRfc3339(endDate));
    } else {
        end.setDateTime(DateTime.parseRfc3339(endDate + "T" + endTime));
    }

    return end;
}
 
Example #24
Source File: Utils.java    From java-samples with Apache License 2.0 5 votes vote down vote up
/** Creates a test event. */
public static Event createTestEvent(Calendar client, String summary) throws IOException {
  Date oneHourFromNow = Utils.getRelativeDate(java.util.Calendar.HOUR, 1);
  Date twoHoursFromNow = Utils.getRelativeDate(java.util.Calendar.HOUR, 2);
  DateTime start = new DateTime(oneHourFromNow, TimeZone.getTimeZone("UTC"));
  DateTime end = new DateTime(twoHoursFromNow, TimeZone.getTimeZone("UTC"));

  Event event = new Event().setSummary(summary)
      .setReminders(new Reminders().setUseDefault(false))
      .setStart(new EventDateTime().setDateTime(start))
      .setEnd(new EventDateTime().setDateTime(end));
  return client.events().insert("primary", event).execute();
}
 
Example #25
Source File: CalendarQuickstart.java    From java-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws IOException, GeneralSecurityException {
    // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();

    // List the next 10 events from the primary calendar.
    DateTime now = new DateTime(System.currentTimeMillis());
    Events events = service.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute();
    List<Event> items = events.getItems();
    if (items.isEmpty()) {
        System.out.println("No upcoming events found.");
    } else {
        System.out.println("Upcoming events");
        for (Event event : items) {
            DateTime start = event.getStart().getDateTime();
            if (start == null) {
                start = event.getStart().getDate();
            }
            System.out.printf("%s (%s)\n", event.getSummary(), start);
        }
    }
}
 
Example #26
Source File: TaskInfo.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public TaskInfo(TaskList taskList) {
    this.etag = taskList.getEtag();
    this.id = taskList.getId();
    this.kind = taskList.getKind();
    this.selfLink = taskList.getSelfLink();
    this.title = taskList.getTitle();
    if (taskList.getUpdated() != null) {
        this.updated = taskList.getUpdated().toString();
    } else {
        this.updated = new DateTime(new Date()).toString();
    }
}
 
Example #27
Source File: GoogleStorageAttributesFinderFeature.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
protected PathAttributes toAttributes(final StorageObject object) {
    final PathAttributes attributes = new PathAttributes();
    if(object.getSize() != null) {
        attributes.setSize(object.getSize().longValue());
    }
    final DateTime lastmodified = object.getTimeCreated();
    if(lastmodified != null) {
        attributes.setModificationDate(lastmodified.getValue());
    }
    attributes.setStorageClass(object.getStorageClass());
    if(StringUtils.isNotBlank(object.getEtag())) {
        attributes.setETag(object.getEtag());
    }
    // The content generation of this object. Used for object versioning.
    // attributes.setVersionId(String.valueOf(object.getGeneration()));
    // Archived versions of objects have a `timeDeleted` property.
    // attributes.setDuplicate(object.getTimeDeleted() != null);
    // if(object.getTimeDeleted() != null) {
    //     attributes.setCustom(Collections.singletonMap(KEY_DELETE_MARKER, Boolean.TRUE.toString()));
    // }
    if(object.getKmsKeyName() != null) {
        attributes.setEncryption(new Encryption.Algorithm("AES256",
            object.getKmsKeyName()) {
            @Override
            public String getDescription() {
                return String.format("SSE-KMS (%s)", key);
            }
        });
    }
    attributes.setChecksum(Checksum.parse(object.getMd5Hash()));
    if(object.getMetadata() != null) {
        attributes.setMetadata(object.getMetadata());
    }
    return attributes;
}
 
Example #28
Source File: GoogleDrive.java    From google-drive-ftp-adapter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Touches the file, changing the name or date modified
 *
 * @param fileId          the file id to patch
 * @param newName         the new file name
 * @param newLastModified the new last modified date
 * @return the patched file
 */
public GFile patchFile(String fileId, String newName, long newLastModified) {
    File patch = new File();
    if (newName != null) {
        patch.setName(newName);
    }
    if (newLastModified > 0) {
        patch.setModifiedTime(new DateTime(newLastModified));
    }
    return create(patchFile(fileId, patch, 3));
}
 
Example #29
Source File: HolidayEventsLoader.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private List<Event> getCalendarEvents(String Calendar_id, long start, long end) throws Exception {
  GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(keyPath)).createScoped(SCOPES);
  Calendar service =
      new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("thirdeye").build();
  return service.events()
      .list(Calendar_id)
      .setTimeMin(new DateTime(start))
      .setTimeMax(new DateTime(end))
      .execute()
      .getItems();
}
 
Example #30
Source File: GoogleDriveFsHelperTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public void testPagination() throws IOException, FileBasedHelperException {
  State state = new State();
  state.appendToSetProp(GoogleDriveFileSystem.PAGE_SIZE, Integer.toString(1));

  GoogleDriveFsHelper fsHelper = new GoogleDriveFsHelper(state, client, Closer.create());
  List listRequest = mock(List.class);
  when(files.list()).thenReturn(listRequest);
  when(listRequest.setPageSize(anyInt())).thenReturn(listRequest);
  when(listRequest.setFields(anyString())).thenReturn(listRequest);
  when(listRequest.setQ(anyString())).thenReturn(listRequest);
  when(listRequest.setPageToken(anyString())).thenReturn(listRequest);

  int paginatedCalls = 5;
  final MutableInt i = new MutableInt(paginatedCalls);
  final File file = new File();
  file.setId("testId");
  file.setModifiedTime(new DateTime(System.currentTimeMillis()));

  when(listRequest.execute()).thenAnswer(new Answer<FileList>() {

    @Override
    public FileList answer(InvocationOnMock invocation) throws Throwable {
      FileList fileList = new FileList();
      fileList.setFiles(ImmutableList.of(file));
      if (i.intValue() > 0) {
        fileList.setNextPageToken("token");
        i.decrement();
      }
      return fileList;
    }
  });

  fsHelper.ls("test");

  int expectedCalls = 1 + paginatedCalls;
  verify(listRequest, times(expectedCalls)).execute();
}