當前位置: 首頁>>代碼示例>>Java>>正文


Java GsonFactory類代碼示例

本文整理匯總了Java中com.google.api.client.json.gson.GsonFactory的典型用法代碼示例。如果您正苦於以下問題:Java GsonFactory類的具體用法?Java GsonFactory怎麽用?Java GsonFactory使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


GsonFactory類屬於com.google.api.client.json.gson包,在下文中一共展示了GsonFactory類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: parseResponse

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
/**
 * Parse the response from the HTTP call into an instance of the given class.
 *
 * @param response The parsed response object
 * @param c The class to instantiate and use to build the response object
 * @return The ApiResponse object
 * @throws IOException Any IO errors
 */
protected ApiResponse parseResponse(HttpResponse response, Class<?> c) throws IOException {
  ApiResponse res = null;
  InputStream in = response.getContent();

  if (in == null) {
    try {
      res = (ApiResponse)c.newInstance();
    } catch(ReflectiveOperationException e) {
      throw new RuntimeException("Cannot instantiate " + c, e);
    }
  } else {
    try {
      JsonParser jsonParser = GsonFactory.getDefaultInstance().createJsonParser(in);
      res = (ApiResponse)jsonParser.parse(c);
    } finally {
      in.close();
    }
  }

  res.setHttpRequest(response.getRequest());
  res.setHttpResponse(response);

  return res;
}
 
開發者ID:dnsimple,項目名稱:dnsimple-java,代碼行數:33,代碼來源:HttpEndpointClient.java

示例2: get

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
public static Messaging get(Context context){
    if (messagingService == null) {
        SharedPreferences settings = context.getSharedPreferences(
                "Watchpresenter", Context.MODE_PRIVATE);
        final String accountName = settings.getString(Constants.PREF_ACCOUNT_NAME, null);
        if(accountName == null){
            Log.i(Constants.LOG_TAG, "Cannot send message. No account name found");
        }
        else {
            GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(context,
                    "server:client_id:" + Constants.ANDROID_AUDIENCE);
            credential.setSelectedAccountName(accountName);
            Messaging.Builder builder = new Messaging.Builder(AndroidHttp.newCompatibleTransport(),
                    new GsonFactory(), credential)
                    .setRootUrl(Constants.SERVER_URL);

            messagingService = builder.build();
        }
    }
    return messagingService;
}
 
開發者ID:google,項目名稱:watchpresenter,代碼行數:22,代碼來源:MessagingService.java

示例3: sync

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
private static void sync(Context context, boolean fullSync) {
  SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
  GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(context,
      "server:client_id:988087637760-6rhh5v6lhgjobfarparsomd4gectmk1v.apps.googleusercontent.com");
  String accountName = preferences.getString(PREF_ACCOUNT_NAME, null);
  if (accountName == null || accountName.isEmpty()) {
    // If you haven't set up an account yet, then we can't sync anyway.
    Log.w(TAG, "No account set, cannot sync!");
    return;
  }

  boolean hasGetAccountsPermission = ContextCompat.checkSelfPermission(
      context, Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED;
  if (!hasGetAccountsPermission) {
    Log.w(TAG, "Don't have GET_ACCOUNTS permission, can't sync.");
    return;
  }

  Log.d(TAG, "Using account: " + accountName);
  credential.setSelectedAccountName(accountName);

  Syncsteps.Builder builder = new Syncsteps.Builder(
      AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential);
  builder.setApplicationName("Steptastic");
  new StepSyncer(context, builder.build(), fullSync).sync();
}
 
開發者ID:codeka,項目名稱:steptastic,代碼行數:27,代碼來源:StepSyncer.java

示例4: getMBSEndpoint

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
private Mobilebackend getMBSEndpoint() {

        // check if credential has account name
        final GoogleAccountCredential gac = mCredential == null
                || mCredential.getSelectedAccountName() == null ? null : mCredential;

        // create HttpRequestInitializer
        HttpRequestInitializer hri = new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) throws IOException {
                request.setBackOffPolicy(new ExponentialBackOffPolicy());
                if (gac != null) {
                    gac.initialize(request);
                }
            }
        };

        // build MBS builder
        // (specify gac or hri as the third parameter)
        return new Mobilebackend.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(),
                hri)
                .setRootUrl(Consts.ENDPOINT_ROOT_URL).build();
    }
 
開發者ID:pkill9,項目名稱:POSproject,代碼行數:24,代碼來源:CloudBackend.java

示例5: onCreate

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:GoogleCloudPlatform,項目名稱:appengine-endpoints-tictactoe-android,代碼行數:26,代碼來源:TictactoeActivity.java

示例6: getMBSEndpoint

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
private Mobilebackend getMBSEndpoint() {

    // check if credential has account name
    final GoogleAccountCredential gac = credential == null
        || credential.getSelectedAccountName() == null ? null : credential;

    // create HttpRequestInitializer
    HttpRequestInitializer hri = new HttpRequestInitializer() {
      @Override
      public void initialize(HttpRequest request) throws IOException {
        request.setBackOffPolicy(new ExponentialBackOffPolicy());
        if (gac != null) {
          gac.initialize(request);
        }
      }
    };

    // build MBS builder
    // (specify gac or hri as the third parameter)
    return new Mobilebackend.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), hri)
        .setRootUrl(Consts.ENDPOINT_ROOT_URL).build();
  }
 
開發者ID:harrypritchett,項目名稱:Give-Me-Ltc-Android-App,代碼行數:23,代碼來源:CloudBackend.java

示例7: generateWebserviceResponseJwt

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
/**
 * Generates the linking/signup JWT from a Wallet Object
 *
 * @param object
 * @param resp
 * @return
 * @throws SignatureException
 */
public String generateWebserviceResponseJwt(GenericJson object,
    WebserviceResponse resp) throws SignatureException {

  JsonToken token = new JsonToken(signer);
  token.setAudience(GOOGLE);
  token.setParam("typ", LOYALTY_WEB);
  token.setIssuedAt(new Instant(
      Calendar.getInstance().getTimeInMillis() - 5000L));
  WobPayload payload = new WobPayload();

  if (object != null) {
    object.setFactory(new GsonFactory());
    payload.addObject(object);
  }

  payload.setResponse(resp);
  JsonObject obj = gson.toJsonTree(payload).getAsJsonObject();
  token.getPayloadAsJsonObject().add("payload", obj);
  return token.serializeAndSign();
}
 
開發者ID:android-pay,項目名稱:s2ap-quickstart-java,代碼行數:29,代碼來源:WobUtils.java

示例8: getMBSEndpoint

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
private Mobilebackend getMBSEndpoint() {

        // check if credential has account name
        final GoogleAccountCredential gac = credential == null || credential.getSelectedAccountName() == null ? null
                : credential;

        // create HttpRequestInitializer
        HttpRequestInitializer hri = new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) throws IOException {
                request.setBackOffPolicy(new ExponentialBackOffPolicy());
                if (gac != null) {
                    gac.initialize(request);
                }
            }
        };

        // build MBS builder
        // (specify gac or hri as the third parameter)
        return new Mobilebackend.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), hri).setRootUrl(
                Consts.ENDPOINT_ROOT_URL).build();
    }
 
開發者ID:yanzm,項目名稱:MobileBackendStarter,代碼行數:23,代碼來源:CloudBackend.java

示例9: getInstance

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
public static FirebaseTokenFactory getInstance() {
  if (null == instance) {
    instance = new FirebaseTokenFactory(new GsonFactory(), Clock.SYSTEM);
  }

  return instance;
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:8,代碼來源:FirebaseTokenFactory.java

示例10: createOptionsWithAllValuesSet

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
@Test
public void createOptionsWithAllValuesSet() throws IOException, InterruptedException {
  GsonFactory jsonFactory = new GsonFactory();
  NetHttpTransport httpTransport = new NetHttpTransport();
  FirebaseOptions firebaseOptions =
      new FirebaseOptions.Builder()
          .setDatabaseUrl(FIREBASE_DB_URL)
          .setStorageBucket(FIREBASE_STORAGE_BUCKET)
          .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
          .setProjectId(FIREBASE_PROJECT_ID)
          .setJsonFactory(jsonFactory)
          .setHttpTransport(httpTransport)
          .setThreadManager(MOCK_THREAD_MANAGER)
          .build();
  assertEquals(FIREBASE_DB_URL, firebaseOptions.getDatabaseUrl());
  assertEquals(FIREBASE_STORAGE_BUCKET, firebaseOptions.getStorageBucket());
  assertEquals(FIREBASE_PROJECT_ID, firebaseOptions.getProjectId());
  assertSame(jsonFactory, firebaseOptions.getJsonFactory());
  assertSame(httpTransport, firebaseOptions.getHttpTransport());
  assertSame(MOCK_THREAD_MANAGER, firebaseOptions.getThreadManager());

  GoogleCredentials credentials = firebaseOptions.getCredentials();
  assertNotNull(credentials);
  assertTrue(credentials instanceof ServiceAccountCredentials);
  assertEquals(
      GoogleCredential.fromStream(ServiceAccount.EDITOR.asStream()).getServiceAccountId(),
      ((ServiceAccountCredentials) credentials).getClientEmail());
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:29,代碼來源:FirebaseOptionsTest.java

示例11: createDriveService

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
private Drive createDriveService(String accountName, Context appContext) {
	logDebug("createDriveService "+accountName);
	GoogleAccountCredential credential = createCredential(appContext);
	credential.setSelectedAccountName(accountName);

	return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
	.setApplicationName(getApplicationName())
	.build();
}
 
開發者ID:PhilippC,項目名稱:keepass2android,代碼行數:10,代碼來源:GoogleDriveFileStorage.java

示例12: create

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
public static Drive create(Context context, String googleDriveAccount) throws IOException, GoogleAuthException, ImportExportException {
    if (googleDriveAccount == null) {
        throw new ImportExportException(R.string.google_drive_account_required);
    }
    try {
        List<String> scope = new ArrayList<String>();
        scope.add(DriveScopes.DRIVE_FILE);
        if (MyPreferences.isGoogleDriveFullReadonly(context)) {
            scope.add(DriveScopes.DRIVE_READONLY);
        }
        GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, scope);
        credential.setSelectedAccountName(googleDriveAccount);
        credential.getToken();
        return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
    } catch (UserRecoverableAuthException e) {
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Intent authorizationIntent = e.getIntent();
        authorizationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(
                Intent.FLAG_FROM_BACKGROUND);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                authorizationIntent, 0);
        Notification notification = new NotificationCompat.Builder(context)
                .setSmallIcon(android.R.drawable.ic_dialog_alert)
                .setTicker(context.getString(R.string.google_drive_permission_requested))
                .setContentTitle(context.getString(R.string.google_drive_permission_requested))
                .setContentText(context.getString(R.string.google_drive_permission_requested_for_account, googleDriveAccount))
                .setContentIntent(pendingIntent).setAutoCancel(true).build();
        notificationManager.notify(0, notification);
        throw new ImportExportException(R.string.google_drive_permission_required);
    }
}
 
開發者ID:tiberiusteng,項目名稱:financisto1-holo,代碼行數:33,代碼來源:GoogleDriveClient.java

示例13: create

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
public static Drive create(Context context) throws IOException, GoogleAuthException, ImportExportException {
    String googleDriveAccount = MyPreferences.getGoogleDriveAccount(context);
    if (googleDriveAccount == null) {
        throw new ImportExportException(R.string.google_drive_account_required);
    }
    try {
        List<String> scope = new ArrayList<String>();
        scope.add(DriveScopes.DRIVE_FILE);
        if (MyPreferences.isGoogleDriveFullReadonly(context)) {
            scope.add(DriveScopes.DRIVE_READONLY);
        }
        GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, scope);
        credential.setSelectedAccountName(googleDriveAccount);
        credential.getToken();
        return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
    } catch (UserRecoverableAuthException e) {
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Intent authorizationIntent = e.getIntent();
        authorizationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(
                Intent.FLAG_FROM_BACKGROUND);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                authorizationIntent, 0);
        Notification notification = new NotificationCompat.Builder(context)
                .setSmallIcon(android.R.drawable.ic_dialog_alert)
                .setTicker(context.getString(R.string.google_drive_permission_requested))
                .setContentTitle(context.getString(R.string.google_drive_permission_requested))
                .setContentText(context.getString(R.string.google_drive_permission_requested_for_account, googleDriveAccount))
                .setContentIntent(pendingIntent).setAutoCancel(true).build();
        notificationManager.notify(0, notification);
        throw new ImportExportException(R.string.google_drive_permission_required);
    }
}
 
開發者ID:tiberiusteng,項目名稱:financisto1-holo,代碼行數:34,代碼來源:GoogleDrivePictureClient.java

示例14: getJsonFactory

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
/**
 * Class instance of the JSON factory.
 */
public static final JsonFactory getJsonFactory() {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // only for honeycomb and newer versions
        return new AndroidJsonFactory();
    } else {
        return new GsonFactory();
    }
}
 
開發者ID:pe-pan,項目名稱:flappy,代碼行數:12,代碼來源:BestScoreService.java

示例15: annotateImage

import com.google.api.client.json.gson.GsonFactory; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:androidthings,項目名稱:doorbell,代碼行數:40,代碼來源:CloudVisionUtils.java


注:本文中的com.google.api.client.json.gson.GsonFactory類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。