quartz – Esempio schedulazione job

Quartz è un framework che permette di schedulare processi da java.
Da questo link si può scaricare tutto il necessario.

Quartz Job

Racchiude la logica di business, dentro il metodo execute, che il job (processo) deve eseguire
HelloJob.java
package com;

import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class HelloJob implements Job {

public void execute(JobExecutionContext arg0) throws JobExecutionException {

System.out.println("Hello World Quartz Scheduler: " + new Date());

}
}

Quartz Trigger
Definisce quando quartz deve eseguire il job:

   //trigger il job ogni 5 secondi
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("helloTriggerName", "group1")
.withSchedule(
CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
.build();

Scheduler
Linka il job con il trigger:

    // schedule it
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
    scheduler.scheduleJob(job, trigger);

Esempio Completo

HelloSchedule.java

  package com;

import java.util.Date; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerFactory; import org.quartz.SimpleTrigger; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; public class HelloSchedule { public HelloSchedule() throws Exception { // JobDetail job = JobBuilder.newJob(HelloJob.class) .withIdentity("helloJobName", "group1").build(); //trigger il job ogni 5 secondi Trigger trigger = TriggerBuilder .newTrigger() .withIdentity("helloTriggerName", "group1") .withSchedule( CronScheduleBuilder.cronSchedule("0/5 * * * * ?")) .build(); // schedule it Scheduler scheduler = new StdSchedulerFactory().getScheduler(); scheduler.start(); scheduler.scheduleJob(job, trigger); } public static void main(String args[]) { try { new HelloSchedule(); } catch (Exception e) { } } }


Esecuzione
Lanciando il main si ha l’esecuzione del job ogni 5 secondi:

SocialAuthException – Verification code is null

Eccezione lanciata quando nella request a Facebook manca il token restituito nella response della login.

codice di socialAuth che lancia l’SocialAuthException:


@Override<br />  <span style="color: #7f0055; font-weight: normal;"><b>public</b></span> Profile verifyResponse(<span style="color: #7f0055; font-weight: normal;"><b>final</b></span> HttpServletRequest httpReq)<br />      <span style="color: #7f0055; font-weight: normal;"><b>throws</b></span> Exception {<br />    LOG.info(<span style="color: #2a00ff; font-weight: normal;">"Retrieving Access Token in verify response function"</span>);<br />    <span style="color: #7f0055; font-weight: normal;"><b>if</b></span> (httpReq.getParameter(<span style="color: #2a00ff; font-weight: normal;">"error_reason"</span>) != null<br />        &amp;&amp; <span style="color: #2a00ff; font-weight: normal;">"user_denied"</span>.equals(httpReq.getParameter(<span style="color: #2a00ff; font-weight: normal;">"error_reason"</span>))) {<br />      <span style="color: #7f0055; font-weight: normal;"><b>throw</b></span> <span style="color: #7f0055; font-weight: normal;"><b>new</b></span> UserDeniedPermissionException();<br />    }<br />    <span style="color: #7f0055; font-weight: normal;"><b>if</b></span> (!isProviderState()) {<br />      <span style="color: #7f0055; font-weight: normal;"><b>throw</b></span> <span style="color: #7f0055; font-weight: normal;"><b>new</b></span> ProviderStateException();<br />    }<br />    String code = httpReq.getParameter(<span style="color: #2a00ff; font-weight: normal;">"code"</span>);<br />    <span style="color: #7f0055; font-weight: normal;"><b>if</b></span> (code == null || code.length() == 0) {<br />      <span style="color: #7f0055; font-weight: normal;"><b>throw</b></span> <span style="color: #7f0055; font-weight: normal;"><b>new</b></span> <b>SocialAuthException</b>(<span style="color: #2a00ff; font-weight: normal;">"</span><span style="color: #2a00ff;"><b>Verification code is null</b></span><span style="color: #2a00ff; font-weight: normal;">"</span>);<br />    }

SocialAuth – Login su Facebook con JAVA e JSF

SocialAuth è un framework che permette di interagire con i vari social (Facebook, Twitter, etc) tramite Java.
Vediamo la login.

CREAZIONE APP FACEBOOK
Andare sulla console sviluppatori di facebook, apparirà la seguente schermata:

Nel campo site URL inserire l’indirizzo “http://localhost:8080”, per testare in locale la login.

BEAN
Per creare la connessione verranno usati l’AppId e l’AppSecret, indicati nelle basic info della nostra app su facebook.

package com;

import java.util.Properties;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.brickred.socialauth.Profile;
import org.brickred.socialauth.SocialAuthConfig;
import org.brickred.socialauth.SocialAuthManager;
import org.brickred.socialauth.exception.SocialAuthException;
import org.springframework.stereotype.Component;

@Component
@ManagedBean
@SessionScoped
public class FacebookBean {
private String FACEBOOK_APP_ID = "...............";
private String FACEBOOK_APP_SECRET = ".................";
private SocialAuthManager manager;
private String originalURL;
private String providerID;
private Profile profile;

public void socialConnect() throws Exception {
// Put your keys and secrets from the providers here
Properties props = System.getProperties();
props.put("graph.facebook.com.consumer_key", FACEBOOK_APP_ID);
props.put("graph.facebook.com.consumer_secret", FACEBOOK_APP_SECRET);
// Define your custom permission if needed
props.put("graph.facebook.com.custom_permissions", "publish_stream,email,user_birthday,user_location,offline_access");
// Initiate required components
SocialAuthConfig config = SocialAuthConfig.getDefault();
config.load(props);
manager = new SocialAuthManager();
manager.setSocialAuthConfig(config);
// 'successURL' is the page you'll be redirected to on successful login
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
// String successURL = externalContext.getRequestContextPath() + "socialLoginSuccess.xhtml";
String successURL = "http://localhost:8080/"+ externalContext.getRequestContextPath()+"/socialLoginSuccess.xhtml";
System.out.println("successURL:" + successURL);
String authenticationURL = manager.getAuthenticationUrl("facebook", successURL);
FacesContext.getCurrentInstance().getExternalContext().redirect(authenticationURL);
}

}
Con  la property “graph.facebook.com.custom_permissions” si chiede all’utente il permesso di accedere delle  sue determinate informazioni. In base a quello che si vuole fare c’è bisogno di determinati permessi (o autorizzazioni). Qui una lista completa dei possibili permessi.
Prestare attenzione alla successURL, l’url a cui si viene reindirizzati dopo aver effettuato l’accesso a facebook. Se tale URL non esiste facebook lancerà la seguente eccezione:
{
   "error": {
"message": "redirect_uri isn't an absolute URI. Check RFC 3986.",
"type": "OAuthException",
"code": 191
}
}







N.B. nel log del server apparrà l’errore:

Server returned HTTP response code: 400 for URL:

per capire meglio quale è il vero errore, prendere l’URL e copiarla nel browser.

PAGINA LOGIN E SUCCESS
Nella pagina di login è presente un semplice tasto che richiama l’action su definita

login.xhtml

<!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:ice="http://www.icesoft.com/icefaces/component"
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>
<h:commandButton value="LOGIN" action="#{facebookBean.socialConnect}" />
</h:form>
</h:body>
</html>

socialLoginSuccess.xhtml

<?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:h="http://java.sun.com/jsf/html">
<h:head>
<title>Social login success</title>
</h:head>
<h:body>
LOGIN SUCCESS
</h:body>
</html>

ESECUZIONE
Andare sull’url “http://localhost:8080/ProvaJSF/login.jsf”:

cliccando sul tasto LOGIN si viene reindirizzati su facebook che ci chiederà se congediamo i permessi su definiti, una volta cliccato su OK si verrà rimandati nell’URL di success:

Convert Request SOAP to String

  Per convertire una request XML in String usiamo il marshal di JAXB:

  public void printXml(Object obj) {
try {
StringWriter sb = new StringWriter();
JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(obj, sb);
log.info(sb.toString());
}
catch (Exception e) {
e.printStackTrace();

// catch exception
}
catch (Throwable e) {
e.printStackTrace();

// catch exception
}
}

Nella request SOAP che si vuole stampare, aggiungere il tag:
@XmlRootElement
dove viene definita la classe

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Contact", propOrder = {
"codecontactid",
})
public class Contact......................

PrimeFaces – multipartrequest “grave: error in parsing fileupload request”

Eccezione lanciata durante il fileUpload con primefaces:

<p:fileUpload
fileUploadListener="#{userBean.handleFileUpload}"
mode="advanced" dragDropSupport="false" fileLimit="30"
allowTypes="/(.|/)(gif|jpe?g|png|avi)$/" auto="true" label="#{msg['label.getMediaObj']}"
update="messages commentlist" />

Per alcuni file, l’upload funzionava correttamente, chiamando userBean.handleFileUpload, per altri no.
Una delle possibili cause, almeno nel mio caso lo è stata, è la grandezza del file indicata in web.xml, tramite
il parametro thresholdSize:

 <filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>
org.primefaces.webapp.filter.FileUploadFilter
</filter-class>
<init-param>
<param-name>thresholdSize</param-name>
<param-value>10000</param-value>
</init-param>
</filter>

Quindi se il file ha una grandezza superiore a quella indicata in thresholdsize viene lanciata l’eccezione su citata. Di seguito la sintassi per definire questo parametro:

<init-param>
<description>
Set the size limit for uploaded files. Format: 10 - 10
bytes 10k - 10 KB 10m - 10 MB 1g - 1 GB
</description>
<param-name>uploadMaxFileSize</param-name>
<param-value>100m</param-value>
</init-param>

Maven – How To Client WebService With CXF

Per generare un client di un web service, tramite Maven, è molto utile e veloce questo plugin della Apache CXF:

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>mavenProva</groupId>
<artifactId>mavenProva</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>
<cxf.version>2.2.3</cxf.version>
</properties>
<build>
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${cxf.version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${project.build.directory}/generated/cxf</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>${basedir}/src/main/resources/FileWSDL.wsdl</wsdl>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>${cxf.version}</version>
</dependency>
</dependencies>
</project>

JSF2 – Ajax rendering of content outside form

Per aggiornare un compontente tramite ajax si utilizza in jsf si utilizza il tag f:ajax:

<f:ajax render=”<nomeComponente>” />

ma quando il compente è fuori dal form si deve utilizzare la sintassi

render=”<nomeForm>:<nomeComponente>”

vediamo un esempio

UserBean.java

package com;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

@ManagedBean
@SessionScoped
public class UserBean {
 private String result = "Hello world";

 public void updateResult() {

  result = "Ciao Mondo";

 }

 public String getResult() {
  return result;
 }

 public void setResult(String result) {
  this.result = result;
 } 
 
 

}



ajaxoutform.xhtml
<!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 id="form">
  <h:commandButton id="button" action="#{userBean.updateResult}">
   <f:ajax render=":otherform:result" />
  </h:commandButton>
 </h:form>
 <h:form id="otherform">
  <h:outputText id="result" value="#{userBean.result}" />
 </h:form>

</h:body>
</html>



eseguendo la pagina si ha:



cliccando il tasto, il testo si aggiorna


JSF2 – p:remoteCommand Example Chat Primefaces

p:remoteCommand chiama un metodo di un backing bean (tramite actionlistener) e, fondamentalemnte, fa da trigger ad uno javascript(oncomplete):

<p:remoteCommand name="nextMessage"
actionListener="#{messageBean.firstUnreadMessage}"
oncomplete="javascript:updateMessages(xhr, status, args);" />

Back-End

MessageBean.java

package com;

import java.io.Serializable;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import org.primefaces.context.RequestContext;


@ManagedBean
@ViewScoped
public class MessageBean implements Serializable {



private final List messages;
private Date lastUpdate;
private Message message;

/**
* Creates a new instance of MessageBean
*/
public MessageBean() {
messages = Collections.synchronizedList(new LinkedList());
lastUpdate = new Date(0);
message = new Message();
}

public Date getLastUpdate() {
return lastUpdate;
}

public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}

public Message getMessage() {
return message;
}

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


public void firstUnreadMessage(ActionEvent evt) {
RequestContext ctx = RequestContext.getCurrentInstance();

ctx.addCallbackParam("ok", message!=null);
if(message==null)
return;

lastUpdate = message.getDateSent();

ctx.addCallbackParam("user", message.getUser());
ctx.addCallbackParam("dateSent", new Date().toString());
ctx.addCallbackParam("text", message.getMessage());

}

}

Message.java
package com;
import java.io.Serializable;

public class Message implements Serializable {
private Date dateSent;
private String user;
private String message;

public Date getDateSent() {
return dateSent;
}

public void setDateSent(Date dateSent) {
this.dateSent = dateSent;
}

public String getMessage() {
return message;
}

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

public String getUser() {
return user;
}

public void setUser(String user) {
this.user = user;
}
}

Front-End

Chat1.xhtml
<?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:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Chat test!</title>
<script type="text/javascript"
src="#{facesContext.externalContext.requestContextPath}/util.js"></script>

</h:head>

<h:body>
<h:form prependId="false">
<h:panelGrid columns="2">
Name: <p:inputText value="#{messageBean.message.user}" />
Text: <p:inputText
value="#{messageBean.message.message}" />
<p:commandButton type="reset" value="Clear" />
<p:commandButton value="Send!"
actionListener="#{messageBean.sendMessage}" onclick="nextMessage();" />
</h:panelGrid>
<p:remoteCommand name="nextMessage"
actionListener="#{messageBean.firstUnreadMessage}"
oncomplete="javascript:updateMessages(xhr, status, args);" />
</h:form>

<hr />
<h3>Live chat</h3>
<div id="chat"></div>
</h:body>
</html>


util.js

function updateMessages(xhr, status, args) {
if(!args.ok) return;
$('#chat').append('<div class="msg">[' +args.dateSent+ '] <strong>'+args.user+'</strong>: '+args.text+'</div>');
}

Esecuzione

lanciando da browser l’url
http://localhost:8080/JSFProject/faces/chat1.xhtml

si ha una simulazione di chat 


Java StringTokenizer Example

La classe StringTokenizer è usata per dividere una stringa in varie sottostringhe, delimitate da un carattere speciale.

1° Esempio – Lettura Stringa

Divisione di una stringa con il carattere speciale blank e la virgola.

StringTokenizer.java
package com;

import java.util.StringTokenizer;

public class StringTokenizerTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  String str = "prova1 prova2 , test1 test2, prova3 test3";
  StringTokenizer st = new StringTokenizer(str);
 
  System.out.println("---- Split by space ------");
  while (st.hasMoreElements()) {
   System.out.println(st.nextElement());
  }
 
  System.out.println("---- Split by comma ',' ------");
  StringTokenizer st2 = new StringTokenizer(str, ",");
 
  while (st2.hasMoreElements()) {
   System.out.println(st2.nextElement());
  }

 }

}


output:
2 Esempio: Lettura File CVS
Le stringhe da splittare sono lette da un file cvs.
friends.cvs
prova| prova1 | prova2| prova3
test | test1  | test2 | test3
CaricaFile.java
package com;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

public class CaricaFile {

 public static void caricaUsers() throws IOException {
  BufferedReader reader = new BufferedReader(new FileReader(
    "D:\friends.txt"));
  String line = reader.readLine();
  while (line != null) {

  StringTokenizer stRecord = new StringTokenizer(line, "|");
   while (stRecord.hasMoreTokens()) {
    String record = stRecord.nextToken();
    System.out.print(record + "  ");
   }
   System.out.println("");
   line = reader.readLine();
  }
 }

 public static void main(String[] args) throws FileNotFoundException,
   IOException {
  caricaUsers();
 }
}


Output:

HQL – Like parameter

Hql con un parametro in input da mettere nella like con le percentuali:

String querySql = "select u from Users u  ";
String whereSql = whereSql + " u.currentLocation like :currentLocation";
querySql = querySql + whereSql;

Query q = this.getEntityManager().createQuery(querySql);
q.setParameter("currentLocation", '%'+user.getCurrentLocation()+'%');