WatchService循环运行两次,除非在调试模式下单步执行

时间:2013-07-10 02:32:32

标签: watchservice

我是WatchService的新手,我有一个非常有趣的错误。当我以正常模式(运行)运行我的代码时,它将循环遍历for(Watch事件:key1.pollEvents())循环两次并创建两个google calander事件但是如果我使用调试模式单步执行它只会添加一个事件。我从网上抓取了几乎所有的代码,试图了解WatchService的工作原理。我真的不知道我在这做什么,所以任何帮助都会很棒。这是我的代码

/*
 * Copyright (c) 2010 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.api.services.samples.calendar.cmdline;

import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.Lists;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Calendar;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Event.Reminders;
import com.google.api.services.calendar.model.EventDateTime;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.TimeZone;

/**
 * @author Yaniv Inbar
 */
public class myCalendar {

  /**
   * Be sure to specify the name of your application. If the application name is {@code null} or
   * blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
   */
  private static final String APPLICATION_NAME = "";

  /** Global instance of the HTTP transport. */
  private static HttpTransport HTTP_TRANSPORT;

  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();

  private static com.google.api.services.calendar.Calendar client;

  static final java.util.List<Calendar> addedCalendarsUsingBatch = Lists.newArrayList();

  /** Authorizes the installed application to access user's protected data. */
  private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(myCalendar.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
        || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
      System.out.println(
          "Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar "
          + "into calendar-cmdline-sample/src/main/resources/client_secrets.json");
      System.exit(1);
    }
    // set up file credential store
    FileCredentialStore credentialStore = new FileCredentialStore(
        new File(System.getProperty("user.home"), ".credentials/calendar.json"), JSON_FACTORY);
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets,
        Collections.singleton(CalendarScopes.CALENDAR)).setCredentialStore(credentialStore).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  }

  public static void main(String[] args) throws IOException {
    Path dir = Paths.get("C:\\Users\\kdevocht\\Dropbox\\Apps\\Attachments\\kjdevocht@gmail.com\\");
    WatchService service = FileSystems.getDefault().newWatchService();
    WatchKey key = dir.register(service, ENTRY_MODIFY);

    System.out.println("Watching directory: "+dir.toString());
    for(;;){
        WatchKey key1;
        try {
            key1 = service.take();
        } catch (InterruptedException x) {
            break;
        }

        for (WatchEvent<?> event: key1.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();

            if (kind == OVERFLOW) {
                continue;
            }

            WatchEvent<Path> ev = (WatchEvent<Path>)event;
            Path filename = ev.context();
            Path child = dir.resolve(filename);
            System.out.println("File: "+child.toString()+" modified.");
            try{
              try {
                try {

                  // initialize the transport
                  HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

                  // authorization
                  Credential credential = authorize();

                  // set up global Calendar instance
                  client = new com.google.api.services.calendar.Calendar.Builder(
                      HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
                      APPLICATION_NAME).build();

                  // run commands
                  Calendar calendar = client.calendars().get("kjdevocht@gmail.com").execute();
                  addEvent(calendar, child.toString());

                } catch (IOException e) {
                  System.err.println(e.getMessage());
                }
              } catch (Throwable t) {
                t.printStackTrace();
              }
              //System.exit(1);;
            }catch(Exception x){
                x.printStackTrace();
            }
        }

        boolean valid = key.reset();
        if (!valid) {
            break;
        }
/*        try {
          Thread.sleep(5000);
          } catch(InterruptedException e) {
          } */
    }

我认为这可能是一个时间问题,所以我尝试了一下睡眠尝试捕获,但这不起作用。

1 个答案:

答案 0 :(得分:0)

所以似乎一切正常。我正在使用notepad ++来编辑我正在观看的目录中的文件。经过一些研究后,似乎进行了两次修改,因此记录了两个事件。有些人建议存储文件的时间戳,只有在更改时才会做出反应,这似乎会过滤掉多个事件。对于我和我在做什么,我只是改变了观看创建活动。现在这很好用,没有任何问题