List of usage examples for javax.servlet.http HttpServletResponse encodeRedirectUrl
@Deprecated
public String encodeRedirectUrl(String url);
From source file:net.yacy.http.servlets.YaCyDefaultServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo;/*from ww w . j a v a 2 s .c om*/ Enumeration<String> reqRanges = null; boolean included = request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null; if (included) { pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO); if (pathInfo == null) { pathInfo = request.getPathInfo(); } } else { pathInfo = request.getPathInfo(); // Is this a Range request? reqRanges = request.getHeaders(HeaderFramework.RANGE); if (!hasDefinedRange(reqRanges)) { reqRanges = null; } } String pathInContext = pathInfo == null ? "/" : pathInfo; // this is the path of the resource in _resourceBase (= path within htroot respective htDocs) boolean endsWithSlash = pathInContext.endsWith(URIUtil.SLASH); // Find the resource Resource resource = null; try { // Look for a class resource boolean hasClass = false; if (reqRanges == null && !endsWithSlash) { final int p = pathInContext.lastIndexOf('.'); if (p >= 0) { String pathofClass = pathInContext.substring(0, p) + ".class"; Resource classresource = _resourceBase.addPath(pathofClass); // Does a class resource exist? if (classresource != null && classresource.exists() && !classresource.isDirectory()) { hasClass = true; } } } // find resource resource = getResource(pathInContext); if (!hasClass && (resource == null || !resource.exists()) && !pathInContext.contains("..")) { // try to get this in the alternative htDocsPath resource = Resource.newResource(new File(_htDocsPath, pathInContext)); } if (ConcurrentLog.isFine("FILEHANDLER")) { ConcurrentLog.fine("FILEHANDLER", "YaCyDefaultServlet: uri=" + request.getRequestURI() + " resource=" + resource); } // Handle resource if (!hasClass && (resource == null || !resource.exists())) { if (included) { throw new FileNotFoundException("!" + pathInContext); } response.sendError(HttpServletResponse.SC_NOT_FOUND); } else if (!resource.isDirectory()) { if (endsWithSlash && pathInContext.length() > 1) { String q = request.getQueryString(); pathInContext = pathInContext.substring(0, pathInContext.length() - 1); if (q != null && q.length() != 0) { pathInContext += "?" + q; } response.sendRedirect(response .encodeRedirectURL(URIUtil.addPaths(_servletContext.getContextPath(), pathInContext))); } else { if (hasClass) { // this is a YaCy servlet, handle the template handleTemplate(pathInfo, request, response); } else { if (included || passConditionalHeaders(request, response, resource)) { sendData(request, response, included, resource, reqRanges); } } } } else { // resource is directory String welcome; if (!endsWithSlash) { StringBuffer buf = request.getRequestURL(); synchronized (buf) { int param = buf.lastIndexOf(";"); if (param < 0) { buf.append('/'); } else { buf.insert(param, '/'); } String q = request.getQueryString(); if (q != null && q.length() != 0) { buf.append('?'); buf.append(q); } response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(buf.toString())); } } // else look for a welcome file else if (null != (welcome = getWelcomeFile(pathInContext))) { ConcurrentLog.fine("FILEHANDLER", "welcome={}" + welcome); // Forward to the index RequestDispatcher dispatcher = request.getRequestDispatcher(welcome); if (dispatcher != null) { if (included) { dispatcher.include(request, response); } else { dispatcher.forward(request, response); } } } else { if (included || passConditionalHeaders(request, response, resource)) { sendDirectory(request, response, resource, pathInContext); } } } } catch (IllegalArgumentException e) { ConcurrentLog.logException(e); if (!response.isCommitted()) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } finally { if (resource != null) { resource.close(); } } }
From source file:org.dspace.app.webui.servlet.admin.EditCommunitiesServlet.java
protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // First, see if we have a multipart request (uploading a logo) String contentType = request.getContentType(); if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) { // This is a multipart request, so it's a file upload processUploadLogo(context, request, response); return;/* w w w . j av a2 s .c om*/ } /* * Respond to submitted forms. Each form includes an "action" parameter * indicating what needs to be done (from the constants above.) */ int action = UIUtil.getIntParameter(request, "action"); /* * Most of the forms supply one or more of these values. Since we just * get null if we try and find something with ID -1, we'll just try and * find both here to save hassle later on */ Community community = Community.find(context, UIUtil.getIntParameter(request, "community_id")); Community parentCommunity = Community.find(context, UIUtil.getIntParameter(request, "parent_community_id")); Collection collection = Collection.find(context, UIUtil.getIntParameter(request, "collection_id")); // Just about every JSP will need the values we received request.setAttribute("community", community); request.setAttribute("parent", parentCommunity); request.setAttribute("collection", collection); /* * First we check for a "cancel" button - if it's been pressed, we * simply return to the main control page */ if (request.getParameter("submit_cancel") != null) { showControls(context, request, response); return; } // Now proceed according to "action" parameter switch (action) { case START_EDIT_COMMUNITY: storeAuthorizeAttributeCommunityEdit(context, request, community); // Display the relevant "edit community" page JSPManager.showJSP(request, response, "/tools/edit-community.jsp"); break; case START_DELETE_COMMUNITY: // Show "confirm delete" page JSPManager.showJSP(request, response, "/tools/confirm-delete-community.jsp"); break; case START_CREATE_COMMUNITY: // no authorize attribute will be given to the jsp so a "clean" creation form // will be always supplied, advanced setting on policies and admin group creation // will be possible after to have completed the community creation // Display edit community page with empty fields + create button JSPManager.showJSP(request, response, "/tools/edit-community.jsp"); break; case START_EDIT_COLLECTION: HarvestedCollection hc = HarvestedCollection.find(context, UIUtil.getIntParameter(request, "collection_id")); request.setAttribute("harvestInstance", hc); storeAuthorizeAttributeCollectionEdit(context, request, collection); // Display the relevant "edit collection" page JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); break; case START_DELETE_COLLECTION: // Show "confirm delete" page JSPManager.showJSP(request, response, "/tools/confirm-delete-collection.jsp"); break; case START_CREATE_COLLECTION: // Forward to collection creation wizard response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/tools/collection-wizard?community_id=" + community.getID())); break; case CONFIRM_EDIT_COMMUNITY: // Edit or creation of a community confirmed processConfirmEditCommunity(context, request, response, community); break; case CONFIRM_DELETE_COMMUNITY: // remember the parent community, if any Community parent = community.getParentCommunity(); // Delete the community community.delete(); // if community was top-level, redirect to community-list page if (parent == null) { response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/community-list")); } else // redirect to parent community page { response.sendRedirect( response.encodeRedirectURL(request.getContextPath() + "/handle/" + parent.getHandle())); } // Show main control page //showControls(context, request, response); // Commit changes to DB context.complete(); break; case CONFIRM_EDIT_COLLECTION: // Edit or creation of a collection confirmed processConfirmEditCollection(context, request, response, community, collection); break; case CONFIRM_DELETE_COLLECTION: // Delete the collection community.removeCollection(collection); // remove the collection object from the request, so that the user // will be redirected on the community home page request.removeAttribute("collection"); // Show main control page showControls(context, request, response); // Commit changes to DB context.complete(); break; default: // Erm... weird action value received. log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); } }
From source file:org.josso.liferay5.agent.LiferaySSOAgentFilter.java
@Override protected void processFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest) request; HttpServletResponse hres = (HttpServletResponse) response; // URI pattern matching is implemented programmatically in case this filter is bound to the root web context // (i.e. '/*' url pattern) required for intercepting locale-prefixed URLs. if (!hreq.getRequestURI().contains(LIFERAY_PORTAL_LOGIN_URI) && !hreq.getRequestURI().contains(LIFERAY_PORTAL_LOGOUT_URI) && !hreq.getRequestURI().contains(LIFERAY_GROUP_URI) && !hreq.getRequestURI().contains(LIFERAY_USER_URI) && !hreq.getRequestURI().contains(LIFERAY_WEB_URI) && !hreq.getRequestURI().contains(JOSSO_SECURITY_CHECK_URI)) { filterChain.doFilter(hreq, hres); return;//from ww w. j a va2s. co m } if (log.isDebugEnabled()) log.debug("Processing : " + hreq.getContextPath()); try { // ------------------------------------------------------------------ // Check with the agent if this context should be processed. // ------------------------------------------------------------------ String contextPath = hreq.getContextPath(); String vhost = hreq.getServerName(); long companyId = PortalUtil.getCompanyId(request); // In catalina, the empty context is considered the root context if ("".equals(contextPath)) contextPath = "/"; if (!_agent.isPartnerApp(vhost, contextPath)) { filterChain.doFilter(hreq, hres); if (log.isDebugEnabled()) log.debug("Context is not a josso partner app : " + hreq.getContextPath()); return; } // ------------------------------------------------------------------ // Check some basic HTTP handling // ------------------------------------------------------------------ // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath); if (cfg.isSendP3PHeader() && !hres.isCommitted()) { hres.setHeader("P3P", cfg.getP3PHeaderValue()); } // Get our session ... HttpSession session = hreq.getSession(true); // ------------------------------------------------------------------ // Check if the Liferay application required its login form [/c/portal/login] // ------------------------------------------------------------------ if (JossoLiferayProps.isEnabled(companyId) && hreq.getRequestURI().endsWith(LIFERAY_PORTAL_LOGIN_URI)) { if (log.isDebugEnabled()) log.debug("Requested liferay login: '" + hreq.getRequestURI() + "'"); //save referer url in case the user clicked on Login from some public resource (page) //so agent can redirect the user back to that page after successful login if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) { saveLoginBackToURL(hreq, hres, session, true); } else { saveLoginBackToURL(hreq, hres, session, false); } String loginUrl = _agent.buildLoginUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } // ------------------------------------------------------------------ // Check if the Liferay application required its logout form [/c/portal/logout] // ------------------------------------------------------------------ if (JossoLiferayProps.isEnabled(companyId) && hreq.getRequestURI().endsWith(LIFERAY_PORTAL_LOGOUT_URI)) { if (log.isDebugEnabled()) log.debug("Requested liferay logout: '" + hreq.getRequestURI() + "'"); String logoutUrl = _agent.buildLogoutUrl(hreq, cfg); if (log.isDebugEnabled()) log.debug("Redirecting to logout url '" + logoutUrl + "'"); // Clear previous COOKIE ... Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(ssoCookie); // invalidate session (unbind josso security context) session.invalidate(); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(logoutUrl)); return; } // ------------------------------------------------------------------ // Check for the single sign on cookie // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking for SSO cookie"); Cookie cookie = null; Cookie cookies[] = hreq.getCookies(); if (cookies == null) cookies = new Cookie[0]; for (int i = 0; i < cookies.length; i++) { if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) { cookie = cookies[i]; break; } } String jossoSessionId = (cookie == null) ? null : cookie.getValue(); LiferayLocalSession localSession = new LiferayLocalSession(session); // ------------------------------------------------------------------ // Check if the partner application submitted custom login form // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'"); } if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) { if (log.isDebugEnabled()) { log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'"); } LiferaySSOAgentRequest customAuthRequest = (LiferaySSOAgentRequest) doMakeSSOAgentRequest( cfg.getId(), SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq, hres); _agent.processRequest(customAuthRequest); return; } if (cookie == null || cookie.getValue().equals("-")) { // ------------------------------------------------------------------ // Trigger LOGIN OPTIONAL if required // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("SSO cookie is not present, verifying optional login process "); // We have no cookie, remember me is enabled and a security check without assertion was received ... // This means that the user could not be identified ... go back to the original resource if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") == null) { if (log.isDebugEnabled()) log.debug(_agent.getJossoSecurityCheckUri() + " received without assertion. Login Optional Process failed"); String requestURI = getSavedRequestURL(hreq); _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); return; } // This is a standard anonymous request! if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) { if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, attempting automatic login"); // Save current request, so we can co back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, but login optional process is not required"); } } if (log.isDebugEnabled()) log.debug("SSO cookie is not present, checking for outbound relaying"); if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null)) { log.debug("SSO cookie not present and relaying was not requested, skipping"); filterChain.doFilter(hreq, hres); return; } } // ------------------------------------------------------------------ // Check if this URI is subject to SSO protection // ------------------------------------------------------------------ if (_agent.isResourceIgnored(cfg, hreq)) { filterChain.doFilter(hreq, hres); return; } // This URI should be protected by SSO, go on ... if (log.isDebugEnabled()) log.debug("Session is: " + session); // ------------------------------------------------------------------ // Invoke the SSO Agent // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Executing agent..."); // ------------------------------------------------------------------ // Check if a user has been authenitcated and should be checked by the agent. // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null) { if (log.isDebugEnabled()) log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '" + hreq.getParameter("josso_assertion_id")); String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER); LiferaySSOAgentRequest relayRequest; if (log.isDebugEnabled()) log.debug("Outbound relaying requested for assertion id [" + assertionId + "]"); relayRequest = (LiferaySSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(relayRequest); if (entry == null) { // This is wrong! We should have an entry here! log.error( "Outbound relaying failed for assertion id [" + assertionId + "], no Principal found."); // Throw an exception and let the container send the INERNAL SERVER ERROR throw new ServletException("No Principal found. Verify your SSO Agent Configuration!"); } if (log.isDebugEnabled()) log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]"); if (log.isDebugEnabled()) log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]"); // The cookie is valid to for the partner application only ... in the future each partner app may // store a different auth. token (SSO SESSION) value cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure()); hres.addCookie(cookie); // Redirect the user to the original request URI (which will cause // the original request to be restored) String requestURI = getSavedSplashResource(hreq); if (requestURI == null) { requestURI = getSavedRequestURL(hreq); if (requestURI == null) { if (cfg.getDefaultResource() != null) { requestURI = cfg.getDefaultResource(); } else { // If no saved request is found, redirect to the partner app root : requestURI = hreq.getRequestURI().substring(0, (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length())); } // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?! String singlePointOfAccess = _agent.getSinglePointOfAccess(); if (singlePointOfAccess != null) { requestURI = singlePointOfAccess + requestURI; } else { String reverseProxyHost = hreq .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER); if (reverseProxyHost != null) { requestURI = reverseProxyHost + requestURI; } } if (log.isDebugEnabled()) log.debug("No saved request found, using : '" + requestURI + "'"); } } clearSavedRequestURLs(hreq, hres); _agent.clearAutomaticLoginReferer(hreq, hres); _agent.prepareNonCacheResponse(hres); // Check if we have a post login resource : String postAuthURI = cfg.getPostAuthenticationResource(); if (postAuthURI != null) { String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI); if (log.isDebugEnabled()) log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'"); hres.sendRedirect(postAuthURL); } else { if (log.isDebugEnabled()) log.debug("Redirecting to original '" + requestURI + "'"); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); } return; } SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(r); if (log.isDebugEnabled()) log.debug("Executed agent."); // Get session map for this servlet context. Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP); if (sessionMap.get(localSession.getWrapped()) == null) { // the local session is new so, make the valve listen for its events so that it can // map them to local session events. // Not supported : session.addSessionListener(this); sessionMap.put(session, localSession); } // ------------------------------------------------------------------ // Has a valid user already been authenticated? // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Process request for '" + hreq.getRequestURI() + "'"); if (entry != null) { if (log.isDebugEnabled()) log.debug("Principal '" + entry.principal + "' has already been authenticated"); // TODO : Not supported // (request).setAuthType(entry.authType); // (request).setUserPrincipal(entry.principal); } else { log.info("No Valid SSO Session, attempt an optional login?"); // This is a standard anonymous request! if (cookie != null) { // cookie is not valid cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(cookie); } if (cookie != null || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) { if (log.isDebugEnabled()) log.debug("SSO Session is not valid, attempting automatic login"); // Save current request, so we can co back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, but login optional process is not required"); } } // propagate the login and logout URLs to // partner applications. hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl()); hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl()); hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId); // ------------------------------------------------------------------ // Invoke the next Valve in our pipeline // ------------------------------------------------------------------ filterChain.doFilter(hreq, hres); } finally { if (log.isDebugEnabled()) log.debug("Processed : " + hreq.getContextPath()); } }
From source file:at.gv.egovernment.moa.id.auth.servlet.GetMISSessionIDServlet.java
/** * Gets the signer certificate from the InfoboxReadRequest and responds with * a new <code>CreateXMLSignatureRequest</code>. <br> * Request parameters:/*from w w w . j av a 2 s . co m*/ * <ul> * <li>MOASessionID: ID of associated authentication session</li> * <li>XMLResponse: <code><InfoboxReadResponse></code></li> * </ul> * * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, * HttpServletResponse) */ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Logger.debug("POST GetMISSessionIDServlet"); Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA); resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); // Map parameters; // try // { // parameters = getParameters(req); // } catch (FileUploadException e) // { // Logger.error("Parsing mulitpart/form-data request parameters failed: " // + e.getMessage()); // throw new IOException(e.getMessage()); // } String sessionID = req.getParameter(PARAM_SESSIONID); // escape parameter strings sessionID = StringEscapeUtils.escapeHtml(sessionID); AuthenticationSession session = null; String pendingRequestID = null; try { // check parameter if (!ParamValidatorUtils.isValidSessionID(sessionID)) throw new WrongParametersException("VerifyCertificate", PARAM_SESSIONID, "auth.12"); pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); session = AuthenticationServer.getSession(sessionID); //change MOASessionID sessionID = AuthenticationSessionStoreage.changeSessionID(session); String misSessionID = session.getMISSessionID(); AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); ConnectionParameter connectionParameters = authConf.getOnlineMandatesConnectionParameter(); SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(), connectionParameters); List<MISMandate> list = MISSimpleClient.sendGetMandatesRequest(connectionParameters.getUrl(), misSessionID, sslFactory); if (list == null || list.size() == 0) { Logger.error("Keine Vollmacht gefunden."); throw new AuthenticationException("auth.15", null); } // for now: list contains only one element MISMandate mandate = (MISMandate) list.get(0); // TODO[tlenz]: UTF-8 ? String sMandate = new String(mandate.getMandate()); if (sMandate == null || sMandate.compareToIgnoreCase("") == 0) { Logger.error("Mandate is empty."); throw new AuthenticationException("auth.15", new Object[] { GET_MIS_SESSIONID }); } //check if it is a parsable XML byte[] byteMandate = mandate.getMandate(); // TODO[tlenz]: UTF-8 ? String stringMandate = new String(byteMandate); DOMUtils.parseDocument(stringMandate, false, null, null).getDocumentElement(); // extract RepresentationType AuthenticationServer.getInstance().verifyMandate(session, mandate); session.setMISMandate(mandate); session.setAuthenticatedUsed(false); session.setAuthenticated(true); //set QAA Level four in case of card authentifcation session.setQAALevel(PVPConstants.STORK_QAA_1_4); String oldsessionID = session.getSessionID(); //Session is implicite stored in changeSessionID!!! String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); Logger.info("Changed MOASession " + oldsessionID + " to Session " + newMOASessionID); Logger.info("Daten angelegt zu MOASession " + newMOASessionID); String redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID), newMOASessionID); redirectURL = resp.encodeRedirectURL(redirectURL); resp.setContentType("text/html"); resp.setStatus(302); resp.addHeader("Location", redirectURL); Logger.debug("REDIRECT TO: " + redirectURL); } catch (MOAIDException ex) { handleError(null, ex, req, resp, pendingRequestID); } catch (GeneralSecurityException ex) { handleError(null, ex, req, resp, pendingRequestID); } catch (PKIException e) { handleError(null, e, req, resp, pendingRequestID); } catch (SAXException e) { handleError(null, e, req, resp, pendingRequestID); } catch (ParserConfigurationException e) { handleError(null, e, req, resp, pendingRequestID); } catch (Exception e) { Logger.error("MISMandateValidation has an interal Error.", e); } finally { ConfigurationDBUtils.closeSession(); } }
From source file:fll.web.setup.CreateDB.java
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { String redirect;// w w w .ja v a2 s . co m final StringBuilder message = new StringBuilder(); InitFilter.initDataSource(application); final DataSource datasource = ApplicationAttributes.getDataSource(application); Connection connection = null; try { connection = datasource.getConnection(); // must be first to ensure the form parameters are set UploadProcessor.processUpload(request); if (null != request.getAttribute("chooseDescription")) { final String description = (String) request.getAttribute("description"); try { final URL descriptionURL = new URL(description); final Document document = ChallengeParser .parse(new InputStreamReader(descriptionURL.openStream(), Utilities.DEFAULT_CHARSET)); GenerateDB.generateDB(document, connection); application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT); message.append("<p id='success'><i>Successfully initialized database</i></p>"); redirect = "/admin/createUsername.jsp"; } catch (final MalformedURLException e) { throw new FLLInternalException("Could not parse URL from choosen description: " + description, e); } } else if (null != request.getAttribute("reinitializeDatabase")) { // create a new empty database from an XML descriptor final FileItem xmlFileItem = (FileItem) request.getAttribute("xmldocument"); if (null == xmlFileItem || xmlFileItem.getSize() < 1) { message.append("<p class='error'>XML description document not specified</p>"); redirect = "/setup"; } else { final Document document = ChallengeParser .parse(new InputStreamReader(xmlFileItem.getInputStream(), Utilities.DEFAULT_CHARSET)); GenerateDB.generateDB(document, connection); application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT); message.append("<p id='success'><i>Successfully initialized database</i></p>"); redirect = "/admin/createUsername.jsp"; } } else if (null != request.getAttribute("createdb")) { // import a database from a dump final FileItem dumpFileItem = (FileItem) request.getAttribute("dbdump"); if (null == dumpFileItem || dumpFileItem.getSize() < 1) { message.append("<p class='error'>Database dump not specified</p>"); redirect = "/setup"; } else { ImportDB.loadFromDumpIntoNewDB(new ZipInputStream(dumpFileItem.getInputStream()), connection); // remove application variables that depend on the database application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT); message.append("<p id='success'><i>Successfully initialized database from dump</i></p>"); redirect = "/admin/createUsername.jsp"; } } else { message.append( "<p class='error'>Unknown form state, expected form fields not seen: " + request + "</p>"); redirect = "/setup"; } } catch (final FileUploadException fue) { message.append("<p class='error'>Error handling the file upload: " + fue.getMessage() + "</p>"); LOG.error(fue, fue); redirect = "/setup"; } catch (final IOException ioe) { message.append("<p class='error'>Error reading challenge descriptor: " + ioe.getMessage() + "</p>"); LOG.error(ioe, ioe); redirect = "/setup"; } catch (final SQLException sqle) { message.append("<p class='error'>Error loading data into the database: " + sqle.getMessage() + "</p>"); LOG.error(sqle, sqle); redirect = "/setup"; } finally { SQLFunctions.close(connection); } session.setAttribute("message", message.toString()); response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + redirect)); }
From source file:com.wso2telco.gsma.authenticators.sms.SMSAuthenticator.java
protected SMSMessage getRedirectInitAuthentication(HttpServletResponse response, AuthenticationContext context, UserStatus userStatus) throws AuthenticationFailedException { SMSMessage smsMessage = null;/* w ww . ja v a2s. c om*/ String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL(); String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(), context.getCallerSessionKey(), context.getContextIdentifier()); if (log.isDebugEnabled()) { log.debug("Query parameters : " + queryParams); } try { String retryParam = ""; if (context.isRetrying()) { retryParam = "&authFailure=true&authFailureMsg=login.fail.message"; } else { // Insert entry to DB only if this is not a retry DBUtils.insertUserResponse(context.getContextIdentifier(), String.valueOf(UserResponse.PENDING)); } //MSISDN will be saved in the context in the MSISDNAuthenticator String msisdn = (String) context.getProperty(Constants.MSISDN); Application application = new Application(); MobileConnectConfig connectConfig = configurationService.getDataHolder().getMobileConnectConfig(); MobileConnectConfig.SMSConfig smsConfig = connectConfig.getSmsConfig(); String encryptedContextIdentifier = AESencrp.encrypt(context.getContextIdentifier()); String messageURL = connectConfig.getSmsConfig().getAuthUrl() + Constants.AUTH_URL_ID_PREFIX; Map<String, String> paramMap = Util.createQueryParamMap(queryParams); String client_id = paramMap.get(Constants.CLIENT_ID); String operator = (String) context.getProperty(Constants.OPERATOR); if (smsConfig.isShortUrl()) { // If a URL shortening service is enabled, then we need to encrypt the context identifier, create the // message URL and shorten it. SelectShortUrl selectShortUrl = new SelectShortUrl(); messageURL = selectShortUrl.getShortUrl(smsConfig.getShortUrlClass(), messageURL + response.encodeURL(encryptedContextIdentifier), smsConfig.getAccessToken(), smsConfig.getShortUrlService()); } else { // If a URL shortening service is not enabled, we need to created a hash key for the encrypted // context identifier and insert a database entry mapping ths hash key to the context identifier. // This is done to shorten the message URL as much as possible. String hashForContextId = getHashForContextId(encryptedContextIdentifier); messageURL += hashForContextId; DBUtils.insertHashKeyContextIdentifierMapping(hashForContextId, context.getContextIdentifier()); } // prepare the USSD message from template HashMap<String, String> variableMap = new HashMap<String, String>(); variableMap.put("application", application.changeApplicationName( context.getSequenceConfig().getApplicationConfig().getApplicationName())); variableMap.put("link", messageURL); boolean isRegistering = (boolean) context.getProperty(Constants.IS_REGISTERING); OutboundMessage.MessageType messageType = OutboundMessage.MessageType.SMS_LOGIN; if (isRegistering) { messageType = OutboundMessage.MessageType.SMS_REGISTRATION; } String messageText = OutboundMessage.prepare(client_id, messageType, variableMap, operator); if (log.isDebugEnabled()) { log.debug("Message URL: " + messageURL); log.debug("Message: " + messageText); log.debug("Operator: " + operator); } DBUtils.insertAuthFlowStatus(msisdn, Constants.STATUS_PENDING, context.getContextIdentifier()); smsMessage = new SMSMessage(); smsMessage.setMsisdn(msisdn); smsMessage.setMessageText(messageText); smsMessage.setOperator(operator); smsMessage.setClient_id(client_id); smsMessage.setRedirectURL(response.encodeRedirectURL(loginPage + ("?" + queryParams)) + "&authenticators=" + getName() + ":" + "LOCAL" + retryParam); } catch (Exception e) { DataPublisherUtil.updateAndPublishUserStatus(userStatus, DataPublisherUtil.UserState.SMS_AUTH_PROCESSING_FAIL, e.getMessage()); throw new AuthenticationFailedException(e.getMessage(), e); } return smsMessage; }
From source file:org.apache.cocoon.servlet.CocoonServlet.java
/** * Process the specified <code>HttpServletRequest</code> producing output * on the specified <code>HttpServletResponse</code>. *//* w ww .j a v a 2 s. c o m*/ public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { /* HACK for reducing class loader problems. */ /* example: xalan extensions fail if someone adds xalan jars in tomcat3.2.1/lib */ if (this.initClassLoader) { try { Thread.currentThread().setContextClassLoader(this.classLoader); } catch (Exception e) { } } // used for timing the processing StopWatch stopWatch = new StopWatch(); stopWatch.start(); // add the cocoon header timestamp if (this.showCocoonVersion) { res.addHeader("X-Cocoon-Version", Constants.VERSION); } // get the request (wrapped if contains multipart-form data) HttpServletRequest request; try { if (this.enableUploads) { request = requestFactory.getServletRequest(req); } else { request = req; } } catch (Exception e) { if (getLogger().isErrorEnabled()) { getLogger().error("Problem with Cocoon servlet", e); } manageException(req, res, null, null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem in creating the Request", null, null, e); return; } // Get the cocoon engine instance if (reloadCocoon(request.getPathInfo(), request.getParameter(Constants.RELOAD_PARAM))) { disposeCocoon(); initLogger(); createCocoon(); } // Check if cocoon was initialized if (this.cocoon == null) { manageException(request, res, null, null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Initialization Problem", null /* "Cocoon was not initialized" */, null /* "Cocoon was not initialized, cannot process request" */, this.exception); return; } // We got it... Process the request String uri = request.getServletPath(); if (uri == null) { uri = ""; } String pathInfo = request.getPathInfo(); if (pathInfo != null) { // VG: WebLogic fix: Both uri and pathInfo starts with '/' // This problem exists only in WL6.1sp2, not in WL6.0sp2 or WL7.0b. if (uri.length() > 0 && uri.charAt(0) == '/') { uri = uri.substring(1); } uri += pathInfo; } if (uri.length() == 0) { /* empty relative URI -> HTTP-redirect from /cocoon to /cocoon/ to avoid StringIndexOutOfBoundsException when calling "".charAt(0) else process URI normally */ String prefix = request.getRequestURI(); if (prefix == null) { prefix = ""; } res.sendRedirect(res.encodeRedirectURL(prefix + "/")); return; } String contentType = null; ContextMap ctxMap = null; Environment env; try { if (uri.charAt(0) == '/') { uri = uri.substring(1); } // Pass uri into environment without URLDecoding, as it is already decoded. env = getEnvironment(uri, request, res); } catch (Exception e) { if (getLogger().isErrorEnabled()) { getLogger().error("Problem with Cocoon servlet", e); } manageException(request, res, null, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem in creating the Environment", null, null, e); return; } try { try { // Initialize a fresh log context containing the object model: it // will be used by the CocoonLogFormatter ctxMap = ContextMap.getCurrentContext(); // Add thread name (default content for empty context) String threadName = Thread.currentThread().getName(); ctxMap.set("threadName", threadName); // Add the object model ctxMap.set("objectModel", env.getObjectModel()); // Add a unique request id (threadName + currentTime ctxMap.set("request-id", threadName + System.currentTimeMillis()); if (this.cocoon.process(env)) { contentType = env.getContentType(); } else { // We reach this when there is nothing in the processing change that matches // the request. For example, no matcher matches. getLogger().fatalError("The Cocoon engine failed to process the request."); manageException(request, res, env, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Request Processing Failed", "Cocoon engine failed in process the request", "The processing engine failed to process the request. This could be due to lack of matching or bugs in the pipeline engine.", null); return; } } catch (ResourceNotFoundException e) { if (getLogger().isDebugEnabled()) { getLogger().warn(e.getMessage(), e); } else if (getLogger().isWarnEnabled()) { getLogger().warn(e.getMessage()); } manageException(request, res, env, uri, HttpServletResponse.SC_NOT_FOUND, "Resource Not Found", "Resource Not Found", "The requested resource \"" + request.getRequestURI() + "\" could not be found", e); return; } catch (ConnectionResetException e) { if (getLogger().isDebugEnabled()) { getLogger().debug(e.toString(), e); } else if (getLogger().isWarnEnabled()) { getLogger().warn(e.toString()); } } catch (IOException e) { // Tomcat5 wraps SocketException into ClientAbortException which extends IOException. if (getLogger().isDebugEnabled()) { getLogger().debug(e.toString(), e); } else if (getLogger().isWarnEnabled()) { getLogger().warn(e.toString()); } } catch (Exception e) { if (getLogger().isErrorEnabled()) { getLogger().error("Internal Cocoon Problem", e); } manageException(request, res, env, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error", null, null, e); return; } stopWatch.stop(); String timeString = null; if (getLogger().isInfoEnabled()) { timeString = processTime(stopWatch.getTime()); getLogger().info("'" + uri + "' " + timeString); } if (contentType != null && contentType.equals("text/html")) { String showTime = request.getParameter(Constants.SHOWTIME_PARAM); boolean show = this.showTime; if (showTime != null) { show = !showTime.equalsIgnoreCase("no"); } if (show) { if (timeString == null) { timeString = processTime(stopWatch.getTime()); } boolean hide = this.hiddenShowTime; if (showTime != null) { hide = showTime.equalsIgnoreCase("hide"); } ServletOutputStream out = res.getOutputStream(); out.print((hide) ? "<!-- " : "<p>"); out.print(timeString); out.println((hide) ? " -->" : "</p>"); } } } finally { if (ctxMap != null) { ctxMap.clear(); } try { if (request instanceof MultipartHttpServletRequest) { if (getLogger().isDebugEnabled()) { getLogger().debug("Deleting uploaded file(s)."); } ((MultipartHttpServletRequest) request).cleanup(); } } catch (IOException e) { getLogger().error("Cocoon got an Exception while trying to cleanup the uploaded files.", e); } /* * Servlet Specification 2.2, 6.5 Closure of Response Object: * * A number of events can indicate that the servlet has provided all of the * content to satisfy the request and that the response object can be * considered to be closed. The events are: * o The termination of the service method of the servlet. * o When the amount of content specified in the setContentLength method * of the response has been written to the response. * o The sendError method is called. * o The sendRedirect method is called. * When a response is closed, all content in the response buffer, if any remains, * must be immediately flushed to the client. * * Due to the above, out.flush() and out.close() are not necessary, and sometimes * (if sendError or sendRedirect were used) request may be already closed. */ } }
From source file:de.zib.scalaris.examples.wikipedia.bliki.WikiServlet.java
/** * Gets a random page and forwards the user to the site with this page. * /*from w w w. ja v a 2 s. c om*/ * @param request * the request of the current operation * @param response * the response of the current operation * @param title * the requested title (mostly "Special:Random") * @param connection * connection to the database * @param page * the bean for the page * * @throws IOException * if the forward fails * @throws ServletException */ private void handleViewRandomPage(HttpServletRequest request, HttpServletResponse response, String title, Connection connection, WikiPageBean page) throws IOException, ServletException { page.setTitle(title); final Random random = new Random(); ValueResult<NormalisedTitle> result; if (existingPages.hasFullList()) { final long timeAtStart = System.currentTimeMillis(); final String statName = "RANDOM_PAGE"; final List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>(); final Set<NormalisedTitle> pages = existingPages.getList(NamespaceEnum.MAIN_NAMESPACE_KEY); final int randIdx = random.nextInt(pages.size()); // no real other option to get a random element from a set :( int i = 0; NormalisedTitle randValue = null; for (Iterator<NormalisedTitle> iterator = pages.iterator(); iterator.hasNext();) { if (i == randIdx) { randValue = iterator.next(); break; } else { iterator.next(); } ++i; } result = new ValueResult<NormalisedTitle>(involvedKeys, randValue, statName, System.currentTimeMillis() - timeAtStart); } else { result = getRandomArticle(connection, random); } page.addStats(result.stats); page.getInvolvedKeys().addAll(result.involvedKeys); final String serviceUser = page.getServiceUser().isEmpty() ? "" : "&service_user=" + page.getServiceUser(); String redirectUrl; ArrayList<Long> times = new ArrayList<Long>(); for (List<Long> time : result.stats.values()) { times.addAll(time); } if (result.success) { StringBuilder redirectUrl0 = new StringBuilder(256); redirectUrl0.append("?title="); redirectUrl0.append(URLEncoder.encode(result.value.denormalise(namespace), "UTF-8")); redirectUrl0.append("&random_times=" + StringUtils.join(times, "%2C")); redirectUrl0.append("&involved_keys=" + URLEncoder.encode(StringUtils.join(page.getInvolvedKeys(), " # "), "UTF-8")); redirectUrl = "http://" + Options.getInstance().SERVERNAME + Options.getInstance().SERVERPATH + response.encodeRedirectURL(redirectUrl0.toString()) + serviceUser; } else if (result.connect_failed) { setParam_error(request, "ERROR: DB connection failed"); showEmptyPage(request, response, connection, page); return; } else { StringBuilder redirectUrl0 = new StringBuilder(256); redirectUrl0.append("?title="); redirectUrl0.append(URLEncoder.encode(MAIN_PAGE, "UTF-8")); redirectUrl0.append("&random_times=" + StringUtils.join(times, "%2C")); redirectUrl0.append("&involved_keys=" + URLEncoder.encode(StringUtils.join(page.getInvolvedKeys(), " # "), "UTF-8")); redirectUrl0.append("¬ice=" + URLParamEncoder.encode("error: can not view random page: <pre>" + result.message + "</pre>")); redirectUrl = "http://" + Options.getInstance().SERVERNAME + Options.getInstance().SERVERPATH + response.encodeRedirectURL(redirectUrl0.toString()) + serviceUser; } for (WikiEventHandler handler : eventHandlers) { handler.onViewRandomPage(page, result, connection); } response.sendRedirect(redirectUrl + "&server_time=" + (System.currentTimeMillis() - page.getStartTime())); }
From source file:org.dspace.app.webui.servlet.admin.EditCommunitiesServlet.java
/** * Create/update collection metadata from a posted form * //from w ww. j a va2s . c o m * @param context * DSpace context * @param request * the HTTP request containing posted info * @param response * the HTTP response * @param community * the community the collection is in * @param collection * the collection to update (or null for creation) */ private void processConfirmEditCollection(Context context, HttpServletRequest request, HttpServletResponse response, Community community, Collection collection) throws ServletException, IOException, SQLException, AuthorizeException { if (request.getParameter("create").equals("true")) { // We need to create a new community collection = community.createCollection(); request.setAttribute("collection", collection); } storeAuthorizeAttributeCollectionEdit(context, request, collection); // Update the basic metadata collection.setMetadata("name", request.getParameter("name")); collection.setMetadata("short_description", request.getParameter("short_description")); String intro = request.getParameter("introductory_text"); if (intro.equals("")) { intro = null; } String copy = request.getParameter("copyright_text"); if (copy.equals("")) { copy = null; } String side = request.getParameter("side_bar_text"); if (side.equals("")) { side = null; } String license = request.getParameter("license"); if (license.equals("")) { license = null; } String provenance = request.getParameter("provenance_description"); if (provenance.equals("")) { provenance = null; } collection.setMetadata("introductory_text", intro); collection.setMetadata("copyright_text", copy); collection.setMetadata("side_bar_text", side); collection.setMetadata("license", license); collection.setMetadata("provenance_description", provenance); // Set the harvesting settings HarvestedCollection hc = HarvestedCollection.find(context, collection.getID()); String contentSource = request.getParameter("source"); // First, if this is not a harvested collection (anymore), set the harvest type to 0; wipe harvest settings if (contentSource.equals("source_normal")) { if (hc != null) { hc.delete(); } } else { // create a new harvest instance if all the settings check out if (hc == null) { hc = HarvestedCollection.create(context, collection.getID()); } String oaiProvider = request.getParameter("oai_provider"); String oaiSetId = request.getParameter("oai_setid"); String metadataKey = request.getParameter("metadata_format"); String harvestType = request.getParameter("harvest_level"); hc.setHarvestParams(Integer.parseInt(harvestType), oaiProvider, oaiSetId, metadataKey); hc.setHarvestStatus(HarvestedCollection.STATUS_READY); hc.update(); } // Which button was pressed? String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_set_logo")) { // Change the logo - delete any that might be there first collection.setLogo(null); // Display "upload logo" page. Necessary attributes already set by // doDSPost() JSPManager.showJSP(request, response, "/dspace-admin/upload-logo.jsp"); } else if (button.equals("submit_delete_logo")) { // Simply delete logo collection.setLogo(null); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); } else if (button.startsWith("submit_wf_create_")) { int step = Integer.parseInt(button.substring(17)); // Create new group Group newGroup = collection.createWorkflowGroup(step); collection.update(); // Forward to group edit page response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/tools/group-edit?group_id=" + newGroup.getID())); } else if (button.equals("submit_admins_create")) { // Create new group Group newGroup = collection.createAdministrators(); collection.update(); // Forward to group edit page response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/tools/group-edit?group_id=" + newGroup.getID())); } else if (button.equals("submit_admins_delete")) { // Remove the administrators group. Group g = collection.getAdministrators(); collection.removeAdministrators(); collection.update(); g.delete(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); } else if (button.equals("submit_submitters_create")) { // Create new group Group newGroup = collection.createSubmitters(); collection.update(); // Forward to group edit page response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/tools/group-edit?group_id=" + newGroup.getID())); } else if (button.equals("submit_submitters_delete")) { // Remove the administrators group. Group g = collection.getSubmitters(); collection.removeSubmitters(); collection.update(); g.delete(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); } else if (button.equals("submit_authorization_edit")) { // Forward to policy edit page response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/tools/authorize?collection_id=" + collection.getID() + "&submit_collection_select=1")); } else if (button.startsWith("submit_wf_edit_")) { int step = Integer.parseInt(button.substring(15)); // Edit workflow group Group g = collection.getWorkflowGroup(step); response.sendRedirect(response .encodeRedirectURL(request.getContextPath() + "/tools/group-edit?group_id=" + g.getID())); } else if (button.equals("submit_submitters_edit")) { // Edit submitters group Group g = collection.getSubmitters(); response.sendRedirect(response .encodeRedirectURL(request.getContextPath() + "/tools/group-edit?group_id=" + g.getID())); } else if (button.equals("submit_admins_edit")) { // Edit 'collection administrators' group Group g = collection.getAdministrators(); response.sendRedirect(response .encodeRedirectURL(request.getContextPath() + "/tools/group-edit?group_id=" + g.getID())); } else if (button.startsWith("submit_wf_delete_")) { // Delete workflow group int step = Integer.parseInt(button.substring(17)); Group g = collection.getWorkflowGroup(step); collection.setWorkflowGroup(step, null); // Have to update to avoid ref. integrity error collection.update(); g.delete(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); } else if (button.equals("submit_create_template")) { // Create a template item collection.createTemplateItem(); // Forward to edit page for new template item Item i = collection.getTemplateItem(); // save the changes collection.update(); context.complete(); response.sendRedirect( response.encodeRedirectURL(request.getContextPath() + "/tools/edit-item?item_id=" + i.getID())); return; } else if (button.equals("submit_edit_template")) { // Forward to edit page for template item Item i = collection.getTemplateItem(); response.sendRedirect( response.encodeRedirectURL(request.getContextPath() + "/tools/edit-item?item_id=" + i.getID())); } else if (button.equals("submit_delete_template")) { collection.removeTemplateItem(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); } else { // Plain old "create/update" button pressed - go back to main page showControls(context, request, response); } // Commit changes to DB collection.update(); context.complete(); }
From source file:org.xwoot.xwootApp.web.servlets.StateManagement.java
/** * {@inheritDoc}//from w ww . ja va 2 s . c om * * @see HttpServlet#service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) */ @Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Map<String, FileItem> requestParameters = parseMultipartParameters(request); XWootAPI xwootEngine = XWootSite.getInstance().getXWootEngine(); StateAction action = null; if (request.getParameter("action_upload") != null || requestParameters.containsKey("action_upload")) { action = StateAction.UPLOAD; } else if (request.getParameter("action_create") != null || requestParameters.containsKey("action_create")) { action = StateAction.CREATE; } else if (request.getParameter("action_retrieve") != null || requestParameters.containsKey("action_retrieve")) { action = StateAction.RETRIEVE; } System.out.println("Performing action: " + action); boolean uploadSuccessful = false; // The result of the action String currentState = null; String exceptionMessage = null; try { if (action == StateAction.UPLOAD) { this.log("Want to upload state file... "); if (requestParameters.containsKey("statefile")) { this.temp = File.createTempFile("uploadedState", ".zip"); FileItem fileToUpload = requestParameters.get("statefile"); if (!xwootEngine.isGroupCreator() && !fileToUpload.getName().equals(xwootEngine.getStateFileName())) { exceptionMessage = "A state for a different group was provided. Please upload the state of this group if you already have it or ask a new one instead."; } else if (this.upload(fileToUpload)) { uploadSuccessful = true; try { XWootSite.getInstance().getXWootEngine().importState(this.temp); } catch (Exception e) { exceptionMessage = e.getMessage(); this.log("Problems with the uloaded state.", e); } } // remove the temporary uploaded file because it was copied to the right place by importState this.temp.delete(); } } else if (action == StateAction.RETRIEVE) { this.getServletContext().log("Retrieving state from group."); File newStateFile = xwootEngine.askStateToGroup(); xwootEngine.importState(newStateFile); newStateFile.delete(); } else if (action == StateAction.CREATE) { this.log("Want to compute state"); XWootSite.getInstance().getXWootEngine().connectToContentManager(); XWootSite.getInstance().getXWootEngine().computeState(); } } catch (Exception e) { exceptionMessage = e.getMessage(); this.log("Problem with state: " + e.getMessage(), e); } // If we performed an action or the state already exists. if (action != null || XWootSite.getInstance().getXWootEngine().isStateComputed()) { // If successful. if (exceptionMessage == null && XWootSite.getInstance().getXWootEngine().isStateComputed()) { if (!xwootEngine.isContentManagerConnected()) { try { xwootEngine.connectToContentManager(); } catch (XWootException e) { this.log("Failed to connect to content manager. Please retry from the Synchronize page.", e); } } try { // Synchronize with the Content Provider. xwootEngine.synchronize(); } catch (XWootException e) { this.log("Failed to synchronize before anti-entropy request with all neighbors."); } // Start the auto-synchronization thread XWootSite.getInstance().getAutoSynchronizationThread().startThread(); // Do initial anti-entropy with all neighbors. try { xwootEngine.doAntiEntropyWithAllNeighbors(); } catch (XWootException e) { this.log("Failed to launch initial anti-entropy request with all neighbors."); } response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/synchronize.do")); return; } // Otherwise switch (action) { case UPLOAD: if (uploadSuccessful) { currentState = "Problem with state: can't import selected file." + "\n(Details: " + exceptionMessage + ")"; } else { currentState = "Problem with state: please select a state file to upload." + (exceptionMessage != null ? "\n(Details: " + exceptionMessage + ")" : ""); } break; case CREATE: currentState = "Problem with state: can't compute a new state." + "\n(Details: " + exceptionMessage + ")"; ; break; case RETRIEVE: currentState = "Problem with state: can't receive a state from the group." + "\n(Details: " + exceptionMessage + ")"; ; break; case REIMPORT_EXISTING: currentState = "Failed to import the existing state for this group. Please get the group's state again." + " (Details: " + exceptionMessage + ")"; default: // First request, there's no error yet break; } } request.setAttribute("xwiki_url", XWootSite.getInstance().getXWootEngine().getContentManagerURL()); request.setAttribute("errors", currentState); request.setAttribute("groupCreator", xwootEngine.isGroupCreator()); request.getRequestDispatcher("/pages/StateManagement.jsp").forward(request, response); return; }