I need to replace CognitoCachingCredentialsProvider with custom AWSCredentialsProvider, to add custom headers with every IoT request, is this possible and how?
My current code snippet:
CognitoCachingCredentialsProvider credentialsProvider;
AWSIotDataClient iotDataClient = new AWSIotDataClient(credentialsProvider); iotDataClient.setEndpoint(AWSConstants.CUSTOMER_SPECIFIC_ENDPOINT);
GetThingShadowRequest request = new GetThingShadowRequest()
.withThingName(AWSConstants.TEMP_THING_NAME);
GetThingShadowResult result = iotDataClient.getThingShadow(request);
Now what I want to do is to replace CognitoCachingCredentialsProvider with custom CredentialsProvider to add custom headers with every iot request.
My Team just contacted aws support and the above question is not applicable.
Edit: aws team is working on that right now, feature will be available soon
Related
I am trying to use Firebase Admin on a Servlet that is communicating on App Engine (Google Cloud Platform). I am using a Servlet because I need to generate a Token towards to validate my access to another API that I am using.
Did anyone have this successful history using Firebase on a Servlet?
I am using com.google.firebase:firebase-admin:5.2.0
App Engine SDK
com.google.appengine:appengine-java-sdk:1.9.50
com.google.appengine:appengine-api-1.0-sdk:1.9.54
Inside the GET I am taking the Token to access the Merchant API.
String mToken = gateway.clientToken().generate();
JSONObject jsonObject = new JSONObject();
jsonObject.put("nonce", mToken);
resp.getWriter().println(jsonObject.toString());
Inside the POST Firebase Admin Full Privileges.
All firebase is inside of a single try and the Transaction Request is in another try.
FileInputStream serviceAccount = new FileInputStream("/WEB-INF/...json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
.setDatabaseUrl("https://MyProject.firebaseio.com/")
.build();
FirebaseApp.initializeApp(options);
IAM already grant the read permission.
Firebase Database Reference with the Transaction
DatabaseReference ref = FirebaseDatabase
.getInstance()
.getReference("price");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String res = (String) dataSnapshot.getValue();
try {
TransactionRequest request = new TransactionRequest()
.amount(new BigDecimal(res)) //Res doesn't show any error but it also doesn't work
.paymentMethodNonce(nonce)
.options()
.submitForSettlement(true)
.storeInVaultOnSuccess(true)
.done();
Result<Transaction> result = gateway.transaction().sale(request);
Thanks.
Firebase Java Admin SDK often gets used inside servlets. You will need to use a manually scaled instance to deploy on App Engine. Firebase database client starts long running threads, and hence cannot operate on the auto-scaled instances (the new GAE java8 runtime seems more lenient in this regard, but I cannot confirm that right now).
I would recommend you to call FirebaseApp.initializeApp() only once per app, ideally inside a ServletContextListener. Then in your servlet, you should be able to perform your transaction as you do now.
I have an issue with implementing Android AWS Amazon push notification using firebase, in Amazon sample, it shows you to add this line of code
link
AWSMobileClient.defaultMobileClient().getPinpointManager().getNotificationClient().registerGCMDeviceToken(refreshedToken);
But once you add it to the project AWSMobileClient class not initialized so I have added these SDK's
compile 'com.amazonaws:aws-android-sdk-core:2.4.5'
compile 'com.amazonaws:aws-android-sdk-cognito:2.4.5'
compile 'com.amazonaws:aws-android-sdk-pinpoint:2.4.5'
compile 'com.amazonaws:aws-android-sdk-mobileanalytics:2.4.5'
But they didn't initialize, after searching I found that you have to add the sample so I added it
Sample classes
but the classes didn't initialize.
So is there any straightforward example to Initializing this thank you.
Hopefully this helps. You'll need to fill in:
IDENTITY_POOL_ID
APP_ID
Adjust Regions.US_EAST_1 to whichever region you are using.
Code:
CognitoCachingCredentialsProvider cognitoCachingCredentialsProvider = new CognitoCachingCredentialsProvider(context,"IDENTITY_POOL_ID",Regions.US_EAST_1);
PinpointConfiguration config = new PinpointConfiguration(context, "APP_ID", Regions.US_EAST_1, cognitoCachingCredentialsProvider);
PinpointManager pinpointManager = new PinpointManager(config);
pinpointManager.getNotificationClient().registerGCMDeviceToken(refreshedToken);
I am creating the Node using the PUBSUB protocol using the link
http://download.igniterealtime.org/smack/docs/latest/documentation/extensions/pubsub.html
Could anyone help me to get the list of items subscribed,created for a particular user? Here's my code:
PubSubManager manager = PubSubManager.getInstance(connection);
LeafNode leaf = mgr.createNode("testNode");
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setAccessModel(AccessModel.open);
form.setDeliverPayloads(false);
form.setNotifyRetract(true);
form.setPersistentItems(true);
form.setPublishModel(PublishModel.open);
leaf.sendConfigurationForm(form);
I am willing to do something like this
manager.getAllListofSubscriedItems(){
// TO DO Implementation here, **Need some idea here**
}
You can use PubSubManager to discover nodes tree.
Use
discoverNodes
getAffiliations()
http://download.igniterealtime.org/smack/docs/latest/javadoc/
I have an API working with Cloud Endpoints and I added its generated client library to my Android app.
However I don't know how to add information to my requests. For now, here is the only HTTP request I know how to send using the client library:
DrinkEndpoint.Builder builder = new DrinkEndpoint.Builder(AndroidHttp.newCompatibleTransport(),new GsonFactory(), null);
DrinkEndpoint service = builder.build();
Drink drink = new Drink();
drink.setName(params[0]);
response = service.insertDrink(drink).execute();
So my question is: how to modify this request to add information either in the headers or in the body of the request?
For instance, I want to add a String that is not an attribute of the Drink entity.
Thank you
Your insertDrink(drink) method returns a InsertDrink instance which is a child of InsertDrinkEndpointRequest.
The InsertDrinkEndpointRequest instance allows you to set the request header by calling the setRequestHeaders(httpHeader) method.
In your case: service.insertDrink(drink).setRequestHeaders(httpHeader).execute().
This way of building a cloud endpoint request may help you: https://stackoverflow.com/a/21492950/2205582
in a nutshell:
Can I work with the Google Play Android Developer API from server-side without providing any app in the play store?
Background:
I'm working on a project which provides apps with monthly subscriptions. The coresponding data of each subscription (purchase token, date etc) gets stored in the backend database.
Now I want to create a cronjob that iterates through each of these datasets.And for each subscription I'd like to contact the Google API to retrieve the information if the subscription is still valid or not, and update our database corresponding to the responsed status.
For the backend logic I use the google-api-java-client library.
To either cancel or verify subscriptions I need to authenticate myself with OAuth2 before.
Been there, done that.
new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes("https://www.googleapis.com/auth/androidpublisher") // $1
.setServiceAccountPrivateKeyFromP12File(new File(filePath))
.setClientSecrets(CLIENT_ID, CLIENT_SECRET) // $2
.build();
$1: I don't know if the given account scope is valid. Because I just could find this value in a very few examples, but neither in this overview nor in the google playground
$2 I guess this is necessary, even though I found a lot of example which did not provide this information.
But, unfortunately, I can't see any differences when I provide invalid data (like wrong email or private key).
Questions
How can i verify that the GoogleCredential is correct?
May I just see it in the next steps, like contacting ie the androidpublisher API?
In the next step I try to get purchase status of a subscription:
Androidpublisher publisher = new Androidpublisher.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(GOOGLE_PRODUCT_NAME) // $1
.build();
Androidpublisher.Purchases purchases = publisher.purchases();
Androidpublisher.Purchases.Get get = purchases.get("android.test.purchased", "monthly001", "mytoken"); // $2
SubscriptionPurchase subscripcion = get.execute();
$1: My dummy product name from the API console -> API Access
$2: Beside the fact, that the androidpush API does not allow contacting it via service accounts, but only via web server applications auth flow, I don't have any clue what to insert in the parameter of the get- method.
Here's the API:
https://developers.google.com/android-publisher/v1/purchases/get
Questions
What is the package name and what is the subscriptionId in this context?
Where do I get/set these values?
After reading this document I know there is a way to to deal with fake/static responses. But I can't read anywhere if this is also possible for subscriptions, or just for in-app-billings on mobile devices only.
I'm wondering anyway why/if there is any easy way of developing with a sandbox or s.th. simliar.
I still have the feeling that I'm just missing a big part to understand how the things should work.
Maybe someone of you can give me a hint how to proceed at this place or may say me where i'm wrong.
Kind regards,
Christopher
I could now figure out most of my previous understanding problems.
=1= GENERATE AUTHORIZATION URL
String authorizeUrl = new GoogleAuthorizationCodeRequestUrl(googleClientId,callbackUrl,"https://www.googleapis.com/auth/androidpublisher").build()
// See why: http://stackoverflow.com/questions/8433990/when-authenticating-with-oauth-and-youtube-always-get-error-invalid-grant-on
authorizeUrl += "&approval_prompt=force&access_type=offline"
=2= AUTHENTICATE
Since the server-webflow is not working for the androidpublisher API the customer must now call the URL generated in (1) manually.
=3= CALLBACK
The google callback should process the next steps. The callback contains the parameter "code" which we have to use.
=4= REQUEST AUTH-TOKEN
// Build the HTTP parameter
Map<String,String> params = [:]
params.put("grant_type", "authorization_code")
params.put("code", code.encodeAsURL())
params.put("client_id", customer.googleClientId.encodeAsURL())
params.put("client_secret", customer.googleClientSecret.encodeAsURL())
params.put("redirect_uri", getCallbackUrl().encodeAsURL())
// Send the POST request
// This action might throw an exception in case any parameter were wrong, invalid or not specified.
String result = HttpRequestHandler.sendRequest("https://accounts.google.com/o/oauth2/token", params);
JSONElement jsonResult = JSON.parse(result)
// Map result
OAuth2Result oAuth2Result = new OAuth2Result()
oAuth2Result.accessToken = jsonResult.getAt("access_token")
oAuth2Result.refreshToken = jsonResult.getAt("refresh_token")
oAuth2Result.ttlSeconds = Integer.parseInt(jsonResult.getAt("expires_in").toString())
oAuth2Result.tokenType = jsonResult.getAt("token_type")
=5= REQUEST REFRESH TOKEN
// Build the HTTP parameter
Map<String,String> params = [:]
params.put("grant_type", "refresh_token")
params.put("refresh_token", this.customer.googleRefreshToken.encodeAsURL())
params.put("client_id", customer.googleClientId.encodeAsURL())
params.put("client_secret", customer.googleClientSecret.encodeAsURL())
// Send the POST request
// This action might throw an exception in case any parameter were wrong, invalid or not specified.
String result = HttpRequestHandler.sendRequest("https://accounts.google.com/o/oauth2/token", params);
JSONElement jsonResult = JSON.parse(result)
// Map result
OAuth2Result oAuth2Result = new OAuth2Result()
oAuth2Result.accessToken = jsonResult.getAt("access_token")
oAuth2Result.refreshToken = jsonResult.getAt("refresh_token")
oAuth2Result.ttlSeconds = Integer.parseInt(jsonResult.getAt("expires_in").toString())
oAuth2Result.tokenType = jsonResult.getAt("token_type")