com.google.api.client.auth.oauth2.BearerToken Java Examples

The following examples show how to use com.google.api.client.auth.oauth2.BearerToken. 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: AdWordsSessionTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
public AdWordsSessionTest(boolean isImmutable) {
  this.isImmutable = isImmutable;
  this.credential = new Credential(BearerToken.authorizationHeaderAccessMethod());

  this.reportingConfiguration =
      new ReportingConfiguration.Builder().skipReportHeader(true).skipReportSummary(true).build();

  this.allSettingsBuilder =
      new AdWordsSession.Builder()
          .withClientCustomerId("customer id")
          .withDeveloperToken("developer token")
          .withEndpoint("https://www.google.com")
          .enablePartialFailure()
          .enableValidateOnly()
          .withOAuth2Credential(credential)
          .withUserAgent("user agent")
          .withReportingConfiguration(reportingConfiguration);
}
 
Example #2
Source File: OAuth2CredentialsTest.java    From rides-java-sdk with MIT License 6 votes vote down vote up
@Test
public void loadCredential() throws Exception {
    OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder()
            .setClientSecrets("CLIENT_ID", "CLIENT_SECRET")
            .setRedirectUri("http://redirect")
            .setHttpTransport(mockHttpTransport)
            .setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST))
            .build();

    oAuth2Credentials.authenticate("authorizationCode", "userId");

    Credential credential = oAuth2Credentials.loadCredential("userId");

    assertEquals("Refresh token does not match.", "refreshToken", credential.getRefreshToken());
    assertTrue("Expected expires_in between 0 and 3600. Was actually: " + credential.getExpiresInSeconds(),
            credential.getExpiresInSeconds() > 0 && credential.getExpiresInSeconds() <= 3600);
    assertEquals("Access token does not match.", "accessToken", credential.getAccessToken());
    assertEquals("Access method (Bearer) does not match",
            BearerToken.authorizationHeaderAccessMethod().getClass(), credential.getMethod().getClass());
}
 
Example #3
Source File: OAuthServlet.java    From vpn-over-dns with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
	return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(),
			new NetHttpTransport(),
			new JacksonFactory(),
			// token server URL:
			// new GenericUrl("https://server.example.com/token"),
			new GenericUrl("https://accounts.google.com/o/oauth2/auth"),
			new BasicAuthentication("458072371664.apps.googleusercontent.com",
					"mBp75wknGsGu0WMzHaHhqfXT"),
			"458072371664.apps.googleusercontent.com",
			// authorization server URL:
			"https://accounts.google.com/o/oauth2/auth").
			// setCredentialStore(new JdoCredentialStore(JDOHelper.getPersistenceManagerFactory("transactions-optional")))
			setCredentialStore(new MemoryCredentialStore()).setScopes("https://mail.google.com/")
			// setCredentialStore(new MyCredentialStore())
			.build();
}
 
Example #4
Source File: OAuthServletCallback.java    From vpn-over-dns with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
	return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(),
			new NetHttpTransport(),
			new JacksonFactory(),
			// token server URL:
			// new GenericUrl("https://server.example.com/token"),
			new GenericUrl("https://accounts.google.com/o/oauth2/auth"),
			new BasicAuthentication("458072371664.apps.googleusercontent.com",
					"mBp75wknGsGu0WMzHaHhqfXT"),
			"458072371664.apps.googleusercontent.com",
			// authorization server URL:
			"https://accounts.google.com/o/oauth2/auth").
			// setCredentialStore(new JdoCredentialStore(JDOHelper.getPersistenceManagerFactory("transactions-optional")))
			setCredentialStore(new MemoryCredentialStore()).setScopes("https://mail.google.com/")
			// setCredentialStore(new MyCredentialStore())
			.build();
}
 
Example #5
Source File: PKCESample.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
    // set up authorization code flow
    String clientId = "pkce-test-client";
    AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(
            BearerToken.authorizationHeaderAccessMethod(),
            HTTP_TRANSPORT,
            JSON_FACTORY,
            new GenericUrl(TOKEN_SERVER_URL),
            new ClientParametersAuthentication(clientId, null),
            clientId,
            AUTHORIZATION_SERVER_URL)
            .setScopes(Arrays.asList(SCOPE))
            .enablePKCE()
            .setDataStoreFactory(DATA_STORE_FACTORY).build();
    // authorize
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setHost("127.0.0.1").build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #6
Source File: DailyMotionSample.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
  OAuth2ClientCredentials.errorIfNotSpecified();
  // set up authorization code flow
  AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken
      .authorizationHeaderAccessMethod(),
      HTTP_TRANSPORT,
      JSON_FACTORY,
      new GenericUrl(TOKEN_SERVER_URL),
      new ClientParametersAuthentication(
          OAuth2ClientCredentials.API_KEY, OAuth2ClientCredentials.API_SECRET),
      OAuth2ClientCredentials.API_KEY,
      AUTHORIZATION_SERVER_URL).setScopes(Arrays.asList(SCOPE))
      .setDataStoreFactory(DATA_STORE_FACTORY).build();
  // authorize
  LocalServerReceiver receiver = new LocalServerReceiver.Builder().setHost(
      OAuth2ClientCredentials.DOMAIN).setPort(OAuth2ClientCredentials.PORT).build();
  return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #7
Source File: ApigeeDataClient.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Stores the given OAuth 2 token response within a file data store.
 * The stored token response can then retrieved using the getOAuth2TokenDataFromStore method.
 *
 * @param storageId a string object that is used to store the token response
 * @param tokenResponse the token response containing the OAuth 2 token information.
 * @return If the token response was stored or not.
 */
public Boolean storeOAuth2TokenData(String storageId, TokenResponse tokenResponse) {
    Boolean wasStored = false;
    try {
        File oauth2StorageFolder = new File(this.context.getFilesDir(),"oauth2StorageFolder");
        oauth2StorageFolder.mkdirs();
        FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(oauth2StorageFolder);
        DataStore<StoredCredential> storedCredentialDataStore = fileDataStoreFactory.getDataStore(storageId);
        Credential oauth2Credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setFromTokenResponse(
                tokenResponse);
        StoredCredential storedOAuth2Credential = new StoredCredential(oauth2Credential);
        storedCredentialDataStore.set(storageId,storedOAuth2Credential);
        wasStored = true;
    } catch ( Exception exception ) {
        logInfo("Exception storing OAuth2TokenData :" + exception.getLocalizedMessage());
    }
    return wasStored;
}
 
Example #8
Source File: AdWordsJaxWsHeaderHandlerTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);

  headerHandler = new AdWordsJaxWsHeaderHandler(soapClientHandler,
      adWordsApiConfiguration,
      adsLibConfiguration,
      authorizationHeaderHandler,
      userAgentCombiner);

  adWordsSession = new AdWordsSession.Builder()
      .withClientCustomerId(CLIENT_CUSTOMER_ID)
      .withOAuth2Credential(new Credential(BearerToken.authorizationHeaderAccessMethod()))
      .withDeveloperToken(DEVELOPER_TOKEN)
      .withUserAgent(USER_AGENT)
      .build();

  adWordsServiceDescriptor =
      new AdWordsServiceDescriptor(interfaceClass, VERSION, adWordsApiConfiguration);
}
 
Example #9
Source File: AdManagerServiceClientFactoryHelperTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckServiceClientPreconditions_passOAuth2() throws Exception {
  AdManagerServiceClientFactoryHelper helper =
      new AdManagerServiceClientFactoryHelper(
          adsServiceClientFactory,
          adsServiceDescriptorFactory,
          soapClientHandler,
          adsLibConfiguration);

  Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod());

  AdManagerSession adManagerSession =
      new AdManagerSession.Builder()
          .withApplicationName("FooBar")
          .withNetworkCode("1000")
          .withEndpoint("https://ads.google.com")
          .withOAuth2Credential(credential)
          .build();

  helper.checkServiceClientPreconditions(
      adManagerSession,
      com.google.api.ads.admanager.lib.factory.helper.testing.v201911.TestService.class);
}
 
Example #10
Source File: AdManagerHttpHeaderHandlerTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Tests setting the headers.
 */
@SuppressWarnings("unchecked")
@Test
public void testSetHeaders() throws Exception {
  Object soapClient = new Object();
  Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod());

  AdManagerSession adManagerSession =
      new AdManagerSession.Builder()
          .withApplicationName("FooBar")
          .withOAuth2Credential(credential)
          .withEndpoint("https://ads.google.com")
          .withNetworkCode("networkCode")
          .build();

  adManagerHttpHeaderHandler.setHttpHeaders(soapClient, adManagerSession);

  verify(soapClientHandler).putAllHttpHeaders(eq(soapClient), any(Map.class));
}
 
Example #11
Source File: AdWordsServiceClientFactoryHelperTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckServiceClientPreconditions_passOAuth2() throws Exception {
  AdWordsServiceClientFactoryHelper helper = new AdWordsServiceClientFactoryHelper(
      adsServiceClientFactory, adsServiceDescriptorFactory, soapClientHandler,
      adsLibConfiguration);

  Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod());

  AdWordsSession adWordsSession = new AdWordsSession.Builder()
      .withUserAgent("FooBar")
      .withEndpoint("https://www.google.com")
      .withOAuth2Credential(credential)
      .withDeveloperToken("developerToken")
      .build();

  helper.checkServiceClientPreconditions(adWordsSession,
      com.google.api.ads.adwords.lib.factory.helper.testing.v201406.cm.TestService.class);
}
 
Example #12
Source File: GCalGoogleOAuth.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private static Credential newCredential(String userId, DataStore<StoredCredential> credentialDataStore) {

        Credential.Builder builder = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
                .setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
                .setTokenServerEncodedUrl("https://accounts.google.com/o/oauth2/token")
                .setClientAuthentication(new ClientParametersAuthentication(client_id, client_secret))
                .setRequestInitializer(null).setClock(Clock.SYSTEM);

        builder.addRefreshListener(new DataStoreCredentialRefreshListener(userId, credentialDataStore));

        return builder.build();
    }
 
Example #13
Source File: AssetApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getAssetSettingsForHttpResponse(String accessToken,  String xeroTenantId) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getAssetSettings");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getAssetSettings");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Settings");
    String url = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("GET " + genericUrl.toString());
    }
    
    HttpContent content = null;
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #14
Source File: OAuthClient.java    From kickflip-android-sdk with Apache License 2.0 5 votes vote down vote up
private HttpRequestFactory getRequestFactoryFromAccessToken(String accessToken) {
    if (accessToken == null) {
        throw new NullPointerException("getRequestFactoryFromAccessToken got null Access Token");
    }
    if (mRequestFactory == null || !accessToken.equals(mOAuthAccessToken)) {
        Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
        NetHttpTransport mHttpTransport = new NetHttpTransport.Builder().build();
        mRequestFactory = mHttpTransport.createRequestFactory(credential);
        mOAuthAccessToken = accessToken;
    }
    return mRequestFactory;
}
 
Example #15
Source File: FileCredentialStoreTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
private Credential createCredential() {
  Credential access = new Credential.Builder(
      BearerToken.queryParameterAccessMethod()).setTransport(new AccessTokenTransport())
      .setJsonFactory(JSON_FACTORY)
      .setTokenServerUrl(TOKEN_SERVER_URL)
      .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
      .build()
      .setAccessToken(ACCESS_TOKEN)
      .setRefreshToken(REFRESH_TOKEN)
      .setExpirationTimeMilliseconds(EXPIRES_IN);
  return access;
}
 
Example #16
Source File: AuthorizationHeaderProviderTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAuthorizationHeader_oAuth2NoRefresh() throws Exception {
  final Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod());
  OAuth2Session adsSession = () -> credential;

  when(oAuth2AuthorizationHeaderProvider.getOAuth2AuthorizationHeader(
      (OAuth2Compatible) adsSession)).thenReturn("OAuth2 Header");
  when(adsLibConfiguration.isAutoRefreshOAuth2TokenEnabled()).thenReturn(false);

  assertEquals("OAuth2 Header",
      authorizationHeaderProvider.getAuthorizationHeader(adsSession, ENDPOINT_URL.toString()));

  verify(oAuth2Helper, times(0)).refreshCredential(credential);
}
 
Example #17
Source File: FileCredentialStoreTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
private Credential createEmptyCredential() {
  Credential access = new Credential.Builder(
      BearerToken.queryParameterAccessMethod()).setTransport(new AccessTokenTransport())
      .setJsonFactory(JSON_FACTORY)
      .setTokenServerUrl(TOKEN_SERVER_URL)
      .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
      .build();
  return access;
}
 
Example #18
Source File: AdManagerSessionTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
public AdManagerSessionTest(boolean isImmutable) {
  this.isImmutable = isImmutable;
  this.credential = new Credential(BearerToken.authorizationHeaderAccessMethod());
  this.allSettingsBuilder =
      new AdManagerSession.Builder()
          .withApplicationName("FooBar")
          .withEndpoint("https://ads.google.com")
          .withOAuth2Credential(credential)
          .withNetworkCode("networkCode");
}
 
Example #19
Source File: IdentityApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getConnectionsForHttpResponse(String accessToken,  UUID authEventId) throws IOException {
    
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getConnections");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/connections");
    if (authEventId != null) {
        String key = "authEventId";
        Object value = authEventId;
        if (value instanceof Collection) {
            uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray());
        } else if (value instanceof Object[]) {
            uriBuilder = uriBuilder.queryParam(key, (Object[]) value);
        } else {
            uriBuilder = uriBuilder.queryParam(key, value);
        }
    }
    String url = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("GET " + genericUrl.toString());
    }
    
    HttpContent content = null;
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #20
Source File: IdentityApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse deleteConnectionForHttpResponse(String accessToken,  UUID id) throws IOException {
    // verify the required parameter 'id' is set
    if (id == null) {
        throw new IllegalArgumentException("Missing the required parameter 'id' when calling deleteConnection");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling deleteConnection");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(""); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("id", id);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/connections/{id}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("DELETE " + genericUrl.toString());
    }
    
    HttpContent content = null;
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.DELETE, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #21
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse updateProjectForHttpResponse(String accessToken,  String xeroTenantId,  UUID projectId,  ProjectCreateOrUpdate projectCreateOrUpdate) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling updateProject");
    }// verify the required parameter 'projectId' is set
    if (projectId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling updateProject");
    }// verify the required parameter 'projectCreateOrUpdate' is set
    if (projectCreateOrUpdate == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectCreateOrUpdate' when calling updateProject");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling updateProject");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("projectId", projectId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("PUT " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(projectCreateOrUpdate);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.PUT, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #22
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse patchProjectForHttpResponse(String accessToken,  String xeroTenantId,  UUID projectId,  ProjectPatch projectPatch) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling patchProject");
    }// verify the required parameter 'projectId' is set
    if (projectId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling patchProject");
    }// verify the required parameter 'projectPatch' is set
    if (projectPatch == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectPatch' when calling patchProject");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling patchProject");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("projectId", projectId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("PATCH " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(projectPatch);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.PATCH, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #23
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getTimeEntryForHttpResponse(String accessToken,  String xeroTenantId,  UUID projectId,  UUID timeEntryId) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getTimeEntry");
    }// verify the required parameter 'projectId' is set
    if (projectId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling getTimeEntry");
    }// verify the required parameter 'timeEntryId' is set
    if (timeEntryId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'timeEntryId' when calling getTimeEntry");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getTimeEntry");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("projectId", projectId);
    uriVariables.put("timeEntryId", timeEntryId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}/time/{timeEntryId}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("GET " + genericUrl.toString());
    }
    
    HttpContent content = null;
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #24
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getTaskForHttpResponse(String accessToken,  String xeroTenantId,  UUID projectId,  UUID taskId) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getTask");
    }// verify the required parameter 'projectId' is set
    if (projectId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling getTask");
    }// verify the required parameter 'taskId' is set
    if (taskId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'taskId' when calling getTask");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getTask");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("projectId", projectId);
    uriVariables.put("taskId", taskId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}/tasks/{taskId}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("GET " + genericUrl.toString());
    }
    
    HttpContent content = null;
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #25
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getProjectForHttpResponse(String accessToken,  String xeroTenantId,  UUID projectId) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getProject");
    }// verify the required parameter 'projectId' is set
    if (projectId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling getProject");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getProject");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("projectId", projectId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("GET " + genericUrl.toString());
    }
    
    HttpContent content = null;
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #26
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse deleteTimeEntryForHttpResponse(String accessToken,  String xeroTenantId,  UUID projectId,  UUID timeEntryId) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling deleteTimeEntry");
    }// verify the required parameter 'projectId' is set
    if (projectId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling deleteTimeEntry");
    }// verify the required parameter 'timeEntryId' is set
    if (timeEntryId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'timeEntryId' when calling deleteTimeEntry");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling deleteTimeEntry");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept(""); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("projectId", projectId);
    uriVariables.put("timeEntryId", timeEntryId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}/time/{timeEntryId}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("DELETE " + genericUrl.toString());
    }
    
    HttpContent content = null;
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.DELETE, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #27
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse createTimeEntryForHttpResponse(String accessToken,  String xeroTenantId,  UUID projectId,  TimeEntryCreateOrUpdate timeEntryCreateOrUpdate) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createTimeEntry");
    }// verify the required parameter 'projectId' is set
    if (projectId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling createTimeEntry");
    }// verify the required parameter 'timeEntryCreateOrUpdate' is set
    if (timeEntryCreateOrUpdate == null) {
        throw new IllegalArgumentException("Missing the required parameter 'timeEntryCreateOrUpdate' when calling createTimeEntry");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createTimeEntry");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("projectId", projectId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}/time");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("POST " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(timeEntryCreateOrUpdate);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #28
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse createProjectForHttpResponse(String accessToken,  String xeroTenantId,  ProjectCreateOrUpdate projectCreateOrUpdate) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createProject");
    }// verify the required parameter 'projectCreateOrUpdate' is set
    if (projectCreateOrUpdate == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectCreateOrUpdate' when calling createProject");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createProject");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects");
    String url = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("POST " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(projectCreateOrUpdate);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #29
Source File: AssetApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getAssetTypesForHttpResponse(String accessToken,  String xeroTenantId) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getAssetTypes");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getAssetTypes");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/AssetTypes");
    String url = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("GET " + genericUrl.toString());
    }
    
    HttpContent content = null;
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #30
Source File: Authorizer.java    From gcp-token-broker with Apache License 2.0 5 votes vote down vote up
/**
 * Handler for the OAuth callback endpoint.
 */
private void handleCallback(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");

    // Ensure that the authorization code is provided
    String authzCode = request.getParameter(CODE_PARAM);
    if (authzCode == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // Confirm the authorization with Google
    final TokenResponse tokenResponse = FLOW
        .newTokenRequest(authzCode)
        .setRedirectUri(((Request) request).getRootURL() + GOOGLE_OAUTH2_CALLBACK_URI)
        .execute();

    // Retrieve some details about the Google identity
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod())
        .setAccessToken(tokenResponse.getAccessToken());
    UserInfo user = getUserInfo(credential);

    // Save the refresh token in the database
    saveRefreshToken(user.getEmail(), tokenResponse.getRefreshToken());

    // Generate the HTML response
    String content = soySauce
        .renderTemplate("Authorizer.Templates.success")
        .renderHtml()
        .get()
        .getContent();
    PrintWriter out = response.getWriter();
    out.write(content);
}