viernes, 29 de julio de 2011

CREACIÓN Y DESPLIEGUE DE UN PROYECTO EAR, USANDO ECLIPSELINK-JPA

1. Descargar:
Glassfish3.1 o gf3.0.1
Driver de la bd que vayas a usar- postgresql.jar
EclipseLink 2.3.0 Installer Zip (28 MB)
enlace: http://www.eclipse.org/eclipselink/downloads/

2.Crear un proyecto EJB en eclipse

3. Crear en la carpeta META-INF, el archivo persistence.xml.

Persistence.xml

< persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" >
< persistence-unit name="EmployeeService" transaction-type="JTA" >
< jta-data-source >jdbc/example
< class >consultorio.Employee
< properties >
< property name="eclipselink.logging.level" value="FINEST" />
< property name="eclipselink.ddl-generation" value="drop-and-create-tables" />

jdbc/example -> recurso bd sql.datasource en glassfish

4. Crear las entidades con notación @entity, el sessionBean(configurar el persistenceUnit, y el entity Manager), y las interfaces(local y remoto) dentro de un paquete nuevo.

1. Clase Entity JPA
@Entity
//@Table(name="EMP", schema="HR")
@Table(name="EMP")
public class Employee implements Serializable {
@Id
@Column(name = "EMP_ID")
private int id;
@Column(name = "COMM")
private String name;
@Column(name = "SAL")
private long salary;

2. SessionBean

@Stateful (mappedName = "ejb/EmployeeService")
public class EmployeeService implements EmployeeServiceLocal, EmployeeServiceRemote {
@PersistenceContext(unitName="EmployeeService", type=PersistenceContextType.TRANSACTION)
EntityManager em;
public Employee createEmployee(int id, String name, long salary, byte[] pic) {
Employee emp = new Employee(id);
emp.setName(name);
emp.setSalary(salary);
em.persist(emp);
emp = findEmployee(id);
System.out.println(emp);
em.flush();
return emp;
}

3. Interfaces Remotas y Locales
@Local
public interface EmployeeServiceLocal {
public void doAction();

public Employee createEmployee(int id, String name, long salary, byte[] pic) ;
public void removeEmployee(int id);

@Remote
public interface EmployeeServiceRemote{
public void doAction();
public Employee createEmployee(int id, String name, long salary, byte[] pic) ;
public void removeEmp


5. Exportar el EJB creado en un .ear (Enterprise Archive).

6.Copiar la lib del driver de bd en glassfish/domain/domain1/lib.

7. Copiar las librerias de eclipselink(descomprimir el jar descargado) --> en /glassfish/lib :

- eclipselink.jar q se encuentra en la carpeta /jlib
- y los 3 .jar q se encuentran dentro de la carpeta: jlib/jpa

8. Crear el recurso jdni a BD en glassfish jdbc/example y hacer ping para comprobar conexión.

9. Desplegar en glassfish el .ear obtenido, visualizar las tablas creadas en bd.

10. Hacer el cliente del .ear.(app de escritorio, consola en este ej) este debe contener en el builtpath las siguientes .jar: Por favor leer este link antes de agregar el jar del EJB....LIB CONFIGURACION

- jar del Ejb. el cual deberia estar ubicado en /glassfish/domain/domain1/lib

En el cliente se debe realizar la conexión al .ear desplegado en glassfish mediante el jdni, IIOP, o en el caso de Ejb3:

El cliente deberia ser algo como:

Context ctx;
try {
ctx = new InitialContext();
//debes de mapear la clase de tu EJB de esta forma @Stateless(mappedName ="ejb/EmployeeService ")
service = (EmployeeServiceRemote) ctx.lookup("ejb/EmployeeService");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//usas la interface o instanciar el bean(nombre del persistenceUnit mapped en el sessionbean creado).
service.createEmployee(45, "AAA", 45000, "asdf".getBytes());

Observar la conexión y las filas creadas en bd :D has realizado una applicación JEE6! Congrats

Referencias:


The following are the valid values for the org.eclipse.persistence.config.PersistenceUnitProperties:

  • NONE – see none.
  • CREATE_ONLY – see create-tables.
  • DROP_AND_CREATE – see drop-and-create-tables.

If you are using persistence in a Java SE environment and would like to create the DDL files without creating tables, additionally define a Java system property INTERACT_WITH_DB and set its value to false.


Example: persistence.xml file


©

VAADIN

View and edit HTML5 music visualization live with VJ:

Vaadin Adding background image to HorizontalLayout
https://vaadin.com/es/forum/-/message_boards/view_message/1015174

TRANSACTION LISTENER AND HTTPSERVLETREQUEST




ApplicationContext


EXCELLENT EXAMPLE: http://vaadin.com/directory/help/using-vaadin-add-ons/

REFCARDZ:
http://refcardz.dzone.com/refcardz/getting-started-vaadin

VAADIN AND GRAILS

ADDRESS BOOK-JPA INICIAL
http://vaadin.com/wiki/-/wiki/Main/Adding%20JPA%20to%20the%20Address%20Book%20Demo

JPA-REDUCIDO
http://devblog.mycorner.fi/18/adding-jpa-based-persistence-to-the-address-book-demo/

ABOUT PERSISTENCE
http://code.google.com/p/vaadin-appfoundation/wiki/Persistence

ECLIPSELINK AND VAADIN: http://vaadin.com/forum/-/message_boards/view_message/258818



ERRORES OBTENIDOS

SEVERE: Exception sending context initialized event to listener instance of class YourApplicationContextListener
Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 1.1.4.v20100812-r7860): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'acesso.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [50, SEQ_GEN]
Query: DataModifyQuery(sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:323)


SOLUTION
It looks like your database structure hasn't been correctly set up. In your persistence.xml file, make sure your persistence unit has this line
1
< property name="eclipselink.ddl-generation" value="drop-and-create-tables" />


drop-and-create-tables means that when your facade is registered, the persistence unit will drop all tables from your database and then recreate them. You probably don't want to recreate the database everytime you start the server, so after the first time you can change the property's value to "none".

context application

http://www.javafaq.nu/java-example-code-233.html

IOP00810257 org.omg.corba.marshal vmcid sun minor code 257 completed maybe GLASSFISH

the best solution for this problem is:

TO ADD THE .JAR IN THE BUILTPATH OF YOUR PROJECT, FOR THE DATABASE THAT YOUŔE USING!!

FOR EXAMPLE: postgresql.jar , or ojdbc14.jar :D thatś it!!


the other solution that i found was this:

this comes from GlassFish (version-build would
help). http://netbeans.org/bugzilla/show_bug.cgi?id=91326

Anyway, can you try to increase verbosity level of ACC (find sun-acc.xml under
the $GF_DomainDir/config and change //log-service/@level to eg. WARNING there)?
This could maybe help you to find the problem. Also check whether appclient's
manifest contains correct Main-Class entry.

persistence version 2 JTA

JTA PERSISTENCE.XML

http://www.developer.com/java/ent/building-jpa-2-applications-using-eclipselink-in-java-ee.html


< ?xml version="1.0" encoding="UTF-8"? >
< persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" >

< persistence-unit name="JPATestWebApp" transaction-type="JTA" >
jdbc/jpa2Pool
com.demo.infosys.Student
< /persistence-unit >

< /persistence >


3 Ejemplos JPA :
http://stackoverflow.com/questions/2880209/jpa-findbyexample





E-COMMERCE EXAMPLE JDNI
http://netbeans.org/kb/docs/javaee/ecommerce/entity-session.html


TUTORIAL ECLIPSELINK-JPA
http://content1.clipmarks.com/content/1BED32E2-9963-4909-9DFD-A8D775FAD4D2/#jpaintro

CONFIGURANDO PERSISTENCE GLASSFISH:
http://glassfish.java.net/javaee5/ejb/EJB_FAQ.html#Are_Global_JNDI_names_portable_How_do

Eclipselink- JPA config- postgreSQL
http://stackoverflow.com/questions/5159101/database-settings-in-persistence-xml-not-used
http://wiki.eclipse.org/EclipseLink/Examples/JPA/JPAConfigure
http://wiki.eclipse.org/EclipseLink/UserGuide

derby:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">

org.eclipse.persistence.jpa.PersistenceProvider
my.app.Foo














POSTGRESQL


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">

org.eclipse.persistence.jpa.PersistenceProvider
my.app.Foo










sábado, 23 de julio de 2011

PostgreSQL



http://www.perudeveloper.net/tag/postgresql

http://laboratorio.is.escuelaing.edu.co/labinfo/doc/Manual_Basico_de_PostgreSQL.pdf

Imposible obtener http://archive.canonical.com/dists/maveric/partner/binary-i386/Packages.gz 404 Not Found

Este error es causado a que no has configurado tu archivo

/etc/apt/sources.list.d/java.list !!!

Debes copiar la linea completa en tu terminal:

echo deb http://archive.canonical.com maverick partner | sudo tee /etc/apt/sources.list.d/java.list <-- 1 sola linea!!

y luego si:

sudo apt-get update
sudo apt-get install sun-java6-jdk

Copiar o hacer backup en postgresql de una base de datos

Copiar o hacer backup en postgresql de una base de datos: "Copiar o hacer backup en postgresql de una base de datos

Despu�s de mucho tiempo sin actualizar el blog, vuelvo a hacerlo con un peque�o truco para administrar una base de datos en postgresql.

Para copiar los datos y el esquema de una base de datos en postgresql podemos utilizar el siguiente comando:

pg_dump -c NOMBRE_DE_LA_BD > ARCHIVO.sql


Si posteriormente queremos introducir estos datos en la base de datos podemos utilizar este comando:

cat ARCHIVO.sql | psql NOMBRE_DE_LA_BD"

VirtualBox Backup Copy

http://www.my-guides.net/en/guides/general-software/155-how-to-copy-and-transfer-or-backup-a-virtualbox-virtual-machine-vdi

Liferay

API: http://docs.liferay.com/portal/6.0/javadocs/

Liferay supports 5 different types of plugins out-of-the-box. They are:

Portlets
Themes
Layout
Templates
Webs
Hooks

REGISTRAR VARIOS USUARIOS -HOOK
http://www.apuntesdejava.com/2010/09/liferay-registrando-varios-usuarios.html

LIFERAY Y VAADIN MULTIPLE SESSIONS
https://vaadin.com/forum/-/message_boards/view_message/943637

SESSION SHARING
http://longgoldenears.blogspot.com/2008/03/liferay-session-sharing-demystified.html

http://www.liferay.com/es/community/wiki/-/wiki/Main/Session+Sharing

¿Qué es Liferay Sync?

Liferay Sync es una herramienta diseñada para Liferay Portal 6.1 CE y EE que permite a sus usuarios publicar y acceder a documentos y archivos desde diferentes dispositivos, incluyendo entornos de escritorio Windows y Mac OS, y plataformas móviles basadas en iOS. Cuando un usuario añade o modifica un documento, Liferay Sync es capaz de sincronizar ese archivo con otros dispositivos que trabajen en las diferentes plataformas soportadas, posibilitando su visualización o su modificación desde esos entornos de forma nativa. Liferay Sync se integra totalmente con Liferay Portal, lo que permite aprovechar sus características avanzadas de autenticación, control de versiones, flujo de aprobaciones y herramientas de colaboración social desde cada uno de los entornos soportados. Liferay Sync ofrece la posibilidad de acceder a documentos aún estando sin conexión, encargándose de su sincronización automática una vez la conexión ha sido reestablecida.



EJB APPLICATION

http://somosunosbarbaros.blogspot.com/2009/10/acceder-desde-una-aplicacion-swing-ejb3.html

Web Services
http://www.liferay.com/es/community/wiki/-/wiki/Main/Web+Service+samples

CAS
http://translate.google.com.co/translate?hl=es&langpair=en%7Ces&u=http://blog.csdn.net/dl88250/article/details/2794943

Integración BD con excel

There is no API available. But you can do it via coding. You just have to create a small portlet which reads rows of sheet in which details are there and insert using Liferay's API. The API method is UserLocalServiceUtil.addUser( )

For reading the excel sheet you can make use of POI or JExcel.

Inserción de datos por medio del API

Since, you are fetching data from an external system, you can use Liferay API to create users.
This way, you will not be required to write SQL statements, no password security concern and no need to know what all tables are involved.

UserLocalServiceUtil.addUser() -- takes in individual parameters, a very long list
UserLocalServiceUtil.addUser() -- takes in User object

UserService servicio = UserServiceUtil.getService ();
service.getUserById (identificador de usuario);

If you look at the database table users_ or at service.xml file, you can find which fields are unique. Off the top of my head, userId, screen name and email address are unique.

Have you looked at the methods in UserLocalServiceUtil?
Check if a method is returning a User object or a List. It seems it's companyId + screenName that's unique.
(companyId can be thought of as Liferay instance.)

e.g.
public static com.liferay.portal.model.User getUserByContactId(
long contactId)

public static com.liferay.portal.model.User getUserByEmailAddress(
long companyId, java.lang.String emailAddress)

public static com.liferay.portal.model.User getUserByFacebookId(
long companyId, long facebookId)

public static com.liferay.portal.model.User getUserById(long companyId,
long userId)

public static com.liferay.portal.model.User getUserByScreenName(
long companyId, java.lang.String screenName)

UserLocalServiceUtil.search(companyId, firstName, middleName, lastName, screenName, emailAddress, active, params, andSearch, start, end, sort)

UserLocalServiceUtil.searchCount(companyId, firstName, middleName, lastName, screenName, emailAddress, active, params, andSearch)

I thought that the search or the searchCount methods would give me results which would help me identify whether the user I am going to insert exists already in Liferay database or not.

-----------------------------------------------------------------------

You don't need a DynamicQuery. These are the methods you are looking for in the classes that Dirk points out:

long[] UserServiceUtil.getRoleUserIds(long roleId)

or

long[] UserLocalServiceUtil.getRoleUserIds(long roleId)
List<User> UserLocalServiceUtil.getRoleUsers(long roleId)

Remember that the methods in the classes XXXLocalServiceUtil are not checking the permissions of the current user.

EDIT: If you are looking for all users with a given role within a given community:

long companyId= _X_; //Perhaps CompanyThreadLocal.getCompanyId() if you don't have it anywhere else?
Role role=RoleLocalServiceUtil.getRole(companyId, "Example Role");
Group group=GroupLocalServiceUtil.getGroup(companyId, "Example Community");
List<UserGroupRole> userGroupRoles = UserGroupRoleLocalServiceUtil.
getUserGroupRolesByGroupAndRole
(groupId, role.getRoleId());
for(UserGroupRole userGroupRole:userGroupRoles){
User oneUser=userGroupRole.getUser();
}





Inserción de datos por medio de Web Services

You can use Liferay's web services to insert users. This approach has been taken by many users.

Please see the Liferay Portal Administrator's Guide, pp 244-247 for instructions on accessing Liferay's web services. You can generate a client from the WSDL very easily using any modern IDE (I've done it on both Eclipse and NetBeans) or Apache's wsdl2java utility. From there, just call the web service via a batch process whenever you want to insert a user.


Referencias
http://www.liferay.com/es/community/forums/-/message_boards/message/2625709
http://www.liferay.com/es/web/francisco.fernandez/blog