id
stringlengths
27
31
content
stringlengths
14
287k
max_stars_repo_path
stringlengths
52
57
crossvul-java_data_good_4174_1
package org.mapfish.print.servlet; import net.sf.jasperreports.engine.fonts.FontFamily; import net.sf.jasperreports.extensions.ExtensionsEnvironment; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.jfree.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONWriter; import org.mapfish.print.Constants; import org.mapfish.print.ExceptionUtils; import org.mapfish.print.MapPrinter; import org.mapfish.print.MapPrinterFactory; import org.mapfish.print.config.Configuration; import org.mapfish.print.config.Template; import org.mapfish.print.processor.Processor; import org.mapfish.print.processor.http.matcher.UriMatchers; import org.mapfish.print.servlet.job.JobManager; import org.mapfish.print.servlet.job.NoSuchReferenceException; import org.mapfish.print.servlet.job.PrintJobStatus; import org.mapfish.print.servlet.job.impl.PrintJobEntryImpl; import org.mapfish.print.servlet.job.impl.ThreadPoolJobManager; import org.mapfish.print.servlet.job.loader.ReportLoader; import org.mapfish.print.url.data.Handler; import org.mapfish.print.wrapper.json.PJsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.MalformedURLException; import java.net.SocketException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.UnknownHostException; import java.nio.file.Files; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static org.mapfish.print.servlet.ServletMapPrinterFactory.DEFAULT_CONFIGURATION_FILE_KEY; /** * The default servlet. */ @Controller public class MapPrinterServlet extends BaseMapServlet { /** * The url path for capabilities requests. */ public static final String CAPABILITIES_URL = "/capabilities.json"; /** * The url path to list all registered configurations. */ public static final String LIST_APPS_URL = "/apps.json"; /** * The url path to get a sample print request. */ public static final String EXAMPLE_REQUEST_URL = "/exampleRequest.json"; /** * The url path to create and get a report. */ public static final String CREATE_AND_GET_URL = "/buildreport"; /** * The url path to get the status for a print task. */ public static final String STATUS_URL = "/status"; /** * The url path to cancel a print task. */ public static final String CANCEL_URL = "/cancel"; /** * The url path to create a print task and to get a finished print. */ public static final String REPORT_URL = "/report"; /** * The url path to get the list of fonts available to geotools. */ public static final String FONTS_URL = "/fonts"; /** * The key containing an error message for failed jobs. */ public static final String JSON_ERROR = "error"; /** * The application ID which indicates the configuration file to load. */ public static final String JSON_APP = "app"; /* Registry keys */ /** * If the job is done (value is true) or not (value is false). * * Part of the {@link #getStatus(String, javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse)} response. */ public static final String JSON_DONE = "done"; /** * The status of the job. One of the following values: * <ul> * <li>waiting</li> * <li>running</li> * <li>finished</li> * <li>cancelled</li> * <li>error</li> * </ul> * Part of the {@link #getStatus(String, javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse)} response */ public static final String JSON_STATUS = "status"; /** * The elapsed time in ms from the point the job started. If the job is finished, this is the duration it * took to process the job. * * Part of the {@link #getStatus(String, javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse)} response. */ public static final String JSON_ELAPSED_TIME = "elapsedTime"; /** * A rough estimate for the time in ms the job still has to wait in the queue until it starts processing. * * Part of the {@link #getStatus(String, javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse)} response. */ public static final String JSON_WAITING_TIME = "waitingTime"; /** * The key containing the print job reference ID in the create report response. */ public static final String JSON_PRINT_JOB_REF = "ref"; /** * The json key in the create report response containing a link to get the status of the print job. */ public static final String JSON_STATUS_LINK = "statusURL"; /** * The json key in the create report and status responses containing a link to download the report. */ public static final String JSON_DOWNLOAD_LINK = "downloadURL"; /** * The JSON key in the request spec that contains the outputFormat. This value will be put into the spec * by the servlet. there is not need for the post to do this. */ public static final String JSON_OUTPUT_FORMAT = "outputFormat"; /** * The json tag referring to the attributes. */ public static final String JSON_ATTRIBUTES = "attributes"; /** * The json property to add the request headers from the print request. * <p> * The request headers from the print request are needed by certain processors, the headers are added to * the request JSON data for those processors. */ public static final String JSON_REQUEST_HEADERS = "requestHeaders"; private static final Logger LOGGER = LoggerFactory.getLogger(MapPrinterServlet.class); private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\$\\{(\\S+)}"); private static final int JSON_INDENT_FACTOR = 4; private static final List<String> REQUEST_ID_HEADERS = Arrays.asList( "X-Request-ID", "X-Correlation-ID", "Request-ID", "X-Varnish", "X-Amzn-Trace-Id" ); static { Handler.configureProtocolHandler(); } private final JobManager jobManager; private final List<ReportLoader> reportLoaders; private final MapPrinterFactory printerFactory; private final ApplicationContext context; private final ServletInfo servletInfo; private final MapPrinterFactory mapPrinterFactory; private long maxCreateAndGetWaitTimeInSeconds = ThreadPoolJobManager.DEFAULT_TIMEOUT_IN_SECONDS; @Autowired public MapPrinterServlet( final JobManager jobManager, final List<ReportLoader> reportLoaders, final MapPrinterFactory printerFactory, final ApplicationContext context, final ServletInfo servletInfo, final MapPrinterFactory mapPrinterFactory) { this.jobManager = jobManager; this.reportLoaders = reportLoaders; this.printerFactory = printerFactory; this.context = context; this.servletInfo = servletInfo; this.mapPrinterFactory = mapPrinterFactory; } /** * Parse the print request json data. * * @param requestDataRaw the request json in string form * @param httpServletResponse the response object to use for returning errors if needed */ private static PJsonObject parseJson( final String requestDataRaw, final HttpServletResponse httpServletResponse) { try { if (requestDataRaw == null) { error(httpServletResponse, "Missing post data. The post payload must either be a form post with a spec " + "parameter or " + "must be a raw json post with the request.", HttpStatus.INTERNAL_SERVER_ERROR); return null; } String requestData = requestDataRaw; if (!requestData.startsWith("spec=") && !requestData.startsWith("{")) { try { requestData = URLDecoder.decode(requestData, Constants.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw ExceptionUtils.getRuntimeException(e); } } if (requestData.startsWith("spec=")) { requestData = requestData.substring("spec=".length()); } try { return MapPrinter.parseSpec(requestData); } catch (RuntimeException e) { try { return MapPrinter.parseSpec(URLDecoder.decode(requestData, Constants.DEFAULT_ENCODING)); } catch (UnsupportedEncodingException uee) { throw ExceptionUtils.getRuntimeException(e); } } } catch (RuntimeException e) { LOGGER.warn("Error parsing request data: {}", requestDataRaw); throw e; } } /** * If the request contains a header that specifies a request ID, add it to the ref. The ref shows up in * every logs, that way, we can trace the request ID across applications. */ private static String maybeAddRequestId(final String ref, final HttpServletRequest request) { final Optional<String> headerName = REQUEST_ID_HEADERS.stream().filter(h -> request.getHeader(h) != null).findFirst(); return headerName.map( s -> ref + "@" + request.getHeader(s).replaceAll("[^a-zA-Z0-9._:-]", "_") ).orElse(ref); } /** * Get a status report on a job. Returns the following json: * * <pre><code> * {"time":0,"count":0,"done":false} * </code></pre> * * @param appId the app ID * @param referenceId the job reference * @param statusRequest the request object * @param statusResponse the response object */ @RequestMapping(value = "/{appId}" + STATUS_URL + "/{referenceId:\\S+}.json", method = RequestMethod.GET) public final void getStatusSpecificAppId( @SuppressWarnings("unused") @PathVariable final String appId, @PathVariable final String referenceId, final HttpServletRequest statusRequest, final HttpServletResponse statusResponse) { getStatus(referenceId, statusRequest, statusResponse); } /** * Get a status report on a job. Returns the following json: * * <pre><code> * {"time":0,"count":0,"done":false} * </code></pre> * * @param referenceId the job reference * @param statusRequest the request object * @param statusResponse the response object */ @RequestMapping(value = STATUS_URL + "/{referenceId:\\S+}.json", method = RequestMethod.GET) public final void getStatus( @PathVariable final String referenceId, final HttpServletRequest statusRequest, final HttpServletResponse statusResponse) { MDC.put(Processor.MDC_JOB_ID_KEY, referenceId); setNoCache(statusResponse); try { PrintJobStatus status = this.jobManager.getStatus(referenceId); setContentType(statusResponse); try (PrintWriter writer = statusResponse.getWriter()) { JSONWriter json = new JSONWriter(writer); json.object(); { json.key(JSON_DONE).value(status.isDone()); json.key(JSON_STATUS).value(status.getStatus().toString().toLowerCase()); json.key(JSON_ELAPSED_TIME).value(status.getElapsedTime()); json.key(JSON_WAITING_TIME).value(status.getWaitingTime()); if (!StringUtils.isEmpty(status.getError())) { json.key(JSON_ERROR).value(status.getError()); } addDownloadLinkToJson(statusRequest, referenceId, json); } json.endObject(); } } catch (JSONException | IOException e) { throw ExceptionUtils.getRuntimeException(e); } catch (NoSuchReferenceException e) { error(statusResponse, e.getMessage(), HttpStatus.NOT_FOUND); } } /** * Cancel a job. * <p> * Even if a job was already finished, subsequent status requests will return that the job was canceled. * * @param appId the app ID * @param referenceId the job reference * @param statusResponse the response object */ @RequestMapping(value = "/{appId}" + CANCEL_URL + "/{referenceId:\\S+}", method = RequestMethod.DELETE) public final void cancelSpecificAppId( @SuppressWarnings("unused") @PathVariable final String appId, @PathVariable final String referenceId, final HttpServletResponse statusResponse) { cancel(referenceId, statusResponse); } /** * Cancel a job. * <p> * Even if a job was already finished, subsequent status requests will return that the job was canceled. * * @param referenceId the job reference * @param statusResponse the response object */ @RequestMapping(value = CANCEL_URL + "/{referenceId:\\S+}", method = RequestMethod.DELETE) public final void cancel( @PathVariable final String referenceId, final HttpServletResponse statusResponse) { MDC.put(Processor.MDC_JOB_ID_KEY, referenceId); setNoCache(statusResponse); try { this.jobManager.cancel(referenceId); } catch (NoSuchReferenceException e) { error(statusResponse, e.getMessage(), HttpStatus.NOT_FOUND); } } /** * Add the print job to the job queue. * * @param appId the id of the app to get the request for. * @param format the format of the returned report * @param requestData a json formatted string with the request data required to perform the report * generation. * @param createReportRequest the request object * @param createReportResponse the response object */ @RequestMapping(value = "/{appId}" + REPORT_URL + ".{format:\\w+}", method = RequestMethod.POST) public final void createReport( @PathVariable final String appId, @PathVariable final String format, @RequestBody final String requestData, final HttpServletRequest createReportRequest, final HttpServletResponse createReportResponse) throws NoSuchAppException { setNoCache(createReportResponse); String ref = createAndSubmitPrintJob(appId, format, requestData, createReportRequest, createReportResponse); if (ref == null) { error(createReportResponse, "Failed to create a print job", HttpStatus.INTERNAL_SERVER_ERROR); return; } createReportResponse.setContentType("application/json; charset=utf-8"); try (PrintWriter writer = createReportResponse.getWriter()) { JSONWriter json = new JSONWriter(writer); json.object(); { json.key(JSON_PRINT_JOB_REF).value(ref); String statusURL = getBaseUrl(createReportRequest) + STATUS_URL + "/" + ref + ".json"; json.key(JSON_STATUS_LINK).value(statusURL); addDownloadLinkToJson(createReportRequest, ref, json); } json.endObject(); } catch (JSONException | IOException e) { LOGGER.warn("Error generating the JSON response", e); } } /** * To get the PDF created previously. * * @param appId the app ID * @param referenceId the path to the file. * @param inline whether or not to inline the * @param getReportResponse the response object */ @RequestMapping(value = "/{appId}" + REPORT_URL + "/{referenceId:\\S+}", method = RequestMethod.GET) public final void getReportSpecificAppId( @SuppressWarnings("unused") @PathVariable final String appId, @PathVariable final String referenceId, @RequestParam(value = "inline", defaultValue = "false") final boolean inline, final HttpServletResponse getReportResponse) throws IOException, ServletException { getReport(referenceId, inline, getReportResponse); } /** * To get the PDF created previously. * * @param referenceId the path to the file. * @param inline whether or not to inline the * @param getReportResponse the response object */ @RequestMapping(value = REPORT_URL + "/{referenceId:\\S+}", method = RequestMethod.GET) public final void getReport( @PathVariable final String referenceId, @RequestParam(value = "inline", defaultValue = "false") final boolean inline, final HttpServletResponse getReportResponse) throws IOException, ServletException { MDC.put(Processor.MDC_JOB_ID_KEY, referenceId); setNoCache(getReportResponse); loadReport(referenceId, getReportResponse, new HandleReportLoadResult<Void>() { @Override public Void unknownReference( final HttpServletResponse httpServletResponse, final String referenceId) { error(httpServletResponse, "Error getting print with ref=" + referenceId + ": unknown reference", HttpStatus.NOT_FOUND); return null; } @Override public Void unsupportedLoader( final HttpServletResponse httpServletResponse, final String referenceId) { error(httpServletResponse, "Error getting print with ref=" + referenceId + " can not be loaded", HttpStatus.NOT_FOUND); return null; } @Override public Void successfulPrint( final PrintJobStatus successfulPrintResult, final HttpServletResponse httpServletResponse, final URI reportURI, final ReportLoader loader) throws IOException { sendReportFile(successfulPrintResult, httpServletResponse, loader, reportURI, inline); return null; } @Override public Void failedPrint( final PrintJobStatus failedPrintJob, final HttpServletResponse httpServletResponse) { error(httpServletResponse, failedPrintJob.getError(), HttpStatus.INTERNAL_SERVER_ERROR); return null; } @Override public Void printJobPending( final HttpServletResponse httpServletResponse, final String referenceId) { error(httpServletResponse, "Report has not yet completed processing", HttpStatus.ACCEPTED); return null; } }); } /** * Add the print job to the job queue. * * @param format the format of the returned report * @param requestData a json formatted string with the request data required to perform the report * generation. * @param createReportRequest the request object * @param createReportResponse the response object */ @RequestMapping(value = REPORT_URL + ".{format:\\w+}", method = RequestMethod.POST) public final void createReport( @PathVariable final String format, @RequestBody final String requestData, final HttpServletRequest createReportRequest, final HttpServletResponse createReportResponse) throws NoSuchAppException { setNoCache(createReportResponse); PJsonObject spec = parseJson(requestData, createReportResponse); if (spec == null) { return; } final String appId = spec.optString(JSON_APP, DEFAULT_CONFIGURATION_FILE_KEY); createReport(appId, format, requestData, createReportRequest, createReportResponse); } /** * add the print job to the job queue. * * @param appId the id of the app to get the request for. * @param format the format of the returned report * @param requestData a json formatted string with the request data required to perform the report * generation. * @param inline whether or not to inline the content * @param createReportRequest the request object * @param createReportResponse the response object */ @RequestMapping(value = "/{appId}" + CREATE_AND_GET_URL + ".{format:\\w+}", method = RequestMethod.POST) public final void createReportAndGet( @PathVariable final String appId, @PathVariable final String format, @RequestBody final String requestData, @RequestParam(value = "inline", defaultValue = "false") final boolean inline, final HttpServletRequest createReportRequest, final HttpServletResponse createReportResponse) throws IOException, ServletException, InterruptedException, NoSuchAppException { setNoCache(createReportResponse); String ref = createAndSubmitPrintJob(appId, format, requestData, createReportRequest, createReportResponse); if (ref == null) { error(createReportResponse, "Failed to create a print job", HttpStatus.INTERNAL_SERVER_ERROR); return; } final HandleReportLoadResult<Boolean> handler = new HandleReportLoadResult<Boolean>() { @Override public Boolean unknownReference( final HttpServletResponse httpServletResponse, final String referenceId) { error(httpServletResponse, "Print with ref=" + referenceId + " unknown", HttpStatus.NOT_FOUND); return true; } @Override public Boolean unsupportedLoader( final HttpServletResponse httpServletResponse, final String referenceId) { error(httpServletResponse, "Print with ref=" + referenceId + " can not be loaded", HttpStatus.NOT_FOUND); return true; } @Override public Boolean successfulPrint( final PrintJobStatus successfulPrintResult, final HttpServletResponse httpServletResponse, final URI reportURI, final ReportLoader loader) throws IOException { sendReportFile(successfulPrintResult, httpServletResponse, loader, reportURI, inline); return true; } @Override public Boolean failedPrint( final PrintJobStatus failedPrintJob, final HttpServletResponse httpServletResponse) { error(httpServletResponse, failedPrintJob.getError(), HttpStatus.INTERNAL_SERVER_ERROR); return true; } @Override public Boolean printJobPending( final HttpServletResponse httpServletResponse, final String referenceId) { return false; } }; boolean isDone = false; long startWaitTime = System.currentTimeMillis(); final long maxWaitTimeInMillis = TimeUnit.SECONDS.toMillis(this.maxCreateAndGetWaitTimeInSeconds); while (!isDone && System.currentTimeMillis() - startWaitTime < maxWaitTimeInMillis) { Thread.sleep(TimeUnit.SECONDS.toMillis(1)); isDone = loadReport(ref, createReportResponse, handler); } } /** * add the print job to the job queue. * * @param format the format of the returned report * @param requestData a json formatted string with the request data required to perform the report * generation. * @param inline whether or not to inline the content * @param createReportRequest the request object * @param createReportResponse the response object */ @RequestMapping(value = CREATE_AND_GET_URL + ".{format:\\w+}", method = RequestMethod.POST) public final void createReportAndGetNoAppId( @PathVariable final String format, @RequestBody final String requestData, @RequestParam(value = "inline", defaultValue = "false") final boolean inline, final HttpServletRequest createReportRequest, final HttpServletResponse createReportResponse) throws IOException, ServletException, InterruptedException, NoSuchAppException { setNoCache(createReportResponse); PJsonObject spec = parseJson(requestData, createReportResponse); if (spec == null) { return; } String appId = spec.optString(JSON_APP, DEFAULT_CONFIGURATION_FILE_KEY); createReportAndGet(appId, format, requestData, inline, createReportRequest, createReportResponse); } /** * To get (in JSON) the information about the available formats and CO. * * @param listAppsResponse the response object */ @RequestMapping(value = LIST_APPS_URL, method = RequestMethod.GET) public final void listAppIds( final HttpServletResponse listAppsResponse) throws ServletException, IOException { MDC.remove(Processor.MDC_JOB_ID_KEY); setCache(listAppsResponse); Set<String> appIds = this.printerFactory.getAppIds(); setContentType(listAppsResponse); try (PrintWriter writer = listAppsResponse.getWriter()) { JSONWriter json = new JSONWriter(writer); try { json.array(); for (String appId: appIds) { json.value(appId); } json.endArray(); } catch (JSONException e) { throw new ServletException(e); } } } /** * To get (in JSON) the information about the available formats and CO. * * @param pretty if true then pretty print the capabilities * @param request the request * @param capabilitiesResponse the response object */ @RequestMapping(value = CAPABILITIES_URL, method = RequestMethod.GET) public final void getCapabilities( @RequestParam(value = "pretty", defaultValue = "false") final boolean pretty, final HttpServletRequest request, final HttpServletResponse capabilitiesResponse) throws ServletException, IOException { getCapabilities(DEFAULT_CONFIGURATION_FILE_KEY, pretty, request, capabilitiesResponse); } /** * To get (in JSON) the information about the available formats and CO. * * @param appId the name of the "app" or in other words, a mapping to the configuration file for * this request. * @param pretty if true then pretty print the capabilities * @param request the request * @param capabilitiesResponse the response object */ @RequestMapping(value = "/{appId}" + CAPABILITIES_URL, method = RequestMethod.GET) public final void getCapabilities( @PathVariable final String appId, @RequestParam(value = "pretty", defaultValue = "false") final boolean pretty, final HttpServletRequest request, final HttpServletResponse capabilitiesResponse) throws ServletException, IOException { MDC.remove(Processor.MDC_JOB_ID_KEY); setCache(capabilitiesResponse); MapPrinter printer; try { printer = this.printerFactory.create(appId); if (!checkReferer(request, printer)) { error(capabilitiesResponse, "Invalid referer", HttpStatus.FORBIDDEN); return; } } catch (NoSuchAppException e) { error(capabilitiesResponse, e.getMessage(), HttpStatus.NOT_FOUND); return; } setContentType(capabilitiesResponse); final ByteArrayOutputStream prettyPrintBuffer = new ByteArrayOutputStream(); try (Writer writer = pretty ? new OutputStreamWriter(prettyPrintBuffer, Constants.DEFAULT_CHARSET) : capabilitiesResponse.getWriter()) { JSONWriter json = new JSONWriter(writer); try { json.object(); { json.key(JSON_APP).value(appId); printer.printClientConfig(json); } { json.key("formats"); Set<String> formats = printer.getOutputFormatsNames(); json.array(); for (String format: formats) { json.value(format); } json.endArray(); } json.endObject(); } catch (JSONException e) { throw new ServletException(e); } } if (pretty) { final JSONObject jsonObject = new JSONObject(new String(prettyPrintBuffer.toByteArray(), Constants.DEFAULT_CHARSET)); capabilitiesResponse.getOutputStream().print(jsonObject.toString(JSON_INDENT_FACTOR)); } } /** * Get a sample request for the app. An empty response may be returned if there is not example request. * * @param request the request object * @param getExampleResponse the response object */ @RequestMapping(value = EXAMPLE_REQUEST_URL, method = RequestMethod.GET) public final void getExampleRequest( final HttpServletRequest request, final HttpServletResponse getExampleResponse) throws IOException { getExampleRequest(DEFAULT_CONFIGURATION_FILE_KEY, request, getExampleResponse); } /** * Get a sample request for the app. An empty response may be returned if there is not example request. * * @param appId the id of the app to get the request for. * @param request the request object * @param getExampleResponse the response object */ @RequestMapping(value = "{appId}" + EXAMPLE_REQUEST_URL, method = RequestMethod.GET) public final void getExampleRequest( @PathVariable final String appId, final HttpServletRequest request, final HttpServletResponse getExampleResponse) throws IOException { MDC.remove(Processor.MDC_JOB_ID_KEY); setCache(getExampleResponse); try { final MapPrinter mapPrinter = this.printerFactory.create(appId); if (!checkReferer(request, mapPrinter)) { error(getExampleResponse, "Invalid referer", HttpStatus.FORBIDDEN); return; } final String requestDataPrefix = "requestData"; final File[] children = mapPrinter.getConfiguration().getDirectory().listFiles( (dir, name) -> name.startsWith(requestDataPrefix) && name.endsWith(".json")); if (children == null) { error(getExampleResponse, "Cannot find the config directory", HttpStatus.NOT_FOUND); return; } JSONObject allExamples = new JSONObject(); for (File child: children) { if (child.isFile()) { String requestData = new String(Files.readAllBytes(child.toPath()), Constants.DEFAULT_CHARSET); try { final JSONObject jsonObject = new JSONObject(requestData); jsonObject.remove(JSON_OUTPUT_FORMAT); jsonObject.remove(JSON_APP); requestData = jsonObject.toString(JSON_INDENT_FACTOR); setContentType(getExampleResponse); } catch (JSONException e) { // ignore, return raw text } String name = child.getName(); name = name.substring(requestDataPrefix.length()); if (name.startsWith("-")) { name = name.substring(1); } name = FilenameUtils.removeExtension(name); name = name.trim(); if (name.isEmpty()) { name = FilenameUtils.removeExtension(child.getName()); } try { allExamples.put(name, requestData); } catch (JSONException e) { Log.error("Error translating object to json", e); error(getExampleResponse, "Error translating object to json: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); return; } } } final String result; try { result = allExamples.toString(JSON_INDENT_FACTOR); } catch (JSONException e) { Log.error("Error translating object to json", e); error(getExampleResponse, "Error translating object to json: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); return; } try (PrintWriter writer = getExampleResponse.getWriter()) { writer.append(result); } } catch (NoSuchAppException e) { error(getExampleResponse, "No print app identified by: " + appId, HttpStatus.NOT_FOUND); } } /** * List the available fonts on the system. * * @return the list of available fonts in the system. The result is a JSON Array that just lists the font * family names available. */ @RequestMapping(value = FONTS_URL) @ResponseBody public final String listAvailableFonts() { MDC.remove(Processor.MDC_JOB_ID_KEY); final JSONArray availableFonts = new JSONArray(); final List<FontFamily> families = ExtensionsEnvironment.getExtensionsRegistry().getExtensions(FontFamily.class); for (FontFamily family: families) { availableFonts.put(family.getName()); } return availableFonts.toString(); } /** * Maximum time to wait for a createAndGet request to complete before returning an error. * * @param maxCreateAndGetWaitTimeInSeconds the maximum time in seconds to wait for a report to be * generated. */ public final void setMaxCreateAndGetWaitTimeInSeconds(final long maxCreateAndGetWaitTimeInSeconds) { this.maxCreateAndGetWaitTimeInSeconds = maxCreateAndGetWaitTimeInSeconds; } /** * Copy the PDF into the output stream. * * @param metadata the client request data * @param httpServletResponse the response object * @param reportLoader the object used for loading the report * @param reportURI the uri of the report * @param inline whether or not to inline the content */ private void sendReportFile( final PrintJobStatus metadata, final HttpServletResponse httpServletResponse, final ReportLoader reportLoader, final URI reportURI, final boolean inline) throws IOException { try (OutputStream response = httpServletResponse.getOutputStream()) { httpServletResponse.setContentType(metadata.getResult().getMimeType()); if (!inline) { String fileName = metadata.getResult().getFileName(); Matcher matcher = VARIABLE_PATTERN.matcher(fileName); while (matcher.find()) { final String variable = matcher.group(1); String replacement = findReplacement(variable, metadata.getCompletionDate()); fileName = fileName.replace("${" + variable + "}", replacement); matcher = VARIABLE_PATTERN.matcher(fileName); } fileName += "." + metadata.getResult().getFileExtension(); httpServletResponse .setHeader("Content-disposition", "attachment; filename=" + cleanUpName(fileName)); } reportLoader.loadReport(reportURI, response); } } private void addDownloadLinkToJson( final HttpServletRequest httpServletRequest, final String ref, final JSONWriter json) { String downloadURL = getBaseUrl(httpServletRequest) + REPORT_URL + "/" + ref; json.key(JSON_DOWNLOAD_LINK).value(downloadURL); } /** * Read the headers from the request. * * @param httpServletRequest the request object */ protected final JSONObject getHeaders(final HttpServletRequest httpServletRequest) { @SuppressWarnings("rawtypes") Enumeration headersName = httpServletRequest.getHeaderNames(); JSONObject headers = new JSONObject(); while (headersName.hasMoreElements()) { String name = headersName.nextElement().toString(); Enumeration<String> e = httpServletRequest.getHeaders(name); while (e.hasMoreElements()) { headers.append(name, e.nextElement()); } } final JSONObject requestHeadersAttribute = new JSONObject(); requestHeadersAttribute.put(JSON_REQUEST_HEADERS, headers); return requestHeadersAttribute; } /** * Start a print job. * * @param appId the id of the printer app * @param format the format of the returned report. * @param requestDataRaw the request json in string form * @param httpServletRequest the request object * @param httpServletResponse the response object * @return the job reference id */ private String createAndSubmitPrintJob( final String appId, final String format, final String requestDataRaw, final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws NoSuchAppException { PJsonObject specJson = parseJson(requestDataRaw, httpServletResponse); if (specJson == null) { return null; } String ref = maybeAddRequestId( UUID.randomUUID().toString() + "@" + this.servletInfo.getServletId(), httpServletRequest); MDC.put(Processor.MDC_JOB_ID_KEY, ref); LOGGER.debug("{}", specJson); specJson.getInternalObj().remove(JSON_OUTPUT_FORMAT); specJson.getInternalObj().put(JSON_OUTPUT_FORMAT, format); specJson.getInternalObj().remove(JSON_APP); specJson.getInternalObj().put(JSON_APP, appId); final JSONObject requestHeaders = getHeaders(httpServletRequest); if (requestHeaders.length() > 0) { specJson.getInternalObj().getJSONObject(JSON_ATTRIBUTES) .put(JSON_REQUEST_HEADERS, requestHeaders); } // check that we have authorization and configure the job so it can only be access by users with // sufficient authorization final String templateName = specJson.getString(Constants.JSON_LAYOUT_KEY); final MapPrinter mapPrinter = this.mapPrinterFactory.create(appId); checkReferer(httpServletRequest, mapPrinter); final Template template = mapPrinter.getConfiguration().getTemplate(templateName); if (template == null) { return null; } PrintJobEntryImpl jobEntry = new PrintJobEntryImpl(ref, specJson, System.currentTimeMillis()); jobEntry.configureAccess(template, this.context); try { this.jobManager.submit(jobEntry); } catch (RuntimeException exc) { LOGGER.error("Error when creating job on {}: {}", appId, specJson, exc); ref = null; } return ref; } private boolean checkReferer( final HttpServletRequest request, final MapPrinter mapPrinter) { final Configuration config = mapPrinter.getConfiguration(); final UriMatchers allowedReferers = config.getAllowedReferersImpl(); if (allowedReferers == null) { return true; } String referer = request.getHeader("referer"); if (referer == null) { referer = "http://localhost/"; } try { return allowedReferers.matches(new URI(referer), HttpMethod.resolve(request.getMethod())); } catch (SocketException | UnknownHostException | URISyntaxException | MalformedURLException e) { LOGGER.error("Referer {} invalid", referer, e); return false; } } private <R> R loadReport( final String referenceId, final HttpServletResponse httpServletResponse, final HandleReportLoadResult<R> handler) throws IOException, ServletException { PrintJobStatus metadata; try { metadata = this.jobManager.getStatus(referenceId); } catch (NoSuchReferenceException e) { return handler.unknownReference(httpServletResponse, referenceId); } if (!metadata.isDone()) { return handler.printJobPending(httpServletResponse, referenceId); } else if (metadata.getResult() != null) { URI pdfURI = metadata.getResult().getReportURI(); ReportLoader loader = null; for (ReportLoader reportLoader: this.reportLoaders) { if (reportLoader.accepts(pdfURI)) { loader = reportLoader; break; } } if (loader == null) { return handler.unsupportedLoader(httpServletResponse, referenceId); } else { return handler.successfulPrint(metadata, httpServletResponse, pdfURI, loader); } } else { return handler.failedPrint(metadata, httpServletResponse); } } private void setContentType(final HttpServletResponse statusResponse) { statusResponse.setContentType("application/json; charset=utf-8"); } }
./CrossVul/dataset_final_sorted/CWE-79/java/good_4174_1
crossvul-java_data_good_1166_1
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package com.sun.faces.lifecycle; import java.util.Map; import javax.faces.component.UINamingContainer; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.lifecycle.ClientWindow; import javax.faces.render.ResponseStateManager; public class ClientWindowImpl extends ClientWindow { String id; public ClientWindowImpl() { } @Override public Map<String, String> getQueryURLParameters(FacesContext context) { return null; } @Override public void decode(FacesContext context) { Map<String, String> requestParamMap = context.getExternalContext().getRequestParameterMap(); if (isClientWindowRenderModeEnabled(context)) { id = requestParamMap.get(ResponseStateManager.CLIENT_WINDOW_URL_PARAM); } // The hidden field always takes precedence, if present. if (requestParamMap.containsKey(ResponseStateManager.CLIENT_WINDOW_PARAM)) { id = requestParamMap.get(ResponseStateManager.CLIENT_WINDOW_PARAM); } if (null == id) { id = calculateClientWindow(context); } } private String calculateClientWindow(FacesContext context) { synchronized(context.getExternalContext().getSession(true)) { final String clientWindowCounterKey = "com.sun.faces.lifecycle.ClientWindowCounterKey"; ExternalContext extContext = context.getExternalContext(); Map<String, Object> sessionAttrs = extContext.getSessionMap(); Integer counter = (Integer) sessionAttrs.get(clientWindowCounterKey); if (null == counter) { counter = Integer.valueOf(0); } char sep = UINamingContainer.getSeparatorChar(context); id = extContext.getSessionId(true) + sep + + counter; sessionAttrs.put(clientWindowCounterKey, ++counter); } return id; } @Override public String getId() { return id; } }
./CrossVul/dataset_final_sorted/CWE-79/java/good_1166_1
crossvul-java_data_bad_4516_0
// // $Id$ // From Philippe Le Hegaret (Philippe.Le_Hegaret@sophia.inria.fr) // // (c) COPYRIGHT MIT and INRIA, 1997. // Please first read the full copyright statement in file COPYRIGHT.html package org.w3c.css.css; import org.w3c.css.atrules.css.AtRuleMedia; import org.w3c.css.atrules.css.AtRulePage; import org.w3c.css.parser.AtRule; import org.w3c.css.parser.CssError; import org.w3c.css.parser.CssFouffa; import org.w3c.css.parser.CssParseException; import org.w3c.css.parser.CssSelectors; import org.w3c.css.parser.CssValidatorListener; import org.w3c.css.parser.Errors; import org.w3c.css.parser.analyzer.ParseException; import org.w3c.css.parser.analyzer.TokenMgrError; import org.w3c.css.properties.css.CssProperty; import org.w3c.css.selectors.IdSelector; import org.w3c.css.util.ApplContext; import org.w3c.css.util.CssVersion; import org.w3c.css.util.InvalidParamException; import org.w3c.css.util.Messages; import org.w3c.css.util.Util; import org.w3c.css.util.Warning; import org.w3c.css.util.Warnings; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.net.URL; import java.util.ArrayList; import java.util.StringTokenizer; /** * @version $Revision$ */ public final class StyleSheetParser implements CssValidatorListener, CssParser { private static Constructor co = null; static { try { Class c = java.lang.Exception.class; Class cp[] = {java.lang.Exception.class}; co = c.getDeclaredConstructor(cp); } catch (NoSuchMethodException ex) { co = null; } } CssFouffa cssFouffa; StyleSheet style = new StyleSheet(); public void reInit() { style = new StyleSheet(); } public StyleSheet getStyleSheet() { return style; } public void setWarningLevel(int warningLevel) { style.setWarningLevel(warningLevel); } public void notifyErrors(Errors errors) { style.addErrors(errors); } public void notifyWarnings(Warnings warnings) { style.addWarnings(warnings); } /** * Adds a vector of properties to a selector. * * @param selector the selector * @param properties Properties to associate with contexts */ public void handleRule(ApplContext ac, CssSelectors selector, ArrayList<CssProperty> properties) { if (selector.getAtRule() instanceof AtRulePage) { style.remove(selector); } for (CssProperty property : properties) { property.setSelectors(selector); style.addProperty(selector, property); } } // part added by Sijtsche de Jong public void addCharSet(String charset) { style.addCharSet(charset); } public void newAtRule(AtRule atRule) { style.newAtRule(atRule); } public void endOfAtRule() { style.endOfAtRule(); } public void setImportant(boolean important) { style.setImportant(important); } public void setSelectorList(ArrayList<CssSelectors> selectors) { style.setSelectorList(selectors); } public void setProperty(ArrayList<CssProperty> properties) { style.setProperty(properties); } public void endOfRule() { style.endOfRule(); } public void removeThisRule() { style.removeThisRule(); } public void removeThisAtRule() { style.removeThisAtRule(); } //end of part added by Sijtsche de Jong /** * Handles an at-rule. * <p/> * <p>The parameter <code>value</code> can be : * <DL> * <DT>CssString * <DD>The value coming from a string. * <DT>CssURL * <DD>The value coming from an URL. * <DT>Vector * <DD>The value is a vector of declarations (it contains properties). * This feature is not legal, so be careful. * </DL> * * @param ident The ident for this at-rule (for example: 'font-face') * @param string The string representation if this at-rule */ public void handleAtRule(ApplContext ac, String ident, String string) { style.getWarnings().addWarning(new Warning(cssFouffa.getSourceFile(), cssFouffa.getLine(), "at-rule", 2, new String[]{ident, string}, ac)); //stylesheet.addAtRule(atRule); } /** * @param url the URL containing the style sheet * @param title the title of the stylesheet * @param kind may be a stylesheet or an alternate stylesheet * @param media the media to apply this * @param origin the origin of the style sheet * @throws IOException an IO error */ public void parseURL(ApplContext ac, URL url, String title, String kind, String media, int origin) { boolean doneref = false; URL ref = ac.getReferrer(); setWarningLevel(ac.getWarningLevel()); if (Util.onDebug) { System.err.println("StyleSheet.parseURL(" + url + ", " + title + ", " + kind + ", " + media + ", " + origin + ")"); } if (kind != null) { kind = kind.trim().toLowerCase(); if (!kind.equals("stylesheet") && !kind.equals("alternate stylesheet")) { return; } } try { ac.setOrigin(origin); // if (cssFouffa == null) { cssFouffa = new CssFouffa(ac, url); cssFouffa.addListener(this); // } else { // cssFouffa.ReInit(ac, url); // } // cssFouffa.setResponse(res); // removed plh 2001-03-08 // cssFouffa.setOrigin(origin); // cssFouffa.setDefaultMedium(defaultmedium); // cssFouffa.doConfig(); if (media == null) { if (ac.getCssVersion() != CssVersion.CSS1) { if (ac.getMedium() == null) { media = "all"; } else { media = ac.getMedium(); } } } AtRuleMedia m = AtRuleMedia.getInstance(ac.getCssVersion()); try { if (media != null) { addMedias(m, media, ac); } cssFouffa.setAtRule(m); } catch (org.w3c.css.util.InvalidParamException e) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(url.toString(), -1, e)); notifyErrors(er); return; } ac.setReferrer(url); doneref = true; cssFouffa.parseStyle(); } catch (Exception e) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(Messages.escapeString(url.toString()), -1, e)); notifyErrors(er); } finally { if (doneref) { ac.setReferrer(ref); } } } // add media, easy version for CSS version < 3, otherwise, reuse the parser private void addMedias(AtRuleMedia m, String medias, ApplContext ac) throws InvalidParamException { // before CSS3, let's parse it the easy way... if (ac.getCssVersion().compareTo(CssVersion.CSS3) < 0) { StringTokenizer tokens = new StringTokenizer(medias, ","); while (tokens.hasMoreTokens()) { m.addMedia(null, tokens.nextToken().trim(), ac); } } else { CssFouffa muP = new CssFouffa(ac, new StringReader(medias)); try { AtRuleMedia arm = muP.parseMediaDeclaration(); if (arm != null) { m.allMedia = arm.allMedia; } } catch (ParseException pex) { // error already added, so nothing else to do } } } /** * Parse a style element. The Style element always comes from the user * * @param reader the reader containing the style data * @param url the name of the file the style element was read in. * @throws IOException an IO error */ public void parseStyleElement(ApplContext ac, Reader reader, String title, String media, URL url, int lineno) { boolean doneref = false; style.setWarningLevel(ac.getWarningLevel()); if (Util.onDebug) { System.err.println("StyleSheet.parseStyleElement(" + title + ", " + media + ", " + url + "," + lineno + ")"); } URL ref = ac.getReferrer(); try { // if (cssFouffa == null) { String charset = ac.getCharsetForURL(url); cssFouffa = new CssFouffa(ac, reader, url, lineno); cssFouffa.addListener(this); // } else { // cssFouffa.ReInit(ac, input, url, lineno); // } // cssFouffa.setResponse(res); // cssFouffa.setDefaultMedium(defaultmedium); // cssFouffa.doConfig(); if (media == null && ac.getCssVersion() != CssVersion.CSS1) { media = "all"; } AtRuleMedia m = AtRuleMedia.getInstance(ac.getCssVersion()); try { if (media != null) { addMedias(m, media, ac); } cssFouffa.setAtRule(m); } catch (org.w3c.css.util.InvalidParamException e) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(url.toString(), -1, e)); notifyErrors(er); return; } ac.setReferrer(url); doneref = true; cssFouffa.parseStyle(); } catch (IOException e) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(url.toString(), -1, e)); notifyErrors(er); } catch (TokenMgrError e) { Errors er = new Errors(); CssParseException cpe = null; if (co != null) { try { Object o[] = new Object[1]; o[0] = e; Exception new_e = (Exception) co.newInstance(o); cpe = new CssParseException(new_e); } catch (Exception ex) { cpe = null; } } if (cpe == null) { cpe = new CssParseException(new Exception(e.getMessage())); } er.addError(new org.w3c.css.parser.CssError(url.toString(), -1, //e.getErrorLine(), cpe)); notifyErrors(er); } catch (RuntimeException e) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(url.toString(), cssFouffa.getLine(), new CssParseException(e))); notifyErrors(er); } finally { if (doneref) { ac.setReferrer(ref); } } } /** * @param input the inputStream containing the style data * @param url the name of the file the style element was read in. * @throws IOException an IO error * @see #parseStyleElement(ApplContext, InputStream, String, String, URL, int) * @deprecated Replaced by parseStyleElement */ public void parseStyleElement(ApplContext ac, String input, URL url, int lineno) { parseStyleElement(ac, new StringReader(input), null, null, url, lineno); } /** * Parse a style element. The Style element always comes from the user * * @param input the input stream containing the style data * @param url the name of the file the style element was read in. * @throws IOException an IO error */ public void parseStyleElement(ApplContext ac, InputStream input, String title, String media, URL url, int lineno) { InputStreamReader reader = null; String charset = ac.getCharsetForURL(url); try { reader = new InputStreamReader(input, (charset == null) ? "iso-8859-1" : charset); } catch (UnsupportedEncodingException uex) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(url.toString(), -1, uex)); notifyErrors(er); } catch (Exception ex) { // in case of error, ignore it. reader = null; if (Util.onDebug) { System.err.println("Error in StyleSheet.parseStyleElement(" + title + "," + url + "," + lineno + ")"); } } if (reader != null) { parseStyleElement(ac, reader, title, media, url, lineno); } } /** * Unify call to the parser for css doc as a reader. * * @param ac * @param reader * @param docref */ public void parseStyleSheet(ApplContext ac, Reader reader, URL docref) { parseStyleElement(ac, reader, null, null, (docref == null) ? ac.getFakeURL() : docref, 0); } /** * Parse some declarations. All declarations always comes from the user * * @param input the inputStream containing the style data * @param id the uniq id * @param url the URL the style element was read in. * @throws IOException an IO error */ public void parseStyleAttribute(ApplContext ac, InputStream input, String id, URL url, int lineno) { style.setWarningLevel(ac.getWarningLevel()); lineno--; // why ?!?! if (Util.onDebug) { System.err.println("StyleSheet.parseStyleAttribute(" + id + "," + url + "," + lineno + ")"); } try { // if (cssFouffa == null) { String charset = ac.getCharsetForURL(url); cssFouffa = new CssFouffa(ac, input, charset, url, lineno); cssFouffa.addListener(this); // } else // cssFouffa.ReInit(ac, input, url, lineno); CssSelectors selector = new CssSelectors(ac); try { AtRuleMedia media = AtRuleMedia.getInstance(ac.getCssVersion()); if (ac.getCssVersion() != CssVersion.CSS1) { media.addMedia(null, "all", ac); } cssFouffa.setAtRule(media); } catch (InvalidParamException e) { } //ignore try { if (id == null || id.length() == 0) { id = "nullId-" + Long.toHexString(System.currentTimeMillis()); // TODO add an error/warning ? } selector.addId(new IdSelector(id.substring(1))); } catch (InvalidParamException e) { style.removeThisRule(); ac.getFrame().addError(new CssError(e)); } cssFouffa.parseDeclarations(selector); } catch (IOException e) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(url.toString(), -1, e)); notifyErrors(er); } } /** * @param input the inputStream containing the style data * @param id the uniq id * @param url the name of the file the style element was read in. * @throws IOException an IO error * @see #parseStyleAttribute(ApplContext, InputStream, String, URL, int) * @deprecated Replaced by parseStyleAttribute */ public void parseStyleAttribute(ApplContext ac, String input, String id, URL url, int lineno) { parseStyleAttribute(ac, new ByteArrayInputStream(input.getBytes()), id, url, lineno); } public void setStyle(Class style) { cssFouffa.setStyle(style); } }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_4516_0
crossvul-java_data_good_5805_1
/* * Copyright 2004-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.util; import static org.junit.Assert.*; import java.io.UnsupportedEncodingException; import org.junit.Test; /** * Test fixture for {@link JavaScriptUtils}. * * @author Rossen Stoyanchev */ public class JavaScriptUtilsTests { @Test public void escape() { StringBuilder sb = new StringBuilder(); sb.append('"'); sb.append("'"); sb.append("\\"); sb.append("/"); sb.append("\t"); sb.append("\n"); sb.append("\r"); sb.append("\f"); sb.append("\b"); sb.append("\013"); assertEquals("\\\"\\'\\\\\\/\\t\\n\\n\\f\\b\\v", JavaScriptUtils.javaScriptEscape(sb.toString())); } // SPR-9983 @Test public void escapePsLsLineTerminators() { StringBuilder sb = new StringBuilder(); sb.append('\u2028'); sb.append('\u2029'); String result = JavaScriptUtils.javaScriptEscape(sb.toString()); assertEquals("\\u2028\\u2029", result); } // SPR-9983 @Test public void escapeLessThanGreaterThanSigns() throws UnsupportedEncodingException { assertEquals("\\u003C\\u003E", JavaScriptUtils.javaScriptEscape("<>")); } }
./CrossVul/dataset_final_sorted/CWE-79/java/good_5805_1
crossvul-java_data_bad_24_0
package org.jolokia.http; import java.io.*; import java.net.*; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.*; import javax.management.RuntimeMBeanException; import javax.security.auth.Subject; import javax.servlet.*; import javax.servlet.http.*; import org.jolokia.backend.BackendManager; import org.jolokia.config.*; import org.jolokia.discovery.AgentDetails; import org.jolokia.discovery.DiscoveryMulticastResponder; import org.jolokia.restrictor.*; import org.jolokia.util.*; import org.json.simple.JSONAware; import org.json.simple.JSONStreamAware; /* * Copyright 2009-2013 Roland Huss * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Agent servlet which connects to a local JMX MBeanServer for * JMX operations. * * <p> * It uses a REST based approach which translates a GET Url into a * request. See the <a href="http://www.jolokia.org/reference/index.html">reference documentation</a> * for a detailed description of this servlet's features. * </p> * * @author roland@jolokia.org * @since Apr 18, 2009 */ public class AgentServlet extends HttpServlet { private static final long serialVersionUID = 42L; // POST- and GET- HttpRequestHandler private ServletRequestHandler httpGetHandler, httpPostHandler; // Backend dispatcher private BackendManager backendManager; // Used for logging private LogHandler logHandler; // Request handler for parsing request parameters and building up a response private HttpRequestHandler requestHandler; // Restrictor to use as given in the constructor private Restrictor restrictor; // Mime type used for returning the answer private String configMimeType; // Listen for discovery request (if switched on) private DiscoveryMulticastResponder discoveryMulticastResponder; // whether to allow reverse DNS lookup for checking the remote host private boolean allowDnsReverseLookup; // whether to allow streaming mode for response private boolean streamingEnabled; /** * No argument constructor, used e.g. by an servlet * descriptor when creating the servlet out of web.xml */ public AgentServlet() { this(null); } /** * Constructor taking a restrictor to use * * @param pRestrictor restrictor to use or <code>null</code> if the restrictor * should be created in the default way ({@link RestrictorFactory#createRestrictor(Configuration,LogHandler)}) */ public AgentServlet(Restrictor pRestrictor) { restrictor = pRestrictor; } /** * Get the installed log handler * * @return loghandler used for logging. */ protected LogHandler getLogHandler() { return logHandler; } /** * Initialize the backend systems, the log handler and the restrictor. A subclass can tune * this step by overriding {@link #createRestrictor(Configuration)}} and {@link #createLogHandler(ServletConfig, boolean)} * * @param pServletConfig servlet configuration */ @Override public void init(ServletConfig pServletConfig) throws ServletException { super.init(pServletConfig); Configuration config = initConfig(pServletConfig); // Create a log handler early in the lifecycle, but not too early String logHandlerClass = config.get(ConfigKey.LOGHANDLER_CLASS); logHandler = logHandlerClass != null ? (LogHandler) ClassUtil.newInstance(logHandlerClass) : createLogHandler(pServletConfig,Boolean.valueOf(config.get(ConfigKey.DEBUG))); // Different HTTP request handlers httpGetHandler = newGetHttpRequestHandler(); httpPostHandler = newPostHttpRequestHandler(); if (restrictor == null) { restrictor = createRestrictor(config); } else { logHandler.info("Using custom access restriction provided by " + restrictor); } configMimeType = config.get(ConfigKey.MIME_TYPE); backendManager = new BackendManager(config,logHandler, restrictor); requestHandler = new HttpRequestHandler(config,backendManager,logHandler); allowDnsReverseLookup = config.getAsBoolean(ConfigKey.ALLOW_DNS_REVERSE_LOOKUP); streamingEnabled = config.getAsBoolean(ConfigKey.STREAMING); initDiscoveryMulticast(config); } /** * Hook for creating an own restrictor * * @param config configuration as given to the servlet * @return return restrictor or null if no restrictor is needed. */ protected Restrictor createRestrictor(Configuration config) { return RestrictorFactory.createRestrictor(config, logHandler); } private void initDiscoveryMulticast(Configuration pConfig) { String url = findAgentUrl(pConfig); if (url != null || listenForDiscoveryMcRequests(pConfig)) { backendManager.getAgentDetails().setUrl(url); try { discoveryMulticastResponder = new DiscoveryMulticastResponder(backendManager,restrictor,logHandler); discoveryMulticastResponder.start(); } catch (IOException e) { logHandler.error("Cannot start discovery multicast handler: " + e,e); } } } // Try to find an URL for system props or config private String findAgentUrl(Configuration pConfig) { // System property has precedence String url = System.getProperty("jolokia." + ConfigKey.DISCOVERY_AGENT_URL.getKeyValue()); if (url == null) { url = System.getenv("JOLOKIA_DISCOVERY_AGENT_URL"); if (url == null) { url = pConfig.get(ConfigKey.DISCOVERY_AGENT_URL); } } return NetworkUtil.replaceExpression(url); } // For war agent needs to be switched on private boolean listenForDiscoveryMcRequests(Configuration pConfig) { // Check for system props, system env and agent config boolean sysProp = System.getProperty("jolokia." + ConfigKey.DISCOVERY_ENABLED.getKeyValue()) != null; boolean env = System.getenv("JOLOKIA_DISCOVERY") != null; boolean config = pConfig.getAsBoolean(ConfigKey.DISCOVERY_ENABLED); return sysProp || env || config; } /** * Create a log handler using this servlet's logging facility for logging. This method can be overridden * to provide a custom log handler. This method is called before {@link RestrictorFactory#createRestrictor(Configuration,LogHandler)} so the log handler * can already be used when building up the restrictor. * * @return a default log handler * @param pServletConfig servlet config from where to get information to build up the log handler * @param pDebug whether to print out debug information. */ protected LogHandler createLogHandler(ServletConfig pServletConfig, final boolean pDebug) { return new LogHandler() { /** {@inheritDoc} */ public void debug(String message) { if (pDebug) { log(message); } } /** {@inheritDoc} */ public void info(String message) { log(message); } /** {@inheritDoc} */ public void error(String message, Throwable t) { log(message,t); } }; } /** {@inheritDoc} */ @Override public void destroy() { backendManager.destroy(); if (discoveryMulticastResponder != null) { discoveryMulticastResponder.stop(); discoveryMulticastResponder = null; } super.destroy(); } /** {@inheritDoc} */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { handle(httpGetHandler, req, resp); } /** {@inheritDoc} */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { handle(httpPostHandler, req, resp); } /** * OPTION requests are treated as CORS preflight requests * * @param req the original request * @param resp the response the answer are written to * */ @Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Map<String,String> responseHeaders = requestHandler.handleCorsPreflightRequest( req.getHeader("Origin"), req.getHeader("Access-Control-Request-Headers")); for (Map.Entry<String,String> entry : responseHeaders.entrySet()) { resp.setHeader(entry.getKey(),entry.getValue()); } } @SuppressWarnings({ "PMD.AvoidCatchingThrowable", "PMD.AvoidInstanceofChecksInCatchClause" }) private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException { JSONAware json = null; try { // Check access policy requestHandler.checkAccess(allowDnsReverseLookup ? pReq.getRemoteHost() : null, pReq.getRemoteAddr(), getOriginOrReferer(pReq)); // Remember the agent URL upon the first request. Needed for discovery updateAgentDetailsIfNeeded(pReq); // Dispatch for the proper HTTP request method json = handleSecurely(pReqHandler, pReq, pResp); } catch (Throwable exp) { json = requestHandler.handleThrowable( exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp); } finally { setCorsHeader(pReq, pResp); if (json == null) { json = requestHandler.handleThrowable(new Exception("Internal error while handling an exception")); } sendResponse(pResp, pReq, json); } } private JSONAware handleSecurely(final ServletRequestHandler pReqHandler, final HttpServletRequest pReq, final HttpServletResponse pResp) throws IOException, PrivilegedActionException { Subject subject = (Subject) pReq.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE); if (subject != null) { return Subject.doAs(subject, new PrivilegedExceptionAction<JSONAware>() { public JSONAware run() throws IOException { return pReqHandler.handleRequest(pReq, pResp); } }); } else { return pReqHandler.handleRequest(pReq, pResp); } } private String getOriginOrReferer(HttpServletRequest pReq) { String origin = pReq.getHeader("Origin"); if (origin == null) { origin = pReq.getHeader("Referer"); } return origin != null ? origin.replaceAll("[\\n\\r]*","") : null; } // Update the agent URL in the agent details if not already done private void updateAgentDetailsIfNeeded(HttpServletRequest pReq) { // Lookup the Agent URL if needed AgentDetails details = backendManager.getAgentDetails(); if (details.isInitRequired()) { synchronized (details) { if (details.isInitRequired()) { if (details.isUrlMissing()) { String url = getBaseUrl(NetworkUtil.sanitizeLocalUrl(pReq.getRequestURL().toString()), extractServletPath(pReq)); details.setUrl(url); } if (details.isSecuredMissing()) { details.setSecured(pReq.getAuthType() != null); } details.seal(); } } } } private String extractServletPath(HttpServletRequest pReq) { return pReq.getRequestURI().substring(0,pReq.getContextPath().length()); } // Strip off everything unneeded private String getBaseUrl(String pUrl, String pServletPath) { String sUrl; try { URL url = new URL(pUrl); String host = getIpIfPossible(url.getHost()); sUrl = new URL(url.getProtocol(),host,url.getPort(),pServletPath).toExternalForm(); } catch (MalformedURLException exp) { sUrl = plainReplacement(pUrl, pServletPath); } return sUrl; } // Check for an IP, since this seems to be safer to return then a plain name private String getIpIfPossible(String pHost) { try { InetAddress address = InetAddress.getByName(pHost); return address.getHostAddress(); } catch (UnknownHostException e) { return pHost; } } // Fallback used if URL creation didnt work private String plainReplacement(String pUrl, String pServletPath) { int idx = pUrl.lastIndexOf(pServletPath); String url; if (idx != -1) { url = pUrl.substring(0,idx) + pServletPath; } else { url = pUrl; } return url; } // Set an appropriate CORS header if requested and if allowed private void setCorsHeader(HttpServletRequest pReq, HttpServletResponse pResp) { String origin = requestHandler.extractCorsOrigin(pReq.getHeader("Origin")); if (origin != null) { pResp.setHeader("Access-Control-Allow-Origin", origin); pResp.setHeader("Access-Control-Allow-Credentials","true"); } } // Extract mime type for response (if not JSONP) private String getMimeType(HttpServletRequest pReq) { String requestMimeType = pReq.getParameter(ConfigKey.MIME_TYPE.getKeyValue()); if (requestMimeType != null) { return requestMimeType; } return configMimeType; } private boolean isStreamingEnabled(HttpServletRequest pReq) { String streamingFromReq = pReq.getParameter(ConfigKey.STREAMING.getKeyValue()); if (streamingFromReq != null) { return Boolean.parseBoolean(streamingFromReq); } return streamingEnabled; } private interface ServletRequestHandler { /** * Handle a request and return the answer as a JSON structure * @param pReq request arrived * @param pResp response to return * @return the JSON representation for the answer * @throws IOException if handling of an input or output stream failed */ JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp) throws IOException; } // factory method for POST request handler private ServletRequestHandler newPostHttpRequestHandler() { return new ServletRequestHandler() { /** {@inheritDoc} */ public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp) throws IOException { String encoding = pReq.getCharacterEncoding(); InputStream is = pReq.getInputStream(); return requestHandler.handlePostRequest(pReq.getRequestURI(),is, encoding, getParameterMap(pReq)); } }; } // factory method for GET request handler private ServletRequestHandler newGetHttpRequestHandler() { return new ServletRequestHandler() { /** {@inheritDoc} */ public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp) { return requestHandler.handleGetRequest(pReq.getRequestURI(),pReq.getPathInfo(), getParameterMap(pReq)); } }; } // ======================================================================= // Get parameter map either directly from an Servlet 2.4 compliant implementation // or by looking it up explictely (thanks to codewax for the patch) private Map<String, String[]> getParameterMap(HttpServletRequest pReq){ try { // Servlet 2.4 API return pReq.getParameterMap(); } catch (UnsupportedOperationException exp) { // Thrown by 'pseudo' 2.4 Servlet API implementations which fake a 2.4 API // As a service for the parameter map is build up explicitely Map<String, String[]> ret = new HashMap<String, String[]>(); Enumeration params = pReq.getParameterNames(); while (params.hasMoreElements()) { String param = (String) params.nextElement(); ret.put(param, pReq.getParameterValues(param)); } return ret; } } // Examines servlet config and servlet context for configuration parameters. // Configuration from the servlet context overrides servlet parameters defined in web.xml Configuration initConfig(ServletConfig pConfig) { Configuration config = new Configuration( ConfigKey.AGENT_ID, NetworkUtil.getAgentId(hashCode(),"servlet")); // From ServletContext .... config.updateGlobalConfiguration(new ServletConfigFacade(pConfig)); // ... and ServletConfig config.updateGlobalConfiguration(new ServletContextFacade(getServletContext())); // Set type last and overwrite anything written config.updateGlobalConfiguration(Collections.singletonMap(ConfigKey.AGENT_TYPE.getKeyValue(),"servlet")); return config; } private void sendResponse(HttpServletResponse pResp, HttpServletRequest pReq, JSONAware pJson) throws IOException { String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue()); setContentType(pResp, callback != null ? "text/javascript" : getMimeType(pReq)); pResp.setStatus(HttpServletResponse.SC_OK); setNoCacheHeaders(pResp); if (pJson == null) { pResp.setContentLength(-1); } else { if (isStreamingEnabled(pReq)) { sendStreamingResponse(pResp, callback, (JSONStreamAware) pJson); } else { // Fallback, send as one object // TODO: Remove for 2.0 where should support only streaming sendAllJSON(pResp, callback, pJson); } } } private void sendStreamingResponse(HttpServletResponse pResp, String pCallback, JSONStreamAware pJson) throws IOException { Writer writer = new OutputStreamWriter(pResp.getOutputStream(), "UTF-8"); IoUtil.streamResponseAndClose(writer, pJson, pCallback); } private void sendAllJSON(HttpServletResponse pResp, String callback, JSONAware pJson) throws IOException { OutputStream out = null; try { String json = pJson.toJSONString(); String content = callback == null ? json : callback + "(" + json + ");"; byte[] response = content.getBytes("UTF8"); pResp.setContentLength(response.length); out = pResp.getOutputStream(); out.write(response); } finally { if (out != null) { // Always close in order to finish the request. // Otherwise the thread blocks. out.close(); } } } private void setNoCacheHeaders(HttpServletResponse pResp) { pResp.setHeader("Cache-Control", "no-cache"); pResp.setHeader("Pragma","no-cache"); // Check for a date header and set it accordingly to the recommendations of // RFC-2616 (http://tools.ietf.org/html/rfc2616#section-14.21) // // "To mark a response as "already expired," an origin server sends an // Expires date that is equal to the Date header value. (See the rules // for expiration calculations in section 13.2.4.)" // // See also #71 long now = System.currentTimeMillis(); pResp.setDateHeader("Date",now); // 1h in the past since it seems, that some servlet set the date header on their // own so that it cannot be guaranteed that these headers are really equals. // It happened on Tomcat that Date: was finally set *before* Expires: in the final // answers some times which seems to be an implementation peculiarity from Tomcat pResp.setDateHeader("Expires",now - 3600000); } private void setContentType(HttpServletResponse pResp, String pContentType) { boolean encodingDone = false; try { pResp.setCharacterEncoding("utf-8"); pResp.setContentType(pContentType); encodingDone = true; } catch (NoSuchMethodError error) { /* Servlet 2.3 */ } catch (UnsupportedOperationException error) { /* Equinox HTTP Service */ } if (!encodingDone) { // For a Servlet 2.3 container or an Equinox HTTP Service, set the charset by hand pResp.setContentType(pContentType + "; charset=utf-8"); } } // ======================================================================================= // Helper classes for extracting configuration from servlet classes // Implementation for the ServletConfig private static final class ServletConfigFacade implements ConfigExtractor { private final ServletConfig config; private ServletConfigFacade(ServletConfig pConfig) { config = pConfig; } /** {@inheritDoc} */ public Enumeration getNames() { return config.getInitParameterNames(); } /** {@inheritDoc} */ public String getParameter(String pName) { return config.getInitParameter(pName); } } // Implementation for ServletContextFacade private static final class ServletContextFacade implements ConfigExtractor { private final ServletContext servletContext; private ServletContextFacade(ServletContext pServletContext) { servletContext = pServletContext; } /** {@inheritDoc} */ public Enumeration getNames() { return servletContext.getInitParameterNames(); } /** {@inheritDoc} */ public String getParameter(String pName) { return servletContext.getInitParameter(pName); } } }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_24_0
crossvul-java_data_bad_1163_0
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package com.sun.faces.context; import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_EXECUTE_PARAM; import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RENDER_PARAM; import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RESET_VALUES_PARAM; import static javax.faces.FactoryFinder.VISIT_CONTEXT_FACTORY; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.application.ResourceHandler; import javax.faces.component.NamingContainer; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import javax.faces.component.visit.VisitCallback; import javax.faces.component.visit.VisitContext; import javax.faces.component.visit.VisitContextFactory; import javax.faces.component.visit.VisitContextWrapper; import javax.faces.component.visit.VisitHint; import javax.faces.component.visit.VisitResult; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.PartialResponseWriter; import javax.faces.context.PartialViewContext; import javax.faces.context.ResponseWriter; import javax.faces.event.PhaseId; import javax.faces.lifecycle.ClientWindow; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import com.sun.faces.RIConstants; import com.sun.faces.component.visit.PartialVisitContext; import com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter; import com.sun.faces.util.FacesLogger; import com.sun.faces.util.HtmlUtils; import com.sun.faces.util.Util; public class PartialViewContextImpl extends PartialViewContext { // Log instance for this class private static Logger LOGGER = FacesLogger.CONTEXT.getLogger(); private boolean released; // BE SURE TO ADD NEW IVARS TO THE RELEASE METHOD private PartialResponseWriter partialResponseWriter; private List<String> executeIds; private Collection<String> renderIds; private List<String> evalScripts; private Boolean ajaxRequest; private Boolean partialRequest; private Boolean renderAll; private FacesContext ctx; private static final String ORIGINAL_WRITER = "com.sun.faces.ORIGINAL_WRITER"; // ----------------------------------------------------------- Constructors public PartialViewContextImpl(FacesContext ctx) { this.ctx = ctx; } // ---------------------------------------------- Methods from PartialViewContext /** * @see javax.faces.context.PartialViewContext#isAjaxRequest() */ @Override public boolean isAjaxRequest() { assertNotReleased(); if (ajaxRequest == null) { ajaxRequest = "partial/ajax".equals(ctx. getExternalContext().getRequestHeaderMap().get("Faces-Request")); if (!ajaxRequest) { ajaxRequest = "partial/ajax".equals(ctx.getExternalContext().getRequestParameterMap(). get("Faces-Request")); } } return ajaxRequest; } /** * @see javax.faces.context.PartialViewContext#isPartialRequest() */ @Override public boolean isPartialRequest() { assertNotReleased(); if (partialRequest == null) { partialRequest = isAjaxRequest() || "partial/process".equals(ctx. getExternalContext().getRequestHeaderMap().get("Faces-Request")); } return partialRequest; } /** * @see javax.faces.context.PartialViewContext#isExecuteAll() */ @Override public boolean isExecuteAll() { assertNotReleased(); String execute = PARTIAL_EXECUTE_PARAM.getValue(ctx); return (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(execute)); } /** * @see javax.faces.context.PartialViewContext#isRenderAll() */ @Override public boolean isRenderAll() { assertNotReleased(); if (renderAll == null) { String render = PARTIAL_RENDER_PARAM.getValue(ctx); renderAll = (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(render)); } return renderAll; } /** * @see javax.faces.context.PartialViewContext#setRenderAll(boolean) */ @Override public void setRenderAll(boolean renderAll) { this.renderAll = renderAll; } @Override public boolean isResetValues() { Object value = PARTIAL_RESET_VALUES_PARAM.getValue(ctx); return (null != value && "true".equals(value)) ? true : false; } @Override public void setPartialRequest(boolean isPartialRequest) { this.partialRequest = isPartialRequest; } /** * @see javax.faces.context.PartialViewContext#getExecuteIds() */ @Override public Collection<String> getExecuteIds() { assertNotReleased(); if (executeIds != null) { return executeIds; } executeIds = populatePhaseClientIds(PARTIAL_EXECUTE_PARAM); // include the view parameter facet ID if there are other execute IDs // to process if (!executeIds.isEmpty()) { UIViewRoot root = ctx.getViewRoot(); if (root.getFacetCount() > 0) { if (root.getFacet(UIViewRoot.METADATA_FACET_NAME) != null) { executeIds.add(0, UIViewRoot.METADATA_FACET_NAME); } } } return executeIds; } /** * @see javax.faces.context.PartialViewContext#getRenderIds() */ @Override public Collection<String> getRenderIds() { assertNotReleased(); if (renderIds != null) { return renderIds; } renderIds = populatePhaseClientIds(PARTIAL_RENDER_PARAM); return renderIds; } /** * @see javax.faces.context.PartialViewContext#getEvalScripts() */ @Override public List<String> getEvalScripts() { assertNotReleased(); if (evalScripts == null) { evalScripts = new ArrayList<>(1); } return evalScripts; } /** * @see PartialViewContext#processPartial(javax.faces.event.PhaseId) */ @Override public void processPartial(PhaseId phaseId) { PartialViewContext pvc = ctx.getPartialViewContext(); Collection <String> myExecuteIds = pvc.getExecuteIds(); Collection <String> myRenderIds = pvc.getRenderIds(); UIViewRoot viewRoot = ctx.getViewRoot(); if (phaseId == PhaseId.APPLY_REQUEST_VALUES || phaseId == PhaseId.PROCESS_VALIDATIONS || phaseId == PhaseId.UPDATE_MODEL_VALUES) { // Skip this processing if "none" is specified in the render list, // or there were no execute phase client ids. if (myExecuteIds == null || myExecuteIds.isEmpty()) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "No execute and render identifiers specified. Skipping component processing."); } return; } try { processComponents(viewRoot, phaseId, myExecuteIds, ctx); } catch (Exception e) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, e.toString(), e); } throw new FacesException(e); } // If we have just finished APPLY_REQUEST_VALUES phase, install the // partial response writer. We want to make sure that any content // or errors generated in the other phases are written using the // partial response writer. // if (phaseId == PhaseId.APPLY_REQUEST_VALUES) { PartialResponseWriter writer = pvc.getPartialResponseWriter(); ctx.setResponseWriter(writer); } } else if (phaseId == PhaseId.RENDER_RESPONSE) { try { // // We re-enable response writing. // PartialResponseWriter writer = pvc.getPartialResponseWriter(); ResponseWriter orig = ctx.getResponseWriter(); ctx.getAttributes().put(ORIGINAL_WRITER, orig); ctx.setResponseWriter(writer); ExternalContext exContext = ctx.getExternalContext(); exContext.setResponseContentType(RIConstants.TEXT_XML_CONTENT_TYPE); exContext.addResponseHeader("Cache-Control", "no-cache"); // String encoding = writer.getCharacterEncoding( ); // if( encoding == null ) { // encoding = "UTF-8"; // } // writer.writePreamble("<?xml version='1.0' encoding='" + encoding + "'?>\n"); writer.startDocument(); if (isResetValues()) { viewRoot.resetValues(ctx, myRenderIds); } if (isRenderAll()) { renderAll(ctx, viewRoot); renderState(ctx); writer.endDocument(); return; } renderComponentResources(ctx, viewRoot); // Skip this processing if "none" is specified in the render list, // or there were no render phase client ids. if (myRenderIds != null && !myRenderIds.isEmpty()) { processComponents(viewRoot, phaseId, myRenderIds, ctx); } renderState(ctx); renderEvalScripts(ctx); writer.endDocument(); } catch (IOException ex) { this.cleanupAfterView(); } catch (RuntimeException ex) { this.cleanupAfterView(); // Throw the exception throw ex; } } } /** * @see javax.faces.context.PartialViewContext#getPartialResponseWriter() */ @Override public PartialResponseWriter getPartialResponseWriter() { assertNotReleased(); if (partialResponseWriter == null) { partialResponseWriter = new DelayedInitPartialResponseWriter(this); } return partialResponseWriter; } /** * @see javax.faces.context.PartialViewContext#release() */ @Override public void release() { released = true; ajaxRequest = null; renderAll = null; partialResponseWriter = null; executeIds = null; renderIds = null; evalScripts = null; ctx = null; partialRequest = null; } // -------------------------------------------------------- Private Methods private List<String> populatePhaseClientIds(PredefinedPostbackParameter parameterName) { String param = parameterName.getValue(ctx); if (param == null) { return new ArrayList<>(); } else { Map<String, Object> appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap(); String[] pcs = Util.split(appMap, param, "[ \t]+"); return ((pcs != null && pcs.length != 0) ? new ArrayList<>(Arrays.asList(pcs)) : new ArrayList<>()); } } // Process the components specified in the phaseClientIds list private void processComponents(UIComponent component, PhaseId phaseId, Collection<String> phaseClientIds, FacesContext context) throws IOException { // We use the tree visitor mechanism to locate the components to // process. Create our (partial) VisitContext and the // VisitCallback that will be invoked for each component that // is visited. Note that we use the SKIP_UNRENDERED hint as we // only want to visit the rendered subtree. EnumSet<VisitHint> hints = EnumSet.of(VisitHint.SKIP_UNRENDERED, VisitHint.EXECUTE_LIFECYCLE); VisitContextFactory visitContextFactory = (VisitContextFactory) FactoryFinder.getFactory(VISIT_CONTEXT_FACTORY); VisitContext visitContext = visitContextFactory.getVisitContext(context, phaseClientIds, hints); PhaseAwareVisitCallback visitCallback = new PhaseAwareVisitCallback(ctx, phaseId); component.visitTree(visitContext, visitCallback); PartialVisitContext partialVisitContext = unwrapPartialVisitContext(visitContext); if (partialVisitContext != null) { if (LOGGER.isLoggable(Level.FINER) && !partialVisitContext.getUnvisitedClientIds().isEmpty()) { Collection<String> unvisitedClientIds = partialVisitContext.getUnvisitedClientIds(); StringBuilder builder = new StringBuilder(); for (String cur : unvisitedClientIds) { builder.append(cur).append(" "); } LOGGER.log(Level.FINER, "jsf.context.partial_visit_context_unvisited_children", new Object[]{builder.toString()}); } } } /** * Unwraps {@link PartialVisitContext} from a chain of {@link VisitContextWrapper}s. * * If no {@link PartialVisitContext} is found in the chain, null is returned instead. * * @param visitContext the visit context. * @return the (unwrapped) partial visit context. */ private static PartialVisitContext unwrapPartialVisitContext(VisitContext visitContext) { if (visitContext == null) { return null; } if (visitContext instanceof PartialVisitContext) { return (PartialVisitContext) visitContext; } if (visitContext instanceof VisitContextWrapper) { return unwrapPartialVisitContext(((VisitContextWrapper) visitContext).getWrapped()); } return null; } private void renderAll(FacesContext context, UIViewRoot viewRoot) throws IOException { // If this is a "render all via ajax" request, // make sure to wrap the entire page in a <render> elemnt // with the special viewStateId of VIEW_ROOT_ID. This is how the client // JavaScript knows how to replace the entire document with // this response. PartialViewContext pvc = context.getPartialViewContext(); PartialResponseWriter writer = pvc.getPartialResponseWriter(); if (!(viewRoot instanceof NamingContainer)) { writer.startUpdate(PartialResponseWriter.RENDER_ALL_MARKER); if (viewRoot.getChildCount() > 0) { for (UIComponent uiComponent : viewRoot.getChildren()) { uiComponent.encodeAll(context); } } writer.endUpdate(); } else { /* * If we have a portlet request, start rendering at the view root. */ writer.startUpdate(viewRoot.getClientId(context)); viewRoot.encodeBegin(context); if (viewRoot.getChildCount() > 0) { for (UIComponent uiComponent : viewRoot.getChildren()) { uiComponent.encodeAll(context); } } viewRoot.encodeEnd(context); writer.endUpdate(); } } private void renderComponentResources(FacesContext context, UIViewRoot viewRoot) throws IOException { ResourceHandler resourceHandler = context.getApplication().getResourceHandler(); PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter(); boolean updateStarted = false; for (UIComponent resource : viewRoot.getComponentResources(context)) { String name = (String) resource.getAttributes().get("name"); String library = (String) resource.getAttributes().get("library"); if (resource.getChildCount() == 0 && resourceHandler.getRendererTypeForResourceName(name) != null && !resourceHandler.isResourceRendered(context, name, library)) { if (!updateStarted) { writer.startUpdate("javax.faces.Resource"); updateStarted = true; } resource.encodeAll(context); } } if (updateStarted) { writer.endUpdate(); } } private void renderState(FacesContext context) throws IOException { // Get the view state and write it to the response.. PartialViewContext pvc = context.getPartialViewContext(); PartialResponseWriter writer = pvc.getPartialResponseWriter(); String viewStateId = Util.getViewStateId(context); writer.startUpdate(viewStateId); String state = context.getApplication().getStateManager().getViewState(context); writer.write(state); writer.endUpdate(); ClientWindow window = context.getExternalContext().getClientWindow(); if (null != window) { String clientWindowId = Util.getClientWindowId(context); writer.startUpdate(clientWindowId); writer.write(window.getId()); writer.endUpdate(); } } private void renderEvalScripts(FacesContext context) throws IOException { PartialViewContext pvc = context.getPartialViewContext(); PartialResponseWriter writer = pvc.getPartialResponseWriter(); for (String evalScript : pvc.getEvalScripts()) { writer.startEval(); writer.write(evalScript); writer.endEval(); } } private PartialResponseWriter createPartialResponseWriter() { ExternalContext extContext = ctx.getExternalContext(); String encoding = extContext.getRequestCharacterEncoding(); extContext.setResponseCharacterEncoding(encoding); ResponseWriter responseWriter = null; Writer out = null; try { out = extContext.getResponseOutputWriter(); } catch (IOException ioe) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, ioe.toString(), ioe); } } if (out != null) { UIViewRoot viewRoot = ctx.getViewRoot(); if (viewRoot != null) { responseWriter = ctx.getRenderKit().createResponseWriter(out, RIConstants.TEXT_XML_CONTENT_TYPE, encoding); } else { RenderKitFactory factory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = factory.getRenderKit(ctx, RenderKitFactory.HTML_BASIC_RENDER_KIT); responseWriter = renderKit.createResponseWriter(out, RIConstants.TEXT_XML_CONTENT_TYPE, encoding); } } if (responseWriter instanceof PartialResponseWriter) { return (PartialResponseWriter) responseWriter; } else { return new PartialResponseWriter(responseWriter); } } private void cleanupAfterView() { ResponseWriter orig = (ResponseWriter) ctx.getAttributes(). get(ORIGINAL_WRITER); assert(null != orig); // move aside the PartialResponseWriter ctx.setResponseWriter(orig); } private void assertNotReleased() { if (released) { throw new IllegalStateException(); } } // ----------------------------------------------------------- Inner Classes private static class PhaseAwareVisitCallback implements VisitCallback { private PhaseId curPhase; private FacesContext ctx; private PhaseAwareVisitCallback(FacesContext ctx, PhaseId curPhase) { this.ctx = ctx; this.curPhase = curPhase; } @Override public VisitResult visit(VisitContext context, UIComponent comp) { try { if (curPhase == PhaseId.APPLY_REQUEST_VALUES) { // RELEASE_PENDING handle immediate request(s) // If the user requested an immediate request // Make sure to set the immediate flag here. comp.processDecodes(ctx); } else if (curPhase == PhaseId.PROCESS_VALIDATIONS) { comp.processValidators(ctx); } else if (curPhase == PhaseId.UPDATE_MODEL_VALUES) { comp.processUpdates(ctx); } else if (curPhase == PhaseId.RENDER_RESPONSE) { PartialResponseWriter writer = ctx.getPartialViewContext().getPartialResponseWriter(); writer.startUpdate(comp.getClientId(ctx)); // do the default behavior... comp.encodeAll(ctx); writer.endUpdate(); } else { throw new IllegalStateException("I18N: Unexpected " + "PhaseId passed to " + " PhaseAwareContextCallback: " + curPhase.toString()); } } catch (IOException ex) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(ex.toString()); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, ex.toString(), ex); } throw new FacesException(ex); } // Once we visit a component, there is no need to visit // its children, since processDecodes/Validators/Updates and // encodeAll() already traverse the subtree. We return // VisitResult.REJECT to supress the subtree visit. return VisitResult.REJECT; } } /** * Delays the actual construction of the PartialResponseWriter <em>until</em> * content is going to actually be written. */ private static final class DelayedInitPartialResponseWriter extends PartialResponseWriter { private ResponseWriter writer; private PartialViewContextImpl ctx; // -------------------------------------------------------- Constructors public DelayedInitPartialResponseWriter(PartialViewContextImpl ctx) { super(null); this.ctx = ctx; ExternalContext extCtx = ctx.ctx.getExternalContext(); extCtx.setResponseContentType(RIConstants.TEXT_XML_CONTENT_TYPE); extCtx.setResponseCharacterEncoding(extCtx.getRequestCharacterEncoding()); extCtx.setResponseBufferSize(ctx.ctx.getExternalContext().getResponseBufferSize()); } // ---------------------------------- Methods from PartialResponseWriter @Override public void write(String text) throws IOException { HtmlUtils.writeUnescapedTextForXML(getWrapped(), text); } @Override public ResponseWriter getWrapped() { if (writer == null) { writer = ctx.createPartialResponseWriter(); } return writer; } } // END DelayedInitPartialResponseWriter }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_1163_0
crossvul-java_data_good_5841_0
///////////////////////////////////////////////////////////////////////////// // // Project ProjectForge Community Edition // www.projectforge.org // // Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de) // // ProjectForge is dual-licensed. // // This community edition is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 3 of the License. // // This community edition is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General // Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, see http://www.gnu.org/licenses/. // ///////////////////////////////////////////////////////////////////////////// package org.projectforge.web.core; import java.util.Collection; import org.apache.commons.lang.ObjectUtils; public class JsonBuilder { final private StringBuilder sb = new StringBuilder(); private boolean escapeHtml; /** * Creates Json result string from the given list.<br/> * [["Horst"], ["Klaus"], ...]] // For single property<br/> * [["Klein", "Horst"],["Schmidt", "Klaus"], ...] // For two Properties (e. g. name, first name) [["id:37", "Klein", "Horst"],["id:42", * "Schmidt", "Klaus"], ...] // For two Properties (e. g. name, first name) with id. <br/> * Uses ObjectUtils.toString(Object) for formatting each value. * @param col The array representation: List<Object> or List<Object[]>. If null then "[]" is returned. * @return */ public static String buildToStringRows(final Collection< ? > col) { if (col == null) { return "[]"; } final JsonBuilder builder = new JsonBuilder(); return builder.append(col).getAsString(); } /** * @param escapeHtml the escapeHtml to set (default is false). * @return this for chaining. */ public JsonBuilder setEscapeHtml(final boolean escapeHtml) { this.escapeHtml = escapeHtml; return this; } public String getAsString() { return sb.toString(); } /** * Appends objects to buffer, e. g.: ["Horst"], ["Klaus"], ... Uses formatValue(Object) to render the values. * @param oArray * @return This (fluent) */ public JsonBuilder append(final Object[] oArray) { sb.append(" ["); // begin array String separator = ""; for (final Object obj : oArray) { sb.append(separator); separator = ","; sb.append(escapeString(formatValue(obj))); } sb.append("]"); // end array return this; } private String escapeString(final String string) { if (string == null || string.length() == 0) { return "\"\""; } char c = 0; int i; final int len = string.length(); final StringBuilder sb = new StringBuilder(len + 4); String t; sb.append('"'); for (i = 0; i < len; i += 1) { c = string.charAt(i); switch (c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; case '/': // if (b == '<') { sb.append('\\'); // } sb.append(c); break; case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: if (c < ' ') { t = "000" + Integer.toHexString(c); sb.append("\\u" + t.substring(t.length() - 4)); } else { if (escapeHtml == true) { switch (c) { case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '&': sb.append("&amp;"); break; case '"': sb.append("&quot;"); break; case '\'': sb.append("&#x27;"); break; case '/': sb.append("&#x2F;"); break; default: sb.append(c); } } else { sb.append(c); } } } } sb.append('"'); return sb.toString(); } /** * Creates Json result string from the given list.<br/> * [["Horst"], ["Klaus"], ...]] // For single property<br/> * [["Klein", "Horst"],["Schmidt", "Klaus"], ...] // For two Properties (e. g. name, first name) [["id:37", "Klein", "Horst"],["id:42", * "Schmidt", "Klaus"], ...] // For two Properties (e. g. name, first name) with id. <br/> * Uses formatValue(Object) for formatting each value. * @param col The array representation: List<Object> or List<Object[]>. If null then "[]" is returned. * @return */ public JsonBuilder append(final Collection< ? > col) { if (col == null) { sb.append("[]"); return this; } // Format: [["1.1", "1.2", ...],["2.1", "2.2", ...]] sb.append("[\n"); String separator = "\n"; for (final Object os : col) { sb.append(separator); separator = ",\n"; if (os instanceof Object[]) { // Multiple properties append((Object[]) os); } else { // Only one property append(transform(os)); } } sb.append("]"); // end data return this; } /** * @param obj * @return * @see ObjectUtils#toString(Object) */ protected String formatValue(final Object obj) { return ObjectUtils.toString(obj); } protected JsonBuilder append(final Object obj) { if (obj instanceof Object[]) { return append((Object[]) obj); } sb.append(" ["); // begin row // " must be quoted as \": sb.append(escapeString(formatValue(obj))); sb.append("]"); // end row return this; } /** * Before rendering a obj of e. g. a collection the obj can be transformed e. g. in an Object array of dimension 2 containing label and * value. * @param obj * @return obj (identity function) if not overload. */ protected Object transform(final Object obj) { return obj; } }
./CrossVul/dataset_final_sorted/CWE-79/java/good_5841_0
crossvul-java_data_bad_24_3
package org.jolokia.jvmagent.handler; /* * Copyright 2009-2013 Roland Huss * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.*; import java.net.InetSocketAddress; import java.net.URI; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.management.MalformedObjectNameException; import javax.management.RuntimeMBeanException; import javax.security.auth.Subject; import com.sun.net.httpserver.*; import org.jolokia.backend.BackendManager; import org.jolokia.config.ConfigKey; import org.jolokia.config.Configuration; import org.jolokia.discovery.AgentDetails; import org.jolokia.discovery.DiscoveryMulticastResponder; import org.jolokia.http.HttpRequestHandler; import org.jolokia.jvmagent.ParsedUri; import org.jolokia.restrictor.*; import org.jolokia.util.*; import org.json.simple.JSONAware; import org.json.simple.JSONStreamAware; /** * HttpHandler for handling a Jolokia request * * @author roland * @since Mar 3, 2010 */ public class JolokiaHttpHandler implements HttpHandler { // Backendmanager for doing request private BackendManager backendManager; // The HttpRequestHandler private HttpRequestHandler requestHandler; // Context of this request private String context; // Content type matching private Pattern contentTypePattern = Pattern.compile(".*;\\s*charset=([^;,]+)\\s*.*"); // Configuration of this handler private Configuration configuration; // Loghandler to use private final LogHandler logHandler; // Respond for discovery mc requests private DiscoveryMulticastResponder discoveryMulticastResponder; /** * Create a new HttpHandler for processing HTTP request * * @param pConfig jolokia specific config tuning the processing behaviour */ public JolokiaHttpHandler(Configuration pConfig) { this(pConfig, null); } /** * Create a new HttpHandler for processing HTTP request * * @param pConfig jolokia specific config tuning the processing behaviour * @param pLogHandler log-handler the log handler to use for jolokia */ public JolokiaHttpHandler(Configuration pConfig, LogHandler pLogHandler) { configuration = pConfig; context = pConfig.get(ConfigKey.AGENT_CONTEXT); if (!context.endsWith("/")) { context += "/"; } logHandler = pLogHandler != null ? pLogHandler : createLogHandler(pConfig.get(ConfigKey.LOGHANDLER_CLASS), pConfig.get(ConfigKey.DEBUG)); } /** * Start the handler * * @param pLazy whether initialisation should be done lazy. */ public void start(boolean pLazy) { Restrictor restrictor = createRestrictor(); backendManager = new BackendManager(configuration, logHandler, restrictor, pLazy); requestHandler = new HttpRequestHandler(configuration, backendManager, logHandler); if (listenForDiscoveryMcRequests(configuration)) { try { discoveryMulticastResponder = new DiscoveryMulticastResponder(backendManager, restrictor, logHandler); discoveryMulticastResponder.start(); } catch (IOException e) { logHandler.error("Cannot start discovery multicast handler: " + e, e); } } } /** * Hook for creating an own restrictor * * @return return restrictor or null if no restrictor is needed. */ protected Restrictor createRestrictor() { return RestrictorFactory.createRestrictor(configuration, logHandler); } private boolean listenForDiscoveryMcRequests(Configuration pConfig) { String enable = pConfig.get(ConfigKey.DISCOVERY_ENABLED); String url = pConfig.get(ConfigKey.DISCOVERY_AGENT_URL); return url != null || enable == null || Boolean.valueOf(enable); } /** * Start the handler and remember connection details which are useful for discovery messages * * @param pLazy whether initialisation should be done lazy. * @param pUrl agent URL * @param pSecured whether the communication is secured or not */ public void start(boolean pLazy, String pUrl, boolean pSecured) { start(pLazy); AgentDetails details = backendManager.getAgentDetails(); details.setUrl(pUrl); details.setSecured(pSecured); } /** * Stop the handler */ public void stop() { if (discoveryMulticastResponder != null) { discoveryMulticastResponder.stop(); discoveryMulticastResponder = null; } backendManager.destroy(); backendManager = null; requestHandler = null; } /** * Handle a request. If the handler is not yet started, an exception is thrown. If running with JAAS * security enabled it will run as the given subject. * * @param pHttpExchange the request/response object * @throws IOException if something fails during handling * @throws IllegalStateException if the handler has not yet been started */ public void handle(final HttpExchange pHttpExchange) throws IOException { try { checkAuthentication(pHttpExchange); Subject subject = (Subject) pHttpExchange.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE); if (subject != null) { doHandleAs(subject, pHttpExchange); } else { doHandle(pHttpExchange); } } catch (SecurityException exp) { sendForbidden(pHttpExchange,exp); } } // run as priviledged action private void doHandleAs(Subject subject, final HttpExchange pHttpExchange) { try { Subject.doAs(subject, new PrivilegedExceptionAction<Void>() { public Void run() throws IOException { doHandle(pHttpExchange); return null; } }); } catch (PrivilegedActionException e) { throw new SecurityException("Security exception: " + e.getCause(),e.getCause()); } } /** * Protocol based authentication checks called very early and before handling a request. * If the check fails a security exception must be thrown * * The default implementation does nothing and should be overridden for a valid check. * * @param pHttpExchange exchange to check * @throws SecurityException if check fails. */ protected void checkAuthentication(HttpExchange pHttpExchange) throws SecurityException { } @SuppressWarnings({"PMD.AvoidCatchingThrowable", "PMD.AvoidInstanceofChecksInCatchClause"}) public void doHandle(HttpExchange pExchange) throws IOException { if (requestHandler == null) { throw new IllegalStateException("Handler not yet started"); } JSONAware json = null; URI uri = pExchange.getRequestURI(); ParsedUri parsedUri = new ParsedUri(uri, context); try { // Check access policy InetSocketAddress address = pExchange.getRemoteAddress(); requestHandler.checkAccess(getHostName(address), address.getAddress().getHostAddress(), extractOriginOrReferer(pExchange)); String method = pExchange.getRequestMethod(); // Dispatch for the proper HTTP request method if ("GET".equalsIgnoreCase(method)) { setHeaders(pExchange); json = executeGetRequest(parsedUri); } else if ("POST".equalsIgnoreCase(method)) { setHeaders(pExchange); json = executePostRequest(pExchange, parsedUri); } else if ("OPTIONS".equalsIgnoreCase(method)) { performCorsPreflightCheck(pExchange); } else { throw new IllegalArgumentException("HTTP Method " + method + " is not supported."); } } catch (Throwable exp) { json = requestHandler.handleThrowable( exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp); } finally { sendResponse(pExchange, parsedUri, json); } } // ======================================================================== // Used for checking origin or referer is an origin policy is enabled private String extractOriginOrReferer(HttpExchange pExchange) { Headers headers = pExchange.getRequestHeaders(); String origin = headers.getFirst("Origin"); if (origin == null) { origin = headers.getFirst("Referer"); } return origin != null ? origin.replaceAll("[\\n\\r]*","") : null; } // Return hostnmae of given address, but only when reverse DNS lookups are allowed private String getHostName(InetSocketAddress address) { return configuration.getAsBoolean(ConfigKey.ALLOW_DNS_REVERSE_LOOKUP) ? address.getHostName() : null; } private JSONAware executeGetRequest(ParsedUri parsedUri) { return requestHandler.handleGetRequest(parsedUri.getUri().toString(),parsedUri.getPathInfo(), parsedUri.getParameterMap()); } private JSONAware executePostRequest(HttpExchange pExchange, ParsedUri pUri) throws MalformedObjectNameException, IOException { String encoding = null; Headers headers = pExchange.getRequestHeaders(); String cType = headers.getFirst("Content-Type"); if (cType != null) { Matcher matcher = contentTypePattern.matcher(cType); if (matcher.matches()) { encoding = matcher.group(1); } } InputStream is = pExchange.getRequestBody(); return requestHandler.handlePostRequest(pUri.toString(),is, encoding, pUri.getParameterMap()); } private void performCorsPreflightCheck(HttpExchange pExchange) { Headers requestHeaders = pExchange.getRequestHeaders(); Map<String,String> respHeaders = requestHandler.handleCorsPreflightRequest(requestHeaders.getFirst("Origin"), requestHeaders.getFirst("Access-Control-Request-Headers")); Headers responseHeaders = pExchange.getResponseHeaders(); for (Map.Entry<String,String> entry : respHeaders.entrySet()) { responseHeaders.set(entry.getKey(), entry.getValue()); } } private void setHeaders(HttpExchange pExchange) { String origin = requestHandler.extractCorsOrigin(pExchange.getRequestHeaders().getFirst("Origin")); Headers headers = pExchange.getResponseHeaders(); if (origin != null) { headers.set("Access-Control-Allow-Origin",origin); headers.set("Access-Control-Allow-Credentials","true"); } // Avoid caching at all costs headers.set("Cache-Control", "no-cache"); headers.set("Pragma","no-cache"); // Check for a date header and set it accordingly to the recommendations of // RFC-2616. See also {@link AgentServlet#setNoCacheHeaders()} // Issue: #71 Calendar cal = Calendar.getInstance(); headers.set("Date",formatHeaderDate(cal.getTime())); // 1h in the past since it seems, that some servlet set the date header on their // own so that it cannot be guaranteed that these headers are really equals. // It happened on Tomcat that "Date:" was finally set *before* "Expires:" in the final // answers sometimes which seems to be an implementation peculiarity from Tomcat cal.add(Calendar.HOUR, -1); headers.set("Expires",formatHeaderDate(cal.getTime())); } private void sendForbidden(HttpExchange pExchange, SecurityException securityException) throws IOException { String response = "403 (Forbidden)\n"; if (securityException != null && securityException.getMessage() != null) { response += "\n" + securityException.getMessage() + "\n"; } pExchange.sendResponseHeaders(403, response.length()); OutputStream os = pExchange.getResponseBody(); os.write(response.getBytes()); os.close(); } private void sendResponse(HttpExchange pExchange, ParsedUri pParsedUri, JSONAware pJson) throws IOException { boolean streaming = configuration.getAsBoolean(ConfigKey.STREAMING); if (streaming) { JSONStreamAware jsonStream = (JSONStreamAware)pJson; sendStreamingResponse(pExchange, pParsedUri, jsonStream); } else { // Fallback, send as one object // TODO: Remove for 2.0 sendAllJSON(pExchange, pParsedUri, pJson); } } private void sendStreamingResponse(HttpExchange pExchange, ParsedUri pParsedUri, JSONStreamAware pJson) throws IOException { Headers headers = pExchange.getResponseHeaders(); if (pJson != null) { headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8"); String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()); pExchange.sendResponseHeaders(200, 0); Writer writer = new OutputStreamWriter(pExchange.getResponseBody(), "UTF-8"); IoUtil.streamResponseAndClose(writer, pJson, callback); } else { headers.set("Content-Type", "text/plain"); pExchange.sendResponseHeaders(200,-1); } } private void sendAllJSON(HttpExchange pExchange, ParsedUri pParsedUri, JSONAware pJson) throws IOException { OutputStream out = null; try { Headers headers = pExchange.getResponseHeaders(); if (pJson != null) { headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8"); String json = pJson.toJSONString(); String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()); String content = callback == null ? json : callback + "(" + json + ");"; byte[] response = content.getBytes("UTF8"); pExchange.sendResponseHeaders(200,response.length); out = pExchange.getResponseBody(); out.write(response); } else { headers.set("Content-Type", "text/plain"); pExchange.sendResponseHeaders(200,-1); } } finally { if (out != null) { // Always close in order to finish the request. // Otherwise the thread blocks. out.close(); } } } // Get the proper mime type according to configuration private String getMimeType(ParsedUri pParsedUri) { if (pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()) != null) { return "text/javascript"; } else { String mimeType = pParsedUri.getParameter(ConfigKey.MIME_TYPE.getKeyValue()); if (mimeType != null) { return mimeType; } mimeType = configuration.get(ConfigKey.MIME_TYPE); return mimeType != null ? mimeType : ConfigKey.MIME_TYPE.getDefaultValue(); } } // Creat a log handler from either the given class or by creating a default log handler printing // out to stderr private LogHandler createLogHandler(String pLogHandlerClass, String pDebug) { if (pLogHandlerClass != null) { return ClassUtil.newInstance(pLogHandlerClass); } else { final boolean debug = Boolean.valueOf(pDebug); return new LogHandler.StdoutLogHandler(debug); } } private String formatHeaderDate(Date date) { DateFormat rfc1123Format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); return rfc1123Format.format(date); } }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_24_3
crossvul-java_data_bad_5810_0
/* * Copyright 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.console.ng.ht.client.editors.taskdetailsmulti; import com.github.gwtbootstrap.client.ui.Heading; import javax.enterprise.context.Dependent; import javax.inject.Inject; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.IsWidget; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.enterprise.event.Observes; import org.jbpm.console.ng.ht.client.i18n.Constants; import org.jbpm.console.ng.ht.model.events.TaskSelectionEvent; import org.uberfire.client.annotations.DefaultPosition; import org.uberfire.client.annotations.WorkbenchMenu; import org.uberfire.lifecycle.OnOpen; import org.uberfire.lifecycle.OnStartup; import org.uberfire.client.annotations.WorkbenchPartTitle; import org.uberfire.client.annotations.WorkbenchPartView; import org.uberfire.client.annotations.WorkbenchScreen; import org.uberfire.client.mvp.AbstractWorkbenchScreenActivity; import org.uberfire.client.mvp.Activity; import org.uberfire.client.mvp.ActivityManager; import org.uberfire.client.mvp.PlaceManager; import org.uberfire.client.mvp.UberView; import org.uberfire.client.workbench.widgets.split.WorkbenchSplitLayoutPanel; import org.uberfire.lifecycle.OnClose; import org.uberfire.mvp.Command; import org.uberfire.mvp.PlaceRequest; import org.uberfire.mvp.impl.DefaultPlaceRequest; import org.uberfire.security.Identity; import org.uberfire.workbench.model.Position; import org.uberfire.workbench.model.menu.MenuFactory; import org.uberfire.workbench.model.menu.Menus; @Dependent @WorkbenchScreen(identifier = "Task Details Multi") public class TaskDetailsMultiPresenter { private Constants constants = GWT.create(Constants.class); @Inject private ActivityManager activityManager; @Inject private PlaceManager placeManager; private long selectedTaskId = 0; private String selectedTaskName = ""; public interface TaskDetailsMultiView extends UberView<TaskDetailsMultiPresenter> { void displayNotification(String text); Heading getTaskIdAndName(); HTMLPanel getContent(); } @Inject Identity identity; @Inject public TaskDetailsMultiView view; private Menus menus; private PlaceRequest place; private Map<String, AbstractWorkbenchScreenActivity> activitiesMap = new HashMap<String, AbstractWorkbenchScreenActivity>(4); public TaskDetailsMultiPresenter() { makeMenuBar(); } @WorkbenchPartView public UberView<TaskDetailsMultiPresenter> getView() { return view; } @DefaultPosition public Position getPosition(){ return Position.EAST; } @OnStartup public void onStartup(final PlaceRequest place) { this.place = place; } @WorkbenchPartTitle public String getTitle() { return constants.Details(); } @OnOpen public void onOpen() { WorkbenchSplitLayoutPanel splitPanel = (WorkbenchSplitLayoutPanel)view.asWidget().getParent().getParent().getParent().getParent() .getParent().getParent().getParent().getParent().getParent().getParent().getParent(); splitPanel.setWidgetMinSize(splitPanel.getWidget(0), 500); } public void onTaskSelectionEvent(@Observes TaskSelectionEvent event){ selectedTaskId = event.getTaskId(); selectedTaskName = event.getTaskName(); view.getTaskIdAndName().setText(String.valueOf(selectedTaskId) + " - "+selectedTaskName); view.getContent().clear(); String placeToGo; if(event.getPlace() != null && !event.getPlace().equals("")){ placeToGo = event.getPlace(); }else{ placeToGo = "Task Details"; } DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo); //Set Parameters here: defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId)); defaultPlaceRequest.addParameter("taskName", selectedTaskName); Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest); AbstractWorkbenchScreenActivity activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next()); activitiesMap.put(placeToGo, activity); IsWidget widget = activity.getWidget(); activity.launch(place, null); activity.onStartup(defaultPlaceRequest); view.getContent().add(widget); activity.onOpen(); } @WorkbenchMenu public Menus getMenus() { return menus; } private void makeMenuBar() { menus = MenuFactory .newTopLevelMenu(constants.Work()) .respondsWith(new Command() { @Override public void execute() { view.getContent().clear(); String placeToGo = "Form Display"; DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo); //Set Parameters here: defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId)); defaultPlaceRequest.addParameter("taskName", selectedTaskName); AbstractWorkbenchScreenActivity activity = null; if(activitiesMap.get(placeToGo) == null){ Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest); activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next()); }else{ activity = activitiesMap.get(placeToGo); } IsWidget widget = activity.getWidget(); activity.launch(place, null); activity.onStartup(defaultPlaceRequest); view.getContent().add(widget); activity.onOpen(); } }) .endMenu() .newTopLevelMenu(constants.Details()) .respondsWith(new Command() { @Override public void execute() { view.getContent().clear(); String placeToGo = "Task Details"; DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo); //Set Parameters here: defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId)); defaultPlaceRequest.addParameter("taskName", selectedTaskName); AbstractWorkbenchScreenActivity activity = null; if(activitiesMap.get(placeToGo) == null){ Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest); activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next()); }else{ activity = activitiesMap.get(placeToGo); } IsWidget widget = activity.getWidget(); activity.launch(place, null); activity.onStartup(defaultPlaceRequest); view.getContent().add(widget); activity.onOpen(); } }) .endMenu() .newTopLevelMenu(constants.Assignments()) .respondsWith(new Command() { @Override public void execute() { view.getContent().clear(); String placeToGo = "Task Assignments"; DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo); //Set Parameters here: defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId)); defaultPlaceRequest.addParameter("taskName", selectedTaskName); AbstractWorkbenchScreenActivity activity = null; if(activitiesMap.get(placeToGo) == null){ Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest); activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next()); }else{ activity = activitiesMap.get(placeToGo); } IsWidget widget = activity.getWidget(); activity.launch(place, null); activity.onStartup(defaultPlaceRequest); view.getContent().add(widget); activity.onOpen(); } }) .endMenu() .newTopLevelMenu(constants.Comments()) .respondsWith(new Command() { @Override public void execute() { view.getContent().clear(); String placeToGo = "Task Comments"; DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo); //Set Parameters here: defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId)); defaultPlaceRequest.addParameter("taskName", selectedTaskName); AbstractWorkbenchScreenActivity activity = null; if(activitiesMap.get(placeToGo) == null){ Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest); activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next()); }else{ activity = activitiesMap.get(placeToGo); } IsWidget widget = activity.getWidget(); activity.launch(place, null); activity.onStartup(defaultPlaceRequest); view.getContent().add(widget); activity.onOpen(); } }) .endMenu() .build(); } @OnClose public void onClose(){ for(String activityId : activitiesMap.keySet()){ activitiesMap.get(activityId).onClose(); } activitiesMap.clear(); } }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_5810_0
crossvul-java_data_bad_1164_0
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package com.sun.faces.context; import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_EXECUTE_PARAM; import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RENDER_PARAM; import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RESET_VALUES_PARAM; import static javax.faces.FactoryFinder.VISIT_CONTEXT_FACTORY; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.application.ResourceHandler; import javax.faces.component.NamingContainer; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import javax.faces.component.visit.VisitCallback; import javax.faces.component.visit.VisitContext; import javax.faces.component.visit.VisitContextFactory; import javax.faces.component.visit.VisitContextWrapper; import javax.faces.component.visit.VisitHint; import javax.faces.component.visit.VisitResult; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.PartialResponseWriter; import javax.faces.context.PartialViewContext; import javax.faces.context.ResponseWriter; import javax.faces.event.PhaseId; import javax.faces.lifecycle.ClientWindow; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import com.sun.faces.RIConstants; import com.sun.faces.component.visit.PartialVisitContext; import com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter; import com.sun.faces.util.FacesLogger; import com.sun.faces.util.HtmlUtils; import com.sun.faces.util.Util; public class PartialViewContextImpl extends PartialViewContext { // Log instance for this class private static Logger LOGGER = FacesLogger.CONTEXT.getLogger(); private boolean released; // BE SURE TO ADD NEW IVARS TO THE RELEASE METHOD private PartialResponseWriter partialResponseWriter; private List<String> executeIds; private Collection<String> renderIds; private List<String> evalScripts; private Boolean ajaxRequest; private Boolean partialRequest; private Boolean renderAll; private FacesContext ctx; private static final String ORIGINAL_WRITER = "com.sun.faces.ORIGINAL_WRITER"; // ----------------------------------------------------------- Constructors public PartialViewContextImpl(FacesContext ctx) { this.ctx = ctx; } // ---------------------------------------------- Methods from PartialViewContext /** * @see javax.faces.context.PartialViewContext#isAjaxRequest() */ @Override public boolean isAjaxRequest() { assertNotReleased(); if (ajaxRequest == null) { ajaxRequest = "partial/ajax".equals(ctx. getExternalContext().getRequestHeaderMap().get("Faces-Request")); if (!ajaxRequest) { ajaxRequest = "partial/ajax".equals(ctx.getExternalContext().getRequestParameterMap(). get("Faces-Request")); } } return ajaxRequest; } /** * @see javax.faces.context.PartialViewContext#isPartialRequest() */ @Override public boolean isPartialRequest() { assertNotReleased(); if (partialRequest == null) { partialRequest = isAjaxRequest() || "partial/process".equals(ctx. getExternalContext().getRequestHeaderMap().get("Faces-Request")); } return partialRequest; } /** * @see javax.faces.context.PartialViewContext#isExecuteAll() */ @Override public boolean isExecuteAll() { assertNotReleased(); String execute = PARTIAL_EXECUTE_PARAM.getValue(ctx); return (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(execute)); } /** * @see javax.faces.context.PartialViewContext#isRenderAll() */ @Override public boolean isRenderAll() { assertNotReleased(); if (renderAll == null) { String render = PARTIAL_RENDER_PARAM.getValue(ctx); renderAll = (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(render)); } return renderAll; } /** * @see javax.faces.context.PartialViewContext#setRenderAll(boolean) */ @Override public void setRenderAll(boolean renderAll) { this.renderAll = renderAll; } @Override public boolean isResetValues() { Object value = PARTIAL_RESET_VALUES_PARAM.getValue(ctx); return (null != value && "true".equals(value)) ? true : false; } @Override public void setPartialRequest(boolean isPartialRequest) { this.partialRequest = isPartialRequest; } /** * @see javax.faces.context.PartialViewContext#getExecuteIds() */ @Override public Collection<String> getExecuteIds() { assertNotReleased(); if (executeIds != null) { return executeIds; } executeIds = populatePhaseClientIds(PARTIAL_EXECUTE_PARAM); // include the view parameter facet ID if there are other execute IDs // to process if (!executeIds.isEmpty()) { UIViewRoot root = ctx.getViewRoot(); if (root.getFacetCount() > 0) { if (root.getFacet(UIViewRoot.METADATA_FACET_NAME) != null) { executeIds.add(0, UIViewRoot.METADATA_FACET_NAME); } } } return executeIds; } /** * @see javax.faces.context.PartialViewContext#getRenderIds() */ @Override public Collection<String> getRenderIds() { assertNotReleased(); if (renderIds != null) { return renderIds; } renderIds = populatePhaseClientIds(PARTIAL_RENDER_PARAM); return renderIds; } /** * @see javax.faces.context.PartialViewContext#getEvalScripts() */ @Override public List<String> getEvalScripts() { assertNotReleased(); if (evalScripts == null) { evalScripts = new ArrayList<>(1); } return evalScripts; } /** * @see PartialViewContext#processPartial(javax.faces.event.PhaseId) */ @Override public void processPartial(PhaseId phaseId) { PartialViewContext pvc = ctx.getPartialViewContext(); Collection <String> myExecuteIds = pvc.getExecuteIds(); Collection <String> myRenderIds = pvc.getRenderIds(); UIViewRoot viewRoot = ctx.getViewRoot(); if (phaseId == PhaseId.APPLY_REQUEST_VALUES || phaseId == PhaseId.PROCESS_VALIDATIONS || phaseId == PhaseId.UPDATE_MODEL_VALUES) { // Skip this processing if "none" is specified in the render list, // or there were no execute phase client ids. if (myExecuteIds == null || myExecuteIds.isEmpty()) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "No execute and render identifiers specified. Skipping component processing."); } return; } try { processComponents(viewRoot, phaseId, myExecuteIds, ctx); } catch (Exception e) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, e.toString(), e); } throw new FacesException(e); } // If we have just finished APPLY_REQUEST_VALUES phase, install the // partial response writer. We want to make sure that any content // or errors generated in the other phases are written using the // partial response writer. // if (phaseId == PhaseId.APPLY_REQUEST_VALUES) { PartialResponseWriter writer = pvc.getPartialResponseWriter(); ctx.setResponseWriter(writer); } } else if (phaseId == PhaseId.RENDER_RESPONSE) { try { // // We re-enable response writing. // PartialResponseWriter writer = pvc.getPartialResponseWriter(); ResponseWriter orig = ctx.getResponseWriter(); ctx.getAttributes().put(ORIGINAL_WRITER, orig); ctx.setResponseWriter(writer); ExternalContext exContext = ctx.getExternalContext(); exContext.setResponseContentType(RIConstants.TEXT_XML_CONTENT_TYPE); exContext.addResponseHeader("Cache-Control", "no-cache"); // String encoding = writer.getCharacterEncoding( ); // if( encoding == null ) { // encoding = "UTF-8"; // } // writer.writePreamble("<?xml version='1.0' encoding='" + encoding + "'?>\n"); writer.startDocument(); if (isResetValues()) { viewRoot.resetValues(ctx, myRenderIds); } if (isRenderAll()) { renderAll(ctx, viewRoot); renderState(ctx); writer.endDocument(); return; } renderComponentResources(ctx, viewRoot); // Skip this processing if "none" is specified in the render list, // or there were no render phase client ids. if (myRenderIds != null && !myRenderIds.isEmpty()) { processComponents(viewRoot, phaseId, myRenderIds, ctx); } renderState(ctx); renderEvalScripts(ctx); writer.endDocument(); } catch (IOException ex) { this.cleanupAfterView(); } catch (RuntimeException ex) { this.cleanupAfterView(); // Throw the exception throw ex; } } } /** * @see javax.faces.context.PartialViewContext#getPartialResponseWriter() */ @Override public PartialResponseWriter getPartialResponseWriter() { assertNotReleased(); if (partialResponseWriter == null) { partialResponseWriter = new DelayedInitPartialResponseWriter(this); } return partialResponseWriter; } /** * @see javax.faces.context.PartialViewContext#release() */ @Override public void release() { released = true; ajaxRequest = null; renderAll = null; partialResponseWriter = null; executeIds = null; renderIds = null; evalScripts = null; ctx = null; partialRequest = null; } // -------------------------------------------------------- Private Methods private List<String> populatePhaseClientIds(PredefinedPostbackParameter parameterName) { String param = parameterName.getValue(ctx); if (param == null) { return new ArrayList<>(); } else { Map<String, Object> appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap(); String[] pcs = Util.split(appMap, param, "[ \t]+"); return ((pcs != null && pcs.length != 0) ? new ArrayList<>(Arrays.asList(pcs)) : new ArrayList<>()); } } // Process the components specified in the phaseClientIds list private void processComponents(UIComponent component, PhaseId phaseId, Collection<String> phaseClientIds, FacesContext context) throws IOException { // We use the tree visitor mechanism to locate the components to // process. Create our (partial) VisitContext and the // VisitCallback that will be invoked for each component that // is visited. Note that we use the SKIP_UNRENDERED hint as we // only want to visit the rendered subtree. EnumSet<VisitHint> hints = EnumSet.of(VisitHint.SKIP_UNRENDERED, VisitHint.EXECUTE_LIFECYCLE); VisitContextFactory visitContextFactory = (VisitContextFactory) FactoryFinder.getFactory(VISIT_CONTEXT_FACTORY); VisitContext visitContext = visitContextFactory.getVisitContext(context, phaseClientIds, hints); PhaseAwareVisitCallback visitCallback = new PhaseAwareVisitCallback(ctx, phaseId); component.visitTree(visitContext, visitCallback); PartialVisitContext partialVisitContext = unwrapPartialVisitContext(visitContext); if (partialVisitContext != null) { if (LOGGER.isLoggable(Level.FINER) && !partialVisitContext.getUnvisitedClientIds().isEmpty()) { Collection<String> unvisitedClientIds = partialVisitContext.getUnvisitedClientIds(); StringBuilder builder = new StringBuilder(); for (String cur : unvisitedClientIds) { builder.append(cur).append(" "); } LOGGER.log(Level.FINER, "jsf.context.partial_visit_context_unvisited_children", new Object[]{builder.toString()}); } } } /** * Unwraps {@link PartialVisitContext} from a chain of {@link VisitContextWrapper}s. * * If no {@link PartialVisitContext} is found in the chain, null is returned instead. * * @param visitContext the visit context. * @return the (unwrapped) partial visit context. */ private static PartialVisitContext unwrapPartialVisitContext(VisitContext visitContext) { if (visitContext == null) { return null; } if (visitContext instanceof PartialVisitContext) { return (PartialVisitContext) visitContext; } if (visitContext instanceof VisitContextWrapper) { return unwrapPartialVisitContext(((VisitContextWrapper) visitContext).getWrapped()); } return null; } private void renderAll(FacesContext context, UIViewRoot viewRoot) throws IOException { // If this is a "render all via ajax" request, // make sure to wrap the entire page in a <render> elemnt // with the special viewStateId of VIEW_ROOT_ID. This is how the client // JavaScript knows how to replace the entire document with // this response. PartialViewContext pvc = context.getPartialViewContext(); PartialResponseWriter writer = pvc.getPartialResponseWriter(); if (!(viewRoot instanceof NamingContainer)) { writer.startUpdate(PartialResponseWriter.RENDER_ALL_MARKER); if (viewRoot.getChildCount() > 0) { for (UIComponent uiComponent : viewRoot.getChildren()) { uiComponent.encodeAll(context); } } writer.endUpdate(); } else { /* * If we have a portlet request, start rendering at the view root. */ writer.startUpdate(viewRoot.getClientId(context)); viewRoot.encodeBegin(context); if (viewRoot.getChildCount() > 0) { for (UIComponent uiComponent : viewRoot.getChildren()) { uiComponent.encodeAll(context); } } viewRoot.encodeEnd(context); writer.endUpdate(); } } private void renderComponentResources(FacesContext context, UIViewRoot viewRoot) throws IOException { ResourceHandler resourceHandler = context.getApplication().getResourceHandler(); PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter(); boolean updateStarted = false; for (UIComponent resource : viewRoot.getComponentResources(context)) { String name = (String) resource.getAttributes().get("name"); String library = (String) resource.getAttributes().get("library"); if (resource.getChildCount() == 0 && resourceHandler.getRendererTypeForResourceName(name) != null && !resourceHandler.isResourceRendered(context, name, library)) { if (!updateStarted) { writer.startUpdate("javax.faces.Resource"); updateStarted = true; } resource.encodeAll(context); } } if (updateStarted) { writer.endUpdate(); } } private void renderState(FacesContext context) throws IOException { // Get the view state and write it to the response.. PartialViewContext pvc = context.getPartialViewContext(); PartialResponseWriter writer = pvc.getPartialResponseWriter(); String viewStateId = Util.getViewStateId(context); writer.startUpdate(viewStateId); String state = context.getApplication().getStateManager().getViewState(context); writer.write(state); writer.endUpdate(); ClientWindow window = context.getExternalContext().getClientWindow(); if (null != window) { String clientWindowId = Util.getClientWindowId(context); writer.startUpdate(clientWindowId); writer.write(window.getId()); writer.endUpdate(); } } private void renderEvalScripts(FacesContext context) throws IOException { PartialViewContext pvc = context.getPartialViewContext(); PartialResponseWriter writer = pvc.getPartialResponseWriter(); for (String evalScript : pvc.getEvalScripts()) { writer.startEval(); writer.write(evalScript); writer.endEval(); } } private PartialResponseWriter createPartialResponseWriter() { ExternalContext extContext = ctx.getExternalContext(); String encoding = extContext.getRequestCharacterEncoding(); extContext.setResponseCharacterEncoding(encoding); ResponseWriter responseWriter = null; Writer out = null; try { out = extContext.getResponseOutputWriter(); } catch (IOException ioe) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, ioe.toString(), ioe); } } if (out != null) { UIViewRoot viewRoot = ctx.getViewRoot(); if (viewRoot != null) { responseWriter = ctx.getRenderKit().createResponseWriter(out, RIConstants.TEXT_XML_CONTENT_TYPE, encoding); } else { RenderKitFactory factory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = factory.getRenderKit(ctx, RenderKitFactory.HTML_BASIC_RENDER_KIT); responseWriter = renderKit.createResponseWriter(out, RIConstants.TEXT_XML_CONTENT_TYPE, encoding); } } if (responseWriter instanceof PartialResponseWriter) { return (PartialResponseWriter) responseWriter; } else { return new PartialResponseWriter(responseWriter); } } private void cleanupAfterView() { ResponseWriter orig = (ResponseWriter) ctx.getAttributes(). get(ORIGINAL_WRITER); assert(null != orig); // move aside the PartialResponseWriter ctx.setResponseWriter(orig); } private void assertNotReleased() { if (released) { throw new IllegalStateException(); } } // ----------------------------------------------------------- Inner Classes private static class PhaseAwareVisitCallback implements VisitCallback { private PhaseId curPhase; private FacesContext ctx; private PhaseAwareVisitCallback(FacesContext ctx, PhaseId curPhase) { this.ctx = ctx; this.curPhase = curPhase; } @Override public VisitResult visit(VisitContext context, UIComponent comp) { try { if (curPhase == PhaseId.APPLY_REQUEST_VALUES) { // RELEASE_PENDING handle immediate request(s) // If the user requested an immediate request // Make sure to set the immediate flag here. comp.processDecodes(ctx); } else if (curPhase == PhaseId.PROCESS_VALIDATIONS) { comp.processValidators(ctx); } else if (curPhase == PhaseId.UPDATE_MODEL_VALUES) { comp.processUpdates(ctx); } else if (curPhase == PhaseId.RENDER_RESPONSE) { PartialResponseWriter writer = ctx.getPartialViewContext().getPartialResponseWriter(); writer.startUpdate(comp.getClientId(ctx)); // do the default behavior... comp.encodeAll(ctx); writer.endUpdate(); } else { throw new IllegalStateException("I18N: Unexpected " + "PhaseId passed to " + " PhaseAwareContextCallback: " + curPhase.toString()); } } catch (IOException ex) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(ex.toString()); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, ex.toString(), ex); } throw new FacesException(ex); } // Once we visit a component, there is no need to visit // its children, since processDecodes/Validators/Updates and // encodeAll() already traverse the subtree. We return // VisitResult.REJECT to supress the subtree visit. return VisitResult.REJECT; } } /** * Delays the actual construction of the PartialResponseWriter <em>until</em> * content is going to actually be written. */ private static final class DelayedInitPartialResponseWriter extends PartialResponseWriter { private ResponseWriter writer; private PartialViewContextImpl ctx; // -------------------------------------------------------- Constructors public DelayedInitPartialResponseWriter(PartialViewContextImpl ctx) { super(null); this.ctx = ctx; ExternalContext extCtx = ctx.ctx.getExternalContext(); extCtx.setResponseContentType(RIConstants.TEXT_XML_CONTENT_TYPE); extCtx.setResponseCharacterEncoding(extCtx.getRequestCharacterEncoding()); extCtx.setResponseBufferSize(ctx.ctx.getExternalContext().getResponseBufferSize()); } // ---------------------------------- Methods from PartialResponseWriter @Override public void write(String text) throws IOException { HtmlUtils.writeUnescapedTextForXML(getWrapped(), text); } @Override public ResponseWriter getWrapped() { if (writer == null) { writer = ctx.createPartialResponseWriter(); } return writer; } } // END DelayedInitPartialResponseWriter }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_1164_0
crossvul-java_data_good_1165_0
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 1997-2016 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package com.sun.faces.context; import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_EXECUTE_PARAM; import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RENDER_PARAM; import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RESET_VALUES_PARAM; import static javax.faces.FactoryFinder.VISIT_CONTEXT_FACTORY; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.application.ResourceHandler; import javax.faces.component.NamingContainer; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import javax.faces.component.visit.VisitCallback; import javax.faces.component.visit.VisitContext; import javax.faces.component.visit.VisitContextFactory; import javax.faces.component.visit.VisitContextWrapper; import javax.faces.component.visit.VisitHint; import javax.faces.component.visit.VisitResult; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.PartialResponseWriter; import javax.faces.context.PartialViewContext; import javax.faces.context.ResponseWriter; import javax.faces.event.PhaseId; import javax.faces.lifecycle.ClientWindow; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import com.sun.faces.component.visit.PartialVisitContext; import com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter; import com.sun.faces.util.FacesLogger; import com.sun.faces.util.HtmlUtils; import com.sun.faces.util.Util; public class PartialViewContextImpl extends PartialViewContext { // Log instance for this class private static Logger LOGGER = FacesLogger.CONTEXT.getLogger(); private boolean released; // BE SURE TO ADD NEW IVARS TO THE RELEASE METHOD private PartialResponseWriter partialResponseWriter; private List<String> executeIds; private Collection<String> renderIds; private List<String> evalScripts; private Boolean ajaxRequest; private Boolean partialRequest; private Boolean renderAll; private FacesContext ctx; private static final String ORIGINAL_WRITER = "com.sun.faces.ORIGINAL_WRITER"; // ----------------------------------------------------------- Constructors public PartialViewContextImpl(FacesContext ctx) { this.ctx = ctx; } // ---------------------------------------------- Methods from PartialViewContext /** * @see javax.faces.context.PartialViewContext#isAjaxRequest() */ @Override public boolean isAjaxRequest() { assertNotReleased(); if (ajaxRequest == null) { ajaxRequest = "partial/ajax".equals(ctx. getExternalContext().getRequestHeaderMap().get("Faces-Request")); if (!ajaxRequest) { ajaxRequest = "partial/ajax".equals(ctx.getExternalContext().getRequestParameterMap(). get("Faces-Request")); } } return ajaxRequest; } /** * @see javax.faces.context.PartialViewContext#isPartialRequest() */ @Override public boolean isPartialRequest() { assertNotReleased(); if (partialRequest == null) { partialRequest = isAjaxRequest() || "partial/process".equals(ctx. getExternalContext().getRequestHeaderMap().get("Faces-Request")); } return partialRequest; } /** * @see javax.faces.context.PartialViewContext#isExecuteAll() */ @Override public boolean isExecuteAll() { assertNotReleased(); String execute = PARTIAL_EXECUTE_PARAM.getValue(ctx); return (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(execute)); } /** * @see javax.faces.context.PartialViewContext#isRenderAll() */ @Override public boolean isRenderAll() { assertNotReleased(); if (renderAll == null) { String render = PARTIAL_RENDER_PARAM.getValue(ctx); renderAll = (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(render)); } return renderAll; } /** * @see javax.faces.context.PartialViewContext#setRenderAll(boolean) */ @Override public void setRenderAll(boolean renderAll) { this.renderAll = renderAll; } @Override public boolean isResetValues() { Object value = PARTIAL_RESET_VALUES_PARAM.getValue(ctx); return (null != value && "true".equals(value)) ? true : false; } @Override public void setPartialRequest(boolean isPartialRequest) { this.partialRequest = isPartialRequest; } /** * @see javax.faces.context.PartialViewContext#getExecuteIds() */ @Override public Collection<String> getExecuteIds() { assertNotReleased(); if (executeIds != null) { return executeIds; } executeIds = populatePhaseClientIds(PARTIAL_EXECUTE_PARAM); // include the view parameter facet ID if there are other execute IDs // to process if (!executeIds.isEmpty()) { UIViewRoot root = ctx.getViewRoot(); if (root.getFacetCount() > 0) { if (root.getFacet(UIViewRoot.METADATA_FACET_NAME) != null) { executeIds.add(0, UIViewRoot.METADATA_FACET_NAME); } } } return executeIds; } /** * @see javax.faces.context.PartialViewContext#getRenderIds() */ @Override public Collection<String> getRenderIds() { assertNotReleased(); if (renderIds != null) { return renderIds; } renderIds = populatePhaseClientIds(PARTIAL_RENDER_PARAM); return renderIds; } /** * @see javax.faces.context.PartialViewContext#getEvalScripts() */ @Override public List<String> getEvalScripts() { assertNotReleased(); if (evalScripts == null) { evalScripts = new ArrayList<>(1); } return evalScripts; } /** * @see PartialViewContext#processPartial(javax.faces.event.PhaseId) */ @Override public void processPartial(PhaseId phaseId) { PartialViewContext pvc = ctx.getPartialViewContext(); Collection <String> myExecuteIds = pvc.getExecuteIds(); Collection <String> myRenderIds = pvc.getRenderIds(); UIViewRoot viewRoot = ctx.getViewRoot(); if (phaseId == PhaseId.APPLY_REQUEST_VALUES || phaseId == PhaseId.PROCESS_VALIDATIONS || phaseId == PhaseId.UPDATE_MODEL_VALUES) { // Skip this processing if "none" is specified in the render list, // or there were no execute phase client ids. if (myExecuteIds == null || myExecuteIds.isEmpty()) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "No execute and render identifiers specified. Skipping component processing."); } return; } try { processComponents(viewRoot, phaseId, myExecuteIds, ctx); } catch (Exception e) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, e.toString(), e); } throw new FacesException(e); } // If we have just finished APPLY_REQUEST_VALUES phase, install the // partial response writer. We want to make sure that any content // or errors generated in the other phases are written using the // partial response writer. // if (phaseId == PhaseId.APPLY_REQUEST_VALUES) { PartialResponseWriter writer = pvc.getPartialResponseWriter(); ctx.setResponseWriter(writer); } } else if (phaseId == PhaseId.RENDER_RESPONSE) { try { // // We re-enable response writing. // PartialResponseWriter writer = pvc.getPartialResponseWriter(); ResponseWriter orig = ctx.getResponseWriter(); ctx.getAttributes().put(ORIGINAL_WRITER, orig); ctx.setResponseWriter(writer); ExternalContext exContext = ctx.getExternalContext(); exContext.setResponseContentType("text/xml"); exContext.addResponseHeader("Cache-Control", "no-cache"); // String encoding = writer.getCharacterEncoding( ); // if( encoding == null ) { // encoding = "UTF-8"; // } // writer.writePreamble("<?xml version='1.0' encoding='" + encoding + "'?>\n"); writer.startDocument(); if (isResetValues()) { viewRoot.resetValues(ctx, myRenderIds); } if (isRenderAll()) { renderAll(ctx, viewRoot); renderState(ctx); writer.endDocument(); return; } renderComponentResources(ctx, viewRoot); // Skip this processing if "none" is specified in the render list, // or there were no render phase client ids. if (myRenderIds != null && !myRenderIds.isEmpty()) { processComponents(viewRoot, phaseId, myRenderIds, ctx); } renderState(ctx); renderEvalScripts(ctx); writer.endDocument(); } catch (IOException ex) { this.cleanupAfterView(); } catch (RuntimeException ex) { this.cleanupAfterView(); // Throw the exception throw ex; } } } /** * @see javax.faces.context.PartialViewContext#getPartialResponseWriter() */ @Override public PartialResponseWriter getPartialResponseWriter() { assertNotReleased(); if (partialResponseWriter == null) { partialResponseWriter = new DelayedInitPartialResponseWriter(this); } return partialResponseWriter; } /** * @see javax.faces.context.PartialViewContext#release() */ @Override public void release() { released = true; ajaxRequest = null; renderAll = null; partialResponseWriter = null; executeIds = null; renderIds = null; evalScripts = null; ctx = null; partialRequest = null; } // -------------------------------------------------------- Private Methods private List<String> populatePhaseClientIds(PredefinedPostbackParameter parameterName) { String param = parameterName.getValue(ctx); if (param == null) { return new ArrayList<>(); } else { Map<String, Object> appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap(); String[] pcs = Util.split(appMap, param, "[ \t]+"); return ((pcs != null && pcs.length != 0) ? new ArrayList<>(Arrays.asList(pcs)) : new ArrayList<>()); } } // Process the components specified in the phaseClientIds list private void processComponents(UIComponent component, PhaseId phaseId, Collection<String> phaseClientIds, FacesContext context) throws IOException { // We use the tree visitor mechanism to locate the components to // process. Create our (partial) VisitContext and the // VisitCallback that will be invoked for each component that // is visited. Note that we use the SKIP_UNRENDERED hint as we // only want to visit the rendered subtree. EnumSet<VisitHint> hints = EnumSet.of(VisitHint.SKIP_UNRENDERED, VisitHint.EXECUTE_LIFECYCLE); VisitContextFactory visitContextFactory = (VisitContextFactory) FactoryFinder.getFactory(VISIT_CONTEXT_FACTORY); VisitContext visitContext = visitContextFactory.getVisitContext(context, phaseClientIds, hints); PhaseAwareVisitCallback visitCallback = new PhaseAwareVisitCallback(ctx, phaseId); component.visitTree(visitContext, visitCallback); PartialVisitContext partialVisitContext = unwrapPartialVisitContext(visitContext); if (partialVisitContext != null) { if (LOGGER.isLoggable(Level.FINER) && !partialVisitContext.getUnvisitedClientIds().isEmpty()) { Collection<String> unvisitedClientIds = partialVisitContext.getUnvisitedClientIds(); StringBuilder builder = new StringBuilder(); for (String cur : unvisitedClientIds) { builder.append(cur).append(" "); } LOGGER.log(Level.FINER, "jsf.context.partial_visit_context_unvisited_children", new Object[]{builder.toString()}); } } } /** * Unwraps {@link PartialVisitContext} from a chain of {@link VisitContextWrapper}s. * * If no {@link PartialVisitContext} is found in the chain, null is returned instead. * * @param visitContext the visit context. * @return the (unwrapped) partial visit context. */ private static PartialVisitContext unwrapPartialVisitContext(VisitContext visitContext) { if (visitContext == null) { return null; } if (visitContext instanceof PartialVisitContext) { return (PartialVisitContext) visitContext; } if (visitContext instanceof VisitContextWrapper) { return unwrapPartialVisitContext(((VisitContextWrapper) visitContext).getWrapped()); } return null; } private void renderAll(FacesContext context, UIViewRoot viewRoot) throws IOException { // If this is a "render all via ajax" request, // make sure to wrap the entire page in a <render> elemnt // with the special viewStateId of VIEW_ROOT_ID. This is how the client // JavaScript knows how to replace the entire document with // this response. PartialViewContext pvc = context.getPartialViewContext(); PartialResponseWriter writer = pvc.getPartialResponseWriter(); if (!(viewRoot instanceof NamingContainer)) { writer.startUpdate(PartialResponseWriter.RENDER_ALL_MARKER); if (viewRoot.getChildCount() > 0) { for (UIComponent uiComponent : viewRoot.getChildren()) { uiComponent.encodeAll(context); } } writer.endUpdate(); } else { /* * If we have a portlet request, start rendering at the view root. */ writer.startUpdate(viewRoot.getClientId(context)); viewRoot.encodeBegin(context); if (viewRoot.getChildCount() > 0) { for (UIComponent uiComponent : viewRoot.getChildren()) { uiComponent.encodeAll(context); } } viewRoot.encodeEnd(context); writer.endUpdate(); } } private void renderComponentResources(FacesContext context, UIViewRoot viewRoot) throws IOException { ResourceHandler resourceHandler = context.getApplication().getResourceHandler(); PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter(); boolean updateStarted = false; for (UIComponent resource : viewRoot.getComponentResources(context)) { String name = (String) resource.getAttributes().get("name"); String library = (String) resource.getAttributes().get("library"); if (resource.getChildCount() == 0 && resourceHandler.getRendererTypeForResourceName(name) != null && !resourceHandler.isResourceRendered(context, name, library)) { if (!updateStarted) { writer.startUpdate("javax.faces.Resource"); updateStarted = true; } resource.encodeAll(context); } } if (updateStarted) { writer.endUpdate(); } } private void renderState(FacesContext context) throws IOException { // Get the view state and write it to the response.. PartialViewContext pvc = context.getPartialViewContext(); PartialResponseWriter writer = pvc.getPartialResponseWriter(); String viewStateId = Util.getViewStateId(context); writer.startUpdate(viewStateId); String state = context.getApplication().getStateManager().getViewState(context); writer.write(state); writer.endUpdate(); ClientWindow window = context.getExternalContext().getClientWindow(); if (null != window) { String clientWindowId = Util.getClientWindowId(context); writer.startUpdate(clientWindowId); writer.writeText(window.getId(), null); writer.endUpdate(); } } private void renderEvalScripts(FacesContext context) throws IOException { PartialViewContext pvc = context.getPartialViewContext(); PartialResponseWriter writer = pvc.getPartialResponseWriter(); for (String evalScript : pvc.getEvalScripts()) { writer.startEval(); writer.write(evalScript); writer.endEval(); } } private PartialResponseWriter createPartialResponseWriter() { ExternalContext extContext = ctx.getExternalContext(); String encoding = extContext.getRequestCharacterEncoding(); extContext.setResponseCharacterEncoding(encoding); ResponseWriter responseWriter = null; Writer out = null; try { out = extContext.getResponseOutputWriter(); } catch (IOException ioe) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, ioe.toString(), ioe); } } if (out != null) { UIViewRoot viewRoot = ctx.getViewRoot(); if (viewRoot != null) { responseWriter = ctx.getRenderKit().createResponseWriter(out, "text/xml", encoding); } else { RenderKitFactory factory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = factory.getRenderKit(ctx, RenderKitFactory.HTML_BASIC_RENDER_KIT); responseWriter = renderKit.createResponseWriter(out, "text/xml", encoding); } } if (responseWriter instanceof PartialResponseWriter) { return (PartialResponseWriter) responseWriter; } else { return new PartialResponseWriter(responseWriter); } } private void cleanupAfterView() { ResponseWriter orig = (ResponseWriter) ctx.getAttributes(). get(ORIGINAL_WRITER); assert(null != orig); // move aside the PartialResponseWriter ctx.setResponseWriter(orig); } private void assertNotReleased() { if (released) { throw new IllegalStateException(); } } // ----------------------------------------------------------- Inner Classes private static class PhaseAwareVisitCallback implements VisitCallback { private PhaseId curPhase; private FacesContext ctx; private PhaseAwareVisitCallback(FacesContext ctx, PhaseId curPhase) { this.ctx = ctx; this.curPhase = curPhase; } @Override public VisitResult visit(VisitContext context, UIComponent comp) { try { if (curPhase == PhaseId.APPLY_REQUEST_VALUES) { // RELEASE_PENDING handle immediate request(s) // If the user requested an immediate request // Make sure to set the immediate flag here. comp.processDecodes(ctx); } else if (curPhase == PhaseId.PROCESS_VALIDATIONS) { comp.processValidators(ctx); } else if (curPhase == PhaseId.UPDATE_MODEL_VALUES) { comp.processUpdates(ctx); } else if (curPhase == PhaseId.RENDER_RESPONSE) { PartialResponseWriter writer = ctx.getPartialViewContext().getPartialResponseWriter(); writer.startUpdate(comp.getClientId(ctx)); // do the default behavior... comp.encodeAll(ctx); writer.endUpdate(); } else { throw new IllegalStateException("I18N: Unexpected " + "PhaseId passed to " + " PhaseAwareContextCallback: " + curPhase.toString()); } } catch (IOException ex) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(ex.toString()); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, ex.toString(), ex); } throw new FacesException(ex); } // Once we visit a component, there is no need to visit // its children, since processDecodes/Validators/Updates and // encodeAll() already traverse the subtree. We return // VisitResult.REJECT to supress the subtree visit. return VisitResult.REJECT; } } /** * Delays the actual construction of the PartialResponseWriter <em>until</em> * content is going to actually be written. */ private static final class DelayedInitPartialResponseWriter extends PartialResponseWriter { private ResponseWriter writer; private PartialViewContextImpl ctx; // -------------------------------------------------------- Constructors public DelayedInitPartialResponseWriter(PartialViewContextImpl ctx) { super(null); this.ctx = ctx; ExternalContext extCtx = ctx.ctx.getExternalContext(); extCtx.setResponseContentType("text/xml"); extCtx.setResponseCharacterEncoding(extCtx.getRequestCharacterEncoding()); extCtx.setResponseBufferSize(ctx.ctx.getExternalContext().getResponseBufferSize()); } // ---------------------------------- Methods from PartialResponseWriter @Override public void write(String text) throws IOException { HtmlUtils.writeUnescapedTextForXML(getWrapped(), text); } @Override public ResponseWriter getWrapped() { if (writer == null) { writer = ctx.createPartialResponseWriter(); } return writer; } } // END DelayedInitPartialResponseWriter }
./CrossVul/dataset_final_sorted/CWE-79/java/good_1165_0
crossvul-java_data_good_24_0
package org.jolokia.http; import java.io.*; import java.net.*; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.*; import javax.management.RuntimeMBeanException; import javax.security.auth.Subject; import javax.servlet.*; import javax.servlet.http.*; import org.jolokia.backend.BackendManager; import org.jolokia.config.*; import org.jolokia.discovery.AgentDetails; import org.jolokia.discovery.DiscoveryMulticastResponder; import org.jolokia.restrictor.*; import org.jolokia.util.*; import org.json.simple.JSONAware; import org.json.simple.JSONStreamAware; /* * Copyright 2009-2013 Roland Huss * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Agent servlet which connects to a local JMX MBeanServer for * JMX operations. * * <p> * It uses a REST based approach which translates a GET Url into a * request. See the <a href="http://www.jolokia.org/reference/index.html">reference documentation</a> * for a detailed description of this servlet's features. * </p> * * @author roland@jolokia.org * @since Apr 18, 2009 */ public class AgentServlet extends HttpServlet { private static final long serialVersionUID = 42L; // POST- and GET- HttpRequestHandler private ServletRequestHandler httpGetHandler, httpPostHandler; // Backend dispatcher private BackendManager backendManager; // Used for logging private LogHandler logHandler; // Request handler for parsing request parameters and building up a response private HttpRequestHandler requestHandler; // Restrictor to use as given in the constructor private Restrictor restrictor; // Mime type used for returning the answer private String configMimeType; // Listen for discovery request (if switched on) private DiscoveryMulticastResponder discoveryMulticastResponder; // whether to allow reverse DNS lookup for checking the remote host private boolean allowDnsReverseLookup; // whether to allow streaming mode for response private boolean streamingEnabled; /** * No argument constructor, used e.g. by an servlet * descriptor when creating the servlet out of web.xml */ public AgentServlet() { this(null); } /** * Constructor taking a restrictor to use * * @param pRestrictor restrictor to use or <code>null</code> if the restrictor * should be created in the default way ({@link RestrictorFactory#createRestrictor(Configuration,LogHandler)}) */ public AgentServlet(Restrictor pRestrictor) { restrictor = pRestrictor; } /** * Get the installed log handler * * @return loghandler used for logging. */ protected LogHandler getLogHandler() { return logHandler; } /** * Initialize the backend systems, the log handler and the restrictor. A subclass can tune * this step by overriding {@link #createRestrictor(Configuration)}} and {@link #createLogHandler(ServletConfig, boolean)} * * @param pServletConfig servlet configuration */ @Override public void init(ServletConfig pServletConfig) throws ServletException { super.init(pServletConfig); Configuration config = initConfig(pServletConfig); // Create a log handler early in the lifecycle, but not too early String logHandlerClass = config.get(ConfigKey.LOGHANDLER_CLASS); logHandler = logHandlerClass != null ? (LogHandler) ClassUtil.newInstance(logHandlerClass) : createLogHandler(pServletConfig,Boolean.valueOf(config.get(ConfigKey.DEBUG))); // Different HTTP request handlers httpGetHandler = newGetHttpRequestHandler(); httpPostHandler = newPostHttpRequestHandler(); if (restrictor == null) { restrictor = createRestrictor(config); } else { logHandler.info("Using custom access restriction provided by " + restrictor); } configMimeType = config.get(ConfigKey.MIME_TYPE); backendManager = new BackendManager(config,logHandler, restrictor); requestHandler = new HttpRequestHandler(config,backendManager,logHandler); allowDnsReverseLookup = config.getAsBoolean(ConfigKey.ALLOW_DNS_REVERSE_LOOKUP); streamingEnabled = config.getAsBoolean(ConfigKey.STREAMING); initDiscoveryMulticast(config); } /** * Hook for creating an own restrictor * * @param config configuration as given to the servlet * @return return restrictor or null if no restrictor is needed. */ protected Restrictor createRestrictor(Configuration config) { return RestrictorFactory.createRestrictor(config, logHandler); } private void initDiscoveryMulticast(Configuration pConfig) { String url = findAgentUrl(pConfig); if (url != null || listenForDiscoveryMcRequests(pConfig)) { backendManager.getAgentDetails().setUrl(url); try { discoveryMulticastResponder = new DiscoveryMulticastResponder(backendManager,restrictor,logHandler); discoveryMulticastResponder.start(); } catch (IOException e) { logHandler.error("Cannot start discovery multicast handler: " + e,e); } } } // Try to find an URL for system props or config private String findAgentUrl(Configuration pConfig) { // System property has precedence String url = System.getProperty("jolokia." + ConfigKey.DISCOVERY_AGENT_URL.getKeyValue()); if (url == null) { url = System.getenv("JOLOKIA_DISCOVERY_AGENT_URL"); if (url == null) { url = pConfig.get(ConfigKey.DISCOVERY_AGENT_URL); } } return NetworkUtil.replaceExpression(url); } // For war agent needs to be switched on private boolean listenForDiscoveryMcRequests(Configuration pConfig) { // Check for system props, system env and agent config boolean sysProp = System.getProperty("jolokia." + ConfigKey.DISCOVERY_ENABLED.getKeyValue()) != null; boolean env = System.getenv("JOLOKIA_DISCOVERY") != null; boolean config = pConfig.getAsBoolean(ConfigKey.DISCOVERY_ENABLED); return sysProp || env || config; } /** * Create a log handler using this servlet's logging facility for logging. This method can be overridden * to provide a custom log handler. This method is called before {@link RestrictorFactory#createRestrictor(Configuration,LogHandler)} so the log handler * can already be used when building up the restrictor. * * @return a default log handler * @param pServletConfig servlet config from where to get information to build up the log handler * @param pDebug whether to print out debug information. */ protected LogHandler createLogHandler(ServletConfig pServletConfig, final boolean pDebug) { return new LogHandler() { /** {@inheritDoc} */ public void debug(String message) { if (pDebug) { log(message); } } /** {@inheritDoc} */ public void info(String message) { log(message); } /** {@inheritDoc} */ public void error(String message, Throwable t) { log(message,t); } }; } /** {@inheritDoc} */ @Override public void destroy() { backendManager.destroy(); if (discoveryMulticastResponder != null) { discoveryMulticastResponder.stop(); discoveryMulticastResponder = null; } super.destroy(); } /** {@inheritDoc} */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { handle(httpGetHandler, req, resp); } /** {@inheritDoc} */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { handle(httpPostHandler, req, resp); } /** * OPTION requests are treated as CORS preflight requests * * @param req the original request * @param resp the response the answer are written to * */ @Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Map<String,String> responseHeaders = requestHandler.handleCorsPreflightRequest( req.getHeader("Origin"), req.getHeader("Access-Control-Request-Headers")); for (Map.Entry<String,String> entry : responseHeaders.entrySet()) { resp.setHeader(entry.getKey(),entry.getValue()); } } @SuppressWarnings({ "PMD.AvoidCatchingThrowable", "PMD.AvoidInstanceofChecksInCatchClause" }) private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException { JSONAware json = null; try { // Check access policy requestHandler.checkAccess(allowDnsReverseLookup ? pReq.getRemoteHost() : null, pReq.getRemoteAddr(), getOriginOrReferer(pReq)); // If a callback is given, check this is a valid javascript function name validateCallbackIfGiven(pReq); // Remember the agent URL upon the first request. Needed for discovery updateAgentDetailsIfNeeded(pReq); // Dispatch for the proper HTTP request method json = handleSecurely(pReqHandler, pReq, pResp); } catch (Throwable exp) { try { json = requestHandler.handleThrowable( exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp); } catch (Throwable exp2) { exp2.printStackTrace(); } } finally { setCorsHeader(pReq, pResp); if (json == null) { json = requestHandler.handleThrowable(new Exception("Internal error while handling an exception")); } sendResponse(pResp, pReq, json); } } private JSONAware handleSecurely(final ServletRequestHandler pReqHandler, final HttpServletRequest pReq, final HttpServletResponse pResp) throws IOException, PrivilegedActionException { Subject subject = (Subject) pReq.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE); if (subject != null) { return Subject.doAs(subject, new PrivilegedExceptionAction<JSONAware>() { public JSONAware run() throws IOException { return pReqHandler.handleRequest(pReq, pResp); } }); } else { return pReqHandler.handleRequest(pReq, pResp); } } private String getOriginOrReferer(HttpServletRequest pReq) { String origin = pReq.getHeader("Origin"); if (origin == null) { origin = pReq.getHeader("Referer"); } return origin != null ? origin.replaceAll("[\\n\\r]*","") : null; } // Update the agent URL in the agent details if not already done private void updateAgentDetailsIfNeeded(HttpServletRequest pReq) { // Lookup the Agent URL if needed AgentDetails details = backendManager.getAgentDetails(); if (details.isInitRequired()) { synchronized (details) { if (details.isInitRequired()) { if (details.isUrlMissing()) { String url = getBaseUrl(NetworkUtil.sanitizeLocalUrl(pReq.getRequestURL().toString()), extractServletPath(pReq)); details.setUrl(url); } if (details.isSecuredMissing()) { details.setSecured(pReq.getAuthType() != null); } details.seal(); } } } } private String extractServletPath(HttpServletRequest pReq) { return pReq.getRequestURI().substring(0,pReq.getContextPath().length()); } // Strip off everything unneeded private String getBaseUrl(String pUrl, String pServletPath) { String sUrl; try { URL url = new URL(pUrl); String host = getIpIfPossible(url.getHost()); sUrl = new URL(url.getProtocol(),host,url.getPort(),pServletPath).toExternalForm(); } catch (MalformedURLException exp) { sUrl = plainReplacement(pUrl, pServletPath); } return sUrl; } // Check for an IP, since this seems to be safer to return then a plain name private String getIpIfPossible(String pHost) { try { InetAddress address = InetAddress.getByName(pHost); return address.getHostAddress(); } catch (UnknownHostException e) { return pHost; } } // Fallback used if URL creation didnt work private String plainReplacement(String pUrl, String pServletPath) { int idx = pUrl.lastIndexOf(pServletPath); String url; if (idx != -1) { url = pUrl.substring(0,idx) + pServletPath; } else { url = pUrl; } return url; } // Set an appropriate CORS header if requested and if allowed private void setCorsHeader(HttpServletRequest pReq, HttpServletResponse pResp) { String origin = requestHandler.extractCorsOrigin(pReq.getHeader("Origin")); if (origin != null) { pResp.setHeader("Access-Control-Allow-Origin", origin); pResp.setHeader("Access-Control-Allow-Credentials","true"); } } private boolean isStreamingEnabled(HttpServletRequest pReq) { String streamingFromReq = pReq.getParameter(ConfigKey.STREAMING.getKeyValue()); if (streamingFromReq != null) { return Boolean.parseBoolean(streamingFromReq); } return streamingEnabled; } private interface ServletRequestHandler { /** * Handle a request and return the answer as a JSON structure * @param pReq request arrived * @param pResp response to return * @return the JSON representation for the answer * @throws IOException if handling of an input or output stream failed */ JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp) throws IOException; } // factory method for POST request handler private ServletRequestHandler newPostHttpRequestHandler() { return new ServletRequestHandler() { /** {@inheritDoc} */ public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp) throws IOException { String encoding = pReq.getCharacterEncoding(); InputStream is = pReq.getInputStream(); return requestHandler.handlePostRequest(pReq.getRequestURI(),is, encoding, getParameterMap(pReq)); } }; } // factory method for GET request handler private ServletRequestHandler newGetHttpRequestHandler() { return new ServletRequestHandler() { /** {@inheritDoc} */ public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp) { return requestHandler.handleGetRequest(pReq.getRequestURI(),pReq.getPathInfo(), getParameterMap(pReq)); } }; } // ======================================================================= // Get parameter map either directly from an Servlet 2.4 compliant implementation // or by looking it up explictely (thanks to codewax for the patch) private Map<String, String[]> getParameterMap(HttpServletRequest pReq){ try { // Servlet 2.4 API return pReq.getParameterMap(); } catch (UnsupportedOperationException exp) { // Thrown by 'pseudo' 2.4 Servlet API implementations which fake a 2.4 API // As a service for the parameter map is build up explicitely Map<String, String[]> ret = new HashMap<String, String[]>(); Enumeration params = pReq.getParameterNames(); while (params.hasMoreElements()) { String param = (String) params.nextElement(); ret.put(param, pReq.getParameterValues(param)); } return ret; } } // Examines servlet config and servlet context for configuration parameters. // Configuration from the servlet context overrides servlet parameters defined in web.xml Configuration initConfig(ServletConfig pConfig) { Configuration config = new Configuration( ConfigKey.AGENT_ID, NetworkUtil.getAgentId(hashCode(),"servlet")); // From ServletContext .... config.updateGlobalConfiguration(new ServletConfigFacade(pConfig)); // ... and ServletConfig config.updateGlobalConfiguration(new ServletContextFacade(getServletContext())); // Set type last and overwrite anything written config.updateGlobalConfiguration(Collections.singletonMap(ConfigKey.AGENT_TYPE.getKeyValue(),"servlet")); return config; } private void sendResponse(HttpServletResponse pResp, HttpServletRequest pReq, JSONAware pJson) throws IOException { String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue()); setContentType(pResp, MimeTypeUtil.getResponseMimeType( pReq.getParameter(ConfigKey.MIME_TYPE.getKeyValue()), configMimeType, callback )); pResp.setStatus(HttpServletResponse.SC_OK); setNoCacheHeaders(pResp); if (pJson == null) { pResp.setContentLength(-1); } else { if (isStreamingEnabled(pReq)) { sendStreamingResponse(pResp, callback, (JSONStreamAware) pJson); } else { // Fallback, send as one object // TODO: Remove for 2.0 where should support only streaming sendAllJSON(pResp, callback, pJson); } } } private void validateCallbackIfGiven(HttpServletRequest pReq) { String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue()); if (callback != null && !MimeTypeUtil.isValidCallback(callback)) { throw new IllegalArgumentException("Invalid callback name given, which must be a valid javascript function name"); } } private void sendStreamingResponse(HttpServletResponse pResp, String pCallback, JSONStreamAware pJson) throws IOException { Writer writer = new OutputStreamWriter(pResp.getOutputStream(), "UTF-8"); IoUtil.streamResponseAndClose(writer, pJson, pCallback); } private void sendAllJSON(HttpServletResponse pResp, String callback, JSONAware pJson) throws IOException { OutputStream out = null; try { String json = pJson.toJSONString(); String content = callback == null ? json : callback + "(" + json + ");"; byte[] response = content.getBytes("UTF8"); pResp.setContentLength(response.length); out = pResp.getOutputStream(); out.write(response); } finally { if (out != null) { // Always close in order to finish the request. // Otherwise the thread blocks. out.close(); } } } private void setNoCacheHeaders(HttpServletResponse pResp) { pResp.setHeader("Cache-Control", "no-cache"); pResp.setHeader("Pragma","no-cache"); // Check for a date header and set it accordingly to the recommendations of // RFC-2616 (http://tools.ietf.org/html/rfc2616#section-14.21) // // "To mark a response as "already expired," an origin server sends an // Expires date that is equal to the Date header value. (See the rules // for expiration calculations in section 13.2.4.)" // // See also #71 long now = System.currentTimeMillis(); pResp.setDateHeader("Date",now); // 1h in the past since it seems, that some servlet set the date header on their // own so that it cannot be guaranteed that these headers are really equals. // It happened on Tomcat that Date: was finally set *before* Expires: in the final // answers some times which seems to be an implementation peculiarity from Tomcat pResp.setDateHeader("Expires",now - 3600000); } private void setContentType(HttpServletResponse pResp, String pContentType) { boolean encodingDone = false; try { pResp.setCharacterEncoding("utf-8"); pResp.setContentType(pContentType); encodingDone = true; } catch (NoSuchMethodError error) { /* Servlet 2.3 */ } catch (UnsupportedOperationException error) { /* Equinox HTTP Service */ } if (!encodingDone) { // For a Servlet 2.3 container or an Equinox HTTP Service, set the charset by hand pResp.setContentType(pContentType + "; charset=utf-8"); } } // ======================================================================================= // Helper classes for extracting configuration from servlet classes // Implementation for the ServletConfig private static final class ServletConfigFacade implements ConfigExtractor { private final ServletConfig config; private ServletConfigFacade(ServletConfig pConfig) { config = pConfig; } /** {@inheritDoc} */ public Enumeration getNames() { return config.getInitParameterNames(); } /** {@inheritDoc} */ public String getParameter(String pName) { return config.getInitParameter(pName); } } // Implementation for ServletContextFacade private static final class ServletContextFacade implements ConfigExtractor { private final ServletContext servletContext; private ServletContextFacade(ServletContext pServletContext) { servletContext = pServletContext; } /** {@inheritDoc} */ public Enumeration getNames() { return servletContext.getInitParameterNames(); } /** {@inheritDoc} */ public String getParameter(String pName) { return servletContext.getInitParameter(pName); } } }
./CrossVul/dataset_final_sorted/CWE-79/java/good_24_0
crossvul-java_data_good_4516_0
// // $Id$ // From Philippe Le Hegaret (Philippe.Le_Hegaret@sophia.inria.fr) // // (c) COPYRIGHT MIT and INRIA, 1997. // Please first read the full copyright statement in file COPYRIGHT.html package org.w3c.css.css; import org.w3c.css.atrules.css.AtRuleMedia; import org.w3c.css.atrules.css.AtRulePage; import org.w3c.css.parser.AtRule; import org.w3c.css.parser.CssError; import org.w3c.css.parser.CssFouffa; import org.w3c.css.parser.CssParseException; import org.w3c.css.parser.CssSelectors; import org.w3c.css.parser.CssValidatorListener; import org.w3c.css.parser.Errors; import org.w3c.css.parser.analyzer.ParseException; import org.w3c.css.parser.analyzer.TokenMgrError; import org.w3c.css.properties.css.CssProperty; import org.w3c.css.selectors.IdSelector; import org.w3c.css.util.ApplContext; import org.w3c.css.util.CssVersion; import org.w3c.css.util.InvalidParamException; import org.w3c.css.util.Messages; import org.w3c.css.util.Util; import org.w3c.css.util.Warning; import org.w3c.css.util.Warnings; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.net.URL; import java.util.ArrayList; import java.util.StringTokenizer; /** * @version $Revision$ */ public final class StyleSheetParser implements CssValidatorListener, CssParser { private static Constructor co = null; static { try { Class c = java.lang.Exception.class; Class cp[] = {java.lang.Exception.class}; co = c.getDeclaredConstructor(cp); } catch (NoSuchMethodException ex) { co = null; } } CssFouffa cssFouffa; StyleSheet style = new StyleSheet(); public void reInit() { style = new StyleSheet(); } public StyleSheet getStyleSheet() { return style; } public void setWarningLevel(int warningLevel) { style.setWarningLevel(warningLevel); } public void notifyErrors(Errors errors) { style.addErrors(errors); } public void notifyWarnings(Warnings warnings) { style.addWarnings(warnings); } /** * Adds a vector of properties to a selector. * * @param selector the selector * @param properties Properties to associate with contexts */ public void handleRule(ApplContext ac, CssSelectors selector, ArrayList<CssProperty> properties) { if (selector.getAtRule() instanceof AtRulePage) { style.remove(selector); } for (CssProperty property : properties) { property.setSelectors(selector); style.addProperty(selector, property); } } // part added by Sijtsche de Jong public void addCharSet(String charset) { style.addCharSet(charset); } public void newAtRule(AtRule atRule) { style.newAtRule(atRule); } public void endOfAtRule() { style.endOfAtRule(); } public void setImportant(boolean important) { style.setImportant(important); } public void setSelectorList(ArrayList<CssSelectors> selectors) { style.setSelectorList(selectors); } public void setProperty(ArrayList<CssProperty> properties) { style.setProperty(properties); } public void endOfRule() { style.endOfRule(); } public void removeThisRule() { style.removeThisRule(); } public void removeThisAtRule() { style.removeThisAtRule(); } //end of part added by Sijtsche de Jong /** * Handles an at-rule. * <p/> * <p>The parameter <code>value</code> can be : * <DL> * <DT>CssString * <DD>The value coming from a string. * <DT>CssURL * <DD>The value coming from an URL. * <DT>Vector * <DD>The value is a vector of declarations (it contains properties). * This feature is not legal, so be careful. * </DL> * * @param ident The ident for this at-rule (for example: 'font-face') * @param string The string representation if this at-rule */ public void handleAtRule(ApplContext ac, String ident, String string) { style.getWarnings().addWarning(new Warning(cssFouffa.getSourceFile(), cssFouffa.getLine(), "at-rule", 2, new String[]{ident, string}, ac)); //stylesheet.addAtRule(atRule); } /** * @param url the URL containing the style sheet * @param title the title of the stylesheet * @param kind may be a stylesheet or an alternate stylesheet * @param media the media to apply this * @param origin the origin of the style sheet * @throws IOException an IO error */ public void parseURL(ApplContext ac, URL url, String title, String kind, String media, int origin) { boolean doneref = false; URL ref = ac.getReferrer(); setWarningLevel(ac.getWarningLevel()); if (Util.onDebug) { System.err.println("StyleSheet.parseURL(" + url + ", " + title + ", " + kind + ", " + media + ", " + origin + ")"); } if (kind != null) { kind = kind.trim().toLowerCase(); if (!kind.equals("stylesheet") && !kind.equals("alternate stylesheet")) { return; } } try { ac.setOrigin(origin); // if (cssFouffa == null) { cssFouffa = new CssFouffa(ac, url); cssFouffa.addListener(this); // } else { // cssFouffa.ReInit(ac, url); // } // cssFouffa.setResponse(res); // removed plh 2001-03-08 // cssFouffa.setOrigin(origin); // cssFouffa.setDefaultMedium(defaultmedium); // cssFouffa.doConfig(); if (media == null) { if (ac.getCssVersion() != CssVersion.CSS1) { if (ac.getMedium() == null) { media = "all"; } else { media = ac.getMedium(); } } } AtRuleMedia m = AtRuleMedia.getInstance(ac.getCssVersion()); try { if (media != null) { addMedias(m, media, ac); } cssFouffa.setAtRule(m); } catch (org.w3c.css.util.InvalidParamException e) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(url.toString(), -1, e)); notifyErrors(er); return; } ac.setReferrer(url); doneref = true; cssFouffa.parseStyle(); } catch (Exception e) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(Messages.escapeString(url.toString()), -1, new Exception(Messages.escapeString(e.getMessage())))); notifyErrors(er); } finally { if (doneref) { ac.setReferrer(ref); } } } // add media, easy version for CSS version < 3, otherwise, reuse the parser private void addMedias(AtRuleMedia m, String medias, ApplContext ac) throws InvalidParamException { // before CSS3, let's parse it the easy way... if (ac.getCssVersion().compareTo(CssVersion.CSS3) < 0) { StringTokenizer tokens = new StringTokenizer(medias, ","); while (tokens.hasMoreTokens()) { m.addMedia(null, tokens.nextToken().trim(), ac); } } else { CssFouffa muP = new CssFouffa(ac, new StringReader(medias)); try { AtRuleMedia arm = muP.parseMediaDeclaration(); if (arm != null) { m.allMedia = arm.allMedia; } } catch (ParseException pex) { // error already added, so nothing else to do } } } /** * Parse a style element. The Style element always comes from the user * * @param reader the reader containing the style data * @param url the name of the file the style element was read in. * @throws IOException an IO error */ public void parseStyleElement(ApplContext ac, Reader reader, String title, String media, URL url, int lineno) { boolean doneref = false; style.setWarningLevel(ac.getWarningLevel()); if (Util.onDebug) { System.err.println("StyleSheet.parseStyleElement(" + title + ", " + media + ", " + url + "," + lineno + ")"); } URL ref = ac.getReferrer(); try { // if (cssFouffa == null) { String charset = ac.getCharsetForURL(url); cssFouffa = new CssFouffa(ac, reader, url, lineno); cssFouffa.addListener(this); // } else { // cssFouffa.ReInit(ac, input, url, lineno); // } // cssFouffa.setResponse(res); // cssFouffa.setDefaultMedium(defaultmedium); // cssFouffa.doConfig(); if (media == null && ac.getCssVersion() != CssVersion.CSS1) { media = "all"; } AtRuleMedia m = AtRuleMedia.getInstance(ac.getCssVersion()); try { if (media != null) { addMedias(m, media, ac); } cssFouffa.setAtRule(m); } catch (org.w3c.css.util.InvalidParamException e) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(url.toString(), -1, e)); notifyErrors(er); return; } ac.setReferrer(url); doneref = true; cssFouffa.parseStyle(); } catch (IOException e) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(url.toString(), -1, e)); notifyErrors(er); } catch (TokenMgrError e) { Errors er = new Errors(); CssParseException cpe = null; if (co != null) { try { Object o[] = new Object[1]; o[0] = e; Exception new_e = (Exception) co.newInstance(o); cpe = new CssParseException(new_e); } catch (Exception ex) { cpe = null; } } if (cpe == null) { cpe = new CssParseException(new Exception(e.getMessage())); } er.addError(new org.w3c.css.parser.CssError(url.toString(), -1, //e.getErrorLine(), cpe)); notifyErrors(er); } catch (RuntimeException e) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(url.toString(), cssFouffa.getLine(), new CssParseException(e))); notifyErrors(er); } finally { if (doneref) { ac.setReferrer(ref); } } } /** * @param input the inputStream containing the style data * @param url the name of the file the style element was read in. * @throws IOException an IO error * @see #parseStyleElement(ApplContext, InputStream, String, String, URL, int) * @deprecated Replaced by parseStyleElement */ public void parseStyleElement(ApplContext ac, String input, URL url, int lineno) { parseStyleElement(ac, new StringReader(input), null, null, url, lineno); } /** * Parse a style element. The Style element always comes from the user * * @param input the input stream containing the style data * @param url the name of the file the style element was read in. * @throws IOException an IO error */ public void parseStyleElement(ApplContext ac, InputStream input, String title, String media, URL url, int lineno) { InputStreamReader reader = null; String charset = ac.getCharsetForURL(url); try { reader = new InputStreamReader(input, (charset == null) ? "iso-8859-1" : charset); } catch (UnsupportedEncodingException uex) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(url.toString(), -1, uex)); notifyErrors(er); } catch (Exception ex) { // in case of error, ignore it. reader = null; if (Util.onDebug) { System.err.println("Error in StyleSheet.parseStyleElement(" + title + "," + url + "," + lineno + ")"); } } if (reader != null) { parseStyleElement(ac, reader, title, media, url, lineno); } } /** * Unify call to the parser for css doc as a reader. * * @param ac * @param reader * @param docref */ public void parseStyleSheet(ApplContext ac, Reader reader, URL docref) { parseStyleElement(ac, reader, null, null, (docref == null) ? ac.getFakeURL() : docref, 0); } /** * Parse some declarations. All declarations always comes from the user * * @param input the inputStream containing the style data * @param id the uniq id * @param url the URL the style element was read in. * @throws IOException an IO error */ public void parseStyleAttribute(ApplContext ac, InputStream input, String id, URL url, int lineno) { style.setWarningLevel(ac.getWarningLevel()); lineno--; // why ?!?! if (Util.onDebug) { System.err.println("StyleSheet.parseStyleAttribute(" + id + "," + url + "," + lineno + ")"); } try { // if (cssFouffa == null) { String charset = ac.getCharsetForURL(url); cssFouffa = new CssFouffa(ac, input, charset, url, lineno); cssFouffa.addListener(this); // } else // cssFouffa.ReInit(ac, input, url, lineno); CssSelectors selector = new CssSelectors(ac); try { AtRuleMedia media = AtRuleMedia.getInstance(ac.getCssVersion()); if (ac.getCssVersion() != CssVersion.CSS1) { media.addMedia(null, "all", ac); } cssFouffa.setAtRule(media); } catch (InvalidParamException e) { } //ignore try { if (id == null || id.length() == 0) { id = "nullId-" + Long.toHexString(System.currentTimeMillis()); // TODO add an error/warning ? } selector.addId(new IdSelector(id.substring(1))); } catch (InvalidParamException e) { style.removeThisRule(); ac.getFrame().addError(new CssError(e)); } cssFouffa.parseDeclarations(selector); } catch (IOException e) { Errors er = new Errors(); er.addError(new org.w3c.css.parser.CssError(url.toString(), -1, e)); notifyErrors(er); } } /** * @param input the inputStream containing the style data * @param id the uniq id * @param url the name of the file the style element was read in. * @throws IOException an IO error * @see #parseStyleAttribute(ApplContext, InputStream, String, URL, int) * @deprecated Replaced by parseStyleAttribute */ public void parseStyleAttribute(ApplContext ac, String input, String id, URL url, int lineno) { parseStyleAttribute(ac, new ByteArrayInputStream(input.getBytes()), id, url, lineno); } public void setStyle(Class style) { cssFouffa.setStyle(style); } }
./CrossVul/dataset_final_sorted/CWE-79/java/good_4516_0
crossvul-java_data_good_2097_1
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts, * Yahoo!, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.model; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.io.StreamException; import com.thoughtworks.xstream.io.xml.XppDriver; import hudson.DescriptorExtensionList; import hudson.ExtensionPoint; import hudson.Functions; import hudson.Indenter; import hudson.Util; import hudson.model.Descriptor.FormException; import hudson.model.labels.LabelAtomPropertyDescriptor; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.Entry; import hudson.search.CollectionSearchIndex; import hudson.search.SearchIndexBuilder; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.security.Permission; import hudson.security.PermissionGroup; import hudson.security.PermissionScope; import hudson.tasks.UserAvatarResolver; import hudson.util.AlternativeUiTextProvider; import hudson.util.AlternativeUiTextProvider.Message; import hudson.util.DescribableList; import hudson.util.DescriptorList; import hudson.util.FormApply; import hudson.util.IOException2; import hudson.util.RunList; import hudson.util.XStream2; import hudson.views.ListViewColumn; import hudson.widgets.Widget; import jenkins.model.Jenkins; import jenkins.util.ProgressiveRendering; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.WebMethod; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import org.kohsuke.stapler.interceptor.RequirePOST; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static jenkins.model.Jenkins.*; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Encapsulates the rendering of the list of {@link TopLevelItem}s * that {@link Jenkins} owns. * * <p> * This is an extension point in Hudson, allowing different kind of * rendering to be added as plugins. * * <h2>Note for implementors</h2> * <ul> * <li> * {@link View} subtypes need the <tt>newViewDetail.jelly</tt> page, * which is included in the "new view" page. This page should have some * description of what the view is about. * </ul> * * @author Kohsuke Kawaguchi * @see ViewDescriptor * @see ViewGroup */ @ExportedBean public abstract class View extends AbstractModelObject implements AccessControlled, Describable<View>, ExtensionPoint, Saveable { /** * Container of this view. Set right after the construction * and never change thereafter. */ protected /*final*/ ViewGroup owner; /** * Name of this view. */ protected String name; /** * Message displayed in the view page. */ protected String description; /** * If true, only show relevant executors */ protected boolean filterExecutors; /** * If true, only show relevant queue items */ protected boolean filterQueue; protected transient List<Action> transientActions; /** * List of {@link ViewProperty}s configured for this view. * @since 1.406 */ private volatile DescribableList<ViewProperty,ViewPropertyDescriptor> properties = new PropertyList(this); protected View(String name) { this.name = name; } protected View(String name, ViewGroup owner) { this.name = name; this.owner = owner; } /** * Gets all the items in this collection in a read-only view. */ @Exported(name="jobs") public abstract Collection<TopLevelItem> getItems(); /** * Gets the {@link TopLevelItem} of the given name. */ public TopLevelItem getItem(String name) { return getOwnerItemGroup().getItem(name); } /** * Alias for {@link #getItem(String)}. This is the one used in the URL binding. */ public final TopLevelItem getJob(String name) { return getItem(name); } /** * Checks if the job is in this collection. */ public abstract boolean contains(TopLevelItem item); /** * Gets the name of all this collection. * * @see #rename(String) */ @Exported(visibility=2,name="name") public String getViewName() { return name; } /** * Renames this view. */ public void rename(String newName) throws Failure, FormException { if(name.equals(newName)) return; // noop checkGoodName(newName); if(owner.getView(newName)!=null) throw new FormException(Messages.Hudson_ViewAlreadyExists(newName),"name"); String oldName = name; name = newName; owner.onViewRenamed(this,oldName,newName); } /** * Gets the {@link ViewGroup} that this view belongs to. */ public ViewGroup getOwner() { return owner; } /** * Backward-compatible way of getting {@code getOwner().getItemGroup()} */ public ItemGroup<? extends TopLevelItem> getOwnerItemGroup() { try { return _getOwnerItemGroup(); } catch (AbstractMethodError e) { return Hudson.getInstance(); } } /** * A pointless function to work around what appears to be a HotSpot problem. See JENKINS-5756 and bug 6933067 * on BugParade for more details. */ private ItemGroup<? extends TopLevelItem> _getOwnerItemGroup() { return owner.getItemGroup(); } public View getOwnerPrimaryView() { try { return _getOwnerPrimaryView(); } catch (AbstractMethodError e) { return null; } } private View _getOwnerPrimaryView() { return owner.getPrimaryView(); } public List<Action> getOwnerViewActions() { try { return _getOwnerViewActions(); } catch (AbstractMethodError e) { return Hudson.getInstance().getActions(); } } private List<Action> _getOwnerViewActions() { return owner.getViewActions(); } /** * Message displayed in the top page. Can be null. Includes HTML. */ @Exported public String getDescription() { return description; } /** * Gets the view properties configured for this view. * @since 1.406 */ public DescribableList<ViewProperty,ViewPropertyDescriptor> getProperties() { // readResolve was the best place to do this, but for compatibility reasons, // this class can no longer have readResolve() (the mechanism itself isn't suitable for class hierarchy) // see JENKINS-9431 // // until we have that, putting this logic here. synchronized (PropertyList.class) { if (properties == null) { properties = new PropertyList(this); } else { properties.setOwner(this); } return properties; } } /** * Returns all the {@link LabelAtomPropertyDescriptor}s that can be potentially configured * on this label. */ public List<ViewPropertyDescriptor> getApplicablePropertyDescriptors() { List<ViewPropertyDescriptor> r = new ArrayList<ViewPropertyDescriptor>(); for (ViewPropertyDescriptor pd : ViewProperty.all()) { if (pd.isEnabledFor(this)) r.add(pd); } return r; } public void save() throws IOException { // persistence is a part of the owner // due to initialization timing issue, it can be null when this method is called if (owner != null) { owner.save(); } } /** * List of all {@link ViewProperty}s exposed primarily for the remoting API. * @since 1.406 */ @Exported(name="property",inline=true) public List<ViewProperty> getAllProperties() { return getProperties().toList(); } public ViewDescriptor getDescriptor() { return (ViewDescriptor) Jenkins.getInstance().getDescriptorOrDie(getClass()); } public String getDisplayName() { return getViewName(); } public String getNewPronoun() { return AlternativeUiTextProvider.get(NEW_PRONOUN, this, Messages.AbstractItem_Pronoun()); } /** * By default, return true to render the "Edit view" link on the page. * This method is really just for the default "All" view to hide the edit link * so that the default Hudson top page remains the same as before 1.316. * * @since 1.316 */ public boolean isEditable() { return true; } /** * If true, only show relevant executors */ public boolean isFilterExecutors() { return filterExecutors; } /** * If true, only show relevant queue items */ public boolean isFilterQueue() { return filterQueue; } /** * Gets the {@link Widget}s registered on this object. * * <p> * For now, this just returns the widgets registered to Hudson. */ public List<Widget> getWidgets() { return Collections.unmodifiableList(Jenkins.getInstance().getWidgets()); } /** * If this view uses &lt;t:projectView> for rendering, this method returns columns to be displayed. */ public Iterable<? extends ListViewColumn> getColumns() { return ListViewColumn.createDefaultInitialColumnList(); } /** * If this view uses &lt;t:projectView> for rendering, this method returns the indenter used * to indent each row. */ public Indenter getIndenter() { return null; } /** * If true, this is a view that renders the top page of Hudson. */ public boolean isDefault() { return getOwnerPrimaryView()==this; } public List<Computer> getComputers() { Computer[] computers = Jenkins.getInstance().getComputers(); if (!isFilterExecutors()) { return Arrays.asList(computers); } List<Computer> result = new ArrayList<Computer>(); HashSet<Label> labels = new HashSet<Label>(); for (Item item : getItems()) { if (item instanceof AbstractProject<?, ?>) { labels.addAll(((AbstractProject<?, ?>) item).getRelevantLabels()); } } for (Computer c : computers) { Node n = c.getNode(); if (n != null) { if (labels.contains(null) && n.getMode() == Mode.NORMAL || !isDisjoint(n.getAssignedLabels(), labels)) { result.add(c); } } } return result; } private boolean isDisjoint(Collection c1, Collection c2) { for (Object o : c1) if (c2.contains(o)) return false; return true; } private List<Queue.Item> filterQueue(List<Queue.Item> base) { if (!isFilterQueue()) { return base; } Collection<TopLevelItem> items = getItems(); List<Queue.Item> result = new ArrayList<Queue.Item>(); for (Queue.Item qi : base) { if (items.contains(qi.task)) { result.add(qi); } else if (qi.task instanceof AbstractProject<?, ?>) { AbstractProject<?,?> project = (AbstractProject<?, ?>) qi.task; if (items.contains(project.getRootProject())) { result.add(qi); } } } return result; } public List<Queue.Item> getQueueItems() { return filterQueue(Arrays.asList(Jenkins.getInstance().getQueue().getItems())); } public List<Queue.Item> getApproximateQueueItemsQuickly() { return filterQueue(Jenkins.getInstance().getQueue().getApproximateItemsQuickly()); } /** * Returns the path relative to the context root. * * Doesn't start with '/' but ends with '/' (except returns * empty string when this is the default view). */ public String getUrl() { return isDefault() ? (owner!=null ? owner.getUrl() : "") : getViewUrl(); } /** * Same as {@link #getUrl()} except this returns a view/{name} path * even for the default view. */ public String getViewUrl() { return (owner!=null ? owner.getUrl() : "") + "view/" + Util.rawEncode(getViewName()) + '/'; } public String getSearchUrl() { return getUrl(); } /** * Returns the transient {@link Action}s associated with the top page. * * <p> * If views don't want to show top-level actions, this method * can be overridden to return different objects. * * @see Jenkins#getActions() */ public List<Action> getActions() { List<Action> result = new ArrayList<Action>(); result.addAll(getOwnerViewActions()); synchronized (this) { if (transientActions == null) { updateTransientActions(); } result.addAll(transientActions); } return result; } public synchronized void updateTransientActions() { transientActions = TransientViewActionFactory.createAllFor(this); } public Object getDynamic(String token) { for (Action a : getActions()) { String url = a.getUrlName(); if (url==null) continue; if(a.getUrlName().equals(token)) return a; } return null; } /** * Gets the absolute URL of this view. */ @Exported(visibility=2,name="url") public String getAbsoluteUrl() { return Jenkins.getInstance().getRootUrl()+getUrl(); } public Api getApi() { return new Api(this); } /** * Returns the page to redirect the user to, after the view is created. * * The returned string is appended to "/view/foobar/", so for example * to direct the user to the top page of the view, return "", etc. */ public String getPostConstructLandingPage() { return "configure"; } /** * Returns the {@link ACL} for this object. */ public ACL getACL() { return Jenkins.getInstance().getAuthorizationStrategy().getACL(this); } public void checkPermission(Permission p) { getACL().checkPermission(p); } public boolean hasPermission(Permission p) { return getACL().hasPermission(p); } /** * Called when a job name is changed or deleted. * * <p> * If this view contains this job, it should update the view membership so that * the renamed job will remain in the view, and the deleted job is removed. * * @param item * The item whose name is being changed. * @param oldName * Old name of the item. Always non-null. * @param newName * New name of the item, if the item is renamed. Or null, if the item is removed. */ public abstract void onJobRenamed(Item item, String oldName, String newName); @ExportedBean(defaultVisibility=2) public static final class UserInfo implements Comparable<UserInfo> { private final User user; /** * When did this user made a last commit on any of our projects? Can be null. */ private Calendar lastChange; /** * Which project did this user commit? Can be null. */ private AbstractProject project; /** @see UserAvatarResolver */ String avatar; UserInfo(User user, AbstractProject p, Calendar lastChange) { this.user = user; this.project = p; this.lastChange = lastChange; } @Exported public User getUser() { return user; } @Exported public Calendar getLastChange() { return lastChange; } @Exported public AbstractProject getProject() { return project; } /** * Returns a human-readable string representation of when this user was last active. */ public String getLastChangeTimeString() { if(lastChange==null) return "N/A"; long duration = new GregorianCalendar().getTimeInMillis()- ordinal(); return Util.getTimeSpanString(duration); } public String getTimeSortKey() { if(lastChange==null) return "-"; return Util.XS_DATETIME_FORMATTER.format(lastChange.getTime()); } public int compareTo(UserInfo that) { long rhs = that.ordinal(); long lhs = this.ordinal(); if(rhs>lhs) return 1; if(rhs<lhs) return -1; return 0; } private long ordinal() { if(lastChange==null) return 0; return lastChange.getTimeInMillis(); } } /** * Does this {@link View} has any associated user information recorded? * @deprecated Potentially very expensive call; do not use from Jelly views. */ public boolean hasPeople() { return People.isApplicable(getItems()); } /** * Gets the users that show up in the changelog of this job collection. */ public People getPeople() { return new People(this); } /** * @since 1.484 */ public AsynchPeople getAsynchPeople() { return new AsynchPeople(this); } @ExportedBean public static final class People { @Exported public final List<UserInfo> users; public final ModelObject parent; public People(Jenkins parent) { this.parent = parent; // for Hudson, really load all users Map<User,UserInfo> users = getUserInfo(parent.getItems()); User unknown = User.getUnknown(); for (User u : User.getAll()) { if(u==unknown) continue; // skip the special 'unknown' user if(!users.containsKey(u)) users.put(u,new UserInfo(u,null,null)); } this.users = toList(users); } public People(View parent) { this.parent = parent; this.users = toList(getUserInfo(parent.getItems())); } private Map<User,UserInfo> getUserInfo(Collection<? extends Item> items) { Map<User,UserInfo> users = new HashMap<User,UserInfo>(); for (Item item : items) { for (Job job : item.getAllJobs()) { if (job instanceof AbstractProject) { AbstractProject<?,?> p = (AbstractProject) job; for (AbstractBuild<?,?> build : p.getBuilds()) { for (Entry entry : build.getChangeSet()) { User user = entry.getAuthor(); UserInfo info = users.get(user); if(info==null) users.put(user,new UserInfo(user,p,build.getTimestamp())); else if(info.getLastChange().before(build.getTimestamp())) { info.project = p; info.lastChange = build.getTimestamp(); } } } } } } return users; } private List<UserInfo> toList(Map<User,UserInfo> users) { ArrayList<UserInfo> list = new ArrayList<UserInfo>(); list.addAll(users.values()); Collections.sort(list); return Collections.unmodifiableList(list); } public Api getApi() { return new Api(this); } /** * @deprecated Potentially very expensive call; do not use from Jelly views. */ public static boolean isApplicable(Collection<? extends Item> items) { for (Item item : items) { for (Job job : item.getAllJobs()) { if (job instanceof AbstractProject) { AbstractProject<?,?> p = (AbstractProject) job; for (AbstractBuild<?,?> build : p.getBuilds()) { for (Entry entry : build.getChangeSet()) { User user = entry.getAuthor(); if(user!=null) return true; } } } } } return false; } } /** * Variant of {@link People} which can be displayed progressively, since it may be slow. * @since 1.484 */ public static final class AsynchPeople extends ProgressiveRendering { // JENKINS-15206 private final Collection<TopLevelItem> items; private final User unknown; private final Map<User,UserInfo> users = new HashMap<User,UserInfo>(); private final Set<User> modified = new HashSet<User>(); private final String iconSize; public final ModelObject parent; /** @see Jenkins#getAsynchPeople} */ public AsynchPeople(Jenkins parent) { this.parent = parent; items = parent.getItems(); unknown = User.getUnknown(); } /** @see View#getAsynchPeople */ public AsynchPeople(View parent) { this.parent = parent; items = parent.getItems(); unknown = null; } { StaplerRequest req = Stapler.getCurrentRequest(); iconSize = req != null ? Functions.validateIconSize(Functions.getCookie(req, "iconSize", "32x32")) : "32x32"; } @Override protected void compute() throws Exception { int itemCount = 0; for (Item item : items) { for (Job<?,?> job : item.getAllJobs()) { if (job instanceof AbstractProject) { AbstractProject<?,?> p = (AbstractProject) job; RunList<? extends AbstractBuild<?,?>> builds = p.getBuilds(); int buildCount = 0; for (AbstractBuild<?,?> build : builds) { if (canceled()) { return; } for (ChangeLogSet.Entry entry : build.getChangeSet()) { User user = entry.getAuthor(); UserInfo info = users.get(user); if (info == null) { UserInfo userInfo = new UserInfo(user, p, build.getTimestamp()); userInfo.avatar = UserAvatarResolver.resolve(user, iconSize); synchronized (this) { users.put(user, userInfo); modified.add(user); } } else if (info.getLastChange().before(build.getTimestamp())) { synchronized (this) { info.project = p; info.lastChange = build.getTimestamp(); modified.add(user); } } } // XXX consider also adding the user of the UserCause when applicable buildCount++; progress((itemCount + 1.0 * buildCount / builds.size()) / (items.size() + 1)); } } } itemCount++; progress(1.0 * itemCount / (items.size() + /* handling User.getAll */1)); } if (unknown != null) { if (canceled()) { return; } for (User u : User.getAll()) { // XXX nice to have a method to iterate these lazily if (u == unknown) { continue; } if (!users.containsKey(u)) { UserInfo userInfo = new UserInfo(u, null, null); userInfo.avatar = UserAvatarResolver.resolve(u, iconSize); synchronized (this) { users.put(u, userInfo); modified.add(u); } } } } } @Override protected synchronized JSON data() { JSONArray r = new JSONArray(); for (User u : modified) { UserInfo i = users.get(u); JSONObject entry = new JSONObject(). accumulate("id", u.getId()). accumulate("fullName", u.getFullName()). accumulate("url", u.getUrl()). accumulate("avatar", i.avatar). accumulate("timeSortKey", i.getTimeSortKey()). accumulate("lastChangeTimeString", i.getLastChangeTimeString()); AbstractProject<?,?> p = i.getProject(); if (p != null) { entry.accumulate("projectUrl", p.getUrl()).accumulate("projectFullDisplayName", p.getFullDisplayName()); } r.add(entry); } modified.clear(); return r; } public Api getApi() { return new Api(new People()); } /** JENKINS-16397 workaround */ @Restricted(NoExternalUse.class) @ExportedBean public final class People { private View.People people; @Exported public synchronized List<UserInfo> getUsers() { if (people == null) { people = parent instanceof Jenkins ? new View.People((Jenkins) parent) : new View.People((View) parent); } return people.users; } } } void addDisplayNamesToSearchIndex(SearchIndexBuilder sib, Collection<TopLevelItem> items) { for(TopLevelItem item : items) { if(LOGGER.isLoggable(Level.FINE)) { LOGGER.fine((String.format("Adding url=%s,displayName=%s", item.getSearchUrl(), item.getDisplayName()))); } sib.add(item.getSearchUrl(), item.getDisplayName()); } } @Override public SearchIndexBuilder makeSearchIndex() { SearchIndexBuilder sib = super.makeSearchIndex(); sib.add(new CollectionSearchIndex<TopLevelItem>() {// for jobs in the view protected TopLevelItem get(String key) { return getItem(key); } protected Collection<TopLevelItem> all() { return getItems(); } @Override protected String getName(TopLevelItem o) { // return the name instead of the display for suggestion searching return o.getName(); } }); // add the display name for each item in the search index addDisplayNamesToSearchIndex(sib, getItems()); return sib; } /** * Accepts the new description. */ public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { checkPermission(CONFIGURE); description = req.getParameter("description"); save(); rsp.sendRedirect("."); // go to the top page } /** * Accepts submission from the configuration page. * * Subtypes should override the {@link #submit(StaplerRequest)} method. */ @RequirePOST public final synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(CONFIGURE); submit(req); description = Util.nullify(req.getParameter("description")); filterExecutors = req.getParameter("filterExecutors") != null; filterQueue = req.getParameter("filterQueue") != null; rename(req.getParameter("name")); getProperties().rebuild(req, req.getSubmittedForm(), getApplicablePropertyDescriptors()); updateTransientActions(); save(); FormApply.success("../"+name).generateResponse(req,rsp,this); } /** * Handles the configuration submission. * * Load view-specific properties here. */ protected abstract void submit(StaplerRequest req) throws IOException, ServletException, FormException; /** * Deletes this view. */ @RequirePOST public synchronized void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(DELETE); owner.deleteView(this); rsp.sendRedirect2(req.getContextPath()+"/" + owner.getUrl()); } /** * Creates a new {@link Item} in this collection. * * <p> * This method should call {@link ModifiableItemGroup#doCreateItem(StaplerRequest, StaplerResponse)} * and then add the newly created item to this view. * * @return * null if fails. */ public abstract Item doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException; public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { rss(req, rsp, " all builds", getBuilds()); } public void doRssFailed( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { rss(req, rsp, " failed builds", getBuilds().failureOnly()); } public RunList getBuilds() { return new RunList(this); } public BuildTimelineWidget getTimeline() { return new BuildTimelineWidget(getBuilds()); } private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException { RSS.forwardToRss(getDisplayName()+ suffix, getUrl(), runs.newBuilds(), Run.FEED_ADAPTER, req, rsp ); } public void doRssLatest( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { List<Run> lastBuilds = new ArrayList<Run>(); for (TopLevelItem item : getItems()) { if (item instanceof Job) { Job job = (Job) item; Run lb = job.getLastBuild(); if(lb!=null) lastBuilds.add(lb); } } RSS.forwardToRss(getDisplayName()+" last builds only", getUrl(), lastBuilds, Run.FEED_ADAPTER_LATEST, req, rsp ); } /** * Accepts <tt>config.xml</tt> submission, as well as serve it. */ @WebMethod(name = "config.xml") public HttpResponse doConfigDotXml(StaplerRequest req) throws IOException { if (req.getMethod().equals("GET")) { // read checkPermission(READ); return new HttpResponse() { public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { rsp.setContentType("application/xml"); // pity we don't have a handy way to clone Jenkins.XSTREAM to temp add the omit Field XStream2 xStream2 = new XStream2(); xStream2.omitField(View.class, "owner"); xStream2.toXMLUTF8(this, rsp.getOutputStream()); } }; } if (req.getMethod().equals("POST")) { // submission updateByXml((Source)new StreamSource(req.getReader())); return HttpResponses.ok(); } // huh? return HttpResponses.error(SC_BAD_REQUEST, "Unexpected request method " + req.getMethod()); } /** * Updates Job by its XML definition. */ public void updateByXml(Source source) throws IOException { checkPermission(CONFIGURE); StringWriter out = new StringWriter(); try { // this allows us to use UTF-8 for storing data, // plus it checks any well-formedness issue in the submitted // data Transformer t = TransformerFactory.newInstance() .newTransformer(); t.transform(source, new StreamResult(out)); out.close(); } catch (TransformerException e) { throw new IOException2("Failed to persist configuration.xml", e); } // try to reflect the changes by reloading InputStream in = new BufferedInputStream(new ByteArrayInputStream(out.toString().getBytes("UTF-8"))); try { Jenkins.XSTREAM.unmarshal(new XppDriver().createReader(in), this); } catch (StreamException e) { throw new IOException2("Unable to read",e); } catch(ConversionException e) { throw new IOException2("Unable to read",e); } catch(Error e) {// mostly reflection errors throw new IOException2("Unable to read",e); } finally { in.close(); } } /** * A list of available view types. * @deprecated as of 1.286 * Use {@link #all()} for read access, and use {@link Extension} for registration. */ public static final DescriptorList<View> LIST = new DescriptorList<View>(View.class); /** * Returns all the registered {@link ViewDescriptor}s. */ public static DescriptorExtensionList<View,ViewDescriptor> all() { return Jenkins.getInstance().<View,ViewDescriptor>getDescriptorList(View.class); } public static List<ViewDescriptor> allInstantiable() { List<ViewDescriptor> r = new ArrayList<ViewDescriptor>(); for (ViewDescriptor d : all()) if(d.isInstantiable()) r.add(d); return r; } public static final Comparator<View> SORTER = new Comparator<View>() { public int compare(View lhs, View rhs) { return lhs.getViewName().compareTo(rhs.getViewName()); } }; public static final PermissionGroup PERMISSIONS = new PermissionGroup(View.class,Messages._View_Permissions_Title()); /** * Permission to create new views. */ public static final Permission CREATE = new Permission(PERMISSIONS,"Create", Messages._View_CreatePermission_Description(), Permission.CREATE, PermissionScope.ITEM_GROUP); public static final Permission DELETE = new Permission(PERMISSIONS,"Delete", Messages._View_DeletePermission_Description(), Permission.DELETE, PermissionScope.ITEM_GROUP); public static final Permission CONFIGURE = new Permission(PERMISSIONS,"Configure", Messages._View_ConfigurePermission_Description(), Permission.CONFIGURE, PermissionScope.ITEM_GROUP); public static final Permission READ = new Permission(PERMISSIONS,"Read", Messages._View_ReadPermission_Description(), Permission.READ, PermissionScope.ITEM_GROUP); // to simplify access from Jelly public static Permission getItemCreatePermission() { return Item.CREATE; } public static View create(StaplerRequest req, StaplerResponse rsp, ViewGroup owner) throws FormException, IOException, ServletException { String requestContentType = req.getContentType(); if(requestContentType==null) throw new Failure("No Content-Type header set"); boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml"); String name = req.getParameter("name"); checkGoodName(name); if(owner.getView(name)!=null) throw new FormException(Messages.Hudson_ViewAlreadyExists(name),"name"); String mode = req.getParameter("mode"); if (mode==null || mode.length()==0) { if(isXmlSubmission) { View v; v = createViewFromXML(name, req.getInputStream()); v.owner = owner; rsp.setStatus(HttpServletResponse.SC_OK); return v; } else throw new FormException(Messages.View_MissingMode(),"mode"); } // create a view View v = all().findByName(mode).newInstance(req,req.getSubmittedForm()); v.owner = owner; // redirect to the config screen rsp.sendRedirect2(req.getContextPath()+'/'+v.getUrl()+v.getPostConstructLandingPage()); return v; } public static View createViewFromXML(String name, InputStream xml) throws IOException { InputStream in = new BufferedInputStream(xml); try { View v = (View) Jenkins.XSTREAM.fromXML(in); v.name = name; return v; } catch(StreamException e) { throw new IOException2("Unable to read",e); } catch(ConversionException e) { throw new IOException2("Unable to read",e); } catch(Error e) {// mostly reflection errors throw new IOException2("Unable to read",e); } finally { in.close(); } } public static class PropertyList extends DescribableList<ViewProperty,ViewPropertyDescriptor> { private PropertyList(View owner) { super(owner); } public PropertyList() {// needed for XStream deserialization } public View getOwner() { return (View)owner; } @Override protected void onModified() throws IOException { for (ViewProperty p : this) p.setView(getOwner()); } } /** * "Job" in "New Job". When a view is used in a context that restricts the child type, * It might be useful to override this. */ public static final Message<View> NEW_PRONOUN = new Message<View>(); private final static Logger LOGGER = Logger.getLogger(View.class.getName()); }
./CrossVul/dataset_final_sorted/CWE-79/java/good_2097_1
crossvul-java_data_bad_2097_1
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts, * Yahoo!, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.model; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.io.StreamException; import com.thoughtworks.xstream.io.xml.XppDriver; import hudson.DescriptorExtensionList; import hudson.ExtensionPoint; import hudson.Functions; import hudson.Indenter; import hudson.Util; import hudson.model.Descriptor.FormException; import hudson.model.labels.LabelAtomPropertyDescriptor; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.Entry; import hudson.search.CollectionSearchIndex; import hudson.search.SearchIndexBuilder; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.security.Permission; import hudson.security.PermissionGroup; import hudson.security.PermissionScope; import hudson.tasks.UserAvatarResolver; import hudson.util.AlternativeUiTextProvider; import hudson.util.AlternativeUiTextProvider.Message; import hudson.util.DescribableList; import hudson.util.DescriptorList; import hudson.util.FormApply; import hudson.util.IOException2; import hudson.util.RunList; import hudson.util.XStream2; import hudson.views.ListViewColumn; import hudson.widgets.Widget; import jenkins.model.Jenkins; import jenkins.util.ProgressiveRendering; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.WebMethod; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import org.kohsuke.stapler.interceptor.RequirePOST; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static jenkins.model.Jenkins.*; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Encapsulates the rendering of the list of {@link TopLevelItem}s * that {@link Jenkins} owns. * * <p> * This is an extension point in Hudson, allowing different kind of * rendering to be added as plugins. * * <h2>Note for implementors</h2> * <ul> * <li> * {@link View} subtypes need the <tt>newViewDetail.jelly</tt> page, * which is included in the "new view" page. This page should have some * description of what the view is about. * </ul> * * @author Kohsuke Kawaguchi * @see ViewDescriptor * @see ViewGroup */ @ExportedBean public abstract class View extends AbstractModelObject implements AccessControlled, Describable<View>, ExtensionPoint, Saveable { /** * Container of this view. Set right after the construction * and never change thereafter. */ protected /*final*/ ViewGroup owner; /** * Name of this view. */ protected String name; /** * Message displayed in the view page. */ protected String description; /** * If true, only show relevant executors */ protected boolean filterExecutors; /** * If true, only show relevant queue items */ protected boolean filterQueue; protected transient List<Action> transientActions; /** * List of {@link ViewProperty}s configured for this view. * @since 1.406 */ private volatile DescribableList<ViewProperty,ViewPropertyDescriptor> properties = new PropertyList(this); protected View(String name) { this.name = name; } protected View(String name, ViewGroup owner) { this.name = name; this.owner = owner; } /** * Gets all the items in this collection in a read-only view. */ @Exported(name="jobs") public abstract Collection<TopLevelItem> getItems(); /** * Gets the {@link TopLevelItem} of the given name. */ public TopLevelItem getItem(String name) { return getOwnerItemGroup().getItem(name); } /** * Alias for {@link #getItem(String)}. This is the one used in the URL binding. */ public final TopLevelItem getJob(String name) { return getItem(name); } /** * Checks if the job is in this collection. */ public abstract boolean contains(TopLevelItem item); /** * Gets the name of all this collection. * * @see #rename(String) */ @Exported(visibility=2,name="name") public String getViewName() { return name; } /** * Renames this view. */ public void rename(String newName) throws Failure, FormException { if(name.equals(newName)) return; // noop checkGoodName(newName); if(owner.getView(newName)!=null) throw new FormException(Messages.Hudson_ViewAlreadyExists(newName),"name"); String oldName = name; name = newName; owner.onViewRenamed(this,oldName,newName); } /** * Gets the {@link ViewGroup} that this view belongs to. */ public ViewGroup getOwner() { return owner; } /** * Backward-compatible way of getting {@code getOwner().getItemGroup()} */ public ItemGroup<? extends TopLevelItem> getOwnerItemGroup() { try { return _getOwnerItemGroup(); } catch (AbstractMethodError e) { return Hudson.getInstance(); } } /** * A pointless function to work around what appears to be a HotSpot problem. See JENKINS-5756 and bug 6933067 * on BugParade for more details. */ private ItemGroup<? extends TopLevelItem> _getOwnerItemGroup() { return owner.getItemGroup(); } public View getOwnerPrimaryView() { try { return _getOwnerPrimaryView(); } catch (AbstractMethodError e) { return null; } } private View _getOwnerPrimaryView() { return owner.getPrimaryView(); } public List<Action> getOwnerViewActions() { try { return _getOwnerViewActions(); } catch (AbstractMethodError e) { return Hudson.getInstance().getActions(); } } private List<Action> _getOwnerViewActions() { return owner.getViewActions(); } /** * Message displayed in the top page. Can be null. Includes HTML. */ @Exported public String getDescription() { return description; } /** * Gets the view properties configured for this view. * @since 1.406 */ public DescribableList<ViewProperty,ViewPropertyDescriptor> getProperties() { // readResolve was the best place to do this, but for compatibility reasons, // this class can no longer have readResolve() (the mechanism itself isn't suitable for class hierarchy) // see JENKINS-9431 // // until we have that, putting this logic here. synchronized (PropertyList.class) { if (properties == null) { properties = new PropertyList(this); } else { properties.setOwner(this); } return properties; } } /** * Returns all the {@link LabelAtomPropertyDescriptor}s that can be potentially configured * on this label. */ public List<ViewPropertyDescriptor> getApplicablePropertyDescriptors() { List<ViewPropertyDescriptor> r = new ArrayList<ViewPropertyDescriptor>(); for (ViewPropertyDescriptor pd : ViewProperty.all()) { if (pd.isEnabledFor(this)) r.add(pd); } return r; } public void save() throws IOException { // persistence is a part of the owner // due to initialization timing issue, it can be null when this method is called if (owner != null) { owner.save(); } } /** * List of all {@link ViewProperty}s exposed primarily for the remoting API. * @since 1.406 */ @Exported(name="property",inline=true) public List<ViewProperty> getAllProperties() { return getProperties().toList(); } public ViewDescriptor getDescriptor() { return (ViewDescriptor) Jenkins.getInstance().getDescriptorOrDie(getClass()); } public String getDisplayName() { return getViewName(); } public String getNewPronoun() { return AlternativeUiTextProvider.get(NEW_PRONOUN, this, Messages.AbstractItem_Pronoun()); } /** * By default, return true to render the "Edit view" link on the page. * This method is really just for the default "All" view to hide the edit link * so that the default Hudson top page remains the same as before 1.316. * * @since 1.316 */ public boolean isEditable() { return true; } /** * If true, only show relevant executors */ public boolean isFilterExecutors() { return filterExecutors; } /** * If true, only show relevant queue items */ public boolean isFilterQueue() { return filterQueue; } /** * Gets the {@link Widget}s registered on this object. * * <p> * For now, this just returns the widgets registered to Hudson. */ public List<Widget> getWidgets() { return Collections.unmodifiableList(Jenkins.getInstance().getWidgets()); } /** * If this view uses &lt;t:projectView> for rendering, this method returns columns to be displayed. */ public Iterable<? extends ListViewColumn> getColumns() { return ListViewColumn.createDefaultInitialColumnList(); } /** * If this view uses &lt;t:projectView> for rendering, this method returns the indenter used * to indent each row. */ public Indenter getIndenter() { return null; } /** * If true, this is a view that renders the top page of Hudson. */ public boolean isDefault() { return getOwnerPrimaryView()==this; } public List<Computer> getComputers() { Computer[] computers = Jenkins.getInstance().getComputers(); if (!isFilterExecutors()) { return Arrays.asList(computers); } List<Computer> result = new ArrayList<Computer>(); HashSet<Label> labels = new HashSet<Label>(); for (Item item : getItems()) { if (item instanceof AbstractProject<?, ?>) { labels.addAll(((AbstractProject<?, ?>) item).getRelevantLabels()); } } for (Computer c : computers) { Node n = c.getNode(); if (n != null) { if (labels.contains(null) && n.getMode() == Mode.NORMAL || !isDisjoint(n.getAssignedLabels(), labels)) { result.add(c); } } } return result; } private boolean isDisjoint(Collection c1, Collection c2) { for (Object o : c1) if (c2.contains(o)) return false; return true; } private List<Queue.Item> filterQueue(List<Queue.Item> base) { if (!isFilterQueue()) { return base; } Collection<TopLevelItem> items = getItems(); List<Queue.Item> result = new ArrayList<Queue.Item>(); for (Queue.Item qi : base) { if (items.contains(qi.task)) { result.add(qi); } else if (qi.task instanceof AbstractProject<?, ?>) { AbstractProject<?,?> project = (AbstractProject<?, ?>) qi.task; if (items.contains(project.getRootProject())) { result.add(qi); } } } return result; } public List<Queue.Item> getQueueItems() { return filterQueue(Arrays.asList(Jenkins.getInstance().getQueue().getItems())); } public List<Queue.Item> getApproximateQueueItemsQuickly() { return filterQueue(Jenkins.getInstance().getQueue().getApproximateItemsQuickly()); } /** * Returns the path relative to the context root. * * Doesn't start with '/' but ends with '/' (except returns * empty string when this is the default view). */ public String getUrl() { return isDefault() ? (owner!=null ? owner.getUrl() : "") : getViewUrl(); } /** * Same as {@link #getUrl()} except this returns a view/{name} path * even for the default view. */ public String getViewUrl() { return (owner!=null ? owner.getUrl() : "") + "view/" + Util.rawEncode(getViewName()) + '/'; } public String getSearchUrl() { return getUrl(); } /** * Returns the transient {@link Action}s associated with the top page. * * <p> * If views don't want to show top-level actions, this method * can be overridden to return different objects. * * @see Jenkins#getActions() */ public List<Action> getActions() { List<Action> result = new ArrayList<Action>(); result.addAll(getOwnerViewActions()); synchronized (this) { if (transientActions == null) { updateTransientActions(); } result.addAll(transientActions); } return result; } public synchronized void updateTransientActions() { transientActions = TransientViewActionFactory.createAllFor(this); } public Object getDynamic(String token) { for (Action a : getActions()) { String url = a.getUrlName(); if (url==null) continue; if(a.getUrlName().equals(token)) return a; } return null; } /** * Gets the absolute URL of this view. */ @Exported(visibility=2,name="url") public String getAbsoluteUrl() { return Jenkins.getInstance().getRootUrl()+getUrl(); } public Api getApi() { return new Api(this); } /** * Returns the page to redirect the user to, after the view is created. * * The returned string is appended to "/view/foobar/", so for example * to direct the user to the top page of the view, return "", etc. */ public String getPostConstructLandingPage() { return "configure"; } /** * Returns the {@link ACL} for this object. */ public ACL getACL() { return Jenkins.getInstance().getAuthorizationStrategy().getACL(this); } public void checkPermission(Permission p) { getACL().checkPermission(p); } public boolean hasPermission(Permission p) { return getACL().hasPermission(p); } /** * Called when a job name is changed or deleted. * * <p> * If this view contains this job, it should update the view membership so that * the renamed job will remain in the view, and the deleted job is removed. * * @param item * The item whose name is being changed. * @param oldName * Old name of the item. Always non-null. * @param newName * New name of the item, if the item is renamed. Or null, if the item is removed. */ public abstract void onJobRenamed(Item item, String oldName, String newName); @ExportedBean(defaultVisibility=2) public static final class UserInfo implements Comparable<UserInfo> { private final User user; /** * When did this user made a last commit on any of our projects? Can be null. */ private Calendar lastChange; /** * Which project did this user commit? Can be null. */ private AbstractProject project; /** @see UserAvatarResolver */ String avatar; UserInfo(User user, AbstractProject p, Calendar lastChange) { this.user = user; this.project = p; this.lastChange = lastChange; } @Exported public User getUser() { return user; } @Exported public Calendar getLastChange() { return lastChange; } @Exported public AbstractProject getProject() { return project; } /** * Returns a human-readable string representation of when this user was last active. */ public String getLastChangeTimeString() { if(lastChange==null) return "N/A"; long duration = new GregorianCalendar().getTimeInMillis()- ordinal(); return Util.getTimeSpanString(duration); } public String getTimeSortKey() { if(lastChange==null) return "-"; return Util.XS_DATETIME_FORMATTER.format(lastChange.getTime()); } public int compareTo(UserInfo that) { long rhs = that.ordinal(); long lhs = this.ordinal(); if(rhs>lhs) return 1; if(rhs<lhs) return -1; return 0; } private long ordinal() { if(lastChange==null) return 0; return lastChange.getTimeInMillis(); } } /** * Does this {@link View} has any associated user information recorded? * @deprecated Potentially very expensive call; do not use from Jelly views. */ public boolean hasPeople() { return People.isApplicable(getItems()); } /** * Gets the users that show up in the changelog of this job collection. */ public People getPeople() { return new People(this); } /** * @since 1.484 */ public AsynchPeople getAsynchPeople() { return new AsynchPeople(this); } @ExportedBean public static final class People { @Exported public final List<UserInfo> users; public final ModelObject parent; public People(Jenkins parent) { this.parent = parent; // for Hudson, really load all users Map<User,UserInfo> users = getUserInfo(parent.getItems()); User unknown = User.getUnknown(); for (User u : User.getAll()) { if(u==unknown) continue; // skip the special 'unknown' user if(!users.containsKey(u)) users.put(u,new UserInfo(u,null,null)); } this.users = toList(users); } public People(View parent) { this.parent = parent; this.users = toList(getUserInfo(parent.getItems())); } private Map<User,UserInfo> getUserInfo(Collection<? extends Item> items) { Map<User,UserInfo> users = new HashMap<User,UserInfo>(); for (Item item : items) { for (Job job : item.getAllJobs()) { if (job instanceof AbstractProject) { AbstractProject<?,?> p = (AbstractProject) job; for (AbstractBuild<?,?> build : p.getBuilds()) { for (Entry entry : build.getChangeSet()) { User user = entry.getAuthor(); UserInfo info = users.get(user); if(info==null) users.put(user,new UserInfo(user,p,build.getTimestamp())); else if(info.getLastChange().before(build.getTimestamp())) { info.project = p; info.lastChange = build.getTimestamp(); } } } } } } return users; } private List<UserInfo> toList(Map<User,UserInfo> users) { ArrayList<UserInfo> list = new ArrayList<UserInfo>(); list.addAll(users.values()); Collections.sort(list); return Collections.unmodifiableList(list); } public Api getApi() { return new Api(this); } /** * @deprecated Potentially very expensive call; do not use from Jelly views. */ public static boolean isApplicable(Collection<? extends Item> items) { for (Item item : items) { for (Job job : item.getAllJobs()) { if (job instanceof AbstractProject) { AbstractProject<?,?> p = (AbstractProject) job; for (AbstractBuild<?,?> build : p.getBuilds()) { for (Entry entry : build.getChangeSet()) { User user = entry.getAuthor(); if(user!=null) return true; } } } } } return false; } } /** * Variant of {@link People} which can be displayed progressively, since it may be slow. * @since 1.484 */ public static final class AsynchPeople extends ProgressiveRendering { // JENKINS-15206 private final Collection<TopLevelItem> items; private final User unknown; private final Map<User,UserInfo> users = new HashMap<User,UserInfo>(); private final Set<User> modified = new HashSet<User>(); private final String iconSize; public final ModelObject parent; /** @see Jenkins#getAsynchPeople} */ public AsynchPeople(Jenkins parent) { this.parent = parent; items = parent.getItems(); unknown = User.getUnknown(); } /** @see View#getAsynchPeople */ public AsynchPeople(View parent) { this.parent = parent; items = parent.getItems(); unknown = null; } { StaplerRequest req = Stapler.getCurrentRequest(); iconSize = req != null ? Functions.getCookie(req, "iconSize", "32x32") : "32x32"; } @Override protected void compute() throws Exception { int itemCount = 0; for (Item item : items) { for (Job<?,?> job : item.getAllJobs()) { if (job instanceof AbstractProject) { AbstractProject<?,?> p = (AbstractProject) job; RunList<? extends AbstractBuild<?,?>> builds = p.getBuilds(); int buildCount = 0; for (AbstractBuild<?,?> build : builds) { if (canceled()) { return; } for (ChangeLogSet.Entry entry : build.getChangeSet()) { User user = entry.getAuthor(); UserInfo info = users.get(user); if (info == null) { UserInfo userInfo = new UserInfo(user, p, build.getTimestamp()); userInfo.avatar = UserAvatarResolver.resolve(user, iconSize); synchronized (this) { users.put(user, userInfo); modified.add(user); } } else if (info.getLastChange().before(build.getTimestamp())) { synchronized (this) { info.project = p; info.lastChange = build.getTimestamp(); modified.add(user); } } } // XXX consider also adding the user of the UserCause when applicable buildCount++; progress((itemCount + 1.0 * buildCount / builds.size()) / (items.size() + 1)); } } } itemCount++; progress(1.0 * itemCount / (items.size() + /* handling User.getAll */1)); } if (unknown != null) { if (canceled()) { return; } for (User u : User.getAll()) { // XXX nice to have a method to iterate these lazily if (u == unknown) { continue; } if (!users.containsKey(u)) { UserInfo userInfo = new UserInfo(u, null, null); userInfo.avatar = UserAvatarResolver.resolve(u, iconSize); synchronized (this) { users.put(u, userInfo); modified.add(u); } } } } } @Override protected synchronized JSON data() { JSONArray r = new JSONArray(); for (User u : modified) { UserInfo i = users.get(u); JSONObject entry = new JSONObject(). accumulate("id", u.getId()). accumulate("fullName", u.getFullName()). accumulate("url", u.getUrl()). accumulate("avatar", i.avatar). accumulate("timeSortKey", i.getTimeSortKey()). accumulate("lastChangeTimeString", i.getLastChangeTimeString()); AbstractProject<?,?> p = i.getProject(); if (p != null) { entry.accumulate("projectUrl", p.getUrl()).accumulate("projectFullDisplayName", p.getFullDisplayName()); } r.add(entry); } modified.clear(); return r; } public Api getApi() { return new Api(new People()); } /** JENKINS-16397 workaround */ @Restricted(NoExternalUse.class) @ExportedBean public final class People { private View.People people; @Exported public synchronized List<UserInfo> getUsers() { if (people == null) { people = parent instanceof Jenkins ? new View.People((Jenkins) parent) : new View.People((View) parent); } return people.users; } } } void addDisplayNamesToSearchIndex(SearchIndexBuilder sib, Collection<TopLevelItem> items) { for(TopLevelItem item : items) { if(LOGGER.isLoggable(Level.FINE)) { LOGGER.fine((String.format("Adding url=%s,displayName=%s", item.getSearchUrl(), item.getDisplayName()))); } sib.add(item.getSearchUrl(), item.getDisplayName()); } } @Override public SearchIndexBuilder makeSearchIndex() { SearchIndexBuilder sib = super.makeSearchIndex(); sib.add(new CollectionSearchIndex<TopLevelItem>() {// for jobs in the view protected TopLevelItem get(String key) { return getItem(key); } protected Collection<TopLevelItem> all() { return getItems(); } @Override protected String getName(TopLevelItem o) { // return the name instead of the display for suggestion searching return o.getName(); } }); // add the display name for each item in the search index addDisplayNamesToSearchIndex(sib, getItems()); return sib; } /** * Accepts the new description. */ public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { checkPermission(CONFIGURE); description = req.getParameter("description"); save(); rsp.sendRedirect("."); // go to the top page } /** * Accepts submission from the configuration page. * * Subtypes should override the {@link #submit(StaplerRequest)} method. */ @RequirePOST public final synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(CONFIGURE); submit(req); description = Util.nullify(req.getParameter("description")); filterExecutors = req.getParameter("filterExecutors") != null; filterQueue = req.getParameter("filterQueue") != null; rename(req.getParameter("name")); getProperties().rebuild(req, req.getSubmittedForm(), getApplicablePropertyDescriptors()); updateTransientActions(); save(); FormApply.success("../"+name).generateResponse(req,rsp,this); } /** * Handles the configuration submission. * * Load view-specific properties here. */ protected abstract void submit(StaplerRequest req) throws IOException, ServletException, FormException; /** * Deletes this view. */ @RequirePOST public synchronized void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(DELETE); owner.deleteView(this); rsp.sendRedirect2(req.getContextPath()+"/" + owner.getUrl()); } /** * Creates a new {@link Item} in this collection. * * <p> * This method should call {@link ModifiableItemGroup#doCreateItem(StaplerRequest, StaplerResponse)} * and then add the newly created item to this view. * * @return * null if fails. */ public abstract Item doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException; public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { rss(req, rsp, " all builds", getBuilds()); } public void doRssFailed( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { rss(req, rsp, " failed builds", getBuilds().failureOnly()); } public RunList getBuilds() { return new RunList(this); } public BuildTimelineWidget getTimeline() { return new BuildTimelineWidget(getBuilds()); } private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException { RSS.forwardToRss(getDisplayName()+ suffix, getUrl(), runs.newBuilds(), Run.FEED_ADAPTER, req, rsp ); } public void doRssLatest( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { List<Run> lastBuilds = new ArrayList<Run>(); for (TopLevelItem item : getItems()) { if (item instanceof Job) { Job job = (Job) item; Run lb = job.getLastBuild(); if(lb!=null) lastBuilds.add(lb); } } RSS.forwardToRss(getDisplayName()+" last builds only", getUrl(), lastBuilds, Run.FEED_ADAPTER_LATEST, req, rsp ); } /** * Accepts <tt>config.xml</tt> submission, as well as serve it. */ @WebMethod(name = "config.xml") public HttpResponse doConfigDotXml(StaplerRequest req) throws IOException { if (req.getMethod().equals("GET")) { // read checkPermission(READ); return new HttpResponse() { public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { rsp.setContentType("application/xml"); // pity we don't have a handy way to clone Jenkins.XSTREAM to temp add the omit Field XStream2 xStream2 = new XStream2(); xStream2.omitField(View.class, "owner"); xStream2.toXMLUTF8(this, rsp.getOutputStream()); } }; } if (req.getMethod().equals("POST")) { // submission updateByXml((Source)new StreamSource(req.getReader())); return HttpResponses.ok(); } // huh? return HttpResponses.error(SC_BAD_REQUEST, "Unexpected request method " + req.getMethod()); } /** * Updates Job by its XML definition. */ public void updateByXml(Source source) throws IOException { checkPermission(CONFIGURE); StringWriter out = new StringWriter(); try { // this allows us to use UTF-8 for storing data, // plus it checks any well-formedness issue in the submitted // data Transformer t = TransformerFactory.newInstance() .newTransformer(); t.transform(source, new StreamResult(out)); out.close(); } catch (TransformerException e) { throw new IOException2("Failed to persist configuration.xml", e); } // try to reflect the changes by reloading InputStream in = new BufferedInputStream(new ByteArrayInputStream(out.toString().getBytes("UTF-8"))); try { Jenkins.XSTREAM.unmarshal(new XppDriver().createReader(in), this); } catch (StreamException e) { throw new IOException2("Unable to read",e); } catch(ConversionException e) { throw new IOException2("Unable to read",e); } catch(Error e) {// mostly reflection errors throw new IOException2("Unable to read",e); } finally { in.close(); } } /** * A list of available view types. * @deprecated as of 1.286 * Use {@link #all()} for read access, and use {@link Extension} for registration. */ public static final DescriptorList<View> LIST = new DescriptorList<View>(View.class); /** * Returns all the registered {@link ViewDescriptor}s. */ public static DescriptorExtensionList<View,ViewDescriptor> all() { return Jenkins.getInstance().<View,ViewDescriptor>getDescriptorList(View.class); } public static List<ViewDescriptor> allInstantiable() { List<ViewDescriptor> r = new ArrayList<ViewDescriptor>(); for (ViewDescriptor d : all()) if(d.isInstantiable()) r.add(d); return r; } public static final Comparator<View> SORTER = new Comparator<View>() { public int compare(View lhs, View rhs) { return lhs.getViewName().compareTo(rhs.getViewName()); } }; public static final PermissionGroup PERMISSIONS = new PermissionGroup(View.class,Messages._View_Permissions_Title()); /** * Permission to create new views. */ public static final Permission CREATE = new Permission(PERMISSIONS,"Create", Messages._View_CreatePermission_Description(), Permission.CREATE, PermissionScope.ITEM_GROUP); public static final Permission DELETE = new Permission(PERMISSIONS,"Delete", Messages._View_DeletePermission_Description(), Permission.DELETE, PermissionScope.ITEM_GROUP); public static final Permission CONFIGURE = new Permission(PERMISSIONS,"Configure", Messages._View_ConfigurePermission_Description(), Permission.CONFIGURE, PermissionScope.ITEM_GROUP); public static final Permission READ = new Permission(PERMISSIONS,"Read", Messages._View_ReadPermission_Description(), Permission.READ, PermissionScope.ITEM_GROUP); // to simplify access from Jelly public static Permission getItemCreatePermission() { return Item.CREATE; } public static View create(StaplerRequest req, StaplerResponse rsp, ViewGroup owner) throws FormException, IOException, ServletException { String requestContentType = req.getContentType(); if(requestContentType==null) throw new Failure("No Content-Type header set"); boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml"); String name = req.getParameter("name"); checkGoodName(name); if(owner.getView(name)!=null) throw new FormException(Messages.Hudson_ViewAlreadyExists(name),"name"); String mode = req.getParameter("mode"); if (mode==null || mode.length()==0) { if(isXmlSubmission) { View v; v = createViewFromXML(name, req.getInputStream()); v.owner = owner; rsp.setStatus(HttpServletResponse.SC_OK); return v; } else throw new FormException(Messages.View_MissingMode(),"mode"); } // create a view View v = all().findByName(mode).newInstance(req,req.getSubmittedForm()); v.owner = owner; // redirect to the config screen rsp.sendRedirect2(req.getContextPath()+'/'+v.getUrl()+v.getPostConstructLandingPage()); return v; } public static View createViewFromXML(String name, InputStream xml) throws IOException { InputStream in = new BufferedInputStream(xml); try { View v = (View) Jenkins.XSTREAM.fromXML(in); v.name = name; return v; } catch(StreamException e) { throw new IOException2("Unable to read",e); } catch(ConversionException e) { throw new IOException2("Unable to read",e); } catch(Error e) {// mostly reflection errors throw new IOException2("Unable to read",e); } finally { in.close(); } } public static class PropertyList extends DescribableList<ViewProperty,ViewPropertyDescriptor> { private PropertyList(View owner) { super(owner); } public PropertyList() {// needed for XStream deserialization } public View getOwner() { return (View)owner; } @Override protected void onModified() throws IOException { for (ViewProperty p : this) p.setView(getOwner()); } } /** * "Job" in "New Job". When a view is used in a context that restricts the child type, * It might be useful to override this. */ public static final Message<View> NEW_PRONOUN = new Message<View>(); private final static Logger LOGGER = Logger.getLogger(View.class.getName()); }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_2097_1
crossvul-java_data_bad_5841_1
///////////////////////////////////////////////////////////////////////////// // // Project ProjectForge Community Edition // www.projectforge.org // // Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de) // // ProjectForge is dual-licensed. // // This community edition is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 3 of the License. // // This community edition is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General // Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, see http://www.gnu.org/licenses/. // ///////////////////////////////////////////////////////////////////////////// package org.projectforge.web.wicket.autocompletion; import java.util.ArrayList; import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.ajax.markup.html.autocomplete.IAutoCompleteRenderer; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.JavaScriptReferenceHeaderItem; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.handler.TextRequestHandler; import org.apache.wicket.util.string.Strings; import org.projectforge.web.core.JsonBuilder; import org.projectforge.web.wicket.WicketRenderHeadUtils; public abstract class PFAutoCompleteBehavior<T> extends AbstractDefaultAjaxBehavior { private static final long serialVersionUID = -6532710378025987377L; protected PFAutoCompleteSettings settings; protected IAutoCompleteRenderer<String> renderer; public PFAutoCompleteBehavior(final IAutoCompleteRenderer<String> renderer, final PFAutoCompleteSettings settings) { this.renderer = renderer; this.settings = settings; } /** * @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#renderHead(org.apache.wicket.Component, * org.apache.wicket.markup.html.IHeaderResponse) */ @Override public void renderHead(final Component component, final IHeaderResponse response) { super.renderHead(component, response); WicketRenderHeadUtils.renderMainJavaScriptIncludes(response); response.render(JavaScriptReferenceHeaderItem.forUrl("scripts/jquery.wicket-autocomplete.js")); renderAutocompleteHead(response); } /** * Render autocomplete init javascript and other head contributions * * @param response */ private void renderAutocompleteHead(final IHeaderResponse response) { final String id = getComponent().getMarkupId(); String indicatorId = findIndicatorId(); if (Strings.isEmpty(indicatorId)) { indicatorId = "null"; } else { indicatorId = "'" + indicatorId + "'"; } final StringBuffer buf = new StringBuffer(); buf.append("var favorite" + id + " = "); final List<T> favorites = getFavorites(); final MyJsonBuilder builder = new MyJsonBuilder(); if (favorites != null) { buf.append(builder.append(favorites).getAsString()); } else { buf.append(builder.append(getRecentUserInputs()).getAsString()); } buf.append(";").append("var z = $(\"#").append(id).append("\");\n").append("z.autocomplete(\"").append(getCallbackUrl()).append("\",{"); boolean first = true; for (final String setting : getSettingsJS()) { if (first == true) first = false; else buf.append(", "); buf.append(setting); } if (first == true) first = false; else buf.append(", "); buf.append("favoriteEntries:favorite" + id); buf.append("});"); if (settings.isHasFocus() == true) { buf.append("\nz.focus();"); } final String initJS = buf.toString(); // String initJS = String.format("new Wicket.AutoComplete('%s','%s',%s,%s);", id, getCallbackUrl(), constructSettingsJS(), indicatorId); response.render(OnDomReadyHeaderItem.forScript(initJS)); } protected final List<String> getSettingsJS() { final List<String> result = new ArrayList<String>(); addSetting(result, "matchContains", settings.isMatchContains()); addSetting(result, "minChars", settings.getMinChars()); addSetting(result, "delay", settings.getDelay()); addSetting(result, "matchCase", settings.isMatchCase()); addSetting(result, "matchSubset", settings.isMatchSubset()); addSetting(result, "cacheLength", settings.getCacheLength()); addSetting(result, "mustMatch", settings.isMustMatch()); addSetting(result, "selectFirst", settings.isSelectFirst()); addSetting(result, "selectOnly", settings.isSelectOnly()); addSetting(result, "maxItemsToShow", settings.getMaxItemsToShow()); addSetting(result, "autoFill", settings.isAutoFill()); addSetting(result, "autoSubmit", settings.isAutoSubmit()); addSetting(result, "scroll", settings.isScroll()); addSetting(result, "scrollHeight", settings.getScrollHeight()); addSetting(result, "width", settings.getWidth()); addSetting(result, "deletableItem", settings.isDeletableItem()); if (settings.isLabelValue() == true) { addSetting(result, "labelValue", settings.isLabelValue()); } return result; } private final void addSetting(final List<String> result, final String name, final Boolean value) { if (value == null) { return; } result.add(name + ":" + ((value == true) ? "1" : "0")); } private final void addSetting(final List<String> result, final String name, final Integer value) { if (value == null) { return; } result.add(name + ":" + value); } /** * @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#onBind() */ @Override protected void onBind() { // add empty AbstractDefaultAjaxBehavior to the component, to force // rendering wicket-ajax.js reference if no other ajax behavior is on // page getComponent().add(new AbstractDefaultAjaxBehavior() { private static final long serialVersionUID = 1L; @Override protected void respond(final AjaxRequestTarget target) { } }); } /** * @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#respond(org.apache.wicket.ajax.AjaxRequestTarget) */ @Override protected void respond(final AjaxRequestTarget target) { final RequestCycle requestCycle = RequestCycle.get(); final org.apache.wicket.util.string.StringValue val = requestCycle.getRequest().getQueryParameters().getParameterValue("q"); onRequest(val != null ? val.toString() : null, requestCycle); } protected final void onRequest(final String val, final RequestCycle requestCycle) { // final PageParameters pageParameters = new PageParameters(requestCycle.getRequest().getParameterMap()); final List<T> choices = getChoices(val); final MyJsonBuilder builder = new MyJsonBuilder(); final String json = builder.append(choices).getAsString(); requestCycle.scheduleRequestHandlerAfterCurrent(new TextRequestHandler("application/json", "utf-8", json)); /* * IRequestTarget target = new IRequestTarget() { * * public void respond(RequestCycle requestCycle) { * * WebResponse r = (WebResponse) requestCycle.getResponse(); // Determine encoding final String encoding = * Application.get().getRequestCycleSettings().getResponseRequestEncoding(); r.setCharacterEncoding(encoding); * r.setContentType("application/json"); // Make sure it is not cached by a r.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); * r.setHeader("Cache-Control", "no-cache, must-revalidate"); r.setHeader("Pragma", "no-cache"); * * final List<T> choices = getChoices(val); renderer.renderHeader(r); renderer.render(JsonBuilder.buildRows(false, choices), r, val); * renderer.renderFooter(r); } * * public void detach(RequestCycle requestCycle) { } }; requestCycle.setRequestTarget(target); */ } /** * Callback method that should return an iterator over all possible choice objects. These objects will be passed to the renderer to * generate output. Usually it is enough to return an iterator over strings. * * @param input current input * @return iterator over all possible choice objects */ protected abstract List<T> getChoices(String input); /** * Callback method that should return a list of all possible default choice objects to show, if the user double clicks the empty input * field. These objects will be passed to the renderer to generate output. Usually it is enough to return an iterator over strings. */ protected abstract List<T> getFavorites(); /** * Callback method that should return a list of all recent user inputs in the text input field. They will be shown, if the user double * clicks the empty input field. These objects will be passed to the renderer to generate output. Usually it is enough to return an * iterator over strings. <br/> * Please note: Please, use only getFavorites() OR getRecentUserInputs()! */ protected abstract List<String> getRecentUserInputs(); /** * Used for formatting the values. */ protected abstract String formatValue(T value); /** * Used for formatting the labels if labelValue is set to true. * @return null at default (if not overload). */ protected String formatLabel(final T value) { return null; } private class MyJsonBuilder extends JsonBuilder { @SuppressWarnings("unchecked") @Override protected String formatValue(final Object obj) { if (obj instanceof String) { return obj.toString(); } else { return PFAutoCompleteBehavior.this.formatValue((T) obj); } } @SuppressWarnings("unchecked") @Override protected Object transform(final Object obj) { if (settings.isLabelValue() == true) { final Object[] oa = new Object[2]; if (obj instanceof String) { oa[0] = obj; oa[1] = obj; } else { oa[0] = PFAutoCompleteBehavior.this.formatLabel((T) obj); oa[1] = PFAutoCompleteBehavior.this.formatValue((T) obj); } return oa; } else { return obj; } } }; }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_5841_1
crossvul-java_data_bad_5805_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-79/java/bad_5805_1
crossvul-java_data_bad_24_2
package org.jolokia.http; /* * Copyright 2009-2011 Roland Huss * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.*; import java.net.SocketException; import java.util.*; import javax.management.JMException; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jolokia.backend.TestDetector; import org.jolokia.config.ConfigKey; import org.jolokia.discovery.JolokiaDiscovery; import org.jolokia.restrictor.*; import org.jolokia.test.util.HttpTestUtil; import org.jolokia.util.LogHandler; import org.jolokia.util.NetworkUtil; import org.jolokia.util.QuietLogHandler; import org.json.simple.JSONObject; import org.testng.SkipException; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.easymock.EasyMock.*; import static org.testng.Assert.*; /** * @author roland * @since 30.08.11 */ public class AgentServletTest { private ServletContext context; private ServletConfig config; private HttpServletRequest request; private HttpServletResponse response; private AgentServlet servlet; @Test public void simpleInit() throws ServletException { servlet = new AgentServlet(); initConfigMocks(null, null,"No access restrictor found", null); replay(config, context); servlet.init(config); servlet.destroy(); } @Test public void initWithAcessRestriction() throws ServletException { servlet = new AgentServlet(); initConfigMocks(new String[]{ConfigKey.POLICY_LOCATION.getKeyValue(), "classpath:/access-sample1.xml"}, null, "Using access restrictor.*access-sample1.xml", null); replay(config, context); servlet.init(config); servlet.destroy(); } @Test public void initWithInvalidPolicyFile() throws ServletException { servlet = new AgentServlet(); initConfigMocks(new String[]{ConfigKey.POLICY_LOCATION.getKeyValue(), "file:///blablub.xml"}, null, "Error.*blablub.xml.*Denying", FileNotFoundException.class); replay(config, context); servlet.init(config); servlet.destroy(); } @Test public void configWithOverWrite() throws ServletException { servlet = new AgentServlet(); request = createMock(HttpServletRequest.class); response = createMock(HttpServletResponse.class); initConfigMocks(new String[] {ConfigKey.AGENT_CONTEXT.getKeyValue(),"/jmx4perl",ConfigKey.MAX_DEPTH.getKeyValue(),"10"}, new String[] {ConfigKey.AGENT_CONTEXT.getKeyValue(),"/j0l0k14",ConfigKey.MAX_OBJECTS.getKeyValue(),"20", ConfigKey.CALLBACK.getKeyValue(),"callback is a request option, must be empty here"}, null,null); replay(config, context,request,response); servlet.init(config); servlet.destroy(); org.jolokia.config.Configuration cfg = servlet.initConfig(config); assertEquals(cfg.get(ConfigKey.AGENT_CONTEXT), "/j0l0k14"); assertEquals(cfg.get(ConfigKey.MAX_DEPTH), "10"); assertEquals(cfg.get(ConfigKey.MAX_OBJECTS), "20"); assertNull(cfg.get(ConfigKey.CALLBACK)); assertNull(cfg.get(ConfigKey.DETECTOR_OPTIONS)); } @Test public void initWithcustomAccessRestrictor() throws ServletException { prepareStandardInitialisation(); servlet.destroy(); } @Test public void initWithCustomLogHandler() throws Exception { servlet = new AgentServlet(); config = createMock(ServletConfig.class); context = createMock(ServletContext.class); HttpTestUtil.prepareServletConfigMock(config, new String[]{ConfigKey.LOGHANDLER_CLASS.getKeyValue(), CustomLogHandler.class.getName()}); HttpTestUtil.prepareServletContextMock(context,null); expect(config.getServletContext()).andStubReturn(context); expect(config.getServletName()).andStubReturn("jolokia"); replay(config, context); servlet.init(config); servlet.destroy(); assertTrue(CustomLogHandler.infoCount > 0); } @Test public void initWithAgentDiscoveryAndGivenUrl() throws ServletException, IOException, InterruptedException { checkMulticastAvailable(); String url = "http://localhost:8080/jolokia"; prepareStandardInitialisation(ConfigKey.DISCOVERY_AGENT_URL.getKeyValue(), url); // Wait listening thread to warm up Thread.sleep(1000); try { JolokiaDiscovery discovery = new JolokiaDiscovery("test", new QuietLogHandler()); List<JSONObject> in = discovery.lookupAgentsWithTimeout(500); for (JSONObject json : in) { if (json.get("url") != null && json.get("url").equals(url)) { return; } } fail("No agent found"); } finally { servlet.destroy(); } } @Test public void initWithAgentDiscoveryAndUrlLookup() throws ServletException, IOException { checkMulticastAvailable(); prepareStandardInitialisation(ConfigKey.DISCOVERY_ENABLED.getKeyValue(), "true"); try { JolokiaDiscovery discovery = new JolokiaDiscovery("test", new QuietLogHandler()); List<JSONObject> in = discovery.lookupAgents(); assertTrue(in.size() > 0); // At least one doesnt have an URL (remove this part if a way could be found for getting // to the URL for (JSONObject json : in) { if (json.get("url") == null) { return; } } fail("Every message has an URL"); } finally { servlet.destroy(); } } private void checkMulticastAvailable() throws SocketException { if (!NetworkUtil.isMulticastSupported()) { throw new SkipException("No multicast interface found, skipping test "); } } @Test public void initWithAgentDiscoveryAndUrlCreationAfterGet() throws ServletException, IOException { checkMulticastAvailable(); prepareStandardInitialisation(ConfigKey.DISCOVERY_ENABLED.getKeyValue(), "true"); try { String url = "http://10.9.11.1:9876/jolokia"; ByteArrayOutputStream sw = initRequestResponseMocks( getDiscoveryRequestSetup(url), getStandardResponseSetup()); replay(request, response); servlet.doGet(request, response); assertTrue(sw.toString().contains("used")); JolokiaDiscovery discovery = new JolokiaDiscovery("test",new QuietLogHandler()); List<JSONObject> in = discovery.lookupAgents(); assertTrue(in.size() > 0); for (JSONObject json : in) { if (json.get("url") != null && json.get("url").equals(url)) { assertTrue((Boolean) json.get("secured")); return; } } fail("Failed, because no message had an URL"); } finally { servlet.destroy(); } } public static class CustomLogHandler implements LogHandler { private static int infoCount = 0; public CustomLogHandler() { infoCount = 0; } public void debug(String message) { } public void info(String message) { infoCount++; } public void error(String message, Throwable t) { } } @Test public void simpleGet() throws ServletException, IOException { prepareStandardInitialisation(); ByteArrayOutputStream sw = initRequestResponseMocks(); expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain"); expect(request.getAttribute("subject")).andReturn(null); replay(request, response); servlet.doGet(request, response); assertTrue(sw.toString().contains("used")); servlet.destroy(); } @Test public void simpleGetWithNoReverseDnsLookupFalse() throws ServletException, IOException { checkNoReverseDns(false,"127.0.0.1"); } @Test public void simpleGetWithNoReverseDnsLookupTrue() throws ServletException, IOException { checkNoReverseDns(true,"localhost","127.0.0.1"); } private void checkNoReverseDns(boolean enabled, String ... expectedHosts) throws ServletException, IOException { prepareStandardInitialisation( (Restrictor) null, ConfigKey.RESTRICTOR_CLASS.getKeyValue(),NoDnsLookupRestrictorChecker.class.getName(), ConfigKey.ALLOW_DNS_REVERSE_LOOKUP.getKeyValue(),Boolean.toString(enabled)); NoDnsLookupRestrictorChecker.expectedHosts = expectedHosts; ByteArrayOutputStream sw = initRequestResponseMocks(); expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain"); expect(request.getAttribute("subject")).andReturn(null); replay(request, response); servlet.doGet(request, response); assertFalse(sw.toString().contains("error")); servlet.destroy(); } // Check whether restrictor is called with the proper args public static class NoDnsLookupRestrictorChecker extends AbstractConstantRestrictor { static String[] expectedHosts; public NoDnsLookupRestrictorChecker() { super(true); } @Override public boolean isRemoteAccessAllowed(String... pHostOrAddress) { if (expectedHosts.length != pHostOrAddress.length) { return false; } for (int i = 0; i < expectedHosts.length; i++) { if (!expectedHosts[i].equals(pHostOrAddress[i])) { return false; } } return true; } } @Test public void simpleGetWithUnsupportedGetParameterMapCall() throws ServletException, IOException { prepareStandardInitialisation(); ByteArrayOutputStream sw = initRequestResponseMocks( new Runnable() { public void run() { expect(request.getHeader("Origin")).andStubReturn(null); expect(request.getHeader("Referer")).andStubReturn(null); expect(request.getRemoteHost()).andReturn("localhost"); expect(request.getRemoteAddr()).andReturn("127.0.0.1"); expect(request.getRequestURI()).andReturn("/jolokia/"); setupAgentDetailsInitExpectations(); expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getParameterMap()).andThrow(new UnsupportedOperationException("")); expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null); Vector params = new Vector(); params.add("debug"); expect(request.getParameterNames()).andReturn(params.elements()); expect(request.getParameterValues("debug")).andReturn(new String[] {"false"}); expect(request.getAttribute("subject")).andReturn(null); expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null); } }, getStandardResponseSetup()); expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null); replay(request,response); servlet.doGet(request,response); servlet.destroy(); } @Test public void simplePost() throws ServletException, IOException { prepareStandardInitialisation(); ByteArrayOutputStream responseWriter = initRequestResponseMocks(); expect(request.getCharacterEncoding()).andReturn("utf-8"); expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain"); expect(request.getAttribute("subject")).andReturn(null); preparePostRequest(HttpTestUtil.HEAP_MEMORY_POST_REQUEST); replay(request, response); servlet.doPost(request, response); assertTrue(responseWriter.toString().contains("used")); servlet.destroy(); } @Test public void unknownMethodWhenSettingContentType() throws ServletException, IOException { prepareStandardInitialisation(); ByteArrayOutputStream sw = initRequestResponseMocks( getStandardRequestSetup(), new Runnable() { public void run() { response.setCharacterEncoding("utf-8"); expectLastCall().andThrow(new NoSuchMethodError()); response.setContentType("text/plain; charset=utf-8"); response.setStatus(200); } }); expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null); expect(request.getAttribute("subject")).andReturn(null); replay(request, response); servlet.doGet(request, response); assertTrue(sw.toString().contains("used")); servlet.destroy(); } @Test public void corsPreflightCheck() throws ServletException, IOException { checkCorsOriginPreflight("http://bla.com", "http://bla.com"); } @Test public void corsPreflightCheckWithNullOrigin() throws ServletException, IOException { checkCorsOriginPreflight("null", "*"); } private void checkCorsOriginPreflight(String in, String out) throws ServletException, IOException { prepareStandardInitialisation(); request = createMock(HttpServletRequest.class); response = createMock(HttpServletResponse.class); expect(request.getHeader("Origin")).andReturn(in); expect(request.getHeader("Access-Control-Request-Headers")).andReturn(null); response.setHeader(eq("Access-Control-Max-Age"), (String) anyObject()); response.setHeader("Access-Control-Allow-Origin", out); response.setHeader("Access-Control-Allow-Credentials", "true"); replay(request, response); servlet.doOptions(request, response); servlet.destroy(); } @Test public void corsHeaderGetCheck() throws ServletException, IOException { checkCorsGetOrigin("http://bla.com","http://bla.com"); } @Test public void corsHeaderGetCheckWithNullOrigin() throws ServletException, IOException { checkCorsGetOrigin("null","*"); } private void checkCorsGetOrigin(final String in, final String out) throws ServletException, IOException { prepareStandardInitialisation(); ByteArrayOutputStream sw = initRequestResponseMocks( new Runnable() { public void run() { expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null); expect(request.getHeader("Origin")).andStubReturn(in); expect(request.getRemoteHost()).andReturn("localhost"); expect(request.getRemoteAddr()).andReturn("127.0.0.1"); expect(request.getRequestURI()).andReturn("/jolokia/").times(2); expect(request.getRequestURL()).andReturn(new StringBuffer("http://localhost/jolokia")); expect(request.getContextPath()).andReturn("/jolokia"); expect(request.getAuthType()).andReturn(null); expect(request.getParameterMap()).andReturn(null); expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null); expect(request.getAttribute("subject")).andReturn(null); } }, new Runnable() { public void run() { response.setHeader("Access-Control-Allow-Origin", out); response.setHeader("Access-Control-Allow-Credentials","true"); response.setCharacterEncoding("utf-8"); response.setContentType("text/plain"); response.setStatus(200); } } ); expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain"); replay(request, response); servlet.doGet(request, response); servlet.destroy(); } private void setNoCacheHeaders(HttpServletResponse pResp) { pResp.setHeader("Cache-Control", "no-cache"); pResp.setHeader("Pragma","no-cache"); pResp.setDateHeader(eq("Date"),anyLong()); pResp.setDateHeader(eq("Expires"),anyLong()); } @Test public void withCallback() throws IOException, ServletException { prepareStandardInitialisation(); ByteArrayOutputStream sw = initRequestResponseMocks( "myCallback", getStandardRequestSetup(), new Runnable() { public void run() { response.setCharacterEncoding("utf-8"); response.setContentType("text/javascript"); response.setStatus(200); } }); expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getAttribute("subject")).andReturn(null); replay(request, response); servlet.doGet(request, response); assertTrue(sw.toString().matches("^myCallback\\(.*\\);$")); servlet.destroy(); } @Test public void withException() throws ServletException, IOException { servlet = new AgentServlet(new AllowAllRestrictor()); initConfigMocks(null, null,"Error 500", IllegalStateException.class); replay(config, context); servlet.init(config); ByteArrayOutputStream sw = initRequestResponseMocks( new Runnable() { public void run() { expect(request.getHeader("Origin")).andReturn(null); expect(request.getRemoteHost()).andThrow(new IllegalStateException()); } }, getStandardResponseSetup()); expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain"); expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null); replay(request, response); servlet.doGet(request, response); String resp = sw.toString(); assertTrue(resp.contains("error_type")); assertTrue(resp.contains("IllegalStateException")); assertTrue(resp.matches(".*status.*500.*")); servlet.destroy(); verify(config, context, request, response); } @Test public void debug() throws IOException, ServletException { servlet = new AgentServlet(); initConfigMocks(new String[]{ConfigKey.DEBUG.getKeyValue(), "true"},null,"No access restrictor found",null); context.log(find("URI:")); context.log(find("Path-Info:")); context.log(find("Request:")); context.log(find("time:")); context.log(find("Response:")); context.log(find("TestDetector"),isA(RuntimeException.class)); expectLastCall().asStub(); replay(config, context); servlet.init(config); ByteArrayOutputStream sw = initRequestResponseMocks(); expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null); expect(request.getAttribute("subject")).andReturn(null); replay(request, response); servlet.doGet(request, response); assertTrue(sw.toString().contains("used")); servlet.destroy(); } @BeforeMethod void resetTestDetector() { TestDetector.reset(); } //@AfterMethod public void verifyMocks() { verify(config, context, request, response); } // ============================================================================================ private void initConfigMocks(String[] pInitParams, String[] pContextParams,String pLogRegexp, Class<? extends Exception> pExceptionClass) { config = createMock(ServletConfig.class); context = createMock(ServletContext.class); String[] params = pInitParams != null ? Arrays.copyOf(pInitParams,pInitParams.length + 2) : new String[2]; params[params.length - 2] = ConfigKey.DEBUG.getKeyValue(); params[params.length - 1] = "true"; HttpTestUtil.prepareServletConfigMock(config,params); HttpTestUtil.prepareServletContextMock(context, pContextParams); expect(config.getServletContext()).andStubReturn(context); expect(config.getServletName()).andStubReturn("jolokia"); if (pExceptionClass != null) { context.log(find(pLogRegexp),isA(pExceptionClass)); } else { if (pLogRegexp != null) { context.log(find(pLogRegexp)); } else { context.log((String) anyObject()); } } context.log((String) anyObject()); expectLastCall().asStub(); context.log(find("TestDetector"),isA(RuntimeException.class)); context.log((String) anyObject(),isA(JMException.class)); expectLastCall().anyTimes(); } private ByteArrayOutputStream initRequestResponseMocks() throws IOException { return initRequestResponseMocks( getStandardRequestSetup(), getStandardResponseSetup()); } private ByteArrayOutputStream initRequestResponseMocks(Runnable requestSetup,Runnable responseSetup) throws IOException { return initRequestResponseMocks(null,requestSetup,responseSetup); } private ByteArrayOutputStream initRequestResponseMocks(String callback,Runnable requestSetup,Runnable responseSetup) throws IOException { request = createMock(HttpServletRequest.class); response = createMock(HttpServletResponse.class); setNoCacheHeaders(response); expect(request.getParameter(ConfigKey.CALLBACK.getKeyValue())).andReturn(callback); requestSetup.run(); responseSetup.run(); class MyServletOutputStream extends ServletOutputStream { ByteArrayOutputStream baos; public void write(int b) throws IOException { baos.write(b); } public void setBaos(ByteArrayOutputStream baos){ this.baos = baos; } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); MyServletOutputStream sos = new MyServletOutputStream(); sos.setBaos(baos); expect(response.getOutputStream()).andReturn(sos); return baos; } private void preparePostRequest(String pReq) throws IOException { ServletInputStream is = HttpTestUtil.createServletInputStream(pReq); expect(request.getInputStream()).andReturn(is); } private void prepareStandardInitialisation(Restrictor restrictor, String ... params) throws ServletException { servlet = new AgentServlet(restrictor); initConfigMocks(params.length > 0 ? params : null, null,"custom access", null); replay(config, context); servlet.init(config); } private void prepareStandardInitialisation(String ... params) throws ServletException { prepareStandardInitialisation(new AllowAllRestrictor(),params); } private Runnable getStandardResponseSetup() { return new Runnable() { public void run() { response.setCharacterEncoding("utf-8"); response.setContentType("text/plain"); response.setStatus(200); } }; } private Runnable getStandardRequestSetup() { return new Runnable() { public void run() { expect(request.getHeader("Origin")).andStubReturn(null); expect(request.getHeader("Referer")).andStubReturn(null); expect(request.getRemoteHost()).andStubReturn("localhost"); expect(request.getRemoteAddr()).andStubReturn("127.0.0.1"); expect(request.getRequestURI()).andReturn("/jolokia/"); setupAgentDetailsInitExpectations(); expect(request.getParameterMap()).andReturn(null); expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null); expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null); } }; } private void setupAgentDetailsInitExpectations() { expect(request.getRequestURI()).andReturn("/jolokia/"); expect(request.getRequestURL()).andReturn(new StringBuffer("http://localhost/jolokia")); expect(request.getContextPath()).andReturn("/jolokia/"); expect(request.getAuthType()).andReturn(null); } private Runnable getDiscoveryRequestSetup(final String url) { return new Runnable() { public void run() { expect(request.getHeader("Origin")).andStubReturn(null); expect(request.getHeader("Referer")).andStubReturn(null); expect(request.getRemoteHost()).andReturn("localhost"); expect(request.getRemoteAddr()).andReturn("127.0.0.1"); expect(request.getRequestURI()).andReturn("/jolokia/"); expect(request.getParameterMap()).andReturn(null); expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null); expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain"); StringBuffer buf = new StringBuffer(); buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getRequestURL()).andReturn(buf); expect(request.getRequestURI()).andReturn("/jolokia" + HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getContextPath()).andReturn("/jolokia"); expect(request.getAuthType()).andReturn("BASIC"); expect(request.getAttribute("subject")).andReturn(null); expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null); } }; } }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_24_2
crossvul-java_data_good_4992_0
/** * Copyright (c) 2013--2014 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package com.redhat.rhn.frontend.action.groups; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.redhat.rhn.domain.server.ManagedServerGroup; import com.redhat.rhn.frontend.struts.RequestContext; import com.redhat.rhn.frontend.struts.RhnAction; import com.redhat.rhn.frontend.struts.RhnHelper; import com.redhat.rhn.manager.system.ServerGroupManager; /** * DeleteGroupAction * @version 1.0 */ public class DeleteGroupAction extends RhnAction { private static final String DELETED_MESSAGE_KEY = "systemgroup.delete.deleted"; /** {@inheritDoc} */ @Override public ActionForward execute(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response) throws Exception { RequestContext context = new RequestContext(request); ManagedServerGroup serverGroup = context.lookupAndBindServerGroup(); if (context.isSubmitted()) { ServerGroupManager manager = ServerGroupManager.getInstance(); manager.remove(context.getCurrentUser(), serverGroup); String [] params = {StringEscapeUtils.escapeHtml(serverGroup.getName())}; getStrutsDelegate().saveMessage(DELETED_MESSAGE_KEY, params, request); return mapping.findForward("success"); } return mapping.findForward(RhnHelper.DEFAULT_FORWARD); } }
./CrossVul/dataset_final_sorted/CWE-79/java/good_4992_0
crossvul-java_data_good_1164_0
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package com.sun.faces.context; import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_EXECUTE_PARAM; import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RENDER_PARAM; import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RESET_VALUES_PARAM; import static javax.faces.FactoryFinder.VISIT_CONTEXT_FACTORY; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.application.ResourceHandler; import javax.faces.component.NamingContainer; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import javax.faces.component.visit.VisitCallback; import javax.faces.component.visit.VisitContext; import javax.faces.component.visit.VisitContextFactory; import javax.faces.component.visit.VisitContextWrapper; import javax.faces.component.visit.VisitHint; import javax.faces.component.visit.VisitResult; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.PartialResponseWriter; import javax.faces.context.PartialViewContext; import javax.faces.context.ResponseWriter; import javax.faces.event.PhaseId; import javax.faces.lifecycle.ClientWindow; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import com.sun.faces.RIConstants; import com.sun.faces.component.visit.PartialVisitContext; import com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter; import com.sun.faces.util.FacesLogger; import com.sun.faces.util.HtmlUtils; import com.sun.faces.util.Util; public class PartialViewContextImpl extends PartialViewContext { // Log instance for this class private static Logger LOGGER = FacesLogger.CONTEXT.getLogger(); private boolean released; // BE SURE TO ADD NEW IVARS TO THE RELEASE METHOD private PartialResponseWriter partialResponseWriter; private List<String> executeIds; private Collection<String> renderIds; private List<String> evalScripts; private Boolean ajaxRequest; private Boolean partialRequest; private Boolean renderAll; private FacesContext ctx; private static final String ORIGINAL_WRITER = "com.sun.faces.ORIGINAL_WRITER"; // ----------------------------------------------------------- Constructors public PartialViewContextImpl(FacesContext ctx) { this.ctx = ctx; } // ---------------------------------------------- Methods from PartialViewContext /** * @see javax.faces.context.PartialViewContext#isAjaxRequest() */ @Override public boolean isAjaxRequest() { assertNotReleased(); if (ajaxRequest == null) { ajaxRequest = "partial/ajax".equals(ctx. getExternalContext().getRequestHeaderMap().get("Faces-Request")); if (!ajaxRequest) { ajaxRequest = "partial/ajax".equals(ctx.getExternalContext().getRequestParameterMap(). get("Faces-Request")); } } return ajaxRequest; } /** * @see javax.faces.context.PartialViewContext#isPartialRequest() */ @Override public boolean isPartialRequest() { assertNotReleased(); if (partialRequest == null) { partialRequest = isAjaxRequest() || "partial/process".equals(ctx. getExternalContext().getRequestHeaderMap().get("Faces-Request")); } return partialRequest; } /** * @see javax.faces.context.PartialViewContext#isExecuteAll() */ @Override public boolean isExecuteAll() { assertNotReleased(); String execute = PARTIAL_EXECUTE_PARAM.getValue(ctx); return (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(execute)); } /** * @see javax.faces.context.PartialViewContext#isRenderAll() */ @Override public boolean isRenderAll() { assertNotReleased(); if (renderAll == null) { String render = PARTIAL_RENDER_PARAM.getValue(ctx); renderAll = (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(render)); } return renderAll; } /** * @see javax.faces.context.PartialViewContext#setRenderAll(boolean) */ @Override public void setRenderAll(boolean renderAll) { this.renderAll = renderAll; } @Override public boolean isResetValues() { Object value = PARTIAL_RESET_VALUES_PARAM.getValue(ctx); return (null != value && "true".equals(value)) ? true : false; } @Override public void setPartialRequest(boolean isPartialRequest) { this.partialRequest = isPartialRequest; } /** * @see javax.faces.context.PartialViewContext#getExecuteIds() */ @Override public Collection<String> getExecuteIds() { assertNotReleased(); if (executeIds != null) { return executeIds; } executeIds = populatePhaseClientIds(PARTIAL_EXECUTE_PARAM); // include the view parameter facet ID if there are other execute IDs // to process if (!executeIds.isEmpty()) { UIViewRoot root = ctx.getViewRoot(); if (root.getFacetCount() > 0) { if (root.getFacet(UIViewRoot.METADATA_FACET_NAME) != null) { executeIds.add(0, UIViewRoot.METADATA_FACET_NAME); } } } return executeIds; } /** * @see javax.faces.context.PartialViewContext#getRenderIds() */ @Override public Collection<String> getRenderIds() { assertNotReleased(); if (renderIds != null) { return renderIds; } renderIds = populatePhaseClientIds(PARTIAL_RENDER_PARAM); return renderIds; } /** * @see javax.faces.context.PartialViewContext#getEvalScripts() */ @Override public List<String> getEvalScripts() { assertNotReleased(); if (evalScripts == null) { evalScripts = new ArrayList<>(1); } return evalScripts; } /** * @see PartialViewContext#processPartial(javax.faces.event.PhaseId) */ @Override public void processPartial(PhaseId phaseId) { PartialViewContext pvc = ctx.getPartialViewContext(); Collection <String> myExecuteIds = pvc.getExecuteIds(); Collection <String> myRenderIds = pvc.getRenderIds(); UIViewRoot viewRoot = ctx.getViewRoot(); if (phaseId == PhaseId.APPLY_REQUEST_VALUES || phaseId == PhaseId.PROCESS_VALIDATIONS || phaseId == PhaseId.UPDATE_MODEL_VALUES) { // Skip this processing if "none" is specified in the render list, // or there were no execute phase client ids. if (myExecuteIds == null || myExecuteIds.isEmpty()) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "No execute and render identifiers specified. Skipping component processing."); } return; } try { processComponents(viewRoot, phaseId, myExecuteIds, ctx); } catch (Exception e) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, e.toString(), e); } throw new FacesException(e); } // If we have just finished APPLY_REQUEST_VALUES phase, install the // partial response writer. We want to make sure that any content // or errors generated in the other phases are written using the // partial response writer. // if (phaseId == PhaseId.APPLY_REQUEST_VALUES) { PartialResponseWriter writer = pvc.getPartialResponseWriter(); ctx.setResponseWriter(writer); } } else if (phaseId == PhaseId.RENDER_RESPONSE) { try { // // We re-enable response writing. // PartialResponseWriter writer = pvc.getPartialResponseWriter(); ResponseWriter orig = ctx.getResponseWriter(); ctx.getAttributes().put(ORIGINAL_WRITER, orig); ctx.setResponseWriter(writer); ExternalContext exContext = ctx.getExternalContext(); exContext.setResponseContentType(RIConstants.TEXT_XML_CONTENT_TYPE); exContext.addResponseHeader("Cache-Control", "no-cache"); // String encoding = writer.getCharacterEncoding( ); // if( encoding == null ) { // encoding = "UTF-8"; // } // writer.writePreamble("<?xml version='1.0' encoding='" + encoding + "'?>\n"); writer.startDocument(); if (isResetValues()) { viewRoot.resetValues(ctx, myRenderIds); } if (isRenderAll()) { renderAll(ctx, viewRoot); renderState(ctx); writer.endDocument(); return; } renderComponentResources(ctx, viewRoot); // Skip this processing if "none" is specified in the render list, // or there were no render phase client ids. if (myRenderIds != null && !myRenderIds.isEmpty()) { processComponents(viewRoot, phaseId, myRenderIds, ctx); } renderState(ctx); renderEvalScripts(ctx); writer.endDocument(); } catch (IOException ex) { this.cleanupAfterView(); } catch (RuntimeException ex) { this.cleanupAfterView(); // Throw the exception throw ex; } } } /** * @see javax.faces.context.PartialViewContext#getPartialResponseWriter() */ @Override public PartialResponseWriter getPartialResponseWriter() { assertNotReleased(); if (partialResponseWriter == null) { partialResponseWriter = new DelayedInitPartialResponseWriter(this); } return partialResponseWriter; } /** * @see javax.faces.context.PartialViewContext#release() */ @Override public void release() { released = true; ajaxRequest = null; renderAll = null; partialResponseWriter = null; executeIds = null; renderIds = null; evalScripts = null; ctx = null; partialRequest = null; } // -------------------------------------------------------- Private Methods private List<String> populatePhaseClientIds(PredefinedPostbackParameter parameterName) { String param = parameterName.getValue(ctx); if (param == null) { return new ArrayList<>(); } else { Map<String, Object> appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap(); String[] pcs = Util.split(appMap, param, "[ \t]+"); return ((pcs != null && pcs.length != 0) ? new ArrayList<>(Arrays.asList(pcs)) : new ArrayList<>()); } } // Process the components specified in the phaseClientIds list private void processComponents(UIComponent component, PhaseId phaseId, Collection<String> phaseClientIds, FacesContext context) throws IOException { // We use the tree visitor mechanism to locate the components to // process. Create our (partial) VisitContext and the // VisitCallback that will be invoked for each component that // is visited. Note that we use the SKIP_UNRENDERED hint as we // only want to visit the rendered subtree. EnumSet<VisitHint> hints = EnumSet.of(VisitHint.SKIP_UNRENDERED, VisitHint.EXECUTE_LIFECYCLE); VisitContextFactory visitContextFactory = (VisitContextFactory) FactoryFinder.getFactory(VISIT_CONTEXT_FACTORY); VisitContext visitContext = visitContextFactory.getVisitContext(context, phaseClientIds, hints); PhaseAwareVisitCallback visitCallback = new PhaseAwareVisitCallback(ctx, phaseId); component.visitTree(visitContext, visitCallback); PartialVisitContext partialVisitContext = unwrapPartialVisitContext(visitContext); if (partialVisitContext != null) { if (LOGGER.isLoggable(Level.FINER) && !partialVisitContext.getUnvisitedClientIds().isEmpty()) { Collection<String> unvisitedClientIds = partialVisitContext.getUnvisitedClientIds(); StringBuilder builder = new StringBuilder(); for (String cur : unvisitedClientIds) { builder.append(cur).append(" "); } LOGGER.log(Level.FINER, "jsf.context.partial_visit_context_unvisited_children", new Object[]{builder.toString()}); } } } /** * Unwraps {@link PartialVisitContext} from a chain of {@link VisitContextWrapper}s. * * If no {@link PartialVisitContext} is found in the chain, null is returned instead. * * @param visitContext the visit context. * @return the (unwrapped) partial visit context. */ private static PartialVisitContext unwrapPartialVisitContext(VisitContext visitContext) { if (visitContext == null) { return null; } if (visitContext instanceof PartialVisitContext) { return (PartialVisitContext) visitContext; } if (visitContext instanceof VisitContextWrapper) { return unwrapPartialVisitContext(((VisitContextWrapper) visitContext).getWrapped()); } return null; } private void renderAll(FacesContext context, UIViewRoot viewRoot) throws IOException { // If this is a "render all via ajax" request, // make sure to wrap the entire page in a <render> elemnt // with the special viewStateId of VIEW_ROOT_ID. This is how the client // JavaScript knows how to replace the entire document with // this response. PartialViewContext pvc = context.getPartialViewContext(); PartialResponseWriter writer = pvc.getPartialResponseWriter(); if (!(viewRoot instanceof NamingContainer)) { writer.startUpdate(PartialResponseWriter.RENDER_ALL_MARKER); if (viewRoot.getChildCount() > 0) { for (UIComponent uiComponent : viewRoot.getChildren()) { uiComponent.encodeAll(context); } } writer.endUpdate(); } else { /* * If we have a portlet request, start rendering at the view root. */ writer.startUpdate(viewRoot.getClientId(context)); viewRoot.encodeBegin(context); if (viewRoot.getChildCount() > 0) { for (UIComponent uiComponent : viewRoot.getChildren()) { uiComponent.encodeAll(context); } } viewRoot.encodeEnd(context); writer.endUpdate(); } } private void renderComponentResources(FacesContext context, UIViewRoot viewRoot) throws IOException { ResourceHandler resourceHandler = context.getApplication().getResourceHandler(); PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter(); boolean updateStarted = false; for (UIComponent resource : viewRoot.getComponentResources(context)) { String name = (String) resource.getAttributes().get("name"); String library = (String) resource.getAttributes().get("library"); if (resource.getChildCount() == 0 && resourceHandler.getRendererTypeForResourceName(name) != null && !resourceHandler.isResourceRendered(context, name, library)) { if (!updateStarted) { writer.startUpdate("javax.faces.Resource"); updateStarted = true; } resource.encodeAll(context); } } if (updateStarted) { writer.endUpdate(); } } private void renderState(FacesContext context) throws IOException { // Get the view state and write it to the response.. PartialViewContext pvc = context.getPartialViewContext(); PartialResponseWriter writer = pvc.getPartialResponseWriter(); String viewStateId = Util.getViewStateId(context); writer.startUpdate(viewStateId); String state = context.getApplication().getStateManager().getViewState(context); writer.write(state); writer.endUpdate(); ClientWindow window = context.getExternalContext().getClientWindow(); if (null != window) { String clientWindowId = Util.getClientWindowId(context); writer.startUpdate(clientWindowId); writer.writeText(window.getId(), null); writer.endUpdate(); } } private void renderEvalScripts(FacesContext context) throws IOException { PartialViewContext pvc = context.getPartialViewContext(); PartialResponseWriter writer = pvc.getPartialResponseWriter(); for (String evalScript : pvc.getEvalScripts()) { writer.startEval(); writer.write(evalScript); writer.endEval(); } } private PartialResponseWriter createPartialResponseWriter() { ExternalContext extContext = ctx.getExternalContext(); String encoding = extContext.getRequestCharacterEncoding(); extContext.setResponseCharacterEncoding(encoding); ResponseWriter responseWriter = null; Writer out = null; try { out = extContext.getResponseOutputWriter(); } catch (IOException ioe) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, ioe.toString(), ioe); } } if (out != null) { UIViewRoot viewRoot = ctx.getViewRoot(); if (viewRoot != null) { responseWriter = ctx.getRenderKit().createResponseWriter(out, RIConstants.TEXT_XML_CONTENT_TYPE, encoding); } else { RenderKitFactory factory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = factory.getRenderKit(ctx, RenderKitFactory.HTML_BASIC_RENDER_KIT); responseWriter = renderKit.createResponseWriter(out, RIConstants.TEXT_XML_CONTENT_TYPE, encoding); } } if (responseWriter instanceof PartialResponseWriter) { return (PartialResponseWriter) responseWriter; } else { return new PartialResponseWriter(responseWriter); } } private void cleanupAfterView() { ResponseWriter orig = (ResponseWriter) ctx.getAttributes(). get(ORIGINAL_WRITER); assert(null != orig); // move aside the PartialResponseWriter ctx.setResponseWriter(orig); } private void assertNotReleased() { if (released) { throw new IllegalStateException(); } } // ----------------------------------------------------------- Inner Classes private static class PhaseAwareVisitCallback implements VisitCallback { private PhaseId curPhase; private FacesContext ctx; private PhaseAwareVisitCallback(FacesContext ctx, PhaseId curPhase) { this.ctx = ctx; this.curPhase = curPhase; } @Override public VisitResult visit(VisitContext context, UIComponent comp) { try { if (curPhase == PhaseId.APPLY_REQUEST_VALUES) { // RELEASE_PENDING handle immediate request(s) // If the user requested an immediate request // Make sure to set the immediate flag here. comp.processDecodes(ctx); } else if (curPhase == PhaseId.PROCESS_VALIDATIONS) { comp.processValidators(ctx); } else if (curPhase == PhaseId.UPDATE_MODEL_VALUES) { comp.processUpdates(ctx); } else if (curPhase == PhaseId.RENDER_RESPONSE) { PartialResponseWriter writer = ctx.getPartialViewContext().getPartialResponseWriter(); writer.startUpdate(comp.getClientId(ctx)); // do the default behavior... comp.encodeAll(ctx); writer.endUpdate(); } else { throw new IllegalStateException("I18N: Unexpected " + "PhaseId passed to " + " PhaseAwareContextCallback: " + curPhase.toString()); } } catch (IOException ex) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(ex.toString()); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, ex.toString(), ex); } throw new FacesException(ex); } // Once we visit a component, there is no need to visit // its children, since processDecodes/Validators/Updates and // encodeAll() already traverse the subtree. We return // VisitResult.REJECT to supress the subtree visit. return VisitResult.REJECT; } } /** * Delays the actual construction of the PartialResponseWriter <em>until</em> * content is going to actually be written. */ private static final class DelayedInitPartialResponseWriter extends PartialResponseWriter { private ResponseWriter writer; private PartialViewContextImpl ctx; // -------------------------------------------------------- Constructors public DelayedInitPartialResponseWriter(PartialViewContextImpl ctx) { super(null); this.ctx = ctx; ExternalContext extCtx = ctx.ctx.getExternalContext(); extCtx.setResponseContentType(RIConstants.TEXT_XML_CONTENT_TYPE); extCtx.setResponseCharacterEncoding(extCtx.getRequestCharacterEncoding()); extCtx.setResponseBufferSize(ctx.ctx.getExternalContext().getResponseBufferSize()); } // ---------------------------------- Methods from PartialResponseWriter @Override public void write(String text) throws IOException { HtmlUtils.writeUnescapedTextForXML(getWrapped(), text); } @Override public ResponseWriter getWrapped() { if (writer == null) { writer = ctx.createPartialResponseWriter(); } return writer; } } // END DelayedInitPartialResponseWriter }
./CrossVul/dataset_final_sorted/CWE-79/java/good_1164_0
crossvul-java_data_bad_2097_2
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe, * Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc., * Yahoo!, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jenkins.model; import com.google.common.collect.Lists; import com.google.inject.Injector; import hudson.ExtensionComponent; import hudson.ExtensionFinder; import hudson.model.LoadStatistics; import hudson.model.Messages; import hudson.model.Node; import hudson.model.AbstractCIBase; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.AdministrativeMonitor; import hudson.model.AllView; import hudson.model.Api; import hudson.model.Computer; import hudson.model.ComputerSet; import hudson.model.DependencyGraph; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.DescriptorByNameOwner; import hudson.model.DirectoryBrowserSupport; import hudson.model.Failure; import hudson.model.Fingerprint; import hudson.model.FingerprintCleanupThread; import hudson.model.FingerprintMap; import hudson.model.FullDuplexHttpChannel; import hudson.model.Hudson; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.ItemGroupMixIn; import hudson.model.Items; import hudson.model.JDK; import hudson.model.Job; import hudson.model.JobPropertyDescriptor; import hudson.model.Label; import hudson.model.ListView; import hudson.model.LoadBalancer; import hudson.model.ManagementLink; import hudson.model.NoFingerprintMatch; import hudson.model.OverallLoadStatistics; import hudson.model.Project; import hudson.model.RestartListener; import hudson.model.RootAction; import hudson.model.Slave; import hudson.model.TaskListener; import hudson.model.TopLevelItem; import hudson.model.TopLevelItemDescriptor; import hudson.model.UnprotectedRootAction; import hudson.model.UpdateCenter; import hudson.model.User; import hudson.model.View; import hudson.model.ViewGroup; import hudson.model.ViewGroupMixIn; import hudson.model.Descriptor.FormException; import hudson.model.labels.LabelAtom; import hudson.model.listeners.ItemListener; import hudson.model.listeners.SCMListener; import hudson.model.listeners.SaveableListener; import hudson.model.Queue; import hudson.model.WorkspaceCleanupThread; import antlr.ANTLRException; import com.google.common.collect.ImmutableMap; import com.thoughtworks.xstream.XStream; import hudson.BulkChange; import hudson.DNSMultiCast; import hudson.DescriptorExtensionList; import hudson.Extension; import hudson.ExtensionList; import hudson.ExtensionPoint; import hudson.FilePath; import hudson.Functions; import hudson.Launcher; import hudson.Launcher.LocalLauncher; import hudson.LocalPluginManager; import hudson.Lookup; import hudson.markup.MarkupFormatter; import hudson.Plugin; import hudson.PluginManager; import hudson.PluginWrapper; import hudson.ProxyConfiguration; import hudson.TcpSlaveAgentListener; import hudson.UDPBroadcastThread; import hudson.Util; import static hudson.Util.fixEmpty; import static hudson.Util.fixNull; import hudson.WebAppMain; import hudson.XmlFile; import hudson.cli.CLICommand; import hudson.cli.CliEntryPoint; import hudson.cli.CliManagerImpl; import hudson.cli.declarative.CLIMethod; import hudson.cli.declarative.CLIResolver; import hudson.init.InitMilestone; import hudson.init.InitStrategy; import hudson.lifecycle.Lifecycle; import hudson.logging.LogRecorderManager; import hudson.lifecycle.RestartNotSupportedException; import hudson.markup.RawHtmlMarkupFormatter; import hudson.remoting.Channel; import hudson.remoting.LocalChannel; import hudson.remoting.VirtualChannel; import hudson.scm.RepositoryBrowser; import hudson.scm.SCM; import hudson.search.CollectionSearchIndex; import hudson.search.SearchIndexBuilder; import hudson.search.SearchItem; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.security.AuthorizationStrategy; import hudson.security.FederatedLoginService; import hudson.security.FullControlOnceLoggedInAuthorizationStrategy; import hudson.security.HudsonFilter; import hudson.security.LegacyAuthorizationStrategy; import hudson.security.LegacySecurityRealm; import hudson.security.Permission; import hudson.security.PermissionGroup; import hudson.security.PermissionScope; import hudson.security.SecurityMode; import hudson.security.SecurityRealm; import hudson.security.csrf.CrumbIssuer; import hudson.slaves.Cloud; import hudson.slaves.ComputerListener; import hudson.slaves.DumbSlave; import hudson.slaves.EphemeralNode; import hudson.slaves.NodeDescriptor; import hudson.slaves.NodeList; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import hudson.slaves.NodeProvisioner; import hudson.slaves.OfflineCause; import hudson.slaves.RetentionStrategy; import hudson.tasks.BuildWrapper; import hudson.tasks.Builder; import hudson.tasks.Publisher; import hudson.triggers.SafeTimerTask; import hudson.triggers.Trigger; import hudson.triggers.TriggerDescriptor; import hudson.util.AdministrativeError; import hudson.util.CaseInsensitiveComparator; import hudson.util.ClockDifference; import hudson.util.CopyOnWriteList; import hudson.util.CopyOnWriteMap; import hudson.util.DaemonThreadFactory; import hudson.util.DescribableList; import hudson.util.FormApply; import hudson.util.FormValidation; import hudson.util.Futures; import hudson.util.HudsonIsLoading; import hudson.util.HudsonIsRestarting; import hudson.util.Iterators; import hudson.util.JenkinsReloadFailed; import hudson.util.Memoizer; import hudson.util.MultipartFormDataParser; import hudson.util.RemotingDiagnostics; import hudson.util.RemotingDiagnostics.HeapDump; import hudson.util.StreamTaskListener; import hudson.util.TextFile; import hudson.util.TimeUnit2; import hudson.util.VersionNumber; import hudson.util.XStream2; import hudson.views.DefaultMyViewsTabBar; import hudson.views.DefaultViewsTabBar; import hudson.views.MyViewsTabBar; import hudson.views.ViewsTabBar; import hudson.widgets.Widget; import jenkins.ExtensionComponentSet; import jenkins.ExtensionRefreshException; import jenkins.InitReactorRunner; import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy; import jenkins.security.ConfidentialKey; import jenkins.security.ConfidentialStore; import jenkins.slaves.WorkspaceLocator; import jenkins.util.io.FileBoolean; import net.sf.json.JSONObject; import org.acegisecurity.AccessDeniedException; import org.acegisecurity.AcegiSecurityException; import org.acegisecurity.Authentication; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.GrantedAuthorityImpl; import org.acegisecurity.context.SecurityContextHolder; import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken; import org.acegisecurity.ui.AbstractProcessingFilter; import org.apache.commons.jelly.JellyException; import org.apache.commons.jelly.Script; import org.apache.commons.logging.LogFactory; import org.jvnet.hudson.reactor.Executable; import org.jvnet.hudson.reactor.ReactorException; import org.jvnet.hudson.reactor.Task; import org.jvnet.hudson.reactor.TaskBuilder; import org.jvnet.hudson.reactor.TaskGraphBuilder; import org.jvnet.hudson.reactor.Reactor; import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; import org.kohsuke.stapler.Ancestor; import org.kohsuke.stapler.HttpRedirect; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.MetaClass; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerFallback; import org.kohsuke.stapler.StaplerProxy; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.WebApp; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import org.kohsuke.stapler.framework.adjunct.AdjunctManager; import org.kohsuke.stapler.interceptor.RequirePOST; import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff; import org.kohsuke.stapler.jelly.JellyRequestDispatcher; import org.xml.sax.InputSource; import javax.crypto.SecretKey; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import static hudson.init.InitMilestone.*; import hudson.security.BasicAuthenticationFilter; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.BindException; import java.net.URL; import java.nio.charset.Charset; import java.security.SecureRandom; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.Timer; import java.util.TreeSet; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import static java.util.logging.Level.SEVERE; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Root object of the system. * * @author Kohsuke Kawaguchi */ @ExportedBean public class Jenkins extends AbstractCIBase implements ModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback, ViewGroup, AccessControlled, DescriptorByNameOwner, ModelObjectWithContextMenu { private transient final Queue queue; /** * Stores various objects scoped to {@link Jenkins}. */ public transient final Lookup lookup = new Lookup(); /** * We update this field to the current version of Hudson whenever we save {@code config.xml}. * This can be used to detect when an upgrade happens from one version to next. * * <p> * Since this field is introduced starting 1.301, "1.0" is used to represent every version * up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or * "?", etc., so parsing needs to be done with a care. * * @since 1.301 */ // this field needs to be at the very top so that other components can look at this value even during unmarshalling private String version = "1.0"; /** * Number of executors of the master node. */ private int numExecutors = 2; /** * Job allocation strategy. */ private Mode mode = Mode.NORMAL; /** * False to enable anyone to do anything. * Left as a field so that we can still read old data that uses this flag. * * @see #authorizationStrategy * @see #securityRealm */ private Boolean useSecurity; /** * Controls how the * <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a> * is handled in Hudson. * <p> * This ultimately controls who has access to what. * * Never null. */ private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED; /** * Controls a part of the * <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a> * handling in Hudson. * <p> * Intuitively, this corresponds to the user database. * * See {@link HudsonFilter} for the concrete authentication protocol. * * Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to * update this field. * * @see #getSecurity() * @see #setSecurityRealm(SecurityRealm) */ private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION; /** * The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention? */ private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; /** * Root directory for the workspaces. * This value will be variable-expanded as per {@link #expandVariablesForDirectory}. * @see #getWorkspaceFor(TopLevelItem) */ private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME; /** * Root directory for the builds. * This value will be variable-expanded as per {@link #expandVariablesForDirectory}. * @see #getBuildDirFor(Job) */ private String buildsDir = "${ITEM_ROOTDIR}/builds"; /** * Message displayed in the top page. */ private String systemMessage; private MarkupFormatter markupFormatter; /** * Root directory of the system. */ public transient final File root; /** * Where are we in the initialization? */ private transient volatile InitMilestone initLevel = InitMilestone.STARTED; /** * All {@link Item}s keyed by their {@link Item#getName() name}s. */ /*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE); /** * The sole instance. */ private static Jenkins theInstance; private transient volatile boolean isQuietingDown; private transient volatile boolean terminating; private List<JDK> jdks = new ArrayList<JDK>(); private transient volatile DependencyGraph dependencyGraph; /** * Currently active Views tab bar. */ private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar(); /** * Currently active My Views tab bar. */ private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar(); /** * All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}. */ private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() { public ExtensionList compute(Class key) { return ExtensionList.create(Jenkins.this,key); } }; /** * All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}. */ private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() { public DescriptorExtensionList compute(Class key) { return DescriptorExtensionList.createDescriptorList(Jenkins.this,key); } }; /** * {@link Computer}s in this Hudson system. Read-only. */ protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>(); /** * Active {@link Cloud}s. */ public final Hudson.CloudList clouds = new Hudson.CloudList(this); public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> { public CloudList(Jenkins h) { super(h); } public CloudList() {// needed for XStream deserialization } public Cloud getByName(String name) { for (Cloud c : this) if (c.name.equals(name)) return c; return null; } @Override protected void onModified() throws IOException { super.onModified(); Jenkins.getInstance().trimLabels(); } } /** * Set of installed cluster nodes. * <p> * We use this field with copy-on-write semantics. * This field has mutable list (to keep the serialization look clean), * but it shall never be modified. Only new completely populated slave * list can be set here. * <p> * The field name should be really {@code nodes}, but again the backward compatibility * prevents us from renaming. */ protected volatile NodeList slaves; /** * Quiet period. * * This is {@link Integer} so that we can initialize it to '5' for upgrading users. */ /*package*/ Integer quietPeriod; /** * Global default for {@link AbstractProject#getScmCheckoutRetryCount()} */ /*package*/ int scmCheckoutRetryCount; /** * {@link View}s. */ private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>(); /** * Name of the primary view. * <p> * Start with null, so that we can upgrade pre-1.269 data well. * @since 1.269 */ private volatile String primaryView; private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) { protected List<View> views() { return views; } protected String primaryView() { return primaryView; } protected void primaryView(String name) { primaryView=name; } }; private transient final FingerprintMap fingerprintMap = new FingerprintMap(); /** * Loaded plugins. */ public transient final PluginManager pluginManager; public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener; private transient UDPBroadcastThread udpBroadcastThread; private transient DNSMultiCast dnsMultiCast; /** * List of registered {@link SCMListener}s. */ private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>(); /** * TCP slave agent port. * 0 for random, -1 to disable. */ private int slaveAgentPort =0; /** * Whitespace-separated labels assigned to the master as a {@link Node}. */ private String label=""; /** * {@link hudson.security.csrf.CrumbIssuer} */ private volatile CrumbIssuer crumbIssuer; /** * All labels known to Jenkins. This allows us to reuse the same label instances * as much as possible, even though that's not a strict requirement. */ private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>(); /** * Load statistics of the entire system. * * This includes every executor and every job in the system. */ @Exported public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics(); /** * Load statistics of the free roaming jobs and slaves. * * This includes all executors on {@link Mode#NORMAL} nodes and jobs that do not have any assigned nodes. * * @since 1.467 */ @Exported public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics(); /** * {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}. * @since 1.467 */ public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad); /** * @deprecated as of 1.467 * Use {@link #unlabeledNodeProvisioner}. * This was broken because it was tracking all the executors in the system, but it was only tracking * free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive * slaves and free-roaming jobs in the queue. */ @Restricted(NoExternalUse.class) public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner; public transient final ServletContext servletContext; /** * Transient action list. Useful for adding navigation items to the navigation bar * on the left. */ private transient final List<Action> actions = new CopyOnWriteArrayList<Action>(); /** * List of master node properties */ private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this); /** * List of global properties */ private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this); /** * {@link AdministrativeMonitor}s installed on this system. * * @see AdministrativeMonitor */ public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class); /** * Widgets on Hudson. */ private transient final List<Widget> widgets = getExtensionList(Widget.class); /** * {@link AdjunctManager} */ private transient final AdjunctManager adjuncts; /** * Code that handles {@link ItemGroup} work. */ private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) { @Override protected void add(TopLevelItem item) { items.put(item.getName(),item); } @Override protected File getRootDirFor(String name) { return Jenkins.this.getRootDirFor(name); } /** * Send the browser to the config page. * use View to trim view/{default-view} from URL if possible */ @Override protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException { String redirect = result.getUrl()+"configure"; List<Ancestor> ancestors = req.getAncestors(); for (int i = ancestors.size() - 1; i >= 0; i--) { Object o = ancestors.get(i).getObject(); if (o instanceof View) { redirect = req.getContextPath() + '/' + ((View)o).getUrl() + redirect; break; } } return redirect; } }; /** * Hook for a test harness to intercept Jenkins.getInstance() * * Do not use in the production code as the signature may change. */ public interface JenkinsHolder { Jenkins getInstance(); } static JenkinsHolder HOLDER = new JenkinsHolder() { public Jenkins getInstance() { return theInstance; } }; @CLIResolver public static Jenkins getInstance() { return HOLDER.getInstance(); } /** * Secret key generated once and used for a long time, beyond * container start/stop. Persisted outside <tt>config.xml</tt> to avoid * accidental exposure. */ private transient final String secretKey; private transient final UpdateCenter updateCenter = new UpdateCenter(); /** * True if the user opted out from the statistics tracking. We'll never send anything if this is true. */ private Boolean noUsageStatistics; /** * HTTP proxy configuration. */ public transient volatile ProxyConfiguration proxy; /** * Bound to "/log". */ private transient final LogRecorderManager log = new LogRecorderManager(); protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException { this(root,context,null); } /** * @param pluginManager * If non-null, use existing plugin manager. create a new one. */ @edu.umd.cs.findbugs.annotations.SuppressWarnings({ "SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer }) protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException { long start = System.currentTimeMillis(); // As Jenkins is starting, grant this process full control ACL.impersonate(ACL.SYSTEM); try { this.root = root; this.servletContext = context; computeVersion(context); if(theInstance!=null) throw new IllegalStateException("second instance"); theInstance = this; if (!new File(root,"jobs").exists()) { // if this is a fresh install, use more modern default layout that's consistent with slaves workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}"; } // doing this early allows InitStrategy to set environment upfront final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader()); Trigger.timer = new Timer("Jenkins cron thread"); queue = new Queue(LoadBalancer.CONSISTENT_HASH); try { dependencyGraph = DependencyGraph.EMPTY; } catch (InternalError e) { if(e.getMessage().contains("window server")) { throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e); } throw e; } // get or create the secret TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key")); if(secretFile.exists()) { secretKey = secretFile.readTrim(); } else { SecureRandom sr = new SecureRandom(); byte[] random = new byte[32]; sr.nextBytes(random); secretKey = Util.toHexString(random); secretFile.write(secretKey); // this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49. // this indicates that there's no need to rewrite secrets on disk new FileBoolean(new File(root,"secret.key.not-so-secret")).on(); } try { proxy = ProxyConfiguration.load(); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to load proxy configuration", e); } if (pluginManager==null) pluginManager = new LocalPluginManager(this); this.pluginManager = pluginManager; // JSON binding needs to be able to see all the classes from all the plugins WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader); adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365)); // initialization consists of ... executeReactor( is, pluginManager.initTasks(is), // loading and preparing plugins loadTasks(), // load jobs InitMilestone.ordering() // forced ordering among key milestones ); if(KILL_AFTER_LOAD) System.exit(0); if(slaveAgentPort!=-1) { try { tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); } catch (BindException e) { new AdministrativeError(getClass().getName()+".tcpBind", "Failed to listen to incoming slave connection", "Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e); } } else tcpSlaveAgentListener = null; try { udpBroadcastThread = new UDPBroadcastThread(this); udpBroadcastThread.start(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to broadcast over UDP",e); } dnsMultiCast = new DNSMultiCast(this); Timer timer = Trigger.timer; if (timer != null) { timer.scheduleAtFixedRate(new SafeTimerTask() { @Override protected void doRun() throws Exception { trimLabels(); } }, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5)); } updateComputerList(); {// master is online now Computer c = toComputer(); if(c!=null) for (ComputerListener cl : ComputerListener.all()) cl.onOnline(c,StreamTaskListener.fromStdout()); } for (ItemListener l : ItemListener.all()) { long itemListenerStart = System.currentTimeMillis(); l.onLoaded(); if (LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for item listener %s startup", System.currentTimeMillis()-itemListenerStart,l.getClass().getName())); } if (LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for complete Jenkins startup", System.currentTimeMillis()-start)); } finally { SecurityContextHolder.clearContext(); } } /** * Executes a reactor. * * @param is * If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Hudson. */ private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException { Reactor reactor = new Reactor(builders) { /** * Sets the thread name to the task for better diagnostics. */ @Override protected void runTask(Task task) throws Exception { if (is!=null && is.skipInitTask(task)) return; ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread String taskName = task.getDisplayName(); Thread t = Thread.currentThread(); String name = t.getName(); if (taskName !=null) t.setName(taskName); try { long start = System.currentTimeMillis(); super.runTask(task); if(LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for %s by %s", System.currentTimeMillis()-start, taskName, name)); } finally { t.setName(name); SecurityContextHolder.clearContext(); } } }; new InitReactorRunner() { @Override protected void onInitMilestoneAttained(InitMilestone milestone) { initLevel = milestone; } }.run(reactor); } public TcpSlaveAgentListener getTcpSlaveAgentListener() { return tcpSlaveAgentListener; } /** * Makes {@link AdjunctManager} URL-bound. * The dummy parameter allows us to use different URLs for the same adjunct, * for proper cache handling. */ public AdjunctManager getAdjuncts(String dummy) { return adjuncts; } @Exported public int getSlaveAgentPort() { return slaveAgentPort; } /** * @param port * 0 to indicate random available TCP port. -1 to disable this service. */ public void setSlaveAgentPort(int port) throws IOException { this.slaveAgentPort = port; // relaunch the agent if(tcpSlaveAgentListener==null) { if(slaveAgentPort!=-1) tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); } else { if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) { tcpSlaveAgentListener.shutdown(); tcpSlaveAgentListener = null; if(slaveAgentPort!=-1) tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); } } } public void setNodeName(String name) { throw new UnsupportedOperationException(); // not allowed } public String getNodeDescription() { return Messages.Hudson_NodeDescription(); } @Exported public String getDescription() { return systemMessage; } public PluginManager getPluginManager() { return pluginManager; } public UpdateCenter getUpdateCenter() { return updateCenter; } public boolean isUsageStatisticsCollected() { return noUsageStatistics==null || !noUsageStatistics; } public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException { this.noUsageStatistics = noUsageStatistics; save(); } public View.People getPeople() { return new View.People(this); } /** * @since 1.484 */ public View.AsynchPeople getAsynchPeople() { return new View.AsynchPeople(this); } /** * Does this {@link View} has any associated user information recorded? * @deprecated Potentially very expensive call; do not use from Jelly views. */ public boolean hasPeople() { return View.People.isApplicable(items.values()); } public Api getApi() { return new Api(this); } /** * Returns a secret key that survives across container start/stop. * <p> * This value is useful for implementing some of the security features. * * @deprecated * Due to the past security advisory, this value should not be used any more to protect sensitive information. * See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets. */ public String getSecretKey() { return secretKey; } /** * Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128. * @since 1.308 * @deprecated * See {@link #getSecretKey()}. */ public SecretKey getSecretKeyAsAES128() { return Util.toAes128Key(secretKey); } /** * Returns the unique identifier of this Jenkins that has been historically used to identify * this Jenkins to the outside world. * * <p> * This form of identifier is weak in that it can be impersonated by others. See * https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID * that can be challenged and verified. * * @since 1.498 */ @SuppressWarnings("deprecation") public String getLegacyInstanceId() { return Util.getDigestOf(getSecretKey()); } /** * Gets the SCM descriptor by name. Primarily used for making them web-visible. */ public Descriptor<SCM> getScm(String shortClassName) { return findDescriptor(shortClassName,SCM.all()); } /** * Gets the repository browser descriptor by name. Primarily used for making them web-visible. */ public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) { return findDescriptor(shortClassName,RepositoryBrowser.all()); } /** * Gets the builder descriptor by name. Primarily used for making them web-visible. */ public Descriptor<Builder> getBuilder(String shortClassName) { return findDescriptor(shortClassName, Builder.all()); } /** * Gets the build wrapper descriptor by name. Primarily used for making them web-visible. */ public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) { return findDescriptor(shortClassName, BuildWrapper.all()); } /** * Gets the publisher descriptor by name. Primarily used for making them web-visible. */ public Descriptor<Publisher> getPublisher(String shortClassName) { return findDescriptor(shortClassName, Publisher.all()); } /** * Gets the trigger descriptor by name. Primarily used for making them web-visible. */ public TriggerDescriptor getTrigger(String shortClassName) { return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all()); } /** * Gets the retention strategy descriptor by name. Primarily used for making them web-visible. */ public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) { return findDescriptor(shortClassName, RetentionStrategy.all()); } /** * Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible. */ public JobPropertyDescriptor getJobProperty(String shortClassName) { // combining these two lines triggers javac bug. See issue #610. Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all()); return (JobPropertyDescriptor) d; } /** * @deprecated * UI method. Not meant to be used programatically. */ public ComputerSet getComputer() { return new ComputerSet(); } /** * Exposes {@link Descriptor} by its name to URL. * * After doing all the {@code getXXX(shortClassName)} methods, I finally realized that * this just doesn't scale. * * @param id * Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility) * @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast) */ @SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix public Descriptor getDescriptor(String id) { // legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly. Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances()); for (Descriptor d : descriptors) { if (d.getId().equals(id)) { return d; } } Descriptor candidate = null; for (Descriptor d : descriptors) { String name = d.getId(); if (name.substring(name.lastIndexOf('.') + 1).equals(id)) { if (candidate == null) { candidate = d; } else { throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId()); } } } return candidate; } /** * Alias for {@link #getDescriptor(String)}. */ public Descriptor getDescriptorByName(String id) { return getDescriptor(id); } /** * Gets the {@link Descriptor} that corresponds to the given {@link Describable} type. * <p> * If you have an instance of {@code type} and call {@link Describable#getDescriptor()}, * you'll get the same instance that this method returns. */ public Descriptor getDescriptor(Class<? extends Describable> type) { for( Descriptor d : getExtensionList(Descriptor.class) ) if(d.clazz==type) return d; return null; } /** * Works just like {@link #getDescriptor(Class)} but don't take no for an answer. * * @throws AssertionError * If the descriptor is missing. * @since 1.326 */ public Descriptor getDescriptorOrDie(Class<? extends Describable> type) { Descriptor d = getDescriptor(type); if (d==null) throw new AssertionError(type+" is missing its descriptor"); return d; } /** * Gets the {@link Descriptor} instance in the current Hudson by its type. */ public <T extends Descriptor> T getDescriptorByType(Class<T> type) { for( Descriptor d : getExtensionList(Descriptor.class) ) if(d.getClass()==type) return type.cast(d); return null; } /** * Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible. */ public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) { return findDescriptor(shortClassName,SecurityRealm.all()); } /** * Finds a descriptor that has the specified name. */ private <T extends Describable<T>> Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) { String name = '.'+shortClassName; for (Descriptor<T> d : descriptors) { if(d.clazz.getName().endsWith(name)) return d; } return null; } protected void updateComputerList() throws IOException { updateComputerList(AUTOMATIC_SLAVE_LAUNCH); } /** * Gets all the installed {@link SCMListener}s. */ public CopyOnWriteList<SCMListener> getSCMListeners() { return scmListeners; } /** * Gets the plugin object from its short name. * * <p> * This allows URL <tt>hudson/plugin/ID</tt> to be served by the views * of the plugin class. */ public Plugin getPlugin(String shortName) { PluginWrapper p = pluginManager.getPlugin(shortName); if(p==null) return null; return p.getPlugin(); } /** * Gets the plugin object from its class. * * <p> * This allows easy storage of plugin information in the plugin singleton without * every plugin reimplementing the singleton pattern. * * @param clazz The plugin class (beware class-loader fun, this will probably only work * from within the jpi that defines the plugin class, it may or may not work in other cases) * * @return The plugin instance. */ @SuppressWarnings("unchecked") public <P extends Plugin> P getPlugin(Class<P> clazz) { PluginWrapper p = pluginManager.getPlugin(clazz); if(p==null) return null; return (P) p.getPlugin(); } /** * Gets the plugin objects from their super-class. * * @param clazz The plugin class (beware class-loader fun) * * @return The plugin instances. */ public <P extends Plugin> List<P> getPlugins(Class<P> clazz) { List<P> result = new ArrayList<P>(); for (PluginWrapper w: pluginManager.getPlugins(clazz)) { result.add((P)w.getPlugin()); } return Collections.unmodifiableList(result); } /** * Synonym for {@link #getDescription}. */ public String getSystemMessage() { return systemMessage; } /** * Gets the markup formatter used in the system. * * @return * never null. * @since 1.391 */ public MarkupFormatter getMarkupFormatter() { return markupFormatter!=null ? markupFormatter : RawHtmlMarkupFormatter.INSTANCE; } /** * Sets the markup formatter used in the system globally. * * @since 1.391 */ public void setMarkupFormatter(MarkupFormatter f) { this.markupFormatter = f; } /** * Sets the system message. */ public void setSystemMessage(String message) throws IOException { this.systemMessage = message; save(); } public FederatedLoginService getFederatedLoginService(String name) { for (FederatedLoginService fls : FederatedLoginService.all()) { if (fls.getUrlName().equals(name)) return fls; } return null; } public List<FederatedLoginService> getFederatedLoginServices() { return FederatedLoginService.all(); } public Launcher createLauncher(TaskListener listener) { return new LocalLauncher(listener).decorateFor(this); } public String getFullName() { return ""; } public String getFullDisplayName() { return ""; } /** * Returns the transient {@link Action}s associated with the top page. * * <p> * Adding {@link Action} is primarily useful for plugins to contribute * an item to the navigation bar of the top page. See existing {@link Action} * implementation for it affects the GUI. * * <p> * To register an {@link Action}, implement {@link RootAction} extension point, or write code like * {@code Hudson.getInstance().getActions().add(...)}. * * @return * Live list where the changes can be made. Can be empty but never null. * @since 1.172 */ public List<Action> getActions() { return actions; } /** * Gets just the immediate children of {@link Jenkins}. * * @see #getAllItems(Class) */ @Exported(name="jobs") public List<TopLevelItem> getItems() { if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured || authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) { return new ArrayList(items.values()); } List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>(); for (TopLevelItem item : items.values()) { if (item.hasPermission(Item.READ)) viewableItems.add(item); } return viewableItems; } /** * Returns the read-only view of all the {@link TopLevelItem}s keyed by their names. * <p> * This method is efficient, as it doesn't involve any copying. * * @since 1.296 */ public Map<String,TopLevelItem> getItemMap() { return Collections.unmodifiableMap(items); } /** * Gets just the immediate children of {@link Jenkins} but of the given type. */ public <T> List<T> getItems(Class<T> type) { List<T> r = new ArrayList<T>(); for (TopLevelItem i : getItems()) if (type.isInstance(i)) r.add(type.cast(i)); return r; } /** * Gets all the {@link Item}s recursively in the {@link ItemGroup} tree * and filter them by the given type. */ public <T extends Item> List<T> getAllItems(Class<T> type) { List<T> r = new ArrayList<T>(); Stack<ItemGroup> q = new Stack<ItemGroup>(); q.push(this); while(!q.isEmpty()) { ItemGroup<?> parent = q.pop(); for (Item i : parent.getItems()) { if(type.isInstance(i)) { if (i.hasPermission(Item.READ)) r.add(type.cast(i)); } if(i instanceof ItemGroup) q.push((ItemGroup)i); } } return r; } /** * Gets all the items recursively. * * @since 1.402 */ public List<Item> getAllItems() { return getAllItems(Item.class); } /** * Gets a list of simple top-level projects. * @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders. * You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject}, * perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s. * (That will also consider the caller's permissions.) * If you really want to get just {@link Project}s at top level, ignoring permissions, * you can filter the values from {@link #getItemMap} using {@link Util#createSubList}. */ @Deprecated public List<Project> getProjects() { return Util.createSubList(items.values(),Project.class); } /** * Gets the names of all the {@link Job}s. */ public Collection<String> getJobNames() { List<String> names = new ArrayList<String>(); for (Job j : getAllItems(Job.class)) names.add(j.getFullName()); return names; } public List<Action> getViewActions() { return getActions(); } /** * Gets the names of all the {@link TopLevelItem}s. */ public Collection<String> getTopLevelItemNames() { List<String> names = new ArrayList<String>(); for (TopLevelItem j : items.values()) names.add(j.getName()); return names; } public View getView(String name) { return viewGroupMixIn.getView(name); } /** * Gets the read-only list of all {@link View}s. */ @Exported public Collection<View> getViews() { return viewGroupMixIn.getViews(); } public void addView(View v) throws IOException { viewGroupMixIn.addView(v); } public boolean canDelete(View view) { return viewGroupMixIn.canDelete(view); } public synchronized void deleteView(View view) throws IOException { viewGroupMixIn.deleteView(view); } public void onViewRenamed(View view, String oldName, String newName) { viewGroupMixIn.onViewRenamed(view,oldName,newName); } /** * Returns the primary {@link View} that renders the top-page of Hudson. */ @Exported public View getPrimaryView() { return viewGroupMixIn.getPrimaryView(); } public void setPrimaryView(View v) { this.primaryView = v.getViewName(); } public ViewsTabBar getViewsTabBar() { return viewsTabBar; } public void setViewsTabBar(ViewsTabBar viewsTabBar) { this.viewsTabBar = viewsTabBar; } public Jenkins getItemGroup() { return this; } public MyViewsTabBar getMyViewsTabBar() { return myViewsTabBar; } public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) { this.myViewsTabBar = myViewsTabBar; } /** * Returns true if the current running Jenkins is upgraded from a version earlier than the specified version. * * <p> * This method continues to return true until the system configuration is saved, at which point * {@link #version} will be overwritten and Hudson forgets the upgrade history. * * <p> * To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version * equal or younger than N. So say if you implement a feature in 1.301 and you want to check * if the installation upgraded from pre-1.301, pass in "1.300.*" * * @since 1.301 */ public boolean isUpgradedFromBefore(VersionNumber v) { try { return new VersionNumber(version).isOlderThan(v); } catch (IllegalArgumentException e) { // fail to parse this version number return false; } } /** * Gets the read-only list of all {@link Computer}s. */ public Computer[] getComputers() { Computer[] r = computers.values().toArray(new Computer[computers.size()]); Arrays.sort(r,new Comparator<Computer>() { final Collator collator = Collator.getInstance(); public int compare(Computer lhs, Computer rhs) { if(lhs.getNode()==Jenkins.this) return -1; if(rhs.getNode()==Jenkins.this) return 1; return collator.compare(lhs.getDisplayName(), rhs.getDisplayName()); } }); return r; } @CLIResolver public Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") String name) { if(name.equals("(master)")) name = ""; for (Computer c : computers.values()) { if(c.getName().equals(name)) return c; } return null; } /** * Gets the label that exists on this system by the name. * * @return null if name is null. * @see Label#parseExpression(String) (String) */ public Label getLabel(String expr) { if(expr==null) return null; expr = hudson.util.QuotedStringTokenizer.unquote(expr); while(true) { Label l = labels.get(expr); if(l!=null) return l; // non-existent try { labels.putIfAbsent(expr,Label.parseExpression(expr)); } catch (ANTLRException e) { // laxly accept it as a single label atom for backward compatibility return getLabelAtom(expr); } } } /** * Returns the label atom of the given name. * @return non-null iff name is non-null */ public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) { if (name==null) return null; while(true) { Label l = labels.get(name); if(l!=null) return (LabelAtom)l; // non-existent LabelAtom la = new LabelAtom(name); if (labels.putIfAbsent(name, la)==null) la.load(); } } /** * Gets all the active labels in the current system. */ public Set<Label> getLabels() { Set<Label> r = new TreeSet<Label>(); for (Label l : labels.values()) { if(!l.isEmpty()) r.add(l); } return r; } public Set<LabelAtom> getLabelAtoms() { Set<LabelAtom> r = new TreeSet<LabelAtom>(); for (Label l : labels.values()) { if(!l.isEmpty() && l instanceof LabelAtom) r.add((LabelAtom)l); } return r; } public Queue getQueue() { return queue; } @Override public String getDisplayName() { return Messages.Hudson_DisplayName(); } public List<JDK> getJDKs() { if(jdks==null) jdks = new ArrayList<JDK>(); return jdks; } /** * Gets the JDK installation of the given name, or returns null. */ public JDK getJDK(String name) { if(name==null) { // if only one JDK is configured, "default JDK" should mean that JDK. List<JDK> jdks = getJDKs(); if(jdks.size()==1) return jdks.get(0); return null; } for (JDK j : getJDKs()) { if(j.getName().equals(name)) return j; } return null; } /** * Gets the slave node of the give name, hooked under this Hudson. */ public @CheckForNull Node getNode(String name) { return slaves.getNode(name); } /** * Gets a {@link Cloud} by {@link Cloud#name its name}, or null. */ public Cloud getCloud(String name) { return clouds.getByName(name); } protected Map<Node,Computer> getComputerMap() { return computers; } /** * Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which * represents the master. */ public List<Node> getNodes() { return slaves; } /** * Adds one more {@link Node} to Hudson. */ public synchronized void addNode(Node n) throws IOException { if(n==null) throw new IllegalArgumentException(); ArrayList<Node> nl = new ArrayList<Node>(this.slaves); if(!nl.contains(n)) // defensive check nl.add(n); setNodes(nl); } /** * Removes a {@link Node} from Hudson. */ public synchronized void removeNode(@Nonnull Node n) throws IOException { Computer c = n.toComputer(); if (c!=null) c.disconnect(OfflineCause.create(Messages._Hudson_NodeBeingRemoved())); ArrayList<Node> nl = new ArrayList<Node>(this.slaves); nl.remove(n); setNodes(nl); } public void setNodes(List<? extends Node> nodes) throws IOException { this.slaves = new NodeList(nodes); updateComputerList(); trimLabels(); save(); } public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() { return nodeProperties; } public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() { return globalNodeProperties; } /** * Resets all labels and remove invalid ones. * * This should be called when the assumptions behind label cache computation changes, * but we also call this periodically to self-heal any data out-of-sync issue. */ private void trimLabels() { for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) { Label l = itr.next(); resetLabel(l); if(l.isEmpty()) itr.remove(); } } /** * Binds {@link AdministrativeMonitor}s to URL. */ public AdministrativeMonitor getAdministrativeMonitor(String id) { for (AdministrativeMonitor m : administrativeMonitors) if(m.id.equals(id)) return m; return null; } public NodeDescriptor getDescriptor() { return DescriptorImpl.INSTANCE; } public static final class DescriptorImpl extends NodeDescriptor { @Extension public static final DescriptorImpl INSTANCE = new DescriptorImpl(); public String getDisplayName() { return ""; } @Override public boolean isInstantiable() { return false; } public FormValidation doCheckNumExecutors(@QueryParameter String value) { return FormValidation.validateNonNegativeInteger(value); } public FormValidation doCheckRawBuildsDir(@QueryParameter String value) { if (!value.contains("${")) { File d = new File(value); if (!d.isDirectory() && (d.getParentFile() == null || !d.getParentFile().canWrite())) { return FormValidation.error(value + " does not exist and probably cannot be created"); } // XXX failure to use either ITEM_* variable might be an error too? } return FormValidation.ok(); // XXX assumes it will be OK after substitution, but can we be sure? } // to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx public Object getDynamic(String token) { return Jenkins.getInstance().getDescriptor(token); } } /** * Gets the system default quiet period. */ public int getQuietPeriod() { return quietPeriod!=null ? quietPeriod : 5; } /** * Sets the global quiet period. * * @param quietPeriod * null to the default value. */ public void setQuietPeriod(Integer quietPeriod) throws IOException { this.quietPeriod = quietPeriod; save(); } /** * Gets the global SCM check out retry count. */ public int getScmCheckoutRetryCount() { return scmCheckoutRetryCount; } public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException { this.scmCheckoutRetryCount = scmCheckoutRetryCount; save(); } @Override public String getSearchUrl() { return ""; } @Override public SearchIndexBuilder makeSearchIndex() { return super.makeSearchIndex() .add("configure", "config","configure") .add("manage") .add("log") .add(new CollectionSearchIndex<TopLevelItem>() { protected SearchItem get(String key) { return getItem(key); } protected Collection<TopLevelItem> all() { return getItems(); } }) .add(getPrimaryView().makeSearchIndex()) .add(new CollectionSearchIndex() {// for computers protected Computer get(String key) { return getComputer(key); } protected Collection<Computer> all() { return computers.values(); } }) .add(new CollectionSearchIndex() {// for users protected User get(String key) { return User.get(key,false); } protected Collection<User> all() { return User.getAll(); } }) .add(new CollectionSearchIndex() {// for views protected View get(String key) { return getView(key); } protected Collection<View> all() { return views; } }); } public String getUrlChildPrefix() { return "job"; } /** * Gets the absolute URL of Jenkins, * such as "http://localhost/jenkins/". * * <p> * This method first tries to use the manually configured value, then * fall back to {@link StaplerRequest#getRootPath()}. * It is done in this order so that it can work correctly even in the face * of a reverse proxy. * * @return * This method returns null if this parameter is not configured by the user. * The caller must gracefully deal with this situation. * The returned URL will always have the trailing '/'. * @since 1.66 * @see Descriptor#getCheckUrl(String) * @see #getRootUrlFromRequest() * @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a> */ public String getRootUrl() { String url = JenkinsLocationConfiguration.get().getUrl(); if(url!=null) { return Util.ensureEndsWith(url,"/"); } StaplerRequest req = Stapler.getCurrentRequest(); if(req!=null) return getRootUrlFromRequest(); return null; } /** * Is Jenkins running in HTTPS? * * Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated * in the reverse proxy. */ public boolean isRootUrlSecure() { String url = getRootUrl(); return url!=null && url.startsWith("https"); } /** * Gets the absolute URL of Hudson top page, such as "http://localhost/hudson/". * * <p> * Unlike {@link #getRootUrl()}, which uses the manually configured value, * this one uses the current request to reconstruct the URL. The benefit is * that this is immune to the configuration mistake (users often fail to set the root URL * correctly, especially when a migration is involved), but the downside * is that unless you are processing a request, this method doesn't work. * * Please note that this will not work in all cases if Jenkins is running behind a * reverse proxy (e.g. when user has switched off ProxyPreserveHost, which is * default setup or the actual url uses https) and you should use getRootUrl if * you want to be sure you reflect user setup. * See https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache * * @since 1.263 */ public String getRootUrlFromRequest() { StaplerRequest req = Stapler.getCurrentRequest(); StringBuilder buf = new StringBuilder(); buf.append(req.getScheme()+"://"); buf.append(req.getServerName()); if(req.getServerPort()!=80) buf.append(':').append(req.getServerPort()); buf.append(req.getContextPath()).append('/'); return buf.toString(); } public File getRootDir() { return root; } public FilePath getWorkspaceFor(TopLevelItem item) { for (WorkspaceLocator l : WorkspaceLocator.all()) { FilePath workspace = l.locate(item, this); if (workspace != null) { return workspace; } } return new FilePath(expandVariablesForDirectory(workspaceDir, item)); } public File getBuildDirFor(Job job) { return expandVariablesForDirectory(buildsDir, job); } private File expandVariablesForDirectory(String base, Item item) { return new File(Util.replaceMacro(base, ImmutableMap.of( "JENKINS_HOME", getRootDir().getPath(), "ITEM_ROOTDIR", item.getRootDir().getPath(), "ITEM_FULLNAME", item.getFullName(), // legacy, deprecated "ITEM_FULL_NAME", item.getFullName().replace(':','$')))); // safe, see JENKINS-12251 } public String getRawWorkspaceDir() { return workspaceDir; } public String getRawBuildsDir() { return buildsDir; } public FilePath getRootPath() { return new FilePath(getRootDir()); } @Override public FilePath createPath(String absolutePath) { return new FilePath((VirtualChannel)null,absolutePath); } public ClockDifference getClockDifference() { return ClockDifference.ZERO; } /** * For binding {@link LogRecorderManager} to "/log". * Everything below here is admin-only, so do the check here. */ public LogRecorderManager getLog() { checkPermission(ADMINISTER); return log; } /** * A convenience method to check if there's some security * restrictions in place. */ @Exported public boolean isUseSecurity() { return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED; } public boolean isUseProjectNamingStrategy(){ return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; } /** * If true, all the POST requests to Hudson would have to have crumb in it to protect * Hudson from CSRF vulnerabilities. */ @Exported public boolean isUseCrumbs() { return crumbIssuer!=null; } /** * Returns the constant that captures the three basic security modes * in Hudson. */ public SecurityMode getSecurity() { // fix the variable so that this code works under concurrent modification to securityRealm. SecurityRealm realm = securityRealm; if(realm==SecurityRealm.NO_AUTHENTICATION) return SecurityMode.UNSECURED; if(realm instanceof LegacySecurityRealm) return SecurityMode.LEGACY; return SecurityMode.SECURED; } /** * @return * never null. */ public SecurityRealm getSecurityRealm() { return securityRealm; } public void setSecurityRealm(SecurityRealm securityRealm) { if(securityRealm==null) securityRealm= SecurityRealm.NO_AUTHENTICATION; this.useSecurity = true; this.securityRealm = securityRealm; // reset the filters and proxies for the new SecurityRealm try { HudsonFilter filter = HudsonFilter.get(servletContext); if (filter == null) { // Fix for #3069: This filter is not necessarily initialized before the servlets. // when HudsonFilter does come back, it'll initialize itself. LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now"); } else { LOGGER.fine("HudsonFilter has been previously initialized: Setting security up"); filter.reset(securityRealm); LOGGER.fine("Security is now fully set up"); } } catch (ServletException e) { // for binary compatibility, this method cannot throw a checked exception throw new AcegiSecurityException("Failed to configure filter",e) {}; } } public void setAuthorizationStrategy(AuthorizationStrategy a) { if (a == null) a = AuthorizationStrategy.UNSECURED; useSecurity = true; authorizationStrategy = a; } public void disableSecurity() { useSecurity = null; setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); authorizationStrategy = AuthorizationStrategy.UNSECURED; markupFormatter = null; } public void setProjectNamingStrategy(ProjectNamingStrategy ns) { if(ns == null){ ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; } projectNamingStrategy = ns; } public Lifecycle getLifecycle() { return Lifecycle.get(); } /** * Gets the dependency injection container that hosts all the extension implementations and other * components in Jenkins. * * @since 1.GUICE */ public Injector getInjector() { return lookup(Injector.class); } /** * Returns {@link ExtensionList} that retains the discovered instances for the given extension type. * * @param extensionType * The base type that represents the extension point. Normally {@link ExtensionPoint} subtype * but that's not a hard requirement. * @return * Can be an empty list but never null. */ @SuppressWarnings({"unchecked"}) public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) { return extensionLists.get(extensionType); } /** * Used to bind {@link ExtensionList}s to URLs. * * @since 1.349 */ public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException { return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType)); } /** * Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given * kind of {@link Describable}. * * @return * Can be an empty list but never null. */ @SuppressWarnings({"unchecked"}) public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) { return descriptorLists.get(type); } /** * Refresh {@link ExtensionList}s by adding all the newly discovered extensions. * * Exposed only for {@link PluginManager#dynamicLoad(File)}. */ public void refreshExtensions() throws ExtensionRefreshException { ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class); for (ExtensionFinder ef : finders) { if (!ef.isRefreshable()) throw new ExtensionRefreshException(ef+" doesn't support refresh"); } List<ExtensionComponentSet> fragments = Lists.newArrayList(); for (ExtensionFinder ef : finders) { fragments.add(ef.refresh()); } ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered(); // if we find a new ExtensionFinder, we need it to list up all the extension points as well List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class)); while (!newFinders.isEmpty()) { ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance(); ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered(); newFinders.addAll(ecs.find(ExtensionFinder.class)); delta = ExtensionComponentSet.union(delta, ecs); } for (ExtensionList el : extensionLists.values()) { el.refresh(delta); } for (ExtensionList el : descriptorLists.values()) { el.refresh(delta); } // TODO: we need some generalization here so that extension points can be notified when a refresh happens? for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) { Action a = ea.getInstance(); if (!actions.contains(a)) actions.add(a); } } /** * Returns the root {@link ACL}. * * @see AuthorizationStrategy#getRootACL() */ @Override public ACL getACL() { return authorizationStrategy.getRootACL(); } /** * @return * never null. */ public AuthorizationStrategy getAuthorizationStrategy() { return authorizationStrategy; } /** * The strategy used to check the project names. * @return never <code>null</code> */ public ProjectNamingStrategy getProjectNamingStrategy() { return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy; } /** * Returns true if Hudson is quieting down. * <p> * No further jobs will be executed unless it * can be finished while other current pending builds * are still in progress. */ @Exported public boolean isQuietingDown() { return isQuietingDown; } /** * Returns true if the container initiated the termination of the web application. */ public boolean isTerminating() { return terminating; } /** * Gets the initialization milestone that we've already reached. * * @return * {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method * never returns null. */ public InitMilestone getInitLevel() { return initLevel; } public void setNumExecutors(int n) throws IOException { this.numExecutors = n; save(); } /** * {@inheritDoc}. * * Note that the look up is case-insensitive. */ public TopLevelItem getItem(String name) { if (name==null) return null; TopLevelItem item = items.get(name); if (item==null) return null; if (!item.hasPermission(Item.READ)) { if (item.hasPermission(Item.DISCOVER)) { throw new AccessDeniedException("Please login to access job " + name); } return null; } return item; } /** * Gets the item by its path name from the given context * * <h2>Path Names</h2> * <p> * If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute. * Otherwise, the name should be something like "foo/bar" and it's interpreted like * relative path name in the file system is, against the given context. * * @param context * null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation. * @since 1.406 */ public Item getItem(String pathName, ItemGroup context) { if (context==null) context = this; if (pathName==null) return null; if (pathName.startsWith("/")) // absolute return getItemByFullName(pathName); Object/*Item|ItemGroup*/ ctx = context; StringTokenizer tokens = new StringTokenizer(pathName,"/"); while (tokens.hasMoreTokens()) { String s = tokens.nextToken(); if (s.equals("..")) { if (ctx instanceof Item) { ctx = ((Item)ctx).getParent(); continue; } ctx=null; // can't go up further break; } if (s.equals(".")) { continue; } if (ctx instanceof ItemGroup) { ItemGroup g = (ItemGroup) ctx; Item i = g.getItem(s); if (i==null || !i.hasPermission(Item.READ)) { // XXX consider DISCOVER ctx=null; // can't go up further break; } ctx=i; } else { return null; } } if (ctx instanceof Item) return (Item)ctx; // fall back to the classic interpretation return getItemByFullName(pathName); } public final Item getItem(String pathName, Item context) { return getItem(pathName,context!=null?context.getParent():null); } public final <T extends Item> T getItem(String pathName, ItemGroup context, Class<T> type) { Item r = getItem(pathName, context); if (type.isInstance(r)) return type.cast(r); return null; } public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) { return getItem(pathName,context!=null?context.getParent():null,type); } public File getRootDirFor(TopLevelItem child) { return getRootDirFor(child.getName()); } private File getRootDirFor(String name) { return new File(new File(getRootDir(),"jobs"), name); } /** * Gets the {@link Item} object by its full name. * Full names are like path names, where each name of {@link Item} is * combined by '/'. * * @return * null if either such {@link Item} doesn't exist under the given full name, * or it exists but it's no an instance of the given type. */ public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) { StringTokenizer tokens = new StringTokenizer(fullName,"/"); ItemGroup parent = this; if(!tokens.hasMoreTokens()) return null; // for example, empty full name. while(true) { Item item = parent.getItem(tokens.nextToken()); if(!tokens.hasMoreTokens()) { if(type.isInstance(item)) return type.cast(item); else return null; } if(!(item instanceof ItemGroup)) return null; // this item can't have any children if (!item.hasPermission(Item.READ)) return null; // XXX consider DISCOVER parent = (ItemGroup) item; } } public @CheckForNull Item getItemByFullName(String fullName) { return getItemByFullName(fullName,Item.class); } /** * Gets the user of the given name. * * @return the user of the given name, if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null * @see User#get(String,boolean) */ public @CheckForNull User getUser(String name) { return User.get(name,hasPermission(ADMINISTER)); } public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException { return createProject(type, name, true); } public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException { return itemGroupMixIn.createProject(type,name,notify); } /** * Overwrites the existing item by new one. * * <p> * This is a short cut for deleting an existing job and adding a new one. */ public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException { String name = item.getName(); TopLevelItem old = items.get(name); if (old ==item) return; // noop checkPermission(Item.CREATE); if (old!=null) old.delete(); items.put(name,item); ItemListener.fireOnCreated(item); } /** * Creates a new job. * * <p> * This version infers the descriptor from the type of the top-level item. * * @throws IllegalArgumentException * if the project of the given name already exists. */ public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException { return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name)); } /** * Called by {@link Job#renameTo(String)} to update relevant data structure. * assumed to be synchronized on Hudson by the caller. */ public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException { items.remove(oldName); items.put(newName,job); for (View v : views) v.onJobRenamed(job, oldName, newName); save(); } /** * Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)} */ public void onDeleted(TopLevelItem item) throws IOException { for (ItemListener l : ItemListener.all()) l.onDeleted(item); items.remove(item.getName()); for (View v : views) v.onJobRenamed(item, item.getName(), null); save(); } public FingerprintMap getFingerprintMap() { return fingerprintMap; } // if no finger print matches, display "not found page". public Object getFingerprint( String md5sum ) throws IOException { Fingerprint r = fingerprintMap.get(md5sum); if(r==null) return new NoFingerprintMatch(md5sum); else return r; } /** * Gets a {@link Fingerprint} object if it exists. * Otherwise null. */ public Fingerprint _getFingerprint( String md5sum ) throws IOException { return fingerprintMap.get(md5sum); } /** * The file we save our configuration. */ private XmlFile getConfigFile() { return new XmlFile(XSTREAM, new File(root,"config.xml")); } public int getNumExecutors() { return numExecutors; } public Mode getMode() { return mode; } public void setMode(Mode m) throws IOException { this.mode = m; save(); } public String getLabelString() { return fixNull(label).trim(); } @Override public void setLabelString(String label) throws IOException { this.label = label; save(); } @Override public LabelAtom getSelfLabel() { return getLabelAtom("master"); } public Computer createComputer() { return new Hudson.MasterComputer(); } private synchronized TaskBuilder loadTasks() throws IOException { File projectsDir = new File(root,"jobs"); if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) { if(projectsDir.exists()) throw new IOException(projectsDir+" is not a directory"); throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually."); } File[] subdirs = projectsDir.listFiles(new FileFilter() { public boolean accept(File child) { return child.isDirectory() && Items.getConfigFile(child).exists(); } }); final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>()); TaskGraphBuilder g = new TaskGraphBuilder(); Handle loadHudson = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() { public void run(Reactor session) throws Exception { // JENKINS-8043: some slaves (eg. swarm slaves) are not saved into the config file // and will get overwritten when reloading. Make a backup copy now, and re-add them later NodeList oldSlaves = slaves; XmlFile cfg = getConfigFile(); if (cfg.exists()) { // reset some data that may not exist in the disk file // so that we can take a proper compensation action later. primaryView = null; views.clear(); // load from disk cfg.unmarshal(Jenkins.this); } // if we are loading old data that doesn't have this field if (slaves == null) slaves = new NodeList(); clouds.setOwner(Jenkins.this); // JENKINS-8043: re-add the slaves which were not saved into the config file // and are now missing, but still connected. if (oldSlaves != null) { ArrayList<Node> newSlaves = new ArrayList<Node>(slaves); for (Node n: oldSlaves) { if (n instanceof EphemeralNode) { if(!newSlaves.contains(n)) { newSlaves.add(n); } } } setNodes(newSlaves); } } }); for (final File subdir : subdirs) { g.requires(loadHudson).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() { public void run(Reactor session) throws Exception { TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir); items.put(item.getName(), item); loadedNames.add(item.getName()); } }); } g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() { public void run(Reactor reactor) throws Exception { // anything we didn't load from disk, throw them away. // doing this after loading from disk allows newly loaded items // to inspect what already existed in memory (in case of reloading) // retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one // hopefully there shouldn't be too many of them. for (String name : items.keySet()) { if (!loadedNames.contains(name)) items.remove(name); } } }); g.requires(JOB_LOADED).add("Finalizing set up",new Executable() { public void run(Reactor session) throws Exception { rebuildDependencyGraph(); {// recompute label objects - populates the labels mapping. for (Node slave : slaves) // Note that not all labels are visible until the slaves have connected. slave.getAssignedLabels(); getAssignedLabels(); } // initialize views by inserting the default view if necessary // this is both for clean Hudson and for backward compatibility. if(views.size()==0 || primaryView==null) { View v = new AllView(Messages.Hudson_ViewName()); setViewOwner(v); views.add(0,v); primaryView = v.getViewName(); } // read in old data that doesn't have the security field set if(authorizationStrategy==null) { if(useSecurity==null || !useSecurity) authorizationStrategy = AuthorizationStrategy.UNSECURED; else authorizationStrategy = new LegacyAuthorizationStrategy(); } if(securityRealm==null) { if(useSecurity==null || !useSecurity) setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); else setSecurityRealm(new LegacySecurityRealm()); } else { // force the set to proxy setSecurityRealm(securityRealm); } if(useSecurity!=null && !useSecurity) { // forced reset to the unsecure mode. // this works as an escape hatch for people who locked themselves out. authorizationStrategy = AuthorizationStrategy.UNSECURED; setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); } // Initialize the filter with the crumb issuer setCrumbIssuer(crumbIssuer); // auto register root actions for (Action a : getExtensionList(RootAction.class)) if (!actions.contains(a)) actions.add(a); } }); return g; } /** * Save the settings to a file. */ public synchronized void save() throws IOException { if(BulkChange.contains(this)) return; getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } /** * Called to shut down the system. */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") public void cleanUp() { for (ItemListener l : ItemListener.all()) l.onBeforeShutdown(); Set<Future<?>> pending = new HashSet<Future<?>>(); terminating = true; for( Computer c : computers.values() ) { c.interrupt(); killComputer(c); pending.add(c.disconnect(null)); } if(udpBroadcastThread!=null) udpBroadcastThread.shutdown(); if(dnsMultiCast!=null) dnsMultiCast.close(); interruptReloadThread(); Timer timer = Trigger.timer; if (timer != null) { timer.cancel(); } // TODO: how to wait for the completion of the last job? Trigger.timer = null; if(tcpSlaveAgentListener!=null) tcpSlaveAgentListener.shutdown(); if(pluginManager!=null) // be defensive. there could be some ugly timing related issues pluginManager.stop(); if(getRootDir().exists()) // if we are aborting because we failed to create JENKINS_HOME, // don't try to save. Issue #536 getQueue().save(); threadPoolForLoad.shutdown(); for (Future<?> f : pending) try { f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; // someone wants us to die now. quick! } catch (ExecutionException e) { LOGGER.log(Level.WARNING, "Failed to shut down properly",e); } catch (TimeoutException e) { LOGGER.log(Level.WARNING, "Failed to shut down properly",e); } LogFactory.releaseAll(); theInstance = null; } public Object getDynamic(String token) { for (Action a : getActions()) { String url = a.getUrlName(); if (url==null) continue; if (url.equals(token) || url.equals('/' + token)) return a; } for (Action a : getManagementLinks()) if(a.getUrlName().equals(token)) return a; return null; } // // // actions // // /** * Accepts submission from the configuration page. */ public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { BulkChange bc = new BulkChange(this); try { checkPermission(ADMINISTER); JSONObject json = req.getSubmittedForm(); workspaceDir = json.getString("rawWorkspaceDir"); buildsDir = json.getString("rawBuildsDir"); systemMessage = Util.nullify(req.getParameter("system_message")); jdks.clear(); jdks.addAll(req.bindJSONToList(JDK.class,json.get("jdks"))); boolean result = true; for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified()) result &= configureDescriptor(req,json,d); version = VERSION; save(); updateComputerList(); if(result) FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null); else FormApply.success("configure").generateResponse(req, rsp, null); // back to config } finally { bc.commit(); } } /** * Gets the {@link CrumbIssuer} currently in use. * * @return null if none is in use. */ public CrumbIssuer getCrumbIssuer() { return crumbIssuer; } public void setCrumbIssuer(CrumbIssuer issuer) { crumbIssuer = issuer; } public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { rsp.sendRedirect("foo"); } private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException { // collapse the structure to remain backward compatible with the JSON structure before 1. String name = d.getJsonSafeClassName(); JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object. json.putAll(js); return d.configure(req, js); } /** * Accepts submission from the node configuration page. */ public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(ADMINISTER); BulkChange bc = new BulkChange(this); try { JSONObject json = req.getSubmittedForm(); MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class); if (mbc!=null) mbc.configure(req,json); getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all()); } finally { bc.commit(); } rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page } /** * Accepts the new description. */ public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { getPrimaryView().doSubmitDescription(req, rsp); } public synchronized HttpRedirect doQuietDown() throws IOException { try { return doQuietDown(false,0); } catch (InterruptedException e) { throw new AssertionError(); // impossible } } @CLIMethod(name="quiet-down") public HttpRedirect doQuietDown( @Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block, @Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException { synchronized (this) { checkPermission(ADMINISTER); isQuietingDown = true; } if (block) { if (timeout > 0) timeout += System.currentTimeMillis(); while (isQuietingDown && (timeout <= 0 || System.currentTimeMillis() < timeout) && !RestartListener.isAllReady()) { Thread.sleep(1000); } } return new HttpRedirect("."); } @CLIMethod(name="cancel-quiet-down") public synchronized HttpRedirect doCancelQuietDown() { checkPermission(ADMINISTER); isQuietingDown = false; getQueue().scheduleMaintenance(); return new HttpRedirect("."); } /** * Backward compatibility. Redirect to the thread dump. */ public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException { rsp.sendRedirect2("threadDump"); } /** * Obtains the thread dump of all slaves (including the master.) * * <p> * Since this is for diagnostics, it has a built-in precautionary measure against hang slaves. */ public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException { checkPermission(ADMINISTER); // issue the requests all at once Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>(); for (Computer c : getComputers()) { try { future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel())); } catch(Exception e) { LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage()); } } if (toComputer() == null) { future.put("master", RemotingDiagnostics.getThreadDumpAsync(MasterComputer.localChannel)); } // if the result isn't available in 5 sec, ignore that. // this is a precaution against hang nodes long endTime = System.currentTimeMillis() + 5000; Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>(); for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) { try { r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS)); } catch (Exception x) { StringWriter sw = new StringWriter(); x.printStackTrace(new PrintWriter(sw,true)); r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString())); } } return r; } public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { return itemGroupMixIn.createTopLevelItem(req, rsp); } /** * @since 1.319 */ public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException { return itemGroupMixIn.createProjectFromXML(name, xml); } @SuppressWarnings({"unchecked"}) public <T extends TopLevelItem> T copy(T src, String name) throws IOException { return itemGroupMixIn.copy(src, name); } // a little more convenient overloading that assumes the caller gives us the right type // (or else it will fail with ClassCastException) public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException { return (T)copy((TopLevelItem)src,name); } public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(View.CREATE); addView(View.create(req,rsp, this)); } /** * Check if the given name is suitable as a name * for job, view, etc. * * @throws Failure * if the given name is not good */ public static void checkGoodName(String name) throws Failure { if(name==null || name.length()==0) throw new Failure(Messages.Hudson_NoName()); if("..".equals(name.trim())) throw new Failure(Messages.Jenkins_NotAllowedName("..")); for( int i=0; i<name.length(); i++ ) { char ch = name.charAt(i); if(Character.isISOControl(ch)) { throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name))); } if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1) throw new Failure(Messages.Hudson_UnsafeChar(ch)); } // looks good } /** * Makes sure that the given name is good as a job name. * @return trimmed name if valid; throws Failure if not */ private String checkJobName(String name) throws Failure { checkGoodName(name); name = name.trim(); projectNamingStrategy.checkName(name); if(getItem(name)!=null) throw new Failure(Messages.Hudson_JobAlreadyExists(name)); // looks good return name; } private static String toPrintableName(String name) { StringBuilder printableName = new StringBuilder(); for( int i=0; i<name.length(); i++ ) { char ch = name.charAt(i); if(Character.isISOControl(ch)) printableName.append("\\u").append((int)ch).append(';'); else printableName.append(ch); } return printableName.toString(); } /** * Checks if the user was successfully authenticated. * * @see BasicAuthenticationFilter */ public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { if(req.getUserPrincipal()==null) { // authentication must have failed rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } // the user is now authenticated, so send him back to the target String path = req.getContextPath()+req.getOriginalRestOfPath(); String q = req.getQueryString(); if(q!=null) path += '?'+q; rsp.sendRedirect2(path); } /** * Called once the user logs in. Just forward to the top page. */ public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException { if(req.getUserPrincipal()==null) { rsp.sendRedirect2("noPrincipal"); return; } String from = req.getParameter("from"); if(from!=null && from.startsWith("/") && !from.equals("/loginError")) { rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain return; } String url = AbstractProcessingFilter.obtainFullRequestUrl(req); if(url!=null) { // if the login redirect is initiated by Acegi // this should send the user back to where s/he was from. rsp.sendRedirect2(url); return; } rsp.sendRedirect2("."); } /** * Logs out the user. */ public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { securityRealm.doLogout(req, rsp); } /** * Serves jar files for JNLP slave agents. */ public Slave.JnlpJar getJnlpJars(String fileName) { return new Slave.JnlpJar(fileName); } public Slave.JnlpJar doJnlpJars(StaplerRequest req) { return new Slave.JnlpJar(req.getRestOfPath().substring(1)); } /** * Reloads the configuration. */ @CLIMethod(name="reload-configuration") public synchronized HttpResponse doReload() throws IOException { checkPermission(ADMINISTER); // engage "loading ..." UI and then run the actual task in a separate thread servletContext.setAttribute("app", new HudsonIsLoading()); new Thread("Jenkins config reload thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); reload(); } catch (Exception e) { LOGGER.log(SEVERE,"Failed to reload Jenkins config",e); WebApp.get(servletContext).setApp(new JenkinsReloadFailed(e)); } } }.start(); return HttpResponses.redirectViaContextPath("/"); } /** * Reloads the configuration synchronously. */ public void reload() throws IOException, InterruptedException, ReactorException { executeReactor(null, loadTasks()); User.reload(); servletContext.setAttribute("app", this); } /** * Do a finger-print check. */ public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { // Parse the request MultipartFormDataParser p = new MultipartFormDataParser(req); if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) { rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found"); } try { rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+ Util.getDigestOf(p.getFileItem("name").getInputStream())+'/'); } finally { p.cleanUp(); } } /** * For debugging. Expose URL to perform GC. */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC") public void doGc(StaplerResponse rsp) throws IOException { checkPermission(Jenkins.ADMINISTER); System.gc(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("GCed"); } /** * End point that intentionally throws an exception to test the error behaviour. */ public void doException() { throw new RuntimeException(); } public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException { ContextMenu menu = new ContextMenu().from(this, request, response); for (MenuItem i : menu.items) { if (i.url.equals(request.getContextPath() + "/manage")) { // add "Manage Jenkins" subitems i.subMenu = new ContextMenu().from(this, request, response, "manage"); } } return menu; } /** * Obtains the heap dump. */ public HeapDump getHeapDump() throws IOException { return new HeapDump(this,MasterComputer.localChannel); } /** * Simulates OutOfMemoryError. * Useful to make sure OutOfMemoryHeapDump setting. */ public void doSimulateOutOfMemory() throws IOException { checkPermission(ADMINISTER); System.out.println("Creating artificial OutOfMemoryError situation"); List<Object> args = new ArrayList<Object>(); while (true) args.add(new byte[1024*1024]); } private transient final Map<UUID,FullDuplexHttpChannel> duplexChannels = new HashMap<UUID, FullDuplexHttpChannel>(); /** * Handles HTTP requests for duplex channels for CLI. */ public void doCli(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { if (!"POST".equals(req.getMethod())) { // for GET request, serve _cli.jelly, assuming this is a browser checkPermission(READ); req.getView(this,"_cli.jelly").forward(req,rsp); return; } // do not require any permission to establish a CLI connection // the actual authentication for the connecting Channel is done by CLICommand UUID uuid = UUID.fromString(req.getHeader("Session")); rsp.setHeader("Hudson-Duplex",""); // set the header so that the client would know FullDuplexHttpChannel server; if(req.getHeader("Side").equals("download")) { duplexChannels.put(uuid,server=new FullDuplexHttpChannel(uuid, !hasPermission(ADMINISTER)) { protected void main(Channel channel) throws IOException, InterruptedException { // capture the identity given by the transport, since this can be useful for SecurityRealm.createCliAuthenticator() channel.setProperty(CLICommand.TRANSPORT_AUTHENTICATION,getAuthentication()); channel.setProperty(CliEntryPoint.class.getName(),new CliManagerImpl(channel)); } }); try { server.download(req,rsp); } finally { duplexChannels.remove(uuid); } } else { duplexChannels.get(uuid).upload(req,rsp); } } /** * Binds /userContent/... to $JENKINS_HOME/userContent. */ public DirectoryBrowserSupport doUserContent() { return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true); } /** * Perform a restart of Hudson, if we can. * * This first replaces "app" to {@link HudsonIsRestarting} */ @CLIMethod(name="restart") public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException { checkPermission(ADMINISTER); if (req != null && req.getMethod().equals("GET")) { req.getView(this,"_restart.jelly").forward(req,rsp); return; } restart(); if (rsp != null) // null for CLI rsp.sendRedirect2("."); } /** * Queues up a restart of Hudson for when there are no builds running, if we can. * * This first replaces "app" to {@link HudsonIsRestarting} * * @since 1.332 */ @CLIMethod(name="safe-restart") public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException { checkPermission(ADMINISTER); if (req != null && req.getMethod().equals("GET")) return HttpResponses.forwardToView(this,"_safeRestart.jelly"); safeRestart(); return HttpResponses.redirectToDot(); } /** * Performs a restart. */ public void restart() throws RestartNotSupportedException { final Lifecycle lifecycle = Lifecycle.get(); lifecycle.verifyRestartable(); // verify that Hudson is restartable servletContext.setAttribute("app", new HudsonIsRestarting()); new Thread("restart thread") { final String exitUser = getAuthentication().getName(); @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); // give some time for the browser to load the "reloading" page Thread.sleep(5000); LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser)); for (RestartListener listener : RestartListener.all()) listener.onRestart(); lifecycle.restart(); } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Failed to restart Hudson",e); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to restart Hudson",e); } } }.start(); } /** * Queues up a restart to be performed once there are no builds currently running. * @since 1.332 */ public void safeRestart() throws RestartNotSupportedException { final Lifecycle lifecycle = Lifecycle.get(); lifecycle.verifyRestartable(); // verify that Hudson is restartable // Quiet down so that we won't launch new builds. isQuietingDown = true; new Thread("safe-restart thread") { final String exitUser = getAuthentication().getName(); @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); // Wait 'til we have no active executors. doQuietDown(true, 0); // Make sure isQuietingDown is still true. if (isQuietingDown) { servletContext.setAttribute("app",new HudsonIsRestarting()); // give some time for the browser to load the "reloading" page LOGGER.info("Restart in 10 seconds"); Thread.sleep(10000); LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser)); for (RestartListener listener : RestartListener.all()) listener.onRestart(); lifecycle.restart(); } else { LOGGER.info("Safe-restart mode cancelled"); } } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Failed to restart Hudson",e); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to restart Hudson",e); } } }.start(); } /** * Shutdown the system. * @since 1.161 */ @CLIMethod(name="shutdown") public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException { checkPermission(ADMINISTER); LOGGER.severe(String.format("Shutting down VM as requested by %s from %s", getAuthentication().getName(), req!=null?req.getRemoteAddr():"???")); if (rsp!=null) { rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); PrintWriter w = rsp.getWriter(); w.println("Shutting down"); w.close(); } System.exit(0); } /** * Shutdown the system safely. * @since 1.332 */ @CLIMethod(name="safe-shutdown") public HttpResponse doSafeExit(StaplerRequest req) throws IOException { checkPermission(ADMINISTER); isQuietingDown = true; final String exitUser = getAuthentication().getName(); final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown"; new Thread("safe-exit thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); LOGGER.severe(String.format("Shutting down VM as requested by %s from %s", exitUser, exitAddr)); // Wait 'til we have no active executors. while (isQuietingDown && (overallLoad.computeTotalExecutors() > overallLoad.computeIdleExecutors())) { Thread.sleep(5000); } // Make sure isQuietingDown is still true. if (isQuietingDown) { cleanUp(); System.exit(0); } } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Failed to shutdown Hudson",e); } } }.start(); return HttpResponses.plainText("Shutting down as soon as all jobs are complete"); } /** * Gets the {@link Authentication} object that represents the user * associated with the current request. */ public static Authentication getAuthentication() { Authentication a = SecurityContextHolder.getContext().getAuthentication(); // on Tomcat while serving the login page, this is null despite the fact // that we have filters. Looking at the stack trace, Tomcat doesn't seem to // run the request through filters when this is the login request. // see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html if(a==null) a = ANONYMOUS; return a; } /** * For system diagnostics. * Run arbitrary Groovy script. */ public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { doScript(req, rsp, req.getView(this, "_script.jelly")); } /** * Run arbitrary Groovy script and return result as plain text. */ public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { doScript(req, rsp, req.getView(this, "_scriptText.jelly")); } private void doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view) throws IOException, ServletException { // ability to run arbitrary script is dangerous checkPermission(RUN_SCRIPTS); String text = req.getParameter("script"); if (text != null) { try { req.setAttribute("output", RemotingDiagnostics.executeGroovy(text, MasterComputer.localChannel)); } catch (InterruptedException e) { throw new ServletException(e); } } view.forward(req, rsp); } /** * Evaluates the Jelly script submitted by the client. * * This is useful for system administration as well as unit testing. */ @RequirePOST public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(ADMINISTER); try { MetaClass mc = WebApp.getCurrent().getMetaClass(getClass()); Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader())); new JellyRequestDispatcher(this,script).forward(req,rsp); } catch (JellyException e) { throw new ServletException(e); } } /** * Sign up for the user account. */ public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp); } /** * Changes the icon size by changing the cookie */ public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { String qs = req.getQueryString(); if(qs==null || !ICON_SIZE.matcher(qs).matches()) throw new ServletException(); Cookie cookie = new Cookie("iconSize", qs); cookie.setMaxAge(/* ~4 mo. */9999999); // #762 rsp.addCookie(cookie); String ref = req.getHeader("Referer"); if(ref==null) ref="."; rsp.sendRedirect2(ref); } public void doFingerprintCleanup(StaplerResponse rsp) throws IOException { FingerprintCleanupThread.invoke(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("Invoked"); } public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException { WorkspaceCleanupThread.invoke(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("Invoked"); } /** * If the user chose the default JDK, make sure we got 'java' in PATH. */ public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) { if(!value.equals("(Default)")) // assume the user configured named ones properly in system config --- // or else system config should have reported form field validation errors. return FormValidation.ok(); // default JDK selected. Does such java really exist? if(JDK.isDefaultJDKValid(Jenkins.this)) return FormValidation.ok(); else return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath())); } /** * Makes sure that the given name is good as a job name. */ public FormValidation doCheckJobName(@QueryParameter String value) { // this method can be used to check if a file exists anywhere in the file system, // so it should be protected. checkPermission(Item.CREATE); if(fixEmpty(value)==null) return FormValidation.ok(); try { checkJobName(value); return FormValidation.ok(); } catch (Failure e) { return FormValidation.error(e.getMessage()); } } /** * Checks if a top-level view with the given name exists. */ public FormValidation doViewExistsCheck(@QueryParameter String value) { checkPermission(View.CREATE); String view = fixEmpty(value); if(view==null) return FormValidation.ok(); if(getView(view)==null) return FormValidation.ok(); else return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view)); } /** * Serves static resources placed along with Jelly view files. * <p> * This method can serve a lot of files, so care needs to be taken * to make this method secure. It's not clear to me what's the best * strategy here, though the current implementation is based on * file extensions. */ public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String path = req.getRestOfPath(); // cut off the "..." portion of /resources/.../path/to/file // as this is only used to make path unique (which in turn // allows us to set a long expiration date path = path.substring(path.indexOf('/',1)+1); int idx = path.lastIndexOf('.'); String extension = path.substring(idx+1); if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) { URL url = pluginManager.uberClassLoader.getResource(path); if(url!=null) { long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/ rsp.serveFile(req,url,expires); return; } } rsp.sendError(HttpServletResponse.SC_NOT_FOUND); } /** * Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve. * This set is mutable to allow plugins to add additional extensions. */ public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList( "js|css|jpeg|jpg|png|gif|html|htm".split("\\|") )); /** * Checks if container uses UTF-8 to decode URLs. See * http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n */ public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException { // expected is non-ASCII String final String expected = "\u57f7\u4e8b"; final String value = fixEmpty(request.getParameter("value")); if (!expected.equals(value)) return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL()); return FormValidation.ok(); } /** * Does not check when system default encoding is "ISO-8859-1". */ public static boolean isCheckURIEncodingEnabled() { return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding")); } /** * Rebuilds the dependency map. */ public void rebuildDependencyGraph() { DependencyGraph graph = new DependencyGraph(); graph.build(); // volatile acts a as a memory barrier here and therefore guarantees // that graph is fully build, before it's visible to other threads dependencyGraph = graph; } public DependencyGraph getDependencyGraph() { return dependencyGraph; } // for Jelly public List<ManagementLink> getManagementLinks() { return ManagementLink.all(); } /** * Exposes the current user to <tt>/me</tt> URL. */ public User getMe() { User u = User.current(); if (u == null) throw new AccessDeniedException("/me is not available when not logged in"); return u; } /** * Gets the {@link Widget}s registered on this object. * * <p> * Plugins who wish to contribute boxes on the side panel can add widgets * by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}. */ public List<Widget> getWidgets() { return widgets; } public Object getTarget() { try { checkPermission(READ); } catch (AccessDeniedException e) { String rest = Stapler.getCurrentRequest().getRestOfPath(); if(rest.startsWith("/login") || rest.startsWith("/logout") || rest.startsWith("/accessDenied") || rest.startsWith("/adjuncts/") || rest.startsWith("/signup") || rest.startsWith("/tcpSlaveAgentListener") // XXX SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access || rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt")) || rest.startsWith("/cli") || rest.startsWith("/federatedLoginService/") || rest.startsWith("/securityRealm")) return this; // URLs that are always visible without READ permission for (String name : getUnprotectedRootActions()) { if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) { return this; } } throw e; } return this; } /** * Gets a list of unprotected root actions. * These URL prefixes should be exempted from access control checks by container-managed security. * Ideally would be synchronized with {@link #getTarget}. * @return a list of {@linkplain Action#getUrlName URL names} * @since 1.495 */ public Collection<String> getUnprotectedRootActions() { Set<String> names = new TreeSet<String>(); names.add("jnlpJars"); // XXX cleaner to refactor doJnlpJars into a URA // XXX consider caching (expiring cache when actions changes) for (Action a : getActions()) { if (a instanceof UnprotectedRootAction) { names.add(a.getUrlName()); } } return names; } /** * Fallback to the primary view. */ public View getStaplerFallback() { return getPrimaryView(); } /** * This method checks all existing jobs to see if displayName is * unique. It does not check the displayName against the displayName of the * job that the user is configuring though to prevent a validation warning * if the user sets the displayName to what it currently is. * @param displayName * @param currentJobName * @return */ boolean isDisplayNameUnique(String displayName, String currentJobName) { Collection<TopLevelItem> itemCollection = items.values(); // if there are a lot of projects, we'll have to store their // display names in a HashSet or something for a quick check for(TopLevelItem item : itemCollection) { if(item.getName().equals(currentJobName)) { // we won't compare the candidate displayName against the current // item. This is to prevent an validation warning if the user // sets the displayName to what the existing display name is continue; } else if(displayName.equals(item.getDisplayName())) { return false; } } return true; } /** * True if there is no item in Jenkins that has this name * @param name The name to test * @param currentJobName The name of the job that the user is configuring * @return */ boolean isNameUnique(String name, String currentJobName) { Item item = getItem(name); if(null==item) { // the candidate name didn't return any items so the name is unique return true; } else if(item.getName().equals(currentJobName)) { // the candidate name returned an item, but the item is the item // that the user is configuring so this is ok return true; } else { // the candidate name returned an item, so it is not unique return false; } } /** * Checks to see if the candidate displayName collides with any * existing display names or project names * @param displayName The display name to test * @param jobName The name of the job the user is configuring * @return */ public FormValidation doCheckDisplayName(@QueryParameter String displayName, @QueryParameter String jobName) { displayName = displayName.trim(); if(LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Current job name is " + jobName); } if(!isNameUnique(displayName, jobName)) { return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName)); } else if(!isDisplayNameUnique(displayName, jobName)){ return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName)); } else { return FormValidation.ok(); } } public static class MasterComputer extends Computer { protected MasterComputer() { super(Jenkins.getInstance()); } /** * Returns "" to match with {@link Jenkins#getNodeName()}. */ @Override public String getName() { return ""; } @Override public boolean isConnecting() { return false; } @Override public String getDisplayName() { return Messages.Hudson_Computer_DisplayName(); } @Override public String getCaption() { return Messages.Hudson_Computer_Caption(); } @Override public String getUrl() { return "computer/(master)/"; } public RetentionStrategy getRetentionStrategy() { return RetentionStrategy.NOOP; } /** * Report an error. */ @Override public HttpResponse doDoDelete() throws IOException { throw HttpResponses.status(SC_BAD_REQUEST); } @Override public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp); } @Override public boolean hasPermission(Permission permission) { // no one should be allowed to delete the master. // this hides the "delete" link from the /computer/(master) page. if(permission==Computer.DELETE) return false; // Configuration of master node requires ADMINISTER permission return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission); } @Override public VirtualChannel getChannel() { return localChannel; } @Override public Charset getDefaultCharset() { return Charset.defaultCharset(); } public List<LogRecord> getLogRecords() throws IOException, InterruptedException { return logRecords; } public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { // this computer never returns null from channel, so // this method shall never be invoked. rsp.sendError(SC_NOT_FOUND); } protected Future<?> _connect(boolean forceReconnect) { return Futures.precomputed(null); } /** * {@link LocalChannel} instance that can be used to execute programs locally. */ public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting); } /** * Shortcut for {@code Hudson.getInstance().lookup.get(type)} */ public static <T> T lookup(Class<T> type) { return Jenkins.getInstance().lookup.get(type); } /** * Live view of recent {@link LogRecord}s produced by Hudson. */ public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE /** * Thread-safe reusable {@link XStream}. */ public static final XStream XSTREAM = new XStream2(); /** * Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily. */ public static final XStream2 XSTREAM2 = (XStream2)XSTREAM; private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2); /** * Thread pool used to load configuration in parallel, to improve the start up time. * <p> * The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers. */ /*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor( TWICE_CPU_NUM, TWICE_CPU_NUM, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new DaemonThreadFactory()); private static void computeVersion(ServletContext context) { // set the version Properties props = new Properties(); try { InputStream is = Jenkins.class.getResourceAsStream("jenkins-version.properties"); if(is!=null) props.load(is); } catch (IOException e) { e.printStackTrace(); // if the version properties is missing, that's OK. } String ver = props.getProperty("version"); if(ver==null) ver="?"; VERSION = ver; context.setAttribute("version",ver); VERSION_HASH = Util.getDigestOf(ver).substring(0, 8); SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8); if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache")) RESOURCE_PATH = ""; else RESOURCE_PATH = "/static/"+SESSION_HASH; VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH; } /** * Version number of this Hudson. */ public static String VERSION="?"; /** * Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number * (such as when Hudson is run with "mvn hudson-dev:run") */ public static VersionNumber getVersion() { try { return new VersionNumber(VERSION); } catch (NumberFormatException e) { try { // for non-released version of Hudson, this looks like "1.345 (private-foobar), so try to approximate. int idx = VERSION.indexOf(' '); if (idx>0) return new VersionNumber(VERSION.substring(0,idx)); } catch (NumberFormatException _) { // fall through } // totally unparseable return null; } catch (IllegalArgumentException e) { // totally unparseable return null; } } /** * Hash of {@link #VERSION}. */ public static String VERSION_HASH; /** * Unique random token that identifies the current session. * Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header. * * We used to use {@link #VERSION_HASH}, but making this session local allows us to * reuse the same {@link #RESOURCE_PATH} for static resources in plugins. */ public static String SESSION_HASH; /** * Prefix to static resources like images and javascripts in the war file. * Either "" or strings like "/static/VERSION", which avoids Hudson to pick up * stale cache when the user upgrades to a different version. * <p> * Value computed in {@link WebAppMain}. */ public static String RESOURCE_PATH = ""; /** * Prefix to resources alongside view scripts. * Strings like "/resources/VERSION", which avoids Hudson to pick up * stale cache when the user upgrades to a different version. * <p> * Value computed in {@link WebAppMain}. */ public static String VIEW_RESOURCE_PATH = "/resources/TBD"; public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true); public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false); /** * Enabled by default as of 1.337. Will keep it for a while just in case we have some serious problems. */ public static boolean FLYWEIGHT_SUPPORT = Configuration.getBooleanConfigParameter("flyweightSupport", true); /** * Tentative switch to activate the concurrent build behavior. * When we merge this back to the trunk, this allows us to keep * this feature hidden for a while until we iron out the kinks. * @see AbstractProject#isConcurrentBuild() * @deprecated as of 1.464 * This flag will have no effect. */ @Restricted(NoExternalUse.class) public static boolean CONCURRENT_BUILD = true; /** * Switch to enable people to use a shorter workspace name. */ private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace"); /** * Automatically try to launch a slave when Jenkins is initialized or a new slave is created. */ public static boolean AUTOMATIC_SLAVE_LAUNCH = true; private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName()); private static final Pattern ICON_SIZE = Pattern.compile("\\d+x\\d+"); public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS; public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER; public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS); public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS); /** * {@link Authentication} object that represents the anonymous user. * Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not * expect the singleton semantics. This is just a convenient instance. * * @since 1.343 */ public static final Authentication ANONYMOUS = new AnonymousAuthenticationToken( "anonymous","anonymous",new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")}); static { XSTREAM.alias("jenkins",Jenkins.class); XSTREAM.alias("slave", DumbSlave.class); XSTREAM.alias("jdk",JDK.class); // for backward compatibility with <1.75, recognize the tag name "view" as well. XSTREAM.alias("view", ListView.class); XSTREAM.alias("listView", ListView.class); // this seems to be necessary to force registration of converter early enough Mode.class.getEnumConstants(); // double check that initialization order didn't do any harm assert PERMISSIONS!=null; assert ADMINISTER!=null; } }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_2097_2
crossvul-java_data_bad_5805_0
/* * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.util; /** * Utility class for JavaScript escaping. * Escapes based on the JavaScript 1.5 recommendation. * * <p>Reference: * <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Literals#String_Literals"> * Core JavaScript 1.5 Guide * </a> * * @author Juergen Hoeller * @author Rob Harrop * @since 1.1.1 */ public class JavaScriptUtils { /** * Turn special characters into escaped characters conforming to JavaScript. * Handles complete character set defined in HTML 4.01 recommendation. * @param input the input string * @return the escaped string */ public static String javaScriptEscape(String input) { if (input == null) { return input; } StringBuilder filtered = new StringBuilder(input.length()); char prevChar = '\u0000'; char c; for (int i = 0; i < input.length(); i++) { c = input.charAt(i); if (c == '"') { filtered.append("\\\""); } else if (c == '\'') { filtered.append("\\'"); } else if (c == '\\') { filtered.append("\\\\"); } else if (c == '/') { filtered.append("\\/"); } else if (c == '\t') { filtered.append("\\t"); } else if (c == '\n') { if (prevChar != '\r') { filtered.append("\\n"); } } else if (c == '\r') { filtered.append("\\n"); } else if (c == '\f') { filtered.append("\\f"); } else { filtered.append(c); } prevChar = c; } return filtered.toString(); } }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_5805_0
crossvul-java_data_bad_509_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-79/java/bad_509_0
crossvul-java_data_bad_4174_2
package org.mapfish.print.servlet; import org.json.JSONObject; import org.junit.After; import org.junit.Test; import org.mapfish.print.AbstractMapfishSpringTest; import org.mapfish.print.config.access.AccessAssertionTestUtil; import org.mapfish.print.test.util.ImageSimilarity; import org.mapfish.print.wrapper.json.PJsonObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.ContextConfiguration; import java.io.IOException; import java.net.URISyntaxException; import java.util.Calendar; import java.util.HashMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @ContextConfiguration(locations = { MapPrinterServletSecurityTest.PRINT_CONTEXT }) public class MapPrinterServletSecurityTest extends AbstractMapfishSpringTest { public static final String PRINT_CONTEXT = "classpath:org/mapfish/print/servlet/mapfish-print-servlet.xml"; @Autowired private MapPrinterServlet servlet; @Autowired private ServletMapPrinterFactory printerFactory; @After public void tearDown() { SecurityContextHolder.clearContext(); } @Test(timeout = 60000) public void testCreateReportAndGet_Success() throws Exception { AccessAssertionTestUtil.setCreds("ROLE_USER", "ROLE_EDITOR"); setUpConfigFiles(); final MockHttpServletRequest servletCreateRequest = new MockHttpServletRequest(); final MockHttpServletResponse servletCreateResponse = new MockHttpServletResponse(); String requestData = loadRequestDataAsString(); this.servlet.createReportAndGetNoAppId("png", requestData, false, servletCreateRequest, servletCreateResponse); assertEquals(HttpStatus.OK.value(), servletCreateResponse.getStatus()); assertCorrectResponse(servletCreateResponse); } @Test(timeout = 60000, expected = AccessDeniedException.class) public void testCreateReportAndGet_InsufficientPrivileges() throws Exception { AccessAssertionTestUtil.setCreds("ROLE_USER"); setUpConfigFiles(); final MockHttpServletRequest servletCreateRequest = new MockHttpServletRequest(); final MockHttpServletResponse servletCreateResponse = new MockHttpServletResponse(); String requestData = loadRequestDataAsString(); this.servlet.createReportAndGetNoAppId("png", requestData, false, servletCreateRequest, servletCreateResponse); } @Test(timeout = 60000, expected = AuthenticationCredentialsNotFoundException.class) public void testCreateReportAndGet_NoCredentials() throws Exception { setUpConfigFiles(); final MockHttpServletRequest servletCreateRequest = new MockHttpServletRequest(); final MockHttpServletResponse servletCreateResponse = new MockHttpServletResponse(); String requestData = loadRequestDataAsString(); this.servlet.createReportAndGetNoAppId("png", requestData, false, servletCreateRequest, servletCreateResponse); } @Test(timeout = 60000) public void testCreateReportAndGet_RequestAllowed_OtherGetDenied() throws Exception { AccessAssertionTestUtil.setCreds("ROLE_USER", "ROLE_EDITOR"); setUpConfigFiles(); final MockHttpServletRequest servletCreateRequest = new MockHttpServletRequest(); final MockHttpServletResponse servletCreateResponse = new MockHttpServletResponse(); String requestData = loadRequestDataAsString(); this.servlet.createReport("png", requestData, servletCreateRequest, servletCreateResponse); assertEquals(HttpStatus.OK.value(), servletCreateResponse.getStatus()); final JSONObject response = new JSONObject(servletCreateResponse.getContentAsString()); final String ref = response.getString(MapPrinterServlet.JSON_PRINT_JOB_REF); String statusURL = response.getString(MapPrinterServlet.JSON_STATUS_LINK); // wait until job is done boolean done = false; while (!done) { MockHttpServletRequest servletStatusRequest = new MockHttpServletRequest("GET", statusURL); MockHttpServletResponse servletStatusResponse = new MockHttpServletResponse(); servlet.getStatus(ref, null, servletStatusRequest, servletStatusResponse); String contentAsString = servletStatusResponse.getContentAsString(); final PJsonObject statusJson = parseJSONObjectFromString(contentAsString); assertTrue(statusJson.toString(), statusJson.has(MapPrinterServlet.JSON_DONE)); done = statusJson.getBool(MapPrinterServlet.JSON_DONE); if (!done) { Thread.sleep(500); } } try { AccessAssertionTestUtil.setCreds("ROLE_USER"); final MockHttpServletResponse getResponse1 = new MockHttpServletResponse(); this.servlet.getReport(ref, false, getResponse1); fail("Expected an AccessDeniedException"); } catch (AccessDeniedException e) { // good } SecurityContextHolder.clearContext(); try { final MockHttpServletResponse getResponse2 = new MockHttpServletResponse(); this.servlet.getReport(ref, false, getResponse2); assertEquals(HttpStatus.UNAUTHORIZED.value(), servletCreateResponse.getStatus()); fail("Expected an AuthenticationCredentialsNotFoundException"); } catch (AuthenticationCredentialsNotFoundException e) { // good } } private byte[] assertCorrectResponse(MockHttpServletResponse servletGetReportResponse) throws IOException { byte[] report; report = servletGetReportResponse.getContentAsByteArray(); final String contentType = servletGetReportResponse.getHeader("Content-Type"); assertEquals("image/png", contentType); final Calendar instance = Calendar.getInstance(); int year = instance.get(Calendar.YEAR); String fileName = servletGetReportResponse.getHeader("Content-disposition").split("=")[1]; assertEquals("test_report-" + year + ".png", fileName); new ImageSimilarity(getFile(MapPrinterServletSecurityTest.class, "expectedSimpleImage.png")) .assertSimilarity(report, 1); return report; } private void setUpConfigFiles() throws URISyntaxException { final HashMap<String, String> configFiles = new HashMap<>(); configFiles.put("default", getFile(MapPrinterServletSecurityTest.class, "config-security.yaml") .getAbsolutePath()); printerFactory.setConfigurationFiles(configFiles); } private String loadRequestDataAsString() throws IOException { final PJsonObject requestJson = parseJSONObjectFromFile(MapPrinterServletSecurityTest.class, "requestData.json"); return requestJson.getInternalObj().toString(); } }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_4174_2
crossvul-java_data_bad_2099_0
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Michael B. Donohue, Seiji Sogabe * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.model; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import hudson.console.ModelHyperlinkNote; import hudson.diagnosis.OldDataMonitor; import hudson.util.XStream2; import jenkins.model.Jenkins; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import com.thoughtworks.xstream.converters.UnmarshallingContext; import java.util.HashSet; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; /** * Cause object base class. This class hierarchy is used to keep track of why * a given build was started. This object encapsulates the UI rendering of the cause, * as well as providing more useful information in respective subypes. * * The Cause object is connected to a build via the {@link CauseAction} object. * * <h2>Views</h2> * <dl> * <dt>description.jelly * <dd>Renders the cause to HTML. By default, it puts the short description. * </dl> * * @author Michael Donohue * @see Run#getCauses() * @see Queue.Item#getCauses() */ @ExportedBean public abstract class Cause { /** * One-line human-readable text of the cause. * * <p> * By default, this method is used to render HTML as well. */ @Exported(visibility=3) public abstract String getShortDescription(); /** * Called when the cause is registered to {@link AbstractBuild}. * * @param build * never null * @since 1.376 */ public void onAddedTo(AbstractBuild build) {} /** * Report a line to the listener about this cause. * @since 1.362 */ public void print(TaskListener listener) { listener.getLogger().println(getShortDescription()); } /** * Fall back implementation when no other type is available. * @deprecated since 2009-02-08 */ public static class LegacyCodeCause extends Cause { private StackTraceElement [] stackTrace; public LegacyCodeCause() { stackTrace = new Exception().getStackTrace(); } @Override public String getShortDescription() { return Messages.Cause_LegacyCodeCause_ShortDescription(); } } /** * A build is triggered by the completion of another build (AKA upstream build.) */ public static class UpstreamCause extends Cause { /** * Maximum depth of transitive upstream causes we want to record. */ private static final int MAX_DEPTH = 10; /** * Maximum number of transitive upstream causes we want to record. */ private static final int MAX_LEAF = 25; private String upstreamProject, upstreamUrl; private int upstreamBuild; /** * @deprecated since 2009-02-28 */ @Deprecated private transient Cause upstreamCause; private @Nonnull List<Cause> upstreamCauses; /** * @deprecated since 2009-02-28 */ // for backward bytecode compatibility public UpstreamCause(AbstractBuild<?,?> up) { this((Run<?,?>)up); } public UpstreamCause(Run<?, ?> up) { upstreamBuild = up.getNumber(); upstreamProject = up.getParent().getFullName(); upstreamUrl = up.getParent().getUrl(); upstreamCauses = new ArrayList<Cause>(); Set<String> traversed = new HashSet<String>(); for (Cause c : up.getCauses()) { upstreamCauses.add(trim(c, MAX_DEPTH, traversed)); } } private UpstreamCause(String upstreamProject, int upstreamBuild, String upstreamUrl, @Nonnull List<Cause> upstreamCauses) { this.upstreamProject = upstreamProject; this.upstreamBuild = upstreamBuild; this.upstreamUrl = upstreamUrl; this.upstreamCauses = upstreamCauses; } private @Nonnull Cause trim(@Nonnull Cause c, int depth, Set<String> traversed) { if (!(c instanceof UpstreamCause)) { return c; } UpstreamCause uc = (UpstreamCause) c; List<Cause> cs = new ArrayList<Cause>(); if (depth > 0) { if (traversed.add(uc.upstreamUrl + uc.upstreamBuild)) { for (Cause c2 : uc.upstreamCauses) { cs.add(trim(c2, depth - 1, traversed)); } } } else if (traversed.size() < MAX_LEAF) { cs.add(new DeeplyNestedUpstreamCause()); } return new UpstreamCause(uc.upstreamProject, uc.upstreamBuild, uc.upstreamUrl, cs); } /** * Returns true if this cause points to a build in the specified job. */ public boolean pointsTo(Job<?,?> j) { return j.getFullName().equals(upstreamProject); } /** * Returns true if this cause points to the specified build. */ public boolean pointsTo(Run<?,?> r) { return r.getNumber()==upstreamBuild && pointsTo(r.getParent()); } @Exported(visibility=3) public String getUpstreamProject() { return upstreamProject; } @Exported(visibility=3) public int getUpstreamBuild() { return upstreamBuild; } /** * @since 1.505 */ public @CheckForNull Run<?,?> getUpstreamRun() { Job<?,?> job = Jenkins.getInstance().getItemByFullName(upstreamProject, Job.class); return job != null ? job.getBuildByNumber(upstreamBuild) : null; } @Exported(visibility=3) public String getUpstreamUrl() { return upstreamUrl; } public List<Cause> getUpstreamCauses() { return upstreamCauses; } @Override public String getShortDescription() { return Messages.Cause_UpstreamCause_ShortDescription(upstreamProject, upstreamBuild); } @Override public void print(TaskListener listener) { print(listener, 0); } private void indent(TaskListener listener, int depth) { for (int i = 0; i < depth; i++) { listener.getLogger().print(' '); } } private void print(TaskListener listener, int depth) { indent(listener, depth); listener.getLogger().println( Messages.Cause_UpstreamCause_ShortDescription( ModelHyperlinkNote.encodeTo('/' + upstreamUrl, upstreamProject), ModelHyperlinkNote.encodeTo('/'+upstreamUrl+upstreamBuild, Integer.toString(upstreamBuild))) ); if (upstreamCauses != null && !upstreamCauses.isEmpty()) { indent(listener, depth); listener.getLogger().println(Messages.Cause_UpstreamCause_CausedBy()); for (Cause cause : upstreamCauses) { if (cause instanceof UpstreamCause) { ((UpstreamCause) cause).print(listener, depth + 1); } else { indent(listener, depth + 1); cause.print(listener); } } } } @Override public String toString() { return upstreamUrl + upstreamBuild + upstreamCauses; } public static class ConverterImpl extends XStream2.PassthruConverter<UpstreamCause> { public ConverterImpl(XStream2 xstream) { super(xstream); } @Override protected void callback(UpstreamCause uc, UnmarshallingContext context) { if (uc.upstreamCause != null) { if (uc.upstreamCauses == null) uc.upstreamCauses = new ArrayList<Cause>(); uc.upstreamCauses.add(uc.upstreamCause); uc.upstreamCause = null; OldDataMonitor.report(context, "1.288"); } } } public static class DeeplyNestedUpstreamCause extends Cause { @Override public String getShortDescription() { return "(deeply nested causes)"; } @Override public String toString() { return "JENKINS-14814"; } } } /** * A build is started by an user action. * * @deprecated 1.428 * use {@link UserIdCause} */ public static class UserCause extends Cause { private String authenticationName; public UserCause() { this.authenticationName = Jenkins.getAuthentication().getName(); } @Exported(visibility=3) public String getUserName() { User u = User.get(authenticationName, false); return u != null ? u.getDisplayName() : authenticationName; } @Override public String getShortDescription() { return Messages.Cause_UserCause_ShortDescription(authenticationName); } @Override public boolean equals(Object o) { return o instanceof UserCause && Arrays.equals(new Object[] {authenticationName}, new Object[] {((UserCause)o).authenticationName}); } @Override public int hashCode() { return 295 + (this.authenticationName != null ? this.authenticationName.hashCode() : 0); } } /** * A build is started by an user action. * * @since 1.427 */ public static class UserIdCause extends Cause { private String userId; public UserIdCause() { User user = User.current(); this.userId = (user == null) ? null : user.getId(); } @Exported(visibility = 3) public String getUserId() { return userId; } @Exported(visibility = 3) public String getUserName() { String userName = "anonymous"; if (userId != null) { User user = User.get(userId, false); if (user != null) userName = user.getDisplayName(); } return userName; } @Override public String getShortDescription() { return Messages.Cause_UserIdCause_ShortDescription(getUserName()); } @Override public void print(TaskListener listener) { listener.getLogger().println(Messages.Cause_UserIdCause_ShortDescription( ModelHyperlinkNote.encodeTo("/user/"+getUserId(), getUserName()))); } @Override public boolean equals(Object o) { return o instanceof UserIdCause && Arrays.equals(new Object[]{userId}, new Object[]{((UserIdCause) o).userId}); } @Override public int hashCode() { return 295 + (this.userId != null ? this.userId.hashCode() : 0); } } public static class RemoteCause extends Cause { private String addr; private String note; public RemoteCause(String host, String note) { this.addr = host; this.note = note; } @Override public String getShortDescription() { if(note != null) { return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, note); } else { return Messages.Cause_RemoteCause_ShortDescription(addr); } } @Override public boolean equals(Object o) { return o instanceof RemoteCause && Arrays.equals(new Object[] {addr, note}, new Object[] {((RemoteCause)o).addr, ((RemoteCause)o).note}); } @Override public int hashCode() { int hash = 5; hash = 83 * hash + (this.addr != null ? this.addr.hashCode() : 0); hash = 83 * hash + (this.note != null ? this.note.hashCode() : 0); return hash; } } }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_2099_0
crossvul-java_data_bad_509_1
package org.hswebframework.web.workflow.web; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import lombok.extern.slf4j.Slf4j; import org.activiti.bpmn.converter.BpmnXMLConverter; import org.activiti.bpmn.model.BpmnModel; import org.activiti.editor.language.json.converter.BpmnJsonConverter; import org.activiti.engine.RepositoryService; import org.activiti.engine.impl.persistence.entity.ModelEntity; import org.activiti.engine.repository.Deployment; import org.activiti.engine.repository.Model; import org.activiti.engine.repository.ModelQuery; import org.apache.batik.transcoder.TranscoderException; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.PNGTranscoder; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.hswebframework.ezorm.core.PropertyWrapper; import org.hswebframework.ezorm.core.SimplePropertyWrapper; import org.hswebframework.ezorm.core.param.TermType; import org.hswebframework.web.NotFoundException; import org.hswebframework.web.authorization.Permission; import org.hswebframework.web.authorization.annotation.Authorize; import org.hswebframework.web.bean.FastBeanCopier; import org.hswebframework.web.commons.entity.PagerResult; import org.hswebframework.web.commons.entity.param.QueryParamEntity; import org.hswebframework.web.controller.message.ResponseMessage; import org.hswebframework.web.workflow.util.QueryUtils; import org.hswebframework.web.workflow.web.request.ModelCreateRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.util.List; import java.util.Map; @RestController @RequestMapping("/workflow/model") @Api(tags = "工作流-模型管理", description = "工作流模型管理") @Authorize(permission = "workflow-model", description = "工作流模型管理") @Slf4j public class FlowableModelManagerController { @Autowired private RepositoryService repositoryService; private final static String MODEL_ID = "modelId"; private final static String MODEL_NAME = "name"; private final static String MODEL_REVISION = "revision"; private final static String MODEL_DESCRIPTION = "description"; private final static String MODEL_KEY = "key"; @GetMapping @Authorize(action = Permission.ACTION_QUERY) @ApiOperation("获取模型列表") public ResponseMessage<PagerResult<Model>> getModelList(QueryParamEntity param) { ModelQuery modelQuery = repositoryService.createModelQuery(); return ResponseMessage.ok( QueryUtils.doQuery(modelQuery, param, model -> FastBeanCopier.copy(model, new ModelEntity()), (term, modelQuery1) -> { if ("latestVersion".equals(term.getColumn())) { modelQuery1.latestVersion(); } })); } @PostMapping @ResponseStatus(value = HttpStatus.CREATED) @ApiOperation("创建模型") public ResponseMessage<Model> createModel(@RequestBody ModelCreateRequest model) throws Exception { JSONObject stencilset = new JSONObject(); stencilset.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#"); JSONObject editorNode = new JSONObject(); editorNode.put("id", "canvas"); editorNode.put("resourceId", "canvas"); editorNode.put("stencilset", stencilset); JSONObject modelObjectNode = new JSONObject(); modelObjectNode.put(MODEL_REVISION, 1); modelObjectNode.put(MODEL_DESCRIPTION, model.getDescription()); modelObjectNode.put(MODEL_KEY, model.getKey()); modelObjectNode.put(MODEL_NAME, model.getName()); Model modelData = repositoryService.newModel(); modelData.setMetaInfo(modelObjectNode.toJSONString()); modelData.setName(model.getName()); modelData.setKey(model.getKey()); repositoryService.saveModel(modelData); repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8")); return ResponseMessage.ok(modelData).status(201); } @PostMapping("/{modelId}/deploy") @ApiOperation("发布模型") @Authorize(action = "deploy") public ResponseMessage<Deployment> deployModel(@PathVariable String modelId) throws Exception { Model modelData = repositoryService.getModel(modelId); if (modelData == null) { throw new NotFoundException("模型不存在!"); } ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId())); BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode); byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model); String processName = modelData.getName() + ".bpmn20.xml"; Deployment deployment = repositoryService.createDeployment() .name(modelData.getName()) .addString(processName, new String(bpmnBytes, "utf8")) .deploy(); return ResponseMessage.ok(deployment).include(Deployment.class, "id", "name", "new"); } /** * 导出model对象为指定类型 * * @param modelId 模型ID * @param type 导出文件类型(bpmn\json) */ @GetMapping(value = "export/{modelId}/{type}") @ApiOperation("导出模型") @Authorize(action = "export") public void export(@PathVariable("modelId") @ApiParam("模型ID") String modelId, @PathVariable("type") @ApiParam(value = "类型", allowableValues = "bpmn,json", example = "json") String type, @ApiParam(hidden = true) HttpServletResponse response) { try { Model modelData = repositoryService.getModel(modelId); BpmnJsonConverter jsonConverter = new BpmnJsonConverter(); byte[] modelEditorSource = repositoryService.getModelEditorSource(modelData.getId()); JsonNode editorNode = new ObjectMapper().readTree(modelEditorSource); BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode); // 处理异常 if (bpmnModel.getMainProcess() == null) { response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value()); response.getOutputStream().println("no main process, can't export for dimension: " + type); response.flushBuffer(); return; } String filename = ""; byte[] exportBytes = null; String mainProcessId = bpmnModel.getMainProcess().getId(); if ("bpmn".equals(type)) { BpmnXMLConverter xmlConverter = new BpmnXMLConverter(); exportBytes = xmlConverter.convertToXML(bpmnModel); filename = mainProcessId + ".bpmn20.xml"; } else if ("json".equals(type)) { exportBytes = modelEditorSource; filename = mainProcessId + ".json"; } else { throw new UnsupportedOperationException("不支持的格式:" + type); } response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8")); /*创建输入流*/ try (ByteArrayInputStream in = new ByteArrayInputStream(exportBytes)) { IOUtils.copy(in, response.getOutputStream()); response.flushBuffer(); in.close(); } } catch (Exception e) { log.error("导出model的xml文件失败:modelId={}, type={}", modelId, type, e); } } @GetMapping(value = "/{modelId}/json") @Authorize(action = Permission.ACTION_GET) public Object getEditorJson(@PathVariable String modelId) { JSONObject modelNode; Model model = repositoryService.getModel(modelId); if (model == null) throw new NullPointerException("模型不存在"); if (StringUtils.isNotEmpty(model.getMetaInfo())) { modelNode = JSON.parseObject(model.getMetaInfo()); } else { modelNode = new JSONObject(); modelNode.put(MODEL_NAME, model.getName()); } modelNode.put(MODEL_ID, model.getId()); modelNode.put("model", JSON.parse(new String(repositoryService.getModelEditorSource(model.getId())))); return modelNode; } @PutMapping(value = "/{modelId}") @ResponseStatus(value = HttpStatus.OK) @Authorize(action = Permission.ACTION_UPDATE) public void saveModel(@PathVariable String modelId, @RequestParam Map<String, String> values) throws TranscoderException, IOException { Model model = repositoryService.getModel(modelId); JSONObject modelJson = JSON.parseObject(model.getMetaInfo()); modelJson.put(MODEL_NAME, values.get("name")); modelJson.put(MODEL_DESCRIPTION, values.get("description")); model.setMetaInfo(modelJson.toString()); model.setName(values.get("name")); repositoryService.saveModel(model); repositoryService.addModelEditorSource(model.getId(), values.get("json_xml").getBytes("utf-8")); InputStream svgStream = new ByteArrayInputStream(values.get("svg_xml").getBytes("utf-8")); TranscoderInput input = new TranscoderInput(svgStream); PNGTranscoder transcoder = new PNGTranscoder(); // Setup output ByteArrayOutputStream outStream = new ByteArrayOutputStream(); TranscoderOutput output = new TranscoderOutput(outStream); // Do the transformation transcoder.transcode(input, output); final byte[] result = outStream.toByteArray(); repositoryService.addModelEditorSourceExtra(model.getId(), result); outStream.close(); } @DeleteMapping("/{modelId}") @Authorize(action = Permission.ACTION_DELETE) public ResponseMessage<Void> delete(@PathVariable String modelId) { repositoryService.deleteModel(modelId); return ResponseMessage.ok(); } }
./CrossVul/dataset_final_sorted/CWE-79/java/bad_509_1