Example usage for javax.servlet ServletContext getResourceAsStream

List of usage examples for javax.servlet ServletContext getResourceAsStream

Introduction

In this page you can find the example usage for javax.servlet ServletContext getResourceAsStream.

Prototype

public InputStream getResourceAsStream(String path);

Source Link

Document

Returns the resource located at the named path as an InputStream object.

Usage

From source file:axiom.servlet.AbstractServletClient.java

/**
 * Forward the request to a static file. The file must be reachable via
 * the context's protectedStatic resource base.
 *///from   w  ww. j a v a 2  s  . com
void sendForward(HttpServletResponse res, HttpServletRequest req, ResponseTrans axiomres) throws IOException {
    String forward = axiomres.getForward();
    ServletContext cx = getServletConfig().getServletContext();
    String path = cx.getRealPath(forward);
    if (path == null)
        throw new IOException("Resource " + forward + " not found");

    File file = new File(path);
    // calculate checksom on last modified date and content length.
    byte[] checksum = getChecksum(file);
    String etag = "\"" + new String(Base64.encode(checksum)) + "\"";
    res.setHeader("ETag", etag);
    String etagHeader = req.getHeader("If-None-Match");
    if (etagHeader != null) {
        StringTokenizer st = new StringTokenizer(etagHeader, ", \r\n");
        while (st.hasMoreTokens()) {
            if (etag.equals(st.nextToken())) {
                res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
        }
    }
    int length = (int) file.length();
    res.setContentLength(length);
    res.setContentType(axiomres.getContentType());

    InputStream in = cx.getResourceAsStream(forward);
    if (in == null)
        throw new IOException("Can't read " + path);
    try {
        OutputStream out = res.getOutputStream();

        int bufferSize = 4096;
        byte buffer[] = new byte[bufferSize];
        int l;

        while (length > 0) {
            if (length < bufferSize)
                l = in.read(buffer, 0, length);
            else
                l = in.read(buffer, 0, bufferSize);

            if (l == -1)
                break;

            length -= l;
            out.write(buffer, 0, l);
        }
    } finally {
        in.close();
    }
}

From source file:org.musicrecital.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}/*from   w  w w.ja v a  2  s.  c o m*/
 */
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    log.debug("Initializing context...");

    ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    PasswordEncoder passwordEncoder = null;
    try {
        ProviderManager provider = (ProviderManager) ctx
                .getBean("org.springframework.security.authentication.ProviderManager#0");
        for (Object o : provider.getProviders()) {
            AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            } else if (ctx.getBean("passwordEncoder") != null) {
                passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder");
            }
        }
    } catch (NoSuchBeanDefinitionException n) {
        log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (log.isDebugEnabled()) {
        log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        if (passwordEncoder != null) {
            log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
        }
        log.debug("Populating drop-downs...");
    }

    setupContext(context);

    // Determine version number for CSS and JS Assets
    String appVersion = null;
    try {
        InputStream is = context.getResourceAsStream("/META-INF/MANIFEST.MF");
        if (is == null) {
            log.warn("META-INF/MANIFEST.MF not found.");
        } else {
            Manifest mf = new Manifest();
            mf.read(is);
            Attributes atts = mf.getMainAttributes();
            appVersion = atts.getValue("Implementation-Version");
        }
    } catch (IOException e) {
        log.error("I/O Exception reading manifest: " + e.getMessage());
    }

    // If there was a build number defined in the war, then use it for
    // the cache buster. Otherwise, assume we are in development mode
    // and use a random cache buster so developers don't have to clear
    // their browser cache.
    if (appVersion == null || appVersion.contains("SNAPSHOT")) {
        appVersion = "" + new Random().nextInt(100000);
    }

    log.info("Application version set to: " + appVersion);
    context.setAttribute(Constants.ASSETS_VERSION, appVersion);
}

From source file:org.apache.click.util.ClickUtils.java

/**
 * Return the InputStream for the Click configuration file <tt>click.xml</tt>.
 * This method will first lookup the <tt>click.xml</tt> under the
 * applications <tt>WEB-INF</tt> directory, and then if not found it will
 * attempt to find the configuration file on the classpath root.
 *
 * @param servletContext the servlet context to obtain the Click configuration
 *     from/*from  w w  w.j  av  a  2 s . c o m*/
 * @return the InputStream for the Click configuration file
 * @throws RuntimeException if the resource could not be found
 */
public static InputStream getClickConfig(ServletContext servletContext) {
    InputStream inputStream = servletContext.getResourceAsStream(DEFAULT_APP_CONFIG);

    if (inputStream == null) {
        inputStream = ClickUtils.getResourceAsStream("/click.xml", ClickUtils.class);
        if (inputStream == null) {
            String msg = "could not find click app configuration file: " + DEFAULT_APP_CONFIG
                    + " or click.xml on classpath";
            throw new RuntimeException(msg);
        }
    }

    return inputStream;
}

From source file:edu.mit.csail.sls.wami.portal.xmlrpc.XmlRpcPortalRecognizer.java

public void setParameters(ServletContext sc, Map<String, String> map) throws RecognizerException {
    this.sc = sc;
    String recDomain = (String) sc.getAttribute("recDomain");
    String developerEmail = map.get("developerEmail");
    String developerKey = map.get("developerKey");
    String recordFormat = map.get("recordFormat");
    int recordSampleRate = Integer.parseInt(map.get("recordSampleRate"));
    boolean recordIsLittleEndian = Boolean.parseBoolean(map.get("recordIsLittleEndian"));
    String incrementalResultsStr = map.get("incrementalResults");
    incrementalResults = (incrementalResultsStr == null || Boolean.parseBoolean(incrementalResultsStr));

    serverAddress = null;/*from ww  w.  java2  s .  c  o m*/
    try {
        serverAddress = new URL(map.get("url"));
    } catch (MalformedURLException e) {
        throw new RecognizerException("Invalid recognizer url", e);
    }

    XmlRpcClientConfig config = createClientConfig(serverAddress, 10 * 1000, 10 * 1000);
    client = new XmlRpcClient();

    XmlRpcCommonsTransportFactory factory = new XmlRpcCommonsTransportFactory(client);

    // Use HTTP 1.1
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    factory.setHttpClient(httpClient);

    client.setTransportFactory(factory);
    client.setConfig(config);

    Object[] createParams = { developerEmail, developerKey, recordFormat, recordSampleRate,
            recordIsLittleEndian, recDomain };

    try {
        sessionId = (String) client.execute("Portal.createRecognizerSession", createParams);
    } catch (XmlRpcException e) {
        if (e.code == ErrorCodes.SERVER_ERROR_CODE) {
            throw new RecognizerException(e);
        } else {
            throw new RecognizerUnreachableException(e);
        }
    }

    String jsgfGrammarPath = map.get("jsgfGrammarPath");
    String jsgfGrammarLanguage = map.get("jsgfGrammarLanguage");
    if (jsgfGrammarPath != null) {
        InputStream in = sc.getResourceAsStream(jsgfGrammarPath);
        if (in == null) {
            throw new RecognizerException("Couldn't find grammar: " + jsgfGrammarPath);
        }

        String language = (jsgfGrammarLanguage != null) ? jsgfGrammarLanguage : "en-us";

        try {
            JsgfGrammar grammar = new JsgfGrammar(in, language);
            setLanguageModel(grammar);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.eclipse.birt.report.utility.ParameterAccessor.java

/**
 * Returns the application properties//  www . j  av  a2  s. c  o m
 * 
 * @param context
 * @param props
 * @return
 */
public synchronized static Map initViewerProps(ServletContext context, Map props) {
    // initialize map
    if (props == null)
        props = new HashMap();

    // get config file
    String file = context.getInitParameter(INIT_PARAM_CONFIG_FILE);
    if (file == null || file.trim().length() <= 0)
        file = IBirtConstants.DEFAULT_VIEWER_CONFIG_FILE;

    try {

        InputStream is = null;
        if (isRelativePath(file)) {
            // realtive path
            if (!file.startsWith("/")) //$NON-NLS-1$
                file = "/" + file; //$NON-NLS-1$

            is = context.getResourceAsStream(file);
        } else {
            // absolute path
            is = new FileInputStream(file);
        }

        // parse the properties file
        PropertyResourceBundle bundle = new PropertyResourceBundle(is);
        if (bundle != null) {
            Enumeration<String> keys = bundle.getKeys();
            while (keys != null && keys.hasMoreElements()) {
                String key = keys.nextElement();
                String value = (String) bundle.getObject(key);
                if (key != null && value != null)
                    props.put(key, value);
            }
        }
    } catch (Exception e) {
    }

    return props;
}

From source file:com.tremolosecurity.scale.config.ScaleCommonConfig.java

@PostConstruct
public void init() {
    try {/*www . j a v a2s . c  o  m*/
        ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();

        String logPath = null;

        try {
            logPath = InitialContext.doLookup("java:comp/env/scaleLog4jPath");
        } catch (NamingException ne) {
            try {
                logPath = InitialContext.doLookup("java:/env/scaleLog4jPath");
            } catch (NamingException ne2) {
                logPath = null;
            }
        }
        if (logPath == null) {
            Properties props = new Properties();
            props.put("log4j.rootLogger", "info,console");

            //props.put("log4j.appender.console","org.apache.log4j.RollingFileAppender");
            //props.put("log4j.appender.console.File","/home/mlb/myvd.log");
            props.put("log4j.appender.console", "org.apache.log4j.ConsoleAppender");
            props.put("log4j.appender.console.layout", "org.apache.log4j.PatternLayout");
            props.put("log4j.appender.console.layout.ConversionPattern", "[%d][%t] %-5p %c{1} - %m%n");

            PropertyConfigurator.configure(props);
        } else {

            if (logPath.startsWith("WEB-INF/")) {
                org.apache.log4j.xml.DOMConfigurator.configure(context.getRealPath(logPath));
            } else {
                org.apache.log4j.xml.DOMConfigurator.configure(logPath);
            }

        }

        logger = Logger.getLogger(ScaleCommonConfig.class.getName());

        logger.info("Initializing Scale " + version);

        String configPath = null;

        try {
            configPath = InitialContext.doLookup("java:comp/env/scaleConfigPath");
        } catch (NamingException ne) {
            try {
                configPath = InitialContext.doLookup("java:/env/scaleConfigPath");
            } catch (NamingException ne2) {
                configPath = null;
            }

        }

        if (configPath == null) {
            configPath = "WEB-INF/scaleConfig.xml";
            logger.warn("No configuraiton path found - Loading configuration from '" + configPath + "'");
        } else {
            logger.info("Loading configuration from '" + configPath + "'");
        }

        InputStream in = null;

        if (configPath.startsWith("WEB-INF")) {

            in = new ByteArrayInputStream(ScaleCommonConfig
                    .includeEnvironmentVariables(context.getRealPath("/" + configPath)).getBytes("UTF-8"));

        } else {
            in = new ByteArrayInputStream(
                    ScaleCommonConfig.includeEnvironmentVariables(configPath).getBytes("UTF-8"));
        }

        JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.scale.config.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();

        Object obj = unmarshaller.unmarshal(in);

        JAXBElement<ScaleCommonConfigType> scaleConfig = (JAXBElement<ScaleCommonConfigType>) obj;

        this.scaleConfig = scaleConfig.getValue();

        String ksPath = this.scaleConfig.getServiceConfiguration().getKeyStorePath();
        String ksPass = this.scaleConfig.getServiceConfiguration().getKeyStorePassword();

        in = null;

        if (ksPath.startsWith("WEB-INF")) {
            in = context.getResourceAsStream("/" + ksPath);
        } else {
            in = new FileInputStream(ksPath);
        }

        this.tlsKeys = KeyStore.getInstance("JKS");
        this.tlsKeys.load(in, ksPass.toCharArray());

        this.sslctx = SSLContexts.custom().loadTrustMaterial(this.tlsKeys)
                .loadKeyMaterial(this.tlsKeys, ksPass.toCharArray()).build();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:be.ff.gui.web.struts.action.ActionPlugInPlugIn.java

/**
 * Loads and verifies (using a DTD) the action plug-in configuration file. Afterwards this
 * method initializes the <code>ActionPlugInChain</code>.
 *
 * @param config ApplicationConfig for the sub-application with which this plug in is associated
 * @exception ServletException if this <code>PlugIn</code> cannot be successfully initialized
 *///from  w ww.jav  a  2s .  c  o m
public void init(ActionServlet config, ModuleConfig module) throws ServletException {
    if (ActionPlugInChain.foiInicializado()) {
        if (log.isDebugEnabled()) {
            log.debug("O ActionPlugInPlugIn j foi inicializado anteriormente. Ignorando.");
        }
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug("Entrada no mtodo");
    }

    // this value object will hold the values specified in the action plug-in config file
    ActionPlugInChainDefinition chainDefintion = new ActionPlugInChainDefinition();

    // create a digester to scan through the action plug-in config file
    Digester digester = new Digester();
    digester.push(chainDefintion);

    // try to find a local DTD to validate the configuration file
    ServletContext context = config.getServletContext();
    if (getConfigDTD() == null) {
        String msg = "[ActionPlugInPlugIn::init] Please specify a valid context relative location of "
                + "the DTD for the action plug-in configuration file. Do this in the Struts configuration "
                + "file at the plug-in tag that initializes the Action Plug-in Extension.";
        log.warn(msg);
        digester.setValidating(false);
        // Although set to false the SAX based parser STILL wants to load the publicly
        // available DTD that is specified in the XML file!! This causes an error on
        // times when the DTD at the specified location is not available.
        // Why doesn't this statement turn this of????
    } else {
        URL dtdURL = null;
        try {
            dtdURL = context.getResource(getConfigDTD());
            if (dtdURL == null) {
                String msg = "[ActionPlugInPlugIn::init] The action plug-in configuration DTD was not found at the "
                        + "context relative location '" + getConfigDTD()
                        + "'. Please make sure that this DTD is available at "
                        + "a context relative location, because the system identifier that is specified in the "
                        + "configuration file might not be accessible.";
                log.warn(msg);
                digester.setValidating(false);
                // Although set to false the SAX based parser STILL wants to load the publicly
                // available DTD that is specified in the XML file!! This causes an error on
                // times when the DTD at the specified location is not available.
                // Why doesn't this statement turn this of????
            } else {
                digester.register(DOCTYPE_PUBLIC_ID, dtdURL.toString());
                digester.setValidating(true);
            }
        } catch (MalformedURLException e) {
            String msg = "[ActionPlugInPlugIn::init] The location of the DTD for the action plug-in configuration file was "
                    + "invalid:'" + getConfigDTD()
                    + "'. Please specify a valid context relative location for the DTD.";
            log.warn(msg);
            digester.setValidating(false);
            // Although set to false the SAX based parser STILL wants to load the publicly
            // available DTD that is specified in the XML file!! This causes an error on
            // times when the DTD at the specified location is not available.
            // Why doesn't this statement turn this of????
        }
    }

    // add rules
    digester.addObjectCreate("action-plug-in-config/action-plug-in", ActionPlugInDefinition.class);
    digester.addSetNext("action-plug-in-config/action-plug-in", "addActionPlugInDefintion",
            ActionPlugInDefinition.class.getName());
    digester.addCallMethod("action-plug-in-config/action-plug-in/class", "setClassName", 0);
    digester.addCallMethod("action-plug-in-config/action-plug-in/init-params/param", "addInitParam", 2);
    digester.addCallParam("action-plug-in-config/action-plug-in/init-params/param/name", 0);
    digester.addCallParam("action-plug-in-config/action-plug-in/init-params/param/value", 1);
    digester.addCallMethod("action-plug-in-config/action-plug-in/disabled-for/action-path",
            "addDisabledActionPath", 0);
    digester.addCallMethod("action-plug-in-config/action-plug-in/enabled-for/action-path",
            "addEnabledActionPath", 0);

    // point to the XML file
    InputStream input = context.getResourceAsStream(getConfigFile());
    if (input == null) {
        String msg = "[ActionPlugInPlugIn::init] The action plug-in configuration file was not found "
                + "at location '" + getConfigFile() + "'. Please make sure that you have specified "
                + "the correct value for the 'configFile' property of the action plug-in Struts "
                + "plug-in that is defined in struts-config.xml. Please note that this path is Web "
                + "application context relative.";
        throw new ServletException(msg);
    }

    // run the digester
    try {
        digester.parse(new BufferedInputStream(input));
    } catch (Exception e) {
        String msg = "[ActionPlugInPlugIn::init] An exception was thrown during the parsing of the "
                + "action plug-in configuration file (" + getConfigFile() + "). Make sure that "
                + "the configuration file refers to a DTD and that its content is valid according to "
                + "that DTD.";
        throw new ServletException(msg, e);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                log.error(
                        "[ActionPlugInPlugIn::init] An IOException was thrown while trying to close the input stream of the action plug-in configuration file.",
                        e);
            }
        }
    }

    // ask the action plug-in chain to initialize itself
    ActionPlugInChain.init(chainDefintion, context);
}

From source file:org.codehaus.groovy.grails.web.errors.GrailsWrappedRuntimeException.java

/**
 * @param servletContext The ServletContext instance
 * @param t The exception that was thrown
 *///from  w w  w . j av a  2 s . com
public GrailsWrappedRuntimeException(ServletContext servletContext, Throwable t) {
    super(t.getMessage(), t);
    cause = t;
    FastStringPrintWriter pw = FastStringPrintWriter.newInstance();
    cause.printStackTrace(pw);
    stackTrace = pw.toString();

    while (cause.getCause() != cause) {
        if (cause.getCause() == null) {
            break;
        }
        cause = cause.getCause();
    }

    stackTraceLines = stackTrace.split("\\n");

    if (cause instanceof MultipleCompilationErrorsException) {
        MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) cause;
        Object message = mcee.getErrorCollector().getErrors().iterator().next();
        if (message instanceof SyntaxErrorMessage) {
            SyntaxErrorMessage sem = (SyntaxErrorMessage) message;
            lineNumber = sem.getCause().getLine();
            className = sem.getCause().getSourceLocator();
            sem.write(pw);
        }
    } else {
        Matcher m1 = PARSE_DETAILS_STEP1.matcher(stackTrace);
        Matcher m2 = PARSE_DETAILS_STEP2.matcher(stackTrace);
        Matcher gsp = PARSE_GSP_DETAILS_STEP1.matcher(stackTrace);
        try {
            if (gsp.find()) {
                className = gsp.group(2);
                lineNumber = Integer.parseInt(gsp.group(3));
                gspFile = URL_PREFIX + "views/" + gsp.group(1) + '/' + className;
            } else {
                if (m1.find()) {
                    do {
                        className = m1.group(1);
                        lineNumber = Integer.parseInt(m1.group(2));
                    } while (m1.find());
                } else {
                    while (m2.find()) {
                        className = m2.group(1);
                        lineNumber = Integer.parseInt(m2.group(2));
                    }
                }
            }
        } catch (NumberFormatException nfex) {
            // ignore
        }
    }

    LineNumberReader reader = null;
    try {
        checkIfSourceCodeAware(t);
        checkIfSourceCodeAware(cause);

        if (getLineNumber() > -1) {
            String fileLocation;
            String url = null;

            if (fileName != null) {
                fileLocation = fileName;
            } else {
                String urlPrefix = "";
                if (gspFile == null) {
                    fileName = className.replace('.', '/') + ".groovy";

                    GrailsApplication application = WebApplicationContextUtils
                            .getRequiredWebApplicationContext(servletContext)
                            .getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class);
                    // @todo Refactor this to get the urlPrefix from the ArtefactHandler
                    if (application.isArtefactOfType(ControllerArtefactHandler.TYPE, className)) {
                        urlPrefix += "/controllers/";
                    } else if (application.isArtefactOfType(TagLibArtefactHandler.TYPE, className)) {
                        urlPrefix += "/taglib/";
                    } else if (application.isArtefactOfType(ServiceArtefactHandler.TYPE, className)) {
                        urlPrefix += "/services/";
                    }
                    url = URL_PREFIX + urlPrefix + fileName;
                } else {
                    url = gspFile;
                    GrailsApplicationAttributes attrs = new DefaultGrailsApplicationAttributes(servletContext);
                    GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
                    int[] lineNumbers = engine.calculateLineNumbersForPage(servletContext, url);
                    if (lineNumber < lineNumbers.length) {
                        lineNumber = lineNumbers[lineNumber - 1];
                    }
                }
                fileLocation = "grails-app" + urlPrefix + fileName;
            }

            InputStream in = null;
            if (!StringUtils.isBlank(url)) {
                in = servletContext.getResourceAsStream(url);
                LOG.debug("Attempting to display code snippet found in url " + url);
            }
            if (in == null) {
                Resource r = null;
                try {
                    r = resolver.getResource(fileLocation);
                    in = r.getInputStream();
                } catch (Throwable e) {
                    r = resolver.getResource("file:" + fileLocation);
                    if (r.exists()) {
                        try {
                            in = r.getInputStream();
                        } catch (IOException e1) {
                            // ignore
                        }
                    }
                }
            }

            if (in != null) {
                reader = new LineNumberReader(new InputStreamReader(in));
                String currentLine = reader.readLine();
                StringBuilder buf = new StringBuilder();
                while (currentLine != null) {
                    int currentLineNumber = reader.getLineNumber();
                    if ((lineNumber > 0 && currentLineNumber == lineNumber - 1)
                            || (currentLineNumber == lineNumber)) {
                        buf.append(currentLineNumber).append(": ").append(currentLine).append("\n");
                    } else if (currentLineNumber == lineNumber + 1) {
                        buf.append(currentLineNumber).append(": ").append(currentLine);
                        break;
                    }
                    currentLine = reader.readLine();
                }
                codeSnippet = buf.toString().split("\n");
            }
        }
    } catch (IOException e) {
        LOG.warn("[GrailsWrappedRuntimeException] I/O error reading line diagnostics: " + e.getMessage(), e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

private Set<String> loadSet(ServletContext context, String resourcePath) {
    Set<String> set = new HashSet<>();
    try {/*from w ww . ja v  a2  s  . c om*/
        InputStream in = context.getResourceAsStream(resourcePath);
        BufferedReader buf = new BufferedReader(new InputStreamReader(in));
        for (String line = null; (line = buf.readLine()) != null;) {
            set.add(line);
        }
        return set;
    } catch (Exception ex) {
        log.error("Error loading set from " + resourcePath, ex);
        return null;
    }
}

From source file:org.grails.web.errors.GrailsWrappedRuntimeException.java

/**
 * @param servletContext The ServletContext instance
 * @param t The exception that was thrown
 *//*from  w  ww . j a v  a  2 s . c om*/
public GrailsWrappedRuntimeException(ServletContext servletContext, Throwable t) {
    super(t.getMessage(), t);
    this.cause = t;
    Throwable cause = t;

    FastStringPrintWriter pw = FastStringPrintWriter.newInstance();
    cause.printStackTrace(pw);
    stackTrace = pw.toString();

    while (cause.getCause() != cause) {
        if (cause.getCause() == null) {
            break;
        }
        cause = cause.getCause();
    }

    stackTraceLines = stackTrace.split("\\n");

    if (cause instanceof MultipleCompilationErrorsException) {
        MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) cause;
        Object message = mcee.getErrorCollector().getErrors().iterator().next();
        if (message instanceof SyntaxErrorMessage) {
            SyntaxErrorMessage sem = (SyntaxErrorMessage) message;
            lineNumber = sem.getCause().getLine();
            className = sem.getCause().getSourceLocator();
            sem.write(pw);
        }
    } else {
        Matcher m1 = PARSE_DETAILS_STEP1.matcher(stackTrace);
        Matcher m2 = PARSE_DETAILS_STEP2.matcher(stackTrace);
        Matcher gsp = PARSE_GSP_DETAILS_STEP1.matcher(stackTrace);
        try {
            if (gsp.find()) {
                className = gsp.group(2);
                lineNumber = Integer.parseInt(gsp.group(3));
                gspFile = URL_PREFIX + "views/" + gsp.group(1) + '/' + className;
            } else {
                if (m1.find()) {
                    do {
                        className = m1.group(1);
                        lineNumber = Integer.parseInt(m1.group(2));
                    } while (m1.find());
                } else {
                    while (m2.find()) {
                        className = m2.group(1);
                        lineNumber = Integer.parseInt(m2.group(2));
                    }
                }
            }
        } catch (NumberFormatException nfex) {
            // ignore
        }
    }

    LineNumberReader reader = null;
    try {
        checkIfSourceCodeAware(t);
        checkIfSourceCodeAware(cause);

        if (getLineNumber() > -1) {
            String fileLocation;
            String url = null;

            if (fileName != null) {
                fileLocation = fileName;
            } else {
                String urlPrefix = "";
                if (gspFile == null) {
                    fileName = className.replace('.', '/') + ".groovy";

                    GrailsApplication application = WebApplicationContextUtils
                            .getRequiredWebApplicationContext(servletContext)
                            .getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class);
                    // @todo Refactor this to get the urlPrefix from the ArtefactHandler
                    if (application.isArtefactOfType(ControllerArtefactHandler.TYPE, className)) {
                        urlPrefix += "/controllers/";
                    } else if (application.isArtefactOfType(TagLibArtefactHandler.TYPE, className)) {
                        urlPrefix += "/taglib/";
                    } else if (application.isArtefactOfType(ServiceArtefactHandler.TYPE, className)) {
                        urlPrefix += "/services/";
                    }
                    url = URL_PREFIX + urlPrefix + fileName;
                } else {
                    url = gspFile;
                    GrailsApplicationAttributes attrs = null;
                    try {
                        attrs = grailsApplicationAttributesConstructor.newInstance(servletContext);
                    } catch (Exception e) {
                        ReflectionUtils.rethrowRuntimeException(e);
                    }
                    ResourceAwareTemplateEngine engine = attrs.getPagesTemplateEngine();
                    lineNumber = engine.mapStackLineNumber(url, lineNumber);
                }
                fileLocation = "grails-app" + urlPrefix + fileName;
            }

            InputStream in = null;
            if (!GrailsStringUtils.isBlank(url)) {
                in = servletContext.getResourceAsStream(url);
                LOG.debug("Attempting to display code snippet found in url " + url);
            }
            if (in == null) {
                Resource r = null;
                try {
                    r = resolver.getResource(fileLocation);
                    in = r.getInputStream();
                } catch (Throwable e) {
                    r = resolver.getResource("file:" + fileLocation);
                    if (r.exists()) {
                        try {
                            in = r.getInputStream();
                        } catch (IOException e1) {
                            // ignore
                        }
                    }
                }
            }

            if (in != null) {
                reader = new LineNumberReader(new InputStreamReader(in, "UTF-8"));
                String currentLine = reader.readLine();
                StringBuilder buf = new StringBuilder();
                while (currentLine != null) {
                    int currentLineNumber = reader.getLineNumber();
                    if ((lineNumber > 0 && currentLineNumber == lineNumber - 1)
                            || (currentLineNumber == lineNumber)) {
                        buf.append(currentLineNumber).append(": ").append(currentLine).append("\n");
                    } else if (currentLineNumber == lineNumber + 1) {
                        buf.append(currentLineNumber).append(": ").append(currentLine);
                        break;
                    }
                    currentLine = reader.readLine();
                }
                codeSnippet = buf.toString().split("\n");
            }
        }
    } catch (IOException e) {
        LOG.warn("[GrailsWrappedRuntimeException] I/O error reading line diagnostics: " + e.getMessage(), e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}