I want to use EHcache in my java project. They have persistent storage support. I have read the docs
https://www.ehcache.org/documentation/2.7/configuration/fast-restart.html and found this code
Configuration cacheManagerConfig = new Configuration()
.diskStore(new DiskStoreConfiguration()
.path("/tmp/file.txt"));
CacheConfiguration cacheConfig = new CacheConfiguration()
.name("my-cache")
.maxBytesLocalHeap(16, MemoryUnit.MEGABYTES)
.maxBytesLocalOffHeap(256, MemoryUnit.MEGABYTES)
.persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP));
cacheManagerConfig.addCache(cacheConfig);
CacheManager cacheManager = new CacheManager(cacheManagerConfig);
Ehcache myCache = cacheManager.getEhcache("my-cache");
I have imported the dependency but it shows lots of error.
Error I got
'Configuration' is abstract; cannot be instantiated
Please provide some simple steps to make use of this library. I read the docs but the code doesn't get worked. Help me with some solutions.
Found the Answer.
try(PersistentCacheManager persistentCacheManager =
newCacheManagerBuilder()
.with(persistence("/tmp/myProjectCache"))
.withCache("test-cache",
newCacheConfigurationBuilder(
String.class, String.class,
newResourcePoolsBuilder()
.heap(1, EntryUnit.ENTRIES)
.offheap(1, MemoryUnit.MB)
.disk(2, MemoryUnit.MB, true)
)
).build(true)) {
org.ehcache.Cache cache = persistentCacheManager.getCache("test-cache", String.class, String.class);
cache.put("name1","steven");
cache.put("name2","prince");
System.out.println(cache.get("name1"));
System.out.println(cache.get("name2"));
}
Related
I am using GraphQL-Java version:11.0
From Official GraphQL-Java documenetation I found that I can disable the introspection query as belwo :
GraphQLSchema schema = GraphQLSchema.newSchema()
.query(StarWarsSchema.queryType)
.fieldVisibility(NoIntrospectionGraphqlFieldVisibility.NO_INTROSPECTION_FIELD_VISIBILITY)
.build();
Same has been given in this SO question's answer
But the issue is in above solutions the fieldVisibility is available with object returned by GraphQLSchema.newSchema().
I am building the GraphQL schema as below:
public GraphQLProvider init(GraphQLResolvers graphQLResolvers) {
GraphQLSchema graphQLSchema = buildSchema (typeRegistry, runtimeWiring);
this.graphQL = createInstance (graphQLSchema);
return this;
}
private GraphQLSchema buildSchema (TypeDefinitionRegistry typeRegistry, RuntimeWiring runtimeWiring) {
SchemaGenerator schemaGenerator = new SchemaGenerator();
return schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
}
private GraphQL createInstance (GraphQLSchema graphQLSchema) {
return GraphQL.newGraphQL(graphQLSchema).build();
}
As you can see in above code, I am not using GraphQLSchema.newSchema() anywhere, so I am not able to set the fieldVisibility for introspectionQuery, can anyone suggest how can I modify above code to accommodate fieldVisibility option?
Any help is much appreciated. Thanks!
The fieldVisibility option is also available on RuntimeWiring, so I just did
RuntimeWiring.Builder builder = graphQLResolvers.newRuntimeWiringBuilder();
builder.fieldVisibility(NoIntrospectionGraphqlFieldVisibility.NO_INTROSPECTION_FIELD_VISIBILITY);
Hope it helps someone :)
I'm new with EJB and Im trying to consume a remote EJB from Liferay. EJB is deployed on WebLogic, Im using t3 client (wlthint3client.jar).
Part of the code of EJB is:
Stateless(name = "myDataEJB", mappedName = "ejb/MyDataEJB",
description = "Get important Data")
#Remote({
MyDataEJB.class,
SecurityContext.class
})
#RolesAllowed({
"MyRole"
})
#TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class MyDataEJBEJBImpl extends TheBaseSpringSecurityEJB implements MyDataEJBEJB {
//some stuff
And my code from Liferay is the next:
Properties p = new Properties();
p.put(Context.PROVIDER_URL, "t3://someip:someip,anotherip:anotherport");
p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
p.put(Context.SECURITY_PRINCIPAL, "some");
p.put(Context.SECURITY_CREDENTIALS, "somepass");
try {
Context ctx = new InitialContext(p);
MyDataEJB mydataEJB =
(MyDataEJB)ctx.lookup("ejb/MyDataEJB#com.company.proyect.worker.ejb.MyDataEJB");
And I´m getting this:
javax.naming.NameNotFoundException: While trying to lookup 'ejb.MyDataEJB#com.company.proyect.worker.ejb.MyDataEJB' didn't find subcontext 'MyDataEJB#com'. Resolved 'ejb'[Root exception is javax.naming.NameNotFoundException:While trying to lookup 'ejb.MyDataEJB#com.company.proyect.worker.ejb.MyDataEJB' didn't find subcontext 'ejb.MyDataEJB#com.Resolved 'ejb'] remaining name 'ejb.MyDataEJB#com/company/proyect/worker/ejb/MyDataEJB''
Do you have any idea about what's happening?
Is the pattern ejb/MyDataEJB#com.company.proyect.worker.ejb.MyDataEJB for my lookup wrong?
Thank you so much! :)
try to use
MyDataEJB mydataEJB =
(MyDataEJB)ctx.lookup("ejb/MyDataEJB");
because your EJB is mapped by ejb/MyDataEJB in the JNDI.
This started happening recently, but I'm not sure what changed to cause it.
When I run all tests from IntelliJ, all is well. Also the gradle build is fine.
When I run a single unit test, all is well.
When I run a single web integration test, it fails because a config class has all null properties.
The config class looks like (Kotlin):
#Component
#ConfigurationProperties(prefix = "api")
public open class ApiConfigImpl : ApiConfig
{
A test looks like:
#RunWith(SpringJUnit4ClassRunner::class)
#ContextConfiguration(classes = arrayOf(ApplicationAssembly::class), loader = SpringApplicationContextLoader::class)
#WebIntegrationTest
open class CandidateProfileControllerTest
{
#Inject lateinit var profileRepo: CandidateProfileRepository
//etc a few more deps used to setup test data
#Test
open fun getById()
{
val greg = CandidateProfile("123", "12312", "Greg", "Jones", dateOfBirth = Date(), gender = Gender.MALE,
biography = "ABC", maxMatchableAge = null, maxMatchableDistance = null)
profileRepo.save(greg)
val auth = given().header("content-type", "application/json")
.body(testCredentials)
.post("/authorization/social").peek().asString()
val accessToken: String = from(auth).get("accessToken")
given().header("Access-Token", accessToken).
header("API-Key", testAPIKey()).
get("/profile/${greg.id}").
peek().then().
body("stageName", notNullValue())
}
I'm not sure what information I can add. Based on the limited information provided:
Is this a known problem with a known solution?
This is a bug, logged in the IntelliJ/Kotlin tracker, with a pending fix.
I am trying to load entities from several jar files.
What I managed to do is
configure hibernate
private void configure(File[] moduleFiles)
{
Configuration configuration = new Configuration()
.setProperty("hibernate.connection.url", getConnectionString())
.setProperty("hibernate.connection.username", "user")
.setProperty("hibernate.connection.password", "pass")
.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbc.JDBCDriver")
.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
.setProperty("hibernate.archive.autodetection", "class,hbm")
.setProperty("exclude-unlisted-classes", "false")
.setProperty("hibernate.hbm2ddl.auto", "update");
if (moduleFiles != null) {
for (File f : moduleFiles) {
configuration.addJar(f);
}
}
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
this.sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
so the entities should be loaded from moduleFiles array. In logs I can see:
2015-08-25 20:52:12 INFO Configuration:837 - HHH000235: Searching for mapping documents in jar: ProgramInfo.jar
2015-08-25 20:52:12 INFO Configuration:837 - HHH000235: Searching for mapping documents in jar: SampleModule.jar
The entity in external jar
#Entity
#Table(name = "PROGRAMINFO_DATA", schema = "PUBLIC", catalog = "PUBLIC")
#NamedQueries({#NamedQuery(name = "PrograminfoDataEntity.findByWindowInfo", query = "FROM PrograminfoDataEntity WHERE PROCESSPATH = :pp AND WINDOWTITLE = :wt AND DAY = :d")})
public class PrograminfoDataEntity implements SVEntity {
private long id;
private Date day;
private String processname;
private String processpath;
private String programname;
private String windowtitle;
// getters setters etc.
}
persistence.xml in external jar (META-INF directory)
<persistence-unit name="ProgramInfoPersistenceUnit">
<class>com.antara.modules.programinfo.db.model.PrograminfoDataEntity</class>
</persistence-unit>
Query with above entity usage
Session session = openSession();
Query q = session.getNamedQuery("PrograminfoDataEntity.findByWindowInfo");
q.setParameter("pp", windowInfo.getProcessPath());
q.setParameter("wt", windowInfo.getWindowTitle());
q.setDate("d", date);
PrograminfoDataEntity result = (PrograminfoDataEntity) q.uniqueResult();
closeSession(session);
which threw an exception:
org.hibernate.MappingException: Named query not known: PrograminfoDataEntity.findByWindowInfo
at org.hibernate.internal.AbstractSessionImpl.getNamedQuery(AbstractSessionImpl.java:177)
at org.hibernate.internal.SessionImpl.getNamedQuery(SessionImpl.java:1372)
at com.antara.modules.programinfo.db.dao.PrograminfoDao.findByWindowInfo(PrograminfoDao.java:26)
at com.antara.modules.programinfo.ProgramInfoImpl.run(ProgramInfoImpl.java:84)
The question is why hibernate didn't loaded the annotated entity from jar? The exception is thrown not only by named query, but any other operation with entity. There are no errors before usage of this entity. Local entities are loaded properly.
EDIT:
After some changes I managed to recognize entity by Hibernate
DEBUG AnnotationBinder:601 - Binding entity from annotated class: com.antara.modules.programinfo.db.model.PrograminfoDataEntity
DEBUG QueryBinder:93 - Binding named query: PrograminfoDataEntity.findByWindowInfo => FROM PrograminfoDataEntity ....
But when I try to use the entity I still get exception:
ERROR AssertionFailure:61 - HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): java.lang.ClassNotFoundException: com.antara.modules.programinfo.db.model.PrograminfoDataEntity
ERROR Main:114 - PersistentClass name cannot be converted into a Class
...
Caused by: java.lang.ClassNotFoundException: com.antara.modules.programinfo.db.model.PrograminfoDataEntity
The change was: passing Configuration to each "module" that is inside jar and add Annotated Class (by module I mean SPI service with method invoked at startup)
#Override
public void configureDB(Configuration configuration) {
configuration.addAnnotatedClass(PrograminfoDataEntity.class);
}
After 3 days of trials I have found the solution: Hibernate loades classes using reflection mechanism by ContextClassLoader
Thread.currentThread().getContextClassLoader();
so I set ContextClassLoader to ClassLoader of PrograminfoDataEntity
Thread.currentThread().setContextClassLoader(PrograminfoDataEntity.class.getClassLoader());
and it solved all NoClassDefFound, ClassCastException and similar errors
According to javadoc and implementation code Hibernate only read *.hbm.xml at Configuration.addJar method
I guess Hibernate doesn't auto scan jars because of restrictions in JPA Specification
I've done auto scan of jars in hibernate extending the scanner and adding the jars on it. But you should use JPA api to that. Something like:
Map<String, Object> map = new HashMap<>();
map.put("hibernate.connection.url", getConnectionString());
map.put("hibernate.connection.username", "user");
map.put("hibernate.connection.password", "pass");
map.put("hibernate.connection.driver_class", "org.hsqldb.jdbc.JDBCDriver");
map.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
map.put("hibernate.archive.autodetection", "class,hbm");
map.put("exclude-unlisted-classes", "false");
map.put("hibernate.hbm2ddl.auto", "update");
//Property to change scanner
map.put("hibernate.ejb.resource_scanner", "me.janario.MyScanner");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProgramInfoPersistenceUnit", map);
SessionFactory sessionFactory = ((HibernateEntityManagerFactory) emf).getSessionFactory();
And the scanner something like:
public class MyScanner extends StandardScanner {
#Override
public ScanResult scan(PersistenceUnitDescriptor persistenceUnit, ScanOptions scanOptions) {
try {
persistenceUnit.getJarFileUrls()
.add(new URL("file:/path/my.jar"));
return super.scan(persistenceUnit, scanOptions);
} catch (MalformedURLException e) {
throw new IllegalStateException(e);
}
}
}
You are setting up a Hibernate bootstrap process. Here are the docs: https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#bootstrap
There are essentially two routes to go down here. You are doing it the Hibernate-specific way. I prefer the JPA one usually because it's the most automatic and simplistic one: you put a persistence.xml file into a jar and that jar will get scanned for classes with the appropriate Entity annotation. JPA will then inject the entity manager (and factory), which you can then in turn transform into the native Hibernate session using:
Session s = (Session) em.getDelegate();
That in turn, should give you access to non-JPA capabilities if need be.
I want to set LDAP connection to list all users from AD.
I successfully accomplished this with information stored in XML
<ldap:context-source
url="ldap://<url>"
base="dc=example,dc=local"
username="<user>#example.local"
password="<pass>" />
But how I can set this informations from Java, not in XML?
Tried with:
LdapContextSource ctxSrc = new LdapContextSource();
ctxSrc.setUrl("ldap://<url>");
ctxSrc.setBase("dc=example,dc=local");
ctxSrc.setUserDn("<user>#example.local");
ctxSrc.setPassword("<pass>");
LdapTemplate tmpl = new LdapTemplate(ctxSrc);
setLdapTemplate(tmpl);
But when runing
List users = (List<User>) ldapTemplate.search(LdapUtils.emptyLdapName(), "(&(objectCategory=person)(objectClass=user))", new UserAttributesMapper());
I get NullPointerExeption. Runing that without setting up properties from java (i.e. reading from xml) everything works fine
please try this
LdapContextSource ctxSrc = new LdapContextSource();
ctxSrc.setUrl("ldap://<url>");
ctxSrc.setBase("dc=example,dc=local");
ctxSrc.setUserDn("<user>#example.local");
ctxSrc.setPassword("<pass>");
ctxSrc.afterPropertiesSet(); // this method should be called.
LdapTemplate tmpl = new LdapTemplate(ctxSrc);
setLdapTemplate(tmpl);