I use Google GWT and RPC. On the Client side is the class SplitDatenhalter. This works OK:
Vector <SplitDatenhalter> vec = new Vector<SplitDatenhalter>();
vec.add(new SplitDatenhalter("a", "b", "c","D"));
vec.add(new SplitDatenhalter("ab", "bc", "dc","Dee"));
How can I send this to the server side?
Update
I have on the client side the class SplitDatenhalter. See below,
public class SplitDatenhalter implements Serializable{
private static final long serialVersionUID = 1L;
String name ;
String vorname;
String nachname;
String email;
public SplitDatenhalter(String name, String vorname, String Nname, String Email) {
this.name = name;
this.vorname = vorname;
this.nachname = Nname;
this.email = Email;
}
public String getName() {
return name;
}
//others setter and getter Function
The client side has MyService:
public interface MyService extends RemoteService
{
public void myVector(Vector<SplitDatenhalter> vec);
}
The other interface:
public interface MyServiceAsync {
public void myVector(Vector < SplitDatenhalter > vec,
AsyncCallback < Void > callback);
}
This is the server side:
public void myVector(Vector < SplitDatenhalter > vec)
{
// TODO Auto-generated method stub
System.out.println("vector");
for (int i = 0; i < vec.size(); i++) {
this.name = vec.get(i).getName();
this.name = vec.get(i).getVorname();
this.name = vec.get(i).getNachname();
this.name = vec.get(i).getEmail();
}
}
This code part is from client side:
Vector<SplitDatenhalter> vect = new Vector<SplitDatenhalter>(); // TODO Auto-generated method stub
MyServiceAsync svc = (MyServiceAsync) GWT.create(MyService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) svc;
// endpoint.setServiceEntryPoint("/myService");
// define a handler for what to do when the service returns a result
#SuppressWarnings("rawtypes")
AsyncCallback callback = new AsyncCallback()
{
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
System.out.println("Fehler");
}
//#Override
public void onSuccess(Object result) {
// TODO Auto-generated method stub
System.out.println(result.toString());
}
};
this.vect.add(new SplitDatenhalter(this.name, Vname, Nname, Email)); //this a part from Function
I need this code part
public static MyServiceAsync getService()
{
MyServiceAsync svc = (MyServiceAsync) GWT.create(MyService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) svc;
endpoint.setServiceEntryPoint("/myService");
return svc;
}
The last part:
# SuppressWarnings("unchecked")
public void vectorExe()
{
System.out.println("vectorExe befor");
getService().myVector(this.vect, callback);
}
After this function executes, I get an error from onFailure(Throwable caught). Where did I go wrong?
you can use vector in client and pass it fto server side (see reference)
Maybe your SplitDatenhalter class is not Serializable. What's the problem?
Related
I'm trying to receive and process messages through GCP Pub/Sub.
I tried to convert and receive the payload part of the message through JacksonPubSubMessageConverter, but it failed.
It seems that I am not handling byte[] properly inside JacksonPubSubMessageConverter. Do I need to change ObjectMapper settings or override JacksonPubSubMessageConverter?
Below is a code example.
#Slf4j
#Configuration
public class PubSubConfig {
#Bean
public PubSubMessageConverter pubSubMessageConverter(ObjectMapper objectMapper) {
return new JacksonPubSubMessageConverter(objectMapper);
}
}
// ...
#Getter
#Setter
#ToString
#NoArgsConstructor(access = AccessLevel.PROTECTED)
public class MessageDTO {
private PubSubAction action;
#JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate startedAt;
private Boolean dryRun;
}
// ...
public enum PubSubAction {
MY_ACTION("my action"),
ETC("etc action");
private final String description;
PubSubAction(String description) {
this.description = description;
}
#JsonCreator
public static PubSubAction create(String name) {
return Stream.of(PubSubAction.values())
.filter(pubSubAction -> pubSubAction.name().equals(name))
.findAny()
.orElse(null);
}
}
// ...
class MyConsumer() {
private final String subscriptionName;
private final PubSubTemplate pubSubTemplate;
public MyConsumer(
String subscriptionName,
PubSubTemplate pubSubTemplate
) {
this.subscriptionName = subscriptionName;
this.pubSubTemplate = pubSubTemplate;
}
private void consume(
ConvertedBasicAcknowledgeablePubsubMessage<MessageDTO> convertedMessage) {
try {
MessageDTO payload = convertedMessage.getPayload();
log.debug("payload {}", payload);
// payload MessageDTO(action=MY_ACTION, startedAt=null, dryRun=null)
convertedMessage.ack();
} catch (Exception e) {
log.error("Unknown Exception {} {}", e.getMessage(), this.subscriptionName, e);
}
}
private Consumer<ConvertedBasicAcknowledgeablePubsubMessage<MessageDTO>> convertConsumer() {
return this::consume;
}
public void subscribe() {
log.info("Subscribing to {}", subscriptionName);
pubSubTemplate.subscribeAndConvert(subscriptionName, this.convertConsumer(),
MessageDTO.class);
}
}
Im trying to access some list items from a json response using retrofit but cant seem to be able to access using get method. The ListQuotes seems to be saying null
#JsonPropertyOrder({
"page",
"last_page",
"quotes"
})
public class ListQuoteResponse {
#JsonProperty("quotes")
private List<Quote> quotes = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public ListQuoteResponse() {
}
#JsonProperty("quotes")
public List<Quote> getQuotes() {
return quotes;
}
#JsonProperty("quotes")
public void setQuotes(List<Quote> quotes) {
this.quotes = quotes;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
But when I open the Quote class I am unable to access any of the properties
public class Quote {
#JsonProperty("id")
private Integer id;
#JsonProperty("dialogue")
private Boolean dialogue;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public Quote() {
}
#JsonProperty("id")
public Integer getId() {
return id;
}
#JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
#JsonProperty("dialogue")
public Boolean getDialogue() {
return dialogue;
}
#JsonProperty("dialogue")
public void setDialogue(Boolean dialogue) {
this.dialogue = dialogue;
}
I tried using
listQuoteBodyResponse.body().getQuotes() but that only returned random numbers and when I tried using the Quote class for the response directly like
QuoteResponse.body.getDialogue() its just returning null
I'm trying to use #Consumed on jpa entity with camel.
this is my route :
<route id="incomingFileHandlerRoute">
<from
uri="jpa://com.menora.inbal.incomingFileHandler.Jpa.model.MessageToDB?consumer.nativeQuery=select
* from file_message where mstatus = 'TODO'&consumer.delay=5000&consumeDelete=false&consumeLockEntity=true&consumer.SkipLockedEntity=true" />
<to uri="bean:incomingFileHandler" />
</route>
and my entity:
#Entity
#Table(name = "file_message")
public class MessageToDB implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
private String uuid;
private String fileName;
private String body;
private String mstatus;
#Temporal(TemporalType.TIMESTAMP)
private Date mtimestamp;
#Consumed
public void updateMstatus() {
setMstatus(MessageStatus.DONE.name());
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getMstatus() {
return mstatus;
}
public void setMstatus(String mstatus) {
this.mstatus = mstatus;
}
public Date getMtimestamp() {
return mtimestamp;
}
public void setMtimestamp(Date mtimestamp) {
this.mtimestamp = mtimestamp;
}
}
I do get to incomingFileHandler bean with results from db but I do not get to the Consumed method updateMstatus . The incomingFileHandler bean is getting called continuously as always there are results from db
I have a similar implementation with camel-jpa and annotations #Consumed and #PreConsumed in the entity but none of these methods is called.
I look the camel-jpa source code and found this in JpaConsumer.java:
protected DeleteHandler<Object> createPreDeleteHandler() {
// Look for #PreConsumed to allow custom callback before the Entity has been consumed
final Class<?> entityType = getEndpoint().getEntityType();
if (entityType != null) {
// Inspect the method(s) annotated with #PreConsumed
if entityType is null the entity class inst inspect the method annotated with #Consumed and #PreConsumed.
Solution: add entityType=com.xx.yy.MessageToDB to your URI to set Endpoint Entity type.
I had been developing and testing on the Codename One simulator and everything worked fine.
However, when I tested it on a real Android device, I get a 405 Method Not Allowed error. This happened on both a POST and GET request.
I suspect it is the #Consume and #Produces which are causing the problem. How do I fix this?
Here are my server side code:
#GET
#Path("/all/{language}")
#Produces("application/json")
public final Response getAllCelebrities(#PathParam("language") String language) {
String celebritiesJSONString = CelebrityActions.getAllCelebritiesNamesJSONString(language);
return Response.ok(celebritiesJSONString).build();
}
#POST
#Path("/login")
#Consumes("application/x-www-form-urlencoded")
#Produces("text/plain")
public final Response login(
#FormParam("loginid") String loginid,
#FormParam("password") String password
) {
System.out.println("login 0 started");
Long fanID;
try {
fanID = AccountsActions.login(loginid, password);
} catch (Exception e) {
return Response.serverError().entity(e.getMessage()).build();
}
if (fanID == null) {
return responseFanIDNotFoundError();
}
System.out.println("This is printed out!!!");
System.out.println("login 100 ended");
return Response.ok().build();
}
And here's my log upon execution of the login() method:
login 0 started
This is printed out!!!
login 100 ended
which means the server side method was ready to return a 200 response.
What is causing the Android client to show a 405 Method Not Allow error?
EDIT: I'm adding my cient-side code here:
(note that this one handles a cookie from a server)
public class Login extends PostConnection {
private final String LoginEndpoint = "account/login";
private String loginIDString;
private String loginPasswordString;
// Tested and works on simulator!
public Login(String loginIDString, String loginPasswordString) {
super();
endpoint = LoginEndpoint;
this.loginIDString = loginIDString;
this.loginPasswordString = loginPasswordString;
}
#Override
protected void prepareParametersMap() {
parametersMap = new HashMap<>();
parametersMap.put("loginid", loginIDString);
parametersMap.put("password", loginPasswordString);
}
}
public abstract class PostConnection extends PostPutConnection {
public PostConnection() {
super();
}
public boolean connect() throws IOException {
connectionRequest.setHttpMethod("POST");
return super.connect();
}
}
public abstract class PostPutConnection extends Connection {
protected HashMap<String, String> parametersMap;
public PostPutConnection() {
super();
}
protected static final void setPostParameters(ConnectionRequest connectionRequest, HashMap<String, String> parametersMap) {
Set<String> paramateterKeys = parametersMap.keySet();
Iterator<String> parameterKeysIterator = paramateterKeys.iterator();
while (parameterKeysIterator.hasNext()) {
String key = parameterKeysIterator.next();
String value = parametersMap.get(key);
connectionRequest.addArgument(key, value);
}
}
protected abstract void prepareParametersMap();
public boolean connect() throws IOException {
prepareParametersMap();
setPost();
setPostParameters();
return super.connect();
}
private void setPostParameters() {
setPostParameters(connectionRequest, parametersMap);
}
private final void setPost() {
connectionRequest.setPost(true);
}
}
public abstract class Connection {
private final static String protocol = "http";
private final static String domain = "192.168.0.109:20000";
protected ConnectionRequest connectionRequest;
protected String endpoint;
public Connection() {
super();
init();
}
protected void init() {
connectionRequest = new ConnectionRequest();
connectionRequest.setCookiesEnabled(true);
ConnectionRequest.setUseNativeCookieStore(true);
}
public boolean connect() throws IOException {
connectionRequest.setUrl(protocol + "://" + domain + "/" + endpoint);
NetworkManager.getInstance().addToQueueAndWait(connectionRequest);
int responseCode = getResponseCode();
return responseCode == 200 ? true : false;
}
private int getResponseCode() {
int responseCode = connectionRequest.getResponseCode();
return responseCode;
}
}
And another method below:
(note that this one does not handle cookies)
public class GetAllCelebrities extends GetConnection {
private final String GetCelebritiesEndpoint = "celebrity/all";
public GetAllCelebrities(String language) {
super();
endpoint = GetCelebritiesEndpoint + "/" + language;
}
}
public abstract class GetConnection extends Connection {
private Map<String, Object> responseData;
public GetConnection() {
super();
}
public boolean connect() throws IOException {
connectionRequest.setHttpMethod("GET");
boolean connectResult = super.connect();
if (!connectResult) {
return false;
}
responseData = getResponseResult();
return true;
}
private Map<String, Object> getResponseResult() throws IOException {
byte[] responseData = connectionRequest.getResponseData();
ByteArrayInputStream responseDataBAIS = new ByteArrayInputStream(responseData);
InputStreamReader responseDataISR = new InputStreamReader(responseDataBAIS, "UTF-8");
JSONParser responseDateJSONParser = new JSONParser();
Map<String, Object> responseResult = responseDateJSONParser.parseJSON(responseDataISR);
return responseResult;
}
public Map<String, Object> getResponseData() {
return responseData;
}
}
And it is called like:
private Map<String, Object> fetchCelebrities() throws IOException {
GetAllCelebrities getAllCelebrities = new GetAllCelebrities("en");
getAllCelebrities.connect();
return getAllCelebrities.getResponseData();
}
private boolean performLogin() throws IOException {
String loginIDString = loginID.getText();
String loginPasswordString = loginPassword.getText();
Login login = new Login(loginIDString, loginPasswordString);
boolean loginResult = login.connect();
return loginResult;
}
It's a bit hard to read all of this code but I'll venture a guess based on the server message. You've set the method to "PUT" along the way in the post put class and that isn't supported by the server yet.
The best way to debug these things is with the network monitor in the Simulator. Its shows the traffic and would have made these things mostly clear
I am trying to get the user's friends list from Facebook.
The problem seems to be the Javabean...
FBUser fbuser = new Gson().fromJson(jsonStr, FBUser.class);
public class FBUser implements Serializable {
private static final long serialVersionUID = -3154429420153433117L;
private String id;
private String name;
private String email;
private Friends friendsList = new Friends();
private FBUser() { }
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Data> getFriendsList() {
return friendsList.getData();
}
public static class Friends implements Serializable {
private static final long serialVersionUID = 6991758772193514527L;
private List<Data> data;
private Friends() { }
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
public class Paging implements Serializable {
private static final long serialVersionUID = 1689816298710621080L;
private String next;
private Paging() { }
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
}
}
public class Data implements Serializable {
private static final long serialVersionUID = -5008541658519841090L;
private String id;
private String name;
private Data() { }
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
Json:
json: {"id":"10861234","name":"Whatever","email":"whatever\u0040gmail.com","friends":{"data":[{"name":"Someone","id":"10861234"},{"name" ...43"}],"paging":{"next":"https:\/\/graph.facebook.com\/10861234\/friends..."}}}
The fields ID, Name and Email I can retrieve succesfully... but the friendsList is null... =(
Maybe it is the way I am trying to get it from the nested class, any suggestions on that?
There is no friendsList in your JSON (or, there's no friends in your Java class - whichever way you'd like to look at it). Gson silently ignores anything in the JSON that is not present in your classes.
You have a field friends whose value is an object. That object has a field data which is an array of objects and a field paging which is another object.
You need to write Java classes that match that structure. You're ... close.
In your FBUser class change:
private Friends friendsList = new Friends();
to:
private Friends friends = new Friends();
or:
#SerializedName("friends")
private Friends friendsList = new Friends();
Then in your Friends class you need to add:
private Paging paging = new Paging();
Also note that you don't have to initialize these values unless you specifically don't want them to be non-null when using these classes elsewhere.