PrimeFaces Upload p:graphicImage BUG

Nel seguente codice si aggiorna l’immagine dopo aver effettuato l’upload di un file:

<h:form id="faqAddUpdateForm">
<p:fileUpload
fileUploadListener="#{userBean.uploadPhotoProfile}"
mode="advanced" dragDropSupport="false"
auto="true" label="#{msg['label.getMediaObj']}"
update="commentlist" />

<h:panelGroup id="commentlist">
<h:outputLabel id="test" value="#{userBean.images}" style="padding-left:100px"/>
<p:graphicImage value="/GetMedia?photoProfile=y" width="200px" />
</h:panelGroup>
</h:form>

NOTA BENE in teoria dovrebbe funzionare così ma, per un bug presenta almeno in primefaces 4.0, il panelgroup viene refreshato  ma l’immagine non viene aggiornata. Per aggirare il problema bisogna inserire un attributo di p:graphicimage che varia di valore durante l’aggiornamento, in questo caso basta aggiungere il seguente attributo:

<p:graphicImage value="/GetMedia?photoProfile=y"  title="#{userBean.images}" width="200px"    />


SocialAuth execute GraphApi Fql Facebook

Effettuare il  login come indicato qui
Una volta che si ha a disposizione una istanza della classe AuthProvider, per eseguire una query su GraphApi basta richiamare il metodo api(……) della classe su menzionata. Esempio:

AuthProvider provider = manager.connect(SocialAuthUtil.getRequestParametersMap(request));

Response resp = provider.api("https://graph.facebook.com/me", MethodType.GET.toString(), null, null, null); System.out.println("print response:" + resp.getResponseBodyAsString(Constants.ENCODING));

per eseguire direttamente una query Fql basta inserire quest’URL:

https://graph.facebook.com/fql?q=query fql

al posto di

https://graph.facebook.com/me

JSOUP parsing facebook page

Facebook, quando si cerca di are il parsing, con JSOUP in questo caso, di una sua pagina, non restituisce la pagina cosi come la si vede ma ci da la pagina di login. Osservando un pò meglio, in realtà le informazioni da noi richieste ci sono, ma sono nei commenti. Il seguente codice permette di ricreare la pagina da noi richiesta, potendo cosi fare il parsing, dai commenti restituiti:

      Document docTotal = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36")
.referrer("http://www.google.com").followRedirects(true)
.execute().parse();

      final StringBuffer commentData = new StringBuffer();
docTotal.traverse(new NodeVisitor() {
public void head(Node node, int depth) {
if (node instanceof Comment) {
Comment comment = (Comment) node;
commentData.append(comment.getData());
}
}
public void tail(Node node, int depth) {
}
});

docTotal contiene le informazioni da noi richieste

eclipselink @OneToMany delete orphan

In eclipseLink  per rimuovere le entity orphan basta aggiungere, oltre al cascade ALL,  la annotation  @PrivateOwned:

@OneToMany(mappedBy="user1", cascade=CascadeType.ALL)
@PrivateOwned
private List<UsersSelectedFromUser> usersSelectedFromUsers1;

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>