java.lang.IllegalStateException while configuring custom attribute serializer in titan graph - illegalstateexception

I am trying to write a custom java.util.Date serializer for titan graph. Here is my titan configuration file:
attributes.allow-all = true
attributes.custom.attribute1.attribute-class = java.util.Date
attributes.custom.attribute1.serializer-class = com.serializer.MyDateSerializer
And My serializer looks like :
public class MyDateSerializer implements AttributeSerializer<Date> {
#Override
public void verifyAttribute(Date value) {
// TODO Auto-generated method stub
}
#Override
public Date convert(Object value) {
// TODO Auto-generated method stub
return null;
}
#Override
public Date read(ScanBuffer buffer) {
// TODO Auto-generated method stub
}
#Override
public void write(WriteBuffer buffer, Date date) {
// TODO Auto-generated method stub
}
}
But after opening the TitanGraph , I am getting the following exception:
java.lang.IllegalStateException: Need to set configuration value: root.attributes.custom.serializer-class
at com.google.common.base.Preconditions.checkState(Preconditions.java:177)
at com.thinkaurelius.titan.diskstorage.configuration.ConfigOption.get(ConfigOption.java:158)
at com.thinkaurelius.titan.diskstorage.configuration.BasicConfiguration.get(BasicConfiguration.java:56)
at com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration.<init>(GraphDatabaseConfiguration.java:1334)
at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:91)
at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:71)
Here is how I am trying to read the configuration from the property file :
BaseConfiguration configuration = new BaseConfiguration();
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream(
"/titanConfiguration.properties"));
Set<Entry<Object, Object>> entrySet = properties.entrySet();
for (Entry<Object, Object> entry : entrySet) {
configuration.setProperty(entry.getKey().toString(), entry
.getValue().toString());
}
I have gone through the titan graph documentation for the version 0.5.2, but Iam not able to figure out the problem. I have gone through similar posts also, but still I am not able to resolve this. Has anybody faced this problem before?
If I try to persist the java.util.Date inside titan vertex as follows :
vertex.setProperty("myDate",new Date());
And then when I try to retrieve the Date from vertex as :
((Date)vertex.getProperty("myDate"));
I get the following exception :
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
at org.rampal.Transaction.getUsers(Transaction.java:179)
at org.rampal.Controller.getUsers(Controller.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)

You're not going to be able to override the date handling as there is already a default handler included with titan.
Using your instructions and Titan 0.5.2 you get:
java.lang.IllegalArgumentException: DataType has already been registered: class java.util.Date
The error message you got is cryptic and doesn't happen for me unless I specify a custom attribute that doesn't start at the number 1. For instance:
attributes.allow-all = true
attributes.custom.attribute10.attribute-class = java.util.Date
attributes.custom.attribute10.serializer-class = com.serializer.MyDateSerializer
Will cause:
java.lang.IllegalStateException: Need to set configuration value: root.attributes.custom.serializer-class

Related

Using JavaConfig stepScope() in Groovy causes NullPointerException

After finding an accepted answer from a Spring Batch dev here, as well as the accompanying JavaConfig code below that, I am still left a bit confused as to how to use stepScope(). I am trying to scope the multiResourceItemReader below, but simply adding the bean definition of stepScope() to the top or bottom of the file causes this error:
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'readFiles' defined in class path resource [com/onlinephotosubmission/csvImporter/service/BatchJobService.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [java.lang.Object]: Factory method 'readFiles' threw exception;
nested exception is java.lang.NullPointerException:
Cannot invoke method get() on null object
All I know is that stepScope() has to be in a #Configuration file, other than that, I'm thoroughly confused as to what needs to be done.
BatchJobService.groovy
#Configuration
#EnableBatchProcessing
class BatchJobService {
#Autowired
JobBuilderFactory jobBuilderFactory
#Autowired
StepBuilderFactory stepBuilderFactory
#Autowired
JobLauncher jobLauncher
#Autowired
AfterJobListener afterJobListener
// Set values from properties file
#Value('${input.directory:file:inputs/*.csv}')
Resource[] resources
#Value('${report.directory:output}')
String reportsDir
#Value('${completed.directory:completed}')
String completedDir
#Value('${report.name.prepend:people}')
String prependName
#Value('${timestamp.format:dd_MM_yyyy_HH_mm_ss}')
String timestampFormat
// End set properties
#Bean
StepScope stepScope() {
final StepScope stepScope = new StepScope()
stepScope.setAutoProxy(true)
return stepScope
}
#Bean
Job readFiles() {
return jobBuilderFactory
.get("readFiles")
.incrementer(new RunIdIncrementer())
.flow(step1())
.end()
.listener(afterJobListener)
.build()
}
#Bean
Step step1() {
return stepBuilderFactory
.get("step1")
//NOTE: may need to adjust chunk size larger (say 1000 to take all transacions at once)
// or smaller (say 1 to take each transaction individually).
// Bigger is usually better, though.
.<Person, Person>chunk(1000)
.reader(multiResourceItemReader())
.processor(modifier())
.writer(writer())
.build()
}
#Bean
MultiResourceItemReader<Person> multiResourceItemReader() {
MultiResourceItemReader<Person> resourceItemReader = new MultiResourceItemReader<Person>()
resourceItemReader.setResources(resources)
resourceItemReader.setDelegate(reader())
return resourceItemReader
}
#Bean
FlatFileItemReader<Person> reader() {
FlatFileItemReader<Person> reader = new FlatFileItemReader<Person>()
reader.setLinesToSkip(1) //skips header line
reader.setLineMapper(new DefaultLineMapper()
{{
setLineTokenizer(new DelimitedLineTokenizer(",")
{{
setNames(["email", "identifier"] as String[])
}})
setFieldSetMapper(new BeanWrapperFieldSetMapper<Person>() // BeanWrapperFieldSetMapper maps the line token values to a POJO directly by name
{{
setTargetType(Person.class)
}})
}})
return reader
}
#Bean
PersonItemProcessor modifier(){
return new PersonItemProcessor()
}
#Bean
FlatFileItemWriter<Person> writer() {
FlatFileItemWriter<Person> writer = new FlatFileItemWriter<>()
writer.setAppendAllowed(true)
writer.setResource(new FileSystemResource(reportsDir + "/" + prependName + getTime() + ".csv"))
writer.setLineAggregator(new DelimitedLineAggregator<Person>()
{{
setDelimiter(",")
setFieldExtractor(new BeanWrapperFieldExtractor<Person>()
{{
setNames(["status", "email", "identifier"] as String[])
}})
}})
return writer
}
}
The #EnableBatchProcessing automatically imports the StepScope, so you don't need to declare it as a bean in your application context. The issue you are linking to happens when there is a mix between XML and Java Config. In your case here, I see only Java Config so the issue should not happen.
I am trying to scope the multiResourceItemReader below
All I know is that stepScope() has to be in a #Configuration file, other than that, I'm thoroughly confused as to what needs to be done.
Just declaring the step scope is not enough, you need to add the #StepScope annotation on the bean definition.
You can find more details about the StepScope in the reference documentation here: https://docs.spring.io/spring-batch/4.0.x/reference/html/step.html#step-scope

JSF with custom Annotation

I am using primefaces version 5 and I am adding messages regarding to a specific actions like save :
public void save(Tenant tenant) {
tenantDao.save(tenant);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Save success"));
}
Since I had a lot of these actions I tried to simplify this by creating a custom annotation called Message:
#Target(Runtime)
#Retention(Method)
public #interface Message {
String value();
}
and in my dao class :
public class TenantDao {
#Message("Saved Successfully")
public Tenant save(Tenant t) {
return em.save(t);
}
}
To read this annotation I have overridden the ELResolver the method invoke
public Object invoke(ELContext context,
Object base,
Object method,
Class<?>[] paramTypes,
Object[] params) {
Object result = super.invoke(context,method,paramTypes,params);
Method m = base.getClass().getMethod(method,paramTypes);
if(m.getAnnotation(Message.class) != null) {
addMessahe(m.getAnnotation(Message.class).value());
}
return result;
}
This was called in property (rendered, update, ..) but not in action listener
After a lot of debugging I discovered that theactionListener is called from MethodExpression class. So, I wrapped the MethodExpression class, and override the method invoke.
The problem now is that there are no way to retreive the class Method from MethodExpression class, also if I used the expression #{tenantDao.save(tenant)} the method getMethodInfo from MethodExpression will throw an exception.
Are there any way to read tAnnotation from any jsf context ?
I know that using Spring with AOP may solve this but I am not using Spring now.
Thanks

PersistenceContextType.EXTENDED leads to failed lookup of Session Bean

I am upgrading from JBoss 7.1.1 to WildFly 8.1.0 and can't get rid of the error described below:
14:53:04,666 ERROR [org.jboss.as.ejb3.invocation] (default task-17) JBAS014134: EJB Invocation failed on component TransRbDAO for method public java.util.List de.bss.dm.kairos.db.kairosgui.TransRbDAO.findAll(): javax.ejb.EJBException: java.lang.IllegalStateException: JBAS011048: Failed to construct component instance
TransRbDAO is:
#Stateless
public class TransRbDAO extends AbstractDAO<TransRb> {
public List<TransRb> findAll() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<TransRb> criteria = cb.createQuery(TransRb.class);
Root<TransRb> root = criteria.from(TransRb.class);
criteria.select(root);
return em.createQuery(criteria).getResultList();
}
}
with AbstractDAO like:
public class AbstractDAO<T> {
#Inject
#CsarGuiDBExtended
#PersistenceContext(unitName = "CSAR_GUI", type = PersistenceContextType.EXTENDED)
protected EntityManager em;
public T findById(Class<T> clazz, Object primaryKey) {
T i = em.find(clazz, primaryKey);
return i;
}
}
This construct works when using only #PersistenceContext(unitName = "CSAR_GUI"), except for the expected LazyInitializationException when accessing data on the JSF-page.
The root-cause for error above is:
Caused by: javax.naming.NamingException: JBAS011878: Failed to lookup env/de.bss.dm.kairos.db.kairosgui.AbstractDAO/em [Root exception is java.lang.ArrayIndexOutOfBoundsException]
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:144)
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:81)
Is this a bug in WildFly? Was this working only because of a bug in JBoss? Or am I doing something completely wrong?
Extended persistence context can only be used in stateful session beans.
See EJB 3.2 spec section 11.11.1.1 or this article:
http://docs.jboss.org/ejb3/app-server/tutorial/extended_pc/extended.html
It appears that the failing code was implemented in JBoss 7.2.0. At this time the setting
default-extended-persistence-inheritance was introduced. Along came the Method
static Map<String, ExtendedEntityManager> More ...getCurrentCall() {
ArrayList<Map<String, ExtendedEntityManager>> stack = currentSFSBCallStack();
Map<String, ExtendedEntityManager> result = null;
if (stack != null) {
result = stack.get(stack.size() - 1);
}
return result;
}
stack.get() was throwing the ArrayIndexOutOfBounds-Exception.
When setting default-extended-persistence-inheritance="DEEP" in standalone.xml and marking TransRbDAO #Stateful the error disappears.
I'm not sure whether it was a bug in JBoss 7.1.1 that I used, or if it is a bug since 7.2.0, clarification is appreciated ;)

Store sessionScope java.util.TreeMap variable in a document in xPage

I am working on an application where I am creating a java.util.TreeMap containing data fetched from various other documents of the application and then assigning that treemap to a sessionsScope variable. This is working fine.
Now I want to provide a functionality wherein I need to store this map inside a NotesDocument.
But when I try doing this, I am getting an error.
var doc:NotesDocument = database.createDocument();
doc.replaceItemValue("Form","testForm");
print("json = "+sessionScope.get("Chart_Map"));
doc.replaceItemValue("Calender_Map",sessionScope.get("Chart_Map"));
doc.save();
Exception:
Error while executing JavaScript action expression
Script interpreter error, line=4, col=13: [TypeError] Exception occurred calling method NotesDocument.replaceItemValue(string, java.util.TreeMap) null**
Is it possible to store a java.util.TreeMap in a notesdocument field?
If yes then how to implement that?
If no then why not? has that something to do with serializability?
You can't store Java objects inside Document fields unless you use the MimeDomino Document data source
http://www.openntf.org/main.nsf/blog.xsp?permaLink=NHEF-8XLA83
Or even better the new openntf Domino API that has this functionallity built in
http://www.openntf.org/main.nsf/project.xsp?r=project/OpenNTF%20Domino%20API
using MimeStorage
Fredrik is right, the MimeDomino makes most sense. If you are not ready and your field isn't too big for a normal Notes item, you could use CustomDataBytes as Sven suggested - or you use JSON by subclassing TreeMap. It could look like this:
import java.util.TreeMap;
import java.util.Vector;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import lotus.domino.Item;
import lotus.domino.NotesException;
public class TreeMapItem extends TreeMap<String, String> {
private static final long serialVersionUID = 1L;
public static TreeMapItem load(Item source) throws JsonSyntaxException, NotesException {
Gson g = new Gson();
TreeMapItem result = g.fromJson(source.getText(), TreeMapItem.class);
return result;
}
public void save(Item target) throws NotesException {
Gson g = new Gson();
target.setValueString(g.toJson(this));
}
}
I used Google's Gson, it is quite easy, but you might need to deploy it as plug-in for the Java security to work. There is build in JSON in XPages too - a little more work. An alternate approach would be to use 2 fields in Domino, one to load the keys from and one for the values - it would be in line with Domino practises from classic.
A third approach would be be to store the values separated using a pipe character:
#SuppressWarnings({ "unchecked", "rawtypes" })
public void saveCompact(Item target) throws NotesException {
Vector v = new Vector();
for (Map.Entry<String, String> me : this.entrySet()) {
v.add(me.getKey()+"|"+me.getValue());
}
target.setValues(v);
}
#SuppressWarnings("rawtypes")
public static TreeMapItem loadCompact(Item source) throws NotesException {
TreeMapItem result = new TreeMapItem();
Vector v = source.getValues();
for (Object o : v) {
String[] candidate = o.toString().split("|");
if (candidate.length > 1) {
result.put(candidate[0], candidate[1]);
}
}
return result;
}
Let us know how it works for you

Throwing Custom exception in XMLAdapter

I am using XMLAdapter to marshal and unmarshal Dates. In my unmarshaller I want to check the format being supplied from the REST service. If the format is wrong then I want to throw an exception of my own. However, the expetion is being eaten up and the application moves on. I know the solution lies with ValidationEventHandler but I am not able to figure out how to use it exactly. PLease help with ways to use it. My XMLAdapter code is like this
public class DateFormatAdapter extends XmlAdapter<String, Date> {
#Override
public String marshal(Date arg0) throws Exception {
return arg0.toString();
}
#Override
public Date unmarshal(String arg0) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
df.setLenient(false);
Date startDate = null;
try {
startDate = df.parse(arg0);
df.format(startDate);
} catch (ParseException e) {
// throw custom exception from here
}
return startDate;
}
}
Thats true! If you throw an Exception inside an implementation of XMLAdapter, it will be catched and the service continues. The status of the response wont be set to Status.INTERNAL_SERVER_ERROR or something else. Insted the data isn't mapped and thus the response doesn't contain the desired data. If you want to influence the response code, in case that the data format doesn't match, you have to throw the exception within the data entity itself. In your case you have to create a CustomDate class which extends Date and then call from the constructor a validation method. Furthermore an apdapter class isn't considered to do data validation, hence the approach with the custom date class and an optional validation proxy is much more convenient.

Resources