My code
AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
.accessKeyId("XXXXXXXXXXXXXXX").secretKey("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
.region("eu-west-1").build();
AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider
.builder().roleArn("XXXXXXXXXXXXX").roleSessionName("123123123")
.build();
LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
.clientId("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
.clientSecret("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
.endpoint("https://api.amazon.com/auth/o2/token").build();
SellersApi sellersApi = new SellersApi.Builder().awsAuthenticationCredentials(awsAuthenticationCredentials)
.lwaAuthorizationCredentials(lwaAuthorizationCredentials)
.awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
.endpoint("https://sellingpartnerapi-eu.amazon.com").build();
GetMarketplaceParticipationsResponse res = sellersApi.getMarketplaceParticipations();
List<MarketplaceParticipation> data = new ArrayList<MarketplaceParticipation>();
data = res.getPayload();
for (MarketplaceParticipation obj : data) {
System.out.println(obj);
}
Error:
Caused by: java.lang.RuntimeException: Error getting LWA Access Token
at com.amazon.SellingPartnerAPIAA.LWAClient.getAccessTokenFromEndpoint(LWAClient.java:74)
at com.amazon.SellingPartnerAPIAA.LWAClient.getAccessTokenFromCache(LWAClient.java:51)
at com.amazon.SellingPartnerAPIAA.LWAClient.getAccessToken(LWAClient.java:40)
at com.amazon.SellingPartnerAPIAA.LWAAuthorizationSigner.sign(LWAAuthorizationSigner.java:69)
at com.amazon.sellingpartner.ApiClient.buildRequest(ApiClient.java:1034)
at com.amazon.sellingpartner.ApiClient.buildCall(ApiClient.java:973)
at com.amazon.sellingpartner.api.SellersApi.getMarketplaceParticipationsCall(SellersApi.java:111)
at com.amazon.sellingpartner.api.SellersApi.getMarketplaceParticipationsValidateBeforeCall(SellersApi.java:118)
at com.amazon.sellingpartner.api.SellersApi.getMarketplaceParticipationsWithHttpInfo(SellersApi.java:141)
at com.amazon.sellingpartner.api.SellersApi.getMarketplaceParticipations(SellersApi.java:130)
at com.yash.spapi.TestSpApiApplication.main(TestSpApiApplication.java:47)
... 5 more
Caused by: java.io.IOException: Unsuccessful LWA token exchange
at com.amazon.SellingPartnerAPIAA.LWAClient.getAccessTokenFromEndpoint(LWAClient.java:63)
... 15 more
You seem not to have provided the refresh token when constructing the LWAAuthorizationCredentials. Try inserting .refreshToken("<your-refresh-token>") after .clientSecret("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").
The following code works for me (with self authorization, and correct security parameters of course):
package amzspapitest;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentialsProvider;
import com.amazon.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import io.swagger.client.ApiException;
import io.swagger.client.api.SellersApi;
import io.swagger.client.model.GetMarketplaceParticipationsResponse;
import io.swagger.client.model.MarketplaceParticipation;
import java.util.List;
import java.util.UUID;
public class AmzSPAPITest {
protected final String awsAccessKeyId = "XXXXXXXXXXXXXXXXXXXX";
protected final String awsSecretAccessKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
protected final String awsRegion = "us-east-1";
protected final String awsRoleArn = "arn:XXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
protected final String awsClientId = "amzn1.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
protected final String awsClientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
protected final String awsRefreshToken = "Atzr|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +
"XXXXXXXXXXXXXXXXXXXXXXXX";
protected final String awsEndpoint = "https://api.amazon.com/auth/o2/token";
public static void main(String[] args) {
new AmzSPAPITest().amazonAwsTest();
}
public void amazonAwsTest() {
try {
AWSAuthenticationCredentials aac = AWSAuthenticationCredentials.builder()
.accessKeyId(awsAccessKeyId)
.secretKey(awsSecretAccessKey)
.region(awsRegion)
.build();
AWSAuthenticationCredentialsProvider aacp = AWSAuthenticationCredentialsProvider.builder()
.roleArn(awsRoleArn)
.roleSessionName(UUID.randomUUID().toString())
.build();
LWAAuthorizationCredentials lac = LWAAuthorizationCredentials.builder()
.clientId(awsClientId)
.clientSecret(awsClientSecret)
.refreshToken(awsRefreshToken)
.endpoint(awsEndpoint)
.build();
SellersApi sa = new SellersApi.Builder()
.awsAuthenticationCredentials(aac)
.lwaAuthorizationCredentials(lac)
.awsAuthenticationCredentialsProvider(aacp)
.endpoint("https://sellingpartnerapi-na.amazon.com")
.build();
GetMarketplaceParticipationsResponse res = sa.getMarketplaceParticipations();
List<MarketplaceParticipation> data = res.getPayload();
for (MarketplaceParticipation obj: data) {
System.out.println(obj);
}
} catch (ApiException e) {
e.printStackTrace(System.err);
}
}
}
Related
I am trying to implement a simple action from the argo workflows example (https://github.com/argoproj/argo-workflows/blob/master/sdks/java/client/docs/WorkflowServiceApi.md), I can do it with the API, but I need to do it from a Java application. The Java SDK doesn't even seem to connect to the Argo API. But the UI is working.
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
String url = "http://xxx.xxx.xxx.xxx:2746";
defaultClient.setBasePath(url);
WorkflowServiceApi apiInstance = new WorkflowServiceApi(defaultClient);
String namespace = "argo"; // String |
String name = "hello-argo"; // String |
String getOptionsResourceVersion = "argoproj.io/v1alpha1"; // String | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset +optional
String fields = ""; // String | Fields to be included or excluded in the response. e.g. \"spec,status.phase\", \"-status.nodes\".
try {
IoArgoprojWorkflowV1alpha1Workflow result = apiInstance.workflowServiceGetWorkflow(namespace, name, getOptionsResourceVersion, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling WorkflowServiceApi#workflowServiceGetWorkflow");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
Here is the error:
Exception when calling WorkflowServiceApi#workflowServiceGetWorkflow
Status code: 0
Reason: null
Response headers: null
io.argoproj.workflow.ApiException: java.io.IOException: unexpected end of stream on http://xxx.xxx.xxx.xxx:2746/...
at io.argoproj.workflow.ApiClient.execute(ApiClient.java:930)
at io.argoproj.workflow.apis.WorkflowServiceApi.workflowServiceGetWorkflowWithHttpInfo(WorkflowServiceApi.java:486)
at io.argoproj.workflow.apis.WorkflowServiceApi.workflowServiceGetWorkflow(WorkflowServiceApi.java:463)
at Argo.main(Argo.java:20)
Caused by: java.io.IOException: unexpected end of stream on http://xxx.xxx.xxx.xxx:2746/...
at okhttp3.internal.http1.Http1ExchangeCodec.readResponseHeaders(Http1ExchangeCodec.kt:202)
at okhttp3.internal.connection.Exchange.readResponseHeaders(Exchange.kt:106)
at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.kt:79)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
at io.argoproj.workflow.ApiClient$2.intercept(ApiClient.java:1267)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:34)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:95)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)
at io.argoproj.workflow.ApiClient.execute(ApiClient.java:926)
... 3 more
Caused by: java.io.EOFException: \n not found: limit=0 content=…
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.kt:332)
at okhttp3.internal.http1.HeadersReader.readLine(HeadersReader.kt:29)`enter code here`
at okhttp3.internal.http1.Http1ExchangeCodec.readResponseHeaders(Http1ExchangeCodec.kt:178)
... 19 more
import io.argoproj.workflow.ApiClient;
import io.argoproj.workflow.ApiException;
import io.argoproj.workflow.Configuration;
import io.argoproj.workflow.models.*;
import io.argoproj.workflow.apis.WorkflowServiceApi;
import io.kubernetes.client.openapi.models.V1Container;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Argo {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setVerifyingSsl(false);
String url = "https://xxx.xxx.xxx.xxx:2746";
defaultClient.setBasePath(url);
WorkflowServiceApi apiInstance = new WorkflowServiceApi(defaultClient);
String namespace = "argo"; // String |
WorkflowCreateRequest body = new WorkflowCreateRequest();// WorkflowCreateRequest |
CreateOptions options = new CreateOptions();
Workflow workflow = new Workflow();
workflow.setApiVersion("argoproj.io/v1alpha1");
V1ObjectMeta meta = new V1ObjectMeta();
meta.setNamespace("argo");
meta.setName("hello-java-client");
WorkflowSpec spec = new WorkflowSpec();
spec.setEntrypoint("argosay");
Template template = new Template();
template.setName("argosay");
V1Container v1Container = new V1Container();
v1Container.setName("pod");
v1Container.setImage("docker/whalesay:latest");
v1Container.setCommand(List.of("cowsay"));
v1Container.setArgs(List.of("test java client"));
template.setContainer(v1Container);
spec.setTemplates(List.of(template));
workflow.setMetadata(meta);
workflow.setSpec(spec);
body.setNamespace("argo");
body.setServerDryRun(false);
body.setWorkflow(workflow);
try {
Workflow result = apiInstance.workflowServiceCreateWorkflow(namespace, body);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling WorkflowServiceApi#workflowServiceCreateWorkflow");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
Try some meaningful value of fields
String fields = "items.spec,items.status.phase";
looking for a sample java code to read parameter store values like RDS connection string from aws parameter store. appreicate code or any reference links. thanks.
Here is the V2 (not V1) example to read a specific parameter value from the AWS parameter store:
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.GetParameterRequest;
import software.amazon.awssdk.services.ssm.model.GetParameterResponse;
import software.amazon.awssdk.services.ssm.model.SsmException;
public class GetParameter {
public static void main(String[] args) {
final String USAGE = "\n" +
"Usage:\n" +
" GetParameter <paraName>\n\n" +
"Where:\n" +
" paraName - the name of the parameter\n";
if (args.length < 1) {
System.out.println(USAGE);
System.exit(1);
}
// Get args
String paraName = args[0];
Region region = Region.US_EAST_1;
SsmClient ssmClient = SsmClient.builder()
.region(region)
.build();
try {
GetParameterRequest parameterRequest = GetParameterRequest.builder()
.name(paraName)
.build();
GetParameterResponse parameterResponse = ssmClient.getParameter(parameterRequest);
System.out.println("The parameter value is "+parameterResponse.parameter().value());
} catch (SsmException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement;
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagementClientBuilder;
import com.amazonaws.services.simplesystemsmanagement.model.GetParametersRequest;
import com.amazonaws.services.simplesystemsmanagement.model.GetParametersResult;
...
private static AWSSimpleSystemsManagement ssmclient = AWSSimpleSystemsManagementClientBuilder
.standard().withRegion(System.getProperty("SystemsManagerRegion")).build();
...
GetParametersRequest paramRequest = new GetParametersRequest()
.withNames(parameterName).withWithDecryption(encrypted);
GetParametersResult paramResult = new GetParametersResult();
paramResult = ssmclient.getParameters(paramRequest);
I think GitHub may be of help. I searched for SsmClient getParameter language:java and some of the results seem promising.
This one for example:
public static String getDiscordToken(SsmClient ssmClient) {
GetParameterRequest request = GetParameterRequest.builder().
name("/discord/token").
withDecryption(Boolean.TRUE).
build();
GetParameterResponse response = ssmClient.getParameter(request);
return response.parameter().value();
}
Data is not added to List. The program gets data from a GraphQL server and filter it through a switch statements, then appends it to the corresponding list. However, the list is empty if accessed outside the switch statement. If you print one of the list in the switch statement, it will print correctly, however if you print it in the getter functions, it will not return anything.
What is wrong with it? The scope? I tried putting the initialization in a few places like on the same function or on the constructor however the result is the same.
package sukebei.anilog.data.source.AniList;
import android.util.Log;
import com.apollographql.apollo.ApolloCall;
import com.apollographql.apollo.ApolloClient;
import com.apollographql.apollo.api.Response;
import com.apollographql.apollo.exception.ApolloException;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import okhttp3.OkHttpClient;
import AniList.UserMediaQuery;
import AniList.UserMediaQuery.Data;
import AniList.type.MediaType;
/* Data Received Example
[
Entry {
__typename = MediaList,
progress = 0,
progressVolumes = null,
score = 0.0,
status = PLANNING,
notes = null,
repeat = 0,
media = Media {
__typename = Media,
chapters = null,
volumes = null,
idMal = 17082,
episodes = 12,
title = Title {
__typename = MediaTitle, romaji = Aiura
}
}
},
Entry {
__typename = MediaList,
progress = 0,
progressVolumes = null,
score = 0.0,
status = PLANNING,
notes = null,
repeat = 0,
media = Media {
__typename = Media,
chapters = null,
volumes = null,
idMal = 33218,
episodes = 1,
title = Title {
__typename = MediaTitle,
romaji = Kimi no Koe wo Todoketai
}
}
}
]
*/
public class AniList {
private static final String BASE_URL = "https://graphql.anilist.co";
private List<UserMediaQuery.Entry> planningMedia = new ArrayList<UserMediaQuery.Entry>();
private List<UserMediaQuery.Entry> currentMedia = new ArrayList<UserMediaQuery.Entry>();
private List<UserMediaQuery.Entry> completedMedia = new ArrayList<UserMediaQuery.Entry>();
private List<UserMediaQuery.Entry> droppedMedia = new ArrayList<UserMediaQuery.Entry>();
private List<UserMediaQuery.Entry> pausedMedia = new ArrayList<UserMediaQuery.Entry>();
private List<UserMediaQuery.Entry> repeatingMedia = new ArrayList<UserMediaQuery.Entry>();
private OkHttpClient okHttpClient;
private ApolloClient apolloClient;
public AniList() {
okHttpClient = new OkHttpClient.Builder().build();
apolloClient = ApolloClient.builder()
.serverUrl(BASE_URL)
.okHttpClient(okHttpClient)
.build();
}
public void loadUserData(String username, MediaType mediaType) {
UserMediaQuery mediaQuery = UserMediaQuery.builder()
.username(username)
.type(mediaType)
.build();
apolloClient.query(mediaQuery).enqueue(new ApolloCall.Callback<Data>() {
#Override public void onResponse(#NotNull Response<Data> dataResponse) {
for (UserMediaQuery.List data : dataResponse.data().userMediaList().lists()) {
for (UserMediaQuery.Entry entry: data.entries()) {
switch(entry.status()) {
case PLANNING:
planningMedia.add(entry);
break;
case CURRENT:
currentMedia.add(entry);
break;
case COMPLETED:
completedMedia.add(entry);
break;
case DROPPED:
droppedMedia.add(entry);
break;
case PAUSED:
pausedMedia.add(entry);
break;
case REPEATING:
repeatingMedia.add(entry);
break;
}
}
}
}
#Override
public void onFailure(#NotNull ApolloException t) {
Log.e("AniList Source", t.getMessage(), t);
}
}
);
}
public List getPlanningMedia() {
return planningMedia;
}
public List getCurrentMedia() {
return currentMedia;
}
public List getCompletedMedia() {
return completedMedia;
}
public List getDroppedMedia() {
return droppedMedia;
}
public List getPausedMedia() {
return pausedMedia;
}
public List getRepeatingMedia() {
return repeatingMedia;
}
}
This prints the data however when you print it in the getter function it does not print the data.
for (UserMediaQuery.List data : dataResponse.data().userMediaList().lists()) {
for (UserMediaQuery.Entry entry: data.entries()) {
if (entry.status() == MediaListStatus.PLANNING) {
planningMedia.add(entry);
Log.d("planning", planningMedia.toString());
}
}
}
apolloClient.query(mediaQuery).enqueue executes code in async, which means it enqueues the request and so the array list will be empty until the request is being done and is successful from another thread.
You might be using the getter directly without waiting for the callback to finish. If that's the case check out the following possible solutions.
If you are waiting for the request to finish to display something on your UI, you might want to bind the data to UI again by using something like notifyDataSetChanged() in case of RecyclerView for instance. Similarly, if you want to use this data for something else you should probably use a callback mechanism.
Hope this helps !!
How can I send a PubSub message manually (that is to say, without using a PubsubIO) in Dataflow ?
Importing (via Maven) google-cloud-dataflow-java-sdk-all 2.5.0 already imports a version of com.google.pubsub.v1 for which I was unable to find an easy way to send messages to a Pubsub topic (this version doesn't, for instance, allow to manipulate Publisher instances, which is the way described in the official documentation).
Would you consider using PubsubUnboundedSink? Quick example:
import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubClient;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubJsonClient;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubUnboundedSink;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubClient.TopicPath;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubMessage;
public class PubsubTest {
public static void main(String[] args) {
DataflowPipelineOptions options = PipelineOptionsFactory.fromArgs(args)
.as(DataflowPipelineOptions.class);
// writes message to "output_topic"
TopicPath topic = PubsubClient.topicPathFromName(options.getProject(), "output_topic");
Pipeline p = Pipeline.create(options);
p
.apply("input string", Create.of("This is just a message"))
.apply("convert to Pub/Sub message", ParDo.of(new DoFn<String, PubsubMessage>() {
#ProcessElement
public void processElement(ProcessContext c) {
c.output(new PubsubMessage(c.element().getBytes(), null));
}
}))
.apply("write to topic", new PubsubUnboundedSink(
PubsubJsonClient.FACTORY,
StaticValueProvider.of(topic), // topic
"timestamp", // timestamp attribute
"id", // ID attribute
5 // number of shards
));
p.run();
}
}
Here's a way I found browsing https://github.com/GoogleCloudPlatform/cloud-pubsub-samples-java/blob/master/dataflow/src/main/java/com/google/cloud/dataflow/examples/StockInjector.java:
import com.google.api.services.pubsub.Pubsub;
import com.google.api.services.pubsub.model.PublishRequest;
import com.google.api.services.pubsub.model.PubsubMessage;
public class PubsubManager {
private static final Logger logger = LoggerFactory.getLogger(PubsubManager.class);
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final Pubsub pubsub = createPubsubClient();
public static class RetryHttpInitializerWrapper implements HttpRequestInitializer {
// Intercepts the request for filling in the "Authorization"
// header field, as well as recovering from certain unsuccessful
// error codes wherein the Credential must refresh its token for a
// retry.
private final GoogleCredential wrappedCredential;
// A sleeper; you can replace it with a mock in your test.
private final Sleeper sleeper;
private RetryHttpInitializerWrapper(GoogleCredential wrappedCredential) {
this(wrappedCredential, Sleeper.DEFAULT);
}
// Use only for testing.
RetryHttpInitializerWrapper(
GoogleCredential wrappedCredential, Sleeper sleeper) {
this.wrappedCredential = Preconditions.checkNotNull(wrappedCredential);
this.sleeper = sleeper;
}
#Override
public void initialize(HttpRequest request) {
final HttpUnsuccessfulResponseHandler backoffHandler =
new HttpBackOffUnsuccessfulResponseHandler(
new ExponentialBackOff())
.setSleeper(sleeper);
request.setInterceptor(wrappedCredential);
request.setUnsuccessfulResponseHandler(
new HttpUnsuccessfulResponseHandler() {
#Override
public boolean handleResponse(HttpRequest request,
HttpResponse response,
boolean supportsRetry)
throws IOException {
if (wrappedCredential.handleResponse(request,
response,
supportsRetry)) {
// If credential decides it can handle it, the
// return code or message indicated something
// specific to authentication, and no backoff is
// desired.
return true;
} else if (backoffHandler.handleResponse(request,
response,
supportsRetry)) {
// Otherwise, we defer to the judgement of our
// internal backoff handler.
logger.info("Retrying " + request.getUrl());
return true;
} else {
return false;
}
}
});
request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(
new ExponentialBackOff()).setSleeper(sleeper));
}
}
/**
* Creates a Cloud Pub/Sub client.
*/
private static Pubsub createPubsubClient() {
try {
HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = GoogleCredential.getApplicationDefault();
HttpRequestInitializer initializer =
new RetryHttpInitializerWrapper(credential);
return new Pubsub.Builder(transport, JSON_FACTORY, initializer).build();
} catch (IOException | GeneralSecurityException e) {
logger.error("Could not create Pubsub client: " + e);
}
return null;
}
/**
* Publishes the given message to a Cloud Pub/Sub topic.
*/
public static void publishMessage(String message, String outputTopic) {
int maxLogMessageLength = 200;
if (message.length() < maxLogMessageLength) {
maxLogMessageLength = message.length();
}
logger.info("Received ...." + message.substring(0, maxLogMessageLength));
// Publish message to Pubsub.
PubsubMessage pubsubMessage = new PubsubMessage();
pubsubMessage.encodeData(message.getBytes());
PublishRequest publishRequest = new PublishRequest();
publishRequest.setMessages(Collections.singletonList(pubsubMessage));
try {
pubsub.projects().topics().publish(outputTopic, publishRequest).execute();
} catch (java.io.IOException e) {
logger.error("Stuff happened in pubsub: " + e);
}
}
}
You can send pubsub message using PubsubIO writeMessages method
dataflow Pipeline steps
Pipeline p = Pipeline.create(options);
p.apply("Transformer1", ParDo.of(new Fn.method1()))
.apply("Transformer2", ParDo.of(new Fn.method2()))
.apply("PubsubMessageSend", PubsubIO.writeMessages().to(PubSubConfig.getTopic(options.getProject(), options.getpubsubTopic ())));
Define Project Name and pubsubTopic where to want to send pub subs message in the PipeLineOptions
I am running into this error when I load my GWT page:
error com.google.gwt.user.client.rpc.SerializationException: Type 'com.summerbreezemotel.server.DBReservation' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded.
I looked at the docs and seemed to follow all the constraints. I also have 3 other classes which do the same thing however this one seems to cause an issue. Any help would be appreciated.
the class which is failing:DBReservation
package com.summerbreezemotel.server;
import java.util.Date;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.summerbreezemotel.shared.DataReservation;
import com.summerbreezemotel.shared.SiteConstants;
public class DBReservation extends DataReservation
{
/**
*
*/
private static final long serialVersionUID = 146606067638056872L;
Date dateReserved;
String userEmail;
public DBReservation() {}
public DBReservation(DataReservation in) {
checkIn = in.checkIn;
checkOut = in.checkOut;
form_FirstName = in.form_FirstName;
form_LastName = in.form_LastName;
form_Addr1 = in.form_Addr1;
form_Addr2 = in.form_Addr2;
form_City = in.form_City;
form_State = in.form_State;
form_Zip = in.form_Zip;
form_Country = in.form_Country;
form_Phone = in.form_Phone;
form_Email = in.form_Email;
form_CardType = in.form_CardType;
form_CardMonth = in.form_CardMonth;
form_CardNumber = in.form_CardNumber;
form_CardYear = in.form_CardYear;
form_RoomType = in.form_RoomType;
form_isSmoking = in.form_isSmoking;
form_numRooms = in.form_numRooms;
ratePerNightPerRoom = in.ratePerNightPerRoom;
totalRate = in.totalRate;
}
DataReservation getData()
{
DataReservation out = new DataReservation();
out.checkIn = checkIn;
out.checkOut = checkOut;
out.form_FirstName = form_FirstName;
out.form_LastName = form_LastName;
out.form_Addr1 = form_Addr1;
out.form_Addr2 = form_Addr2;
out.form_City = form_City;
out.form_State = form_State;
out.form_Zip = form_Zip;
out.form_Country = form_Country;
out.form_Phone = form_Phone;
out.form_Email = form_Email;
out.form_CardType = form_CardType;
out.form_CardMonth = form_CardMonth;
out.form_CardNumber = form_CardNumber;
out.form_CardYear = form_CardYear;
out.form_RoomType = form_RoomType;
out.form_isSmoking = form_isSmoking;
out.form_numRooms = form_numRooms;
out.ratePerNightPerRoom = ratePerNightPerRoom;
out.totalRate = totalRate;
return out;
}
// gets item from DB and convertes it to this
void fillReservationFromEntity(Entity item)
{
userEmail = (String) item.getProperty(SiteConstants.USER_PROPERTY);
dateReserved = (Date) item.getProperty(SiteConstants.RESERVE_DATE_PROPERTY);
checkIn = (Date) item.getProperty(SiteConstants.IN_DATE_PROPERTY);
checkOut = (Date) item.getProperty(SiteConstants.OUT_DATE_PROPERTY);
form_FirstName = (String) item.getProperty(SiteConstants.FORM_FIRSTNAME_PROPERTY);
form_LastName = (String) item.getProperty(SiteConstants.FORM_LASTNAME_PROPERTY);
form_Addr1 = (String) item.getProperty(SiteConstants.FORM_ADDR1_PROPERTY);
form_Addr2 = (String) item.getProperty(SiteConstants.FORM_ADDR2_PROPERTY);
form_City = (String) item.getProperty(SiteConstants.FORM_CITY_PROPERTY);
form_State = (String) item.getProperty(SiteConstants.FORM_STATE_PROPERTY);
form_Zip = (String) item.getProperty(SiteConstants.FORM_ZIP_PROPERTY);
form_Country = (String)item.getProperty(SiteConstants.FORM_COUNTRY_PROPERTY);
form_Phone = (String) item.getProperty(SiteConstants.FORM_PHONE_PROPERTY);
form_Email = (String) item.getProperty(SiteConstants.FORM_EMAIL_PROPERTY);
form_CardType = (String) item.getProperty(SiteConstants.FORM_CARDTYPE_PROPERTY);
form_CardMonth = (String) item.getProperty(SiteConstants.FORM_CARDMONTH_PROPERTY);
form_CardNumber = (String) item.getProperty(SiteConstants.FORM_CARDNUMBER_PROPERTY);
form_CardYear = (Long) item.getProperty(SiteConstants.FORM_CARDYEAR_PROPERTY);
form_RoomType = (Long) item.getProperty(SiteConstants.FORM_ROOMTYPE_PROPERTY);
form_isSmoking = (Boolean) item.getProperty(SiteConstants.FORM_ISSMOKING_PROPERTY);
form_numRooms = (Long) item.getProperty(SiteConstants.FORM_NUMROOMS_PROPERTY);
ratePerNightPerRoom = (Double) item.getProperty(SiteConstants.RATEPERNIGHTPERROOM_PROPERTY);
totalRate = (Double) item.getProperty(SiteConstants.TOTALRATE_PROPERTY);
}
void addReservationsToEntity(Entity item)
{
item.setProperty(SiteConstants.USER_PROPERTY, userEmail);
item.setProperty(SiteConstants.RESERVE_DATE_PROPERTY, dateReserved);
item.setProperty(SiteConstants.IN_DATE_PROPERTY, checkIn);
item.setProperty(SiteConstants.OUT_DATE_PROPERTY, checkOut);
item.setProperty(SiteConstants.FORM_FIRSTNAME_PROPERTY,form_FirstName);
item.setProperty(SiteConstants.FORM_LASTNAME_PROPERTY,form_LastName);
item.setProperty(SiteConstants.FORM_ADDR1_PROPERTY,form_Addr1);
item.setProperty(SiteConstants.FORM_ADDR2_PROPERTY,form_Addr2);
item.setProperty(SiteConstants.FORM_CITY_PROPERTY,form_City);
item.setProperty(SiteConstants.FORM_STATE_PROPERTY,form_State);
item.setProperty(SiteConstants.FORM_ZIP_PROPERTY,form_Zip);
item.setProperty(SiteConstants.FORM_COUNTRY_PROPERTY,form_Country);
item.setProperty(SiteConstants.FORM_PHONE_PROPERTY,form_Phone);
item.setProperty(SiteConstants.FORM_EMAIL_PROPERTY,form_Email);
item.setProperty(SiteConstants.FORM_CARDTYPE_PROPERTY,form_CardType);
item.setProperty(SiteConstants.FORM_CARDMONTH_PROPERTY,form_CardMonth);
item.setProperty(SiteConstants.FORM_CARDNUMBER_PROPERTY,form_CardNumber);
item.setProperty(SiteConstants.FORM_CARDYEAR_PROPERTY,form_CardYear);
item.setProperty(SiteConstants.FORM_ROOMTYPE_PROPERTY,form_RoomType);
item.setProperty(SiteConstants.FORM_ISSMOKING_PROPERTY,form_isSmoking);
item.setProperty(SiteConstants.FORM_NUMROOMS_PROPERTY,form_numRooms);
item.setProperty(SiteConstants.RATEPERNIGHTPERROOM_PROPERTY,ratePerNightPerRoom);
item.setProperty(SiteConstants.TOTALRATE_PROPERTY,totalRate);
}
void store()
{
// UserService userService = UserServiceFactory.getUserService();
// User user = userService.getCurrentUser();
// if(user.getEmail() != null)
// userEmail = user.getEmail();
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
String SummerBreezeDateStoreName = new String(SiteConstants.KEY_NAME);
Key SummerBreezeDateStoreKey = KeyFactory.createKey(SiteConstants.KEY_KEY, SummerBreezeDateStoreName);
Entity reservationsEntry = new Entity(SiteConstants.DB_RESERVATIONS, SummerBreezeDateStoreKey);
addReservationsToEntity(reservationsEntry);
datastore.put(reservationsEntry);
// use this if writes get to high
// item.setProperty("testBlob",new Blob(toByte(roomResevationRequest)));
datastore.put(reservationsEntry);
}
}
my DataReservation
package com.summerbreezemotel.shared;
import java.io.Serializable;
import java.util.Date;
public class DataReservation implements Serializable
{
private static final long serialVersionUID = -7598404617383692994L;
public String form_FirstName;
public String form_LastName;
public String form_Addr1;
public String form_Addr2;
public String form_City;
public String form_State;
public String form_Zip;
public String form_Country;
public String form_Phone;
public String form_Email;
public String form_CardType;
public String form_CardMonth;
public String form_CardNumber;
public long form_CardYear;
public long form_RoomType;
public boolean form_isSmoking;
public Date checkIn;
public Date checkOut;
public long form_numRooms;
public double ratePerNightPerRoom;
public double totalRate;
public DataReservation()
{
}
}
I think this is a typical case of shooting yourself in the foot. By extending your server object with the logic from the shared class you made is somewhat easier to create a server side class including the database code, but if you by accident return the server side instead instead of calling getData() just before sending it to the client you get the server side class which can´t be send to the client of course. But the compiler won't warn you for it because it syntactical correct. So I believe the answer is not in the code given, that looks good, but in between the gwt servlet and the usage of DBReservation.
You are using a file in shared folder that implements Serializable and extending it on server side. Are you sure about this logic?? It usually will be a pojo/dto/model on the client/shared side implements IsSerializable and it is sent to the server. Then servers do the manipulation and returns it back.
It should implement the Serializable interface. You don't 'inherit' the implementation by extending the class.