本文整理匯總了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;
}
示例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;
}
示例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();
}
示例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();
}
示例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();
}
示例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();
}
示例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();
}
示例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;
}
示例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());
}
示例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();
}
示例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);
}
}
示例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);
}
}
示例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();
}
}
示例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);
}