Java Code Examples for com.google.api.client.extensions.android.http.AndroidHttp#newCompatibleTransport()

The following examples show how to use com.google.api.client.extensions.android.http.AndroidHttp#newCompatibleTransport() . 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: AndroidGoogleDrive.java    From QtAndroidTools with MIT License 9 votes vote down vote up
public boolean authenticate(String AppName, String ScopeName)
{
    final GoogleSignInAccount SignInAccount = GoogleSignIn.getLastSignedInAccount(mActivityInstance);

    if(SignInAccount != null)
    {
        GoogleAccountCredential AccountCredential;
        Drive.Builder DriveBuilder;

        AccountCredential = GoogleAccountCredential.usingOAuth2(mActivityInstance, Collections.singleton(ScopeName));
        AccountCredential.setSelectedAccount(SignInAccount.getAccount());

        DriveBuilder = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), AccountCredential);
        DriveBuilder.setApplicationName(AppName);
        mDriveService = DriveBuilder.build();

        return true;
    }

    Log.d(TAG, "You have to signin by select account before use this call!");
    return false;
}
 
Example 2
Source File: MainActivity.02.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 6 votes vote down vote up
/**
 * Calls appropriate CloudEndpoint to indicate that user checked into a place.
 *
 * @param params the place where the user is checking in.
 */
@Override
protected Void doInBackground(Void... params) {
  CheckIn checkin = new CheckIn();

  // Set the ID of the store where the user is.
  checkin.setPlaceId("StoreNo123");

  Checkinendpoint.Builder builder = new Checkinendpoint.Builder(
      AndroidHttp.newCompatibleTransport(), new JacksonFactory(), null);

  builder = CloudEndpointUtils.updateBuilder(builder);

  Checkinendpoint endpoint = builder.build();


  try {
    endpoint.insertCheckIn(checkin).execute();
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

  return null;
}
 
Example 3
Source File: DriveSyncProvider.java    From science-journal with Apache License 2.0 6 votes vote down vote up
private void addServiceForAccount(AppAccount appAccount) {


    HttpTransport transport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    accountMap.put(
        appAccount,
        new DriveSyncManager(
            appAccount,
            AppSingleton.getInstance(applicationContext).getDataController(appAccount),
            transport,
            jsonFactory,
            applicationContext,
            driveSupplier,
            AppSingleton.getInstance(applicationContext)
                .getSensorEnvironment()
                .getDataController(appAccount)));
  }
 
Example 4
Source File: TGDriveBrowser.java    From tuxguitar with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void open(final TGBrowserCallBack<Object> cb){
	try {
		this.drive = null;
		this.folder = null;
		this.httpTransport = AndroidHttp.newCompatibleTransport();
		
		TGDriveBrowserLogin login = new TGDriveBrowserLogin(this.findActivity(), this.settings, new TGBrowserCallBack<GoogleAccountCredential>() {
			public void onSuccess(GoogleAccountCredential credential) {
				Drive.Builder builder = new Drive.Builder(TGDriveBrowser.this.httpTransport, GsonFactory.getDefaultInstance(), credential);
				builder.setApplicationName(findActivity().getString(R.string.gdrive_application_name));
				TGDriveBrowser.this.drive = builder.build();
				
				cb.onSuccess(null);
			}
			
			public void handleError(Throwable throwable) {
				cb.handleError(throwable);
			}
		});
		login.process();
	} catch (Throwable e) {
		cb.handleError(e);
	}
}
 
Example 5
Source File: MainActivity.java    From solutions-mobile-shopping-assistant-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Calls appropriate CloudEndpoint to indicate that user checked into a place.
 *
 * @param params the place where the user is checking in.
 */
@Override
protected Void doInBackground(PlaceInfo... params) {

  CheckIn checkin = new CheckIn();
  checkin.setPlaceId(params[0].getPlaceId());

  Builder endpointBuilder = new Shoppingassistant.Builder(
      AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
      CloudEndpointBuilderHelper.getRequestInitializer());

  CheckInEndpoint checkinEndpoint =
      CloudEndpointBuilderHelper.updateBuilder(endpointBuilder).build().checkInEndpoint();

  try {
    checkinEndpoint.insert(checkin).execute();
  } catch (IOException e) {
    String message = e.getMessage();
    if (message == null) {
      message = e.toString();
    }
    log.warning("Exception when checking in =" + message);
  }
  return null;
}
 
Example 6
Source File: MainActivity.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 6 votes vote down vote up
/**
 * Calls appropriate CloudEndpoint to indicate that user checked into a place.
 *
 * @param params the place where the user is checking in.
 */
@Override
protected Void doInBackground(Void... params) {
  CheckIn checkin = new com.google.samplesolutions.mobileassistant.checkinendpoint.model.CheckIn();

  // Set the ID of the store where the user is.
  checkin.setPlaceId("StoreNo123");

  Checkinendpoint.Builder builder = new Checkinendpoint.Builder(
      AndroidHttp.newCompatibleTransport(), new JacksonFactory(), null);

  builder = CloudEndpointUtils.updateBuilder(builder);

  Checkinendpoint endpoint = builder.build();


  try {
    endpoint.insertCheckIn(checkin).execute();
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

  return null;
}
 
Example 7
Source File: TictactoeActivity.java    From appengine-endpoints-tictactoe-android with Apache License 2.0 6 votes vote down vote up
/**
 * Called when the activity is first created. It displays the UI, checks
 * for the account previously chosen to sign in (if available), and
 * configures the service object.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  settings = getSharedPreferences(TAG, 0);
  credential = GoogleAccountCredential.usingAudience(this, ClientCredentials.AUDIENCE);
  setAccountName(settings.getString(PREF_ACCOUNT_NAME, null));

  Tictactoe.Builder builder = new Tictactoe.Builder(
      AndroidHttp.newCompatibleTransport(), new GsonFactory(),
      credential);
  service = builder.build();

  if (credential.getSelectedAccountName() != null) {
    onSignIn();
  }

  Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
}
 
Example 8
Source File: PlaceDetailsActivity.java    From solutions-mobile-shopping-assistant-android-client with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the list of offers through appropriate CloudEndpoint.
 *
 * @param params the place for which to retrieve offers.
 * @return collection of retrieved offers.
 */
@Override
protected OfferCollection doInBackground(PlaceInfo... params) {
  PlaceInfo place = params[0];

  if (place == null) {
    return null;
  }

  Builder endpointBuilder = new Shoppingassistant.Builder(
      AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
      CloudEndpointBuilderHelper.getRequestInitializer());

  OfferEndpoint offerEndpoint =
      CloudEndpointBuilderHelper.updateBuilder(endpointBuilder).build().offerEndpoint();

  OfferCollection result;

  try {
    result = offerEndpoint.list(place.getPlaceId()).execute();
  } catch (IOException e) {
    String message = e.getMessage();
    if (message == null) {
      message = e.toString();
    }
    log.severe("Exception=" + message);
    result = null;
  }
  return result;
}
 
Example 9
Source File: PlaceDetailsActivity.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the list of recommendations through appropriate CloudEndpoint.
 *
 * @param params the place for which to retrieve recommendations.
 * @return collection of retrieved recommendations.
 */
@Override
protected CollectionResponseRecommendation doInBackground(Place... params) {
  Recommendationendpoint.Builder endpointBuilder = new Recommendationendpoint.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), null);
  endpointBuilder = CloudEndpointUtils.updateBuilder(endpointBuilder);
  CollectionResponseRecommendation result;
  Recommendationendpoint endpoint = endpointBuilder.build();
  try {
    result = endpoint.listRecommendation().execute();
  } catch (IOException e) {
    e.printStackTrace();
    result = null;
  }
  return result;
}
 
Example 10
Source File: MainActivity.01.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * Calls appropriate CloudEndpoint to indicate that user checked into a place.
 *
 * @param params the place where the user is checking in.
 */
@Override
protected Void doInBackground(Void... params) {
  CheckIn checkin = new CheckIn();
  
  // Set the ID of the store where the user is. 
  // This would be replaced by the actual ID in the final version of the code. 
  checkin.setPlaceId("StoreNo123");

  Checkinendpoint.Builder builder = new Checkinendpoint.Builder(
      AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
      null);
      
  builder = CloudEndpointUtils.updateBuilder(builder);

  Checkinendpoint endpoint = builder.build();
  

  try {
    endpoint.insertCheckIn(checkin).execute();
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

  return null;
}
 
Example 11
Source File: PlaceDetailsActivity.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the list of recommendations through appropriate CloudEndpoint.
 *
 * @param params the place for which to retrieve recommendations.
 * @return collection of retrieved recommendations.
 */
@Override
protected CollectionResponseRecommendation doInBackground(Place... params) {
  Recommendationendpoint.Builder endpointBuilder = new Recommendationendpoint.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), null);
  endpointBuilder = CloudEndpointUtils.updateBuilder(endpointBuilder);
  CollectionResponseRecommendation result;
  Recommendationendpoint endpoint = endpointBuilder.build();
  try {
    result = endpoint.listRecommendation().execute();
  } catch (IOException e) {
    e.printStackTrace();
    result = null;
  }
  return result;
}
 
Example 12
Source File: PlaceDetailsActivity.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the list of offers through appropriate CloudEndpoint.
 * @param params the place for which to retrieve offers.
 * @return collection of retrieved offers.
 */
@Override
protected CollectionResponseOffer doInBackground(Place... params) {
    Offerendpoint.Builder endpointBuilder = new Offerendpoint.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), null);
    endpointBuilder = CloudEndpointUtils.updateBuilder(endpointBuilder);
    CollectionResponseOffer result;
    Offerendpoint endpoint = endpointBuilder.build();
    try {
      result = endpoint.listOffer().execute();
    } catch (IOException e){
      e.printStackTrace();
      result=null;
    }
    return result;
}
 
Example 13
Source File: GCMIntentService.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
public GCMIntentService() {
  super(PROJECT_NUMBER);
  Deviceinfoendpoint.Builder endpointBuilder = new Deviceinfoendpoint.Builder(
      AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
      new HttpRequestInitializer() {
        public void initialize(HttpRequest httpRequest) {
        }
      });
  endpoint = CloudEndpointUtils.updateBuilder(endpointBuilder).build();
}
 
Example 14
Source File: PlaceDetailsActivity.java    From solutions-mobile-shopping-assistant-android-client with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the list of recommendations through appropriate CloudEndpoint.
 *
 * @param params the place for which to retrieve recommendations.
 * @return collection of retrieved recommendations.
 */
@Override
protected RecommendationCollection doInBackground(PlaceInfo... params) {
  PlaceInfo place = params[0];

  if (place == null) {
    return null;
  }

  Builder endpointBuilder = new Shoppingassistant.Builder(
      AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
      CloudEndpointBuilderHelper.getRequestInitializer());

  RecommendationEndpoint recommendationEndpoint =
      CloudEndpointBuilderHelper.updateBuilder(endpointBuilder)
          .build().recommendationEndpoint();

  RecommendationCollection result;

  try {
    result = recommendationEndpoint.list(place.getPlaceId()).execute();
  } catch (IOException e) {
    String message = e.getMessage();
    if (message == null) {
      message = e.toString();
    }
    log.severe("Exception=" + message);
    result = null;
  }
  return result;
}
 
Example 15
Source File: PlaceDetailsActivity.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the list of offers through appropriate CloudEndpoint.
 * @param params the place for which to retrieve offers.
 * @return collection of retrieved offers.
 */
@Override
protected CollectionResponseOffer doInBackground(Place... params) {
    Offerendpoint.Builder endpointBuilder = new Offerendpoint.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), null);
    endpointBuilder = CloudEndpointUtils.updateBuilder(endpointBuilder);
    CollectionResponseOffer result;
    Offerendpoint endpoint = endpointBuilder.build();
    try {
      result = endpoint.listOffer().execute();
    } catch (IOException e){
      e.printStackTrace();
      result=null;
    }
    return result;
}
 
Example 16
Source File: OIDCRequestManager.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
/**
 *  Exchanges a Refresh Token for a new set of tokens.
 *
 *  Note that the Token Server may require you to use the `offline_access` scope to receive
 *  Refresh Tokens.
 *
 * @param refreshToken the refresh token used to request new Access Token / idToken.
 * @return the parsed successful token response received from the token endpoint
 * @throws IOException for an error response
 */
public TokenResponse refreshTokens(String refreshToken) throws IOException {

    List<String> scopesList = Arrays.asList(scopes);

    RefreshTokenRequest request = new RefreshTokenRequest(
            AndroidHttp.newCompatibleTransport(),
            new GsonFactory(),
            new GenericUrl(tokenEndpoint),
            refreshToken);

    if (!scopesList.isEmpty()) {
        request.setScopes(scopesList);
    }

    // This are extra query parameters that can be specific to an OP. For instance prompt -> consent
    // tells the Authorization Server that it SHOULD prompt the End-User for consent before returning
    // information to the Client.
    if (extras != null) {
        for (Map.Entry<String, String> queryParam : extras.entrySet()) {
            request.set(queryParam.getKey(), queryParam.getValue());
        }
    }

    // If the oidc client is confidential (needs authentication)
    if (!TextUtils.isEmpty(clientSecret)) {
        request.setClientAuthentication(new BasicAuthentication(clientId, clientSecret));
    } else {
        request.set("client_id", clientId);
    }

    if (useOAuth2) {
        if (scopesList.contains("openid")) {
            Log.w(TAG, "Using OAuth2 only request but scopes contain values for OpenId Connect");
        }
        return request.executeUnparsed().parseAs(TokenResponse.class);
    } else {
        return IdTokenResponse.execute(request);
    }
}
 
Example 17
Source File: CloudVisionUtils.java    From doorbell with Apache License 2.0 5 votes vote down vote up
/**
 * Construct an annotated image request for the provided image to be executed
 * using the provided API interface.
 *
 * @param imageBytes image bytes in JPEG format.
 * @return collection of annotation descriptions and scores.
 */
public static Map<String, Float> annotateImage(byte[] imageBytes) throws IOException {
    // Construct the Vision API instance
    HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
    VisionRequestInitializer initializer = new VisionRequestInitializer(CLOUD_VISION_API_KEY);
    Vision vision = new Vision.Builder(httpTransport, jsonFactory, null)
            .setVisionRequestInitializer(initializer)
            .build();

    // Create the image request
    AnnotateImageRequest imageRequest = new AnnotateImageRequest();
    Image img = new Image();
    img.encodeContent(imageBytes);
    imageRequest.setImage(img);

    // Add the features we want
    Feature labelDetection = new Feature();
    labelDetection.setType(LABEL_DETECTION);
    labelDetection.setMaxResults(MAX_LABEL_RESULTS);
    imageRequest.setFeatures(Collections.singletonList(labelDetection));

    // Batch and execute the request
    BatchAnnotateImagesRequest requestBatch = new BatchAnnotateImagesRequest();
    requestBatch.setRequests(Collections.singletonList(imageRequest));
    BatchAnnotateImagesResponse response = vision.images()
            .annotate(requestBatch)
            // Due to a bug: requests to Vision API containing large images fail when GZipped.
            .setDisableGZipContent(true)
            .execute();

    return convertResponseToMap(response);
}
 
Example 18
Source File: CheckupReminders.java    From Crimson with Apache License 2.0 5 votes vote down vote up
public MakeRequestTask(GoogleAccountCredential credential) {
    HttpTransport transport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    mService = new com.google.api.services.calendar.Calendar.Builder(
            transport, jsonFactory, credential)
            .setApplicationName("Google Calendar API Android Quickstart")
            .build();
}
 
Example 19
Source File: MainActivity.java    From solutions-mobile-shopping-assistant-android-client with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves the list of nearby places through appropriate CloudEndpoint.
 *
 * @param params the current geolocation for which to retrieve the list of nearby places.
 * @return the collection of retrieved nearby places.
 */
@Override
protected PlaceInfoCollection doInBackground(Location... params) {
  Location checkInLocation = params[0];

  float longitude;
  float latitude;

  if (checkInLocation == null) {
    // return null;
    // TODO(user): Remove this temporary code and just return null

    longitude = (float) -122.12151;
    latitude = (float) 47.67399;
  } else {
    latitude = (float) checkInLocation.getLatitude();
    longitude = (float) checkInLocation.getLongitude();
  }

  Builder endpointBuilder = new Shoppingassistant.Builder(
      AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
      CloudEndpointBuilderHelper.getRequestInitializer());

  PlaceEndpoint placeEndpoint =
      CloudEndpointBuilderHelper.updateBuilder(endpointBuilder).build().placeEndpoint();

  PlaceInfoCollection result;

  // Retrieve the list of up to 10 places within 50 kms
  try {
    long distanceInKm = 50;
    int count = 10;

    result = placeEndpoint.list(
        count, distanceInKm, Float.toString(latitude), Float.toString(longitude)).execute();
  } catch (IOException e) {
    if (e != null) {
      String message = e.getMessage();
      if (message == null) {
        message = e.toString();
      }
      log.severe("Exception=" + message);
    }
    result = null;
  }
  return result;
}
 
Example 20
Source File: RegisterActivity.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_register);
  Button regButton = (Button) findViewById(R.id.regButton);

  registerListener = new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
      switch (event.getAction() & MotionEvent.ACTION_MASK) {
      case MotionEvent.ACTION_DOWN:
        if (GCMIntentService.PROJECT_NUMBER == null
            || GCMIntentService.PROJECT_NUMBER.length() == 0) {
          showDialog("Unable to register for Google Cloud Messaging. "
              + "Your application's PROJECT_NUMBER field is unset! You can change "
              + "it in GCMIntentService.java");
        } else {
          updateState(State.REGISTERING);
          try {
            GCMIntentService.register(getApplicationContext());
          } catch (Exception e) {
            Log.e(RegisterActivity.class.getName(),
                "Exception received when attempting to register for Google Cloud "
                    + "Messaging. Perhaps you need to set your virtual device's "
                    + " target to Google APIs? "
                    + "See https://developers.google.com/eclipse/docs/cloud_endpoints_android"
                    + " for more information.", e);
            showDialog("There was a problem when attempting to register for "
                + "Google Cloud Messaging. If you're running in the emulator, "
                + "is the target of your virtual device set to 'Google APIs?' "
                + "See the Android log for more details.");
            updateState(State.UNREGISTERED);
          }
        }
        return true;
      case MotionEvent.ACTION_UP:
        return true;
      default:
        return false;
      }
    }
  };

  unregisterListener = new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
      switch (event.getAction() & MotionEvent.ACTION_MASK) {
      case MotionEvent.ACTION_DOWN:
        updateState(State.UNREGISTERING);
        GCMIntentService.unregister(getApplicationContext());
        return true;
      case MotionEvent.ACTION_UP:
        return true;
      default:
        return false;
      }
    }
  };

  regButton.setOnTouchListener(registerListener);
  
  /*
   * build the messaging endpoint so we can access old messages via an endpoint call
   */
  MessageEndpoint.Builder endpointBuilder = new MessageEndpoint.Builder(
      AndroidHttp.newCompatibleTransport(),
      new JacksonFactory(),
      new HttpRequestInitializer() {
        public void initialize(HttpRequest httpRequest) { }
      });

  messageEndpoint = CloudEndpointUtils.updateBuilder(endpointBuilder).build();
}