Agregar Hibernate JPA a Base de datos Oracle en proyecto J2EE en Netbeans 7.4

Oracle Thin/XA Driver Configuration Properties

The following table contains sample code for configuring a JDBC data source:

Oracle Thin/XA Driver: Connection Pool Configuration
Property Name
Property Value
Name
oracleXAPool
URL
jdbc:oracle:thin:@serverName:port(typically 1521 on Windows):sid
DriverClassname
oracle.jdbc.xa.client.OracleXADataSource
Database Username
Scott
Properties
user=scott
Test Table Name
DUAL

Teamviewer 8 auto-start en UBUNTU 13.10

Siguiendo con la instalacion el demonio del teamviewer no corre en el inicio, lo que no deja facil monitorear la maquina desde internet que es la gracia de esta aplicacion en una red clase 3 como los ISP.

installing-teamviewer-on-ubuntu-1310

Ejecutar y editar el init:
cd /opt/teamviewer8/tv_bin/script
sudo cp teamviewerd.sysv /etc/init.d/
sudo chmod 755 /etc/init.d/teamviewerd.sysv
sudo update-rc.d teamviewerd.sysv defaults

Ejecutar el servicio al final:
sudo service teamviewerd.sysv start

Weblogic 10.20 en modo Profile con NetBeans

Windows: En mi caso la shell starWeblogic_nbprofiler.cmd queda asi:
@ECHO OFF

@REM WARNING: This file is created by the Configuration Wizard.
@REM Any changes to this script may be lost when adding extensions to this configuration.

SETLOCAL
set DOMAIN_HOME=C:\WL1020\user_projects\domains\entel01
JAVA_OPTIONS=%SAVE_JAVA_OPTIONS%:
set JAVA_VENDOR=Sun
set JAVA_HOME=C:\WL1020\jdk150_11
set JAVA_OPTIONS=-agentpath:%PROFILER_LIBS%\deployed\jdk15\windows\profilerinterface.dll=%PROFILER_LIBS%,%AGENT_PORT% %JAVA_OPTIONS%
call "%DOMAIN_HOME%\bin\startWebLogic.cmd" %*



ENDLOCAL
La Shell de setDomainEnv_nbprofiler.cmd:
@ECHO OFF

@REM WARNING: This file is created by the Configuration Wizard.
@REM Any changes to this script may be lost when adding extensions to this configuration.

@REM *************************************************************************
@REM This script is used to setup the needed environment to be able to start Weblogic Server in this domain.
@REM 
@REM This script initializes the following variables before calling commEnv to set other variables:
@REM 
@REM WL_HOME         - The BEA home directory of your WebLogic installation.
@REM JAVA_VM         - The desired Java VM to use. You can set this environment variable before calling
@REM                   this script to switch between Sun or BEA or just have the default be set. 
@REM JAVA_HOME       - Location of the version of Java used to start WebLogic
@REM                   Server. Depends directly on which JAVA_VM value is set by default or by the environment.
@REM USER_MEM_ARGS   - The variable to override the standard memory arguments
@REM                   passed to java.
@REM PRODUCTION_MODE - The variable that determines whether Weblogic Server is started in production mode.
@REM DOMAIN_PRODUCTION_MODE 
@REM                 - The variable that determines whether the workshop related settings like the debugger,
@REM         testconsole or iterativedev should be enabled. ONLY settable using the 
@REM                   command-line parameter named production
@REM                   NOTE: Specifying the production command-line param will force 
@REM                          the server to start in production mode.
@REM 
@REM Other variables used in this script include:
@REM SERVER_NAME     - Name of the weblogic server.
@REM JAVA_OPTIONS    - Java command-line options for running the server. (These
@REM                   will be tagged on to the end of the JAVA_VM and
@REM                   MEM_ARGS)
@REM 
@REM For additional information, refer to the WebLogic Server Administration
@REM Console Online Help(http://e-docs.bea.com/wls/docs100/ConsoleHelp/startstop.html).
@REM *************************************************************************

set WL_HOME=C:\WL1020\wlserver_10.0
for %%i in ("%WL_HOME%") do set WL_HOME=%%~fsi

set BEA_JAVA_HOME=C:\WL1020\jrockit_150_11

set SUN_JAVA_HOME=C:\WL1020\jdk150_11

if "%JAVA_VENDOR%"=="BEA" (
 set JAVA_HOME=%BEA_JAVA_HOME%
) else (
 if "%JAVA_VENDOR%"=="Sun" (
  set JAVA_HOME=%SUN_JAVA_HOME%
 ) else (
  set JAVA_VENDOR=BEA
  set JAVA_HOME=C:\WL1020\jrockit_150_11
 )
)

@REM We need to reset the value of JAVA_HOME to get it shortened AND 
@REM we can not shorten it above because immediate variable expansion will blank it

set JAVA_HOME=%JAVA_HOME%
for %%i in ("%JAVA_HOME%") do set JAVA_HOME=%%~fsi

set SAMPLES_HOME=%WL_HOME%\samples

set DOMAIN_HOME=C:\WL1020\user_projects\domains\entel01
for %%i in ("%DOMAIN_HOME%") do set DOMAIN_HOME=%%~fsi

set LONG_DOMAIN_HOME=C:\WL1020\user_projects\domains\entel01

if "%DEBUG_PORT%"=="" (
 set DEBUG_PORT=8453
)

if "%SERVER_NAME%"=="" (
 set SERVER_NAME=AdminServer
)

set POINTBASE_FLAG=false

set enableHotswapFlag=

set PRODUCTION_MODE=

set doExitFlag=false
set verboseLoggingFlag=false
for %%p in (%*) do call :SET_PARAM %%p
GOTO :CMD_LINE_DONE
 :SET_PARAM
 for %%q in (%1) do set noQuotesParam=%%~q
 if /i "%noQuotesParam%" == "nodebug" (
  set debugFlag=false
  GOTO :EOF
 )
 if /i "%noQuotesParam%" == "production" (
  set DOMAIN_PRODUCTION_MODE=true
  GOTO :EOF
 )
 if /i "%noQuotesParam%" == "notestconsole" (
  set testConsoleFlag=false
  GOTO :EOF
 )
 if /i "%noQuotesParam%" == "noiterativedev" (
  set iterativeDevFlag=false
  GOTO :EOF
 )
 if /i "%noQuotesParam%" == "noLogErrorsToConsole" (
  set logErrorsToConsoleFlag=false
  GOTO :EOF
 )
 if /i "%noQuotesParam%" == "nopointbase" (
  set POINTBASE_FLAG=false
  GOTO :EOF
 )
 if /i "%noQuotesParam%" == "doExit" (
  set doExitFlag=true
  GOTO :EOF
 )
 if /i "%noQuotesParam%" == "noExit" (
  set doExitFlag=false
  GOTO :EOF
 )
 if /i "%noQuotesParam%" == "verbose" (
  set verboseLoggingFlag=true
  GOTO :EOF
 )
 if /i "%noQuotesParam%" == "enableHotswap" (
  set enableHotswapFlag=-javaagent:%WL_HOME%\server\lib\diagnostics-agent.jar
  GOTO :EOF
 ) else (
  set PROXY_SETTINGS=%PROXY_SETTINGS% %1
 )
 GOTO :EOF
:CMD_LINE_DONE


set MEM_DEV_ARGS=

if "%DOMAIN_PRODUCTION_MODE%"=="true" (
 set PRODUCTION_MODE=%DOMAIN_PRODUCTION_MODE%
)

if "%PRODUCTION_MODE%"=="true" (
 set debugFlag=false
 set testConsoleFlag=false
 set iterativeDevFlag=false
)

@REM If you want to override the default Patch Classpath, Library Path and Path for this domain,
@REM Please uncomment the following lines and add a valid value for the environment variables
@REM set PATCH_CLASSPATH=[myPatchClasspath] (windows)
@REM set PATCH_LIBPATH=[myPatchLibpath] (windows)
@REM set PATCH_PATH=[myPatchPath] (windows)
@REM PATCH_CLASSPATH=[myPatchClasspath] (unix)
@REM PATCH_LIBPATH=[myPatchLibpath] (unix)
@REM PATCH_PATH=[myPatchPath] (unix)

call "%WL_HOME%\common\bin\commEnv.cmd"

set WLS_HOME=%WL_HOME%\server

set WLI_HOME=%WL_HOME%\integration

set MEM_ARGS=-Xms256m -Xmx512m

if "%JAVA_VENDOR%"=="Sun" (
 if "%PRODUCTION_MODE%"=="" (
  set MEM_DEV_ARGS=-XX:CompileThreshold=8000 -XX:PermSize=48m 
 )
)

@REM Had to have a separate test here BECAUSE of immediate variable expansion on windows

if "%JAVA_VENDOR%"=="Sun" (
 set MEM_ARGS=%MEM_ARGS% %MEM_DEV_ARGS% -XX:MaxPermSize=128m
)

if "%JAVA_VENDOR%"=="HP" (
 set MEM_ARGS=%MEM_ARGS% -XX:MaxPermSize=128m
)

@REM IF USER_MEM_ARGS the environment variable is set, use it to override ALL MEM_ARGS values

if NOT "%USER_MEM_ARGS%"=="" (
 set MEM_ARGS=%USER_MEM_ARGS%
)

set JAVA_PROPERTIES=-Dplatform.home=%WL_HOME% -Dwls.home=%WLS_HOME% -Dweblogic.home=%WLS_HOME% -Dwli.home=%WLI_HOME%

@REM  To use Java Authorization Contract for Containers (JACC) in this domain, 
@REM  please uncomment the following section. If there are multiple machines in 
@REM  your domain, be sure to edit the setDomainEnv in the associated domain on 
@REM  each machine.
@REM 
@REM -Djava.security.manager
@REM -Djava.security.policy=location of weblogic.policy
@REM -Djavax.security.jacc.policy.provider=weblogic.security.jacc.simpleprovider.SimpleJACCPolicy
@REM -Djavax.security.jacc.PolicyConfigurationFactory.provider=weblogic.security.jacc.simpleprovider.PolicyConfigurationFactoryImpl
@REM -Dweblogic.security.jacc.RoleMapperFactory.provider=weblogic.security.jacc.simpleprovider.RoleMapperFactoryImpl

set JAVA_PROPERTIES=%JAVA_PROPERTIES% %EXTRA_JAVA_PROPERTIES%

set ARDIR=%WL_HOME%\server\lib

pushd %LONG_DOMAIN_HOME%

@REM Clustering support (edit for your cluster!)

if "%ADMIN_URL%"=="" (
 @REM The then part of this block is telling us we are either starting an admin server OR we are non-clustered
 set CLUSTER_PROPERTIES=-Dweblogic.management.discover=true
) else (
 set CLUSTER_PROPERTIES=-Dweblogic.management.discover=false -Dweblogic.management.server=%ADMIN_URL%
)

if NOT "%LOG4J_CONFIG_FILE%"=="" (
 set JAVA_PROPERTIES=%JAVA_PROPERTIES% -Dlog4j.configuration=file:%LOG4J_CONFIG_FILE%
)

set JAVA_PROPERTIES=%JAVA_PROPERTIES% %CLUSTER_PROPERTIES%

@REM Clear the pre_classpath here in case an application template wants to set it before the larger pre_classpath is invoked below

set PRE_CLASSPATH=

set JAVA_DEBUG=

if "%debugFlag%"=="true" (
 set JAVA_DEBUG=-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=%DEBUG_PORT%,server=y,suspend=n -Djava.compiler=NONE
 set JAVA_OPTIONS=%JAVA_OPTIONS% %enableHotswapFlag% -ea -da:com.bea... -da:javelin... -da:weblogic... -ea:com.bea.wli... -ea:com.bea.broker... -ea:com.bea.sbconsole...
) else (
 set JAVA_OPTIONS=%JAVA_OPTIONS% %enableHotswapFlag% -da
)

if NOT exist %JAVA_HOME%\lib (
 echo The JRE was not found in directory %JAVA_HOME%. ^(JAVA_HOME^)
 echo Please edit your environment and set the JAVA_HOME
 echo variable to point to the root directory of your Java installation.
 popd
 pause
 GOTO :EOF
)

if "%POINTBASE_FLAG%"=="true" (
 set DATABASE_CLASSPATH=%POINTBASE_CLASSPATH%
) else (
 set DATABASE_CLASSPATH=%POINTBASE_CLIENT_CLASSPATH%
)

set POST_CLASSPATH=

set POST_CLASSPATH=%POST_CLASSPATH%;%DATABASE_CLASSPATH%;%ARDIR%\xqrl.jar

@REM PROFILING SUPPORT

set JAVA_PROFILE=

set SERVER_CLASS=weblogic.Server

set JAVA_PROPERTIES=%JAVA_PROPERTIES% %WLP_JAVA_PROPERTIES%

set JAVA_OPTIONS=%JAVA_OPTIONS% %JAVA_PROPERTIES% -Dwlw.iterativeDev=%iterativeDevFlag% -Dwlw.testConsole=%testConsoleFlag% -Dwlw.logErrorsToConsole=%logErrorsToConsoleFlag%

@REM -- Setup properties so that we can save stdout and stderr to files

if NOT "%WLS_STDOUT_LOG%"=="" (
 echo Logging WLS stdout to %WLS_STDOUT_LOG%
 set JAVA_OPTIONS=%JAVA_OPTIONS% -Dweblogic.Stdout=%WLS_STDOUT_LOG%
)

if NOT "%WLS_STDERR_LOG%"=="" (
 echo Logging WLS stderr to %WLS_STDERR_LOG%
 set JAVA_OPTIONS=%JAVA_OPTIONS% -Dweblogic.Stderr=%WLS_STDERR_LOG%
)

@REM ADD EXTENSIONS TO CLASSPATHS

if NOT "%EXT_PRE_CLASSPATH%"=="" (
 set PRE_CLASSPATH=%EXT_PRE_CLASSPATH%;%PRE_CLASSPATH%
)

if NOT "%EXT_POST_CLASSPATH%"=="" (
 set POST_CLASSPATH=%POST_CLASSPATH%;%EXT_POST_CLASSPATH%
)

if NOT "%WEBLOGIC_EXTENSION_DIRS%"=="" (
 set JAVA_OPTIONS=%JAVA_OPTIONS% -Dweblogic.ext.dirs=%WEBLOGIC_EXTENSION_DIRS%
)

set JAVA_OPTIONS=%JAVA_OPTIONS%

@REM SET THE CLASSPATH

set CLASSPATH=%PRE_CLASSPATH%;%WEBLOGIC_CLASSPATH%;%POST_CLASSPATH%;%WLP_POST_CLASSPATH%

set JAVA_VM=%JAVA_VM% %JAVA_DEBUG% %JAVA_PROFILE%

Ejecutar el weblogic en modo profile desde la consola con el script que se modifico "starWeblogic_nbprofiler.cmd": Luego :
 Ir al Netbeans ir adjuntar el Profiler:
 
 Seleccionar el proyecto:
 
 Seleccionar los metodos raiz, pueden ser aplicaciones web o de logica EJB: En el filtro seleccionar si solo se desea inspeccionar las clases propias del proyecto y las librerias. Y finalmente dar Atach:

Installing Teamviewer on Ubuntu 13.10

Al intentar instalar teamviewer en ubuntu 13.10 sale un error de dependencias.
>sudo dpkg -i teamviewer_linux_x64.deb 

Selecting previously unselected package teamviewer.
(Reading database ... 231622 files and directories currently installed.)
Unpacking teamviewer (from teamviewer_linux_x64.deb) ...
dpkg: dependency problems prevent configuration of teamviewer:
 teamviewer depends on lib32asound2; however:
  Package lib32asound2 is not installed.
 teamviewer depends on ia32-libs; however:
  Package ia32-libs is not installed.

dpkg: error processing teamviewer (--install):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 teamviewer
Bajar la version Multiarch: BAJAR
sudo dpkg -i teamviewer_linux.deb 
sudo apt-get install libxtst6
sudo apt-get update && sudo apt-get install -f && sudo apt-get update

Obtener Roles de grupos desde Weblogic.

import javax.security.auth.Subject;
import weblogic.security.Security;
import weblogic.security.principal.WLSGroupImpl;
import weblogic.security.principal.WLSUserImpl;
import java.util.ArrayList;
import java.util.Set;

public class SecurityBean {
    public ArrayList roles = new ArrayList();
    public String user = "";
    public Subject subject=null;
    public Set allPrincipals=null;
  public SecurityBean() {
subject = Security.getCurrentSubject();
       allPrincipals = subject.getPrincipals();
        for (Principal principal : allPrincipals) {
            
            if (principal instanceof WLSGroupImpl) {
                
                roles.add(principal.getName());
            }
            if (principal instanceof WLSUserImpl) {
                
                user = principal.getName();
            }
        }
}
}

Configurar Hibernate 3.0 + Oracle 11g R2 + JTA en Weblogic 11g

El archivo de configuracion de hibernate si es que se trabaja con JTA (transacciones controladas por el servidor de aplicaciones) se debe configurar con un archivo de configuracion XML que describe entre otras cosas la conexion, propiedades especiales de hibernate, por ej: hibernate.cache.provider_class: si se usa el cache de hibernate en el resultado de las querys, en su defecto es como formzar un flush en los insert para que los datos se refresquen hibernate.dialect:en el caso de este ejmplo estamos usando Oracle ; org.hibernate.dialect.Oracle10gDialect hibernate.default_batch_fetch_size: esta variable tiene que ver con la cantidad de colecciones de datos que soporta una query, por defecto es bajo, pero si tenemos querys que devuelven muchos registros hibernate se limita a la capacidad de memoria de java en crear un List, esto se mejora con la creacion de colecciones de datos. Este valor tambien se debe programar dependiendo de la estrategia de obtencion de datos.

 
  

   weblogic.jndi.WLInitialContextFactory
   jdbc/BERRDB
   org.hibernate.transaction.WeblogicTransactionManagerLookup
   
   claroChile
   org.hibernate.dialect.Oracle10gDialect
   
   org.hibernate.cache.NoCacheProvider
                        org.hibernate.cache.NoCacheProvider
                        false
   org.hibernate.transaction.JTATransactionFactory
                       4
                       10
                       
                       
                      
   
   
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
 

Ahora esta configuracion es dependiente de un servidor que esta en una red privada sin acceso a internet por lo que todos los descriptores de XMLS deben estar en el classpath:"classpath://hibernate-configuration-3.0.dtd"

Instalacion de JBOSS 7.0 con Eclipse Parte 3 (Maven + hibernate + JPA+ Spring )

Ahora tenemos configurado el jboss para trabajar con conexiones jta de oracle, ahora creare un proyecto Maven, la gracia de trabajar con maven es agregar las dependencias y librerias de forma semi automatica editando un archivo pom.xml este archivo tiene una estructura que definiendo unos arquetipos maven es capaz de obtener de sus repositorios todas las dependencias de librerias necesaria para formar un proyecto java para utilizando varias tecnologias.

La diferencia de una aplicacion J2EE estandar es que no utiliza Ant para construir el classpath y poder compliar las clases java, por lo que en algunos estandares o empresas no esta bien aceptado este metodo, por lo que eh tenido problemas para armar aplicaciones con Maven, lo cual tuve que volver a armar un proyecto web dinamico y agregando manualmente todos los jar al proyecto.


En la imagen siguiente agregaremos el nombre base de los artefactos a construir:


La estructura inicial del archivo pom.xml sera:

  4.0.0
  Ejemplo
  Ejemplo
  0.0.1-SNAPSHOT
  Ejemplo
  Ejemplo


Agregaremos los tag properties que se utlizan para agregar variables comunes para todos los artefactos que agregaremos:

  4.0.0
  Ejemplo
  Ejemplo
  0.0.1-SNAPSHOT
  Ejemplo
  Ejemplo
   
  
  
  UTF-8
  
  1.0.0.Final
  
  
  4.2.2.Final
  3.0.5.RELEASE
 

Como se ve estamos agregando al repositorio las versiones de Spring y richfaces que utilizaremos al hacer referencia al tag "version" se llamara al properties que contiene este valor. Ahora empezaremos agregar dependencias al archivo:

  
   
   
    org.jboss.bom
    jboss-javaee-6.0-with-tools
    ${javaee6.with.tools.version}
    pom
    import
   
   
   
    org.richfaces
    richfaces-bom
    ${org.richfaces.bom.version}
    pom
    import
   
  
 
Ahora agregaremos las siguiente dependencias: hibernate, junit, spring core, spring data, spring security, etc.
 


  
  
   javax.enterprise
   cdi-api
   provided
  

  
  
   org.jboss.spec.javax.annotation
   jboss-annotations-api_1.1_spec
   provided
  

  
  
   org.jboss.spec.javax.ws.rs
   jboss-jaxrs-api_1.1_spec
   provided
  

  
  
   org.hibernate.javax.persistence
   hibernate-jpa-2.0-api
   provided
  

  
  
   org.jboss.spec.javax.ejb
   jboss-ejb-api_3.1_spec
   provided
  

  
  
  
  
   org.hibernate
   hibernate-validator
   4.2.0.Final
   provided
   
    
     org.slf4j
     slf4j-api
    
   
  

  
  
   org.jboss.spec.javax.faces
   jboss-jsf-api_2.1_spec
   provided
  

  
  
   org.jboss.spec.javax.servlet
   jboss-servlet-api_3.0_spec
   provided
  

  
  
   org.richfaces.core
   richfaces-core-impl
   
    
     guava
     com.google.guava
    
   
  
  
  
   org.richfaces.ui
   richfaces-components-ui
  

  
  
   org.atmosphere
   atmosphere-runtime
   
    
     org.slf4j
     slf4j-api
    
   
  

  

  
  
   org.hibernate
   hibernate-jpamodelgen
   1.2.0.Final
   provided
  

  
  
   org.ocpsoft.rewrite
   rewrite-servlet
  

  
  
   org.ocpsoft.rewrite
   rewrite-integration-cdi
  

  
  
   junit
   junit
   test
  

  
  
  
   org.jboss.arquillian.junit
   arquillian-junit-container
   test
  

  
   org.jboss.arquillian.protocol
   arquillian-protocol-servlet
   test
  

  
   org.springframework
   spring-core
   ${org.springframework.version}
  

  
   org.springframework
   spring-orm
   ${org.springframework.version}
  

  
   org.springframework
   spring-web
   ${org.springframework.version}
  

  
   org.springframework
   spring-expression
   ${org.springframework.version}
  

  
   org.springframework.security
   spring-security-core
   3.1.2.RELEASE
  

  
   org.springframework.security
   spring-security-web
   3.1.2.RELEASE
  

  
   org.springframework.security
   spring-security-config
   3.1.2.RELEASE
  

  
   org.springframework.security
   spring-security-ldap
   3.1.2.RELEASE
  

  
   org.springframework.ldap
   spring-ldap-core
   1.3.1.RELEASE
  

  
   org.springframework.ldap
   spring-ldap-core-tiger
   1.3.1.RELEASE
  

  
   org.springframework.ldap
   spring-ldap-odm
   1.3.1.RELEASE
  

  
   org.springframework.ldap
   spring-ldap-ldif-core
   1.3.1.RELEASE
  

  
   org.springframework.ldap
   spring-ldap-ldif-batch
   1.3.1.RELEASE
  

 

Ahora agregaremos el BUILD eb este iran el compilador de maven y la ruta del JBOSS HOME:
 
  
  ${project.artifactId}
  
   
   
    maven-compiler-plugin
    2.3.2
    
     1.6
     1.6
    
   
   
    maven-war-plugin
    2.1.1
    
     
     false
     
      
       com.google.guava,org.slf4j
      
     
    
   
   
   
   
    org.jboss.as.plugins
    jboss-as-maven-plugin
    7.1.1.Final
   
   
   
    org.codehaus.mojo
    jboss-maven-plugin
    1.5.0
    
     
     C:\JBOSS\jboss-as-7.0.1.Final
     
     default
    
   
  

 
 
  
   
   
   default
   
    true
   
   
    
     
      maven-surefire-plugin
      2.10
      
       true
      
     
    
   
  

  
   
   
   
   arq-jbossas-managed
   
    
     org.jboss.as
     jboss-as-arquillian-container-managed
     test
    
   
  

  
   
   
   arq-jbossas-remote
   
    
     org.jboss.as
     jboss-as-arquillian-container-remote
     test
    
   
  

  
   
   
   
   
   openshift
   
    
     
      maven-war-plugin
      
       deployments
       ROOT
      
     
    
   
  

 

Ahora actualizaremos la configuracion de maven inicial de la siguiente forma:

Ahora revisaremos el buildpath del proyecto maven y deberias aparecer todas las librerias configuradas anteriormente:



Ahora crearemos la siguiente estructura de directorios:











 

Instalacion de JBOSS 7.0 con Eclipse Parte 2 (JTA BD Oracle)

Antes de comenzar la guia repasare la estrucutrua del servidor, lo que queremos hacer es agregar un nuevo modulos al Jboss que se capaz de comunicarnos con una Base de datos Oracle 11G. El servidor cuenta con varios modulos ya integrados como x ej , hibernate , richfaces, etc.
Estos modulos forman parte de una estructura de directorios y librerias que vienen alojados en el servidor con un archivo de configuracion "module.xml" que describe de donde tiene que obtener las librerias para cargar el modulo en el servidor.




Ahora un ejemplo del modulo de hibernate seria el siguiente:

El modulo primero esta unicado en:

C:\JBOSS\jboss-as-7.0.1.Final\modules\org\hibernate\main

Si queremos agregar un nuevo modulo debemos agregarlo en un classpath definido en "modules".

Un el archivo de configuracion del modulo tiene este contenido:

    
        
        
        
        
        
    

    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    



Cabe destacar que el jboss viene preparado para soportar hibernate por lo que si queremos usarlo solo debemos crear el JNDI en la consola de admisntracion o directamente en el archivo standalone.xml.

Ahora procederemos a crear un modulo para conectarnos a una BD Oracle 11G:

Primero crear la sigueinte ruta dentro del jboss:

C:\JBOSS\jboss-as-7.0.1.Final\modules\com\oracle\main

en ella copiar el jar del ODBC :

El archivo .index se crea cuando se carga el modulo con el jboss al primer reinicio.
El archivo Module.xml tiene este contenido:


 
    
        
    
    
        
        
    



Ahora configuraremos el driver con una conexion JTA en el servidor jboss, para ello debemos editar el archivo standalone.xml: Dentro del TAG "data-sources" agregaremos lo siguiente:
                    
                    jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE=off)(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=XE)(SERVER=DEDICATED)))
                    ojdbc6.jar
                    
                        3
                        5
                    
                    
                        allware
                        allware
                    
                    
                        5000
                        5
                    
                
                
            
              
     
                    oracle.jdbc.xa.client.OracleXADataSource
     
  
                


Ahora tenemos configurado la conexion JTA, guardamos los cambios, reiniciamos el jboss y verificamos en la consola de administracion:






Instalacion de JBOSS 7.0 con Eclipse Parte 1

En realidad es la: Spring Tool Suite Version: 3.3.0.RELEASE Build Id: 201307092139 pasos a seguir:

En el eclipse marketplace buscar y instalar la herramienta JBOSS TOOLS que trae la suit completa de administracion del servidor de aplicaciones de redhat, ahora cabe destacar que deben elegir bien la version de eclipse que tiene instalada.



Luego de instalarla ir a: el menu windows -> preferencias:


En la pestaña runtime environments , elegimos un nuevo servidor:


elegir el servidor Jboss 7.0:


Descargar el jboss:



Ahora cabe destacar que la version certificada para Java EE6 es la 6 Final. Desde la version 7.X no estan certificadas por lo que no respeta el standart, ya que estas traen muchas librerias incluidas en jaboss que no forman parte del standart de J2EE6.



Despues de descargar aparece en la lista de servidores :


Ahora como accedo a la consola de administracion?



Ahora todas estas configuracion son editables via consola de administracion, (que a decir verdad es bien rustica en comparacion con la de WEBLOGIC solucion privativa de Oracle), esta condiguracion esta disponible en un archivo de configuracion .XML en mi caso ubicado en:

 C:\JBOSS\jboss-as-7.0.1.Final\standalone\configuration

Ahora una muestra del archivo XML:




    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    

    
        
            
                
                    
                
            
            
                
                    
                
            
        
        
            
                
            
            
                
            
        
    

    
        
            
                
                
                    
                
            
            
                
                    
                
                
                
                
            
            
                
            
   
   
   
            
                
            
            
                
            
            
                
            
            
                
            
            
                
                
                    
                    
                
            
        
        
        
            
     
                
                    jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE=off)(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=XE)(SERVER=DEDICATED)))
                    ojdbc6.jar
                    
                        3
                        5
                    
                    
                        allware
                        allware
                    
                    
                        5000
                        5
                    
                
                
            
              
     
                    oracle.jdbc.xa.client.OracleXADataSource
     
  
                
            
        
        
            
        
  

        
  
        
            
                
                    
                
                
                
            
            
                
                    
                    
                
            
            
                
                
            
            
                
            
            
            
                
            
            
            
                
                    
                    
                
            
        
        
            
                
                    
                    
                    
                
                
                    
                    
                    
                
                
                    
                    
                
            
        
        
        
            
            
            
                
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                
            
            
        
        
        
            
            
        
        
            
        
        
        
        
            
                
                    1
                
            
            
                
                
                
                
                
                
            
        
        
        
            
        
        
        
        
            
                
                    
                        
                            
                        
                        
                            
                            
                            
                            
                        
                    
                
                
                    
                        
                    
                
                
                    
                        
                    
                
            
        
        
        
            
                
                    
                
            
            
            
        
        
            
            
                
                
            
        
        
            true
            ${jboss.bind.address:127.0.0.1}
            
            
                
                    
                
            
        
        
    

    
        
            
        
        
            
        
        
            
        
    

    
        
        
        
        
        
        
        
        
        
        
        
            
        
    







Ahora que se tiene instalador como se puede configurar una conexion JTA con Oracle o Sql server?, utilizar hibernate, Spring , Maven, etc en el proximo post Parte 2.








Tratamiento de Señales en C

Unix Signals

SIGHUP 1 Exit Hangup
SIGINT 2 Exit Interrupt
SIGQUIT 3 Core Quit
SIGILL 4 Core Illegal Instruction
SIGTRAP 5 Core Trace/Breakpoint Trap
SIGABRT 6 Core Abort
SIGEMT 7 Core Emulation Trap
SIGFPE 8 Core Arithmetic Exception
SIGKILL 9 Exit Killed
SIGBUS 10 Core Bus Error
SIGSEGV 11 Core Segmentation Fault
SIGSYS 12 Core Bad System Call
SIGPIPE 13 Exit Broken Pipe
SIGALRM 14 Exit Alarm Clock
SIGTERM 15 Exit Terminated
SIGUSR1 16 Exit User Signal 1
SIGUSR2 17 Exit User Signal 2
SIGCHLD 18 Ignore Child Status
SIGPWR 19 Ignore Power Fail/Restart
SIGWINCH 20 Ignore Window Size Change
SIGURG 21 Ignore Urgent Socket Condition
SIGPOLL 22 Ignore Socket I/O Possible
SIGSTOP 23 Stop Stopped (signal)
SIGTSTP 24 Stop Stopped (user)
SIGCONT 25 Ignore Continued
SIGTTIN 26 Stop Stopped (tty input)
SIGTTOU 27 Stop Stopped (tty output)
SIGVTALRM 28 Exit Virtual Timer Expired
SIGPROF 29 Exit Profiling Timer Expired
SIGXCPU 30 Core CPU time limit exceeded
SIGXFSZ 31 Core File size limit exceeded
SIGWAITING 32 Ignore All LWPs blocked
SIGLWP 33 Ignore Virtual Interprocessor Interrupt for Threads Library
SIGAIO 34 Ignore Asynchronous I/O



Importante es identificar el tipo de señal a programar, aveces no son las mismas que Linux, si la excepcion no esta programada, da una salida por defecto, ej:

Si la rutina no esta programa este proceso da un core al finalizar el proceso. Ej señal tratamiento de señales.



Ej en codigo C:
// envio de señal kill -31 PID
 act.sa_handler = apps_parametros;
 sigemptyset(&act.sa_mask);
 act.sa_flags = 0;
 sigaction(SIGXFSZ, &act, &oact);


Ahora la funcion que captura la señal y realiza la accion al caputar la señal 31 es:

/*funcion que cambia el valor de la configuracion de parametros adicionales*/
void apps_parametros(int v)
{
  int cola_WRITE;
  char temp[256];
  int f=0;
 //struct sigaction act, oact;
 //act.sa_handler = SIG_IGN;
 //sigemptyset(&act.sa_mask);
 //act.sa_flags = 0;
 //sigaction(SIGXFSZ, &act, &oact);
 if (transaccion == 1) {
  interpretaREQ(texto_resp);
  sprintf(temp, "%s", mensajeOUT);
  cola_WRITE = creacola(COLA_ESCRITURA);
  if (strcmp(InMsg.szTipoIPC, "IPC_Input") != 0)
   insertacola(cola_WRITE, temp, tipo);
 }
 
 
  if(strcmp(DatosAdicionales,"off")==0 && f==0){
  //agregar el cambio del FLAG al LOG
  syslog(LOG_DEBUG,"Cambio el valor de DATOS_ADICIONALES=ON.");
   strcpy(DatosAdicionales,"on");
   f=1;
  }else if(strcmp(DatosAdicionales,"on")==0 && f==0){
  //agregar el cambio del FLAG al LOG
  syslog(LOG_DEBUG,"Cambio el valor de DATOS_ADICIONALES=OFF.");
   strcpy(DatosAdicionales,"off");
   f=1;
  }
  
}




Señales Estándar
       Linux soporta las señales  estándar  listadas  a  continuación.  Muchos
       números  de  señales dependen de la arquitectura, tal como se indica en
       la columna "Valor".  (Donde aparezcan tres valores, el primero de ellos
       es  válido  normalmente para alpha y sparc, el segundo para i386, ppc y
       sh, y el último para mips.  Un - indica que una señal no está  presente
       en la arquitectura correspondiente.)

       Las  entradas  en la columna "Acción" de la tabla especifican la acción
       por defecto para la señal de la siguiente manera:

       Term   La acción por defecto es terminar el proceso.

       Ign    La acción por defecto es ignorar la señal.

       Core   La acción por defecto es  terminar  el  proceso  y  realizar  un
              volcado de memoria.

       Stop   La acción por defecto es detener el proceso.

       En  primer lugar se listan las señales descritas en el estándar POSIX.1
       original.

       Señal      Valor     Acción   Comentario
       ----------------------------------------------------------------------
       SIGHUP        1       Term    Cuelgue detectado en la terminal de
                                     control o muerte del proceso de control
       SIGINT        2       Term    Interrupción procedente del teclado
       SIGQUIT       3       Core    Terminación procedente del teclado
       SIGILL        4       Core    Instrucción ilegal
       SIGABRT       6       Core    Señal de aborto procedente de abort(3)
       SIGFPE        8       Core    Excepción de coma flotante
       SIGKILL       9       Term    Señal de matar
       SIGSEGV      11       Core    Referencia inválida a memoria
       SIGPIPE      13       Term    Tubería rota: escritura sin lectores
       SIGALRM      14       Term    Señal de alarma de alarm(2)
       SIGTERM      15       Term    Señal de terminación
       SIGUSR1   30,10,16    Term    Señal definida por usuario 1
       SIGUSR2   31,12,17    Term    Señal definida por usuario 2
       SIGCHLD   20,17,18    Ign     Proceso hijo terminado o parado
       SIGCONT   19,18,25            Continuar si estaba parado
       SIGSTOP   17,19,23    Stop    Parar proceso
       SIGTSTP   18,20,24    Stop    Parada escrita en la tty
       SIGTTIN   21,21,26    Stop    E. de la tty para un proc. de fondo
       SIGTTOU   22,22,27    Stop    S. a la tty para un proc. de fondo

       Las señales SIGKILL y SIGSTOP no pueden ser  capturadas,  bloqueadas  o
       ignoradas.

       A  continuación  se  listan  las señales que no aparecen en el estándar
       POSIX.1 pero que son descritas en SUSv2 y SUSv3 / POSIX 1003.1-2001.

       Señal        Valor     Acción   Comentario
       -------------------------------------------------------------------------
       SIGBUS      10,7,10     Core    Error de bus (acceso a memoria inválido)
       SIGPOLL                 Term    Evento que se puede consultar (Sys V).
                                       Sinónimo de SIGIO
       SIGPROF     27,27,29     A      Ha expirado el reloj de perfilado
                                       (profiling)
       SIGSYS      12,-,12      C      Argumento de rutina inválido (SVID)
       SIGTRAP        5        Core    Trampa de traza/punto de ruptura
       SIGURG      16,23,21     B      Condición urgente en conector (4.2 BSD)
       SIGVTALRM   26,26,28     A      Alarma virtual (4.2 BSD)
       SIGXCPU     24,24,30     C      Límite de tiempo de CPU excedido
                                       (4.2 BSD)
       SIGXFSZ     25,25,31     C      Límite de tamaño de fichero excedido
                                       (4.2 BSD)

       En las versiones de Linux  anteriores  a  la  2.2  (incluida  ésta)  el
       comportamiento  por  defecto para SIGSYS, SIGXCPU, SIGXFSZ, y (en otras
       arquitecturas distintas a SPARC y MIPS) SIGBUS era terminar el  proceso
       (sin  realizar  un volcado de memoria).  (En otros Unix’s la acción por
       defecto para SIGXCPU y SIGXFSZ es terminar el proceso sin  realizar  un
       volcado  de  memoria.)   Linux  2.4  cumple los requisitos del estándar
       POSIX 1003.1-2001 con respecto a estas señales, terminando  el  proceso
       con un volcado de memoria.

       A continuación otras señales.

       Señal          Valor      Acción   Comentario
       ------------------------------------------------------------------------------------
       SIGIOT           6         Core    Trampa IOT. Un sinónimo de SIGABRT
       SIGEMT      7,-,7  Term
       SIGSTKFLT     -,16,-       Term    Fallo de la pila en el coprocesador (no usada)
       SIGIO        23,29,22      Term    E/S permitida ya (4.2 BSD)
       SIGCLD        -,-,18       Ign     Un sinónimo de SIGCHLD
       SIGPWR       29,30,19      Term    Fallo de corriente eléctrica (System V)
       SIGINFO       29,-,-               Un sinónimo para SIGPWR
       SIGLOST        -,-,-       Term    Bloqueo de fichero perdido.
       SIGWINCH     28,28,20      Ign     Señal de reescalado de la ventana (4.3 BSD, Sun)
       SIGUNUSED     -,31,-       Term    Señal no usada.

       (La  señal 29 es SIGINFO / SIGPWR en la arquitectura alpha pero SIGLOST
       en sparc.)

       La señal SIGEMT no está especificada en el estándar POSIX  1003.1-2001,
       pero   sin   embargo   aparece  en  la  mayoría  de  Unix’s,  donde  su
       comportamiento por defecto es habitualmente  terminar  el  proceso  sin
       realizar un volcado de memoria.

       La  señal  SIGPWR  (que  no  está  especificada  en  el  estándar POSIX
       1003.1-2001) es ignorada habitualmente por defecto en  aquellos  Unix’s
       donde aparece.

       La  señal  SIGIO  (que  no  está  especificada  en  el  estándar  POSIX
       1003.1-2001) es ignorada por defecto en muchos Unix’s.

BUG UBUNTU 13.04 UPGRADE GNOME3.0

Este error da al actualizaar Ubuntu instalando la ultima version de Gnome Mate 1.6, estas librerias son dependencias de GTK3.0 por lo que no dejan instalar aplicaciones con este requisito y tampoco hacer upgrade.
sudo apt-get -f install
[sudo] password for lucho: 
Leyendo lista de paquetes... Hecho
Creando árbol de dependencias       
Leyendo la información de estado... Hecho
Corrigiendo dependencias... Listo
Se instalarán los siguientes paquetes extras:
  libwayland-client0 libwayland-cursor0
Se instalarán los siguientes paquetes NUEVOS:
  libwayland-client0 libwayland-cursor0
0 actualizados, 2 se instalarán, 0 para eliminar y 2 no actualizados.
31 no instalados del todo o eliminados.
Se necesita descargar 0 B/36,7 kB de archivos.
Se utilizarán 155 kB de espacio de disco adicional después de esta operación.
¿Desea continuar [S/n]? s
(Leyendo la base de datos ... 272362 ficheros o directorios instalados actualmente.)
Desempaquetando libwayland-client0:amd64 (de .../libwayland-client0_1.2.0-0ubuntu1~13.04~ricotz0_amd64.deb) ...
dpkg: error al procesar /var/cache/apt/archives/libwayland-client0_1.2.0-0ubuntu1~13.04~ricotz0_amd64.deb (--unpack):
 intentando sobreescribir `/usr/lib/x86_64-linux-gnu/libwayland-client.so.0.1.0', que está también en el paquete libwayland0:amd64 1.0.5-0ubuntu1
Desempaquetando libwayland-cursor0:amd64 (de .../libwayland-cursor0_1.2.0-0ubuntu1~13.04~ricotz0_amd64.deb) ...
dpkg: error al procesar /var/cache/apt/archives/libwayland-cursor0_1.2.0-0ubuntu1~13.04~ricotz0_amd64.deb (--unpack):
 intentando sobreescribir `/usr/lib/x86_64-linux-gnu/libwayland-cursor.so.0.0.0', que está también en el paquete libwayland0:amd64 1.0.5-0ubuntu1
Se encontraron errores al procesar:
 /var/cache/apt/archives/libwayland-client0_1.2.0-0ubuntu1~13.04~ricotz0_amd64.deb
 /var/cache/apt/archives/libwayland-cursor0_1.2.0-0ubuntu1~13.04~ricotz0_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)


Solucion: Como el .deb lo deja en el cache del repositorio solo hay que forzar la instalacion.
sudo dpkg -i --force-overwrite /var/cache/apt/archives/libwayland-*

respuesta:
(Leyendo la base de datos ... 272362 ficheros o directorios instalados actualmente.)
Desempaquetando libwayland-client0:amd64 (de .../libwayland-client0_1.2.0-0ubuntu1~13.04~ricotz0_amd64.deb) ...
dpkg: aviso: sobreseyendo el problema porque está activa la opción --force:
 
 intentando sobreescribir `/usr/lib/x86_64-linux-gnu/libwayland-client.so.0.1.0', que está también en el paquete libwayland0:amd64 1.0.5-0ubuntu1
dpkg: aviso: sobreseyendo el problema porque está activa la opción --force:
 
 intentando sobreescribir `/usr/lib/x86_64-linux-gnu/libwayland-client.so.0', que está también en el paquete libwayland0:amd64 1.0.5-0ubuntu1
Desempaquetando libwayland-cursor0:amd64 (de .../libwayland-cursor0_1.2.0-0ubuntu1~13.04~ricotz0_amd64.deb) ...
dpkg: aviso: sobreseyendo el problema porque está activa la opción --force:
 
 intentando sobreescribir `/usr/lib/x86_64-linux-gnu/libwayland-cursor.so.0.0.0', que está también en el paquete libwayland0:amd64 1.0.5-0ubuntu1
dpkg: aviso: sobreseyendo el problema porque está activa la opción --force:
 
 intentando sobreescribir `/usr/lib/x86_64-linux-gnu/libwayland-cursor.so.0', que está también en el paquete libwayland0:amd64 1.0.5-0ubuntu1
Configurando libwayland-client0:amd64 (1.2.0-0ubuntu1~13.04~ricotz0) ...
Configurando libwayland-cursor0:amd64 (1.2.0-0ubuntu1~13.04~ricotz0) ...
Procesando disparadores para libc-bin ...
ldconfig deferred processing now taking place

How To getRoles in Spring Security

Hi i am building an application some kind of hr portal, here i need to login three types of users 'hr, employee and admin', i am planning to use spring security , i want these three to be logged in in a single loginpage Now the question is 1 - How to design a login form telling the user to select a user type(hr or emp or admin) 2 - When a user is logged in and control goes to a targeted controlled , how to identify which type of user has logged it (identify logged in user role basically) If any other best practice of getting three type of users logged in with a single login form and identify the login role ..plesae suggest Thanks
Example: JSF2.0+ Spring Security

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;
import java.security.Principal;
import javax.security.auth.Subject;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.ArrayList;

@ManagedBean(name = "authenticationBean")
@RequestScoped
@Component
public class AuthenticationBean {
 public Principal principals ;
  public Set allPrincipals=null;
  public Subject subject=null;
  public ArrayList roles = new ArrayList();
  public String user = "";

 @Autowired
 @Qualifier("authenticationManager")
 protected AuthenticationManager authenticationManager;

 @Size(min = 1, message = "Username cannot be empty")
 private String username;

 @Size(min = 1, message = "Password cannot be empty")
 private String password;

 public AuthenticationBean() {

 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getUsername() {
  return username;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getPassword() {
  return password;
 }

 /**
  * @return
  * @throws IOException
  * @throws ServletException
  */
 public String login() throws IOException, ServletException {
  
  

  try {

   Authentication request = new UsernamePasswordAuthenticationToken(this.username, this.password);
 
   Collection authority = request.getAuthorities();
   
          for (GrantedAuthority granted : authority) {
           
           roles.add(granted.getAuthority());
           
                  
          }
          
          Authentication auth = SecurityContextHolder.getContext().getAuthentication();
          String name = auth.getName(); //get logged in username
          
   Authentication result = authenticationManager.authenticate(request);

   SecurityContextHolder.getContext().setAuthentication(result);
   
   ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
   
   HttpServletResponse responseHTTP = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
   
   HttpServletRequest requestHTTP = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();

   SavedRequest defaultSavedRequest = new HttpSessionRequestCache().getRequest(requestHTTP, responseHTTP);
   
   context.redirect(defaultSavedRequest.getRedirectUrl());

   FacesContext.getCurrentInstance().responseComplete();

   return null;

  } catch (AuthenticationException e) {

   FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()));
   return null;
  }



 }

 public String logout() throws IOException {
  this.username = "";
  this.password = "";
  ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
  context.redirect(context.getRequestContextPath() + "/j_spring_security_logout");
  FacesContext.getCurrentInstance().responseComplete();
  return null;
 }

}

& LOGIN.xhtml

 

  

  
   

Problemas de activación WIFI6 en LG_OLED55CXPSA

  Mi experiencia con este TV  ah sido impecable hasta ahora, llevaba un uso normal y no tenia que usar la conexión por wifi ya que tengo una...