ALL_CACHE_MANAGERS CacheManager net.sf.ehcache - ehcache

Is there a replacement for net.sf.ehcache.CacheManager.ALL_CACHE_MANAGERS in
<!-- https://mvnrepository.com/artifact/org.ehcache/ehcache -->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.8.1</version>
</dependency>
?
This is the code that I need to modify to work with version 3.8.1:
import org.ehcache.CacheManager;
.
.
.
List list = CacheManager.ALL_CACHE_MANAGERS;
for (int i = 0, n = list.size(); i < n; i++) {
CacheManager cm = (CacheManager) list.get(i);
log.debug("CacheManager: " + cm.getName());
if (cm.getName().equals(CACHE_MANAGER_NAME)) {
log.debug("CM " + CACHE_MANAGER_NAME + " existed. Destroying it.");
cm.shutdown();
}
}
Is there a way of doing this in ehcache 3.8.1?

That should work:
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();
System.out.println(cacheManager); // For my case: Eh107CacheManager[urn:X-ehcache:jsr107-default-config]

It looks ALL_CACHE_MANAGERS is replaced with org.ehcache.clustered.operations command ListCacheManagers in ehcache 3.8.1.
It can be used as follows.
OperationsTool.main(...)
public static void main(String[] args) {
System.exit(innerMain(args));
}
OperationsTool.innerMain(...)
public static int innerMain(String[] args) {
BaseOptions base = new BaseOptions();
JCommander jc = new JCommander(base);
jc.setProgramName("ehcache-ops");
jc.addCommand(new ListCacheManagers(base));
jc.addCommand(new CreateCacheManager(base));
jc.addCommand(new UpdateCacheManager(base));
jc.addCommand(new DestroyCacheManager(base));
jc.setParameterDescriptionComparator(REQUIRED_FIRST);
for (JCommander jcc : jc.getCommands().values()) {
jcc.setParameterDescriptionComparator(REQUIRED_FIRST);
}
try {
jc.parse(args);
if (base.isHelp()) {
return usage(jc, new StringBuilder());
} else {
int result = 0;
for (Object o : jc.getCommands().get(jc.getParsedCommand()).getObjects()) {
result |= ((Command) o).execute();
}
return result;
}
} catch (ParameterException e) {
return usage(jc, new StringBuilder(e.getMessage()).append("\n"));
}
}
OperationsToolTest.run(...)
public static int run(String command) {
return OperationsTool.innerMain(command.split("\\s+"));
}
}
Reference:
https://www.codota.com/web/assistant/code/rs/5c76b38b49efcb0001524b15#L36
https://www.codota.com/code/java/classes/org.ehcache.clustered.operations.OperationsTool

Related

Freemarker Debugger framework usage example

I have started working on a Freemarker Debugger using breakpoints etc. The supplied framework is based on java RMI. So far I get it to suspend at one breakpoint but then ... nothing.
Is there a very basic example setup for the serverpart and the client part other then the debug/imp classes supplied with the sources. That would be of great help.
this is my server class:
class DebuggerServer {
private final int port;
private final String templateName1;
private final Environment templateEnv;
private boolean stop = false;
public DebuggerServer(String templateName) throws IOException {
System.setProperty("freemarker.debug.password", "hello");
port = SecurityUtilities.getSystemProperty("freemarker.debug.port", Debugger.DEFAULT_PORT).intValue();
System.setProperty("freemarker.debug.password", "hello");
Configuration cfg = new Configuration();
// Some other recommended settings:
cfg.setIncompatibleImprovements(new Version(2, 3, 20));
cfg.setDefaultEncoding("UTF-8");
cfg.setLocale(Locale.US);
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
Template template = cfg.getTemplate(templateName);
templateName1 = template.getName();
System.out.println("Debugging " + templateName1);
Map<String, Object> root = new HashMap();
Writer consoleWriter = new OutputStreamWriter(System.out);
templateEnv = new Environment(template, null, consoleWriter);
DebuggerService.registerTemplate(template);
}
public void start() {
new Thread(new Runnable() {
#Override
public void run() {
startInternal();
}
}, "FreeMarker Debugger Server Acceptor").start();
}
private void startInternal() {
boolean handled = false;
while (!stop) {
List breakPoints = DebuggerService.getBreakpoints(templateName1);
for (int i = 0; i < breakPoints.size(); i++) {
try {
Breakpoint bp = (Breakpoint) breakPoints.get(i);
handled = DebuggerService.suspendEnvironment(templateEnv, templateName1, bp.getLine());
} catch (RemoteException e) {
System.err.println(e.getMessage());
}
}
}
}
public void stop() {
this.stop = true;
}
}
This is the client class:
class DebuggerClientHandler {
private final Debugger client;
private boolean stop = false;
public DebuggerClientHandler(String templateName) throws IOException {
// System.setProperty("freemarker.debug.password", "hello");
// System.setProperty("java.rmi.server.hostname", "192.168.2.160");
client = DebuggerClient.getDebugger(InetAddress.getByName("localhost"), Debugger.DEFAULT_PORT, "hello");
client.addDebuggerListener(environmentSuspendedEvent -> {
System.out.println("Break " + environmentSuspendedEvent.getName() + " at line " + environmentSuspendedEvent.getLine());
// environmentSuspendedEvent.getEnvironment().resume();
});
}
public void start() {
new Thread(new Runnable() {
#Override
public void run() {
startInternal();
}
}, "FreeMarker Debugger Server").start();
}
private void startInternal() {
while (!stop) {
}
}
public void stop() {
this.stop = true;
}
public void addBreakPoint(String s, int i) throws RemoteException {
Breakpoint bp = new Breakpoint(s, i);
List breakpoints = client.getBreakpoints();
client.addBreakpoint(bp);
}
}
Liferay IDE (https://github.com/liferay/liferay-ide) has FreeMarker template debug support (https://issues.liferay.com/browse/IDE-976), so somehow they managed to use it. I have never seen it in action though. Other than that, I'm not aware of anything that uses the debug API.

gwt cell table dynamic columns - sorting need an example

I'm new to GWT and I need to create a sortable dynamic celltable.
I saw an example of IndexedColumn class. I generated a Dynamic cell table (List of ArrayList of String), but couldn't make it sort.
does anybody have a simple implementation example?
Thanks
Found my mistake...
Here is my working example:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.view.client.ListDataProvider;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class DynamicTable implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
List<ArrayList<String>> data = this.getThedata();
CellTable<List<String>> table = new CellTable<List<String>>();
ArrayList<String> dataHeaders = data.remove(0);
ArrayList<IdxColumn> columnList = new ArrayList<IdxColumn>();
ListDataProvider<List<String>> dataProvider = new ListDataProvider<List<String>>();
dataProvider.addDataDisplay(table);
List<List<String>> list = dataProvider.getList();
for (List<String> l : data) {
list.add(l);
}
ListHandler<List<String>> columnSortHandler = new ListHandler<List<String>>(list);
table.getColumnSortList().clear();
for (int i = 0; i < data.get(0).size(); i++) {
final int index = i;
IdxColumn iCol = new IdxColumn(index);
columnList.add(iCol);
table.addColumn(iCol, dataHeaders.get(index) + " (" +iCol.getIndex() + ")");
columnSortHandler.setComparator(iCol, new Comparator<List<String>>() {
public int compare(List<String> o1, List<String> o2) {
if (o1 == o2) {
return 0;
}
if (o1 != null) {
return (o2 != null) ? o1.get(0).compareTo(o2.get(0)) : 1;
}
return -1;
}
});
iCol.setSortable(true);
table.getColumnSortList().push(iCol);
}
table.addColumnSortHandler(columnSortHandler);
table.setRowCount(data.size(), true);
table.setRowData(0, data);
RootPanel.get().add(table);
}
// build the data
private List<ArrayList<String>> getThedata() {
List<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
ArrayList<String> dataHeaders = new ArrayList<String>();
dataHeaders.add("Header 1");
dataHeaders.add("Header 2");
dataHeaders.add("Header 3");
dataHeaders.add("Header 4");
dataHeaders.add("Header 5");
dataHeaders.add("Header 6");
data.add(dataHeaders);
for (int i = 0; i < 20; i++) {
ArrayList<String> dataRow = new ArrayList<String>();
dataRow.add("Col1 Row" + i);
dataRow.add("Col2 Row" + i);
dataRow.add("Col3 Row" + i);
dataRow.add("Col4 Row" + i);
dataRow.add("Col5 Row" + i);
dataRow.add("Col6 Row" + i);
data.add(dataRow);
}
return data;
}
}
And the IdxColumn class:
import java.util.List;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.user.cellview.client.Column;
public class IdxColumn extends Column<List<String>, String> {
private final int index;
public IdxColumn( int index) {
super(new TextCell());
this.index = index;
}
#Override
public String getValue(List<String> object) {
return object.get(index);
}
public int getIndex() {
return this.index;
}
}

Spring BeanUtils.copyProperties not working

I want to copy properties from one object to another, both are of the same class. However it's not copying the fields. Here is the demo code:
public static void main(String[] args) throws Exception {
A from = new A();
A to = new A();
from.i = 123;
from.l = 321L;
System.out.println(from.toString());
System.out.println(to.toString());
BeanUtils.copyProperties(from, to);
System.out.println(from.toString());
System.out.println(to.toString());
}
public static class A {
public String s;
public Integer i;
public Long l;
#Override
public String toString() {
return "A{" +
"s=" + s +
", i=" + i +
", l=" + l +
'}';
}
}
And the output is:
A{s=null, i=123, l=321}
A{s=null, i=null, l=null}
A{s=null, i=123, l=321}
A{s=null, i=null, l=null}
Looks like I have to have setter/getters for the class:
public static void main(String[] args) throws Exception {
A from = new A();
A to = new A();
from.i = 123;
from.l = 321L;
System.out.println(from.toString());
System.out.println(to.toString());
BeanUtils.copyProperties(from, to);
System.out.println(from.toString());
System.out.println(to.toString());
}
public static class A {
public String s;
public Integer i;
public Long l;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public Integer getI() {
return i;
}
public void setI(Integer i) {
this.i = i;
}
public Long getL() {
return l;
}
public void setL(Long l) {
this.l = l;
}
#Override
public String toString() {
return "A{" +
"s=" + s +
", i=" + i +
", l=" + l +
'}';
}
}
Now the output is:
A{s=null, i=123, l=321}
A{s=null, i=null, l=null}
A{s=null, i=123, l=321}
A{s=null, i=123, l=321}

AsyncTask in Android (pass ArrayList<Integer>)

I have a
ArrayList<Integer>
and i want to pass it to
AsyncTask<ArrayList<Integer>, void, void>.
But in
doInBackground(ArrayList<Integer>...params) function,
i can't receive arrayList, which i passed.
Inside doInBackground i use ArrayList<Integer> arr = params[0] then i log(arr.size()) is 0
My code:
class count extends AsyncTask<Void, Integer, ArrayList<Integer>>{
ArrayList<Integer> arr = new ArrayList<Integer>();
ArrayList<Integer> temp = new ArrayList<Integer>();
#SuppressWarnings("unchecked")
#Override
protected ArrayList<Integer> doInBackground(Void... params) {
// TODO Auto-generated method stub
for(int i = 1; i <= 100; i++){
SystemClock.sleep(200);
arr.add(i);
if(i % 10 == 0){
temp = arr;
//Log.d("DEBUG", "Length of temp = "+ temp.size());
arr.clear();
mean task1 = new mean();
task1.execute(temp);
}
publishProgress(i);
}
return arr;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
tvNum.setText(values[0]+"");
}
}
class mean extends AsyncTask<ArrayList<Integer>, Integer, ArrayList<Integer>>{
#Override
protected ArrayList<Integer> doInBackground(
ArrayList<Integer>... params) {
// TODO Auto-generated method stub
ArrayList<Integer> arrL =new ArrayList<Integer>();
arrL= params[0];
Log.d("DEBUG","iNPUT Size = " + arrL.size());
return null;
}
}
Please help me,
Thanks.
If you pass the Arraylist in as the only parameter when you're calling execute(), it should be in params[0]. For example,
YourTask.execute(YourList);
And you would access it inside of the ASyncTask as so:
Arraylist<Integer> myList = params[0];
Easy Example for your understanding. such as
public class MainActivity extends Activity {
List<CalcPrimesTask> taskList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
taskList = new ArrayList<CalcPrimesTask>();
}
public void onClickStart(View view) {
EditText maximumEditText = (EditText) findViewById(R.id.maximumEditText);
int maxNum = Integer.parseInt(maximumEditText.getText().toString());
CalcPrimesTask task = new CalcPrimesTask(this);
taskList.add(task);
task.execute(maxNum);
Toast.makeText(getApplicationContext(), "New run queued.", Toast.LENGTH_SHORT).show();
}
public void onStopClick(View view) {
for (CalcPrimesTask task : taskList) {
task.cancel(true);
}
Toast.makeText(getApplicationContext(), "All runs cancelled.", Toast.LENGTH_SHORT).show();
}
}
and
public class CalcPrimesTask extends AsyncTask<Integer, String, List<Integer>> {
Activity activity;
public CalcPrimesTask(Activity mainActivity) {
activity = mainActivity;
}
#Override
protected List<Integer> doInBackground(Integer... params) {
int maxNum = params[0];
List<Integer> primeList = new ArrayList<Integer>();
for (int i = 2; i <= maxNum ; i++) {
int maxCalc = (int)Math.sqrt(i);
boolean isPrime = true;
for (int j = 2; j <= maxCalc ; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primeList.add(i);
publishProgress("Prime " + i + " found.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
return primeList;
}
#Override
protected void onProgressUpdate(String... values) {
TextView messageView = (TextView) activity.findViewById(R.id.messageText);
messageView.setText(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(List<Integer> result) {
TextView messageView = (TextView) activity.findViewById(R.id.messageText);
messageView.setText("Total of " + result.size() + " primes found.");
super.onPostExecute(result);
}
}
If your hand available time then read Android AsyncTask. Best of Luck!

How can I get a dependency's version in the current pom.xml for maven-enforcer-plugin?

I'm trying to write an maven-enforcer rule, which checks that that project uses dependency management.
But I've got trouble to get the version which is written in the current project's pom.xml. I thought DependencyNode#getPremanagedVersion() would provide it, but it looks like it's returning a version which is set by a dependency (i.e. log4j is set in jbossall-client).
How can I get a dependency's version in the current pom.xml?
package org.example;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactCollector;
import org.apache.maven.enforcer.rule.api.EnforcerRule;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.dependency.tree.DependencyNode;
import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder;
import org.opencredo.maven.plugins.enforcer.utils.DefaultDependencyTreePrinter;
import com.oneandone.access.preclearing.AbstractNonCacheableEnforcerRule;
public class ForceDependencyManagement extends AbstractNonCacheableEnforcerRule implements EnforcerRule {
private String message = "";
private MavenProject project;
private ArtifactRepository localRepository;
private ArtifactFactory artifactFactory;
private ArtifactMetadataSource artifactMetadataSource;
private ArtifactCollector artifactCollector;
private DependencyTreeBuilder dependencyTreeBuilder;
private void init(EnforcerRuleHelper helper) throws EnforcerRuleException {
try {
project = (MavenProject) helper.evaluate("${project}");
localRepository = (ArtifactRepository) helper.evaluate("${localRepository}");
artifactFactory = (ArtifactFactory) helper.getComponent(ArtifactFactory.class);
artifactCollector = (ArtifactCollector) helper.getComponent(ArtifactCollector.class);
artifactMetadataSource = (ArtifactMetadataSource) helper.getComponent(ArtifactMetadataSource.class);
dependencyTreeBuilder = (DependencyTreeBuilder) helper.getComponent(DependencyTreeBuilder.class);
} catch (Exception eee) {
throw new EnforcerRuleException("Unable to retrieve the rule dependencies: ", eee);
}
}
public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException {
init(helper);
DependencyNode rootNode = buildDependencyTree();
if (rootNode != null) {
Set found = new HashSet();
Iterator iter = rootNode.iterator();
System.out.println("Dependencies: ");
while (iter.hasNext()) {
DependencyNode node = (DependencyNode) iter.next();
if (StringUtils.isNotEmpty(node.getPremanagedVersion())) {
found.add(node);
}
}
if (found.size() > 0) {
fail(found);
}
}
}
protected DependencyNode buildDependencyTree() {
try {
DependencyNode rootNode =
dependencyTreeBuilder.buildDependencyTree(project, localRepository, artifactFactory,
artifactMetadataSource, null, artifactCollector);
return rootNode;
} catch (Exception e) {
throw new RuntimeException("Failed to build dependency tree", e);
}
}
private void fail(Set found) throws EnforcerRuleException {
Iterator iter;
StringBuffer fullMessage = new StringBuffer();
if (StringUtils.isNotEmpty(message)) {
fullMessage.append(message);
} else {
fullMessage.append("Found artifact without dependency management:");
}
fullMessage.append("\n");
iter = found.iterator();
while (iter.hasNext()) {
DependencyNode node = (DependencyNode) iter.next();
Artifact artifact = node.getArtifact();
fullMessage.append(" " + artifact.getGroupId() + ":" + artifact.getArtifactId() + " is set to version "
+ node.getPremanagedVersion() + "\n");
getTreePrinter().printDependencyTree(fullMessage, artifact, 4);
}
throw new EnforcerRuleException(fullMessage.toString());
}
private DefaultDependencyTreePrinter getTreePrinter() {
return new DefaultDependencyTreePrinter(project, localRepository, artifactFactory, artifactMetadataSource,
artifactCollector, dependencyTreeBuilder);
}
public boolean isCacheable() {
return false;
}
public String getCacheId() {
return null;
}
public boolean isResultValid(EnforcerRule cachedRule) {
return false;
}
}
This should do it
MavenProject project = (MavenProject) helper.evaluate("${project}");
List dependencies = project.getDependencies();
From there just iterate throught the list of dependencies and call .getVersion()
for (int i = 0; i < project.getDependencies().size(); i++) {
String version = project.getDependencies().get(i).getVersion();
}
You can also get to the dependency management info from the project object

Resources