How to print one val to PartitionBy - scala

I have one problem in Apache Spark GraphX, i tried to partition one graph with this method in the main:
graph.partitionBy(HDRF, 128)
HDRF is a method to do partitioning, I would like to print a val that is inside it, I tried to print but it does not print anything
/EDIT/
package app
import org.apache.spark.graphx._
import org.apache.spark._
import org.apache.spark.rdd.RDD
/**
* Main del sistema
*/
object Main{
def main(args: Array[String]) {
val sc = new SparkContext(new SparkConf().setMaster("local").setAppName("HDRF"))
// mostra solo i log in caso di errore
sc.setLogLevel("ERROR")
//modifico il file di testo preso in ingresso
val edges:RDD[Edge[String]]=
sc.textFile("data/u1.base").map{ line =>
val fields= line.split("\t")
Edge(fields(0).toLong,fields(1).toLong,fields(2))
}
val graph: Graph[Any,String] =Graph.fromEdges(edges,"defaultProperty")
graph.partitionBy(HDRF,128)
}
}
.
package app
import org.apache.spark.graphx._
import scala.collection.concurrent.TrieMap
object HDRF extends PartitionStrategy{
private var init=0; //lo puoi usare per controllare una fase di inizializzazione che viene eseguita solo la prima volta
private var partitionsLoad:Array[Long] = Array.empty[Long] //carico (numero di archi) di ogni partizione
private val vertexIdListPartitions: TrieMap[Long, List[Long]] = TrieMap() //lista di partizioni associate a ogni vertice
private val vertexIdEdges: TrieMap[Long, Long] = TrieMap() //grado di ogni vertice
private var edges = 0
private var sum :Long= 0
override def getPartition(src:VertexId,dst:VertexId,numParts:Int): PartitionID ={
var valoreMax:Long =Int.MaxValue
var partScarica:Int = -1
var c:Int = 0
if(init==0){
init=1
partitionsLoad=Array.fill[Long](numParts)(0)
}
//AGGIORNA IL GRADO CONOSCIUTO DEI VERTICI src E dst NELLA VARIABILE vertexIdEdges
vertexIdEdges(src)=vertexIdEdges(src)+1
vertexIdEdges(dst)=vertexIdEdges(dst)+1
sum=vertexIdEdges(src) + vertexIdEdges(dst)
//PARTIZIONA IL GRAFO
if((!vertexIdListPartitions.contains(src))&&(!vertexIdListPartitions.contains(dst))){
//NESSUNO DEI DUE VERTICI E' STATO MAI INSERITO IN QUALCHE PARTIZIONE
//SCELGO LA PARTZIIONE PIU' SCARICA E LI ASSEGNO A QUELLA
while(c==numParts){
if(partitionsLoad(c)<valoreMax){
valoreMax=partitionsLoad(c)
partScarica=c
}
c=c+1
}
if(partScarica != -1) {
partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
vertexIdListPartitions(partScarica).union(List(src, dst))
}
return partScarica
}else if(((vertexIdListPartitions.contains(src))&&(!vertexIdListPartitions.contains(dst)))||((!vertexIdListPartitions.contains(src))&&(vertexIdListPartitions.contains(dst)))){
//UNO SOLO DEI DUE VERTICI E' GIA' PRESENTE IN ALMENO UNA PARTIZIONE
if((vertexIdListPartitions.contains(src))&&(!vertexIdListPartitions.contains(dst))){
//SI TRATTA DI src
//SCELGO LA PARTIZIONE PIU' SCARICA TRA QUELLE IN CUI E' PRESENTE src E CI REPLICO dst
while(c==numParts){
if(partitionsLoad(c)<valoreMax){
if(vertexIdListPartitions(c).contains(src)) {
valoreMax = partitionsLoad(c)
partScarica = c
}
}
c=c+1
}
if(partScarica != -1) {
partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
vertexIdListPartitions(partScarica).union(List(dst))
}
}else{
//SI TRATTA DI dst
//SCELGO LA PARTZIIONE PIU' SCARICA TRA QUELLE IN CUI E' PRESENTE dst E CI REPLICO src
while(c==numParts){
if(partitionsLoad(c)<valoreMax){
if(vertexIdListPartitions(c).contains(src)) {
valoreMax = partitionsLoad(c)
partScarica = c
}
}
c=c+1
}
if(partScarica != -1) {
partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
vertexIdListPartitions(partScarica).union(List(src))
}
}
}else if(!vertexIdListPartitions(src).intersect(vertexIdListPartitions(dst)).isEmpty){
//ENTRAMBI I VERTICI SONO PRESENTI IN DIVERSE PARTIZIONI ED ESISTE UNA INTERSEZIONE DEI SET NON NULLA (CIOE' ESISTE ALMENO UNA PARTIZIONE CHE LI CONTIENE ENTRAMBI)
//SCELGO NELL'INTERSEZIONE DEI SET LA PARTIZIONE PIU' SCARICA
while(c==numParts) {
if (partitionsLoad(c) < valoreMax) {
if (vertexIdListPartitions(c).contains(src) && vertexIdListPartitions(c).contains(dst)) {
valoreMax = partitionsLoad(c)
partScarica = c
}
}
c = c + 1
}
if(partScarica != -1) {
partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
vertexIdListPartitions(partScarica).union(List(src))
}
}else {
//ENTRAMBI I VERTICI SONO PRESENTI IN DIVERSE PARTIZIONI MA L'INTERSEZIONE DEI SET E' NULLA (CIOE' NON ESISTE ALCUNA PARTIZIONE CHE LI CONTIENE ENTRAMBI)
if((vertexIdEdges(src))>=(vertexIdEdges(dst))){
//SCELGO TRA LE PARTIZIONI A CUI E' ASSEGNATO dst QUELLA PIU' SCARICA E CI COPIO src
while(c==numParts){
if(partitionsLoad(c)<valoreMax){
if(vertexIdListPartitions(c).contains(dst)) {
valoreMax = partitionsLoad(c)
partScarica = c
}
}
c=c+1
}
if(partScarica != -1) {
partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
vertexIdListPartitions(partScarica).union(List(src))
}
}else{
//SCELGO TRA LE PARTIZIONI A CUI E' ASSEGNATO src QUELLA PIU' SCARICA E CI COPIO dst
while(c==numParts){
if(partitionsLoad(c)<valoreMax){
if(vertexIdListPartitions(c).contains(src)) {
valoreMax = partitionsLoad(c)
partScarica = c
}
}
c=c+1
}
if(partScarica != -1) {
partitionsLoad(partScarica) = partitionsLoad(partScarica) + 1
vertexIdListPartitions(partScarica).union(List(dst))
}
}
}
edges=edges+1
if(edges==80000) {
print(sum)
}
return partScarica
}
}
I need to print sum, but I don't understand why it does not appear.

partitionBy, like many Graph functions, is a lazily-evaluated operation that generates a new Graph object, but doesn't actually compute that Graph until it's necessary - i.e. until some action is performed on the result (e.g. counting, persisting, or collecting it).
Using a simpler example we can see that if we act on the result, these prints will be visible:
object SimpleExample extends PartitionStrategy {
override def getPartition(src: VertexId, dst: VertexId, numParts: PartitionID): PartitionID = {
println("partitioning!")
numParts
}
}
val result = graph.partitionBy(SimpleExample, 128) // nothing printed so far...
result.edges.count() // now that we act on the result,
// we see "paritioning!" printed (several times).
NOTE that printing from a PartitionStrategy (or any transformation function passed to Spark to be performed on an RDD, a Graph, or a Dataset) is not too helpful: these functions are executed on the worker nodes, hence these prints will be "scattered" in outputs of different processes on different machines, and would probably NOT be visible in the output of the driver application (your main function).

Related

Valid value range is empty: 0

my function search for a specifies pharmacy's and add these to my List of Map but my list still empty in the return
Future<List<Map>> geto(String s) async{
var user_position = await _locationService1.GetCurrentPosition();
print(user_position.latitude) ;
print(user_position.longitude) ;
List <Map> pp =[] ;
await FirebaseFirestore.instance.collection('pharma')
.get().then((value) => {
value.docs.forEach((pharma) async{
print(pharma.id) ;
await FirebaseFirestore.instance.collection('pharma')
.doc(pharma.id)
.collection('med')
.get().then((med) => {
med.docs.forEach((element) async{
if(element['qtc'] >0 && element.id.toString().toLowerCase()==s.toLowerCase()){
print(element.data()) ; // printer le nom de med
print(pharma['nom']) ; // printer la pharma de med avant
// print(pharma['latitude']) ; // acceder a un champ de pharma
var d = Geolocator.distanceBetween(
(pharma)['latitude'],
(pharma)['longitude'],
user_position.latitude,
user_position.longitude,
);
pp.add({'id' : pharma.id , 'distance' : d}) ;
print('Cest la list felicitation $pp') ;
}
})
});
})
})
;
print("--------------------...........................${pp.length}") ;
return pp ;
}
-I tried Future Builder and pass the function as the futur argument but it's didn't work and return a red screen which tell me that the list is empty

org.apache.shiro.UnavailableSecurityManagerException

I have a big problem on my project. I have looked everywhere in internet but nothing was found. So this is my Bean:
#Named(value = "loginBean")
#SessionScoped
public class LoginBean implements Serializable {
#EJB
private RoleServiceLocal rsbl;
#EJB
private ProfilServiceLocal psbl;
#EJB
private UtilisateurServiceLocal usbl;
private String username;
private String password;
private String newPass;
private String retapPass;
private String lastPass;
private String us = "";
private String per = "";
private String question;
private String recupResponse = "";
private String reponse;
private String creerDoleance, modifierDoleance,
creerficheExec, modifierficheExec, creerRapportTest, modifierRapportTest, fiche, direction, creerDirection, modifierDirection,
creerProduit, modifierProduit, creerClient, modifierClient, creerVersion, modifierVersion, technicien, creerTechnicien, modifierTechnicien,
creerMAJ, modifierMAJ, MAJ, doleance, ficheExec, RapportTest, produit, client, version, technique, creerTechnique, modifierTechnique,
profil, creerProfil, modifierProfil, associerProfil, associerRole, activerCompte, desactiverCompte, securite, administration;
private Utilisateur user;
private Utilisateur utilisateur;
private boolean remember = false;
private boolean admin;
#EJB //HUM Tu m'as vraiment dérangé.plus de 24h avant de me rappeller de te mettre.hum
private ProfilRoleServiceLocal prsbl;
public LoginBean() {
user = new Utilisateur();
utilisateur = new Utilisateur();
}
#PostConstruct
public void init() {
List<Role> all = rsbl.getAll();
if (all.isEmpty()) {
this.rsbl.saveOne(new Role(1, "Créer une Doléance", "doleance"));
this.rsbl.saveOne(new Role(2, "Modifier Doléance", "doleance"));
this.rsbl.saveOne(new Role(3, "Créer une fiche", "fiche"));
this.rsbl.saveOne(new Role(4, "Modifier une fiche", "fiche"));
this.rsbl.saveOne(new Role(5, "Créer une fiche d'exécution", "fiche d'exécution"));
this.rsbl.saveOne(new Role(6, "Modifier fiche d'exécution", "fiche d'exécution"));
this.rsbl.saveOne(new Role(7, "Créer une rapport de test", "rapport de test"));
this.rsbl.saveOne(new Role(8, "Modifier une rapport de test", "rapport de test"));
this.rsbl.saveOne(new Role(9, "Créer un produit", "produit"));
this.rsbl.saveOne(new Role(10, "Modifier un produit", "produit"));
this.rsbl.saveOne(new Role(11, "Créer un client", "client"));
this.rsbl.saveOne(new Role(12, "Modifier un client", "client"));
this.rsbl.saveOne(new Role(13, "Créer une direction", "direction"));
this.rsbl.saveOne(new Role(14, "Modifier une direction", "direction"));
this.rsbl.saveOne(new Role(15, "Créer une version", "version"));
this.rsbl.saveOne(new Role(16, "Modifier une version", "version"));
this.rsbl.saveOne(new Role(17, "Créer une mise à jour", "mise à jour"));
this.rsbl.saveOne(new Role(18, "Modifier une mise à jour", "mise à jour"));
this.rsbl.saveOne(new Role(19, "Créer une solution technique", "solution technique"));
this.rsbl.saveOne(new Role(20, "Modifier une solution technique", "solution technique"));
this.rsbl.saveOne(new Role(21, "Modifier planning", "planning"));
this.rsbl.saveOne(new Role(22, "Créer profil", "profil"));
this.rsbl.saveOne(new Role(23, "Modifier profil", "profil"));
this.rsbl.saveOne(new Role(24, "Créer securite", "securite"));
this.rsbl.saveOne(new Role(25, "Associer profil", "role"));
this.rsbl.saveOne(new Role(26, "Associer role", "role"));
this.rsbl.saveOne(new Role(27, "Activer compte", "compte"));
this.rsbl.saveOne(new Role(28, "Désactiver compte", "compte"));
this.rsbl.saveOne(new Role(29, "Modifier securite", "securite"));
}
List<Profil> alle = psbl.getAll();
if (alle.isEmpty()) {
this.psbl.saveOne(new Profil(1, "Administrateur", "administrer"));
this.psbl.saveOne(new Profil(2, "Super Admin", "Super admin"));
this.psbl.saveOne(new Profil(3, "Directeur", "directeur"));
this.psbl.saveOne(new Profil(4, "Responsable", "Responsable"));
this.psbl.saveOne(new Profil(5, "Collaborateur", "collaborer"));
this.psbl.saveOne(new Profil(6, "Technicien", "technicien"));
}
List<Profil> profils = psbl.getBy("nom", "Rohastrick");
UserTransaction tx = TransactionManager.getUserTransaction();
if (profils.isEmpty()) {
try {
tx.begin();
this.psbl.saveOne(new Profil(1, "Rohastrick", "rot2rick"));
List<Role> roles = this.rsbl.getAll();
for (Role role : roles) {
ProfilRole pr = new ProfilRole();
pr.setRole(role);
pr.setProfil(psbl.getOneBy("nom", "Rohastrick"));
prsbl.saveOne(pr);
}
Utilisateur ut = new Utilisateur();
ut.setNom("Rot2rick");
ut.setLogin("Rohastrick");
ut.setPass(new Sha256Hash("helen#").toHex());
ut.setEmail("admin");
ut.setTelephone("admin");
ut.setProfil(psbl.getOneBy("nom", "Rohastrick"));
ut.setActif(true);
usbl.saveOne(ut);
tx.commit();
} catch (Exception e) {
try {
tx.rollback();
} catch (IllegalStateException ex) {
Logger.getLogger(FicheBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(FicheBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (SystemException ex) {
Logger.getLogger(FicheBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (AuthenticationException ex) {
ex.printStackTrace();
}
}
}
}
public boolean checkIntConnection() {
boolean status = false;
Socket sock = new Socket();
InetSocketAddress address = new InetSocketAddress("www.google.com", 80);
try {
sock.connect(address, 3000);
if (sock.isConnected()) {
status = true;
}
} catch (Exception e) {
} finally {
try {
sock.close();
} catch (Exception e) {
}
}
return status;
}
public void login() throws IOException {
System.out.println("Test Roler");
try {
System.out.println("user=" + username);
System.out.println("ps=" + password);
user = usbl.getOneBy("login", username);
if (user != null) {
if (user.isActif() == false) {
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('error').show();");
username = "";
return;
}
}
if (user != null) {
boolean test = new Sha256Hash("admin").toHex().equals(user.getPass());
if (test && user.isActif() == false) {
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dialogpasse').show();");
return;
}
}
UsernamePasswordToken token = new UsernamePasswordToken(username.trim(), password.trim());
token.setRememberMe(false);
try {
SecurityUtils.getSubject().login(token);
} catch (Exception e) {
System.out.println(""+ e.getMessage());
}
Subject subject = EntityRealm.getSubject();
if (!username.equalsIgnoreCase("admin")) {
if (subject.hasRole("Créer une fiche") || subject.hasRole("Modifier une fiche")
|| subject.hasRole("Créer une fiche d'exécution") || subject.hasRole("Modifier une fiche d'exécution")
|| subject.hasRole("Créer une Doléance") || subject.hasRole("Modifier une Doléance")
|| subject.hasRole("Créer un rapport de test") || subject.hasRole("Modifier un rapport de test")
|| subject.hasRole("Créer un produit") || subject.hasRole("Modifier un produit")
|| subject.hasRole("Créer une version à un produit") || subject.hasRole("Modifier une version du produit")
|| subject.hasRole("Créer une mise à jour") || subject.hasRole("Modifier une mise à jour")
|| subject.hasRole("Créer un Client") || subject.hasRole("Modifier Client")
|| subject.hasRole("Créer un Technicien") || subject.hasRole("Modifier un Technicien")
|| subject.hasRole("Créer une Solution Technique") || subject.hasRole("Modifier une Solution Technique")
|| subject.hasRole("Créer une Direction") || subject.hasRole("Modifier une Direction")) {
this.administration = "true";
} else {
this.administration = "false";
}
//connexion();
if (subject.hasRole("Créer une fiche")
|| subject.hasRole("Modifier fiche") || subject.hasRole("Modifier fiche")
|| subject.hasRole("Supprimer fiche")) {
this.fiche = "true";
} else {
this.fiche = "false";
}
if (subject.hasRole("Créer securite") || subject.hasRole("Modifier securite")
|| subject.hasRole("Créer profil") || subject.hasRole("Modifier profil")
|| subject.hasRole("Creer securite") || subject.hasRole("Associer profil")
|| subject.hasRole("Associer role") || subject.hasRole("Activer compte")
|| subject.hasRole("Désactiver compte")) {
this.securite = "true";
} else {
this.securite = "false";
}
if (subject.hasRole("Créer une Doléance")) {
this.creerDoleance = "true";
} else {
this.creerDoleance = "false";
}
if (subject.hasRole("Modifier une Doléance")) {
this.modifierDoleance = "true";
this.doleance = "true";
} else {
this.modifierDoleance = "false";
this.doleance = "false";
}
if (subject.hasRole("Créer un rapport de test") || subject.hasRole("Modifier un rapport de test")) {
this.RapportTest = "true";
} else {
this.RapportTest = "false";
}
if (subject.hasRole("Créer une fiche d'exécution") || subject.hasRole("Modifier une fiche d'exécution")) {
this.ficheExec = "true";
} else {
this.ficheExec = "false";
}
if (subject.hasRole("Créer une fiche d'exécution")) {
this.creerficheExec = "true";
} else {
this.creerficheExec = "false";
}
if (subject.hasRole("Modifier une fiche d'exécution")) {
this.modifierficheExec = "true";
} else {
this.modifierficheExec = "false";
}
if (subject.hasRole("Créer un rapport de test") || subject.hasRole("Modifier un rapport de test")) {
this.RapportTest = "true";
} else {
this.RapportTest = "false";
}
if (subject.hasRole("Créer un rapport de test")) {
this.creerRapportTest = "true";
} else {
this.creerRapportTest = "false";
}
if (subject.hasRole("Modifier un rapport de test")) {
this.modifierRapportTest = "true";
} else {
this.modifierRapportTest = "false";
}
if (subject.hasRole("Créer un produit") || subject.hasRole("Modifier un produit")) {
this.produit = "true";
} else {
this.produit = "false";
}
if (subject.hasRole("Créer un produit")) {
this.creerProduit = "true";
} else {
this.creerProduit = "false";
}
if (subject.hasRole("Modifier un produit")) {
this.modifierProduit = "true";
} else {
this.modifierProduit = "false";
}
if (subject.hasRole("Créer un technicien") || subject.hasRole("Modifier un technicien")) {
this.technicien = "true";
} else {
this.technicien = "false";
}
if (subject.hasRole("Créer un technicien")) {
this.creerTechnicien = "true";
} else {
this.creerTechnicien = "false";
}
if (subject.hasRole("Modifier un technicien")) {
this.modifierTechnicien = "true";
} else {
this.modifierTechnicien = "false";
}
if (subject.hasRole("Créer un client") || subject.hasRole("Modifier un client")) {
this.client = "true";
} else {
this.client = "false";
}
if (subject.hasRole("Créer un client")) {
this.creerClient = "true";
} else {
this.creerClient = "false";
}
if (subject.hasRole("Modifier un client")) {
this.modifierClient = "true";
} else {
this.modifierClient = "false";
}
if (subject.hasRole("Créer un client") || subject.hasRole("Modifier un client")) {
this.client = "true";
} else {
this.client = "false";
}
if (subject.hasRole("Créer un client")) {
this.creerClient = "true";
} else {
this.creerClient = "false";
}
if (subject.hasRole("Modifier un client")) {
this.modifierClient = "true";
} else {
this.modifierClient = "false";
}
if (subject.hasRole("Créer une solution technique") || subject.hasRole("Modifier une solution technique")) {
this.technique = "true";
} else {
this.technique = "false";
}
if (subject.hasRole("Créer une solution technique")) {
this.creerTechnique = "true";
} else {
this.creerTechnique = "false";
}
if (subject.hasRole("Modifier une solution technique")) {
this.modifierTechnique = "true";
} else {
this.modifierTechnique = "false";
}
if (subject.hasRole("Créer une direction") || subject.hasRole("Modifier une direction")) {
this.direction = "true";
} else {
this.direction = "false";
}
if (subject.hasRole("Créer une direction")) {
this.creerDirection = "true";
} else {
this.creerDirection = "false";
}
if (subject.hasRole("Modifier une direction")) {
this.modifierDirection = "true";
} else {
this.modifierDirection = "false";
}
if (subject.hasRole("Créer un produit") || subject.hasRole("Modifier un produit")) {
this.produit = "true";
} else {
this.produit = "false";
}
if (subject.hasRole("Créer un produit")) {
this.creerProduit = "true";
} else {
this.creerProduit = "false";
}
if (subject.hasRole("Modifier un produit")) {
this.modifierProduit = "true";
} else {
this.modifierProduit = "false";
}
if (subject.hasRole("Créer une mise à jour") || subject.hasRole("Modifier une mise à jour")) {
this.MAJ = "true";
} else {
this.MAJ = "false";
}
if (subject.hasRole("Créer une mise à jour")) {
this.creerMAJ = "true";
} else {
this.creerMAJ = "false";
}
if (subject.hasRole("Modifier une mise à jour")) {
this.modifierMAJ = "true";
} else {
this.modifierMAJ = "false";
}
if (subject.hasRole("Créer un client") || subject.hasRole("Modifier un client")) {
this.client = "true";
} else {
this.client = "false";
}
if (subject.hasRole("Créer un client")) {
this.creerClient = "true";
} else {
this.creerClient = "false";
}
if (subject.hasRole("Modifier un client")) {
this.modifierClient = "true";
} else {
this.modifierClient = "false";
}
if (subject.hasRole("Créer un profil") || subject.hasRole("Modifier un profil")) {
this.profil = "true";
} else {
this.profil = "false";
}
if (subject.hasRole("Créer un profil")) {
this.creerProfil = "true";
} else {
this.creerProfil = "false";
}
if (subject.hasRole("Modifier un profil")) {
this.modifierProfil = "true";
} else {
this.modifierProfil = "false";
}
if (subject.hasRole("Associer un profil")) {
this.associerProfil = "true";
} else {
this.associerProfil = "false";
}
if (subject.hasRole("Associer role")) {
this.associerRole = "true";
} else {
this.associerRole = "false";
}
if (subject.hasRole("Activer un compte")) {
this.activerCompte = "true";
} else {
this.activerCompte = "false";
}
if (subject.hasRole("Désactiver un compte")) {
this.desactiverCompte = "true";
} else {
this.desactiverCompte = "false";
}
}
SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(Faces.getRequest());
Faces.redirect(savedRequest != null ? savedRequest.getRequestUrl() : "index.xhtml");
} catch (AuthenticationException e) {
e.printStackTrace();
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"Nom d'utlisateur ou mot de passe incorrect", "");
FacesContext.getCurrentInstance().addMessage("", mf);
}
//return "index";
}
public String currentUser() {
Utilisateur user = EntityRealm.getUser();
if (user == null) {
return "Admin";
}
return EntityRealm.getUser().getLogin();
}
public Date sessionTime() {
return EntityRealm.getSubject().getSession().getStartTimestamp();
}
public void logout() {
try {
EntityRealm.getSubject().logout();
Faces.redirect("login.xhtml");
username = "";
} catch (IOException ex) {
}
}
public void mot() {
System.out.println("test");
}
public void modifierPasse() {
System.out.println("test");
System.out.println(newPass);
System.out.println(retapPass);
if (newPass.trim().equals(retapPass.trim())) {
user.setPass(new Sha256Hash(newPass.trim()).toHex());
user.setQuestion(question);
user.setReponse(reponse);
usbl.updateOne(user);
question = "";
reponse = "";
RequestContext.getCurrentInstance().execute("PF('dialogpasse').hide();");
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Mot de passe corriger", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
} else {
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"Les mots de passe ne concorde pas", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
}
}
public void modifierPasse2() {
if (new Sha256Hash(lastPass).toHex().equals(EntityRealm.getUser().getPass())) {
if (newPass.trim().equals(retapPass.trim())) {
if (new Sha256Hash(newPass).toHex().equals(EntityRealm.getUser().getPass())) {
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"Tapez un mot de passe différent de l'ancien", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
newPass = "";
lastPass = "";
retapPass = "";
} else {
EntityRealm.getUser().setPass(new Sha256Hash(newPass.trim()).toHex());
usbl.updateOne(EntityRealm.getUser());
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Mot de passe corrigé", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dialogpasse').hide()");
}
} else {
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"Les mots de passe ne concorde pas", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
newPass = "";
lastPass = "";
retapPass = "";
}
} else {
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"mot de passe incorrect!!!", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
newPass = "";
lastPass = "";
retapPass = "";
}
}
public void reinitialiserPasse() {
Utilisateur u = this.usbl.getOneBy("login", per);
if (u.isActif() == true) {
if (reponse.equals(u.getReponse())) {
u.setPass(new Sha256Hash("admin").toHex());
u.setQuestion(null);
u.setReponse(null);
usbl.updateOne(u);
question = "";
reponse = "";
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dialogRecup').hide();");
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Mot de passe réinitialisé", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
} else {
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"La reponse est fausse", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
}
}
}
public String recupererQuestion() {
if (!per.equals("")) {
Utilisateur u = this.usbl.getOneBy("login", per);
String quest = "";
if (u != null) {
if (!u.getPass().equals(new Sha256Hash("admin").toHex())) {
if (u.isActif() == true) {
quest = u.getQuestion();
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dialogRecup').show();");
context.execute("PF('dialogOublie').hide();");
return quest;
} else {
per = "";
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dialogOublie').hide();");
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"Votre compte est inactif,contactez l'administrateur", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
}
} else {
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dialogOublie').hide();");
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Connectez vous à votre compte pour changer votre mot de passe", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
}
} else {
per = "";
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"le login saisi est inconnu", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
}
}
return "";
}
this is the JSF page
<h:form id="login" >
<p:growl id="message" life="4000" showSummary="true" />
<p:outputPanel autoUpdate="true" style="background-image:">
<div class="card login-panel ui-fluid" style=" border-radius: 10px;">
<div class="ui-g">
<div class="ui-g-12">
<p:graphicImage name="images/logo2x.png" library="ultima-layout" />
</div>
<div class="ui-g-12">
<h:panelGroup styleClass="md-inputfield">
<p:inputText id="identifiant" value="#{loginBean.username}" />
<label>Email...</label>
</h:panelGroup>
</div>
<div class="ui-g-12">
<h:panelGroup styleClass="md-inputfield">
<p:password id="motdepasse" value="#{loginBean.password}" />
<label>Mot de Passe...</label>
</h:panelGroup>
</div>
<div class="ui-g-12">
<p:commandButton process="#form" value="Se connecter" icon="ui-icon-person" update="message" actionListener="#{loginBean.login()}" />
<p:commandButton value="Mot de passe oublié" icon="ui-icon-help" styleClass="secondary" onclick="PF('dialogOublie').show()"/>
</div>
</div>
</div>
</p:outputPanel>
</h:form>
and the error
Caused by: org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration.

Leaflet spiderfy onclick on link to open poup

first, sorry for my english...
I am working on a map using openstreetmap and information leaflet and a listing
According to checked "rubrics", I show markers of different structures on the map and the list of its structures under the map
When they click on the title of the list of structures under the map, I open the popup on the map.
My problem is that there are structures with the meme address (same lat and lon), therefore markers overlaps. Markers is clusters. if they click on the map on cluster, that "spiderfy" and i can see several markers. On the contrary when they click on the title of structure under the map, it doesn't show that spiral and the popup
I have found a solution which disable cluster and that no longer indicates that there are multiple markers to the same address. It is a solution which I am not fully satisfied because I'd like that users see that there are several structures/markers to this address
the map is : http://www.ecocitoyen-grenoble.org/joomla/index.php/annuaire ( to test with the last checkbox "Loisirs, espaces naturels" - picto of a man and click on the last structure in the list)
Scripts:
The map:
<script type="text/javascript">
// <![CDATA[
var osm = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA'
});
var map = L.map('map', {
center: [45.1666700, 5.7166700],
zoom: 13,
layers: [osm]
});
var markers = L.markerClusterGroup({
//disableClusteringAtZoom: 18
});
// ]]>
</script>
Display markers :
function rech_picto_structure()
{
map.removeLayer(markers);
markers.clearLayers();
var rub1 = '0';
var rub2 = '0';
var rub3 = '0';
var rub4 = '0';
var rub5 = '0';
var rub6 = '0';
var cp_ville = '';
cp_ville = document.getElementById("cp_ville").value;
if (document.getElementById("box_layer_1").checked )
{
rub1 = '1';
}
if (document.getElementById("box_layer_2").checked )
{
rub2 = '1';
}
if (document.getElementById("box_layer_3").checked )
{
rub3 = '1';
}
if (document.getElementById("box_layer_4").checked )
{
rub4 = '1';
}
if (document.getElementById("box_layer_5").checked )
{
rub5 = '1';
}
if (document.getElementById("box_layer_6").checked )
{
rub6 = '1';
}
if (rub1 == '0' && rub2 == '0' && rub3 == '0' && rub4 == '0' && rub5 == '0' && rub6 == '0')
{
document.getElementById('liste_annuaire').innerHTML = "Veuillez choisir une rubrique pour afficher les structures.";
document.getElementById('picto_structure_div').innerHTML = "Veuillez choisir une rubrique pour afficher les structures.";
}
else
{
var xhr = getXhr();
// On défini ce qu'on va faire quand on aura la réponse
xhr.onreadystatechange = function()
{
// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
if(xhr.readyState == 4 && xhr.status == 200)
{
var picto = xhr.responseText;
if (picto.length > 3)
{
liste_structure = '';
var tab_picto = [];
markers_all = [];
var addressPoints = picto.split("|");
//alert (addressPoints);
for (var i = 0; i < addressPoints.length; i++) {
var cel = addressPoints[i].split("µ");
tab_picto.push(cel);
}
for (var i = 0; i < tab_picto.length; i++) {
var a = tab_picto[i];
var title = a[2];
var marker = L.marker(new L.LatLng(a[0], a[1]), { title: title }).bindPopup("<div><b>" + a[3] + "</b><br/>" + a[4] + "<br><br>" + a[5] + "<br/></div>");
liste_structure += a[6];
markers_all.push(marker);
}
for (var i in markers_all){
markers.addLayer(markers_all[i]);
}
map.addLayer(markers);
map.fitBounds(markers.getBounds());
if (liste_structure == '')
{
document.getElementById('liste_annuaire').innerHTML = "Veuillez choisir une rubrique pour afficher les structures.";
document.getElementById('picto_structure_div').innerHTML = "Veuillez choisir une rubrique pour afficher les structures.";
}
else
{
document.getElementById('liste_annuaire').innerHTML = liste_structure;
document.getElementById('picto_structure_div').innerHTML = tab_picto.length + " structures trouvées";
}
}
else
{
document.getElementById('liste_annuaire').innerHTML = "Veuillez choisir une rubrique pour afficher les structures.";
document.getElementById('picto_structure_div').innerHTML = "Veuillez choisir une rubrique pour afficher les structures.";
}
}
}
xhr.open("POST","../../admin/annuaire/generer_carte.php",true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send("rub1="+rub1+"&rub2="+rub2+"&rub3="+rub3+"&rub4="+rub4+"&rub5="+rub5+"&rub6="+rub6+"&cp_ville="+cp_ville);
}
}
Open popup on click on the title of the list under the map
function markerFunction(id){
for (var i in markers_all){
var markerID = markers_all[i].options.title;
//alert(markerID);
if (markerID == id){
LatLng = markers_all[i].getLatLng();
//alert(LatLng);
//map.setView([45.19116, 5.7311], 15);
map.setView([LatLng.lat, LatLng.lng], 20);
//markers.spiderfy();
//markers.unspiderfy()
markers_all[i].openPopup();
};
}}
Thx
stephane
If I understand well, you want to open the popup corresponding to the item in the list, but the marker is in a cluster
Providing you put all your markers in an array when you create them, you can remove the marker from the cluster and add it to the map when you want to open the popup
markerCluster.removeLayer(markers[selectedId]);
map.addLayer(markers[selectedId]);
markers[selectedId].openPopup();
Look at the page source of this: http://franceimage.github.io/leaflet/8/?map=46.566414,2.4609375,6&popup=81
In my case, I want to highlight the marker when I have a 'popup' parm in the url

Add/update roster as an admin using php

As per my project's nature, I want to add/update roster information using some script(php). I want to do it in the same way, it is done by web admin interface of ejabberd manually. But i want to automate this. Is there any way to do this?
Any suggestion on how to achieve this goal is highly appreciated. Thanks in advance !
If you are using Openfire, you can just use the Userservice plugin, which will allow you to administer user rosters via HTTP requests
<?php
/**
* Created by JetBrains PhpStorm.
* User: Abel Espinosa Cañive
* Date: 8/5/15
* Time: 7:43 PM
* To change this template use File | Settings | File Templates.
*/
/*
ERROR CODE:
0 :Success
Other Number:Error
*/
define ( "MAX_SIZE", "5120" ); // 5MB MAX file size
define ( "DOMAIN", "my.domain.com" );
class eJabberedPlugin
{
var $display_debug_info;
//activa la opcion de debugueo del XMPP
function eJabberedPlugin($v_display_debug_info=false)
{
$this->display_debug_info = $v_display_debug_info;
}
//Crea un nuevo usuario
//$UserLogin : usuario que se creará
//$UserPass : contraseña para el usuario nuevo
function createNewUserREST($UserLogin,$UserPass)
{
$url = "http://DOMAIN:5280/rest/";
$request = "register $UserLogin DOMAIN $UserPass";
$response = $this->sendRESTRequest($url, $request);
return $response;
}
//Adiciona Amigo1 a Amigo2 y viceversa (forzado)
//$user1 : usuario que desea agregar a $user2
//$user2 : usuario que desea agregar a $user1
//$nick_user1 : nick que le dará el $user2 al $user1 en su roster
//$nick_user2 : nick que le dará el $user1 al $user2 en su roster
//$group1 : Grupo en el roster de $user1 que se agregará al $user2
//$group2 : Grupo en el roster de $user2 que se agregará al $user1
function addFriendREST($user1,$user2,$nick_user1="",$nick_user2="",$group1="Friends",$group2="Friends")
{
$url = "http://DOMAIN:5280/rest/";
$exist_user1 = $this->checkUser($user1);
$exist_user2 = $this->checkUser($user2);
if($exist_user1==0 && $exist_user2==0)
{
$request1 = "add_rosteritem $user1 DOMAIN $user2 DOMAIN $nick_user2 $group1 both";
$request2 = "add_rosteritem $user2 DOMAIN $user1 DOMAIN $nick_user1 $group2 both";
$response1 = $this->sendRESTRequest($url, $request1);
$response2 = $this->sendRESTRequest($url, $request2);
}
else
{
$response1 = $exist_user1;
$response2 = $exist_user2;
}
$response_array = [$response1,$response2];
return $response_array;
}
//Elimina un usuario del servidor
//$username : Usuario que se eliminará
function deleteUserREST($username)
{
$url = "http://DOMAIN:5280/rest/";
$request = "unregister $username DOMAIN";
$response = $this->sendRESTRequest($url, $request);
return $response;
}
//Agrega o cambia un avatar a un usuario dado
//$username : usuario que se modificará
//$photo_url : archivo de la imagen nueva
function addAvatarREST($username,$photo_url)
{
$url = "http://DOMAIN:5280/rest/";
$raw_file = file_get_contents($photo_url["tmp_name"]);
$photo = base64_encode($raw_file);
$request = "set_vcard2 $username DOMAIN PHOTO BINVAL $photo";
$response = $this->sendRESTRequest($url, $request);
return $response;
}
//Verifica si el usuario existe en el servidor
//$username : Usuario a verificar
function checkUser($username)
{
$url = "http://DOMAIN:5280/rest/";
$request = "check_account $username DOMAIN";
$response = $this->sendRESTRequest($url, $request);
return $response;
}
//Obtiene una lista de todos los usuarios registrados en el servidor
function allUsers()
{
$url = "http://DOMAIN:5280/rest/";
$request = "registered_users DOMAIN";
$response = $this->sendRESTRequest($url, $request);
$arr = str_split($response);
$collecting = "";
$result = [];
for ($i = 0; $i < count($arr); $i++) {
if (ctype_alnum($arr[$i])==true) {
$collecting.=$arr[$i];
if ($i==count($arr)-1) {
array_push($result,$collecting);
}
}
else
{
array_push($result,$collecting);
$collecting = "";
}
}
return $result;
}
//Ejecuta las consultas con el servidor
//$url : Direccion del servidor REST
//$xml : Consulta
function sendRESTRequest ($url, $xml) {
$context = stream_context_create(
array('http' =>
array(
'method' => "POST",
'header' => "Content-Length: ".strlen($xml),
'content' => $xml
)
)
);
$file = file_get_contents($url, false, $context);
return "$file";
}
//Obtiene la extension del archivo adjunto
//$str : Nombre del archivo que se verifica
function getExtension($str) {
$i = strrpos ( $str, "." );
if (! $i) {
return "";
}
$l = strlen ( $str ) - $i;
$ext = substr ( $str, $i + 1, $l );
return $ext;
}
}
//*****FIN DE LA CLASE*****//
// Crea una instancia de la clase eJabberedPlugin
$obj = new eJabberedPlugin();
// Ahora comenzamos a usar la clase de arriba :)
//Crear nuevo usuario
if(isset($_POST['action']) && $_POST['action']=='newUser')
{
if(isset($_POST['user']) && isset($_POST['pass']))
{
$result = $obj->createNewUserREST($_POST['user'],$_POST['pass']);
if($result==0)
{
echo "created ok";
}
else
{
echo "not created, error:$result";
}
}
}
//Eliminar usuario
elseif(isset($_POST['action']) && $_POST['action']=='delUser')
{
if(isset($_POST['user']))
{
$result = $obj->deleteUserREST($_POST['user']);
if($result==0)
{
echo "deleted ok";
}
else
{
echo "not deleted, error:$result";
}
}
}
//Agregar amigos
elseif(isset($_POST['action']) && $_POST['action']=='addFriend')
{
if(isset($_POST['userFriend1']) && isset($_POST['userFriend2']) && isset($_POST['nickUser1']) && isset($_POST['nickUser2']) && isset($_POST['groupUser1']) && isset($_POST['groupUser2']) )
{
$result = $obj->addFriendREST($_POST['userFriend1'],$_POST['userFriend2'],$_POST['nickUser1'],$_POST['nickUser2'],$_POST['groupUser1'],$_POST['groupUser2']);
if(count($result)==2 && $result[0]==0 && $result[1]==0)
{
echo "added ok";
}
else
{
echo "not added, error:<br>";
if($result[0]==1 && $result[1]==0)
{
echo "Usuario ".$_POST['userFriend1'].": Usuario no registrado.<br>";
echo "Usuario ".$_POST['userFriend2'].": ".$result[1]." errores<br>";
}
elseif($result[0]==0 && $result[1]==1)
{
echo "Usuario ".$_POST['userFriend1'].": ".$result[0]." errores<br>";
echo "Usuario ".$_POST['userFriend2'].": Usuario no registrado.<br>";
}
else
{
echo "Usuarios ".$_POST['userFriend1']." y ".$_POST['userFriend2']." no registrados.<br>";
}
}
}
}
//Agregar avatar
elseif(isset($_POST['action']) && $_POST['action']=='addAvatar')
{
if(isset($_POST['user']) && isset($_FILES['avatar']))
{
$filename = stripslashes ( $_FILES ["avatar"] ["name"] );
$size = filesize ( $_FILES ["avatar"] ["tmp_name"]);
// Convert extension into a lower case format
$ext = $obj->getExtension ( $filename );
$ext = strtolower ( $ext );
// File extension check
// Valid image formats
$valid_formats = array ("jpg","png","gif","bmp","jpeg");
if (in_array ( $ext, $valid_formats )) {
// File size check
if ($size < (MAX_SIZE * 1024)) {
$result = $obj->addAvatarREST($_POST['user'],$_FILES['avatar']);
if($result==0)
{
echo "added ok";
}
else
{
echo "not added, error:$result";
}
}
}
}
}
?>

Trying to update OR insert in Symfony2 controller with a form

What's wrong in my code ? I want to update or insert an Moteur object depending on url.
Thanks by advance.
/**
* #Route("/moteur/{moteurid}", name="moteur", requirements={"moteurid" = "\d+"}, defaults={"moteurid" = null})
* #Template()
*
* Cette page permet d'enregistrer de nouveaux moteurs (et de les éditer).
*/
public function moteurAction($moteurid)
{
$args=array();
$avertissement = null;
if (!$this->get('security.context')->isGranted('ROLE_ADMIN'))
{
$avertissement = "Vous n'avez pas le droit d'accéder à cet espace.";
return $this->redirect($this->generateUrl('index', array('avertissement' => $avertissement)));
}
$args['menu']['admin'] = 'selected';
$obj = null;
if ($moteurid == null)
{
$obj = new Moteur();
}
else
{
$obj = $this->getDoctrine()->getRepository('CreasixtineAFBundle:Moteur')->find($moteurid);
}
$form = $this->createForm(new FormMoteur(), $obj);
$args['form'] = $form->createView();
if ($this->getRequest()->getMethod() == 'POST')
{
$form->bindRequest($this->getRequest());
if ($form->isValid())
{
$obj = $form->getData(); // Type Moteur()
$pn = $obj->getPnid();
$em = $this->getDoctrine()->getEntityManager();
if ($moteurid == null)
{
$em->persist($obj);
$avertissement = "Moteur créé !";
}
else
{
// Rien, le moteur sera mis à jour avec flush()
$avertissement = "Moteur mis à jour !";
}
foreach ($pn as $my_pn){$em->persist($my_pn);}
$em->flush();
return $this->redirect($this->generateUrl('admin', array('avertissement' => $avertissement)));
}
else
{
throw new Exception("Le formulaire n'est pas valide.");
}
}
$contenu = $this->rendu($args, "formulaire_moteur.html.twig");
return $contenu;
}
First, you don't need this line as PHP5 natively passes object by reference :
$obj = $form->getData(); // Type Moteur()
Then, your relation between Moteur and Pn is a bit confusing. You get a Pn with getPnid() but you get an object you wanna persist ?
Anyway, these Pn objects should be persisted before Moteur, so here is what I would write :
if ($form->isValid())
{
$em = $this->getDoctrine()->getEntityManager();
$pn = $obj->getPnid();
//Persist these related objects BEFORE Moteur
foreach ($pn as $my_pn)
{
$em->persist($my_pn);
}
if ($moteurid == null)
{
$em->persist($obj);
$avertissement = "Moteur créé !";
}
else
{
// Rien, le moteur sera mis à jour avec flush()
$avertissement = "Moteur mis à jour !";
}
$em->flush();
return $this->redirect($this->generateUrl('admin', array('avertissement' => $avertissement)));
}
else
{
throw new Exception("Le formulaire n'est pas valide.");
}