Commit 78ec98cf by Percy Quispe

Conexion entre web apps

parent 5cbccaba
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package demojsoncrud.servlets;
import demojsoncrud.services.PersonaService;
import demojsoncrud.utilities.PostRequest;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
/**
*
* @author Percy
*/
public class RedireccionarServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
listarPersona(request, response);
}
private void listarPersona(HttpServletRequest request, HttpServletResponse response) {
final String URL = "http://localhost:8080/security-rest/api/proyecto/enviarNuevoToken";
response.setContentType("application/json");
PrintWriter pw = null;
JSONObject salida = new JSONObject();
try {
pw = response.getWriter();
String authorization =request.getHeader("Authorization");
if(authorization!=null && authorization.contains("Bearer ")){
PostRequest sendPost = new PostRequest(URL);
String respuesta = sendPost.getRespueta(authorization);
JSONObject obj = new JSONObject(respuesta);
salida=obj;
}else{
salida.put("status", false);
salida.put("message", "Credenciales incorrectas.");
}
} catch (Exception e) {
salida.put("status", false);
salida.put("message", e.getMessage());
}
pw.print(salida);
}
}
...@@ -24,6 +24,7 @@ import org.json.JSONObject; ...@@ -24,6 +24,7 @@ import org.json.JSONObject;
@WebFilter("/*") @WebFilter("/*")
public class RequestFilter implements Filter, ServletContextListener { public class RequestFilter implements Filter, ServletContextListener {
private final String BASE = "http://localhost:8080/proyecto-estandar/";//Modificar con la ruta de su proyecto private final String BASE = "http://localhost:8080/proyecto-estandar/";//Modificar con la ruta de su proyecto
private final String BASE_IP = "http://172.16.2.53:8080/proyecto-estandar/";
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException { public void init(FilterConfig filterConfig) throws ServletException {
...@@ -52,15 +53,16 @@ public class RequestFilter implements Filter, ServletContextListener { ...@@ -52,15 +53,16 @@ public class RequestFilter implements Filter, ServletContextListener {
String respuesta = ""; String respuesta = "";
String urlRequested = "http://172.16.2.53:8080/security-rest/api/user/verificarLogin"; String urlRequested = "http://172.16.2.53:8080/security-rest/api/user/verificarLogin";
System.out.println("URI "+request.getRequestURI()); System.out.println("URI "+request.getRequestURI());
if (String.valueOf(request.getRequestURL()).contains(BASE)) { // if (String.valueOf(request.getRequestURL()).contains(BASE)||String.valueOf(request.getRequestURL()).contains(BASE_IP)) {
String login = request.getContextPath() + "/vistas/index.jsp"; String login = request.getContextPath() + "/vistas/index.jsp";
String plantilla = request.getContextPath() + "/plantilla"; String plantilla = request.getContextPath() + "/plantilla";
String js = request.getContextPath() + "/js"; String js = request.getContextPath() + "/js";
String css = request.getContextPath() + "/css"; String css = request.getContextPath() + "/css";
System.out.println(js); System.out.println(js);
String url = String.valueOf(request.getRequestURL()); String url = String.valueOf(request.getRequestURL());
System.out.println("URI _"+request.getRequestURI());
if (url.equalsIgnoreCase(BASE) || url.contains(login) || url.contains(plantilla) || url.contains(js)|| url.contains(css)|| url.contains("index.jsp")||url.contains("main.jsp")) { if (url.equalsIgnoreCase(BASE) || url.contains(login) || url.contains(plantilla) || url.contains(js)|| url.contains(css)|| url.contains("index.jsp")||url.contains("main.jsp")
|| url.contains("RedireccionarServlet")||url.contains("cargando.jsp")) {
chain.doFilter(request, response); chain.doFilter(request, response);
} else { } else {
PostRequest postRequest = new PostRequest(urlRequested); PostRequest postRequest = new PostRequest(urlRequested);
...@@ -133,9 +135,9 @@ public class RequestFilter implements Filter, ServletContextListener { ...@@ -133,9 +135,9 @@ public class RequestFilter implements Filter, ServletContextListener {
sendError(response); sendError(response);
} }
} }
} else { // } else {
sendError(response); // sendError(response);
} // }
} }
private void sendError (HttpServletResponse response) throws IOException{ private void sendError (HttpServletResponse response) throws IOException{
......
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<!-- <welcome-file-list> <!-- <welcome-file-list>
<welcome-file>/vistas/index.jsp</welcome-file> <welcome-file>/vistas/index.jsp</welcome-file>
</welcome-file-list>--> </welcome-file-list>-->
<servlet> <servlet>
...@@ -11,6 +11,10 @@ ...@@ -11,6 +11,10 @@
<servlet-name>UbigeoServlet</servlet-name> <servlet-name>UbigeoServlet</servlet-name>
<servlet-class>demojsoncrud.servlets.UbigeoServlet</servlet-class> <servlet-class>demojsoncrud.servlets.UbigeoServlet</servlet-class>
</servlet> </servlet>
<servlet>
<servlet-name>RedireccionarServlet</servlet-name>
<servlet-class>demojsoncrud.servlets.RedireccionarServlet</servlet-class>
</servlet>
<servlet-mapping> <servlet-mapping>
<servlet-name>PersonaServlet</servlet-name> <servlet-name>PersonaServlet</servlet-name>
<url-pattern>/PersonaServlet</url-pattern> <url-pattern>/PersonaServlet</url-pattern>
...@@ -19,6 +23,10 @@ ...@@ -19,6 +23,10 @@
<servlet-name>UbigeoServlet</servlet-name> <servlet-name>UbigeoServlet</servlet-name>
<url-pattern>/UbigeoServlet</url-pattern> <url-pattern>/UbigeoServlet</url-pattern>
</servlet-mapping> </servlet-mapping>
<servlet-mapping>
<servlet-name>RedireccionarServlet</servlet-name>
<url-pattern>/RedireccionarServlet</url-pattern>
</servlet-mapping>
<session-config> <session-config>
<session-timeout> <session-timeout>
30 30
...@@ -33,5 +41,4 @@ ...@@ -33,5 +41,4 @@
<error-code>404</error-code> <error-code>404</error-code>
<location>/vistas/index.jsp</location> <location>/vistas/index.jsp</location>
</error-page> </error-page>
</web-app> </web-app>
/**
* Crea los elementos option del array que se pase como parametro /*Ajax genral*/
* @method createSelectOptions const ajaxRequestGeneral = obj => {
* @param {JSONArray} obj array de objetos let body=JSON.stringify(obj.body);
* @param {String} valueName la key del json que se usará como value del elemento option return new Promise((resolve, reject) => {
* @param {String} textName la key del json que se usará como text del elemento option $.ajax({
* @returns {Promise} Promise retorna status, msg url: obj.url,
*/ type: obj.type,
headers: obj.headers,
data: {body:body},
beforeSend: (xhr, settings) => {
}, success: (response, textStatus, jqXHR) => {
resolve(response)
}, error: (jqXHR, textStatus, errorThrown) => {
reject({
status: jqXHR.status,
throw: errorThrown || {},
jqXHR: jqXHR,
request: obj
})
}
})
})
}
/*Ajax General*/
let createSelectOptions = (obj, valueName, textName) => { let createSelectOptions = (obj, valueName, textName) => {
let options = '' let options = ''
obj.forEach((data) => { obj.forEach((data) => {
......
...@@ -45,6 +45,15 @@ const httpRequest = { ...@@ -45,6 +45,15 @@ const httpRequest = {
"Authorization": Cookies.get('Authorization') "Authorization": Cookies.get('Authorization')
} }
}) })
},
getNewToken() {
return ajaxRequest({
url: '../RedireccionarServlet',
type: 'POST',
headers: {
"Authorization":"Bearer "+getToken()
}
})
} }
} }
...@@ -87,7 +96,46 @@ const DOMEvents = { ...@@ -87,7 +96,46 @@ const DOMEvents = {
.catch(err => console.log(err)) .catch(err => console.log(err))
}) })
} }
}
let getToken=()=>{
let authorization;
let auth = window.location.search;
if(auth!==null && auth.includes('%20')){
authorization =auth.split('%20');
}else{
authorization[1] ="";
}
return authorization[1];
}
let obtenerToken=()=>{
debugger
let token = getToken();
if(token!==null && token!==""){
httpRequest.getNewToken()
.then(data => {
if (data.status) {
delete data["status"]
Cookies.set('Authorization', `Bearer ${data.token}`, {expiry: 36000000})
Cookies.set('menu', `${JSON.stringify(data.menu)}`, {expiry: 36000000})
console.log("MENU main.js"+data.menu);
window.location.href = 'main.jsp';
// window.history.replaceState( {} , '', 'main.jsp' );
} else {
alert('No tienes autorización')
}
console.log(data)
})
// .then(()=>{
// promiseSqrt();
// })
.catch(err => console.log(err))
}
} }
DOMEvents.init() DOMEvents.init()
\ No newline at end of file //obtenerToken();
\ No newline at end of file
//
//function promiseSqrt(){
// return new Promise(function (fulfill, reject){
// setMenu();
// });
//}
let getToken=()=>{
let authorization;
let auth = window.location.search;
if(auth!==null && auth.includes('%20')){
authorization =auth.split('%20');
}else{
authorization[1] ="";
}
return authorization[1];
}
const httpRequest = {
getNewToken() {
return ajaxRequestGeneral({
url: '../RedireccionarServlet',
type: 'POST',
headers: {
"Authorization":"Bearer "+getToken()
}
})
}
}
let obtenerToken=()=>{
httpRequest.getNewToken()
.then(data => {
if (data.status) {
delete data["status"]
Cookies.set('Authorization', `Bearer ${data.token}`, {expiry: 36000000})
Cookies.set('menu', `${JSON.stringify(data.menu)}`, {expiry: 36000000})
console.log("MENU main.js"+data.menu);
// window.history.replaceState( {} , '', 'main.jsp' );
window.location.href = "main.jsp";
} else {
alert('No tienes autorización')
}
console.log(data)
})
// .then(()=>{
// promiseSqrt();
// })
.catch(err => console.log(err))
}
//let getNewToken = () =>{
// let auth = window.location.search;
// console.log("auth"+auth);
// if(auth!==null && auth.includes('%20')){
// let authorization =auth.split('%20');
// console.log("TOKEN+ "+authorization[1])
// $.ajax({
// url: '../RedireccionarServlet',
// type: 'POST',
// data: {
// },
// headers: {
// "Authorization":"Bearer "+authorization[1],
// "Accept": 'application/json'
// },
// dataType: 'json',
// success: function (data) {
// Cookies.set('Authorization', `Bearer ${data.token}`, {expiry: 36000000})
// Cookies.set('menu', `${JSON.stringify(data.menu)}`, {expiry: 36000000})
// console.log("MENU main.js"+data.menu);
//
// },
// error : function(xhr, errmsg, err) {
// console.log(xhr.status + ": " + xhr.responseText);
// }
// });
// }
// window.history.replaceState( {} , '', 'main.jsp' );
//}
//
//getNewToken();
obtenerToken();
\ No newline at end of file
const httpRequestt = {
getproyectos(params) {
return ajaxRequestGeneral({
url: 'http://172.16.2.53:8080/security-rest/api/proyecto/listarProyectoUsuario',
type: 'POST',
headers: {
"Content-type": 'application/json',
"Accept": 'application/json',
"Authorization":Cookies.get('Authorization')
},
body: params
})
}
}
let setProyecto = () => {
let params= {
"usuario" : "amoreno",
"pass" : "75441247",
"codigoProyecto":"2"
}
console.log("TOKEN : : : : :"+Cookies.get('Authorization'));
httpRequestt.getproyectos(params)
.then(data => {
if (data.status) {
delete data["status"];
let html='';
let proyectos = data.proyectos;
console.log(proyectos)
for(let i in proyectos){
// let url = proyectos[i].url;//produccion
let url = 'http://172.16.2.53:8080/proyecto-estandar/';//Pruebas
html+='<li><a href="'+url+'vistas/cargando.jsp?Authorization='+Cookies.get('Authorization')+'" class="redirect" class="deutsch" ><img src="assets/images/flags/de.png" alt=""> '
+ '<i class="glyphicon glyphicon-arrow-right"></i>'+proyectos[i].nombre+'</a></li>';
}
/*Pruebas*/
let url2 = 'http://172.16.2.53:8080/aplicaciones/';//Pruebas
html+='<li><a href="'+url2+'vistas/cargando.jsp?Authorization='+Cookies.get('Authorization')+'" class="redirect" class="deutsch" ><img src="assets/images/flags/de.png" alt=""> '
+ '<i class="glyphicon glyphicon-arrow-right"></i>Test</a></li>';
/*Pruebas*/
document.getElementById("proyectos").innerHTML = html;
} else {
// window.location.href = 'http://localhost:8080/aplicaciones/';
}
// console.log(data)
})
.catch(err => console.log(err))
}
setProyecto();
let getMenu = () => {
return JSON.parse(Cookies.get('menu'));
}
let setMenu = () => { let setMenu = () => {
let location = window.location; let location = window.location;
let position =getUrl(location.pathname,"/"); let position =getUrl(location.pathname,"/");
let path = location.pathname.substring(position+1);//obtiene el nombre de la vista jsp para activar la clase .active let path = location.pathname.substring(position+1);//obtiene el nombre de la vista jsp para activar la clase .active
let menu = document.getElementById("MENU"); let menu = document.getElementById("MENU");
let contenido = getMenu(); let contenido = JSON.parse(Cookies.get('menu'));
console.log(contenido) console.log(contenido)
let titulo = contenido.titulo; let titulo = contenido.titulo;
let modulo = titulo.modulo; let modulo = titulo.modulo;
...@@ -57,10 +54,6 @@ let setMenu = () => { ...@@ -57,10 +54,6 @@ let setMenu = () => {
html+='</li>'; html+='</li>';
} }
menu.innerHTML=html; menu.innerHTML=html;
// let activeUrl = window.location.href.substring(getUrl(location.href,"=")+1);
// let active = activeUrl.substring(0,activeUrl.length-4);
// $("#"+active).parent('li').addClass('active');
} }
let getUrl = (pathname,caracter) => { let getUrl = (pathname,caracter) => {
let position = 0; let position = 0;
......
/* global Cookies */ /* global Cookies */
((window, Cookies) => { //((window, Cookies) => {
console.log(Cookies.get('Authorization')) // console.log(Cookies.get('Authorization'))
if (Cookies.get('Authorization') === undefined) { // if (Cookies.get('Authorization') === undefined) {
window.location.href = "index.jsp" // window.location.href = "index.jsp"
} else { // } else {
console.log("Estas logueado") // console.log("Estas logueado")
} // }
})(window, Cookies); //})(window, Cookies);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Limitless - Responsive Web Application Kit by Eugene Kopyov</title>
<!-- Global stylesheets -->
<link href="https://fonts.googleapis.com/css?family=Roboto:400,300,100,500,700,900" rel="stylesheet" type="text/css">
<link href="../plantilla/assets/css/icons/icomoon/styles.css" rel="stylesheet" type="text/css">
<link href="../plantilla/assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="../plantilla/assets/css/core.css" rel="stylesheet" type="text/css">
<link href="../plantilla/assets/css/components.css" rel="stylesheet" type="text/css">
<link href="../plantilla/assets/css/colors.css" rel="stylesheet" type="text/css">
<link href="../plantilla/assets/css/extras/animate.min.css" rel="stylesheet" type="text/css">
<!-- /global stylesheets -->
<!-- Core JS files -->
<script type="text/javascript" src="../plantilla/assets/js/plugins/loaders/pace.min.js"></script>
<script type="text/javascript" src="../plantilla/assets/js/core/libraries/jquery.min.js"></script>
<script type="text/javascript" src="../plantilla/assets/js/core/libraries/bootstrap.min.js"></script>
<script type="text/javascript" src="../plantilla/assets/js/plugins/loaders/blockui.min.js"></script>
<!-- /core JS files -->
<!-- Theme JS files -->
<script type="text/javascript" src="../plantilla/assets/js/plugins/ui/prism.min.js"></script>
<script type="text/javascript" src="../plantilla/assets/js/core/app.js"></script>
<script type="text/javascript" src="../plantilla/assets/js/pages/extension_blockui.js"></script>
<!-- /theme JS files -->
</head>
<body>
<script src="../js/lib/cookies.js" type="text/javascript"></script>
<script src="../js/general.js" type="text/javascript"></script>
<script src="../js/pages/main.js" type="text/javascript"></script>
<script>
$.blockUI({
message: '<i class="icon-spinner4 spinner"></i>',
overlayCSS: {
backgroundColor: '#1b2024',
opacity: 0.8,
cursor: 'wait'
},
css: {
border: 0,
color: '#fff',
padding: 0,
backgroundColor: 'transparent'
}
});
</script>
</body>
</html>
\ No newline at end of file
...@@ -33,5 +33,10 @@ ...@@ -33,5 +33,10 @@
<script type="text/javascript" src="../plantilla/assets/js/pages/form_bootstrap_select.js"></script> <script type="text/javascript" src="../plantilla/assets/js/pages/form_bootstrap_select.js"></script>
<!--js--> <!--js-->
<script src="../js/pages/sidebar.js" type="text/javascript"></script> <script src="../js/pages/sidebar.js" type="text/javascript"></script>
<script>
((window) => {
window.history.replaceState( {} , '', 'main.jsp' );
})(window);
</script>
</body> </body>
</html> </html>
...@@ -29,4 +29,5 @@ ...@@ -29,4 +29,5 @@
<script type="text/javascript" src="../plantilla/assets/js/core/app.js"></script> <script type="text/javascript" src="../plantilla/assets/js/core/app.js"></script>
<!-- /core JS files --> <!-- /core JS files -->
<!-- /Generales --> <!-- /Generales -->
<script src="../js/general.js" type="text/javascript"></script> <script src="../js/general.js" type="text/javascript"></script>
\ No newline at end of file <script src="../js/pages/navbar.js" type="text/javascript"></script>
\ No newline at end of file
<!-- Main navbar --> <!-- Main navbar -->
<div class="navbar navbar-default header-highlight"> <div class="navbar navbar-default header-highlight">
<div class="navbar-header"> <div class="navbar-header">
<a class="navbar-brand" href="../vistas/main.jsp"><img src="../plantilla/assets/images/logo_light.png" alt=""></a> <a class="navbar-brand" href="../vistas/main.jsp"><img src="../plantilla/assets/images/logo_light.png" alt=""></a>
<ul class="nav navbar-nav visible-xs-block"> <ul class="nav navbar-nav visible-xs-block">
<li><a data-toggle="collapse" data-target="#navbar-mobile"><i class="icon-tree5"></i></a></li> <li><a data-toggle="collapse" data-target="#navbar-mobile"><i class="icon-tree5"></i></a></li>
<li><a class="sidebar-mobile-main-toggle"><i class="icon-paragraph-justify3"></i></a></li> <li><a class="sidebar-mobile-main-toggle"><i class="icon-paragraph-justify3"></i></a></li>
</ul> </ul>
</div> </div>
<div class="navbar-collapse collapse" id="navbar-mobile">
<ul class="nav navbar-nav">
<li><a class="sidebar-control sidebar-main-toggle hidden-xs"><i class="icon-paragraph-justify3"></i></a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown language-switch">
<a class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<img src="assets/images/flags/gb.png" class="position-left" alt="">
Sistemas
<span class="caret"></span>
</a>
<div class="navbar-collapse collapse" id="navbar-mobile"> <ul class="dropdown-menu" id="proyectos">
<ul class="nav navbar-nav"> </ul>
<li><a class="sidebar-control sidebar-main-toggle hidden-xs"><i class="icon-paragraph-justify3"></i></a></li> </li>
</ul>
<ul class="nav navbar-nav navbar-right"> <li class="dropdown dropdown-user">
<li class="dropdown dropdown-user"> <a class="dropdown-toggle" data-toggle="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown"> <img src="../plantilla/assets/images/placeholder.jpg" alt="">
<img src="../plantilla/assets/images/placeholder.jpg" alt=""> <span>Alonso Moreno Postigo</span>
<span>Alonso Moreno Postigo</span> <i class="caret"></i>
<i class="caret"></i> </a>
</a>
<ul class="dropdown-menu dropdown-menu-right"> <ul class="dropdown-menu dropdown-menu-right">
<li><a href="#" id="logOut"><i class="icon-switch2"></i> Logout</a></li> <li><a href="#" id="logOut"><i class="icon-switch2"></i> Logout</a></li>
</ul>
</li>
</ul> </ul>
</li> </div>
</ul>
</div>
</div> </div>
<!-- /main navbar --> <!-- /main navbar -->
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment