liferay 6.0.6 how to use DynamicQuery for class com.liferay.portal.model.User - liferay-6

I'm deploying a portlet on liferay portal 6.0.6. I used DynamicQuery to access to com.liferay.portal.model.User object.
My code:
DynamicQuery userQuery = DynamicQueryFactoryUtil.forClass(User.class, PortletClassLoaderUtil.getClassLoader());
userQuery.add(RestrictionsFactoryUtil.ilike("screenName","%"+query+"%"));
try {
users = UserLocalServiceUtil.dynamicQuery(userQuery);
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And it throwed:
09:47:02,332 ERROR [DynamicQueryFactoryImpl:83] Unable find model com.liferay.portal.model.impl.UserImpl
java.lang.ClassNotFoundException: com.liferay.portal.model.impl.UserImpl
Please point me on how to resolve this problem.
Thanks!

Use PortalClassLoaderUtil instead of PortletClassLoaderUtil because User class belongs to liferay OOTB.

Related

iText Receiving Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor

Im stumped.Im trying to add an immage watermark in iText
I have received the above titled message when entering
Image watermark_image = Image.getInstance("c:/images/MyImage.png");
I have no idea how to define an explicit constructor in iText?
Im using the iTextg 5.5.9 jar file.
Any help is MOST appreciated.
Thank You
This is a general java error, not iText related.
You have two options.
Catch the exception
Image watermark_image = null;
try {
watermark_image = Image.getInstance("c:/images/MyImage.png");
} catch (IOException e) {
e.printStackTrace();
}
Or add a throws clause to your method definition:
public void getImageInstance() throws IOException {
watermark_image = Image.getInstance("c:/images/MyImage.png");
}

Finding What the Android Facebook SDK Version Is

How do I find out the version of the current SDK is installed or referenced by my application? I have looked through the class files and the manifest but there is no reference as to what version it is.
Thanks in advance.
You have FacebookSdkVersion class with the current version: https://github.com/facebook/facebook-android-sdk/blob/master/facebook/src/com/facebook/FacebookSdkVersion.java
final class FacebookSdkVersion {
public static final String BUILD = "3.5.2";
public static final String MIGRATION_BUNDLE = "fbsdk:20130708";
}
Since this class is without modifier and you can't access it from your package, use a reflection.
This will return you the sdk version:
private String getFacebookSDKVersion()
{
String sdkVersion = null;
ClassLoader classLoader = getClass().getClassLoader();
Class<?> cls;
try
{
cls = classLoader.loadClass("com.facebook.FacebookSdkVersion");
Field field = cls.getField("BUILD");
sdkVersion = String.valueOf(field.get(null));
}
catch (ClassNotFoundException e)
{
// error
}
catch (NoSuchFieldException e)
{
// error
}
catch (IllegalArgumentException e)
{
// error
}
catch (IllegalAccessException e)
{
// error
}
return sdkVersion;
}
The most easy way:
1.- Go to your AndroidManifest.xml
2.- Look at your Bottom Navigation View, there is two tabs: Text and Merged Manifest, click on the last one.
3.- On the right side will appear the Manifest Sources, there it is: for example i have this: facebook-android-sdk:4.20.0 manifest.
I know its a bit old, but i searched this in march of 2017 and there is no an easy answer like this.
There is a public API:
import com.facebook.Settings;
Settings.getSdkVersion()
"Gets the current version of the Facebook SDK for Android as a string."
I don't recommend using reflection to access the package class - they may change that in the future and break your code, but this public API should be considered stable.
Late to answer but I found one more class while trying #sromku's answer.
There is one class called FacebookSdk: import com.facebook.FacebookSdk;
It exposes 2 useful methods which we can try:
getGraphApiVersion()
getSdkVersion()

Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event: 'prePersist'

I created an EJB Session facade in my Netbeans 7 for saving my entity.
I have a manytoone mapping between my Insurance and RatePlan Class.
public class Insurance{
#ManyToOne(optional=false)
#JoinColumn(name="PLAN_ID")
private RatePlan plan;
}
public class RatePlan{
#OneToMany(mappedBy="plan")
private Set<Insurance> insuranceItems;
}
When I tried saving in my database using my EJB Session Bean, I am encountering below error.
Caused by: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
What I did was to turn off my Bean validation in my Persistence.xml file.
I would like to know what Bean validation error has occurred but I dont know how or where to find it or how to configure and catch it.
My EJB facade is a simple class like tis.
public class InsuranceFacade{
public void saveInsurance(Insurance insurance){
em.persist(insurance);
}
}
Any hints?
I would like to know what Bean validation error has occurred but I dont know how or where to find it or how to configure and catch it.
To know what specific constraint violations have occurred, you could just inspect the exception caught. ConstraintViolationException.getConstraintViolations() returns a Set of ConstraintViolations which you can iterate and inspect.
I got the same problem, but after hours looking for the answer, Finally I Found it.... You should edit your AbstractFacade.java class and add this code
public void create(T entity) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);
if(constraintViolations.size() > 0){
Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
while(iterator.hasNext()){
ConstraintViolation<T> cv = iterator.next();
System.err.println(cv.getRootBeanClass().getName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
JsfUtil.addErrorMessage(cv.getRootBeanClass().getSimpleName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
}
}else{
getEntityManager().persist(entity);
}
}
Now this method will alert you which property and why it fails the validation.
I hope this works for you, as it does for me.
catch (EJBException e) {
#SuppressWarnings("ThrowableResultIgnored")
Exception cause = e.getCausedByException();
if (cause instanceof ConstraintViolationException) {
#SuppressWarnings("ThrowableResultIgnored")
ConstraintViolationException cve = (ConstraintViolationException) e.getCausedByException();
for (Iterator<ConstraintViolation<?>> it = cve.getConstraintViolations().iterator(); it.hasNext();) {
ConstraintViolation<? extends Object> v = it.next();
System.err.println(v);
System.err.println("==>>"+v.getMessage());
}
}
Assert.fail("ejb exception");
}
Catch the following exception where you persisting the entity. In my case its in the EJB add method. where I am doing em.persist(). Then check the server log, you will see which attribute having constrain violation.
catch (ConstraintViolationException e) {
log.log(Level.SEVERE,"Exception: ");
e.getConstraintViolations().forEach(err->log.log(Level.SEVERE,err.toString()));
}

How do I catch the constraint violation exception from EclipseLink?

I am using EclipseLink in my web application, and I am having a hard time gracefully catching and handling Exceptions it generates. I see from this thread what seems to be a similar problem, but I don't see how to work around or fix it.
My code looks like this:
public void persist(Category category) {
try {
utx.begin();
em.persist(category);
utx.commit();
} catch (RollbackException ex) {
// Log something
} catch (HeuristicMixedException ex) {
// Log something
} catch (HeuristicRollbackException ex) {
// Log something
} catch (SecurityException ex) {
// Log something
} catch (IllegalStateException ex) {
// Log something
} catch (NotSupportedException ex) {
// Log something
} catch (SystemException ex) {
// Log something
}
}
When persist() is called with an entity that violates a uniqueness constraint, I get an explosion of exceptions that are caught and logged by the container.
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504):
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: The statement
was aborted because it would have caused a duplicate key value in a unique or
primary key constraint or unique index identified by 'SQL110911125638570'
defined on 'CATEGORY'.
Error Code: -1
(etc)
I have tried the following:
try {
cc.persist(newCategory);
} catch (PersistenceException eee) {
// Never gets here
System.out.println("MaintCategory.doNewCateogry(): caught: " + eee);
} catch (DatabaseException dbe) {
// Never gets here neither
System.out.println("MaintCategory.doNewCateogry(): caught: " + dbe);
}
I realize that using DataBaseException is not portable, but I need to start somewhere. The exceptions never get caught. Any suggestions?
It looks like I won't get any more activity on this question, so I will post my work-around and leave it at that. A number of web searches haven't found much of anything that is helpful. I would have thought this is a textbook case but none of the tutorials I have found covers it.
As it turns out in this condition with EclipseLink, the Exception you can catch when the SQL constraint is violated is the RollBackException that is the result of the em.commit() call. So I have modified my persist method like this:
public void persist(Category category) throws EntityExistsException {
try {
utx.begin();
em.persist(category);
utx.commit();
} catch (RollbackException ex) {
Logger.getLogger(CategoryControl.class.getName()).log(Level.SEVERE, null, ex);
throw new EntityExistsException(ex);
} catch (HeuristicMixedException ex) {
Logger.getLogger(CategoryControl.class.getName()).log(Level.SEVERE, null, ex);
} catch (HeuristicRollbackException ex) {
Logger.getLogger(CategoryControl.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(CategoryControl.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalStateException ex) {
Logger.getLogger(CategoryControl.class.getName()).log(Level.SEVERE, null, ex);
} catch (NotSupportedException ex) {
Logger.getLogger(CategoryControl.class.getName()).log(Level.SEVERE, null, ex);
} catch (SystemException ex) {
Logger.getLogger(CategoryControl.class.getName()).log(Level.SEVERE, null, ex);
}
}
So the caller catches the EntityExistsException and takes the appropriate action. The log still fills up with the internal exceptions but that can be shut off later.
I realize that this is a bit of an abuse of the intent of the EntityExistsException that is normally only used when an entity ID field is re-used, but for the purposes of the user application it doesn't matter.
If anyone has a better approach please post a new answer or comment.
Edit your persistence.xml adding the following property:
property name="eclipselink.exception-handler" value="your.own.package.path.YourOwnExceptionHandler"
Now create the class YourOwnExceptionHandler (on the correct package). It requires to implement org.eclipse.persistence.exceptions.ExceptionHandler.
Create a non argument constructor and the required method handleException(...).
Inside this method, you can catch the exceptions!
EclipseLink should only be throwing either a PersitenceException or a RollbackException depending on the environment and the order of operations you are calling on the EntityManager.
What is your logging level? It is likely that you are seeing these exceptions logged by EclipseLink but only thrown as causes of the RollbackException.
You can turn off exception logging with the PU property but for diagnostic purposes it is generally better to allow EclipseLink to log the exceptions.
2019-12-18
As its a very well viewed question and I just had a very similar issue with EclipseLink, in a Maven multi module web application running on Weblogic 12c server and using JTA, I am going to post my solution here, hoping to save a couple hours for someone.
In the persistence.xml we are having:
< property name="eclipselink.persistence-context.flush-mode"
value="commit" />
The REST resource class was marked with #Transactional, meaning that the transaction starts at the point when the request has been received by the related method of the resource class, and it ends when this method returns.
JTA used for managing the transactions.
Now, JTA commit time happens to occur AFTER the resource class's method returns (with a response to the REST client).
Which subsequently means that:
Even though you had a very proper setup to catch the Exception, you
cannot, as exceptions like SQLIntegrityConstraintViolationException
occur only AFTER your INSERT/UPDATE/DELETE query
--that has been sitting all this time in your JPA provider cache--,
now finally sent to the database.
Which happens just after the resource class's method returns, and at that point, all the exceptions has been skipped already.
Since no query sent == no exception occured at the time when the execution ran through the try{...}catch(Exception e){...} lines, you were not able to catch it,
but at the end, you will see the exception in the server's log.
Solution:
I had to manually call flush() on EntityManager to force flush and the exception to occur at the proper time and line (basically in the try block) to be able to catch it, handle it, and allow my REST method to return with my intended response.
The final caught exception in the log (I have masked some not related info):
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - x.x.x.v00000000-0000000): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (XXXXX.UNIQUE_KEY_NAME) violated
Related pseudo code:
try {
repository.update(entity);
repository.getEntityManager().flush();
} catch (Exception e ) {
log.info(e.toString());
...
}
I'm using Spring Boot 1.1.9 + EclipseLink 2.5.2. This is the only way I can catch ConstraintViolationException. Note that my handleError(ConstraintViolationException) is a very simple implementation which just returns the first violation it finds.
Note that this code was also required when I switched to Hibernate 4.3.7 and Hibernate Validator 5.1.3.
It seems that adding PersistenceExceptionTranslationPostProcessor exceptionTranslation() to my persistence JavaConfig class also has no effect.
import javax.persistence.RollbackException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
#ControllerAdvice
class GlobalExceptionHandler
{
#ExceptionHandler(TransactionSystemException.class)
public ResponseEntity<Object> handleError(final TransactionSystemException tse)
{
if(tse.getCause() != null && tse.getCause() instanceof RollbackException)
{
final RollbackException re = (RollbackException) tse.getCause();
if(re.getCause() != null && re.getCause() instanceof ConstraintViolationException)
{
return handleError((ConstraintViolationException) re.getCause());
}
}
throw tse;
}
#ExceptionHandler(ConstraintViolationException.class)
#SuppressWarnings("unused")
public ResponseEntity<Object> handleError(final ConstraintViolationException cve)
{
for(final ConstraintViolation<?> v : cve.getConstraintViolations())
{
return new ResponseEntity<Object>(new Object()
{
public String getErrorCode()
{
return "VALIDATION_ERROR";
}
public String getMessage()
{
return v.getMessage();
}
}, HttpStatus.BAD_REQUEST);
}
throw cve;
}
}
I use this.
if (!ejbGuardia.findByPkCompuestaSiExiste(bean.getSipreTmpGuardiaPK())) {
ejbGuardia.persist(bean);
showMessage(ConstantesUtil.MENSAJE_RESPUESTA_CORRECTA, SEVERITY_INFO);
} else {
showMessage("Excel : El registro ya existe. (" + bean.toString() + ") ", SEVERITY_ERROR);
}
and my function from above:
public boolean findByPkCompuestaSiExiste(Object clasePkHija) throws ClassNotFoundException {
if (null != em.find(this.clazz, clasePkHija)) {
return true;
}
return false;
}
With that I dont need to program a validation for each Persist, its common in the my DAO Classes.

gwt-rpc + appengine + persistence using restlet throws exception

I was trying to rebuild the Restlet sample Application for GWT + GAE ( http://wiki.restlet.org/docs_2.1/13-restlet/21-restlet/318-restlet/303-restlet.html ) .
I changed it a bit, since I am planning something diffrent but I thought it would be a good start.
It was going okish until now. The "Put" was coming through to app engine but when i tried to persist the Objects using JPA i get the following Exception:
Caused by: org.datanucleus.exceptions.ClassNotResolvedException: Class "de.fr1zle.shoplist.web.gae.client.ShoppingListRessourceProxy" was not found in the CLASSPATH. Please check your specification and your CLASSPATH.
at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:250)
at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:415)
at org.datanucleus.metadata.MetaDataManager.loadPersistenceUnit(MetaDataManager.java:767)
... 79 more
As you can see, datanucleus somehow tries to access the GWT Proxy class when loading the info from the persistence.xml.
I use the following in my ServerRessource:
#Put
public void putShoppingList(ShoppingList shoppingList) {
ShoppingListDOA shoppingListDOA = new ShoppingListDOA(shoppingList);
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("transactions-optional");
try {
EntityManager entityManager = emf.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(shoppingListDOA);
entityManager.flush();
transaction.commit();
entityManager.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (emf != null)
emf.close();
}
}
I somehow have the feeling that DataNucleus enhances the Proxy Class, too although I changed the properites for it to not do so.
Using: GAE 1.4.2 (tried 1.4.3, too) , GWT 2.2 and Restlet 2.1m3
Am I missing a point here? Your help is appricated :-)
Thanks in advance!
fr1zle