Criar aplicativos Java com o Microsoft Graph
Este tutorial ensina como criar um aplicativo de console Java que usa a API do Microsoft Graph para recuperar informações de calendário de um usuário.This tutorial teaches you how to build a Java console app that uses the Microsoft Graph API to retrieve calendar information for a user.
Dica
Se preferir baixar o tutorial concluído, você poderá baixar ou clonar o repositório do GitHub.If you prefer to just download the completed tutorial, you can download or clone the GitHub repository.
Pré-requisitosPrerequisites
Antes de iniciar este tutorial, você deve ter o Java se Development Kit (JDK) e o gradle instalados em sua máquina de desenvolvimento.Before you start this tutorial, you should have the Java SE Development Kit (JDK) and Gradle installed on your development machine. Se você não tiver o JDK ou o gradle, visite os links anteriores para obter opções de download.If you do not have the JDK or Gradle, visit the previous links for download options.
Você também deve ter uma conta pessoal da Microsoft com uma caixa de correio no Outlook.com ou uma conta corporativa ou de estudante da Microsoft.You should also have either a personal Microsoft account with a mailbox on Outlook.com, or a Microsoft work or school account. Se você não tem uma conta da Microsoft, há algumas opções para obter uma conta gratuita:If you don't have a Microsoft account, there are a couple of options to get a free account:
- Você pode se inscrever para uma nova conta pessoal da Microsoft.You can sign up for a new personal Microsoft account.
- Você pode se inscrever no programa para desenvolvedores do office 365 para obter uma assinatura gratuita do Office 365.You can sign up for the Office 365 Developer Program to get a free Office 365 subscription.
Observação
Este tutorial foi escrito com OpenJDK versão 14.0.0.36 e gradle 6.7.1.This tutorial was written with OpenJDK version 14.0.0.36 and Gradle 6.7.1. As etapas deste guia podem funcionar com outras versões, mas que não foram testadas.The steps in this guide may work with other versions, but that has not been tested.
ComentáriosFeedback
Forneça comentários sobre este tutorial no repositório do GitHub.Please provide any feedback on this tutorial in the GitHub repository.
Criar um aplicativo de console Java
Nesta seção, você criará um aplicativo básico Java console.In this section you'll create a basic Java console app.
Abra sua interface de linha de comando (CLI) em um diretório onde você deseja criar o projeto.Open your command-line interface (CLI) in a directory where you want to create the project. Execute o seguinte comando para criar um novo projeto Gradle.Run the following command to create a new Gradle project.
gradle init --dsl groovy --test-framework junit --type java-application --project-name graphtutorial --package graphtutorial
Depois que o projeto for criado, verifique se ele funciona executando o seguinte comando para executar o aplicativo em sua CLI.Once the project is created, verify that it works by running the following command to run the app in your CLI.
./gradlew --console plain run
Se funcionar, o aplicativo deverá ter
Hello World.
saída .If it works, the app should outputHello World.
.
Instalar dependênciasInstall dependencies
Antes de continuar, adicione algumas dependências adicionais que você usará mais tarde.Before moving on, add some additional dependencies that you will use later.
- Biblioteca de clientes do Azure Identity para Java autenticar o usuário e adquirir tokens de acesso.Azure Identity client library for Java to authenticate the user and acquire access tokens.
- Microsoft Graph SDK para Java fazer chamadas para o Microsoft Graph.Microsoft Graph SDK for Java to make calls to the Microsoft Graph.
Abra ./build.gradle.Open ./build.gradle. Atualize
dependencies
a seção para adicionar essas dependências.Update thedependencies
section to add those dependencies.dependencies { // This dependency is used by the application. implementation 'com.google.guava:guava:28.2-jre' // Use JUnit test framework testImplementation 'junit:junit:4.12' implementation 'com.microsoft.azure:msal4j:1.8.0' implementation 'com.microsoft.graph:microsoft-graph:2.4.1' implementation 'org.slf4j:slf4j-nop:1.8.0-beta4' }
Adicione o seguinte ao final de ./build.gradle.Add the following to the end of ./build.gradle.
run { standardInput = System.in }
Na próxima vez que você criar o projeto, Gradle baixará essas dependências.The next time you build the project, Gradle will download those dependencies.
Design do aplicativoDesign the app
Abra o arquivo ./src/main/java/graphtutorial/App.java e substitua seu conteúdo pelo seguinte.Open the ./src/main/java/graphtutorial/App.java file and replace its contents with the following.
package graphtutorial; import java.util.InputMismatchException; import java.util.Scanner; /** * Graph Tutorial * */ public class App { public static void main(String[] args) { System.out.println("Java Graph Tutorial"); System.out.println(); Scanner input = new Scanner(System.in); int choice = -1; while (choice != 0) { System.out.println("Please choose one of the following options:"); System.out.println("0. Exit"); System.out.println("1. Display access token"); System.out.println("2. View this week's calendar"); System.out.println("3. Add an event"); try { choice = input.nextInt(); } catch (InputMismatchException ex) { // Skip over non-integer input } input.nextLine(); // Process user choice switch(choice) { case 0: // Exit the program System.out.println("Goodbye..."); break; case 1: // Display access token break; case 2: // List the calendar break; case 3: // Create a new event break; default: System.out.println("Invalid choice"); } } input.close(); } }
Isso implementa um menu básico e lê a escolha do usuário na linha de comando.This implements a basic menu and reads the user's choice from the command line.
Registrar o aplicativo no portal
Neste exercício, você criará um novo aplicativo do Azure AD usando o centro de administração do Azure Active Directory.In this exercise you will create a new Azure AD application using the Azure Active Directory admin center.
Abra um navegador, navegue até o centro de administração do Azure Active Directory e faça logon usando uma conta pessoal (também conhecida como conta da Microsoft) ou Conta Corporativa ou de Estudante.Open a browser and navigate to the Azure Active Directory admin center and login using a personal account (aka: Microsoft Account) or Work or School Account.
Selecione Azure Active Directory na navegação esquerda e selecione Registros de aplicativos em Gerenciar.Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.
Selecione Novo registro.Select New registration. Na página Registrar um aplicativo, defina os valores da seguinte forma.On the Register an application page, set the values as follows.
- Defina Nome para
Java Graph Tutorial
.Set Name toJava Graph Tutorial
. - Defina Tipos de conta com suporte para Contas em qualquer diretório organizacional e contas pessoais da Microsoft.Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts.
- Em URI de redirecionamento, altere o menu suspenso para cliente público (Desktop & móvel) e defina
https://login.microsoftonline.com/common/oauth2/nativeclient
o valor como.Under Redirect URI, change the dropdown to Public client (mobile & desktop), and set the value tohttps://login.microsoftonline.com/common/oauth2/nativeclient
.
- Defina Nome para
Escolha Registrar.Choose Register. Na página tutorial do Java Graph , copie o valor da ID do aplicativo (cliente) e salve-o, você precisará dele na próxima etapa.On the Java Graph Tutorial page, copy the value of the Application (client) ID and save it, you will need it in the next step.
Selecione Autenticação em Gerenciar.Select Authentication under Manage. Localize a seção Configurações avançadas e altere o aplicativo tratar como um cliente público //para Sime, em seguida, escolha salvar.Locate the Advanced settings section and change the Treat application as a public client toggle to Yes, then choose Save.
Adicionar autenticação do Azure AD
Neste exercício, você estenderá o aplicativo do exercício anterior para dar suporte à autenticação com o Azure AD.In this exercise you will extend the application from the previous exercise to support authentication with Azure AD. Isso é necessário para obter o token de acesso OAuth necessário para chamar o Microsoft Graph.This is required to obtain the necessary OAuth access token to call the Microsoft Graph. Nesta etapa, você integrará a Biblioteca de Autenticação da Microsoft (MSAL) para Java ao aplicativo.In this step you will integrate the Microsoft Authentication Library (MSAL) for Java into the application.
Crie um novo diretório chamado graphtutorial no diretório ./src/main/resources.Create a new directory named graphtutorial in the ./src/main/resources directory.
Crie um novo arquivo no diretório ./src/main/resources/graphtutorial chamado oAuth.properties e adicione o seguinte texto nesse arquivo.Create a new file in the ./src/main/resources/graphtutorial directory named oAuth.properties, and add the following text in that file. Substitua
YOUR_APP_ID_HERE
pela ID do aplicativo que você criou no portal do Azure.ReplaceYOUR_APP_ID_HERE
with the application ID you created in the Azure portal.app.id=YOUR_APP_ID_HERE app.scopes=User.Read,MailboxSettings.Read,Calendars.ReadWrite
O valor de
app.scopes
contém os escopos de permissão que o aplicativo requer.The value ofapp.scopes
contains the permission scopes the application requires.- User.Read permite que o aplicativo acesse o perfil do usuário.User.Read allows the app to access the user's profile.
- MailboxSettings.Read permite que o aplicativo acesse configurações da caixa de correio do usuário, incluindo o fuso horário configurado pelo usuário.MailboxSettings.Read allows the app to access settings from the user's mailbox, including the user's configured time zone.
- Calendars.ReadWrite permite que o aplicativo liste o calendário do usuário e adicione novos eventos ao calendário.Calendars.ReadWrite allows the app to list the user's calendar and add new events to the calendar.
Importante
Se você estiver usando o controle de origem, como git, agora seria um bom momento para excluir o arquivo oAuth.properties do controle de origem para evitar o vazamento inadvertida da ID do aplicativo.If you're using source control such as git, now would be a good time to exclude the oAuth.properties file from source control to avoid inadvertently leaking your app ID.
Abra App.java e adicione as instruções
import
a seguir.Open App.java and add the followingimport
statements.import java.io.IOException; import java.util.Properties;
Adicione o código a seguir pouco antes
Scanner input = new Scanner(System.in);
da linha para carregar o arquivo oAuth.properties.Add the following code just before theScanner input = new Scanner(System.in);
line to load the oAuth.properties file.// Load OAuth settings final Properties oAuthProperties = new Properties(); try { oAuthProperties.load(App.class.getResourceAsStream("oAuth.properties")); } catch (IOException e) { System.out.println("Unable to read OAuth configuration. Make sure you have a properly formatted oAuth.properties file. See README for details."); return; } final String appId = oAuthProperties.getProperty("app.id"); final String[] appScopes = oAuthProperties.getProperty("app.scopes").split(",");
Implementar loginImplement sign-in
Crie um novo arquivo no diretório ./graphtutorial/src/main/java/graphtutorial chamado Graph.java e adicione o código a seguir.Create a new file in the ./graphtutorial/src/main/java/graphtutorial directory named Graph.java and add the following code.
package graphtutorial; import java.net.URL; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.LinkedList; import java.util.List; import java.util.Set; import okhttp3.Request; import com.azure.identity.DeviceCodeCredential; import com.azure.identity.DeviceCodeCredentialBuilder; import com.microsoft.graph.authentication.TokenCredentialAuthProvider; import com.microsoft.graph.logger.DefaultLogger; import com.microsoft.graph.logger.LoggerLevel; import com.microsoft.graph.models.Attendee; import com.microsoft.graph.models.DateTimeTimeZone; import com.microsoft.graph.models.EmailAddress; import com.microsoft.graph.models.Event; import com.microsoft.graph.models.ItemBody; import com.microsoft.graph.models.User; import com.microsoft.graph.models.AttendeeType; import com.microsoft.graph.models.BodyType; import com.microsoft.graph.options.HeaderOption; import com.microsoft.graph.options.Option; import com.microsoft.graph.options.QueryOption; import com.microsoft.graph.requests.GraphServiceClient; import com.microsoft.graph.requests.EventCollectionPage; import com.microsoft.graph.requests.EventCollectionRequestBuilder; public class Graph { private static GraphServiceClient<Request> graphClient = null; private static TokenCredentialAuthProvider authProvider = null; public static void initializeGraphAuth(String applicationId, List<String> scopes) { // Create the auth provider final DeviceCodeCredential credential = new DeviceCodeCredentialBuilder() .clientId(applicationId) .challengeConsumer(challenge -> System.out.println(challenge.getMessage())) .build(); authProvider = new TokenCredentialAuthProvider(scopes, credential); // Create default logger to only log errors DefaultLogger logger = new DefaultLogger(); logger.setLoggingLevel(LoggerLevel.ERROR); // Build a Graph client graphClient = GraphServiceClient.builder() .authenticationProvider(authProvider) .logger(logger) .buildClient(); } public static String getUserAccessToken() { try { URL meUrl = new URL("https://graph.microsoft.com/v1.0/me"); return authProvider.getAuthorizationTokenAsync(meUrl).get(); } catch(Exception ex) { return null; } } }
Em App.java, adicione o código a seguir pouco antes da
Scanner input = new Scanner(System.in);
linha para obter um token de acesso.In App.java, add the following code just before theScanner input = new Scanner(System.in);
line to get an access token.// Initialize Graph with auth settings Graph.initializeGraphAuth(appId, appScopes); final String accessToken = Graph.getUserAccessToken();
Adicione a seguinte linha após o
// Display access token
comentário.Add the following line after the// Display access token
comment.System.out.println("Access token: " + accessToken);
Execute o aplicativo.Run the app. O aplicativo exibe uma URL e um código de dispositivo.The application displays a URL and device code.
Java Graph Tutorial To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code F7CG945YZ to authenticate.
Abra um navegador e navegue até a URL exibida.Open a browser and browse to the URL displayed. Insira o código fornecido e entre.Enter the provided code and sign in. Depois de concluído, retorne ao aplicativo e escolha o 1. Exibir a opção de token de acesso para exibir o token de acesso.Once completed, return to the application and choose the 1. Display access token option to display the access token.
Dica
Tokens de acesso para contas de estudante ou de trabalho da Microsoft podem ser analisados para fins de solução de problemas em https://jwt.ms .Access tokens for Microsoft work or school accounts can be parsed for troubleshooting purposes at https://jwt.ms. Tokens de acesso para contas pessoais da Microsoft usam um formato proprietário e não podem ser analisados.Access tokens for personal Microsoft accounts use a proprietary format and cannot be parsed.
Obter um modo de exibição de calendário
Neste exercício, você incorporará o Microsoft Graph ao aplicativo.In this exercise you will incorporate the Microsoft Graph into the application. Para este aplicativo, você usará o SDK do Microsoft Graph para Java fazer chamadas para o Microsoft Graph.For this application, you will use the Microsoft Graph SDK for Java to make calls to Microsoft Graph.
Obter detalhes do usuárioGet user details
Crie um novo arquivo no diretório ./graphtutorial/src/main/java/graphtutorial chamado Graph.java e adicione o código a seguir.Create a new file in the ./graphtutorial/src/main/java/graphtutorial directory named Graph.java and add the following code.
Adicione a
import
instrução a seguir na parte superior de App.java.Add the followingimport
statement at the top of App.java.import com.microsoft.graph.models.User;
Adicione o código a seguir em App.java pouco antes da linha para obter o usuário e exibir o nome de
Scanner input = new Scanner(System.in);
exibição do usuário.Add the following code in App.java just before theScanner input = new Scanner(System.in);
line to get the user and output the user's display name.// Greet the user User user = Graph.getUser(); System.out.println("Welcome " + user.displayName); System.out.println("Time zone: " + user.mailboxSettings.timeZone); System.out.println();
Execute o aplicativo.Run the app. Depois de fazer logoff, o aplicativo recebe você pelo nome.After you log in the app welcomes you by name.
Obtenha eventos de calendário do OutlookGet calendar events from Outlook
Adicione a seguinte função à
Graph
classe em Graph.java para obter eventos do calendário do usuário.Add the following function to theGraph
class in Graph.java to get events from the user's calendar.public static List<Event> getCalendarView(String accessToken, ZonedDateTime viewStart, ZonedDateTime viewEnd, String timeZone) { ensureGraphClient(accessToken); List<Option> options = new LinkedList<Option>(); options.add(new QueryOption("startDateTime", viewStart.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))); options.add(new QueryOption("endDateTime", viewEnd.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))); // Sort results by start time options.add(new QueryOption("$orderby", "start/dateTime")); // Start and end times adjusted to user's time zone options.add(new HeaderOption("Prefer", "outlook.timezone=\"" + timeZone + "\"")); // GET /me/events IEventCollectionPage eventPage = graphClient .me() .calendarView() .buildRequest(options) .select("subject,organizer,start,end") .top(25) .get(); List<Event> allEvents = new LinkedList<Event>(); // Create a separate list of options for the paging requests // paging request should not include the query parameters from the initial // request, but should include the headers. List<Option> pagingOptions = new LinkedList<Option>(); pagingOptions.add(new HeaderOption("Prefer", "outlook.timezone=\"" + timeZone + "\"")); while (eventPage != null) { allEvents.addAll(eventPage.getCurrentPage()); IEventCollectionRequestBuilder nextPage = eventPage.getNextPage(); if (nextPage == null) { break; } else { eventPage = nextPage .buildRequest(pagingOptions) .get(); } } return allEvents; }
Considere o que este código está fazendo.Consider what this code is doing.
- O URL que será chamado é
/me/calendarview
.The URL that will be called is/me/calendarview
.QueryOption
são usados para adicionar osstartDateTime
endDateTime
parâmetros e, definindo o início e o fim do exibição de calendário.QueryOption
objects are used to add thestartDateTime
andendDateTime
parameters, setting the start and end of the calendar view.- Um
QueryOption
objeto é usado para adicionar o$orderby
parâmetro, classificação dos resultados por hora de início.AQueryOption
object is used to add the$orderby
parameter, sorting the results by start time. - Um
HeaderOption
objeto é usado para adicionar o header, fazendo com que os horários de início e término sejam ajustados aoPrefer: outlook.timezone
fuso horário do usuário.AHeaderOption
object is used to add thePrefer: outlook.timezone
header, causing the start and end times to be adjusted to the user's time zone. - A
select
função limita os campos retornados para cada evento para apenas aqueles que o aplicativo realmente usará.Theselect
function limits the fields returned for each event to just those the app will actually use. - A
top
função limita o número de eventos na resposta a um máximo de 25.Thetop
function limits the number of events in the response to a maximum of 25.
- A função é usada para solicitar páginas adicionais de resultados se houver mais de
getNextPage
25 eventos na semana atual.ThegetNextPage
function is used to request additional pages of results if there are more than 25 events in the current week.
Crie um novo arquivo no diretório ./graphtutorial/src/main/java/graphtutorial chamado GraphToIana.java e adicione o código a seguir.Create a new file in the ./graphtutorial/src/main/java/graphtutorial directory named GraphToIana.java and add the following code.
package graphtutorial; import java.time.ZoneId; import java.util.Map; // Basic lookup for mapping Windows time zone identifiers to // IANA identifiers // Mappings taken from // https://github.com/unicode-org/cldr/blob/master/common/supplemental/windowsZones.xml public class GraphToIana { private static final Map<String, String> timeZoneIdMap = Map.ofEntries( Map.entry("Dateline Standard Time", "Etc/GMT+12"), Map.entry("UTC-11", "Etc/GMT+11"), Map.entry("Aleutian Standard Time", "America/Adak"), Map.entry("Hawaiian Standard Time", "Pacific/Honolulu"), Map.entry("Marquesas Standard Time", "Pacific/Marquesas"), Map.entry("Alaskan Standard Time", "America/Anchorage"), Map.entry("UTC-09", "Etc/GMT+9"), Map.entry("Pacific Standard Time (Mexico)", "America/Tijuana"), Map.entry("UTC-08", "Etc/GMT+8"), Map.entry("Pacific Standard Time", "America/Los_Angeles"), Map.entry("US Mountain Standard Time", "America/Phoenix"), Map.entry("Mountain Standard Time (Mexico)", "America/Chihuahua"), Map.entry("Mountain Standard Time", "America/Denver"), Map.entry("Central America Standard Time", "America/Guatemala"), Map.entry("Central Standard Time", "America/Chicago"), Map.entry("Easter Island Standard Time", "Pacific/Easter"), Map.entry("Central Standard Time (Mexico)", "America/Mexico_City"), Map.entry("Canada Central Standard Time", "America/Regina"), Map.entry("SA Pacific Standard Time", "America/Bogota"), Map.entry("Eastern Standard Time (Mexico)", "America/Cancun"), Map.entry("Eastern Standard Time", "America/New_York"), Map.entry("Haiti Standard Time", "America/Port-au-Prince"), Map.entry("Cuba Standard Time", "America/Havana"), Map.entry("US Eastern Standard Time", "America/Indianapolis"), Map.entry("Turks And Caicos Standard Time", "America/Grand_Turk"), Map.entry("Paraguay Standard Time", "America/Asuncion"), Map.entry("Atlantic Standard Time", "America/Halifax"), Map.entry("Venezuela Standard Time", "America/Caracas"), Map.entry("Central Brazilian Standard Time", "America/Cuiaba"), Map.entry("SA Western Standard Time", "America/La_Paz"), Map.entry("Pacific SA Standard Time", "America/Santiago"), Map.entry("Newfoundland Standard Time", "America/St_Johns"), Map.entry("Tocantins Standard Time", "America/Araguaina"), Map.entry("E. South America Standard Time", "America/Sao_Paulo"), Map.entry("SA Eastern Standard Time", "America/Cayenne"), Map.entry("Argentina Standard Time", "America/Buenos_Aires"), Map.entry("Greenland Standard Time", "America/Godthab"), Map.entry("Montevideo Standard Time", "America/Montevideo"), Map.entry("Magallanes Standard Time", "America/Punta_Arenas"), Map.entry("Saint Pierre Standard Time", "America/Miquelon"), Map.entry("Bahia Standard Time", "America/Bahia"), Map.entry("UTC-02", "Etc/GMT+2"), Map.entry("Azores Standard Time", "Atlantic/Azores"), Map.entry("Cape Verde Standard Time", "Atlantic/Cape_Verde"), Map.entry("UTC", "Etc/GMT"), Map.entry("GMT Standard Time", "Europe/London"), Map.entry("Greenwich Standard Time", "Atlantic/Reykjavik"), Map.entry("Sao Tome Standard Time", "Africa/Sao_Tome"), Map.entry("Morocco Standard Time", "Africa/Casablanca"), Map.entry("W. Europe Standard Time", "Europe/Berlin"), Map.entry("Central Europe Standard Time", "Europe/Budapest"), Map.entry("Romance Standard Time", "Europe/Paris"), Map.entry("Central European Standard Time", "Europe/Warsaw"), Map.entry("W. Central Africa Standard Time", "Africa/Lagos"), Map.entry("Jordan Standard Time", "Asia/Amman"), Map.entry("GTB Standard Time", "Europe/Bucharest"), Map.entry("Middle East Standard Time", "Asia/Beirut"), Map.entry("Egypt Standard Time", "Africa/Cairo"), Map.entry("E. Europe Standard Time", "Europe/Chisinau"), Map.entry("Syria Standard Time", "Asia/Damascus"), Map.entry("West Bank Standard Time", "Asia/Hebron"), Map.entry("South Africa Standard Time", "Africa/Johannesburg"), Map.entry("FLE Standard Time", "Europe/Kiev"), Map.entry("Israel Standard Time", "Asia/Jerusalem"), Map.entry("Kaliningrad Standard Time", "Europe/Kaliningrad"), Map.entry("Sudan Standard Time", "Africa/Khartoum"), Map.entry("Libya Standard Time", "Africa/Tripoli"), Map.entry("Namibia Standard Time", "Africa/Windhoek"), Map.entry("Arabic Standard Time", "Asia/Baghdad"), Map.entry("Turkey Standard Time", "Europe/Istanbul"), Map.entry("Arab Standard Time", "Asia/Riyadh"), Map.entry("Belarus Standard Time", "Europe/Minsk"), Map.entry("Russian Standard Time", "Europe/Moscow"), Map.entry("E. Africa Standard Time", "Africa/Nairobi"), Map.entry("Iran Standard Time", "Asia/Tehran"), Map.entry("Arabian Standard Time", "Asia/Dubai"), Map.entry("Astrakhan Standard Time", "Europe/Astrakhan"), Map.entry("Azerbaijan Standard Time", "Asia/Baku"), Map.entry("Russia Time Zone 3", "Europe/Samara"), Map.entry("Mauritius Standard Time", "Indian/Mauritius"), Map.entry("Saratov Standard Time", "Europe/Saratov"), Map.entry("Georgian Standard Time", "Asia/Tbilisi"), Map.entry("Volgograd Standard Time", "Europe/Volgograd"), Map.entry("Caucasus Standard Time", "Asia/Yerevan"), Map.entry("Afghanistan Standard Time", "Asia/Kabul"), Map.entry("West Asia Standard Time", "Asia/Tashkent"), Map.entry("Ekaterinburg Standard Time", "Asia/Yekaterinburg"), Map.entry("Pakistan Standard Time", "Asia/Karachi"), Map.entry("Qyzylorda Standard Time", "Asia/Qyzylorda"), Map.entry("India Standard Time", "Asia/Calcutta"), Map.entry("Sri Lanka Standard Time", "Asia/Colombo"), Map.entry("Nepal Standard Time", "Asia/Katmandu"), Map.entry("Central Asia Standard Time", "Asia/Almaty"), Map.entry("Bangladesh Standard Time", "Asia/Dhaka"), Map.entry("Omsk Standard Time", "Asia/Omsk"), Map.entry("Myanmar Standard Time", "Asia/Rangoon"), Map.entry("SE Asia Standard Time", "Asia/Bangkok"), Map.entry("Altai Standard Time", "Asia/Barnaul"), Map.entry("W. Mongolia Standard Time", "Asia/Hovd"), Map.entry("North Asia Standard Time", "Asia/Krasnoyarsk"), Map.entry("N. Central Asia Standard Time", "Asia/Novosibirsk"), Map.entry("Tomsk Standard Time", "Asia/Tomsk"), Map.entry("China Standard Time", "Asia/Shanghai"), Map.entry("North Asia East Standard Time", "Asia/Irkutsk"), Map.entry("Singapore Standard Time", "Asia/Singapore"), Map.entry("W. Australia Standard Time", "Australia/Perth"), Map.entry("Taipei Standard Time", "Asia/Taipei"), Map.entry("Ulaanbaatar Standard Time", "Asia/Ulaanbaatar"), Map.entry("Aus Central W. Standard Time", "Australia/Eucla"), Map.entry("Transbaikal Standard Time", "Asia/Chita"), Map.entry("Tokyo Standard Time", "Asia/Tokyo"), Map.entry("North Korea Standard Time", "Asia/Pyongyang"), Map.entry("Korea Standard Time", "Asia/Seoul"), Map.entry("Yakutsk Standard Time", "Asia/Yakutsk"), Map.entry("Cen. Australia Standard Time", "Australia/Adelaide"), Map.entry("AUS Central Standard Time", "Australia/Darwin"), Map.entry("E. Australia Standard Time", "Australia/Brisbane"), Map.entry("AUS Eastern Standard Time", "Australia/Sydney"), Map.entry("West Pacific Standard Time", "Pacific/Port_Moresby"), Map.entry("Tasmania Standard Time", "Australia/Hobart"), Map.entry("Vladivostok Standard Time", "Asia/Vladivostok"), Map.entry("Lord Howe Standard Time", "Australia/Lord_Howe"), Map.entry("Bougainville Standard Time", "Pacific/Bougainville"), Map.entry("Russia Time Zone 10", "Asia/Srednekolymsk"), Map.entry("Magadan Standard Time", "Asia/Magadan"), Map.entry("Norfolk Standard Time", "Pacific/Norfolk"), Map.entry("Sakhalin Standard Time", "Asia/Sakhalin"), Map.entry("Central Pacific Standard Time", "Pacific/Guadalcanal"), Map.entry("Russia Time Zone 11", "Asia/Kamchatka"), Map.entry("New Zealand Standard Time", "Pacific/Auckland"), Map.entry("UTC+12", "Etc/GMT-12"), Map.entry("Fiji Standard Time", "Pacific/Fiji"), Map.entry("Chatham Islands Standard Time", "Pacific/Chatham"), Map.entry("UTC+13", "Etc/GMT-13"), Map.entry("Tonga Standard Time", "Pacific/Tongatapu"), Map.entry("Samoa Standard Time", "Pacific/Apia"), Map.entry("Line Islands Standard Time", "Pacific/Kiritimati") ); public static String getIanaFromWindows(String windowsTimeZone) { String iana = timeZoneIdMap.get(windowsTimeZone); // If a mapping was not found, assume the value passed // was already an IANA identifier return (iana == null) ? windowsTimeZone : iana; } public static ZoneId getZoneIdFromWindows(String windowsTimeZone) { String timeZoneId = getIanaFromWindows(windowsTimeZone); return ZoneId.of(timeZoneId); } }
Essa classe implementa uma simples análise para converter nomes de fuso horário do Windows em identificadores IANA e gerar uma ZoneId com base em um nome de fuso horário do Windows.This class implements a simple lookup to convert Windows time zone names to IANA identifiers, and to generate a ZoneId based on a Windows time zone name.
Exibir os resultadosDisplay the results
Adicione as instruções
import
a seguir em App.java.Add the followingimport
statements in App.java.import java.time.DayOfWeek; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.format.FormatStyle; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAdjusters; import java.util.HashSet; import java.util.List; import com.microsoft.graph.models.DateTimeTimeZone; import com.microsoft.graph.models.Event;
Adicione a seguinte função à classe para formatar as propriedades
App
dateTimeTimeZone do Microsoft Graph em um formato amigável.Add the following function to theApp
class to format the dateTimeTimeZone properties from Microsoft Graph into a user-friendly format.private static String formatDateTimeTimeZone(DateTimeTimeZone date) { LocalDateTime dateTime = LocalDateTime.parse(date.dateTime); return dateTime.format( DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)) + " (" + date.timeZone + ")"; }
Adicione a função a seguir à classe para obter os eventos do usuário e
App
de saída para o console.Add the following function to theApp
class to get the user's events and output them to the console.private static void listCalendarEvents(String accessToken, String timeZone) { ZoneId tzId = GraphToIana.getZoneIdFromWindows("Pacific Standard Time"); // Get midnight of the first day of the week (assumed Sunday) // in the user's timezone, then convert to UTC ZonedDateTime startOfWeek = ZonedDateTime.now(tzId) .with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY)) .truncatedTo(ChronoUnit.DAYS) .withZoneSameInstant(ZoneId.of("UTC")); // Add 7 days to get the end of the week ZonedDateTime endOfWeek = startOfWeek.plusDays(7); // Get the user's events List<Event> events = Graph.getCalendarView(accessToken, startOfWeek, endOfWeek, timeZone); System.out.println("Events:"); for (Event event : events) { System.out.println("Subject: " + event.subject); System.out.println(" Organizer: " + event.organizer.emailAddress.name); System.out.println(" Start: " + formatDateTimeTimeZone(event.start)); System.out.println(" End: " + formatDateTimeTimeZone(event.end)); } System.out.println(); }
Adicione o seguinte logo após
// List the calendar
o comentário namain
função.Add the following just after the// List the calendar
comment in themain
function.listCalendarEvents(user.mailboxSettings.timeZone);
Salve todas as alterações, crie o aplicativo e execute-o.Save all of your changes, build the app, then run it. Escolha a opção Listar eventos de calendário para ver uma lista dos eventos do usuário.Choose the List calendar events option to see a list of the user's events.
Welcome Adele Vance Please choose one of the following options: 0. Exit 1. Display access token 2. View this week's calendar 3. Add an event 2 Events: Subject: Weekly meeting Organizer: Lynne Robbins Start: 12/7/20, 2:00 PM (Pacific Standard Time) End: 12/7/20, 3:00 PM (Pacific Standard Time) Subject: Carpool Organizer: Lynne Robbins Start: 12/7/20, 4:00 PM (Pacific Standard Time) End: 12/7/20, 5:30 PM (Pacific Standard Time) Subject: Tailspin Toys Proposal Review + Lunch Organizer: Lidia Holloway Start: 12/8/20, 12:00 PM (Pacific Standard Time) End: 12/8/20, 1:00 PM (Pacific Standard Time) Subject: Project Tailspin Organizer: Lidia Holloway Start: 12/8/20, 3:00 PM (Pacific Standard Time) End: 12/8/20, 4:30 PM (Pacific Standard Time) Subject: Company Meeting Organizer: Christie Cline Start: 12/9/20, 8:30 AM (Pacific Standard Time) End: 12/9/20, 11:00 AM (Pacific Standard Time) Subject: Carpool Organizer: Lynne Robbins Start: 12/9/20, 4:00 PM (Pacific Standard Time) End: 12/9/20, 5:30 PM (Pacific Standard Time) Subject: Project Team Meeting Organizer: Lidia Holloway Start: 12/10/20, 8:00 AM (Pacific Standard Time) End: 12/10/20, 9:30 AM (Pacific Standard Time) Subject: Weekly Marketing Lunch Organizer: Adele Vance Start: 12/10/20, 12:00 PM (Pacific Standard Time) End: 12/10/20, 1:00 PM (Pacific Standard Time) Subject: Project Tailspin Organizer: Lidia Holloway Start: 12/10/20, 3:00 PM (Pacific Standard Time) End: 12/10/20, 4:30 PM (Pacific Standard Time) Subject: Lunch? Organizer: Lynne Robbins Start: 12/11/20, 12:00 PM (Pacific Standard Time) End: 12/11/20, 1:00 PM (Pacific Standard Time) Subject: Friday Unwinder Organizer: Megan Bowen Start: 12/11/20, 4:00 PM (Pacific Standard Time) End: 12/11/20, 5:00 PM (Pacific Standard Time)
Criar um novo evento
Nesta seção, você adicionará a capacidade de criar eventos no calendário do usuário.In this section you will add the ability to create events on the user's calendar.
Abra ./graphtutorial/src/main/java/graphtutorial/Graph.java e adicione a seguinte função à classe Graph.Open ./graphtutorial/src/main/java/graphtutorial/Graph.java and add the following function to the Graph class.
public static void createEvent( String accessToken, String timeZone, String subject, LocalDateTime start, LocalDateTime end, Set<String> attendees, String body) { ensureGraphClient(accessToken); Event newEvent = new Event(); newEvent.subject = subject; newEvent.start = new DateTimeTimeZone(); newEvent.start.dateTime = start.toString(); newEvent.start.timeZone = timeZone; newEvent.end = new DateTimeTimeZone(); newEvent.end.dateTime = end.toString(); newEvent.end.timeZone = timeZone; if (attendees != null && !attendees.isEmpty()) { newEvent.attendees = new LinkedList<Attendee>(); attendees.forEach((email) -> { Attendee attendee = new Attendee(); // Set each attendee as required attendee.type = AttendeeType.REQUIRED; attendee.emailAddress = new EmailAddress(); attendee.emailAddress.address = email; newEvent.attendees.add(attendee); }); } if (body != null) { newEvent.body = new ItemBody(); newEvent.body.content = body; // Treat body as plain text newEvent.body.contentType = BodyType.TEXT; } // POST /me/events graphClient .me() .events() .buildRequest() .post(newEvent); }
Abra ./graphtutorial/src/main/java/graphtutorial/App.java e adicione a seguinte função à classe App.Open ./graphtutorial/src/main/java/graphtutorial/App.java and add the following function to the App class.
private static void createEvent(String accessToken, String timeZone, Scanner input) { DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("M/d/yyyy h:mm a"); // Prompt for subject String subject = ""; while (subject.isBlank()) { System.out.print("Subject (required): "); subject = input.nextLine(); } // Prompt for start date/time LocalDateTime start = null; while (start == null) { System.out.print("Start (mm/dd/yyyy hh:mm AM/PM): "); String date = input.nextLine(); try { start = LocalDateTime.parse(date, inputFormat); } catch (DateTimeParseException dtp) { System.out.println("Invalid input, try again."); } } // Prompt for end date/time LocalDateTime end = null; while (end == null) { System.out.print("End (mm/dd/yyyy hh:mm AM/PM): "); String date = input.nextLine(); try { end = LocalDateTime.parse(date, inputFormat); } catch (DateTimeParseException dtp) { System.out.println("Invalid input, try again."); } if (end.isBefore(start)) { System.out.println("End time must be after start time."); end = null; } } // Prompt for attendees HashSet<String> attendees = new HashSet<String>(); System.out.print("Would you like to add attendees? (y/n): "); if (input.nextLine().trim().toLowerCase().startsWith("y")) { String attendee = ""; do { System.out.print("Enter an email address (leave blank to finalize the list): "); attendee = input.nextLine(); if (!attendee.isBlank()) { attendees.add(attendee); } } while (!attendee.isBlank()); } // Prompt for body String body = null; System.out.print("Would you like to add a body? (y/n): "); if (input.nextLine().trim().toLowerCase().startsWith("y")) { System.out.print("Enter a body: "); body = input.nextLine(); } // Confirm input System.out.println(); System.out.println("New event:"); System.out.println("Subject: " + subject); System.out.println("Start: " + start.format(inputFormat)); System.out.println("End: " + end.format(inputFormat)); System.out.println("Attendees: " + (attendees.size() > 0 ? attendees.toString() : "NONE")); System.out.println("Body: " + (body == null ? "NONE" : body)); System.out.print("Is this correct? (y/n): "); if (input.nextLine().trim().toLowerCase().startsWith("y")) { Graph.createEvent(accessToken, timeZone, subject, start, end, attendees, body); System.out.println("Event created."); } else { System.out.println("Canceling."); } System.out.println(); }
Essa função solicita ao usuário assunto, participantes, início, fim e corpo, em seguida, usa esses valores para chamar
Graph.createEvent
.This function prompts the user for subject, attendees, start, end, and body, then uses those values to callGraph.createEvent
.Adicione o seguinte logo após
// Create a new event
o comentário naMain
função.Add the following just after the// Create a new event
comment in theMain
function.createEvent(user.mailboxSettings.timeZone, input);
Salve todas as alterações e execute o aplicativo.Save all of your changes and run the app. Escolha a opção Adicionar um evento.Choose the Add an event option. Responda aos prompts para criar um novo evento no calendário do usuário.Respond to the prompts to create a new event on the user's calendar.
Parabéns!
Você concluiu o tutorial de Java Microsoft Graph.You've completed the Java Microsoft Graph tutorial. Agora que você tem um aplicativo de trabalho que chama o Microsoft Graph, você pode experimentar e adicionar novos recursos.Now that you have a working app that calls Microsoft Graph, you can experiment and add new features. Visite a visão geral do Microsoft Graph para ver todos os dados que você pode acessar com o Microsoft Graph.Visit the Overview of Microsoft Graph to see all of the data you can access with Microsoft Graph.
ComentáriosFeedback
Forneça comentários sobre este tutorial no repositório do GitHub.Please provide any feedback on this tutorial in the GitHub repository.
Tem algum problema com essa seção? Se tiver, envie seus comentários para que possamos melhorar esta seção.