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;
@WebFilter("/*")
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_IP = "http://172.16.2.53:8080/proyecto-estandar/";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
......@@ -52,15 +53,16 @@ public class RequestFilter implements Filter, ServletContextListener {
String respuesta = "";
String urlRequested = "http://172.16.2.53:8080/security-rest/api/user/verificarLogin";
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 plantilla = request.getContextPath() + "/plantilla";
String js = request.getContextPath() + "/js";
String css = request.getContextPath() + "/css";
System.out.println(js);
String url = String.valueOf(request.getRequestURL());
if (url.equalsIgnoreCase(BASE) || url.contains(login) || url.contains(plantilla) || url.contains(js)|| url.contains(css)|| url.contains("index.jsp")||url.contains("main.jsp")) {
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")
|| url.contains("RedireccionarServlet")||url.contains("cargando.jsp")) {
chain.doFilter(request, response);
} else {
PostRequest postRequest = new PostRequest(urlRequested);
......@@ -133,9 +135,9 @@ public class RequestFilter implements Filter, ServletContextListener {
sendError(response);
}
}
} else {
sendError(response);
}
// } else {
// sendError(response);
// }
}
private void sendError (HttpServletResponse response) throws IOException{
......
<?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">
<!-- <welcome-file-list>
<!-- <welcome-file-list>
<welcome-file>/vistas/index.jsp</welcome-file>
</welcome-file-list>-->
<servlet>
......@@ -11,6 +11,10 @@
<servlet-name>UbigeoServlet</servlet-name>
<servlet-class>demojsoncrud.servlets.UbigeoServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>RedireccionarServlet</servlet-name>
<servlet-class>demojsoncrud.servlets.RedireccionarServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PersonaServlet</servlet-name>
<url-pattern>/PersonaServlet</url-pattern>
......@@ -19,6 +23,10 @@
<servlet-name>UbigeoServlet</servlet-name>
<url-pattern>/UbigeoServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RedireccionarServlet</servlet-name>
<url-pattern>/RedireccionarServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
......@@ -33,5 +41,4 @@
<error-code>404</error-code>
<location>/vistas/index.jsp</location>
</error-page>
</web-app>
/**
* Crea los elementos option del array que se pase como parametro
* @method createSelectOptions
* @param {JSONArray} obj array de objetos
* @param {String} valueName la key del json que se usará como value del elemento option
* @param {String} textName la key del json que se usará como text del elemento option
* @returns {Promise} Promise retorna status, msg
*/
/*Ajax genral*/
const ajaxRequestGeneral = obj => {
let body=JSON.stringify(obj.body);
return new Promise((resolve, reject) => {
$.ajax({
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 options = ''
obj.forEach((data) => {
......
......@@ -45,6 +45,15 @@ const httpRequest = {
"Authorization": Cookies.get('Authorization')
}
})
},
getNewToken() {
return ajaxRequest({
url: '../RedireccionarServlet',
type: 'POST',
headers: {
"Authorization":"Bearer "+getToken()
}
})
}
}
......@@ -87,7 +96,46 @@ const DOMEvents = {
.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()
//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 location = window.location;
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 menu = document.getElementById("MENU");
let contenido = getMenu();
let contenido = JSON.parse(Cookies.get('menu'));
console.log(contenido)
let titulo = contenido.titulo;
let modulo = titulo.modulo;
......@@ -57,10 +54,6 @@ let setMenu = () => {
html+='</li>';
}
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 position = 0;
......
/* global Cookies */
((window, Cookies) => {
console.log(Cookies.get('Authorization'))
if (Cookies.get('Authorization') === undefined) {
window.location.href = "index.jsp"
} else {
console.log("Estas logueado")
}
})(window, Cookies);
//((window, Cookies) => {
// console.log(Cookies.get('Authorization'))
// if (Cookies.get('Authorization') === undefined) {
// window.location.href = "index.jsp"
// } else {
// console.log("Estas logueado")
// }
//})(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 @@
<script type="text/javascript" src="../plantilla/assets/js/pages/form_bootstrap_select.js"></script>
<!--js-->
<script src="../js/pages/sidebar.js" type="text/javascript"></script>
<script>
((window) => {
window.history.replaceState( {} , '', 'main.jsp' );
})(window);
</script>
</body>
</html>
......@@ -30,3 +30,4 @@
<!-- /core JS files -->
<!-- /Generales -->
<script src="../js/general.js" type="text/javascript"></script>
<script src="../js/pages/navbar.js" type="text/javascript"></script>
\ No newline at end of file
......@@ -15,6 +15,17 @@
</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>
<ul class="dropdown-menu" id="proyectos">
</ul>
</li>
<li class="dropdown dropdown-user">
<a class="dropdown-toggle" data-toggle="dropdown">
<img src="../plantilla/assets/images/placeholder.jpg" alt="">
......
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