Interpretiert den Script-Name und laedt das entsprechende Bild aus den internen Resourcen.

@see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest,
javax.servlet.http.HttpServletResponse)
336549
@Override
    protected void service(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
	// get out Stream

	// pic
	String[] arrPath = (req.getServletPath()).split("\\.");
	String pic = PIC_SOURCE + "404.gif";
	if (arrPath.length >= 3) {
	    pic = PIC_SOURCE + ((arrPath[arrPath.length - 3] + "." + arrPath[arrPath.length - 2]).replaceFirst("/", ""));

	    // mime type
	    String mime = "image/" + arrPath[arrPath.length - 2];
	    ReqRspUtil.setContentType(rsp, mime);
	}

	// write data from pic input to response output
	OutputStream os = null;
	InputStream is = null;
	try {
	    os = rsp.getOutputStream();
	    is = getClass().getResourceAsStream(pic);
	    if (is == null) {
		is = getClass().getResourceAsStream(PIC_SOURCE + "404.gif");
	    }

	    byte[] buf = new byte[4 * 1024];
	    int nread = 0;
	    while ((nread = is.read(buf)) >= 0) {
		os.write(buf, 0, nread);
	    }
	}
	catch (FileNotFoundException e) {}
	catch (IOException e) {}
	finally {
	    IOUtil.closeEL(is, os);
	}
    }
1045675
@Override
  public String getProtocol(HttpServletRequest request) {
    String proto = request.getHeader(X_FORWARED_PROTO);
    if( proto != null ) return proto;
    return super.getProtocol(request);
  }
409951
@SuppressWarnings("unchecked")
	private StringBuffer buildEngineScript(StringBuffer engineScript,ServletContext servletContext) {
		List<Container> containers = ContainerUtil.getAllPublishedContainers(servletContext);
		String allowGetForSafariButMakeForgeryEasier = "";
		String scriptTagProtection = DwrConstants.SCRIPT_TAG_PROTECTION;
		String pollWithXhr = "";
		String sessionCookieName = "JSESSIONID";
		

		
		for(Iterator<Container> it = containers.iterator();it.hasNext();) {
			Container container = it.next();
			ServerLoadMonitor monitor = (ServerLoadMonitor) container.getBean(ServerLoadMonitor.class.getName());
			pollWithXhr = monitor.supportsStreaming() ? "false" : "true";
			
			if(null != container.getBean("allowGetForSafariButMakeForgeryEasier")){
				allowGetForSafariButMakeForgeryEasier = (String)container.getBean("allowGetForSafariButMakeForgeryEasier");
			}
			if(null != container.getBean("scriptTagProtection")){
				scriptTagProtection = (String)container.getBean("scriptTagProtection");
			}
			if(null != container.getBean("sessionCookieName")){
				sessionCookieName = (String)container.getBean("sessionCookieName");
			}		
		}
		StringBuffer sb = new StringBuffer();
		Matcher matcher = PARAMS_PATTERN.matcher(engineScript);
		while(matcher.find()) {
			String match = matcher.group();
			if("${allowGetForSafariButMakeForgeryEasier}".equals(match)){
				matcher.appendReplacement(sb, allowGetForSafariButMakeForgeryEasier);				
			}
			else if("${pollWithXhr}".equals(match)){
				matcher.appendReplacement(sb, pollWithXhr);				
			}
			else if("${sessionCookieName}".equals(match)){
				matcher.appendReplacement(sb, sessionCookieName);				
			}
			else if("${scriptTagProtection}".equals(match)){
				matcher.appendReplacement(sb, scriptTagProtection);				
			}
			else if("${scriptSessionId}".equals(match)){
				matcher.appendReplacement(sb, "\"+JAWR.dwr_scriptSessionId+\"");	
			}
			else if("${defaultPath}".equals(match)){

				matcher.appendReplacement(sb, "\"+JAWR.jawr_dwr_path+\"");
			}
		}
		DWRParamWriter.setUseDynamicSessionId(true);
		matcher.appendTail(sb);
		return sb;
	}
79295
public void service(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException
    {
    	if ((proxyURLPrefix == null) || (proxyURLPrefix.length() == 0))
    	{	// No proxy specified
        	super.service(req, res);
    		return;
    	}
		ServletOutputStream streamOut = res.getOutputStream();
    	try {
    		String proxyURLString = getProxyURLString(req);
    		HttpRequestBase httpRequest = getHttpRequest(req, proxyURLString);
    		addHeaders(req, httpRequest);
    		this.getDataFromClient(httpRequest, streamOut);
		} catch (Exception e) {
			displayErrorInHtml(streamOut, e);
		}
    }
493283
@Override
  public boolean service(RequestBaratine request)
  {
    request.status(HttpStatus.NOT_FOUND);
    
    request.write("Not found: " + request.uri() + "\n");
    request.ok();
    
    return true;
  }
542007
@Override
  public void onHttpRequest(
      final ParsedHttpRequest parsedHttpRequest,
      final HttpServletResponse response) throws IOException, ServletException {

    LOG.log(Level.INFO, "HttpServerReefEventHandler in webserver onHttpRequest is called: {0}",
        parsedHttpRequest.getRequestUri());

    final String version = parsedHttpRequest.getVersion().toLowerCase();
    final String target = parsedHttpRequest.getTargetEntity().toLowerCase();

    switch (target) {
    case "evaluators": {
      final String queryStr = parsedHttpRequest.getQueryString();
      if (queryStr == null || queryStr.isEmpty()) {
        if (version.equals(VER)) {
          writeEvaluatorsJsonOutput(response);
        } else {
          writeEvaluatorsWebOutput(response);
        }
      } else {
        handleQueries(response, parsedHttpRequest.getQueryMap(), version);
      }
      break;
    }
    case "driver":
      if (version.equals(VER)) {
        writeDriverJsonInformation(response);
      } else {
        writeDriverWebInformation(response);
      }
      break;
    case "close":
      for (final EventHandler<Void> e : clientCloseHandlers) {
        e.onNext(null);
      }
      response.getWriter().println("Enforced closing");
      break;
    case "kill":
      reefStateManager.onClientKill();
      response.getWriter().println("Killing");
      break;
    case "duration":
      final ArrayList<String> lines =
          LogParser.getFilteredLinesFromFile(driverStderrFile, LoggingScopeImpl.DURATION, LoggingScopeImpl.TOKEN, null);
      writeLines(response, lines, "Performance...");
      break;
    case "stages":
      final ArrayList<String> starts =
          LogParser.getFilteredLinesFromFile(driverStderrFile, LoggingScopeImpl.START_PREFIX, logLevelPrefix, null);
      final ArrayList<String> exits =
          LogParser.getFilteredLinesFromFile(driverStderrFile, LoggingScopeImpl.EXIT_PREFIX, logLevelPrefix,
              LoggingScopeImpl.DURATION);
      final ArrayList<String> startsStages = LogParser.findStages(starts, LogParser.START_INDICATORS);
      final ArrayList<String> endStages = LogParser.findStages(exits, LogParser.END_INDICATORS);
      final ArrayList<String> result = LogParser.mergeStages(startsStages, endStages);
      writeLines(response, result, "Current Stages...");
      break;
    case "logfile":
      final List<String> names = parsedHttpRequest.getQueryMap().get("filename");
      final PrintWriter writer = response.getWriter();
      if (names == null || names.size() == 0) {
        writer.println("File name is not provided");
      } else {
        final String fileName = names.get(0);
        if (!fileName.equals(driverStdoutFile) && !fileName.equals(driverStderrFile)) {
          writer.println(String.format("Unsupported file names: [%s] ", fileName));
        } else {
          try {
            final byte[] outputBody = readFile(fileName).getBytes(StandardCharsets.UTF_8);
            writer.print(Arrays.toString(outputBody));
          } catch (final IOException e) {
            writer.println(String.format("Cannot find the log file: [%s].", fileName));
          }
        }
      }
      break;
    case "progress":
      response.getWriter().println(progressProvider.get().getProgress());
      break;
    default:
      response.getWriter().println(String.format("Unsupported query for entity: [%s].", target));
    }
  }
273937
@Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String method = req.getMethod();

        if (LOG.isDebugEnabled()) {
            String path = getRelativePath(req);
            LOG.debug("[" + method + "] " + path);
        }

        // check authorization
        String auth = req.getHeader(HEADER_AUTHORIZATION);
        if ((auth == null) || !auth.toUpperCase().startsWith(AUTHORIZATION_BASIC_PREFIX)) {

            // no authorization data is available
            requestAuthorization(resp);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_NO_AUTHORIZATION_0));
            }

            return;
        }

        // get encoded user and password, following after "BASIC "
        String base64Token = auth.substring(6);

        // decode it, using base 64 decoder
        String token = new String(Base64.decodeBase64(base64Token.getBytes()));
        String password = null;
        int pos = token.indexOf(SEPARATOR_CREDENTIALS);
        if (pos != -1) {
            m_username = token.substring(0, pos);
            password = token.substring(pos + 1);
        }

        // get session
        try {
            m_session = m_repository.login(m_username, password);
        } catch (CmsException ex) {
            m_session = null;
        }

        if (m_session == null) {

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_LOGIN_FAILED_1, m_username));
            }

            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        if (method.equals(METHOD_PROPFIND)) {
            doPropfind(req, resp);
        } else if (method.equals(METHOD_PROPPATCH)) {
            doProppatch(req, resp);
        } else if (method.equals(METHOD_MKCOL)) {
            doMkcol(req, resp);
        } else if (method.equals(METHOD_COPY)) {
            doCopy(req, resp);
        } else if (method.equals(METHOD_MOVE)) {
            doMove(req, resp);
        } else if (method.equals(METHOD_LOCK)) {
            doLock(req, resp);
        } else if (method.equals(METHOD_UNLOCK)) {
            doUnlock(req, resp);
        } else {

            // DefaultServlet processing
            super.service(req, resp);
        }

    }
847969
public void service(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException
    {
	    boolean fileFound = sendResourceFile(req, resp);
		if (!fileFound)
		    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
//    	super.service(req, resp);
    }
1099594
@Override
  public final void service (@Nonnull final ServletRequest req,
                             @Nonnull final ServletResponse res) throws ServletException, IOException
  {
    super.service (req, res);
  }
717980
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        WebAppServletInvocationEvent evt = null;
        if (notifyInvocationListeners) {
            evt = new WebAppServletInvocationEvent(this, getServletContext(), getServletName(), servletConfig.getClassName(), req, res); // 263020
        }

        service(req, res, evt);
    }
410213
public void service(ServletRequest req, ServletResponse res) throws ServletException,
            IOException
    {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        if ("CONNECT".equalsIgnoreCase(request.getMethod()))
        {
            handleConnect(request,response);
        }
        else
        {
            String uri=request.getRequestURI();
            if (request.getQueryString()!=null)
                uri+="?"+request.getQueryString();
            URL url = new URL(request.getScheme(),
                    		  request.getServerName(),
                    		  request.getServerPort(),
                    		  uri);
            
            context.log("URL="+url);

            URLConnection connection = url.openConnection();
            connection.setAllowUserInteraction(false);
            
            // Set method
            HttpURLConnection http = null;
            if (connection instanceof HttpURLConnection)
            {
                http = (HttpURLConnection)connection;
                http.setRequestMethod(request.getMethod());
                http.setInstanceFollowRedirects(false);
            }

            // check connection header
            String connectionHdr = request.getHeader("Connection");
            if (connectionHdr!=null)
            {
                connectionHdr=connectionHdr.toLowerCase();
                if (connectionHdr.equals("keep-alive")||
                    connectionHdr.equals("close"))
                    connectionHdr=null;
            }
            
            // copy headers
            boolean xForwardedFor=false;
            boolean hasContent=false;
            Enumeration enm = request.getHeaderNames();
            while (enm.hasMoreElements())
            {
                // TODO could be better than this!
                String hdr=(String)enm.nextElement();
                String lhdr=hdr.toLowerCase();

                if (_DontProxyHeaders.contains(lhdr))
                    continue;
                if (connectionHdr!=null && connectionHdr.indexOf(lhdr)>=0)
                    continue;

                if ("content-type".equals(lhdr))
                    hasContent=true;

                Enumeration vals = request.getHeaders(hdr);
                while (vals.hasMoreElements())
                {
                    String val = (String)vals.nextElement();
                    if (val!=null)
                    {
                        connection.addRequestProperty(hdr,val);
                        context.log("req "+hdr+": "+val);
                        xForwardedFor|="X-Forwarded-For".equalsIgnoreCase(hdr);
                    }
                }
            }

            // Proxy headers
            connection.setRequestProperty("Via","1.1 (jetty)");
            if (!xForwardedFor)
                connection.addRequestProperty("X-Forwarded-For",
                                              request.getRemoteAddr());

            // a little bit of cache control
            String cache_control = request.getHeader("Cache-Control");
            if (cache_control!=null &&
                (cache_control.indexOf("no-cache")>=0 ||
                 cache_control.indexOf("no-store")>=0))
                connection.setUseCaches(false);

            // customize Connection
            
            try
            {    
                connection.setDoInput(true);
                
                // do input thang!
                InputStream in=request.getInputStream();
                if (hasContent)
                {
                    connection.setDoOutput(true);
                    IO.copy(in,connection.getOutputStream());
                }
                
                // Connect
                connection.connect();    
            }
            catch (Exception e)
            {
                context.log("proxy",e);
            }
            
            InputStream proxy_in = null;

            // handler status codes etc.
            int code=500;
            if (http!=null)
            {
                proxy_in = http.getErrorStream();
                
                code=http.getResponseCode();
                response.setStatus(code,http.getResponseMessage());
                context.log("response = "+http.getResponseCode());
            }
            
            if (proxy_in==null)
            {
                try {proxy_in=connection.getInputStream();}
                catch (Exception e)
                {
                    context.log("stream",e);
                    proxy_in = http.getErrorStream();
                }
            }
            
            // clear response defaults.
            response.setHeader("Date",null);
            response.setHeader("Server",null);
            
            // set response headers
            int h=0;
            String hdr=connection.getHeaderFieldKey(h);
            String val=connection.getHeaderField(h);
            while(hdr!=null || val!=null)
            {
                String lhdr = hdr!=null?hdr.toLowerCase():null;
                if (hdr!=null && val!=null && !_DontProxyHeaders.contains(lhdr))
                    response.addHeader(hdr,val);

                context.log("res "+hdr+": "+val);
                
                h++;
                hdr=connection.getHeaderFieldKey(h);
                val=connection.getHeaderField(h);
            }
            response.addHeader("Via","1.1 (jetty)");

            // Handle
            if (proxy_in!=null)
                IO.copy(proxy_in,response.getOutputStream());
            
        }
    }
249283
protected void executeScript(URL scriptUrl) {
        log.debug("Executing script '{}'", scriptUrl);
        final Jedis jedis = pool.getResource();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(scriptUrl.openStream(), StandardCharsets.UTF_8))) {
            reader.lines()
                    .filter(line -> !Strings.isNullOrEmpty(line) && line.charAt(0) != '#' && !line.startsWith("//"))
                    .forEach(line -> {
                        try {
                            log.trace("execute: {}", line);
                            String[] args = line.split(" ", 3);
                            String command = null;
                            if (args.length == 1) {
                                command = String.format("return redis.call('%s')", args[0]);
                            } else if (args.length == 2) {
                                command = String.format("return redis.call('%s', '%s')", args[0], args[1]);
                            } else if (args.length == 3) {
                                command = String.format("return redis.call('%s', '%s', '%s')", args[0], args[1], unwrapQuotes(args[2]));
                            } else {
                                log.error("Unexpected number of script arguments {}", args.length);
                            }
                            log.trace("command: {}", command);
                            Object result = jedis.eval(command);
                        } catch (Exception e) {
                            log.error("Failed to execute '{}'", line, e);
                        }
                    });
        } catch (IOException e) {
            log.error("Failed to execute script '{}'", scriptUrl, e);
            pool.returnBrokenResource(jedis);
//            jedis = null;
        } finally {
            if (jedis != null) {
                pool.returnResource(jedis);
            }
        }
    }
184046
@Deprecated
  public static void loadScript(String url, String id) {
    GQuery gs = GQuery.$(DOM.createElement("script"));
    GQuery gp = GQuery.$("#" + id).parent();
    if (gp.size() != 1) {
      gp = GQuery.$(GQuery.document.getBody());
    }
    GQuery.$("#" + id).remove();
    gp.append(gs.attr("src", url).attr("type", "text/javascript").attr("id", id));
  }
1120301
@Bean
  public JobFactory<ScriptJobExecution> scriptJobFactory() {
    return new JobFactory<ScriptJobExecution>() {
      @Override
      public Job<ScriptResult> createJob(ScriptJobExecution scriptJobExecution) {
        final String name = scriptJobExecution.getName();
        final String parameterString = scriptJobExecution.getParameters();
        return progress -> {
          Map<String, Object> params = new HashMap<>();
          params.putAll(gson.fromJson(parameterString, MAP_TOKEN));
          params.put("scriptJobExecutionId", scriptJobExecution.getIdValue());
          ScriptResult scriptResult = savedScriptRunner.runScript(name, params);
          if (scriptResult.getOutputFile() != null) {
            scriptJobExecution.setResultUrl(
                format("/files/%s", scriptResult.getOutputFile().getId()));
          }
          progress.status(format("Script output:%n%s", scriptResult.getOutput()));
          return scriptResult;
        };
      }
    };
  }
7963
@Override
    public void service(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException
    {
    	String sourceFileName = req.getParameter("source");
    	String styleSheetFileName = req.getParameter("stylesheet");
    	FileReader sourceFileReader = new FileReader(sourceFileName);
    	FileReader stylesheetFileReader = new FileReader(styleSheetFileName);
    	
    	ServletOutputStream outStream = res.getOutputStream();
    	
        try {
            StreamSource source = new StreamSource(sourceFileReader);

            Result result = new StreamResult(outStream);

            TransformerFactory tFact = TransformerFactory.newInstance();
            StreamSource streamTransformer = new StreamSource(stylesheetFileReader);
            
            Transformer transformer = tFact.newTransformer(streamTransformer);

            transformer.transform(source, result);
        } catch (TransformerConfigurationException ex)    {
            ex.printStackTrace();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }                    
    	
    	super.service(req, res);
    }
1341280
public void setPreUninstallScript( final String script) {
        setPreUninstallProgram(readProgram(script));
        if ( script != null) format.getHeader().createEntry( PREUNSCRIPT, script);
	}
510870
protected String determineThemeNameToChoose(final HttpServletRequest request,
                                                final Service service,
                                                final RegisteredService rService) {
        HttpResponse response = null;
        try {
            LOGGER.debug("Service [{}] is configured to use a custom theme [{}]", rService, rService.getTheme());

            val resource = ResourceUtils.getRawResourceFrom(rService.getTheme());
            if (resource instanceof FileSystemResource && resource.exists()) {
                LOGGER.debug("Executing groovy script to determine theme for [{}]", service.getId());
                val result = ScriptingUtils.executeGroovyScript(resource, new Object[]{service, rService,
                    request.getQueryString(), HttpRequestUtils.getRequestHeaders(request), LOGGER}, String.class, true);
                return StringUtils.defaultIfBlank(result, getDefaultThemeName());
            }
            if (resource instanceof UrlResource) {
                val url = resource.getURL().toExternalForm();
                LOGGER.debug("Executing URL [{}] to determine theme for [{}]", url, service.getId());
                response = HttpUtils.executeGet(url, CollectionUtils.wrap("service", service.getId()));
                if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    val result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
                    return StringUtils.defaultIfBlank(result, getDefaultThemeName());
                }
            }

            val messageSource = new CasThemeResourceBundleMessageSource();
            messageSource.setBasename(rService.getTheme());
            if (messageSource.doGetBundle(rService.getTheme(), request.getLocale()) != null) {
                LOGGER.trace("Found custom theme [{}] for service [{}]", rService.getTheme(), rService);
                return rService.getTheme();
            }
            LOGGER.warn("Custom theme [{}] for service [{}] cannot be located. Falling back to default theme...", rService.getTheme(), rService);
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            HttpUtils.close(response);
        }
        return getDefaultThemeName();
    }