当前位置: 首页>>代码示例>>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;未经允许,请勿转载。