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.

Simple notificaciones HTML5 con Java




"Bien lo que pasa es de que" estaba revisando una notas sobre el API de notificaciones, y me pareció interesante la forma en que funcionaban, ya que pueden ser útiles para dar avisos de una forma sencilla. Pues bien como estaba trabajando con DWR ,un framework ajax para Java pues me di a la tarea de implementar estas notificaciones con DWR y estos fue lo que hice:

Mi escenario es en siguiente:




El cliente estará esperando a que el administrador envié algún mensaje , este mensaje se mostrara en pantalla principal y mostrara la notificación HTML5 del cliente.

El proyecto deberá tener la siguiente estructura de paquetes, clases y folders para .jsp .js


En la clase TheController colocamos los siguientes métodos:

@RequestMapping("/index.html")
    public String loadIndex() {
return "index";
    }

@RequestMapping("/administrator.html")
    public String loadAdministrator() {
return "admin";
    }


public void enviaElMensaje(String mensaje) {

try{
final String elmensaje=mensaje;
WebContext wctx = WebContextFactory.get();
//Browser.withAllSessions(wctx, new Runnable() {

Browser.withPage("/SimpleNotificacionesDWR/index.html", new Runnable() {
public void run() {
ScriptSessions.addFunctionCall("muestraMensaje",elmensaje);
}
});
}catch (Exception e){
e.printStackTrace();
}
}

El funciones-cliente.js
document.addEventListener("DOMContentLoaded", function() {
  if (Notification.permission !== "granted")
     Notification.requestPermission();
}, false);


function muestraMensaje(msj){
console.log(msj);
$("#mensaje").append(msj);
notifyMe(msj);
}


function errh(data){
console.log("error"+data);
}


function notifyMe(msj) {

if (!Notification) {
alert('Las notificaciones no estan disponibles en tu navegador');
return;
}

if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification(
'El Kardumen',
{
icon : 'http://a2.cdn.gaiaonline.com/dress-up/avatar/ava/bf/b2/57609e5dbdb2bf.png',
body : "Hey existe algo nuevo en el  kardumen!"+msj,
});

notification.onclick = function() {
window.open("http://kardumen.blogspot.com");
};

}
}


Para funciones.js


$(function(){

$("#btnEnvia").on("click",function(){
theController.enviaElMensaje($("#txtmensaje").val());
$("#txtmensaje").val("");
});

});



function errh(data){
console.log("error"+data);
}
Para admin.jsp

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ejemplo basico notificaciones HTML5 con Java</title>



<link href="http://materializecss.com/css/prism.css" rel="stylesheet">
    <link href="http://materializecss.com/css/ghpages-materialize.css" type="text/css" rel="stylesheet" media="screen,projection">
    <link href="http://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

</head>

<body onload="dwr.engine.setActiveReverseAjax(true);dwr.engine.setErrorHandler(errh);">
<h5>

</h5>


<div class="container">
<div class="row">
      <div class="col s12 m12">
        <div class="card-panel teal">
          <span class="white-text">Ejemplo basico de notificaciones html5 enviadas con Java , desarrollado con Frameworks Spring 3 y DWR
          algunas referencias
          <br>
         
          
          </span>
           http://www.jasoft.org/Blog/post/Mostrando-notificaciones-desde-el-navegador-con-HTML5.aspx
          <br>
          http://www.html5rocks.com/en/tutorials/notifications/quick/
          <br>
          https://www.w3.org/TR/notifications/
          <br>
          https://developers.google.com/web/updates/2015/05/notifying-you-of-changes-to-notifications
          
          
          
        </div>
        <div class="input-field col s6">
          <input id="txtmensaje" placeholder="mensaje" id="first_name" type="text" class="validate">
          <label for="first_name">Escribe el mensaje</label>
          <button id="btnEnvia" class="btn waves-effect waves-light red lighten-3" type="submit" name="action" alt="online!">Envia notificación</button>
         </div>
      </div>
    </div>

</div>

          


</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="js/funciones.js"></script>
<!--scripts DWR -->
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/engine.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/theController.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/util.js"></script>

<script type="text/javascript" src="http://materializecss.com/bin/materialize.js"></script>


</html>



Para index.jsp

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Espera Notificación</title>

<link href="http://materializecss.com/css/prism.css" rel="stylesheet">
    <link href="http://materializecss.com/css/ghpages-materialize.css" type="text/css" rel="stylesheet" media="screen,projection">
    <link href="http://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">


</head>

<body onload="dwr.engine.setActiveReverseAjax(true);dwr.engine.setErrorHandler(errh);">

<div class="container">
<div class="row">
<div class="col s12 m12">
<div class="card-panel teal">
<span class="white-text">Aca espera las Notificaciones dale
aceptar cuando aparesca el mensaje! <br>
</span>
<div id="mensaje"></div>
</div>

</div>
</div>

</div>
</body>

<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="js/funciones-cliente.js"></script>

<!--scripts DWR -->
<script type="text/javascript"
src="<%=request.getContextPath()%>/dwr/engine.js"></script>
<script type="text/javascript"
src="<%=request.getContextPath()%>/dwr/interface/theController.js"></script>
<script type="text/javascript"
src="<%=request.getContextPath()%>/dwr/util.js"></script>

<script type="text/javascript" src="http://materializecss.com/bin/materialize.js"></script>

</html>

Para spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr/spring-dwr-3.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">


    <context:component-scan base-package="com.elkardumen.controller" />
    <mvc:annotation-driven />

   <dwr:controller id="dwrController" debug="true">
    <dwr:config-param name="crossDomainSessionSecurity" value="false"/>
    <dwr:config-param name="activeReverseAjaxEnabled" value="true"/>
    <dwr:config-param name="pollAndCometEnabled" value="true" />
    <dwr:config-param name="maxWaitAfterWrite" value="-1"/>
    </dwr:controller>

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
 <property value="true" name="alwaysUseFullPath"></property> 
 <property name="mappings">
   <props> 
     <prop key="/dwr/**/*">dwrController</prop>
   </props>
</property>
</bean>


<bean id="theController" class="com.elkardumen.controller.TheController" scope="application">
<dwr:remote javascript="theController">
  <dwr:include method="enviaElMensaje"/>
</dwr:remote>
</bean>

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
  <bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

  
 
  <bean id="jspViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    
    
    
</beans>

 y para web.xml

<?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" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
id="WebApp_ID" version="3.0">
  <display-name>SimpleNotificacionesDWR</display-name>

  <!-- ************************** spring MVC **************************  -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

<servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

<servlet-mapping>
<servlet-name>spring</servlet-name>
  <url-pattern>/dwr/*</url-pattern>
</servlet-mapping>

<welcome-file-list>
        <welcome-file>/pages/index.jsp</welcome-file>
    </welcome-file-list>
  
</web-app>

 para que todo esto funcione yo lo probe con las siguientes versiones:

Spring 3.0.5
DWR 2.9
Apache Tomcat 7

Para poder probar una vez desplegado nuestro proyecto podremos probar en

http://localhost/SimpleNotificacionesDWR/index.html ---Para el cliente
http://localhost/SimpleNotificacionesDWR/administrator.html --Para el administrador

De cualquier forma yo dejo el proyecto completo listo para importarlo en su workspace

DESCARGA AQUI

Fuentes:
http://www.html5rocks.com/en/tutorials/notifications/quick/
https://www.w3.org/TR/notifications/
http://www.chromium.org/developers/design-documents/desktop-notifications/api-specification
https://developers.google.com/web/updates/2015/05/notifying-you-of-changes-to-notifications
https://github.com/ttsvetko/HTML5-Desktop-Notifications

Comentarios

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