Ir al contenido principal

Snippets Mongo DB

 Esta publicación servirá para ir colocando fragmentos de consultas que en algún momento me fueron útiles para usarlo en MongoDB Fragmento 1:  Se requería obtener todos los elementos que dentro de un atributo que es de tipo array(arreglo) coincida  con type:"fire"  Fragmento 2: Se requería actualizar el atributo " lastUpdate "  de toda la colección donde la  edad sea mayor o igual a 15.

Ejemplo Highchart con DWR

Esta vez traigo un ejemplo que puede ser útil en algún momento se trata de un escenario que presenta por una parte utilizar Highchart para gráficas (Front) y por otra parte WDR para trabajar el negocio(Backend), este también servirá para que la interacción entre el Frontend y Backend pueda realizarse de forma asíncrona ayudando a la visualización que la gráfica tenga movimiento.



Creamo nuestro proyecto New-> Dynamic Web Project


Una vez que dimos a todo siguiente obtenemos el proyecto, para iniciar debemos crear los paquetes com.elkardumen.inicia y com.elkardumen.thread tal como se ve en la siguiente imagen
 

El en paquete com.elkardumen,inicia debemos crear la clase Inicia.java y en el paquete com.elkardumen.thread crear la clase HiloLectura.java tal como se ve en

En la clase Inicia.java colocaremos el siguiente código.
package com.elkardumen.inicia;


import javax.servlet.ServletContext;

import org.directwebremoting.ServerContext;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContextFactory;


import com.elkardumen.thread.HiloLectura;


public class Inicia 
{
private ServerContext sctx;
    
    private transient boolean active = true;
    
    public Inicia()
    {
        ServletContext servletContext = WebContextFactory.get().getServletContext();
        sctx = ServerContextFactory.get(servletContext);
    }

  
public synchronized void toggle() {
// active = !active;
System.out.println("!!!!!!!!" + active);
if (active) {

try {

HiloLectura hiloInter = new HiloLectura(sctx);
Thread theReader = new Thread(hiloInter);
theReader.start();

System.out.println("!!!!!!!!Generaste Hilo");
active = false;

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

}
}

}
En a clase HiloLectura.java debemos colocar el siguiente codigo.


package com.elkardumen.thread;


import java.util.Collection;

import org.directwebremoting.ServerContext;
import org.directwebremoting.proxy.dwr.Util;

public class HiloLectura implements Runnable{
    
private ServerContext sctx;
 

    
    public HiloLectura (ServerContext sctx){
        this.sctx=sctx;
    }
    
    public  void run(){
        try{
        System.out.println("Incia envio de info...");
    int i=0;
    Collection sessions=null;
    Util pages=null;
    String Json;
    int contador=0;
    while (true) {
       sessions= sctx.getScriptSessionsByPage("/HighChartWithDwr/index.html");
                    pages = new Util(sessions);
                    Json="{\"hora\":\""+System.currentTimeMillis() +"\",\"conteo\":\""+contador+"\"}";  
                System.out.println(Json);
                    pages.addFunctionCall("putDatos",Json);
                contador++;
                Thread.sleep(10000);
    }  
       
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
  
    
}

Si tenemos problemas con las clases o marca alguna excepción  en el código pegado deberemos colocar la carpeta lib en WEB-INF los .jar siguientes:

Ahora bien el siguiente paso es crear la vista, para esto iniciamos colocando en la carpeta WebContent la carpeta js dentro de esta jquery.js y highstock.js estos js son los framework para crear gráficas y colocaDatos.js es el js donde colocaremos nuestro código.

Código de colocaDatos.js
var TRX;
var chartI;

$(document).ready(function(){
inicializaGraficaGeneric("","");
});


function putDatos(jsonStr){
if(jsonStr!=null &&  jsonStr!=""){

if(typeof jsonStr =='object')
{
 obj=jsonStr;
}else{
//obj = JSON && JSON.parse(jsonStr);
obj=jQuery.parseJSON(jsonStr);
}
}
//console.log(jsonStr);
TRX.series[0].addPoint([Number(obj.hora),Number(obj.conteo)],true,false);
TRX.series[1].addPoint([Number(obj.hora),Number(obj.conteo)],true,false);
//chartI.series[0].addPoint([Number(obj.hora),Number(obj.conteo)],true,false);
}



function inicializaGraficaGeneric(id, data) {
id="TRX";
data="[{ \"name\": \"Incorrectas\", \"type\": \"area\", \"color\": \"#FFff00\",\"tooltip\": { \"valueDecimals\": 0 },  \"fillColor\": {  \"linearGradient\": {  \"x1\": 0, \"y1\": 0, \"x2\": 0, \"y2\": 1 },  \"stops\": [[0, \"rgb(255, 255, 0)\"], [1, \"rgb(85,255,0)\"]] }, \"pointInterval\": 1000, \"pointStart\": 1381254009795, \"showInLegend\": true, \"data\": [ [1381254009795,0],[1381255160172,510]] }," +
  "{ \"name\": \"Correctas\", \"type\": \"area\", \"color\": \"#00FFFF\", \"tooltip\": { \"valueDecimals\": 0}, \"fillColor\": {  \"linearGradient\": {  \"x1\": 0, \"y1\": 0, \"x2\": 0, \"y2\": 1 },  \"stops\": [ [0, \"rgb(6, 255, 255)\"], [1, \"rgb(153,0,255)\"]] }, \"yAxis\": 1, \"pointInterval\": 1000, \"pointStart\": 1381254009795, \"showInLegend\": true, \"data\": [ [1381254009795,0 ],[1381255160172,510]] }]";
str = jQuery.parseJSON(data);
var options ={ 
chart :{
backgroundColor: true,
marginTop: 0,
renderTo: id,
borderRadius: 0,
type: 'area',
zoomType: 'x',
width:560,
height:333
},
rangeSelector: {
buttonTheme: {
align: 'right',
fill: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
fillWidth: 0,
stops: [[0.4, '#373737'],[0.6, '#141414']]
      },
      stroke: false,
      style: {
         color: '#787878',
         fontSize: '10px',
         fontFamily: 'Gill Sans'
      },
      states: {
         hover: {
            fill: {
               linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
               stops: [[0.4, '#888'],[0.6, '#555']]
            },
            stroke: false,
            style: {
                   color: '#787878',
                   fontSize: '10px',
                   fontFamily: 'Gill Sans'
            }
         },
         select: {
            fill: {
               linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
               stops: [[0.1, '#464646'],[0.3, '#1E1E1E']]
            },
            stroke: false,
            style: {
                color: '#787878',
                fontSize: '10px',
     fontFamily: 'Gill Sans'
            }
         }
      }
   },
buttons: [{
count: '30',
type: 'minute',
text: '30m'
}, {
count: '2',
type: 'hour',
text: '2h'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0,
labelStyle: {
fontSize: '6px',
color: '#939393',
fontFamily: 'Lucida Sans Unicode, Lucida Grande'
}
},
scrollbar: {
enabled: false,
trackBackgroundColor: {
        linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
        stops: [
           [0, '#000'],
           [1, '#333']
        ]
     },
     trackBorderColor: '#666'
},
navigator: {
maskFill: 'rgba(10, 10, 10, 0.7)',
    series: {
type: "area",
        color: "#6E6E6E",
        fillColor:{
        linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
            stops: [
               [0, '#5F5F5F'],
               [1, '#5F5F5F']
            ]
         },
           lineColor: "#6E6E6E"
       },
     
xAxis: {
tickWidth: 0,
lineWidth: 0,
startOnTick: false,
endOnTick: false,
gridLineWidth: 0,
tickPixelInterval: 100,
labels: {
style: {
    fontSize: '8px',
    color: '#939393',
    fontFamily: 'Lucida Sans Unicode, Lucida Grande'
},
y: 8,
x: -10
}
},
    height: 23,
    margin: 0,
    marker: {
enabled: false
},
shadow: false,
    handles: {
    backgroundColor: 'RGB(130,130,130)'
    }
},
credits:{
enabled:false
   },
   exporting: {
enabled: false
   },
   tooltip: {
valueDecimals : 0,
shared: true,
backgroundColor: 'rgba(10,10,10, 0.6)',
  borderWidth: 1,
  style: {
  color: 'rgb(255,255,255)',
  fontSize: '11px',
  fontFamily: 'Gill Sans'    
 
  },
crosshairs: {
dashStyle: 'dash'
}
},
xAxis: {
     lineColor: '#6e6e6e',
type :'datetime',
tickInterval : 240000 * 60 *1,
dateTimeLabelFormats: {
day:'%H:%M:%S'
},
labels: {
         style: {
          fontSize: '9px',
          color: '#5a5a5a',
          fontFamily: 'Gill Sans'
},
         enabled: true
     }, 
showFirstLabel: true
},
yAxis: [{
labels: {
style: {
fontSize: '11px',
color: '#FFFF00',
fontFamily: 'Gill Sans'
},
enabled: true
},
plotLines: [{
width: 1,
color: '#FFFF00'
}],
height: 129,
top: 10,
min: 0,
offset: 0,
endOnTick: true,
startOnTick: true,
showFirstLabel: true,
gridLineColor: ''
 },{
   height: 129,
top: 142,
offset: 0,
lineWidth: 0,
min: 0,
endOnTick: true,
startOnTick: true,
showFirstLabel: true,
labels: {
style: {
fontSize: '11px',
color: '#05E8FA',
fontFamily: 'Gill Sans'
},
enabled: true
},
gridLineColor: ''
 }],
   legend: {
       enabled: false
   },
plotOptions: {
area: {
marker: {
enabled: false,
symbol: 'circle',
radius: 1,
states: {
hover: {
enabled: true
}
}
}
}  
},
   series:str
};
Highcharts.setOptions({
global : {
useUTC : false
}

});

TRX= new Highcharts.StockChart(options);
}

Ahora es necesario agregar nuestro dwr.xml con la siguiente configuración
<?xml version="1.0" encoding="UTF-8"?>

<dwr>
<allow>
<create creator="new" javascript="Inicial" scope="application">
<param name="class" value="com.elkardumen.inicia.Inicia" />
</create>
</allow>

</dwr>

y en web.xml agregar la siguiente configuracion

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>HighChartWithDwr</display-name>
  
  
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
    <init-param>
      <param-name>debug</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>activeReverseAjaxEnabled</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>pollAndCometEnabled</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>allowScriptTagRemoting</param-name>
      <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dwr-invoker</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
  </servlet-mapping>

  
</web-app>


Y en index.html colocaremos

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>

 <script type='text/javascript' src='dwr/interface/Inicial.js'> </script>
  <script type='text/javascript' src='dwr/engine.js'> </script>
  <script type='text/javascript' src='dwr/util.js'> </script>
  

<script type="text/javascript" src="js/jquery.js"></script>  
<script type="text/javascript" src="js/highstock.js"></script>
<script type="text/javascript" src="js/colocaDatos.js"></script>

 <script>
 $(document).ready(function (){

 
 });

 </script>
</head>
<body onload="dwr.engine.setActiveReverseAjax(true);Inicial.toggle();">


<div id="TRX" ></div>

<div id="container" style="height: 270px;"></div>



</body>
</html>

Una vez hecho todo esto solo queda hacer el Run as.. y en nuestro navegador debermos tener lo siguiente.




Ya saben si no sale pues acá esta el código fuente:
PD: Este ejemplo nu hubiera sido elaborado sin el apoyo de mi buen amigo @mariof4
 
Descarga
   
  
 


Comentarios

  1. Muy buen ejemplo campeon , buen blog!!

    ResponderBorrar
  2. Pues que te digo Bro , es el cascaron de tu antiguo trabajo..

    ResponderBorrar
  3. Muy bien aqui comenzo todo, esto te llevara a un lado de Patriarca Bro muy bien

    ResponderBorrar

Publicar un comentario

Entradas más populares de este blog

Resetear usuario y contraseña Weblogic

Esta ocasión se me presento un pequeño problema con el acceso a mi weblogic local, podía levantar mi weblogic pero para entrar a la consola no tenia el usuario ni password (Autenticación Denegada Weblogic).Por lo que busque en la red para poder resetear el usuario y password de weblogic.

No se puede llamar Invoke o a BeginInvoke

Que tal banderola pues aca escribiendo sobre un error que me dio al instalar el administrador Microsoft SQL 2008 , pues bien resulta que necesitaba instalar esta tool, y cuando trataba de iniciar el wizard me lanzaba un error que decia algo asi " No se puede llama a Invoke o a BeginInvoke en un control hasta que se halla creado el indentificador de ventana" si no me creen vean la imagen : y entonces me dije a mi mismo, "mi mismo como le voy hacer" entonces pues tube que recurrir a mi salvacion como siemore :D San Google.com, y ya con unas cuantas palabras clave pues que me lanza algunos resultados de los cuales me habia encontrado algo como esto: Problemas al instalar SQL Server 2008 ? Para lo cual no hice caso a este tip pues resulta que yo no tenia instaldo el windows xp, mas bien tenia instalado el windows 7 por que leyendo en los comentarios que se habian hecho llegue a un muy buen tip que decia algo asi: "Para aquellos compañeros que quieren instalar el S