I need to get a value of ListenableFutureCallback from the delete function of asyncresttemplate - asyncresttemplate

I have a problem getting an object from ListenableFutureCallback when I use delete function of AsyncRestTemplate. This is my source code:
ListenableFutureCallback<Object> callbackDelete = new ListenableFutureCallback<Object>() {
#Override
public void onFailure(Throwable ex) {
logger.error("Error processing the delete request: " + ex.getMessage());
}
#Override
public void onSuccess(Object result) {
System.out.println("Async Delete Success : " + result.toString() );
logger.debug("The request has been processed successfully");
}
};
ListenableFuture<?> response = asyncRestTemplate.delete(DELETE_URL + "/" + id);
response.addCallback(callbackDelete);
When I execute result.toString(), result is always null.
Thanks

Related

Spring batch write skipper item into csv file

I want to write skipper lines in first csv file and the result of processor in second file in one step but it not works !
My code :
// => Step cecStep1
#Bean
public Step cecStep1(StepBuilderFactory stepBuilders) throws IOException {
return stepBuilders.get("fileDecrypt")
.<CSCivique, String>chunk(100)
.reader(reader1())
.processor(processor1FileDecrypt())
.writer(writer1())
.faultTolerant()
.skip(Exception.class)
.skipLimit(100)
.listener(new MySkipListener())
.build();
}
// ##################################### Step SkipListener ###################################################
public static class MySkipListener implements SkipListener {
private BufferedWriter bw = null;
public MySkipListener(File file) throws IOException {
//this.fileWriter = new FileWriter(file);
bw= new BufferedWriter(new FileWriter(file, true));
System.out.println("MySkipListener =========> :"+file);
}
#Override
public void onSkipInRead(Throwable throwable) {
if (throwable instanceof FlatFileParseException) {
FlatFileParseException flatFileParseException = (FlatFileParseException) throwable;
System.out.println("onSkipInRead =========> :");
try {
bw.write(flatFileParseException.getInput()+"; Vérifiez les colonnes !!");
bw.newLine();
bw.flush();
// fileWriter.close();
} catch (IOException e) {
System.err.println("Unable to write skipped line to error file");
}
}
}
#Override
public void onSkipInWrite(CSCivique item, Throwable t) {
System.out.println("Item " + item + " was skipped due to: " + t.getMessage());
}
#Override
public void onSkipInProcess(CSCivique item, Throwable t) {
System.out.println("Item " + item + " was skipped due to: " + t.getMessage());
}
}
#Bean
public FlatFileItemWriter<String> writer1() {
return new FlatFileItemWriterBuilder<String>().name(greetingItemWriter)
.resource(new FileSystemResource("target/test-outputs/greetings.csv"))
.lineAggregator(new PassThroughLineAggregator<>()).build();
}
Tankyou !
In your processor, you can:
throw a skippable exception for invalid items so that the skip listener intercepts them and writes them to the specified file
let valid items go to the writer so that they are written as configured in the item writer
For example:
class MyItemProcessor implements ItemProcessor<Object, Object> {
#Override
public Object process(Object item) throws Exception {
if (shouldBeSkipped(item)) {
throw new MySkippableException();
}
// process item
return item;
}
}
Hope this helps.

Android Volley with REST Api - POST will not insert into dB and respons incorrectly

I am using https://github.com/mevdschee/php-crud-api as REST Api to access my MySQL db. To access data from Android application I use Volley lib.
All works fine except POST (creating new item in db). But instead new item created I am getting JSON will all items (look like output from GET) and item is not created in dB.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "APP START");
tv = findViewById(R.id.textView);
buttonPost = findViewById(R.id.buttonPost);
buttonGet = findViewById(R.id.buttonGet);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
current_date = sd1.format(new Date(cal.getTimeInMillis()));
Log.d(TAG, "current_date=" + current_date);
cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
buttonGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "ButtonGet pressed");
tv.setText("");
getRest();
}
});
buttonPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "ButtonPost pressed");
tv.setText("");
postRest();
}
});
}
getRest()
tv.append("REST API - reading data via GET " + "\n");
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, endpointUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject vancuraLevel1 = response.getJSONObject("restdemo");
JSONArray vancuraLevel2 = vancuraLevel1.getJSONArray("records");
int JSONlenght2 = vancuraLevel2.length();
Log.d("JSON", "JSONlenght2 =" + JSONlenght2 );
for(int n = 0; n < JSONlenght2; n++) {
Log.d("JSON", "looping " + n );
JSONArray vancuraLevel3 = vancuraLevel2.getJSONArray(n);
int JSONlenght3 = vancuraLevel3.length();
String index = vancuraLevel3.getString(0);
String datum = vancuraLevel3.getString(1);
String subjekt = vancuraLevel3.getString(2);
String ovoce = vancuraLevel3.getString(3);
Log.d("JSON", "result datum" + datum + " subjekt=" + subjekt);
tv.append("Data : " + index + "/" + datum + "/" + subjekt + "/" + ovoce + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Volley REST error " + error.toString());
tv.append("ERROR " + error.toString() +"\n");
}
});
// fire Volley request
mRequestQueue.add(jsObjRequest);
postRest(){
final String whatToInsert = "foo subjekt " + current_date;
// POST - insert data
tv.append("REST API - inserting data via POST - payload=" + whatToInsert +"\n");
StringRequest postRequest = new StringRequest(Request.Method.POST, endpointUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
// tv.append(current_date + "\n");
tv.append("response = " + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.e("Error.Response", error.getMessage());
tv.append("ERROR " + error.toString() +"\n");
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//params.put("index", "NULL");
params.put("datum", "2017-12-30");
params.put("subjekt", whatToInsert);
params.put("ovoce", "2");
return params;
}
};
// fire Volley request
mRequestQueue.add(postRequest);
Result GET - it is OK
Result POST - fault
project is available at https://github.com/fanysoft/AndroidRESTapi
Looking closely at the code the GET method returns a JSONObject response while the POST method return a String response. The string response of the POST Method is very correct and it carries exactly the same result as the GET method result all you have to do is convert the String response to JSON object you ll have same JSONObject as the GET method
JSONObject jsonObject = new JSONObject(response);
Then you can parse the object for your result
Solved by disabling Volley cache
getRequest.setShouldCache(false);
postRequest.setShouldCache(false);

Vertx.deployVerticle does not call the supplied completion handler

I writing a service where a deployed verticle is linked to a rest endpoint. The service is working 100% (I dynamically deployed the verticle and calling the REST endpoint execute a function on the verticle). The problem is that the supplied completion handler is never called. Any ideas?
Following is my code:
LOGGER.debug(String.format("Starting runner %s:%s:%s" ,functionName, faasFunctionClass, fileName));
DeploymentOptions deploymentOptions = new DeploymentOptions();
deploymentOptions.setInstances(1);
JsonObject jsonObject = new JsonObject();
jsonObject.put(FUNCTION_NAME, functionName);
jsonObject.put(FUNCTION_CLASS, faasFunctionClass);
jsonObject.put(FUNCTION_FILENAME, fileName);
deploymentOptions.setConfig(jsonObject);
LOGGER.debug(String.format("Deploying [%s]" ,jsonObject.encode()));
this.vertx.deployVerticle("faas:" + VertxFaasRunner.class.getCanonicalName(),deploymentOptions, event->{
if (event.succeeded()) {
System.out.println("Deployment id is: " + event.result());
} else {
System.out.println("Deployment failed!");
}
});
In this case it depends on how you have implemented your Verticle.
in the below code when future.complete() is executed then only event.succeeded() will be true.
public class MainVerticle extends AbstractVerticle {
#Override
public void start() throws Exception {
System.out.println("[Main] Running in " + Thread.currentThread().getName());
vertx
.deployVerticle("io.vertx.example.core.verticle.worker.WorkerVerticle",
new DeploymentOptions().setWorker(true), event -> {
if (event.succeeded()) {
System.out.println("Deployment id is: " + event.result());
} else {
System.out.println("Deployment failed!");
}
});
}
}
public class WorkerVerticle extends AbstractVerticle {
#Override
public void start(Future future) throws Exception {
System.out.println("[Worker] Starting in " + Thread.currentThread().getName());
vertx.eventBus().<String>consumer("sample.data", message -> {
System.out.println("[Worker] Consuming data in " + Thread.currentThread().getName());
String body = message.body();
message.reply(body.toUpperCase());
});
// this notifies that the verticle is deployed successfully.
future.complete();
}
}

how to watch the cilent when it lose Leadership through zookeeper curator?

as we know,when the client get the leadership,will invode the takeLeadership,but the document do not tell me when the client lost the leadership!!!so,how to watch the cilent when it lose Leadership through zookeeper curator?
question two : why my client was lose,i am can not debug the stateChanged(...) thought idea?
here my code, expect your great answer,thx
public class ExampleClient extends LeaderSelectorListenerAdapter implements Closeable{
private final String name;
private final LeaderSelector leaderSelector;
private final AtomicInteger leaderCount = new AtomicInteger();//用于记录领导次数
public ExampleClient(CuratorFramework client,String path,String name) {
this.name = name;
leaderSelector = new LeaderSelector(client, path, this);
leaderSelector.autoRequeue();//保留重新获取领导权资格
}
public void start() throws IOException {
leaderSelector.start();
}
#Override
public void close() throws IOException {
leaderSelector.close();
}
#Override
public void stateChanged(CuratorFramework client, ConnectionState newState)
{
if ((newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST) ) {
log.info("stateChanged !!!");
throw new CancelLeadershipException();
}
}
/**
* will be invoded when get leadeship
* #param client
* #throws Exception
*/
#Override
public void takeLeadership(CuratorFramework client) throws Exception {
final int waitSeconds =(int)(Math.random()*5)+1;
log.info(name + " is the leader now,wait " + waitSeconds + " seconds!");
log.info(name + " had been leader for " + leaderCount.getAndIncrement() + " time(s) before");
try {
/**/
Thread.sleep(TimeUnit.SECONDS.toMillis(waitSeconds));
//do something!!!
/*while(true){
//guarantee this client be the leader all the time!
}*/
}catch (InterruptedException e){
log.info(name+" was interrupted!");
Thread.currentThread().interrupt();
}finally{
log.info(name+" relinquishing leadership.\n");
}
}
}
LeaderLatchListener has two call backs about isLeader and notLeader. Some examples,
http://www.programcreek.com/java-api-examples/index.php?api=org.apache.curator.framework.recipes.leader.LeaderLatchListener

How to integrate oauth with gwt?

Here is my code, how do I use oauth to get the data such as user_id or first and last name of the user and sign them to fields? Should I implement them in the onSuccess method?
private void addFacebookAuth(){
loginButton.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
final AuthRequest req = new AuthRequest(FACEBOOK_AUTH_URL, FACEBOOK_APP_ID).withScopes(
FACEBOOK_EMAIL_SCOPE,
FACEBOOK_BIRTHDAY_SCOPE,
FACEBOOK_USERID_SCOPE,
FACEBOOK_USER_LAST_NAME_SCOPE,
FACEBOOK_USER_FIRST_NAME_SCOPE).withScopeDelimiter(",");
AUTH.login(req, new Callback<String, Throwable>(){
#Override
public void onFailure(Throwable reason) {
Window.alert("Error:\n" + reason.getMessage());
}
#Override
public void onSuccess(String token) {
// Window.alert("Got an OAuth token:\n" + token + "\n"
// + "Token expires in " + AUTH.expiresIn(req) + " ms\n");
RootPanel.get().remove(loginButton);
}
});
}
});
RootPanel.get().add(loginButton);
}