Guava Cache - quickly return initial value and do async refresh - guava

I am trying to implement "cache entry enrichment" behavior:
When the key is new/outdated for the cache, return the quickly precalculated value and trigger async recalculation for the key
Once async recalculation is done, return the updated value
The following code implements that, but is obviously dramatically bad. Is there a way to achieve that by pure cache config?
Code+Test:
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.SneakyThrows;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
#RunWith(MockitoJUnitRunner.class)
public class GuavaCacheTest {
final LoadingCache<Long, String> myCache = CacheBuilder.newBuilder()
.maximumSize(1000)
.build(
new CacheLoader<Long, String>() {
ExecutorService executor = Executors.newFixedThreadPool(10);
public String load(Long key) {
System.out.println("load() " + key);
return "INITIAL";
}
public ListenableFuture<String> reload(final Long key, String prevString) {
// asynchronous!
ListenableFutureTask<String> task = ListenableFutureTask.create(() -> {
System.out.println("reload() started for ... " + key);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("reload() ended for ... " + key);
return "Calculated value for " + key;
});
executor.execute(task);
return task;
}
});
public String myget(Long key) {
String v = myCache.getUnchecked(key);
if (v == "INITIAL") {
myCache.refresh(key);
myCache.getUnchecked(key);
v = "Initial value for " + key;
}
return v;
}
#Test
#SneakyThrows
public void testRepeatedCalls() {
System.out.println("Call result: " + myget(55L));
System.out.println("Call result: " + myget(55L));
System.out.println("Call result: " + myget(55L));
System.out.println("Call result: " + myget(55L));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("---------------");
System.out.println("Call result: " + myget(55L));
System.out.println("Call result: " + myget(55L));
System.out.println("Call result: " + myget(55L));
System.out.println("Call result: " + myget(55L));
}
}
Output:
load() 55
reload() started for ... 55
Call result: Initial value for 55
Call result: Initial value for 55
Call result: Initial value for 55
Call result: Initial value for 55
reload() ended for ... 55
---------------
Call result: Calculated value for 55
Call result: Calculated value for 55
Call result: Calculated value for 55
Call result: Calculated value for 55

Related

I need to get a value of ListenableFutureCallback from the delete function of 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

apache beam: accessing metrics during pipeline processing

Using the WordCount.java example to test metrics. The PrintMetricsFn function (see below) prints the metrics correctly once the pipeline is finished, but fails when called while the pipeline is processing. DirectRunner and FlinkRunner both throw exceptions (null input), while SparkRunner prints only the header line (similar to "* Metric Values *").
private static void PrintMetricsFn(final MetricsFilter inputFilter) {
final MetricResults metrics = result.metrics();
final MetricQueryResults returns = metrics.queryMetrics(inputFilter);
final Iterable<MetricResult<Long>> counters = returns.getCounters();
System.out.println("*** Metric Values ***");
for(final MetricResult<Long> s: counters){
System.out.println(s.getName().getNamespace() + ":" +
s.getName().getName() + ":" + s.getStep() + ": count=" +
s.getAttempted()) ;
}
final Iterable<MetricResult<DistributionResult>> dist = returns.getDistributions();
for (final MetricResult<DistributionResult> d: dist) {
System.out.println(d.getName().getNamespace() + ":" +
d.getName().getName() + ":" + d.getStep() + ": sum=" +
d.getAttempted().getSum() + ", count=" +
d.getAttempted().getCount() + ", min=" +
d.getAttempted().getMin() + ", max=" +
d.getAttempted().getMax() + ", mean=" +
d.getAttempted().getMean());
}
final Iterable<MetricResult<GaugeResult>> gauge = returns.getGauges();
for (final MetricResult<GaugeResult> g: gauge) {
System.out.println(g.getName().getNamespace() + ":" +
g.getName().getName() + ":" + g.getStep() + ": gauge=" +
g.getAttempted().getValue());
}
return;
}
Here are the declarations for the external variables:
private static PipelineResult result;
private static MetricQueryResults returns;
private static MetricsFilter mFilter;
And here's where the mFilter and result variables are set:
mFilter = MetricsFilter.builder()
.addNameFilter(MetricNameFilter.named("ExtractWordsFn", "emptyLines"))
.addNameFilter(MetricNameFilter.named("ExtractWordsFn", "lineLenDistro"))
.addNameFilter(MetricNameFilter.named("ExtractWordsFn", "maxLineLen"))
.build();
result = p.run();
Finally, here's the function that calls PrintMetricsFN without success:
#ProcessElement
public void processElement(#Element final String element, final OutputReceiver<String> receiver) {
lineLen = element.length();
lineLenDist.update(lineLen);
if (element.trim().isEmpty()) {
emptyLines.inc();
}
if (lineLen > localMax) {
localMax = lineLen;
maxLineLen.set(localMax);
}
if((lineCnt++ % 10) == 0) {
PrintMetricsFn(mFilter);
}
// Split the line into words.
final String[] words = element.split(ExampleUtils.TOKENIZER_PATTERN, -1);
// Output each word encountered into the output PCollection.
for (final String word : words) {
if (!word.isEmpty()) {
receiver.output(word);
}
}
}
And for completeness, here's the error I get from DirectRunner:
Caused by: java.lang.NullPointerException
at org.apache.beam.examples.WordCount.PrintMetricsFn(WordCount.java:158)
at org.apache.beam.examples.WordCount.access$1(WordCount.java:157)
at org.apache.beam.examples.WordCount$ExtractWordsFn.processElement(WordCount.java:132)

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);

#AspectJ pointcut for execute methods of a package that contains keyword service

I'm trying to intercept all classes that contains a specific word in their package name... something as below:
#Pointcut("execution(* *..service..*.*(..))")
I have all the classes in the packages to intercept:
com.domain.model.user.service.save(User user);
com.domain.model.user.service.impl.save(XPTO xpto);
com.domain.model.foo.service.HelloWorld.getMessage(Foo foo);
In short, i would like to intercept all the methods in the classes that belong to the
package *service*
I am trying to get this working from past many days.
Try this. Perhaps you have to exclude your aspect classes to avoid endless loops. This example catch all methods with com..login..* in package
#Aspect
#SuppressAjWarnings({ "adviceDidNotMatch" })
public class AllMethodsAspect {
private static Map<String, Long> beforeTimestamps = new HashMap<>();
#Pointcut("!within(aspects..*)"
+ " && (!execution(* org..* (..)) && !within(org..*) && !call(* org..* (..)) )"
+ " && (!execution(* java..* (..)) && !within(java..*) && !call(* java..* (..)) )"
+ " && (!execution(* javax..* (..)) && !within(javax..*) && !call(* javax..* (..)) )"
+ " && (!execution(* sun..* (..)) && !within(sun..*) && !call(* sun..* (..)) )"
+ " && execution(* com..login..*(..))")
public void methodCall() {
}
#Before("methodCall()")
public void before(JoinPoint joinPoint) {
beforeMethodCall(joinPoint);
}
#AfterReturning(pointcut = "methodCall()", returning = "returnObject")
public void after(JoinPoint joinPoint, Object returnObject) {
afterMethodCall(joinPoint, returnObject);
}
#AfterThrowing(pointcut = "methodCall()", throwing = "throwable")
public void throwing(JoinPoint joinPoint, Throwable throwable) {
afterThrowingMethodCall(joinPoint, throwable);
}
void beforeMethodCall(JoinPoint joinPoint) {
try {
long start = System.currentTimeMillis();
beforeTimestamps.put(joinPoint.toString() + " - " + Thread.currentThread().getName(), Long.valueOf(start));
LOG.info(".before " + joinPoint);
} catch (Exception e) {
LOG.error(".before Exception " + e);
}
}
void afterMethodCall(JoinPoint joinPoint, Object returnObject) {
afterMethodCall(joinPoint, returnObject, 0);
}
void afterMethodCall(JoinPoint joinPoint, Object returnObject, int depth) {
try {
long start = beforeTimestamps.get(joinPoint.toString() + " - " + Thread.currentThread().getName()).longValue();
beforeTimestamps.remove(joinPoint.toString() + " - " + Thread.currentThread().getName());
long duration = System.currentTimeMillis() - start;
Signature signature = joinPoint.getSignature();
if (signature instanceof MethodSignature) {
Class<?> returnType = ((MethodSignature) signature).getReturnType();
LOG.info(".after " + joinPoint + " " + duration + "ms" + (void.class == returnType ? "" : " [" + returnObject + "]"));
} else if (signature instanceof ConstructorSignature) {
LOG.info(".after " + joinPoint + " " + duration + "ms Constructor");
} else if (signature instanceof FieldSignature) {
LOG.info(".after " + joinPoint + " " + duration + "ms Field");
} else {
LOG.info(".after " + joinPoint + " " + duration + "ms unknown");
}
} catch (Exception e) {
LOG.error(".after Exception " + e);
}
}
void afterThrowingMethodCall(JoinPoint joinPoint, Throwable throwable) {
try {
Long startAsLong = beforeTimestamps.get(joinPoint.toString() + " - " + Thread.currentThread().getName());
long start = startAsLong == null ? 0 : startAsLong.longValue();
beforeTimestamps.remove(joinPoint.toString() + " - " + Thread.currentThread().getName());
long duration = System.currentTimeMillis() - start;
LOG.info(".fail " + joinPoint.toString() + " " + duration + " ms - " + throwable.getMessage());
} catch (NullPointerException e) {
LOG.info(".fail NullPointerException " + "unknown - " + throwable.getMessage());
}
}
static final class LOG {
static void info(String loggingData) {
System.err.println(new Date() + " " + loggingData);
}
static void error(String loggingData) {
System.err.println(new Date() + " " + loggingData);
}
}
}
I think you can capture what you need with a pointcut like this:
before(): execution(* *(..)) &&
(within(*..service..*.*) || within(service..*.*) || within(*..service.*)) {}
The three within clauses capture the three alternatives:
within(*..service..*.*): 'service' is somewhere in the package name but not at the start or end
within(service..*.*): 'service' is at the start of the package name (maybe this can't happen in your scenario)
within(*..service.*)): 'service' is at the end of the package name
If you need to capture serviceFoo variants you could add further wildcards around service (I think): within(*..*service*.*)
You should use a pointcut expression like this:
within(your.base.package..service..*)
restrict to at least your base package (typically this is not an issue)
match 'service' keyword in your package name at any level
for example, this will match those classes :
your.base.package.service.ServiceClass
your.base.package.service.customer.ServiceClass
your.base.package.internal.service.ServiceClass
your.base.package.internal.service.customer.ServiceClass

Nokia Forms not showing text

I only wish Nokia documentation was more helpful. Its search on developer documentation totally sucks.
public class UpdateJourney extends Form implements CommandListener, Runnable {
private LocationProvider myLocation;
private Criteria myCriteria;
private Location myCurrentLocation;
private HomeScreen helloScreen;
private Command exitCommand;
private Thread getLocationThread = new Thread(this);;
public UpdateJourney(HomeScreen helloScreen) {
super("Taxeeta");
this.helloScreen = helloScreen;
getLocationThread.start();
}
public void run() {
myCriteria = new Criteria();
myCriteria.setHorizontalAccuracy(500);
try {
myLocation = LocationProvider.getInstance(myCriteria);
myCurrentLocation = myLocation.getLocation(60);
} catch (LocationException e) {
e.printStackTrace();
System.out
.println("Error : Unable to initialize location provider");
return;
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Error: Waited enough for location to return");
return;
}
System.out.println("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
String helloText = new String("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
super.append(helloText);
exitCommand = new Command("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude(),
Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
}
}
do you mean not showing from this command?:
System.out.println("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
It's not showing to phone screen. Instead it will show on console (IDE / debugging).
to showing text on Form.. you need to use somethings like:
form.addComponent(new Label("hi...");
hope it helps.