martedì 6 novembre 2012

openshift: restart mysql

utilissimo!!
durante up upgrade della piattaforma va giu  mysql..
non posso riavviarlo da shell
...

mi connetto su freechat...e trovo assistenza!!

mi suggeriscono questo semplice comando:
rhc app cartridge restart -a testapp -c mysql-5.1


DA RICORDARE!!!






sabato 1 settembre 2012

git: eliminare un repository locale

basta eliminare la cartella .git

nel caso in cui ci siano cartelle annidate (tipo sottomoduli):


find $GIT_DIR -name *.git* -ok rm -Rf {} \;
http://stackoverflow.com/questions/1213430/how-to-fully-delete-a-git-repository-created-with-init

venerdì 31 agosto 2012

applicazione war con due entity manager contemporanemente

ambiente: jboss-7.1.1 
applicazione: war con due entity, due session bean repository, un service rest che opera usando entrambi i session bean.
caricare il driver mysql tra i moduli di jboss7

(scarica da qui: https://github.com/fiorenzino/dual-jpa.git)

ricordarsi di:
1) persistence.xml aggiungere i nomi delle classi che deve gestire ciascun em
2) persistence.xml non usare <property name="hibernate.hbm2ddl.auto" value="update" /> altrimenti crea le tabelle in entrambi i db (consiglio di crearle prima di deployare)


esempio di entity:

@Entity
public class UserA implements Serializable {

private Long id;
private String name;
....


@Entity
public class UserB implements Serializable {

private Long id;
private String name;

....



esempio di persistence.xml:

<?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="PuA">
<jta-data-source>java:jboss/datasources/ExampleA</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
<class>it.coopservice.test.model.UserA</class>
</persistence-unit>
<persistence-unit name="PuB">
<jta-data-source>java:jboss/datasources/ExampleB</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
<class>it.coopservice.test.model.UserB</class>
</persistence-unit>
</persistence>

3) nei repository iniettare gli entity manager specificando la persistence unit:

esempio di session bean: 



@Stateless
@LocalBean
public class SessionA implements Serializable {
@PersistenceContext(unitName = "PuA")
protected EntityManager em;
...



@Stateless
@LocalBean
public class SessionB implements Serializable {
@PersistenceContext(unitName = "PuB")
protected EntityManager em;

...


4) nello standalone.xml mappare i datasource usando driver XA (altrimenti non sarà possibile effettuare operazioni nella stessa transazione su entrambi i datasource:

esempio di datasource in standalone.xml:


<datasources>
<xa-datasource jndi-name="java:jboss/datasources/ExampleA" pool-name="ExampleAD" enabled="true" use-ccm="false">
<xa-datasource-property name="URL">jdbc:mysql://localhost:3306/exampleA</xa-datasource-property>
<driver>com.mysql</driver>
<xa-pool>
   <is-same-rm-override>false</is-same-rm-override>
   <interleaving>false</interleaving>
   <pad-xid>false</pad-xid>
   <wrap-xa-resource>true</wrap-xa-resource>
</xa-pool>
<security>
   <user-name>root</user-name>
   <password>flower</password>
</security>
<recovery>
   <recover-credential>
<user-name>root</user-name>
<password>flower</password>
   </recover-credential>
</recovery>
    </xa-datasource>
<xa-datasource jndi-name="java:jboss/datasources/ExampleB" pool-name="ExampleBD" enabled="true" use-ccm="false">
<xa-datasource-property name="URL">jdbc:mysql://localhost:3306/exampleB</xa-datasource-property>
<driver>com.mysql</driver>
<xa-pool>
   <is-same-rm-override>false</is-same-rm-override>
   <interleaving>false</interleaving>
   <pad-xid>false</pad-xid>
   <wrap-xa-resource>true</wrap-xa-resource>
</xa-pool>
<security>
   <user-name>root</user-name>
   <password>flower</password>
</security>
<recovery>
   <recover-credential>
<user-name>root</user-name>
<password>flower</password>
   </recover-credential>
</recovery>
    </xa-datasource>
</datasources>



 <drivers>
                    <driver name="com.mysql" module="com.mysql">
                        <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
                    </driver>
 </drivers>




a questo punto sara' possibile usare un service che si inettta entrambi i session bean delegati a ciascun respository e fare operazioni transazionali:


esempio di service che opera su entrambi i session beans:

@Stateless
@LocalBean
public class ServiceAB implements Serializable {

@Inject
SessionA sessionA;

@Inject
SessionB sessionB;

public String createAB(String nameA, String nameB) {
UserA userA = new UserA(nameA);
Long idA = sessionA.persist(userA);
UserB userB = new UserB(nameB);
Long idB = sessionB.persist(userB);
return "a:" + idA + " - b:" + idB;
}
}



esempio di servizio rest per fare i test :


@Path("/v1/test")
@Stateless
@LocalBean
public class Rest implements Serializable {

@Inject
SessionA sessionA;
@Inject
SessionB sessionB;

@Inject
ServiceAB serviceAB;

@GET
@Path("/addA/{name}")
@Produces(MediaType.TEXT_PLAIN)
public Long addA(@PathParam("name") String name) {
UserA userA = new UserA();
userA.setName(name);
return sessionA.persist(userA);
}

@GET
@Path("/addB/{name}")
@Produces(MediaType.TEXT_PLAIN)
public Long addB(@PathParam("name") String name) {
UserB userB = new UserB();
userB.setName(name);
return sessionB.persist(userB);
}

@GET
@Path("/addAB/{nameA}/{nameB}")
@Produces(MediaType.TEXT_PLAIN)
public String addAB(@PathParam("nameA") String nameA,
@PathParam("nameB") String nameB) {
return serviceAB.createAB(nameA, nameB);
}
}

ricordarsi di aggiungere un rest activator:


@ApplicationPath("/rest")
public class JaxRsActivator extends javax.ws.rs.core.Application {

}






giovedì 23 agosto 2012

appunti git

1) nel caso in cui esiste gia' un reporisoty locale e ci vuoi attacare un repo remoto
Create a new repository on the command line
touch README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/fiorenzino/b-flower.git
git push -u origin master

Push an existing repository from the command line
git remote add origin https://github.com/fiorenzino/b-flower.git
git push -u origin master


per distrugger repository remoti
git push <remote> :<remote_branch>

es. git push origin :FORGE-610

per aggiungere al precedente commit:
git commit --amend

mercoledì 22 agosto 2012

turbo maven


mvn -T 4 clean install
mvn -T 2C clean install

and skip test:

-Dmaven.test.skip=true

Skipping tests in some modules in Maven


What about skipping tests only in this module ?
In the pom.xml of this module:
<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.4.2</version>
        <configuration>
          <skipTests>true</skipTests>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]</project>

http://stackoverflow.com/questions/772735/skipping-tests-in-some-modules-in-maven


ubuntu update sun jdk


chmod 777 jdk-6u33-linux-x64.bin
./jdk-6u33-linux-x64.bin
ls
mv jdk1.6.0_33 /usr/lib/jvm/
sudo mv jdk1.6.0_33 /usr/lib/jvm/
cd /usr/lib/jvm/
ls
sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk1.6.0_33/bin/javac 1
sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk1.6.0_33/bin/java 1
sudo update-alternatives --install /usr/bin/javaws javaws /usr/lib/jvm/jdk1.6.0_33/bin/javaws 1
sudo update-alternatives --config javac
sudo update-alternatives --config java
sudo update-alternatives --config javac
sudo update-alternatives --config javaws

mercoledì 11 luglio 2012

creare modulo attivo (con annotazioni) in jboss 7.1.1.final

jandex versione 1.0.3.final (non la 1.0.4 - elimina il jar senza dire nulla).

- produce il file idx e lo inserisce nel jar sotto meta-inf
java -jar jandex-1.0.3.Final.jar -m -v commons2Web-1.6.2.jar

aggiungerlo come modulo.

per gestire la dipendeza nell'applicazione che la usa, creare il file jboss-deplyment-structure.xml (sotto web-inf) e aggiungere la voce:


<module name="it.coopservice.commons2Web" export="true" slot="no-renderer" annotations="true">
       <imports>
               <include path="*" />
       </imports>
</module>



per riferimenti:
https://community.jboss.org/thread/196129

giovedì 28 giugno 2012

openshift: hot deploy

Da provare!!
basta aggiungere un solo file (hot_deploy) nella cartella .openshift/markers/ per evitare che openshift faccia il reboot dell'application server.


bisogna vedere come si comporta (forse va aggiunto nel commit il file ROOT.war.dodeploy per effettuare il rideploy a caldo)


https://openshift.redhat.com/community/blogs/new-openshift-release-june-26-2012-jboss-eap-hot-deployments-pricing-and-more


Hot Deployment

Hot deployment is slowly being added. We've started with the Jboss AS 7 cartridge, but will be implementing the same feature with the others soon. Hot deployment allows you to push to your application without having to restart it. This helps with zero downtime deployments. To use it add the following marker to your git repo:
.openshift/markers/hot_deploy
Just git add, commit and push it and we'll attempt to deploy the new code without stopping JBoss. Keep in mind you still have to live inside your memory footprint. 
So, if you have a memory intensive app that has a memory intensive build, you may want to look at using Jenkins to build so the process happens inside a different gear.

openshift: come gestire la rotazione dei log

Utile post dal forum per gestire la rotazione dei log ed eventuale eliminazione/compressione:
https://openshift.redhat.com/community/forums/openshift/log-rotation-not-enabled





cd $OPENSHIFT_LOGS_DIR   
 
   find . -type f ( -name access_log-* , -name error_log-* ) -mtime +180  
   #  Add this to the above command to backup as a gzipped tarball:    | xargs tar -czvf  backup-logs-$(date +%Y%m%d).tar.gz   
   #  Add this to the above command to delete 'em:   -exec rm {} \;      or     | xargs rm)   

martedì 5 giugno 2012

openshift+jboss: RewriteValve from 80 to 443

riportato dal forum:


1. In your application, create a file called jboss-web.xml in src/main/webapp/WEB-INF/ directory with this content.
 sh$ cat  src/main/webapp/WEB-INF/jboss-web.xml   
<jboss-web>
      <security-domain>jboss-web-policy</security-domain>
       <valve>
             <class-name>org.jboss.web.rewrite.RewriteValve</class-name>
       </valve>
</jboss-web>
2. Create a rewrite.properties file in the src/main/webapp/WEB-INF/ directory with checking for http and redirecting to https.
sh$ cat src/main/webapp/WEB-INF/rewrite.properties  
RewriteCond %{HTTP:X-Forwarded-Proto} http   
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R,L]    

links utili

sabato 19 maggio 2012

jboss7 deployment timeout

Se il server va in timeout durante il deploy, undeploya tutte le applicazioni.

per evitarlo:


 <subsystem xmlns="urn:jboss:domain:deployment-scanner:1.1">
            <deployment-scanner path="deployments" relative-to="jboss.server.base.dir" scan-interval="5000" deployment-timeout="6000"/>
        </subsystem>

java.lang.IllegalStateException: Parameter count exceeded allowed maximum: 512

immagina di avere una mega griglia con numero di parametri variabile ed alto...
quando viene fatto il submit e partono i valori jboss7 risponde:


java.lang.IllegalStateException: Parameter count exceeded allowed maximum: 512


https://community.jboss.org/thread/197650?_sscc=t

Add the following system property to the configuration file(eg standalone.xml).
<property name="org.apache.tomcat.util.http.Parameters.MAX_COUNT" value="10000"/>
grande openshift!!

domenica 29 aprile 2012

openshift: non esiste +$OPENSHIFT_APP_DIR

modificare script post_deplo!!
da $OPENSHIFT_APP_DIR/ a $OPENSHIFT_HOMEDIR/$OPENSHIFT_APP_NAME/

openshift: remove file with git

Remember this:


git rm -rf src/ pom.xml
git commit -a -m "removing default files"

domenica 15 aprile 2012

picketlink social: come creare un meccanismo di autenticazione+autorizzazione ibrido

Scenario: sito web con registrazione utenti per fornire servizi personalizzati
autenticazione + autorizzazione: come gestirle?

Tecnologia prescelta: jee6 + jboss (su openshift) + mysql

Soluzioni possibili:
 - tutto interno
 - autenticazione esterna + autorizzazione interna
 - entrambe le soluzioni insieme

Ragioniamo...
Oggi quasi tutti hanno un account su facebook o su google, perchè non utilizzare il sistema di autenticazione offerto da questi provider, gestendo internamente il processo di autorizzazione?

Nulla toglie la possibilità di registrare un utente internamente per il processo di autenticazione + autorizzazione..

Soluzione: usare due domini di sicurezza a cascata.

Indizi:
usare facebbok + google per autenticazione:
http://server.dzone.com/articles/jbossas7-making-your-web

Multiple login modules can be chained together in a stack, with each login module providing both the authentication and authorization components. This works for many use cases, but sometimes authentication and authorization are split across multiple user management stores.
http://docs.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/5/html/Security_Guide/ch12.html#sect-Password_Stacking

Abilitare l'audit del processo di autenticazione:
http://middlewaremagic.com/jboss/?p=453

Gestione dei domini in standalone.xml:

<security-domain cache-type="default" name="external_auth">
            <authentication>
                <login-module code="org.picketlink.social.auth.ExternalAuthLoginModule" flag="required">
                    <module-option name="password-stacking" value="useFirstPass">
                </module-option></login-module>
                 <login-module code="Database" flag="required">
                    <module-option name="dsJndiName" value="java:jboss/datasources/MysqlDS">
                    <module-option name="principalsQuery" value="select A.password from UserAuth as A where A.username=?">
                    <module-option name="rolesQuery" value="SELECT B.roleName,'Roles' FROM UserRole as B left join UserAuth as A on (A.id =B.userAuth_id) where A.username = ?">
                    <module-option name="password-stacking" value="useFirstPass">                   
                </module-option></module-option></module-option></module-option></login-module>
            </authentication>
        </security-domain>


Questo è solo l'inizio...

sabato 24 marzo 2012

ho roottato sul mio asus eee pad

seguendo la guida: http://www.androidauthority.com/how-to-root-the-asus-eee-pad-transformer-using-nachoroot-46407/

- adesso con linux installer vediamo se posso usare jboss forge per programmare dal tablet...
visto che eclipse non si può avere ci accontentiamo di una shell!
...esperimenti in movimento...

martedì 13 marzo 2012

openshift: gestire + di un account sullo stesso pc

Immaginate di avere più computer con cui gestire openshift oppure immaginate di voler condividere lo sviluppo di un applicazione con un vs collega.
Come fate ad accedere dal II pc o dal pc del vs collega?

Strada semplice:


1) generate sul II pc o sul pc del vs collega una nuova chiave ssh:
ssh-keygen -trsa

2) aggiungiamola sul server openshift:
rhc sshkey add -i aliasDellaNuovaChiave -k /percorso/su/file/system/.ssh/id_rsa.pub -l account@gmail.com

3) per aggiungere l'host di openshift tra quelli in trust sul nostro pc:
prima eseguiamo:
rhc-domain-info -l account@gmail.com
prendiamo la stringa ssh://utente@hostname e proviamo a fare una connessione ssh
ssh xxxxxxxxxxxxxxxxxxxxxxdee2a911d@app-domain.rhcloud.com

Il gioco è fatto!!
Adesso possiamo scaricare il ns progetto usando:

git clone ssh://xxxxxxxxxxxxxxxxxxxxxxdee2a911d@app-domain.rhcloud.com/~/git/app.git/


BUON DIVERTIMENTO

giovedì 1 marzo 2012

openshift: usare scp per scaricare dati

Non credevo fosse possibile..ma in realta' se e' possibile collegarsi via ssh, perche' non fare copie remote via scp??

Leggendo nei forum, si suggeriva:

scp UUID@AppName-NameSpace.rhcloud
.com:~/AppName/logs/* 
A cosa puo' servire?
semplice..fare backup su altri server...
per scaricare l'intera configurazione?
..backup for me!!

domenica 12 febbraio 2012

jsf2: stringhe vuote convertite in zero.. automaticamente

Nelle ultime versioni di jsf c'è una nuova future voluta (che non mi piace affatto!!) che consente di gestire la conversione automatica tra valori vuoti e 0..
faccio un esempio: quando avete un array di select items capita di spesso di inserire un valore vuoto con label "seleziona" - il valore vuoto serve per non far scattare il filtro nel meccanismo di ricerca.
Se invece il vuoto viene convertito in 0, a quel punto il meccanismo di ricerca lo utilizza...


per ulteriori informazioni a riguardo:


Una possibile soluzione in jboss è di aggiungere nel file jboss7/bin/standalone.conf  questo parametro:
-Dorg.apache.el.parser.COERCE_TO_ZERO=false

Nel file web.xml aggiungete invece:
<context-param>
        <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
        <param-value>true</param-value>
</context-param>


funziona...peccato che su openshift non si possano aggiungere variabili d'ambiente custom!!!

openshift: OPENSHIFT_DATA_DIR come usarlo per file RESISTENTI AI PUSH

Indagare meglio su come usare il nostro spazio:
"For persistent data (also in env var OPENSHIFT_DATA_DIR)"


Ho provato ad usarlo, creando un link simbolico tra:
ln -s ~/appname/data ~/appname/jbossas-7.0/standalone/deployments/ROOT.war/data




MA NON FUNZIA!!




link utile:
https://www.redhat.com/openshift/community/forums/express/few-questions-to-learn-more-about-express

openshift: aggiungere alias

Se registrate un dominio per pochi euro (dominio+dns+posta = 10/20 euro).
Create presso il vs DNS una CNAME del tipo: test.dominio.it. [NOTATE IL PUNTO!] 

che ridirge verso 

appname-domainname.rhcloud.com

Comunicate ad openshift questo CNAME, tramite il comando rhc-ctl-app:
rhc-ctl-app -a appname -c add-alias --alias appname.domainname.it -l account@gmail.com

E voilà la vs applicazione è raggiungibile a tutto il mondo!

ricordatevi ogni tanto di verificare che il jboss sia ancora attivo (openshift è ancora in beta...ogni tanto va tutto giù senza preavviso)!!!!


openshift: usiamo il cron per riavviare jboss di notte!

Date le poche risorse a disposizione, potrebbe essere utile riavviare jboss tutte le notti alle 3:00 (..si lo so che una buon applicazione non ne dovrebbe aver bisogno...):

  1) abilitiamo il cron alla ns applicazione
rhc-ctl-app -a giavacms -e add-cron-1.4

  2) creaiamo cartelle e script per usare i cron su openshift
mkdir -p .openshift/cron/hourly

 3) creiamo il ns file di restart di jboss 
touch .openshift/cron/hourly/restart_jboss.sh

4) aggiungiamo il seguente contenuto al suo interno

#!/bin/bash
echo "--------------------------------------------" >> $OPENSHIFT_REPO_DIR/cron_jboss/cron.log
date >> $OPENSHIFT_REPO_DIR/cron_jboss/cron.log
NOW=$(date +"%H")
echo $NOW >> $OPENSHIFT_REPO_DIR/cron_jboss/cron.log
echo 'resto' $RESTO '- cnfr' $CNFR >> $OPENSHIFT_REPO_DIR/cron_jboss/cron.log
if [ "$NOW" -eq "03"\ ];then
        $OPENSHIFT_APP_CTL_SCRIPT restart;
        echo "restart jboss now:" >> $OPENSHIFT_REPO_DIR/cron_jboss/cron.log
else
        echo "no restart jboss now!!" >> $OPENSHIFT_REPO_DIR/cron_jboss/cron.log
fi
date >> $OPENSHIFT_REPO_DIR/cron_jboss/cron.log
echo "--------------------------------------------" >> $OPENSHIFT_REPO_DIR/cron_jboss/cron.log


5) creiamo una cartella in cui archiviare il log di restart:
mkdir cron_jboss
touch cron_jboss//cron.log

6) committiamo tutti i files su openshift
git add .openshift/*
git add cron_jboss/*
git commit -m"start with cron" .openshift/*
git commit -m"start with cron" cron_jboss/*
git push



7) link utili
https://www.redhat.com/openshift/community/forums/express/restart-jboss-with-cron
http://docs.redhat.com/docs/en-US/OpenShift_Express/2.0/html/User_Guide/sect-User_Guide-Scheduling_Timed_Jobs_with_Cron.html