AnnotationConfigApplicationContext#4c0bc4 has not been refreshed yet - java

I'm getting stack trace for following code,
public interface SequenceDAO {
public Sequence getSequence(String sequenceId);
public int getNextValue(String sequenceId);
}
``````````````````````````````````````````
public class Sequence {
private int initial;
private String prefix;
private String suffix;
public Sequence(int initial, String prefix, String suffix) {
this.initial = initial;
this.prefix = prefix;
this.suffix = suffix;
}
````````````````````````````````````````````````
#Component("SequenceDAO")
public class SequenceDAOImpl implements SequenceDAO {
private Map<String, Sequence> sequences;
private Map<String, Integer> values;
public SequenceDAOImpl() {
sequences = new HashMap<>();
sequences.put("IT", new Sequence(30, "IT", "A"));
values = new HashMap<>();
values.put("IT", 10000);
}
#Override
public Sequence getSequence(String sequenceId) {
return sequences.get(sequenceId);
}
#Override
public int getNextValue(String sequenceId) {
int value = values.get(sequenceId);
values.put(sequenceId, value + 1);
return value;
}
}
``````````````````````````````````````````````
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.example");
SequenceDAO obj = context.getBean("SequenceDAO", SequenceDAO.class);
System.out.println(obj.getNextValue("IT"));
System.out.println(obj.getSequence("IT"));
}
`````````````````````````````````````````````````````````
Exception in thread "main" java.lang.IllegalStateException: org.springframework.context.annotation.AnnotationConfigApplicationContext#4c0bc4 has not been refreshed yet
at org.springframework.context.support.AbstractApplicationContext.assertBeanFactoryActive(AbstractApplicationContext.java:1041)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1059)
at com.example.SpringAnnotationsSequenceGeneratorWithDaoIntroductionApplication.main(SpringAnnotationsSequenceGeneratorWithDaoIntroductionApplication.java:14)
Iam new to spring and I am learning spring without annotations , so if anyone can tell me what happend wrong here
any help is appericiated.
Beat Regards

Your context init should like this:
ApplicationContext aContext = new AnnotationConfigApplicationContext(ConcertConfig.class);
#Configuration
#EnableAspectJAutoProxy
#ComponentScan
public class ConcertConfig {
}

Related

How can I provide this sort of String builder class?

I like to have a Drive class where all files and folders for a project are managed.
My first attempt was pretty easy like a lot of functions (most of them with arguments).
Now I try to make it more fancy because it became more and more annoying to have a lot of functions, in which the desired one can be found. To not have an XY-problem here, I start with my dream.
I like to construct the Drive class in a way, so that it is super easy to find a certain file or folder.
If you look in the main function, I can find every needed file by writing a point and look which subclasses/methods are proposed to continue, till I find it and add .str to it. At every point, only the subclasses/methods will be proposed which makes sense at this point.
It almost works! It is more complicated to write and maintain as the first approach, but If I use it very often, it could be worth it.
I can:
go into subfolders
go into subfolders with name inside the argument
But there is an error if I define a fixed-name-subfolder of a fluid-name-folder like in the code below.
Now my questions:
how can I change the code so the main Function doesn't show this error?
would you recommend a completely different approach to the "make it easy to find strings inside a huge list of strings via making collections inside collections... of strings"-problem?
package utilities;
public class Drive_draft {
private static final String fs = System.getProperty("file.separator");
public static final String str = System.getProperty("user.home").concat(fs);
public static class IeCreation {
public static final String str = Drive_draft.str.concat(".meetings").concat(fs);
public static class Abstract {
public static final String str = IeCreation.str.concat("Abstracts").concat(fs);
}
public static class Meeting {
public static final String str = IeCreation.str.concat("Ueberordnungen").concat(fs);
}
}
public static class MetsSIPs {
public static final String str = Drive_draft.str.concat("workspace").concat(fs).concat("metsSIPs").concat(fs);
public static class preSIPs {
public static final String str = MetsSIPs.str.concat("preSIPs").concat(fs);
}
public static class RosettaInstance {
private static class MaterialflowId {
public static String str;
private static class ProducerId {
public static String str;
private static class Abstract {
public static String str;
public static class Mets {
public static final String str = Abstract.str.concat("content").concat(fs).concat("ie1.xml");
}
}
private static class Meeting {
public static String str;
}
public static Abstract Abstract (String value) {
Abstract ret = new Abstract();
ProducerId.Abstract.str = str.concat(value).concat(fs);
return ret;
}
public static Meeting Meeting (String value) {
Meeting ret = new Meeting();
ProducerId.Meeting.str = str.concat(value).concat(fs);
return ret;
}
}
public static ProducerId ProducerId (String value) {
ProducerId ret = new ProducerId();
MaterialflowId.ProducerId.str = str.concat(value).concat(fs);
return ret;
}
}
public static MaterialflowId MaterialflowId (String value) {
MaterialflowId ret = new MaterialflowId();
MaterialflowId.str = str.concat(value).concat(fs);
return ret;
}
}
public static class Dev extends RosettaInstance {
public static final String str = MetsSIPs.str.concat("dev").concat(fs);
}
public static class Test extends RosettaInstance {
public static final String str = MetsSIPs.str.concat("test").concat(fs);
}
public static class Prod extends RosettaInstance{
public static final String str = MetsSIPs.str.concat("prod").concat(fs);
}
}
#SuppressWarnings("static-access")
public static void main(String[] args) {
System.out.println(Drive_draft.MetsSIPs.Dev.str);
System.out.println(Drive_draft.MetsSIPs.Dev.MaterialflowId("1").str);
System.out.println(Drive_draft.MetsSIPs.Dev.MaterialflowId("2").str);
System.out.println(Drive_draft.MetsSIPs.Dev.MaterialflowId("1").ProducerId("t").str);
System.out.println(Drive_draft.MetsSIPs.Dev.MaterialflowId("1").ProducerId("t").Abstract("est").str);
System.out.println(Drive_draft.MetsSIPs.Dev.MaterialflowId("1").ProducerId("t").Meeting("oast").str);
System.out.println(Drive_draft.MetsSIPs.Dev.MaterialflowId("1").ProducerId("t").Abstract("est").Mets.str); //Error: Mets cannot be resolved or is not a field
}
}
You can encode your "directory" structure with interfaces, with each interface declaring what the user can do next. Then the implementation can use a StringBuilder to just append the appropriate snippets and keep returning this.
// PathBuilderInterfaces.java
public class PathBuilderInterfaces {
public interface Buildable {
String build();
}
public interface Drive extends Buildable {
IeCreation ieCreation();
MetsSIPs metsSIPs();
}
public interface IeCreation extends Buildable {
String ieCreationAbstract();
String meeting();
}
public interface MetsSIPs extends Buildable {
RosettaInstance dev();
RosettaInstance test();
RosettaInstance prod();
}
public interface RosettaInstance extends Buildable {
MaterialFlowId materialFlowId(String value);
}
public interface MaterialFlowId extends Buildable {
ProducerId producerId(String value);
}
public interface ProducerId extends Buildable {
Abstract producerIdAbstract(String value);
String meeting(String value);
}
public interface Abstract extends Buildable {
String mets();
}
}
// PathBuilder.java
import static com.example.somepackage.PathBuilderInterfaces.*;
public class PathBuilder implements Drive, IeCreation, MetsSIPs, RosettaInstance, MaterialFlowId, ProducerId, Abstract{
private StringBuilder builder = new StringBuilder(str);
private static final String fs = System.getProperty("file.separator");
public static final String str = System.getProperty("user.home").concat(fs);
public static Drive drive() {
return new PathBuilder();
}
#Override
public String build() {
return builder.toString();
}
#Override
public IeCreation ieCreation() {
builder.append(".meetings").append(fs);
return this;
}
#Override
public MetsSIPs metsSIPs() {
builder.append("workspace").append(fs).append("metsSIPs").append(fs);
return this;
}
#Override
public RosettaInstance dev() {
builder.append("dev").append(fs);
return this;
}
#Override
public RosettaInstance test() {
builder.append("test").append(fs);
return this;
}
#Override
public RosettaInstance prod() {
builder.append("prod").append(fs);
return this;
}
#Override
public MaterialFlowId materialFlowId(String value) {
builder.append(value).append(fs);
return this;
}
#Override
public ProducerId producerId(String value) {
builder.append(value).append(fs);
return this;
}
#Override
public Abstract producerIdAbstract(String value) {
builder.append(value).append(fs);
return this;
}
#Override
public String meeting(String value) {
builder.append(value).append(fs);
return build();
}
#Override
public String mets() {
builder.append("content").append(fs).append("ie1.xml");
return build();
}
#Override
public String ieCreationAbstract() {
builder.append("Abstracts").append(fs);
return build();
}
#Override
public String meeting() {
builder.append("Ueberordnungen").append(fs);
return build();
}
}
Usage:
// in a main method somewhere
System.out.println(
PathBuilder.drive()
.metsSIPs()
.dev()
.materialFlowId("1")
.producerId("t")
.producerIdAbstract("est")
.mets());

Java Priority Queue Issue

Issue: I've got a priority queue to process actions. When I instantiate the actions and then add them to the queue it works, however when I instantiate them directly as I add them to the queue it no longer retains the priority.
This works - Executes by priority
public static void main(String[] args) {
final Action<Void> low = new LowAction();
final Action<Void> med = new MedAction();
final Action<Integer> high = new HighAction();
final Action<Boolean> walk = new WalkAction();
final ActionScheduler scheduler = new ActionScheduler(1,10);
scheduler.queue(high);
scheduler.queue(walk);
scheduler.queue(low);
scheduler.queue(med);
}
This does not work - Executes in the order I called them
public static void main(String[] args) {
final ActionScheduler scheduler = new ActionScheduler(1,10);
scheduler.queue(new HighAction());
scheduler.queue(new WalkAction());
scheduler.queue(new LowAction());
scheduler.queue(new MedAction());
}
ActionScheduler class
public class ActionScheduler {
private ExecutorService priorityJobPoolExecutor;
private ExecutorService priorityJobScheduler
= Executors.newSingleThreadExecutor();
private PriorityBlockingQueue<Action<?>> priorityQueue;
private Future<?> result;
public ActionScheduler(Integer poolSize, Integer queueSize) {
priorityJobPoolExecutor = Executors.newFixedThreadPool(poolSize);
priorityQueue = new PriorityBlockingQueue<>(queueSize);
priorityJobScheduler.submit(() -> {
while (true) {
try {
result = priorityJobPoolExecutor.submit(priorityQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
});
}
public void schedule(Action<?> action) {
priorityQueue.offer(action);
}
public <T> Future<T> queue(Action<?> action) {
this.schedule(action);
return (Future<T>) result;
}
}
This also works correctly
public static void main(String[] args) {
final Action<Void> low = new LowAction();
final Action<Void> med = new MedAction();
final Action<Integer> high = new HighAction();
final Action<Boolean> walk = new WalkAction();
final ActionScheduler scheduler = new ActionScheduler(1,10);
scheduler.queue(new HighAction());
scheduler.queue(new WalkAction());
scheduler.queue(new LowAction());
scheduler.queue(new MedAction());
}
If anyone could offer any insight on why this is happening and how I can get it to execute by priority in both examples posted it would be greatly appreciated.
EDIT
Action Class
public abstract class Action<T> implements Callable<T>, Comparable<Action<?>> {
private final ActionContext context;
public Action(ActionContext context) {
this.context = context;
}
#Override
public int compareTo(Action action) {
if (action.getContext().getPriority() == this.getContext().getPriority()) {
return 0;
} else if (this.getContext().getPriority().ordinal() > action.getContext().getPriority().ordinal()) {
return -1;
} else {
return 1;
}
}
public ActionContext getContext() {
return context;
}
}
LowAction class
public class LowAction extends Action<Void> {
public LowAction() {
super(new ActionContext("low", Priority.LOW, true, false));
}
#Override
public Void call() throws Exception {
System.out.println("LOW");
return null;
}
}
There is one difference which I can see in the first approach you are binding your object with an actual type like final Action<**Void**> low = new LowAction(); on the other hand new LowAction() will be treat as a raw creation.
The internal working of the PriorityQueue is based on the Binary Heap.The elements of the priority queue are ordered according to the natural ordering, or by a comparator provided at construction time of the queue, depending on which constructor is used.

Strange Null Pointer Exception in my tests passes one but fails other

Trying to use test driven development and ran into a NPE that I can't resolve and obviously because of that one of my tests fail.
In a method to fetch items I pass in a limit int and then instantiate a callback.
this is exactly where it falis the listener returns null I think.
[![enter image description here][1]][1]
Test class
package com.techyourchance.testdrivendevelopment.example11;
#RunWith(MockitoJUnitRunner.class)
public class FetchCartItemsUseCaseTest {
public static final int LIMIT = 10;
public static final int PRICE = 5;
public static final String ID = "id";
public static final String TITLE = "title";
public static final String DESCRIPTION = "description";
FetchCartItemsUseCase SUT;
#Mock
FetchCartItemsUseCase.Listener mListnerMock1;
FetchCartItemsUseCase.Listener mListnerMock2;
#Mock
GetCartItemsHttpEndpoint mGetCartItemsHttpEndpointMock;
#Captor
ArgumentCaptor<List<CartItem>> mAcListCartItem;
#Before
public void setup() throws Exception {
SUT = new FetchCartItemsUseCase(mGetCartItemsHttpEndpointMock);
success();
}
private void success() {
doAnswer(new Answer() {
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Callback callback = (Callback) args[1];
callback.onGetCartItemsSucceeded(getCartItemSchemes());
return null;
}
}).when(mGetCartItemsHttpEndpointMock).getCartItems(anyInt(), any(Callback.class));
}
private List<CartItemSchema> getCartItemSchemes() {
List<CartItemSchema> schemas = new ArrayList<>();
schemas.add(new CartItemSchema(ID, TITLE, DESCRIPTION, PRICE));
return schemas;
}
#Test
public void fetchCartItems_correctLimitPassedToEndPoint() throws Exception {
ArgumentCaptor<Integer> acInt = ArgumentCaptor.forClass(Integer.class);
SUT.fetchCartItemsAndNotify(LIMIT);
verify(mGetCartItemsHttpEndpointMock).getCartItems(acInt.capture(), any(GetCartItemsHttpEndpoint.Callback.class));
assertThat(acInt.getValue(), is(LIMIT));
}
#Test
public void fetchCartItems_success_observersNotifiedWithCorrectData() throws Exception {
SUT.registerListener(mListnerMock1);
SUT.registerListener(mListnerMock2);
SUT.fetchCartItemsAndNotify(LIMIT);
verify(mListnerMock1).onCartItemsFetched(mAcListCartItem.capture());
verify(mListnerMock2).onCartItemsFetched(mAcListCartItem.capture());
List<List<CartItem>> captures = mAcListCartItem.getAllValues();
List<CartItem> capture1 = captures.get(0);
List<CartItem> capture2 = captures.get(1);
assertThat(capture1, is(getCartItems()));
assertThat(capture2, is(getCartItems()));
}
private List<CartItem> getCartItems() {
List<CartItem> cartItems = new ArrayList<>();
cartItems.add(new CartItem(ID, TITLE, DESCRIPTION, PRICE));
return cartItems;
}
//correct limit passed to the endpoint
//success - all observers notified with correct data
//success - unsubscribed observers not notified
//general error - observers notified of failure
//network error - observers notified of failure
}
public class FetchCartItemsUseCase {
private final List<Listener> mListeners = new ArrayList<>();
private final GetCartItemsHttpEndpoint mGetCartItemsHttpEndpoint;
public FetchCartItemsUseCase(GetCartItemsHttpEndpoint mGetCartItemsHttpEndpoint) {
this.mGetCartItemsHttpEndpoint = mGetCartItemsHttpEndpoint;
}
public void fetchCartItemsAndNotify(int limit) {
mGetCartItemsHttpEndpoint.getCartItems(limit, new GetCartItemsHttpEndpoint.Callback() {
#Override
public void onGetCartItemsSucceeded(List<CartItemSchema> cartItems) {
for(Listener listener : mListeners) {
listener.onCartItemsFetched(cartItemsFromSchemas(cartItems));
}
}
#Override
public void onGetCartItemsFailed(GetCartItemsHttpEndpoint.FailReason failReason) {
}
}) ;
}
private List<CartItem> cartItemsFromSchemas(List<CartItemSchema> cartItemSchemas) {
List<CartItem> cartItems = new ArrayList<>();
for(CartItemSchema schema : cartItemSchemas) {
cartItems.add(new CartItem(schema.getId(), schema.getTitle(),
schema.getDescription(), schema.getPrice()));
}
return cartItems;
}
public void registerListener(Listener listener) {
mListeners.add(listener);
}
public interface Listener {
Void onCartItemsFetched(List<CartItem> capture);
}
}
[1]: https://i.stack.imgur.com/r6Sea.png
really lost would appreciate any help
public class FetchReputationUseCaseSync {
private GetReputationHttpEndpointSync mGetReputationHttpEndpointSync;
public FetchReputationUseCaseSync(GetReputationHttpEndpointSync getReputationHttpEndpointSync) {
this.mGetReputationHttpEndpointSync = getReputationHttpEndpointSync;
}
public UseCaseResult fetchReputation() {
GetReputationHttpEndpointSync.EndpointResult result;
try{
result = mGetReputationHttpEndpointSync.getReputationSync();
}catch (NetworkErrorException e) {
e.printStackTrace();
return UseCaseResult.FAILURE;
}
switch(result.getStatus()) {
case SUCCESS:
return UseCaseResult.SUCCESS;
case GENERAL_ERROR:
return UseCaseResult.FAILURE;
default:
throw new RuntimeException("invalid status: " + result);
}
}
public enum UseCaseResult{
SUCCESS, FAILURE
}
}

Spring, ehCache, multiple cache managers throwing errors where pre-existing caches of the same name found

Good evening all.. maybe someone can help me sort this out some.
I'm attempting to set up multiple cache managers, each with its own set of distinct caches. To that end, I have the following:
MyCachingFactory:
public interface MyCachingFactory {
public JCacheCacheManager cacheManager();
public JCacheCacheManager commonCacheManager();
public JCacheCacheManager secondaryCacheManager();
public JCacheCacheManager secondaryCacheManager();
}
MyCachingFactoryImpl:
#EnableCaching
public class MyCachingFactoryImpl implements MyCachingFactory {
private static final int DEFAULT_CACHE_EXPIRY = 64800;
private static final List<String> DEFAULT_CACHES = Arrays.asList(
"default");
private static final List<String> COMMON_CACHES = Arrays.asList(
"common_default",
"common_config",
"common_session",
"common_roles",
"common_capabilities");
private static final List<String> SECONDARY_CACHES = Arrays.asList(
"secondary_default",
"secondary_foo");
private static final List<String> TERTIARY_CACHES = Arrays.asList(
"tertiary_default",
"tertiary_foo");
#Bean
public JCacheCacheManager cacheManager() {
return getNewJCacheManager(DEFAULT_CACHES);
}
#Bean
public JCacheCacheManager commonCacheManager() {
return getNewJCacheManager(COMMON_CACHES);
}
#Bean
public JCacheCacheManager secondaryCacheManager() {
return getNewJCacheManager(SECONDARY_CACHES);
}
#Bean
public JCacheCacheManager tertiaryCacheManager() {
return getNewJCacheManager(TERTIARY_CACHES);
}
private JCacheCacheManager getNewJCacheManager(List<String> cacheNames) {
JCacheCacheManager springJCacheManager = new JCacheCacheManager();
CachingProvider provider = Caching.getCachingProvider();
EhcacheCachingProvider ehcacheProvider = (EhcacheCachingProvider) provder;
javax.cache.CacheManager jCacheManager = ehcacheProvider.getCacheManager();
AtomicInteger count = new AtomicInteger(1);
cacheNames.forEach((listName) -> {
logger.debug("[" + count + "] Creating cache name [" + listName + "].");
jCacheManager.createCache(listName, new MutableConfiguration<>()
.setExpiryPolicyFactory(TouchedPolicyExpiry.factoryOf(new Duration(TimeUnit.SECONDS, DEFAULT_CACHE_EXPIRY)))
.setStoryByValue(false)
.setStatisticsEnabled(true));
count.incrementAndGet();
});
springJCacheManager.setCacheManager(jCacheManager);
return springJCacheManager;
}
}
Example class:
public class Example {
#Resource
private JCacheCacheManager commonCacheManager;
#CacheResult(cacheName = "common_config")
public String getCachedConfigByName(String name) { ... }
#CacheResult(cacheName = "common_config")
public String getCachedConfigByType(String type) { ... }
}
However, when starting up my application, I see my debug statements for cache creation... iterating over the same list (in this case, COMMON_CACHE) multiple times. This, in turn, causes a nested exception in that Spring complains that a cache named X already exists.
What am I doing wrong here?
Thanks in advance (go easy please... I am new to spring caching).

EHCache 3 not working as a Map

I'm using EHCache for my Spring application and I don't think its working as expected
If you see below I'm adding the same data to a hashmap and also to Ehcache .. but when I tried to get it from the ehCache it prints null
Is there anything wrong in the way I have initialized the Cache or something that I have missed.
My class
#Named
public class Myclass extends DataLoader {
private static final Logger LOGGER = Logger.getLogger(Myclass.class.getName());
#Inject
private DictionaryInitializer dictionaryLoader;
#Inject
#Named("fileLoader")
private FileLoader fileLoader;
private Cache<String,Object> dictionary;
#PostConstruct
#Override
public void loadResource() {
List<String> spellTerms = null;
dictionary=dictionaryLoader.getCache();
String fileName = "C:\\spelling.txt";
spellTerms = fileLoader.loadResource(fileName);
HashMap<String,Object> dictData = new HashMap<>();
for(String line:spellTerms)
{
for (String key : parseWords(line))
{
HashMap<String,Object> tempMap = dictionaryUtil.indexWord(key);
if(tempMap!=null && !tempMap.isEmpty())
{
Set<Map.Entry<String, Object>> entries = tempMap.entrySet();
for(Map.Entry<String, Object> entry:entries)
{
dictionary.put(entry.getKey(), entry.getValue());
}
}
dictData.putAll(tempMap);
}
}
System.out.println(dictData.get("urcle")); //prints 45670
System.out.println(dictionary.get("urcle")); // prints null
}
private static Iterable<String> parseWords(String text)
{
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("[\\w-[\\d_]]+").matcher(text.toLowerCase());
while (m.find()) {
allMatches.add(m.group());
}
return allMatches;
}
}
My DictionaryInitializer is like below
public class DictionaryInitializer {
private static final Logger LOGGER = Logger.getLogger(DictionaryInitializer.class.getName());
private Cache<String,Object> dictionary;
#PostConstruct
public void initializeCache() {
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.build(true);
this.dictionary = cacheManager.createCache("myCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, Object.class,
ResourcePoolsBuilder.heap(100)).build());
LOGGER.info("Dictionary loaded");
}
public Cache<String,Object> getCache(){
return dictionary;
}
public void setCache(Cache<String,Object> dictionary) {
this.dictionary=dictionary;
}
}
I have found the issue.
I have initialized the Cache with a heap of just 100 entry and hence it takes only the fist 100 entries into the cache.
Fixed that and it works as expected

Categories