List of usage examples for javax.servlet UnavailableException UnavailableException
public UnavailableException(String msg)
From source file:org.nordapp.web.servlet.DEVServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/*from w w w. j a v a 2 s . c o m*/ //@SuppressWarnings("unused") final String mandatorId = RequestPath.getMandator(req); final String uuid = RequestPath.getSession(req); // // Session handler (HTTP) and session control (OSGi) // //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession()); SessionControl ctrl = new SessionControlImpl(context); ctrl.setMandatorID(mandatorId); ctrl.setCertID(uuid); //RequestHandler rqHdl = new RequestHandler(context, ctrl); ctrl.loadTempSession(); ctrl.getAll(); ctrl.incRequestCounter(); ctrl.setAll(); ctrl.saveTempSession(); // // Session service // String cert = null; String[] elem = RequestPath.getPath(req); if (elem.length != 1) throw new MalformedURLException("The URL needs the form '" + req.getServletPath() + "/[create|load]' but was '" + req.getRequestURI() + "'"); Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), ctrl.getCertID()); if (mSession == null) { List<String> list = ctrl.getShortTimePassword(); if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID()))) throw new UnavailableException("Needs a valid User-Session."); } ServiceReference<DeployService> srDeploy = context.getServiceReference(DeployService.class); if (srDeploy == null) throw new IOException( "The deploy service reference is not available (maybe down or a version conflict)."); DeployService svDeploy = context.getService(srDeploy); if (svDeploy == null) throw new IOException("The deploy service is not available (maybe down or a version conflict)."); String processID = IdGen.getURLSafeString(IdGen.getUUID()); String mandatorID = ctrl.getMandatorID(); String groupID = ctrl.getGroupID(); String artifactID = ctrl.getArtifactID(); File zip = null; if (elem[0].equalsIgnoreCase("create")) { zip = svDeploy.createEmptyZip(processID, mandatorID, groupID, artifactID); } else if (elem[0].equalsIgnoreCase("load")) { zip = svDeploy.zipFromData(processID, mandatorID, groupID, artifactID); } else { throw new MalformedURLException("The URL needs the form '" + req.getServletPath() + "/[create|load]' but was '" + req.getRequestURI() + "'"); } ResponseHandler rsHdl = new ResponseHandler(context, ctrl); rsHdl.avoidCaching(resp); resp.setContentType("application/octet-stream"); resp.setHeader("Content-Type", "application/octet-stream"); resp.setHeader("Content-Disposition", "attachment; filename=\"" + processID + ".zip\""); InputStream is = new FileInputStream(zip); try { rsHdl.sendFile(is, resp, null); } finally { is.close(); } } catch (Exception e) { ResponseHandler rsHdl = new ResponseHandler(context, null); rsHdl.sendError(logger, e, resp, null); } }
From source file:org.nordapp.web.servlet.DEVServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from w ww.j a va 2 s . c o m //@SuppressWarnings("unused") final String mandatorId = RequestPath.getMandator(req); final String uuid = RequestPath.getSession(req); // // Session handler (HTTP) and session control (OSGi) // //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession()); SessionControl ctrl = new SessionControlImpl(context); ctrl.setMandatorID(mandatorId); ctrl.setCertID(uuid); //RequestHandler rqHdl = new RequestHandler(context, ctrl); ctrl.loadTempSession(); ctrl.getAll(); ctrl.incRequestCounter(); ctrl.setAll(); ctrl.saveTempSession(); // // Session and other services // String cert = null; //The '0' session of the mandator Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), "0"); //The 'user' session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), ctrl.decodeCert().toString()); if (mSession == null) { List<String> list = ctrl.getShortTimePassword(); if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID()))) throw new UnavailableException("Needs a valid User-Session."); } //The mandator Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID()); if (mandator == null) { throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + "."); } // // Get some data // FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp"); // // prepare the engine // String[] elem = RequestPath.getPath(req); if (elem.length != 0) throw new MalformedURLException("The URL needs the form '" + req.getServletPath() + "' but was '" + req.getRequestURI() + "'"); // // Initialize the work // ServiceReference<DeployService> srDeploy = context.getServiceReference(DeployService.class); if (srDeploy == null) throw new IOException( "The deploy service reference is not available (maybe down or a version conflict)."); DeployService svDeploy = context.getService(srDeploy); if (svDeploy == null) throw new IOException("The deploy service is not available (maybe down or a version conflict)."); String processID = IdGen.getURLSafeString(IdGen.getUUID()); String mandatorID = ctrl.getMandatorID(); String groupID = ctrl.getGroupID(); String artifactID = ctrl.getArtifactID(); // // Process upload // // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); File repository = tmpLoc.add("http-upload").toFile(); if (!repository.exists()) { repository.mkdirs(); } factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); try { // parses the request's content to extract file data //@SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(req); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (item.isFormField()) { //data } else { File zip = svDeploy.createEmptyZip(processID, mandatorID, groupID, artifactID); OutputStream os = new FileOutputStream(zip); InputStream is = item.getInputStream(); try { IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } svDeploy.zipToData(processID, mandatorID, groupID, artifactID, zip.getName()); } //fi } //for } //fi } catch (Exception ex) { req.setAttribute("message", "There was an error: " + ex.getMessage()); } // // Prints the result from the user-session // StringBuffer buffer = new StringBuffer(); ResponseHandler rsHdl = new ResponseHandler(context, ctrl); logger.debug("The user session is{}found mandatorId:{}, sessionId:{}.", (mSession == null ? " not " : " "), ctrl.getMandatorID(), ctrl.getCertID()); rsHdl.getSessionData(buffer, mSession); // // // byte[] bytes = buffer.toString().getBytes(); // // Send the resource // rsHdl.avoidCaching(resp); rsHdl.sendData(bytes, resp); } catch (Exception e) { ResponseHandler rsHdl = new ResponseHandler(context, null); rsHdl.sendError(logger, e, resp, null); } }
From source file:org.nordapp.web.servlet.IOServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/*from w ww.j av a2 s .co m*/ //@SuppressWarnings("unused") final String mandatorId = RequestPath.getMandator(req); final String uuid = RequestPath.getSession(req); // // Session handler (HTTP) and session control (OSGi) // //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession()); SessionControl ctrl = new SessionControlImpl(context); ctrl.setMandatorID(mandatorId); ctrl.setCertID(uuid); //RequestHandler rqHdl = new RequestHandler(context, ctrl); ctrl.loadTempSession(); ctrl.getAll(); ctrl.incRequestCounter(); ctrl.setAll(); ctrl.saveTempSession(); // // Session service // String cert = null; //The '0' session of the mandator Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), "0"); Integer baseIndex = ((Integer) mSession.getValue(Session.ENGINE_BASE_INDEX)).intValue(); //String sessionId = session.getId(); mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), ctrl.decodeCert().toString()); String[] elem = RequestPath.getPath(req); if (elem.length != 2) throw new MalformedURLException("The URL needs the form '" + req.getServletPath() + "/function-id/file-uuid' but was '" + req.getRequestURI() + "'"); BigInteger engineId = ctrl.decodeCert(); String functionId = elem.length >= 1 ? elem[0] : null; String fileUuid = elem.length >= 2 ? elem[1] : null; mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), ctrl.getCertID()); if (mSession == null) { List<String> list = ctrl.getShortTimePassword(); if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID()))) throw new UnavailableException("Needs a valid User-Session."); } DatabaseService dbService = DatabaseServiceImpl.getDatabase(context, cert, ctrl.getMandatorID()); if (dbService == null) { throw new UnavailableException( "Needs a valid database service for mandator " + ctrl.getMandatorID() + "."); } ResponseHandler rsHdl = new ResponseHandler(context, ctrl); Map<String, String> headers = new HashMap<String, String>(); try { // // Gets the engine base service // EngineBaseService engineBaseService = EngineBaseServiceImpl.getService(context, ctrl.getMandatorID(), String.valueOf(baseIndex)); if (engineBaseService == null) throw new IOException( "The mandator base service is not available (maybe down or a version conflict)."); // // Run the step // Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID()); if (mandator == null) throw new IOException( "The mandator service is not available (maybe down or a version conflict)."); Engine engine = engineBaseService.getEngine(engineId); if (!engine.isLogin()) throw new IllegalAccessException("There is no login to this session."); // // Initialize the work // engine.setLocalValue(httpSessionID, engineId.toString()); //ctrl.decodeCert().toString() IdRep processUUID = IdGen.getUUID(); engine.setLocalValue(httpProcessID, processUUID); IOContainer ioc = new IOContainer(); ioc.setProcessUUID(processUUID.toString()); ioc.setField(openFileByID, fileUuid); engine.setLocalValue(httpIOContainer, ioc); // // Call script // try { engine.call(functionId); } catch (Exception e) { e.printStackTrace(); } //Prints a file out //rsHdl.getSessionData(buffer, mSession); InputStream in = null; try { //DbDatabase dbs = dbService.getDatabase(); //DbFileStore dbf = dbs.getFileStore(); //DbFile file = dbf.getFileFromId( (String)engine.getLocalValue(openFileByRef) ); String[] fn = ioc.getFilenames(); if (fn.length == 0) throw new IllegalArgumentException("There is no file specified to open (empty array)."); DbFile file = (DbFile) ioc.getFile(fn[0]); in = file.getInputStream(); headers.put("Content-Type", file.getMimetype()); headers.put("Content-Length", String.valueOf(file.getLength())); rsHdl.avoidCaching(resp); rsHdl.sendFile(in, resp, headers); } finally { if (in != null) in.close(); ioc.cleanup(); engine.setLocalValue(httpSessionID, null); engine.setLocalValue(httpProcessID, null); engine.setLocalValue(httpIOContainer, null); } } catch (Exception e) { logger.error("Error running the step.", e); } } catch (Exception e) { ResponseHandler rsHdl = new ResponseHandler(context, null); rsHdl.sendError(logger, e, resp, null); } }
From source file:org.nordapp.web.servlet.IOServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from w w w . j av a 2 s.c o m //@SuppressWarnings("unused") final String mandatorId = RequestPath.getMandator(req); final String uuid = RequestPath.getSession(req); // // Session handler (HTTP) and session control (OSGi) // //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession()); SessionControl ctrl = new SessionControlImpl(context); ctrl.setMandatorID(mandatorId); ctrl.setCertID(uuid); //RequestHandler rqHdl = new RequestHandler(context, ctrl); ctrl.loadTempSession(); ctrl.getAll(); ctrl.incRequestCounter(); // // Session and other services // String cert = null; //The '0' session of the mandator Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), "0"); Integer baseIndex = ((Integer) mSession.getValue(Session.ENGINE_BASE_INDEX)).intValue(); //The 'user' session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), ctrl.decodeCert().toString()); if (mSession == null) { List<String> list = ctrl.getShortTimePassword(); if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID()))) throw new UnavailableException("Needs a valid User-Session."); } //The mandator Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID()); if (mandator == null) { throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + "."); } EngineBaseService engineBaseService = null; try { engineBaseService = EngineBaseServiceImpl.getService(context, ctrl.getMandatorID(), String.valueOf(baseIndex)); } catch (InvalidSyntaxException e1) { } if (engineBaseService == null) throw new IOException( "The mandator base service is not available (maybe down or a version conflict)."); // // Get some data // FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp"); // // prepare the engine // String[] elem = RequestPath.getPath(req); if (elem.length == 0) throw new MalformedURLException("The URL needs the form '" + req.getServletPath() + "/function-id' but was '" + req.getRequestURI() + "'"); BigInteger engineId = ctrl.decodeCert(); String functionId = elem.length >= 1 ? elem[0] : null; Engine engine = null; try { engine = engineBaseService.getEngine(engineId); } catch (Exception e1) { throw new ServletException(e1); } if (!engine.isLogin()) throw new ServletException("There is no login to this session."); // // Initialize the work // engine.setLocalValue(httpSessionID, engineId.toString()); //ctrl.decodeCert().toString() IdRep processUUID = IdGen.getUUID(); engine.setLocalValue(httpProcessID, processUUID); IOContainer ioc = new IOContainer(); ioc.setProcessUUID(processUUID.toString()); engine.setLocalValue(httpIOContainer, ioc); // // Process upload // // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); File repository = tmpLoc.add("http-upload").toFile(); if (!repository.exists()) { repository.mkdirs(); } factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); try { // parses the request's content to extract file data //@SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(req); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (item.isFormField()) { //data ioc.setField(item.getFieldName(), item); } else { ioc.setFile(IdGen.getUUID().toString(), item); } //fi } //for } //fi } catch (Exception ex) { req.setAttribute("message", "There was an error: " + ex.getMessage()); } // // Call script // try { engine.call(functionId); } catch (Exception e) { e.printStackTrace(); } ioc.cleanup(); engine.setLocalValue(httpSessionID, null); engine.setLocalValue(httpProcessID, null); engine.setLocalValue(httpIOContainer, null); // // Prints the result from the user-session // StringBuffer buffer = new StringBuffer(); ResponseHandler rsHdl = new ResponseHandler(context, ctrl); logger.debug("The user session is{}found mandatorId:{}, sessionId:{}.", (mSession == null ? " not " : " "), ctrl.getMandatorID(), ctrl.getCertID()); rsHdl.getSessionData(buffer, mSession); // // // byte[] bytes = buffer.toString().getBytes(); // // Send the resource // rsHdl.avoidCaching(resp); rsHdl.sendData(bytes, resp); } catch (Exception e) { ResponseHandler rsHdl = new ResponseHandler(context, null); rsHdl.sendError(logger, e, resp, null); } }
From source file:org.nordapp.web.servlet.SessionCallServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/* w ww . ja va 2 s .c om*/ //@SuppressWarnings("unused") final String mandatorId = RequestPath.getMandator(req); final String uuid = RequestPath.getSession(req); // // Session handler // //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession()); SessionControl ctrl = new SessionControlImpl(context); ctrl.setMandatorID(mandatorId); ctrl.setCertID(uuid); ctrl.loadTempSession(); ctrl.getAll(); ctrl.incRequestCounter(); ctrl.setAll(); ctrl.saveTempSession(); // // Process upload // // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); //The mandator Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID()); if (mandator == null) { throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + "."); } FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp"); File repository = tmpLoc.add("http-upload").toFile(); if (!repository.exists()) { repository.mkdirs(); } factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // Gets the JSON data GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LinkedHashMap.class, new GsonHashMapDeserializer()); Gson gson = gsonBuilder.create(); Map<String, Object> res = new HashMap<String, Object>(); try { // parses the request's content to extract file data //@SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(req); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (item.isFormField()) { //data res.put(item.getFieldName(), item.getString()); //ioc.setField(item.getFieldName(), item); } else { //Gets JSON as Stream Reader json = new InputStreamReader(item.getInputStream()); //String json = item.getString(); try { @SuppressWarnings("unchecked") LinkedHashMap<String, Object> mapJ = gson.fromJson(json, LinkedHashMap.class); for (String key : mapJ.keySet()) { Object val = mapJ.get(key); if (val == null) continue; res.put(key, val); } //for } finally { json.close(); } } //fi } //for } //fi } catch (Exception ex) { req.setAttribute("message", "There was an error: " + ex.getMessage()); } process(ctrl, req, resp, res); } catch (Exception e) { ResponseHandler rsHdl = new ResponseHandler(context, null); rsHdl.sendError(logger, e, resp, null); } }
From source file:org.opencms.webdav.CmsWebdavServlet.java
/** * Initialize this servlet.<p>// w w w .ja va 2 s . c o m * * @throws ServletException if something goes wrong */ @Override public void init() throws ServletException { if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.LOG_INIT_WEBDAV_SERVLET_0)); } String value = null; // init parameter: listings try { value = getServletConfig().getInitParameter(INIT_PARAM_LIST); if (value != null) { m_listings = Boolean.valueOf(value).booleanValue(); } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_READ_INIT_PARAM_ERROR_2, INIT_PARAM_LIST, value), e); } } if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.LOG_READ_INIT_PARAM_2, INIT_PARAM_LIST, Boolean.valueOf(m_listings))); } // init parameter: read only try { value = getServletConfig().getInitParameter(INIT_PARAM_READONLY); if (value != null) { m_readOnly = Boolean.valueOf(value).booleanValue(); } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_READ_INIT_PARAM_ERROR_2, INIT_PARAM_READONLY, value), e); } } if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.LOG_READ_INIT_PARAM_2, INIT_PARAM_READONLY, Boolean.valueOf(m_readOnly))); } // Load the MD5 helper used to calculate signatures. try { m_md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_MD5_NOT_AVAILABLE_0), e); } throw new UnavailableException(Messages.get().getBundle().key(Messages.ERR_MD5_NOT_AVAILABLE_0)); } // Instantiate repository from init-param String repositoryName = getInitParameter(INIT_PARAM_REPOSITORY); if (repositoryName == null) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_INIT_PARAM_MISSING_1, INIT_PARAM_REPOSITORY)); } throw new ServletException( Messages.get().getBundle().key(Messages.ERR_INIT_PARAM_MISSING_1, INIT_PARAM_REPOSITORY)); } m_repository = OpenCms.getRepositoryManager().getRepository(repositoryName); if (m_repository == null) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_REPOSITORY_NOT_FOUND_1, repositoryName)); } throw new ServletException( Messages.get().getBundle().key(Messages.ERR_REPOSITORY_NOT_FOUND_1, repositoryName)); } if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.LOG_USE_REPOSITORY_1, repositoryName)); } }
From source file:org.opennms.web.asset.ImportAssetsServlet.java
/** * Looks up the <code>redirect.success</code> parameter in the servlet's * configuration. If not present, this servlet will throw an exception so it will * be marked unavailable.//from w ww.j av a 2 s . c om * * @throws javax.servlet.ServletException if any. */ @Override public void init() throws ServletException { ServletConfig config = this.getServletConfig(); this.redirectSuccess = config.getInitParameter("redirect.success"); if (this.redirectSuccess == null) { throw new UnavailableException("Require a redirect.success init parameter."); } this.model = new AssetModel(); }
From source file:org.openqa.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {/* www.j a va 2s . co m*/ throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:org.rhq.helpers.rtfilter.filter.RtFilter.java
/** * Initialize parameters from the web.xml filter init-params * * @param conf the filter configuration//from w w w . ja v a2 s . c om */ private void initializeParameters(FilterConfig conf) throws UnavailableException { String chop = conf.getInitParameter(InitParams.CHOP_QUERY_STRING); if (chop != null) { this.chopUrl = Boolean.valueOf(chop.trim()).booleanValue(); } String logDirectoryPath = conf.getInitParameter(InitParams.LOG_DIRECTORY); if (logDirectoryPath != null) { this.logDirectory = new File(logDirectoryPath.trim()); } else { /* * If this is a JBossAS deployed container, or a Standalone TC container, use a logical * default (so those plugins can be written in a compatible way). * First, try to default to "${JBOSS_SERVER_HOME_DIR_SYSPROP}/JBOSSAS_SERVER_LOG_SUBDIR/rt"; * If not set try "${TOMCAT_SERVER_HOME_DIR_SYSPROP}/TOMCAT_SERVER_LOG_SUBDIR/rt"; * If, for some reason, neither property is set, fall back to "${java.io.tmpdir}/rhq/rt". */ File serverLogDir = null; String serverHomeDirPath = System.getProperty(JBOSSAS_SERVER_HOME_DIR_SYSPROP); if (null != serverHomeDirPath) { serverLogDir = new File(serverHomeDirPath, JBOSSAS_SERVER_LOG_SUBDIR); } else { serverHomeDirPath = System.getProperty(TOMCAT_SERVER_HOME_DIR_SYSPROP); if (serverHomeDirPath != null) { serverLogDir = new File(serverHomeDirPath, TOMCAT_SERVER_LOG_SUBDIR); } } if (null != serverLogDir) { this.logDirectory = new File(serverLogDir, "rt"); } else { this.logDirectory = new File(System.getProperty(JAVA_IO_TMPDIR_SYSPROP), "rhq/rt"); log.warn( "The 'logDirectory' filter init param was not set. Also, the standard system properties were not set (" + JBOSSAS_SERVER_HOME_DIR_SYSPROP + ", " + TOMCAT_SERVER_HOME_DIR_SYSPROP + "); defaulting RT log directory to '" + this.logDirectory + "'."); } } if (this.logDirectory.exists()) { if (!this.logDirectory.isDirectory()) { throw new UnavailableException( "Log directory '" + this.logDirectory + "' exists but is not a directory."); } } else { try { this.logDirectory.mkdirs(); } catch (Exception e) { throw new UnavailableException( "Unable to create log directory '" + this.logDirectory + "' - cause: " + e); } if (!logDirectory.exists()) { throw new UnavailableException("Unable to create log directory '" + this.logDirectory + "'."); } } String logFilePrefixString = conf.getInitParameter(InitParams.LOG_FILE_PREFIX); if (logFilePrefixString != null) { this.logFilePrefix = logFilePrefixString.trim(); } String dontLog = conf.getInitParameter(InitParams.DONT_LOG_REG_EX); if (dontLog != null) { this.dontLogPattern = Pattern.compile(dontLog.trim()); } String flushTimeout = conf.getInitParameter(InitParams.TIME_BETWEEN_FLUSHES_IN_SEC); if (flushTimeout != null) { try { timeBetweenFlushes = Long.parseLong(flushTimeout.trim()) * 1000; } catch (NumberFormatException nfe) { timeBetweenFlushes = DEFAULT_FLUSH_TIMEOUT; } } String uriOnly = conf.getInitParameter(InitParams.MATCH_ON_URI_ONLY); if (uriOnly != null) { matchOnUriOnly = Boolean.getBoolean(uriOnly.trim()); } String lines = conf.getInitParameter(InitParams.FLUSH_AFTER_LINES); if (lines != null) { try { flushAfterLines = Long.parseLong(lines.trim()); if (flushAfterLines <= 0) { throw new NumberFormatException(); } } catch (NumberFormatException nfe) { log.error("Invalid '" + InitParams.FLUSH_AFTER_LINES + "' init parameter: " + lines + " (value must be a positive integer) - using default."); flushAfterLines = DEFAULT_FLUSH_AFTER_LINES; } } String maxLogFileSizeString = conf.getInitParameter(InitParams.MAX_LOG_FILE_SIZE); if (maxLogFileSizeString != null) { try { this.maxLogFileSize = Long.parseLong(maxLogFileSizeString.trim()); if (this.maxLogFileSize <= 0) { throw new NumberFormatException(); } } catch (NumberFormatException e) { log.error("Invalid '" + InitParams.MAX_LOG_FILE_SIZE + "' init parameter: " + maxLogFileSizeString + " (value must be a positive integer) - using default."); this.maxLogFileSize = DEFAULT_MAX_LOG_FILE_SIZE; } } /* * Read mappings from a vhost mapping file in the format of a properties file * inputhost = mapped host * This file needs to live in the search path - e.g. in server/<config>/conf/ * The name of it must be passed as init-param to the filter. Otherwise the mapping * will not be used. * <param-name>vHostMappingFile</param-name> */ String vhostMappingFileString = conf.getInitParameter(InitParams.VHOST_MAPPING_FILE); if (vhostMappingFileString != null) { InputStream stream = getClass().getClassLoader().getResourceAsStream(vhostMappingFileString); if (stream != null) { try { vhostMappings.load(stream); } catch (IOException e) { log.warn("Can't read vhost mappings from " + vhostMappingFileString + " :" + e.getMessage()); } finally { if (stream != null) try { stream.close(); } catch (Exception e) { log.debug(e); } } } else { log.warn("Can't read vhost mappings from " + vhostMappingFileString); } } }
From source file:org.sakaiproject.webdav.SakaiWebDavServlet.java
/** * {@inheritDoc}//w w w.j a v a 2 s. co m * * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig) */ @Override public void init(ServletConfig config) throws ServletException { super.init(config); String filter = config.getInitParameter("path-filter"); if (StringUtils.isEmpty(filter)) { filter = DEFAULT_FILTER; } String[] filters = StringUtils.split(filter, ';'); if (filters != null) { for (String f : filters) { f = f.trim(); filterElement.put(f, f); } } KernelManager km = new KernelManager(); jcrService = km.getService(JCRService.class); repository = jcrService.getRepository(); // for now, the ResourceConfig is fixed final String configPath = "/webdav-resource-config.xml"; final ResourceConfig rc = new ResourceConfig(); final URL cfg = getClass().getResource(configPath); if (cfg == null) { throw new UnavailableException("ResourceConfig source not found:" + configPath); } rc.parse(cfg); setResourceConfig(rc); }