Spring 3 @autowired Esempio


@autowired è usata per iniettare direttamente i valori configurati nell’xml nel bean.
Si puo usare  sul metodo set, costruttore o direttamente sul campo.

Bean
Bean dichiarato nel file xml con un solo  campo msg.

package com;

public class Message {

private String author;
private String body;

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public String getBody() {
return body;
}

public void setBody(String body) {
this.body = body;
}

}

applicatioContext.xml
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:context=”http://www.springframework.org/schema/context”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd”
xmlns:util=”http://www.springframework.org/schema/util”>

<context:component-scan base-package=”com” />

<bean id=”provaBean” class=”com.ProvaBean”>

</bean>
<bean id=”message” class=”com.Message”>
<property name=”msg” value=”Hello World” />
<property name=”author” value=”Pippo” />
</bean>

</beans>


Abilitazione Annotazione
Per usare @autowired si deve registrare AutowiredAnnotationBeanPostProcessor. Questo si può fare in due modi:
1) si aggiunge
   <context:annotation-config />    
dentro applicationContext.xml
2) si aggiunge:
   <bean class=”org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor”/> dentro applicationContext.xml  
@autowired Esempi
@autowired su campo

ProvaBean.java
package com;

import org.springframework.beans.factory.annotation.Autowired;

public class ProvaBean {
@Autowired
private Message message;

public Message getMessage() {
return message;
}

public void setMessage(Message message) {
this.message = message;
}


}

@autowired sul metodo set

ProvaBean.java
package com;

import org.springframework.beans.factory.annotation.Autowired;

public class ProvaBean {

private Message message;

public Message getMessage() {
return message;
}

@Autowired
public void setMessage(Message message) {
this.message = message;
}


}


@autowired sul costruttore

ProvaBean.java
package com;

import org.springframework.beans.factory.annotation.Autowired;

public class ProvaBean {

private Message message;

@Autowired
public ProvaBean(Message msg)
{
message = msg;
}

public Message getMessage() {
return message;
}

public void setMessage(Message message) {
this.message = message;
}


}



Esecuzione Test

TestBean.java
package com;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBean {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
“applicationContext.xml”);

ProvaBean obj = (ProvaBean) context.getBean(“provaBean”);
System.out.println(obj.getMessage().getBody());
System.out.println(obj.getMessage().getAuthor());
}

}


avviando il main si otterrà, in tutte e tre casi, il seguente output:

Java Reflection Esempio

Copiare due classi diverse ma con gli stessi campi tramite la reflection

Bean 

A.java

package com;

import java.lang.reflect.Field;

public class A {
private String name;

private long punteggio;

public long getPunteggio() {
return punteggio;
}

public void setPunteggio(long punteggio) {
this.punteggio = punteggio;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

B.java

package com;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class B {
private String name;

private long punteggio;

public long getPunteggio() {
return punteggio;
}

public void setPunteggio(long punteggio) {
this.punteggio = punteggio;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void copy(Object obj) {
try {

Method[] methods = obj.getClass().getMethods();

for (int i = 0; i < methods.length; i++) {
String methodName = methods[i].getName();
try{
if(methodName.startsWith(“get”)){
this.getClass().getMethod(methodName.replaceFirst(“get”, “set”) , methods[i].getReturnType() ).invoke(this, methods[i].invoke(obj, null));
}else if(methodName.startsWith(“is”) ){
this.getClass().getMethod(methodName.replaceFirst(“is”, “set”) ,  methods[i].getReturnType()  ).invoke(this, methods[i].invoke(obj, null));
}

}catch (NoSuchMethodException e) {
// TODO: handle exception
}catch (IllegalArgumentException e) {
// TODO: handle exception
}

}

} catch (Exception ex) {
ex.printStackTrace();
}
}

}


Classe per il test:
TestReflection.java
package com;
public class TestReflection {
public static void main(String[] args) {
A obj1 = new A();
obj1.setName(“hello world”);
A obj2 = new A();
obj2.copy(obj1);
System.out.println(“name obj copy with reflection:”+obj2.getName());
}
}
Esecuzione
lanciando il main si ottiene una copia identica dell’istanza obj1:

Spring 3 Bean Example

Configurazione
Mettere il seguente file dentro la cartella resources.

applicationContext.xml

<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:context=”http://www.springframework.org/schema/context”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd”
xmlns:util=”http://www.springframework.org/schema/util”>

<context:component-scan base-package=”com” />

  <bean id=”provaBean” class=”com.ProvaBean”>
</bean>
</beans>

Bean Spring
creare un file java di nome ProvaBean nel package “com”
ProvaBean.java
package com;
public class ProvaBean {
private String msg = “HelloWord”;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
creare un file java di nome TestBean:
TestBean.java
package com;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBean {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
“applicationContext.xml”);
ProvaBean obj = (ProvaBean) context.getBean(“provaBean”);
System.out.println(obj.getMsg());
}
}

Esecuzione
lanciare il main del file TestBean. L’ouput sarà:

java.lang.ClassNotFoundException: org.apache.myfaces.webapp.StartupServletContextListener JSF 2

Eccezione:

SEVERE: Error configuring application listener of class org.apache.myfaces.webapp.StartupServletContextListener
java
.lang.ClassNotFoundException: org.apache.myfaces.webapp.StartupServletContextListener
at org
.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
at org
.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
at org
.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3786)
at org
.apache.catalina.core.StandardContext.start(StandardContext.java:4342)
at org
.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org
.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org
.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org
.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org
.apache.catalina.core.StandardService.start(StandardService.java:516)
at org
.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org
.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun
.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun
.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun
.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java
.lang.reflect.Method.invoke(Method.java:597)
at org
.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org
.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)

Soluzione:
Mancano alcuni jar delle MyFaces. Scaricare i file da qui e metterli nella cartella /WEB-INF/lib

Read Write File With InputStream OutputStream Java

Le istruzioni che leggono  il  file con InputStream sono:

InputStream inputStream = new FileInputStream(“c:/myFile.txt”);
inputStream.read(bytes);

Per scrivere su un file con OutputStream:

OutputStream outputStream = new FileOutputStream(new File(“c:/myFileNew.txt”));
outputStream.write(bytes, off, len);// scrive un array di byte di  lunghezza len a partire da posizione off

Esempio completo:

package com;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class InputStreamToFile {
    public static void main(String[] args) {

InputStream inputStream = null;
OutputStream outputStream = null;

try {
inputStream = new FileInputStream(“c:/myFile.txt”);

// write the inputStream to a FileOutputStream
outputStream = new FileOutputStream(new File(“c:/myFileNew.txt”));

int read = 0;
byte[] bytes = new byte[1024];

while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}

System.out.println(“Done!”);

} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
// outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}
    }
}

f:ajax with f:param, JSF2

f:ajax è un tag JSF che aggiunge il meccanismo delle request asincrone a molti componenti UI. 
Per passare dei parametri viene aggiunto il tag f:param
pagina con supporto ajax:


ProvaAjax.xhmtl

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”
xmlns:f=”http://java.sun.com/jsf/core”
xmlns:h=”http://java.sun.com/jsf/html”
xmlns:ui=”http://java.sun.com/jsf/facelets”
xmlns:p=”http://primefaces.org/ui”
xmlns:c=”http://java.sun.com/jsp/jstl/core”>
<h:head/>
<h:body>
<h:form>
<input type=”hidden” name=”id2″ id=”id2″ value=”55″ />
<h:commandLink value=”ssss”>
<f:param name=”id” value=”44″ />
<f:ajax listener=”#{galleriaBean.countListener}”>

</f:ajax>
</h:commandLink>

</h:form>
</h:body>
</html>


nel tag f:ajax:
            – execute=”name”, indica che il componente con id “name” deve essere mandato al server.
            – render=”output”, indica che il componente con id “output” dovrà, dopo la request ajax, essere aggiornato.
            – listener=“#{provaTag.handleEvent}”, indica il metodo del bean da chiamare.


GalleriaBean.java

package com;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

@ManagedBean
@SessionScoped
public class GalleriaBean {

public void countListener(AjaxBehaviorEvent event) {
System.out.println(“test:”);
String id = FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get(“id”);
System.out.println(“id:” + id);
}

}

aprendo l’indirizzo: http://localhost:8080/JSFProject/faces/ProvaAjax.xhtml



cliccando sul link “sss” si entra dentro il listener che scrive sulla console:







MySql Stored Procedure Example Simple

Stored Procedure che mostra l’utilizzo di dichiarazione variabili, cursori annidati, ciclo while, if then.

CREATE  PROCEDURE `updateOffer`()
BEGIN
 declare v_col2 int default 0;
 declare no_more_rows2 int default 0;
DECLARE finito INT default 0;
DECLARE OrderItemID INT;
DECLARE userId INT;
DECLARE example_cursor CURSOR FOR select id from imps_customer_tb;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finito = 1;

  — open the cursor
OPEN example_cursor;
  ciclo: WHILE NOT finito DO
       — read the name from next row into the variable l_name
  FETCH  example_cursor INTO   userId;

                 INSERT INTO imps_offer_tb (`PROG_ANNO`, `EMISSION_DATE`, `DIVISION_ID`, `CUSTOMER_ID`, `CREATION_DATE`, `LAST_UPDATE_DATE`, `STATO_ID`, `TOTAL_AMOUNT`,`PRIMARIA`) VALUES (1, ‘2013-11-28’, 1, userId, ‘2013-11-28 17:03:25’, ‘2013-11-28 17:03:26′, 1, 0,’y’);
    set OrderItemID = LAST_INSERT_ID();

BLOCK2: begin
declare v_col2 int;
declare no_more_rows2 INT default 0;
  declare cursor2 cursor for    select distinct of.id from imps_course_tb of, imps_offer_tb o   WHERE    o.CUSTOMER_ID = userId and of.OFFER_ID = o.ID ;
    declare continue handler for not found   set no_more_rows2 = 1;
    open cursor2;
            LOOP2: WHILE NOT no_more_rows2 DO
                fetch cursor2 into  v_col2;
                          if v_col2 <> 0 then
         UPDATE `imps_course_tb` SET `OFFER_ID`=OrderItemID  WHERE  `ID`=v_col2;
                          end if;
            END WHILE  LOOP2;
            CLOSE cursor2;
       end BLOCK2;

        END WHILE ciclo;
CLOSE example_cursor;

END

Ottimo debug per mysql:
http://mydebugger.com/

f:ajax tag JSF 2.0

f:ajax è un tag JSF che aggiunge il meccanismo delle request asincrone a molti componenti UI. 

pagina con supporto ajax:


ProvaAjax.xhmtl

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” 
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”
      xmlns:f=”http://java.sun.com/jsf/core”      
      xmlns:h=”http://java.sun.com/jsf/html”>

    <h:body>
    <h3>JSF 2.0 + Ajax Hello World Example</h3>

    <h:form>
      <h:inputText id=”name” value=”#{provaTag.name}” ></h:inputText>
      <h:commandButton value=”Try Me” >
    <f:ajax execute=”name” render=”output” listener=”#{provaTag.handleEvent}” />
      </h:commandButton>

      <h2><h:outputText id=”output” value=”#{provaTag.message}” /></h2>
    </h:form>

    </h:body>
</html>

nel tag f:ajax:
            – execute=”name”, indica che il componente con id “name” deve essere mandato al server.
            – render=”output”, indica che il componente con id “output” dovrà, dopo la request ajax, essere aggiornato.
            – listener=“#{provaTag.handleEvent}”, indica il metodo del bean da chiamare.

ProvaTag.java

package com;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AjaxBehaviorEvent;

import java.io.Serializable;

@ManagedBean
@SessionScoped
public class ProvaTag implements Serializable {

private static final long serialVersionUID = 1L;

private String name;
private String message;

public String getName() {
  return name;
}

public void setName(String name) {
this.name = name;
}

public String getMessage(){
return message;
}

public void setMessage(String message) {
this.message = message;
}

public void handleEvent(AjaxBehaviorEvent event) {
       message = “Hello World:”+ name;
   }
 
}


risultato:



cliccando sul tasto “Try Me”:






How To Create New File

import java.io.*;

public class CreateFile{
  public static void main(String[] args) throws IOException{
  File f;
  f=new File(“myfile.txt”);
  if(!f.exists()){
  f.createNewFile();
  System.out.println(“New file “myfile.txt” has been created
  to the current directory”);
  }
  }
}

Spring 3, get file properties from source with @Value

Creare un file di properties dentro la cartella resources:

configurationFBM.properties

prova= bohhhh

Modificare il file di configurazione di spring:

<beans xmlns:context=”http://www.springframework.org/schema/context” xmlns:util=”http://www.springframework.org/schema/util” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns=”http://www.springframework.org/schema/beans” xsi:schemalocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd”>

<context:component-scan base-package=”com.fbm”>
       <util:properties id=”configurationFBM” location=”classpath:/configurationFBM.properties”>

</util:properties></context:component-scan></beans>

Da dentro il codice si può accedere ad una proprietà del file di properties con la seguente annotation:

@Value(“#{configurationFBM[‘prova’]}”)
String someValue;