public Long getLastModified(String resource) { long result = -1; URLConnection uc = null; try { URL jspUrl = getResource(resource); if (jspUrl == null) { incrementRemoved(); return Long.valueOf(result); } uc = jspUrl.openConnection(); if (uc instanceof JarURLConnection) { result = ((JarURLConnection) uc).getJarEntry().getTime(); } else { result = uc.getLastModified(); } } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.lastModified", getJspFile()), e); } result = -1; } finally { if (uc != null) { try { uc.getInputStream().close(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.lastModified", getJspFile()), e); } result = -1; } } } return Long.valueOf(result); }
public static Method getReadMethod(Class<?> beanClass, String prop) throws JasperException { Method method = null; Class<?> type = null; try { java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(beanClass); if (info != null) { java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); for (int i = 0; i < pd.length; i++) { if (pd[i].getName().equals(prop)) { method = pd[i].getReadMethod(); type = pd[i].getPropertyType(); break; } } } else { // just in case introspection silently fails. throw new JasperException( Localizer.getMessage("jsp.error.beans.nobeaninfo", beanClass.getName())); } } catch (Exception ex) { throw new JasperException(ex); } if (method == null) { if (type == null) { throw new JasperException( Localizer.getMessage("jsp.error.beans.noproperty", prop, beanClass.getName())); } else { throw new JasperException( Localizer.getMessage("jsp.error.beans.nomethod", prop, beanClass.getName())); } } return method; }
protected void initWebXml() throws JasperException { try { if (webxmlLevel >= INC_WEBXML) { mapout = openWebxmlWriter(new File(webxmlFile)); servletout = new CharArrayWriter(); mappingout = new CharArrayWriter(); } else { mapout = null; servletout = null; mappingout = null; } if (webxmlLevel >= ALL_WEBXML) { mapout.write(Localizer.getMessage("jspc.webxml.header")); mapout.flush(); } else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings) { mapout.write(Localizer.getMessage("jspc.webinc.header")); mapout.flush(); } } catch (IOException ioe) { mapout = null; servletout = null; mappingout = null; throw new JasperException(ioe); } }
public static void main(String arg[]) { if (arg.length == 0) { System.out.println(Localizer.getMessage("jspc.usage")); } else { JspC jspc = new JspC(); try { jspc.setArgs(arg); if (jspc.helpNeeded) { System.out.println(Localizer.getMessage("jspc.usage")); } else { jspc.execute(); } } catch (JasperException je) { System.err.println(je); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } } catch (BuildException je) { System.err.println(je); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } } } }
public Class<?> load() throws JasperException { try { getJspLoader(); String name = getFQCN(); servletClass = jspLoader.loadClass(name); } catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); } catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); } removed = false; return servletClass; }
private void handleMissingResource( HttpServletRequest request, HttpServletResponse response, String jspUri) throws ServletException, IOException { String includeRequestUri = (String) request.getAttribute("javax.servlet.include.request_uri"); if (includeRequestUri != null) { String msg = Localizer.getMessage("jsp.error.file.not.found", jspUri); throw new ServletException(SecurityUtil.filter(msg)); } else { try { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); } catch (IllegalStateException e) { log.error(Localizer.getMessage("jsp.error.file.not.found", jspUri)); } } }
/** * Create a "Compiler" object based on some init param data. This is not done yet. Right now we're * just hardcoding the actual compilers that are created. */ public Compiler createCompiler() { if (jspCompiler != null) { return jspCompiler; } jspCompiler = null; if (options.getCompilerClassName() != null) { jspCompiler = createCompiler(options.getCompilerClassName()); } else { if (options.getCompiler() == null) { jspCompiler = createCompiler("org.apache.jasper.compiler.JDTCompiler"); if (jspCompiler == null) { jspCompiler = createCompiler("org.apache.jasper.compiler.AntCompiler"); } } else { jspCompiler = createCompiler("org.apache.jasper.compiler.AntCompiler"); if (jspCompiler == null) { jspCompiler = createCompiler("org.apache.jasper.compiler.JDTCompiler"); } } } if (jspCompiler == null) { throw new IllegalStateException(Localizer.getMessage("jsp.error.compiler")); } jspCompiler.init(this, jsw); return jspCompiler; }
private void doForward(String relativeUrlPath) throws ServletException, IOException { // JSP.4.5 If the buffer was flushed, throw IllegalStateException try { out.clear(); } catch (IOException ex) { IllegalStateException ise = new IllegalStateException( Localizer.getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; } // Make sure that the response object is not the wrapper for include while (response instanceof ServletResponseWrapperInclude) { response = ((ServletResponseWrapperInclude) response).getResponse(); } final String path = getAbsolutePathRelativeToContext(relativeUrlPath); String includeUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); if (includeUri != null) request.removeAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); try { context.getRequestDispatcher(path).forward(request, response); } finally { if (includeUri != null) request.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, includeUri); } }
protected void completeWebXml() { if (mapout != null) { try { servletout.writeTo(mapout); mappingout.writeTo(mapout); if (webxmlLevel >= ALL_WEBXML) { mapout.write(Localizer.getMessage("jspc.webxml.footer")); } else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings) { mapout.write(Localizer.getMessage("jspc.webinc.footer")); } mapout.close(); } catch (IOException ioe) { // nothing to do if it fails since we are done with it } } }
private void doRemoveAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: attributes.remove(name); break; case REQUEST_SCOPE: request.removeAttribute(name); break; case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer.getMessage("jsp.error.page.noSession")); } session.removeAttribute(name); break; case APPLICATION_SCOPE: context.removeAttribute(name); break; default: throw new IllegalArgumentException("Invalid scope"); } }
public void compile() throws JasperException, FileNotFoundException { createCompiler(); if (jspCompiler.isOutDated()) { if (isRemoved()) { throw new FileNotFoundException(jspUri); } try { jspCompiler.removeGeneratedFiles(); jspLoader = null; jspCompiler.compile(); jsw.setReload(true); jsw.setCompilationException(null); } catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); if (options.getDevelopment() && options.getRecompileOnFail()) { // Force a recompilation attempt on next access jsw.setLastModificationTest(-1); } throw ex; } catch (FileNotFoundException fnfe) { // Re-throw to let caller handle this - will result in a 404 throw fnfe; } catch (Exception ex) { JasperException je = new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; } } }
public Class load() throws JasperException, FileNotFoundException { try { getJspLoader(); String name; if (isTagFile()) { name = tagInfo.getTagClassName(); } else { name = getServletPackageName() + "." + getServletClassName(); } servletClass = jspLoader.loadClass(name); } catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); } catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); } removed = 0; return servletClass; }
protected Compiler createCompiler(String className) { Compiler compiler = null; try { compiler = (Compiler) Class.forName(className).newInstance(); } catch (InstantiationException e) { log.warn(Localizer.getMessage("jsp.error.compiler"), e); } catch (IllegalAccessException e) { log.warn(Localizer.getMessage("jsp.error.compiler"), e); } catch (NoClassDefFoundError e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.compiler"), e); } } catch (ClassNotFoundException e) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.error.compiler"), e); } } return compiler; }
public void destroy() { if (theServlet != null) { theServlet.destroy(); InstanceManager instanceManager = InstanceManagerFactory.getInstanceManager(config); try { instanceManager.destroyInstance(theServlet); } catch (Exception e) { // Log any exception, since it can't be passed along log.error(Localizer.getMessage("jsp.error.file.not.found", e.getMessage()), e); } } }
public static Object getValueFromPropertyEditorManager( Class<?> attrClass, String attrName, String attrValue) throws JasperException { try { PropertyEditor propEditor = PropertyEditorManager.findEditor(attrClass); if (propEditor != null) { propEditor.setAsText(attrValue); return propEditor.getValue(); } else { throw new IllegalArgumentException( Localizer.getMessage("jsp.error.beans.propertyeditor.notregistered")); } } catch (IllegalArgumentException ex) { throw new JasperException( Localizer.getMessage( "jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); } }
// __begin lookupReadMethodMethod public static Object handleGetProperty(Object o, String prop) throws JasperException { if (o == null) { throw new JasperException(Localizer.getMessage("jsp.error.beans.nullbean")); } Object value = null; try { Method method = getReadMethod(o.getClass(), prop); value = method.invoke(o, (Object[]) null); } catch (Exception ex) { throw new JasperException(ex); } return value; }
protected void createOutputDir() { String path = null; if (isTagFile()) { String tagName = tagInfo.getTagClassName(); path = tagName.replace('.', File.separatorChar); path = path.substring(0, path.lastIndexOf(File.separatorChar)); } else { path = getServletPackageName().replace('.', File.separatorChar); } // Append servlet or tag handler path to scratch dir try { File base = options.getScratchDir(); baseUrl = base.toURI().toURL(); outputDir = base.getAbsolutePath() + File.separator + path + File.separator; if (!makeOutputDir()) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder")); } } catch (MalformedURLException e) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e); } }
public void destroy() { if (theServlet != null) { theServlet.destroy(); InstanceManager instanceManager = InstanceManagerFactory.getInstanceManager(config); try { instanceManager.destroyInstance(theServlet); } catch (Exception e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); // Log any exception, since it can't be passed along log.error(Localizer.getMessage("jsp.error.file.not.found", e.getMessage()), t); } } }
public static Object getValueFromBeanInfoPropertyEditor( Class<?> attrClass, String attrName, String attrValue, Class<?> propertyEditorClass) throws JasperException { try { PropertyEditor pe = (PropertyEditor) propertyEditorClass.newInstance(); pe.setAsText(attrValue); return pe.getValue(); } catch (Exception ex) { throw new JasperException( Localizer.getMessage( "jsp.error.beans.property.conversion", attrValue, attrClass.getName(), attrName, ex.getMessage())); } }
/** * Find the WEB-INF dir by looking up in the directory tree. This is used if no explicit docbase * is set, but only files. XXX Maybe we should require the docbase. */ protected void locateUriRoot(File f) { String tUriBase = uriBase; if (tUriBase == null) { tUriBase = "/"; } try { if (f.exists()) { f = new File(f.getAbsolutePath()); while (true) { File g = new File(f, "WEB-INF"); if (g.exists() && g.isDirectory()) { uriRoot = f.getCanonicalPath(); uriBase = tUriBase; if (log.isInfoEnabled()) { log.info(Localizer.getMessage("jspc.implicit.uriRoot", uriRoot)); } break; } if (f.exists() && f.isDirectory()) { tUriBase = "/" + f.getName() + "/" + tUriBase; } String fParent = f.getParent(); if (fParent == null) { break; } else { f = new File(fParent); } // If there is no acceptable candidate, uriRoot will // remain null to indicate to the CompilerContext to // use the current working/user dir. } if (uriRoot != null) { File froot = new File(uriRoot); uriRoot = froot.getCanonicalPath(); } } } catch (IOException ioe) { // since this is an optional default and a null value // for uriRoot has a non-error meaning, we can just // pass straight through } }
private synchronized void init() throws JasperException { if (mappings != null) { return; } HashMap tmpMappings = null; try { tmpMappings = new HashMap(); processWebDotXml(tmpMappings); loadStandardTlds(tmpMappings); processTldsInFileSystem("/WEB-INF/", tmpMappings); } catch (Exception ex) { String msg = Localizer.getMessage("jsp.error.internal.tldinit", ex.getMessage()); throw new JasperException(msg, ex); } finally { mappings = tmpMappings; } }
@Override public void removeAttribute(final String name, final int scope) { if (name == null) { throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged( new PrivilegedAction<Void>() { @Override public Void run() { doRemoveAttribute(name, scope); return null; } }); } else { doRemoveAttribute(name, scope); } }
@Override public Object getAttribute(final String name, final int scope) { if (name == null) { throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { return AccessController.doPrivileged( new PrivilegedAction<Object>() { @Override public Object run() { return doGetAttribute(name, scope); } }); } else { return doGetAttribute(name, scope); } }
@Override public int getAttributesScope(final String name) { if (name == null) { throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { return (AccessController.doPrivileged( new PrivilegedAction<Integer>() { @Override public Integer run() { return Integer.valueOf(doGetAttributeScope(name)); } })) .intValue(); } else { return doGetAttributeScope(name); } }
private Enumeration<String> doGetAttributeNamesInScope(int scope) { switch (scope) { case PAGE_SCOPE: return Collections.enumeration(attributes.keySet()); case REQUEST_SCOPE: return request.getAttributeNames(); case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer.getMessage("jsp.error.page.noSession")); } return session.getAttributeNames(); case APPLICATION_SCOPE: return context.getAttributeNames(); default: throw new IllegalArgumentException("Invalid scope"); } }
private Object doGetAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: return attributes.get(name); case REQUEST_SCOPE: return request.getAttribute(name); case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer.getMessage("jsp.error.page.noSession")); } return session.getAttribute(name); case APPLICATION_SCOPE: return context.getAttribute(name); default: throw new IllegalArgumentException("Invalid scope"); } }
public void compile() throws JasperException, FileNotFoundException { createCompiler(); if (jspCompiler.isOutDated()) { try { jspCompiler.removeGeneratedFiles(); jspLoader = null; jspCompiler.compile(); jsw.setReload(true); jsw.setCompilationException(null); } catch (JasperException ex) { // Cache compilation exception jsw.setCompilationException(ex); throw ex; } catch (Exception ex) { JasperException je = new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); // Cache compilation exception jsw.setCompilationException(je); throw je; } } }
@Override public void release() { out = baseOut; try { if (isIncluded) { ((JspWriterImpl) out).flushBuffer(); // push it into the including jspWriter } else { // Old code: // out.flush(); // Do not flush the buffer even if we're not included (i.e. // we are the main page. The servlet will flush it and close // the stream. ((JspWriterImpl) out).flushBuffer(); } } catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer.getMessage("jsp.error.flush"), ex); throw ise; } finally { servlet = null; config = null; context = null; applicationContext = null; elContext = null; errorPageURL = null; request = null; response = null; depth = -1; baseOut.recycle(); session = null; attributes.clear(); for (BodyContentImpl body : outs) { body.recycle(); } } }
/** * Attempts to construct a JasperException that contains helpful information about what went * wrong. Uses the JSP compiler system to translate the line number in the generated servlet that * originated the exception to a line number in the JSP. Then constructs an exception containing * that information, and a snippet of the JSP to help debugging. Please see * http://issues.apache.org/bugzilla/show_bug.cgi?id=37062 and http://www.tfenne.com/jasper/ for * more details. * * @param ex the exception that was the cause of the problem. * @return a JasperException with more detailed information */ protected JasperException handleJspException(Exception ex) { try { Throwable realException = ex; if (ex instanceof ServletException) { realException = ((ServletException) ex).getRootCause(); } // First identify the stack frame in the trace that represents the JSP StackTraceElement[] frames = realException.getStackTrace(); StackTraceElement jspFrame = null; for (int i = 0; i < frames.length; ++i) { if (frames[i].getClassName().equals(this.getServlet().getClass().getName())) { jspFrame = frames[i]; break; } } if (jspFrame == null || this.ctxt.getCompiler().getPageNodes() == null) { // If we couldn't find a frame in the stack trace corresponding // to the generated servlet class or we don't have a copy of the // parsed JSP to hand, we can't really add anything return new JasperException(ex); } int javaLineNumber = jspFrame.getLineNumber(); JavacErrorDetail detail = ErrorDispatcher.createJavacError( jspFrame.getMethodName(), this.ctxt.getCompiler().getPageNodes(), null, javaLineNumber, ctxt); // If the line number is less than one we couldn't find out // where in the JSP things went wrong int jspLineNumber = detail.getJspBeginLineNumber(); if (jspLineNumber < 1) { throw new JasperException(ex); } if (options.getDisplaySourceFragment()) { return new JasperException( Localizer.getMessage("jsp.exception", detail.getJspFileName(), "" + jspLineNumber) + Constants.NEWLINE + Constants.NEWLINE + detail.getJspExtract() + Constants.NEWLINE + Constants.NEWLINE + "Stacktrace:", ex); } return new JasperException( Localizer.getMessage("jsp.exception", detail.getJspFileName(), "" + jspLineNumber), ex); } catch (Exception je) { // If anything goes wrong, just revert to the original behaviour if (ex instanceof JasperException) { return (JasperException) ex; } return new JasperException(ex); } }
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException { Servlet servlet; try { if (ctxt.isRemoved()) { throw new FileNotFoundException(jspUri); } if ((available > 0L) && (available < Long.MAX_VALUE)) { if (available > System.currentTimeMillis()) { response.setDateHeader("Retry-After", available); response.sendError( HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable")); return; } // Wait period has expired. Reset. available = 0; } /* * (1) Compile */ if (options.getDevelopment() || firstTime) { synchronized (this) { firstTime = false; // The following sets reload to true, if necessary ctxt.compile(); } } else { if (compileException != null) { // Throw cached compilation exception throw compileException; } } /* * (2) (Re)load servlet class file */ servlet = getServlet(); // If a page is to be precompiled only, return. if (precompile) { return; } } catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (FileNotFoundException fnfe) { // File has been removed. Let caller handle this. throw fnfe; } catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } try { /* * (3) Handle limitation of number of loaded Jsps */ if (unloadAllowed) { synchronized (this) { if (unloadByCount) { if (unloadHandle == null) { unloadHandle = ctxt.getRuntimeContext().push(this); } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { ctxt.getRuntimeContext().makeYoungest(unloadHandle); lastUsageTime = System.currentTimeMillis(); } } else { if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) { lastUsageTime = System.currentTimeMillis(); } } } } /* * (4) Service request */ if (servlet instanceof SingleThreadModel) { // sync on the wrapper so that the freshness // of the page is determined right before servicing synchronized (this) { servlet.service(request, response); } } else { servlet.service(request, response); } } catch (UnavailableException ex) { String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); if (includeRequestUri != null) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw ex; } int unavailableSeconds = ex.getUnavailableSeconds(); if (unavailableSeconds <= 0) { unavailableSeconds = 60; // Arbitrary default } available = System.currentTimeMillis() + (unavailableSeconds * 1000L); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage()); } catch (ServletException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IOException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (IllegalStateException ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw ex; } catch (Exception ex) { if (options.getDevelopment()) { throw handleJspException(ex); } throw new JasperException(ex); } }