List of usage examples for javax.servlet.http HttpServletRequest getRemoteHost
public String getRemoteHost();
From source file:org.openecomp.sdnc.filters.LogFilter.java
private void post(HttpServletRequest request, HttpServletResponse response, long startTime) { //AUDIT.info("{}|{}|{}{}",request.getRemoteHost(),request.getMethod(),request.getRequestURL().toString(),request.getQueryString()); //AUDIT.info(request.getRemoteHost() + D + request.getMethod() + D + request.getRequestURL().toString() + D + request.getQueryString()); //METRIC.info(request.getMethod() + D + response.getStatus() + D + request.getRequestURL().toString() + D + (System.currentTimeMillis() - startTime) + " ms"); MDC.put(BEGIN_TIMESTAMP, asIso8601(startTime)); MDC.put(END_TIMESTAMP, asIso8601(System.currentTimeMillis())); //MDC.put(REQUEST_ID,"already done above"); MDC.put(SERVICE_NAME, request.getRequestURL().toString()); int idx = request.getPathInfo().toString().lastIndexOf(":"); String instance = ""; if (idx != -1) { instance = request.getPathInfo().substring(idx + 1); }/*from w ww.jav a 2 s . co m*/ MDC.put(SERVICE_INSTANCE, instance); MDC.put(THREAD_ID, ""); MDC.put(PHYSICAL_SERVER_NAME, ""); //MDC.put(PARTNER_NAME,"already done above"); if (response.getStatus() >= 400) { MDC.put(STATUS_CODE, "ERROR"); } else { MDC.put(STATUS_CODE, "COMPLETE"); } MDC.put(RESP_CODE, "" + response.getStatus()); MDC.put(RESP_DESC, ""); MDC.put(INSTANCE_UUID, ""); MDC.put(CATEGORY, ""); MDC.put(SEVERITY, ""); //MDC.put(SERVER_IP,""); //by chef MDC.put(ELAPSED_TIME, "" + (System.currentTimeMillis() - startTime)); //MDC.put(SERVER_HOST,""); //by chef MDC.put(CLIENT_IP, request.getRemoteHost()); MDC.put(CLASS, ""); MDC.put(UNUSED, ""); MDC.put(PROCESS_KEY, ""); MDC.put(CUST_1, ""); MDC.put(CUST_2, ""); MDC.put(CUST_3, ""); MDC.put(CUST_4, ""); MDC.put(DETAIL_MESSAGE, request.getMethod()); AUDIT.info(""); }
From source file:org.mitre.openid.connect.assertion.SAML3AssertionTokenEndpointFilter.java
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { LOG.debug("Arrive dans attemptAuthentication"); Authentication ret = null;/* w w w . j av a2 s . c o m*/ String SAMLResponse = request.getParameter("SAMLResponse"); String relayState = request.getParameter(RELAYSTATE); if (relayState == null) { logger.debug("Pas de relayState null"); } else if (relayState.isEmpty()) { logger.debug("Pas de relayState vide"); } else { if (relayStateRepository == null) { relayStateRepository = ApplicationContextProvider.getApplicationContext() .getBean(RelayStateRepositoryService.class); } if (relayStateRepository.existRelayState(relayState)) { logger.debug("retour avec relayState=" + relayState); } else { logger.error("retour avec mauvais relayState=" + relayState); throw new BadCredentialsException("bad csrf relayState"); } } EIDASAuthnResponse authnResponse = null; IPersonalAttributeList personalAttributeList = null; logger.debug("Arrive dans filtre SAML attemptAuthentication"); //spUrl = configs.getProperty(Constants.SP_URL); //Decodes SAML Response byte[] decSamlToken = EIDASUtil.decodeSAMLToken(SAMLResponse); //Get SAMLEngine instance try { EIDASSAMLEngine engine = SPUtil.createSAMLEngine(Constants.SP_CONF); //validate SAML Token authnResponse = engine.validateEIDASAuthnResponse(decSamlToken, request.getRemoteHost(), 0); } catch (EIDASSAMLEngineException e) { logger.error(e.getMessage()); if (StringUtils.isEmpty(e.getErrorDetail())) { throw new IOException(SAML_VALIDATION_ERROR, e); } else { throw new IOException(SAML_VALIDATION_ERROR, e); } } Set<GrantedAuthority> authorities = new HashSet<>(); String userId = null; if (authnResponse.isFail()) { throw new IOException("Saml Response is fail" + authnResponse.getMessage()); } else { LOG.info("token saml valide cherche userId"); personalAttributeList = authnResponse.getPersonalAttributeList(); for (PersonalAttribute pa : personalAttributeList) { if (pa.getName().equalsIgnoreCase("personidentifier")) { userId = pa.getValue().get(0); break; } } } if (userId == null) { throw new IOException("Pas trouve personidentifier dans attributs SAML"); } //ajoute les attributs de l'utilisateur for (String nom : lesNoms()) { for (PersonalAttribute pa : personalAttributeList) { if (pa.getName().equalsIgnoreCase(nom)) { authorities.add(new SimpleGrantedAuthority(pa.getValue().get(0))); break; } } } //attention c'est un raccourci normalement il faut passer par authentProvider !!! authorities.add(ROLE_CLIENT); authorities.add(ROLE_USER); authorities.add(ROLE_ADMIN); authorities.add(ROLE_ANONYMOUS); SAML2AssertionAuthenticationToken authTok = new SAML2AssertionAuthenticationToken(userId, authorities); authTok.setDetails(personalAttributeList); UserInfo userInf = new SamlUserInfo(personalAttributeList); if (userInfServ != null) { ((DefaultUserInfoService) userInfServ).addUserInfo(userInf); } else { LOG.error("marche pas injection GRRRRR !"); } authTok.setAuthnResponse(authnResponse); ret = ((Authentication) authTok); return ret; }
From source file:fsi_admin.JPacConn.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ERROR = null, codErr = null; try {//from ww w.java2 s . c om boolean CANCEL = false, TEST = true; //Protege el timbrado a pruebas if (request.getParameter("TEST") != null) TEST = (request.getParameter("TEST").equals("false") ? false : true); if (request.getParameter("CANCEL") != null) CANCEL = (request.getParameter("CANCEL").equals("false") ? false : true); if (request.getParameter("SERVER") == null || request.getParameter("DATABASE") == null || request.getParameter("USER") == null || request.getParameter("PASSWORD") == null || request.getParameter("NAME") == null) { System.out.println("No recibi parametros de conexion antes del archivo a recibir"); ERROR = "ERROR: El servidor no recibi todos los parametros de conexion (SERVER,DATABASE,USER,PASSWORD) antes del archivo XML a recibir"; codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), request.getParameter("SERVER"), request.getParameter("USER"), request.getParameter("PASSWORD"), request, ERROR, 3); } //Hasta aqui se han enviado todos los parametros ninguno nulo if (ERROR == null) { StringBuffer msj = new StringBuffer(), PACURL = new StringBuffer(), PACUSR = new StringBuffer(), PACPASS = new StringBuffer(); MutableBoolean COBRAR = new MutableBoolean(false); MutableDouble COSTO = new MutableDouble(0.0), SALDO = new MutableDouble(0.0); // Primero obtiene info del PAC if (!obtenInfoPAC(request.getRemoteAddr(), request.getRemoteHost(), request.getParameter("SERVER"), request.getParameter("DATABASE"), request.getParameter("USER"), request.getParameter("PASSWORD"), PACURL, PACUSR, PACPASS, msj, COSTO, SALDO, COBRAR)) { System.out.println("El usuario y contrasea de servicio estan mal"); ERROR = msj.toString(); codErr = "2"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), request.getParameter("SERVER"), request.getParameter("USER"), request.getParameter("PASSWORD"), request, ERROR, 2); } else { if (CANCEL == false) //Intenta sellar documento mandado { if (COBRAR.booleanValue() && SALDO.doubleValue() < COSTO.doubleValue()) { System.out.println("El servicio tiene un costo que no alcanza en el saldo"); ERROR = "El servicio de timbrado tiene un costo que no alcanza en el saldo"; codErr = "2"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), request.getParameter("SERVER"), request.getParameter("USER"), request.getParameter("PASSWORD"), request, ERROR, 2); } else { if (!salvarArchivoSubido(request.getParameter("SERVER"), request.getParameter("DATABASE"), request.getParameter("NAME"), request.getParameter("CFDXML"), msj)) { System.out.println("No se permiti subir el archivo"); ERROR = msj.toString(); codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), request.getParameter("SERVER"), request.getParameter("USER"), request.getParameter("PASSWORD"), request, ERROR, 3); } else { StringBuffer registrar = new StringBuffer(""); if (!generarTFD(request.getParameter("SERVER"), request.getParameter("DATABASE"), request.getParameter("NAME"), PACURL.toString(), PACUSR.toString(), PACPASS.toString(), TEST, registrar, msj)) { System.out.println("Errores al sellar el documento"); ERROR = msj.toString(); codErr = "1"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), request.getParameter("SERVER"), request.getParameter("USER"), request.getParameter("PASSWORD"), request, ERROR, 1); } else // de lo contrario, regresa el archivo del sello { if (!registrar.toString().equals("false")) ingresarRegistroExitoso(request.getParameter("SERVER"), request.getParameter("DATABASE"), request.getParameter("NAME"), TEST, COSTO, SALDO, COBRAR); else System.out.println( "No se registro en exitosos porque ya existia registro de este timbre"); String nombre = "/usr/local/forseti/pac/TFDs/" + request.getParameter("SERVER") + "-" + request.getParameter("DATABASE") + "-SIGN_" + request.getParameter("NAME") + ".xml"; String destino = "SIGN_" + request.getParameter("NAME") + ".xml"; JBajarArchivo fd = new JBajarArchivo(); fd.doDownload(response, getServletConfig().getServletContext(), nombre, destino); //Finalmente, borra el archivo xml del cfd y los zip String strFilePathZip = "/usr/local/forseti/pac/CFDs/" + request.getParameter("SERVER") + "-" + request.getParameter("DATABASE") + "-" + request.getParameter("NAME") + ".zip"; String strFilePathXML = "/usr/local/forseti/pac/CFDs/" + request.getParameter("SERVER") + "-" + request.getParameter("DATABASE") + "-" + request.getParameter("NAME") + ".xml"; String strFilePathZip2 = "/usr/local/forseti/pac/TFDs/" + request.getParameter("SERVER") + "-" + request.getParameter("DATABASE") + "-" + request.getParameter("NAME") + ".zip"; File fileZip = new File(strFilePathZip); File fileXML = new File(strFilePathXML); File fileZip2 = new File(strFilePathZip2); if (fileZip.exists()) fileZip.delete(); if (fileXML.exists()) fileXML.delete(); if (fileZip2.exists()) fileZip2.delete(); } } } } else // Es una cancelacion { if (!salvarArchivoSubidoCER_KEY(request.getParameter("SERVER"), request.getParameter("DATABASE"), request.getParameter("NAME"), request.getParameter("CERPEM"), request.getParameter("KEYPEM"), msj)) { System.out.println("No se permiti subir el archivo pfx"); ERROR = msj.toString(); codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), request.getParameter("SERVER"), request.getParameter("USER"), request.getParameter("PASSWORD"), request, ERROR, 3); } else { if (!generarCancelacion(request.getParameter("SERVER"), request.getParameter("DATABASE"), request.getParameter("NAME"), PACURL.toString(), PACUSR.toString(), PACPASS.toString(), msj)) { System.out.println("Errores al cancelar el documento"); ERROR = msj.toString(); codErr = "1"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), request.getParameter("SERVER"), request.getParameter("USER"), request.getParameter("PASSWORD"), request, ERROR, 1); } else // de lo contrario, regresa el archivo de la cancelacion { ingresarCancelacionExitosa(request.getParameter("SERVER"), request.getParameter("DATABASE"), request.getParameter("NAME")); String nombre = "/usr/local/forseti/pac/TFDs/" + request.getParameter("SERVER") + "-" + request.getParameter("DATABASE") + "-CANCEL_" + request.getParameter("NAME") + ".xml"; String destino = "CANCEL_" + request.getParameter("NAME") + ".xml"; JBajarArchivo fd = new JBajarArchivo(); fd.doDownload(response, getServletConfig().getServletContext(), nombre, destino); //Finalmente, borra los archivos pem String strFilePathCer = "/usr/local/forseti/pac/TFDs/" + request.getParameter("SERVER") + "-" + request.getParameter("DATABASE") + "-" + request.getParameter("NAME") + ".cer.pem"; String strFilePathKey = "/usr/local/forseti/pac/TFDs/" + request.getParameter("SERVER") + "-" + request.getParameter("DATABASE") + "-" + request.getParameter("NAME") + ".key.pem"; File fileCer = new File(strFilePathCer); File fileKey = new File(strFilePathKey); if (fileCer.exists()) fileCer.delete(); if (fileKey.exists()) fileKey.delete(); } } } } } } catch (Exception e) { e.printStackTrace(); ERROR = "ERROR DE EXCEPCION EN SERVIDOR PAC: " + e.getMessage(); } //Genera el archivo XML de error para ser devuelto al Servidor if (ERROR != null) { Element SIGN_ERROR = new Element("SIGN_ERROR"); SIGN_ERROR.setAttribute("CodError", codErr); SIGN_ERROR.setAttribute("MsjError", ERROR); Document Reporte = new Document(SIGN_ERROR); Format format = Format.getPrettyFormat(); format.setEncoding("utf-8"); format.setTextMode(TextMode.NORMALIZE); XMLOutputter xmlOutputter = new XMLOutputter(format); ByteArrayOutputStream out = new ByteArrayOutputStream(); xmlOutputter.output(Reporte, out); byte[] data = out.toByteArray(); ByteArrayInputStream istream = new ByteArrayInputStream(data); String destino = "SIGN_ERROR.xml"; JBajarArchivo fd = new JBajarArchivo(); fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length, destino); } }
From source file:fsi_admin.JAwsS3Conn.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ERROR = null, codErr = null; try {//w ww . j a va 2s. c o m Properties parametros = new Properties(); Vector archivos = new Vector(); DiskFileUpload fu = new DiskFileUpload(); List items = fu.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) parametros.put(item.getFieldName(), item.getString()); else archivos.addElement(item); } if (parametros.getProperty("SERVER") == null || parametros.getProperty("DATABASE") == null || parametros.getProperty("USER") == null || parametros.getProperty("PASSWORD") == null || parametros.getProperty("ACTION") == null) { System.out.println("No recibi parametros de conexin antes del archivo"); ERROR = "ERROR: El servidor no recibi todos los parametros de conexion (SERVER,DATABASE,USER,PASSWORD,ACTION) antes del archivo"; codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 3); } //Hasta aqui se han enviado todos los parametros ninguno nulo if (ERROR == null) { StringBuffer msj = new StringBuffer(), S3BUKT = new StringBuffer(), S3USR = new StringBuffer(), S3PASS = new StringBuffer(); MutableBoolean COBRAR = new MutableBoolean(false); MutableDouble COSTO = new MutableDouble(0.0), SALDO = new MutableDouble(0.0); // Primero obtiene info del S3 if (!obtenInfoAWSS3(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), S3BUKT, S3USR, S3PASS, msj, COSTO, SALDO, COBRAR)) { System.out.println("El usuario y contrasea de servicio estan mal"); ERROR = msj.toString(); codErr = "2"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 2); } else { AWSCredentials credentials = new BasicAWSCredentials(S3USR.toString(), S3PASS.toString()); AmazonS3 s3 = new AmazonS3Client(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); s3.setRegion(usWest2); //System.out.println("AwsConn:" + parametros.getProperty("NOMBRE") + ":parametros.getProperty(NOMBRE)"); String nombre = parametros.getProperty("SERVER") + parametros.getProperty("DATABASE") + parametros.getProperty("ID_MODULO") + parametros.getProperty("OBJIDS") + parametros.getProperty("IDSEP") + parametros.getProperty("NOMBRE"); //System.out.println("AwsConn_Nombre:" + nombre + ":nombre"); if (parametros.getProperty("ACTION").equals("SUBIR")) { Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES"))); Double TAMBITES = new Double(Double.parseDouble(parametros.getProperty("TAMBITES"))); if (COBRAR.booleanValue() && SALDO .doubleValue() < (COSTO.doubleValue() * (((TOTBITES + TAMBITES) / 1024) / 1024))) { System.out .println("El servicio S3 de subida tiene un costo que no alcanza en el saldo"); ERROR = "El servicio S3 de subida tiene un costo que no alcanza en el saldo"; codErr = "2"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 2); } else { if (!subirArchivo(msj, s3, S3BUKT.toString(), nombre, archivos)) { System.out.println("No se permiti subir el archivo al s3"); ERROR = msj.toString(); codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 3); } else { ingresarRegistroExitoso(parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"), parametros.getProperty("ID_MODULO"), parametros.getProperty("OBJIDS"), parametros.getProperty("IDSEP"), parametros.getProperty("NOMBRE"), parametros.getProperty("TAMBITES")); } } } else if (parametros.getProperty("ACTION").equals("ELIMINAR")) { Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES"))); if (COBRAR.booleanValue() && SALDO.doubleValue() < (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024))) { System.out .println("El servicio S3 de borrado tiene un costo que no alcanza en el saldo"); ERROR = "El servicio S3 de borrado tiene un costo que no alcanza en el saldo"; codErr = "2"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 2); } else { if (!eliminarArchivo(msj, s3, S3BUKT.toString(), nombre)) { System.out.println("No se permiti eliminar el archivo del s3"); ERROR = msj.toString(); codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 3); } else { eliminarRegistroExitoso(parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"), parametros.getProperty("ID_MODULO"), parametros.getProperty("OBJIDS"), parametros.getProperty("IDSEP"), parametros.getProperty("NOMBRE")); } } } else if (parametros.getProperty("ACTION").equals("DESCARGAR")) { Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES"))); //System.out.println("COBRAR: " + COBRAR.booleanValue() + " SALDO: " + SALDO.doubleValue() + " COSTO: " + COSTO.doubleValue() + " TOTBITES: " + TOTBITES + " TOTMB: " + ((TOTBITES / 1024) / 1024) + " RES: " + (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024))); if (COBRAR.booleanValue() && SALDO.doubleValue() < (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024))) { System.out.println( "El servicio S3 de descarga tiene un costo que no alcanza en el saldo"); ERROR = "El servicio S3 de descarga tiene un costo que no alcanza en el saldo"; codErr = "2"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 2); } else { if (!descargarArchivo(response, msj, s3, S3BUKT.toString(), nombre, parametros.getProperty("NOMBRE"))) { System.out.println("No se permiti descargar el archivo del s3"); ERROR = msj.toString(); codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 3); } else return; } } if (ERROR == null) { //Devuelve la respuesta al cliente Element S3 = new Element("S3"); S3.setAttribute("Archivo", nombre); S3.setAttribute("MsjError", ""); Document Reporte = new Document(S3); Format format = Format.getPrettyFormat(); format.setEncoding("utf-8"); format.setTextMode(TextMode.NORMALIZE); XMLOutputter xmlOutputter = new XMLOutputter(format); ByteArrayOutputStream out = new ByteArrayOutputStream(); xmlOutputter.output(Reporte, out); byte[] data = out.toByteArray(); ByteArrayInputStream istream = new ByteArrayInputStream(data); String destino = "Archivo.xml"; JBajarArchivo fd = new JBajarArchivo(); fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length, destino); } } } } catch (Exception e) { e.printStackTrace(); ERROR = "ERROR DE EXCEPCION EN SERVIDOR AWS S3: " + e.getMessage(); } //Genera el archivo XML de error para ser devuelto al Servidor if (ERROR != null) { Element SIGN_ERROR = new Element("SIGN_ERROR"); SIGN_ERROR.setAttribute("CodError", codErr); SIGN_ERROR.setAttribute("MsjError", ERROR); Document Reporte = new Document(SIGN_ERROR); Format format = Format.getPrettyFormat(); format.setEncoding("utf-8"); format.setTextMode(TextMode.NORMALIZE); XMLOutputter xmlOutputter = new XMLOutputter(format); ByteArrayOutputStream out = new ByteArrayOutputStream(); xmlOutputter.output(Reporte, out); byte[] data = out.toByteArray(); ByteArrayInputStream istream = new ByteArrayInputStream(data); String destino = "SIGN_ERROR.xml"; JBajarArchivo fd = new JBajarArchivo(); fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length, destino); } }
From source file:edu.umich.its.lti.google.GoogleLtiServlet.java
/** * Verifies if the request is valid; if so, this initializes Google Drive so * the browser may make requests to see resources associated with the given * ToolConsumer(TC) site./* w w w . j a v a 2s . c om*/ */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { if (verifyPost(request, response)) { bundleManipulation(request); TcSessionData tcSessionData = lockInSession(request); if (tcSessionData == null) { doError(request, response, resource.getString("gd.launch.post.failure")); return; } List<String> roster = RosterClientUtils.getRoster(tcSessionData); int googleSharingLimit = 0; String googleSharingLimitString = getGoogleServiceAccount(request.getRemoteHost()) .getGoogleSharingLimit(); if (googleSharingLimitString == null || (googleSharingLimitString.isEmpty())) { doError(request, response, resource.getString("gd.launch.error.msg.google.sharing.limit.missing")); M_log.error( "The Google sharing Limit variable is missing from googleServiceProps.properties file"); return; } else { googleSharingLimit = Integer.parseInt(googleSharingLimitString); } /*Checking if the roster size is greater than Google accepted limit. Made the limit configurable in case google changes that in future. The Logic (roster-1) meaning, the person sharing his folder is also included in roster. So the Folder is already owned by him so google won't apply the sharing limit on owner of the folder */ if (googleSharingLimit != ZERO) { if ((roster.size() - 1) >= googleSharingLimit) { StringBuilder sb = new StringBuilder(); sb.append( "The Roster size is greater than the google acceptable support while sharing a folder/file. the roster size: \""); sb.append(roster.size()); sb.append("\" for the context id: \""); sb.append(tcSessionData.getContextId()); sb.append("\" User Id: \""); sb.append(tcSessionData.getUserId()); sb.append("\" Email Address: \""); sb.append(tcSessionData.getUserEmailAddress()); sb.append("\""); M_log.error(sb.toString()); doError(request, response, MessageFormat.format( resource.getString( "gd.launch.error.msg.roster.size.greater.than.google.approved"), googleSharingLimit)); return; } } TcSiteToGoogleLink link = TcSiteToGoogleStorage.getLinkingFromSettingService(tcSessionData, request); if ((link != null)) { loadJspPage(request, response, tcSessionData, JspPage.Home); } else if (tcSessionData.getIsInstructor()) { loadJspPage(request, response, tcSessionData, JspPage.LinkFolder); } else { loadJspPage(request, response, tcSessionData, JspPage.Home); } } } catch (Exception e) { M_log.error("POST request failed", e); } }
From source file:edu.umich.its.lti.google.GoogleLtiServlet.java
/** * Send response to the browser with the access token for Google Drive and the given user email address. * // w w w. j a v a 2s .c o m * If the user's email address is empty, write a message to the log and to the response. * * If the access token string returned from Google is null, an error has occurred. Most likely it means * the user doesn't have a valid Google account. Write a message to the log, then send the string "ERROR" as the * response. */ private void getGoogleAccessToken(HttpServletRequest request, HttpServletResponse response, TcSessionData tcSessionData) throws IOException { String userEmailAddress = tcSessionData.getUserEmailAddress(); if (getIsEmpty(userEmailAddress)) { M_log.error( "Error: unable to get access token - the ToolProvider(TP) server does not know the user's email address."); response.getWriter().print("ERROR"); return; } // Throws exception for bad email and other reasons. Should we catch it? GoogleAccessToken accessToken = GoogleSecurity.getGoogleAccessTokenWithTimeStamp( getGoogleServiceAccount(request.getRemoteHost()), userEmailAddress); request.getSession().setAttribute(ACCESS_TOKEN_IN_SESSION, accessToken); if (accessToken == null) { StringBuilder s = new StringBuilder(); s.append(" ERROR: User \""); s.append(tcSessionData.getUserSourceDid()); s.append( "\" does not have a valid Google account for Google Drive LTI. Unable to get access token or too many credentials got created in a short span of time So google refused to give more access Tokens for (Email: \""); s.append(userEmailAddress); s.append("\" ; ID: \""); s.append(tcSessionData.getUserId()); s.append(")\""); M_log.error(s.toString()); response.getWriter().print("ERROR"); return; } if (request.getMethod().equals("GET")) { StringBuilder jsonTokenObject = new StringBuilder("{"); jsonTokenObject.append("\"access_token\" : \"").append(accessToken.getToken()).append("\""); jsonTokenObject.append(", \"time_stamp\" : \"").append(accessToken.getTimeTokenCreated()).append("\""); jsonTokenObject.append("} "); response.getWriter().print(jsonTokenObject.toString()); } }
From source file:org.openiam.webadmin.role.RoleResourceController.java
@Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { log.info("RoleResourceController - onSubmit called."); RoleResourceCommand roleCommand = (RoleResourceCommand) command; String userId = (String) request.getSession().getAttribute("userId"); String domainId = (String) request.getSession().getAttribute("domainid"); String login = (String) request.getSession().getAttribute("login"); // current resource-role list List<Resource> curRoleResList = resourceDataService.getResourcesForRole(roleCommand.getDomainId(), roleCommand.getRoleId());/*from w ww .java 2s .c o m*/ List<Resource> newRoleResList = roleCommand.getResourceList(); // log.info("comparing new resource selection with current selecton."); if (newRoleResList != null) { for (Resource res : newRoleResList) { log.info("Checking resource id=" + res.getResourceId()); Resource curRes = getCurrentResource(res, curRoleResList); if (curRes == null && res.getSelected()) { // link role and resource log.info("Adding resource (1) " + res.getResourceId() + " to role=" + roleCommand.getRoleId()); resourceDataService.addResourceRole( getResourceRole(res, roleCommand.getRoleId(), roleCommand.getDomainId())); auditHelper.addLog("MODIFY", domainId, login, "WEBCONSOLE", userId, "0", "ROLE", roleCommand.getRoleId(), null, "SUCCESS", null, "ADD RESOURCE", res.getResourceId(), null, null, roleCommand.getRoleId() + "-" + roleCommand.getDomainId(), request.getRemoteHost()); } else { log.info("Check if resource should be removed"); log.info("Current Res=" + curRes); log.info("Res Selected=" + res.getSelected()); if (!res.getSelected() && curRes != null) { log.info("attemptng to remove association to resource: " + res.getResourceId()); // remove the association ResourceRole r = getResourceRole(curRes, roleCommand.getRoleId(), roleCommand.getDomainId()); if (r != null) { log.info("removing resource " + res.getResourceId() + " to role=" + roleCommand.getRoleId()); resourceDataService.removeResourceRole(r.getId()); auditHelper.addLog("MODIFY", domainId, login, "WEBCONSOLE", userId, "0", "ROLE", roleCommand.getRoleId(), null, "SUCCESS", null, "REMOVE RESOURCE", r.getId().getResourceId(), null, null, roleCommand.getRoleId() + "-" + roleCommand.getDomainId(), request.getRemoteHost()); } } } } } ModelAndView mav = new ModelAndView(getSuccessView()); return mav; }
From source file:edu.umich.its.lti.google.GoogleLtiServlet.java
private void getGoogleOwnerAccessToken(HttpServletRequest request, HttpServletResponse response, TcSessionData tcSessionData, String ownerEmailAddress) throws IOException { String accessToken = null;/*from www . j a v a 2s. c o m*/ if (ownerEmailAddress.equals(tcSessionData.getUserEmailAddress())) { GoogleAccessToken token = (GoogleAccessToken) request.getSession() .getAttribute(ACCESS_TOKEN_IN_SESSION); if (token != null) { accessToken = token.getToken(); } else { M_log.error("Error: When retriving the accessToken from the Session"); } } else { accessToken = GoogleSecurity.getGoogleAccessToken(getGoogleServiceAccount(request.getRemoteHost()), ownerEmailAddress); } if (accessToken != null) { response.getWriter().print(accessToken); } else { M_log.warn("ERROR: User \"" + tcSessionData.getUserSourceDid() + "\" got error in generating access token. (Email: " + ownerEmailAddress + "; ID: " + tcSessionData.getUserId() + ")"); response.getWriter().print("ERROR"); } }
From source file:org.hoteia.qalingo.core.web.util.impl.RequestUtilImpl.java
/** * /*from ww w . j a v a 2 s .c o m*/ */ public void addClickstream(final HttpServletRequest request) throws Exception { ClickstreamSession clickstream = getClickstreamSession(request); Date lastRequest = new Date(); clickstream.setLastRequest(lastRequest); clickstream.setHostname(request.getRemoteHost()); clickstream.getRequests().add(new ClickstreamRequest(request, lastRequest)); request.getSession().setAttribute(Constants.ENGINE_CLICKSTREAM, clickstream); }
From source file:org.nema.medical.mint.server.controller.JobsController.java
@RequestMapping(method = RequestMethod.POST, value = "/jobs/createstudy") public void createStudy(HttpServletRequest req, HttpServletResponse res) throws IOException { String studyUUID = UUID.randomUUID().toString(); String jobID = UUID.randomUUID().toString(); File jobFolder = new File(jobTemp, jobID); jobFolder.mkdirs();//from ww w .j a v a 2 s. c o m // the list of files uploaded List<File> files = new ArrayList<File>(); // the set of form parameters Map<String, String> params = new HashMap<String, String>(); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "expected multipart form data"); return; } try { handleUpload(req, jobFolder, files, params); } catch (FileUploadException e) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "unable to parse multipart form data"); return; } Iterator<File> iterator = files.iterator(); if (!iterator.hasNext()) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "at least one file (containing metadata) is required."); return; } JobInfo jobInfo = new JobInfo(); jobInfo.setId(jobID); jobInfo.setStudyID(studyUUID); jobInfo.setStatus(JobStatus.IN_PROGRESS); jobInfo.setStatusDescription("0% complete"); String jobURI = req.getContextPath() + "/jobs/status/" + jobInfo.getId(); jobInfoDAO.saveOrUpdateJobInfo(jobInfo); final MetadataType dataDictionary = availableTypes.get("DICOM"); StudyCreateProcessor processor = new StudyCreateProcessor(jobFolder, new File(studiesRoot, studyUUID), dataDictionary, req.getRemoteUser(), req.getRemoteHost(), jobInfoDAO, studyDAO, updateDAO); executor.execute(processor); // process immediately in the background res.setStatus(HttpServletResponse.SC_SEE_OTHER); res.setHeader("Location", jobURI); }