Twórz, aktualizuj lub usuwaj Kalendarz Google w Javie

Kalendarz Google to usługa planowania, która umożliwia tworzenie i śledzenie wydarzeń, takich jak spotkania. Możesz rejestrować wydarzenia w kalendarzu i otrzymywać przypomnienia o nadchodzących. Google umożliwia również programowe korzystanie z usługi kalendarza. W ten sposób możesz zarządzać swoimi wydarzeniami za pomocą Kalendarzy Google z poziomu swoich aplikacji. W tym artykule dowiesz się, jak programowo tworzyć, aktualizować i usuwać Kalendarz Google w Javie.

Java API do tworzenia i manipulowania kalendarzem Google

Do współpracy z usługą Google Calendar wykorzystamy Aspose.Email for Java. Jest to potężny interfejs API, który zapewnia szereg funkcji do przetwarzania wiadomości e-mail, pracy z klientami poczty e-mail i korzystania z usług Google do współpracy. Możesz pobrać interfejs API lub zainstalować go przy użyciu następujących konfiguracji Mavena.

Magazyn:

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>http://repository.aspose.com/repo/</url>
</repository>

Zależność:

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-email</artifactId>
    <version>22.3</version>
    <classifier>jdk16</classifier>
</dependency>

Utwórz Kalendarz Google w Javie

Zanim zaczniesz, musisz utworzyć projekt w Google Developer Console, aby Twoja aplikacja mogła komunikować się z usługami Google. Aby go utworzyć, możesz postępować zgodnie z tym przewodnikiem.

Teraz utwórz klasę pomocniczą o nazwie GoogleOAuthHelper, która zajmie się uwierzytelnianiem konta Google. Utwórz również klasę o nazwie OAuthUser do przechowywania informacji o użytkowniku. Poniżej znajduje się pełna implementacja obu klas.

public class OAuthUser {
        String email;
        String clientId;
        String clientSecret;
        String refreshToken;
    }
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.xml.bind.DatatypeConverter;

/**
 * <p>
 * Konsola programisty https://console.developers.google.com/projectselector/apis/credentials?pli=1 
 * Dokumentacja https://developers.google.com/identity/protocols/OAuth2InstalledApp
 * </p>
 */
class GoogleOAuthHelper {
    public static final String AUTHORIZATION_URL = "https://accounts.google.com/o/oauth2/v2/auth";
    public static final String TOKEN_REQUEST_URL = "https://oauth2.googleapis.com/token";
    public static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
    public static final String REDIRECT_TYPE = "code";
    public static final String SCOPE = "https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar" // Calendar
            + "+https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds%2F" // Contacts
            + "+https%3A%2F%2Fmail.google.com%2F"; // IMAP & SMTP

    static String createCodeChalange() {
        String verifierStr = UUID.randomUUID().toString() + "-" + UUID.randomUUID().toString();
        System.out.println("Code Verifier: " + verifierStr);

        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalAccessError(e.getMessage());
        }
        byte[] hash = digest.digest(verifierStr.getBytes(StandardCharsets.UTF_8));
        String base64Hash = DatatypeConverter.printBase64Binary(hash);

        base64Hash = base64Hash.split("=")[0];
        base64Hash = base64Hash.replace('+', '-').replace('/', '_');
        return base64Hash;
    }

    static String getAuthorizationCodeUrl(OAuthUser acc) {
        return getAuthorizationCodeUrl(acc, SCOPE, REDIRECT_URI, REDIRECT_TYPE);
    }

    static String getAuthorizationCodeUrl(OAuthUser acc, String scope, String redirectUri, String responseType) {
        System.out.println("---------------------------------------------------------");
        System.out.println("------------- OAuth 2.0 AuthorizationCodeUrl -------------");
        System.out.println("---------------------------------------------------------");
        System.out.println("Login: " + acc.email);
        String codeChallenge = createCodeChalange();

        String state = urlEncode(UUID.randomUUID().toString());
        String approveUrl = AUTHORIZATION_URL + "?client_id=" + acc.clientId + "&redirect_uri=" + redirectUri + "&response_type=" + responseType + "&scope=" + scope
                + "&code_challenge=" + codeChallenge + "&code_challenge_method=S256&state=" + state;

        System.out.println("Approve Url: " + approveUrl);
        return approveUrl;
    }

    static String urlEncode(String value) {
        try {
            return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            throw new IllegalAccessError(e.getMessage());
        }
    }

    static String urlDecode(String value) {
        try {
            return URLDecoder.decode(value, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            throw new IllegalAccessError(e.getMessage());
        }
    }

    static String getAccessTokenByAuthCode(String authorizationCode, String codeVerifier, OAuthUser user) {
        String encodedParameters = "client_id=" + urlEncode(user.clientId) + "&client_secret=" + urlEncode(user.clientSecret) + "&code=" + urlEncode(authorizationCode)
                + "&code_verifier=" + codeVerifier + "&redirect_uri=" + urlEncode(REDIRECT_URI) + "&grant_type=authorization_code";
        System.out.println("---------------------------------------------------------");
        System.out.println("------------- OAuth 2.0 AccessTokenByAuthCode -------------");
        System.out.println("---------------------------------------------------------");
        System.out.println("Authorization code: " + authorizationCode);

        String result = "";
        Map<String, String> token = geToken(encodedParameters);
       for (String key : token.keySet()) {
            System.out.println(key + ": " + token.get(key));
            if (key.equals("refresh_token")) {
                result = token.get(key);
            }
        }

        System.out.println("---------------------------------------------------------");

        return result;
    }

    static String getAccessTokenByRefreshToken(OAuthUser user) {
        String encodedParameters = "client_id=" + urlEncode(user.clientId) + "&client_secret=" + urlEncode(user.clientSecret) + "&refresh_token=" + urlEncode(user.refreshToken)
                + "&grant_type=refresh_token";
        System.out.println("---------------------------------------------------------");
        System.out.println("----------- OAuth 2.0 AccessTokenByRefreshToken -----------");
        System.out.println("---------------------------------------------------------");
        System.out.println("Login: " + user.email);

        String result = "";
        Map<String, String> token = geToken(encodedParameters);
       for (String key : token.keySet()) {
            System.out.println(key + ": " + token.get(key));
            if (key.equals("access_token")) {
                result = token.get(key);
            }
        }

        System.out.println("---------------------------------------------------------");

        return result;
    }

    static Map<String, String> geToken(String encodedParameters) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(TOKEN_REQUEST_URL).openConnection();
            connection.setRequestMethod("POST");

            byte[] requestData = encodedParameters.getBytes(StandardCharsets.UTF_8);

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + requestData.length);

            final OutputStream st = connection.getOutputStream();
            try {
                st.write(requestData, 0, requestData.length);
            } finally {
                st.flush();
                st.close();
            }

            connection.connect();

            if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST) {
                throw new IllegalAccessError("Operation failed: " + connection.getResponseCode() + "/" + connection.getResponseMessage() + "\r\nDetails:\r\n{2}"
                        + readInputStream(connection.getErrorStream()));
            }

            String responseText = readInputStream(connection.getInputStream());

            Map<String, String> result = new HashMap<String, String>();
            System.out.println(responseText);
            String[] strs = responseText.replace("{", "").replace("}", "").replace("\"", "").replace("\r", "").replace("\n", "").split(",");
           for (String sPair : strs) {
                String[] pair = sPair.split(":");
                String name = pair[0].trim().toLowerCase();
                String value = urlDecode(pair[1].trim());
                result.put(name, value);
            }

            return result;
        } catch (IOException e) {
            throw new IllegalAccessError(e.getMessage());
        }
    }

    static String readInputStream(InputStream is) {
        if (is == null)
            return "";

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder result = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        } catch (IOException e) {
            // ignorować
        }
        return result.toString();
    }
}

Po dokonaniu powyższej konfiguracji można przystąpić do pracy z usługą Kalendarz Google. Poniżej przedstawiono kroki tworzenia i aktualizowania Kalendarza Google w Javie.

Poniższy przykładowy kod pokazuje, jak utworzyć Kalendarz Google w Javie.

OAuthUser user = new OAuthUser();

// Ustaw clientId, clientSecret i e-mail 
user.clientId = "<<clientID>>"; 
user.clientSecret = "<<clientSecret>>"; 
user.email = "<<email>>";

// Musisz ręcznie pobrać AuthorizationCode za pomocą wygenerowanego AuthorizationCodeUrl
// Ustaw kod autoryzacji
String authorizationCode = "<<authCode>>";

// Skopiuj weryfikator kodu z danych wyjściowych poprzedniego kroku
// Ustaw codeVerifier
String codeVerifier = "<<codeVerifier>>";

// Zdobądź token odświeżania
String refreshToken = GoogleOAuthHelper.getAccessTokenByAuthCode(authorizationCode, codeVerifier, user);
user.refreshToken = refreshToken;

// Uzyskaj token dostępu
String accessToken = GoogleOAuthHelper.getAccessTokenByRefreshToken(user);

// Utwórz klienta Gmaila
try (IGmailClient client = GmailClient.getInstance(accessToken, user.email)) {
    // Wstaw, pobierz i zaktualizuj kalendarz
    Calendar calendar = new Calendar("Summary", "Description", "Location", "America/Los_Angeles");

    // Wstaw kalendarz i pobierz ten sam kalendarz za pomocą identyfikatora
    String id = client.createCalendar(calendar);
}

Zaktualizuj Kalendarz Google w Javie

Poniżej przedstawiono kroki, aby programowo zaktualizować Kalendarz Google w Javie.

Poniższy przykładowy kod pokazuje, jak zaktualizować kalendarz Google w Javie.

// Utwórz klienta Gmaila
try (IGmailClient client = GmailClient.getInstance(accessToken, email)) {
    // Określ identyfikator kalendarza
    String id ="<<calendar ID>>"
      
    // Pobierz kalendarz
    Calendar cal = client.fetchCalendar(id);

    // Zmień informacje w pobranym kalendarzu i zaktualizuj kalendarz
    cal.setDescription("New Description");
    cal.setLocation("New Location");
  
    // Zaktualizuj kalendarz
    client.updateCalendar(cal);
}

Usuń kalendarz Google w Javie

Możesz także usunąć konkretny kalendarz za pomocą Aspose.Email for Java. Poniżej przedstawiono kroki, aby wykonać tę operację.

Poniższy przykładowy kod pokazuje, jak usunąć Kalendarz Google w Javie.

// Utwórz klienta Gmaila
try (IGmailClient client = GmailClient.getInstance(accessToken, email)) {
    // Dostęp i usuwanie kalendarza z podsumowaniem zaczynającym się od „Podsumowania kalendarza”
    String summary = "Calendar summary";

    // Pobierz listę kalendarzy
    ExtendedCalendar[] lst = client.listCalendars();

   for (ExtendedCalendar extCal : lst) {
        // Usuń wybrane kalendarze
        if (extCal.getSummary().startsWith(summary))
            client.deleteCalendar(extCal.getId());
    }
}

Uzyskaj bezpłatną licencję API

Możesz uzyskać darmową tymczasową licencję na korzystanie z Aspose.Email for Java bez ograniczeń ewaluacyjnych.

Wniosek

W tym artykule nauczyłeś się programowo tworzyć Kalendarz Google w Javie. Ponadto widziałeś, jak aktualizować i usuwać określony Kalendarz Google w Javie. Poza tym możesz przejrzeć dokumentację, aby dowiedzieć się więcej o Aspose.Email dla Javy. Możesz także zadawać pytania za pośrednictwem naszego forum.

Zobacz też