List of usage examples for javax.servlet.http HttpServletResponse SC_FORBIDDEN
int SC_FORBIDDEN
To view the source code for javax.servlet.http HttpServletResponse SC_FORBIDDEN.
Click Source Link
From source file:eu.trentorise.smartcampus.unidataservice.controller.rest.StudentInfoController.java
@RequestMapping(method = RequestMethod.GET, value = "/getoperacard/{userId}") public @ResponseBody OperaStudent getCard(HttpServletRequest request, HttpServletResponse response, HttpSession session, @PathVariable String userId) throws IOException { try {//from w w w. j a va2 s .c o m User user = getUserObject(userId); if (user == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return null; } String token = getToken(request); String idAda = getIdAda(userId, token); OperaStudent result = getCard(idAda); if (result != null) { return result; } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } catch (Exception e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return null; }
From source file:com.haulmont.cuba.restapi.DataServiceController.java
@RequestMapping(value = "/api/query", method = RequestMethod.POST) public void queryByPost(@RequestParam(value = "s") String sessionId, @RequestHeader(value = "Content-Type") MimeType contentType, @RequestBody String requestContent, HttpServletRequest request, HttpServletResponse response) throws IOException { if (!authentication.begin(sessionId)) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return;/*from w w w. j a v a2 s . co m*/ } try { Converter converter = conversionFactory.getConverter(contentType); QueryRequest queryRequest = converter.parseQueryRequest(requestContent); MetaClass metaClass = metadata.getClass(queryRequest.getEntity()); if (metaClass == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Persistent entity " + queryRequest.getEntity() + " does not exist"); return; } if (!entityOpPermitted(metaClass, EntityOp.READ)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } LoadContext loadCtx = new LoadContext(metaClass); loadCtx.setLoadDynamicAttributes(Boolean.TRUE.equals(queryRequest.loadDynamicAttributes())); LoadContext.Query query = new LoadContext.Query(queryRequest.getQuery()); for (String key : queryRequest.getParams().keySet()) { query.setParameter(key, queryRequest.getParams().get(key)); } loadCtx.setQuery(query); if (queryRequest.getFirst() != null) query.setFirstResult(queryRequest.getFirst()); if (queryRequest.getMax() != null) query.setMaxResults(queryRequest.getMax()); if (queryRequest.getViewName() == null) { View view = metadata.getViewRepository().getView(metaClass, View.LOCAL); loadCtx.setView(new View(view, "local-with-system-props", true)); } else { loadCtx.setView(queryRequest.getViewName()); } List<Entity> entities = dataService.loadList(loadCtx); String result = converter.process(entities, metaClass, loadCtx.getView()); writeResponse(response, result, converter.getMimeType()); } catch (RowLevelSecurityException e) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "The operation with entity " + e.getEntity() + " is denied"); } catch (Throwable e) { sendError(request, response, e); } finally { authentication.end(); } }
From source file:org.artifactory.webapp.servlet.RepoFilter.java
@SuppressWarnings("OverlyComplexMethod") private void execute(FilterChain chain, final HttpServletRequest request, HttpServletResponse response, String servletPath) throws IOException, ServletException { if (log.isDebugEnabled()) { log.debug("Entering request {}.", requestDebugString(request)); }//from w w w . ja va2s . co m if (request.getRequestURI().endsWith("treebrowser")) { ArtifactoryRequest artifactoryRequest = new HttpArtifactoryRequest(request); request.setAttribute(ATTR_ARTIFACTORY_REPOSITORY_PATH, artifactoryRequest.getRepoPath()); request.setAttribute(ATTR_ARTIFACTORY_REQUEST_PROPERTIES, artifactoryRequest.getProperties()); } boolean repoRequest = servletPath != null && RequestUtils.isRepoRequest(request, true); if (repoRequest && servletPath.startsWith("/" + ArtifactoryRequest.LIST_BROWSING_PATH) && servletPath.endsWith("/")) { ArtifactoryRequest artifactoryRequest = new HttpArtifactoryRequest(request); String repoKey = artifactoryRequest.getRepoKey(); if (VirtualRepoDescriptor.GLOBAL_VIRTUAL_REPO_KEY.equals(repoKey) && ConstantValues.disableGlobalRepoAccess.getBoolean()) { // The global /repo is disabled. Cannot be used here, returning 403! String msg = "Accessing the global virtual repository /repo is disabled!"; log.warn(msg); response.sendError(HttpStatus.SC_FORBIDDEN, msg); return; } doRepoListing(request, response, servletPath, artifactoryRequest); return; } String method = request.getMethod().toLowerCase().intern(); if (repoRequest) { ArtifactoryRequest artifactoryRequest = new HttpArtifactoryRequest(request); //Handle upload and download requests ArtifactoryResponse artifactoryResponse = new HttpArtifactoryResponse(response); if (artifactoryRequest.isDirectoryRequest() && isGetOrHeadRequest(method)) { //Check that this is not a recursive call if (artifactoryRequest.isRecursive()) { String msg = "Recursive call detected for '" + request + "'. Returning nothing."; artifactoryResponse.sendError(HttpStatus.SC_NOT_FOUND, msg, log); return; } log.debug("Serving a directory get request."); String repoKey = artifactoryRequest.getRepoKey(); if (VirtualRepoDescriptor.GLOBAL_VIRTUAL_REPO_KEY.equals(repoKey) && ConstantValues.disableGlobalRepoAccess.getBoolean()) { // The global /repo is disabled. Cannot be used here, returning 403! String msg = "Accessing the global virtual repository /repo is disabled!"; log.warn(msg); response.sendError(HttpStatus.SC_FORBIDDEN, msg); return; } doRepoListing(request, response, servletPath, artifactoryRequest); return; } try { initRequestContext(method, artifactoryRequest, artifactoryResponse); if (isGetOrHeadRequest(method)) { /** * Do not check for this parameter when not performing a get/head request so that the container * doesn't try to read the parameters and verify the size of the form in case of an upload */ if (artifactoryRequest.getParameter(ArtifactRestConstants.TRACE_PARAM) != null) { //Re-init the context with the trace logging response artifactoryResponse = new TraceLoggingResponse(artifactoryResponse); initRequestContext(method, artifactoryRequest, artifactoryResponse); } // TODO: Should we return 405 Method not allowed for head request on properties: // TODO: For now the HEAD request will ignore this properties query param if (artifactoryRequest.getParameter(ArtifactRestConstants.PROPERTIES_PARAM) != null) { //Set the response to return only the properties of the item in json format artifactoryResponse.setPropertiesMediaType(MediaType.APPLICATION_JSON.toString()); } if (artifactoryRequest.getParameter(ArtifactRestConstants.PROPERTIES_XML_PARAM) != null) { //Set the response to return only the properties of the item in json format artifactoryResponse.setPropertiesMediaType(MediaType.APPLICATION_XML.toString()); } doDownload(request, response, method, artifactoryRequest, artifactoryResponse); return; } if ("put".equals(method)) { doUpload(artifactoryRequest, artifactoryResponse); return; } doWebDavMethod(request, response, method, artifactoryRequest, artifactoryResponse); } finally { RepoRequests.destroy(); } } else if (!response.isCommitted()) { // Webdav request not on repository, return 403 if (RequestUtils.isWebdavRequest(request)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); if (log.isDebugEnabled()) { log.debug("Received webdav request on " + servletPath + " which is not a repository!\n" + "Returning " + HttpServletResponse.SC_FORBIDDEN); } } else { // TODO: [by dan] this is a workaround for the Git LFS bug in 0.5.1 - see RTFACT-7587 remove this ugly // TODO: hack when we decide we can drop support for versions < 0.5.2 or when Jersey is updated above 2.0 chain.doFilter(wrapRequestIfNeeded(request), response); } } if (log.isDebugEnabled()) { log.debug("Exiting request " + requestDebugString(request)); } }
From source file:org.jetbrains.webdemo.sessions.MyHttpSession.java
private void sendAddFileResult() { try {/*from ww w . j ava 2s . c om*/ String projectPublicId = request.getParameter("publicId"); String fileName = request.getParameter("filename"); String id = MySqlConnector.getInstance().addFileToProject(sessionInfo.getUserInfo(), projectPublicId, fileName); writeResponse(id, HttpServletResponse.SC_OK); } catch (NullPointerException e) { writeResponse("Can't get parameters", HttpServletResponse.SC_BAD_REQUEST); } catch (DatabaseOperationException e) { writeResponse(e.getMessage(), HttpServletResponse.SC_FORBIDDEN); } }
From source file:com.sun.faban.harness.webclient.Deployer.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {// w w w .j a v a 2 s. com List<String> deployNames = new ArrayList<String>(); List<String> cantDeployNames = new ArrayList<String>(); List<String> errDeployNames = new ArrayList<String>(); List<String> invalidNames = new ArrayList<String>(); List<String> errHeaders = new ArrayList<String>(); List<String> errDetails = new ArrayList<String>(); String user = null; String password = null; boolean clearConfig = false; boolean hasPermission = true; // Check whether we have to return text or html boolean acceptHtml = false; String acceptHeader = request.getHeader("Accept"); if (acceptHeader != null && acceptHeader.indexOf("text/html") >= 0) acceptHtml = true; DiskFileUpload fu = new DiskFileUpload(); // No maximum size fu.setSizeMax(-1); // maximum size that will be stored in memory fu.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() fu.setRepositoryPath(Config.TMP_DIR); StringWriter messageBuffer = new StringWriter(); PrintWriter messageWriter = new PrintWriter(messageBuffer); List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("user".equals(fieldName)) { user = item.getString(); } else if ("password".equals(fieldName)) { password = item.getString(); } else if ("clearconfig".equals(fieldName)) { String value = item.getString(); clearConfig = Boolean.parseBoolean(value); } continue; } if (!"jarfile".equals(fieldName)) continue; String fileName = item.getName(); if (fileName == null) // We don't process files without names continue; if (Config.SECURITY_ENABLED) { if (Config.DEPLOY_USER == null || Config.DEPLOY_USER.length() == 0 || !Config.DEPLOY_USER.equals(user)) { hasPermission = false; break; } if (Config.DEPLOY_PASSWORD == null || Config.DEPLOY_PASSWORD.length() == 0 || !Config.DEPLOY_PASSWORD.equals(password)) { hasPermission = false; break; } } // Now, this name may have a path attached, dependent on the // source browser. We need to cover all possible clients... char[] pathSeparators = { '/', '\\' }; // Well, if there is another separator we did not account for, // just add it above. for (int j = 0; j < pathSeparators.length; j++) { int idx = fileName.lastIndexOf(pathSeparators[j]); if (idx != -1) { fileName = fileName.substring(idx + 1); break; } } // Ignore all non-jarfiles. if (!fileName.toLowerCase().endsWith(".jar")) { invalidNames.add(fileName); continue; } String deployName = fileName.substring(0, fileName.length() - 4); if (deployName.indexOf('.') > -1) { invalidNames.add(deployName); continue; } // Check if we can deploy benchmark or service. // If running or queued, we won't deploy benchmark. // If service being used by current run,we won't deploy service. if (!DeployUtil.canDeployBenchmark(deployName) || !DeployUtil.canDeployService(deployName)) { cantDeployNames.add(deployName); continue; } File uploadFile = new File(Config.BENCHMARK_DIR, fileName); if (uploadFile.exists()) FileHelper.recursiveDelete(uploadFile); try { item.write(uploadFile); } catch (Exception e) { throw new ServletException(e); } try { DeployUtil.processUploadedJar(uploadFile, deployName); } catch (Exception e) { messageWriter.println("\nError deploying " + deployName + ".\n"); e.printStackTrace(messageWriter); errDeployNames.add(deployName); continue; } deployNames.add(deployName); } if (clearConfig) for (String benchName : deployNames) DeployUtil.clearConfig(benchName); if (!hasPermission) response.setStatus(HttpServletResponse.SC_FORBIDDEN); else if (cantDeployNames.size() > 0) response.setStatus(HttpServletResponse.SC_CONFLICT); else if (errDeployNames.size() > 0) response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); else if (invalidNames.size() > 0) response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); else if (deployNames.size() > 0) response.setStatus(HttpServletResponse.SC_CREATED); else response.setStatus(HttpServletResponse.SC_NOT_FOUND); StringBuilder b = new StringBuilder(); if (deployNames.size() > 0) { if (deployNames.size() > 1) b.append("Benchmarks/services "); else b.append("Benchmark/service "); for (int i = 0; i < deployNames.size(); i++) { if (i > 0) b.append(", "); b.append((String) deployNames.get(i)); } b.append(" deployed."); errHeaders.add(b.toString()); b.setLength(0); } if (invalidNames.size() > 0) { if (invalidNames.size() > 1) b.append("Invalid deploy files "); else b.append("Invalid deploy file "); for (int i = 0; i < invalidNames.size(); i++) { if (i > 0) b.append(", "); b.append((String) invalidNames.get(i)); } b.append(". Deploy files must have .jar extension."); errHeaders.add(b.toString()); b.setLength(0); } if (cantDeployNames.size() > 0) { if (cantDeployNames.size() > 1) b.append("Cannot deploy benchmarks/services "); else b.append("Cannot deploy benchmark/services "); for (int i = 0; i < cantDeployNames.size(); i++) { if (i > 0) b.append(", "); b.append((String) cantDeployNames.get(i)); } b.append(". Benchmark/services being used or " + "queued up for run."); errHeaders.add(b.toString()); b.setLength(0); } if (errDeployNames.size() > 0) { if (errDeployNames.size() > 1) { b.append("Error deploying benchmarks/services "); for (int i = 0; i < errDeployNames.size(); i++) { if (i > 0) b.append(", "); b.append((String) errDeployNames.get(i)); } } errDetails.add(messageBuffer.toString()); errHeaders.add(b.toString()); b.setLength(0); } if (!hasPermission) errHeaders.add("Permission denied!"); Writer writer = response.getWriter(); if (acceptHtml) writeHtml(request, writer, errHeaders, errDetails); else writeText(writer, errHeaders, errDetails); writer.flush(); writer.close(); } catch (ServletException e) { logger.log(Level.SEVERE, e.getMessage(), e); throw e; } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage(), e); throw e; } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); throw new ServletException(e); } }
From source file:org.jboss.as.test.manualmode.web.ssl.HTTPSWebConnectorTestCase.java
/** * @test.tsfi tsfi.keystore.file//from w ww .j a v a 2 s . com * @test.tsfi tsfi.truststore.file * @test.objective Testing default HTTPs connector with verify-client attribute set to "false". The CLIENT-CERT * authentication (BaseCertLoginModule) is configured for this test. Trusted client is allowed to access * both secured/unsecured resource. Untrusted client can only access unprotected resources. * @test.expectedResult Trusted client has access to protected and unprotected resources. Untrusted client has only access * to unprotected resources. * @throws Exception */ @Test @InSequence(1) public void testNonVerifyingConnector() throws Exception { Assume.assumeFalse( SystemUtils.IS_JAVA_1_6 && SystemUtils.JAVA_VENDOR.toUpperCase(Locale.ENGLISH).contains("IBM")); final URL printPrincipalUrl = getServletUrl(HTTPS_PORT_VERIFY_FALSE, PrincipalPrintingServlet.SERVLET_PATH); final URL securedUrl = getServletUrl(HTTPS_PORT_VERIFY_FALSE, SECURED_SERVLET_WITH_SESSION); final URL unsecuredUrl = getServletUrl(HTTPS_PORT_VERIFY_FALSE, SimpleServlet.SERVLET_PATH); final HttpClient httpClient = getHttpClient(CLIENT_KEYSTORE_FILE); final HttpClient httpClientUntrusted = getHttpClient(UNTRUSTED_KEYSTORE_FILE); try { makeCallWithHttpClient(printPrincipalUrl, httpClient, HttpServletResponse.SC_FORBIDDEN); String responseBody = makeCallWithHttpClient(securedUrl, httpClient, HttpServletResponse.SC_OK); assertEquals("Secured page was not reached", SimpleSecuredServlet.RESPONSE_BODY, responseBody); String principal = makeCallWithHttpClient(printPrincipalUrl, httpClient, HttpServletResponse.SC_OK); assertEquals("Unexpected principal", "cn=client", principal.toLowerCase()); responseBody = makeCallWithHttpClient(unsecuredUrl, httpClientUntrusted, HttpServletResponse.SC_OK); assertEquals("Secured page was not reached", SimpleServlet.RESPONSE_BODY, responseBody); try { makeCallWithHttpClient(securedUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN); } catch (SSLHandshakeException e) { // OK } catch (java.net.SocketException se) { // OK - on windows usually fails with this one } } finally { httpClient.getConnectionManager().shutdown(); httpClientUntrusted.getConnectionManager().shutdown(); } }
From source file:com.sun.faban.harness.webclient.Uploader.java
/** * Responsible for uploading the runs.//from w w w.ja v a 2 s .co m * @param request * @param response * @return String * @throws java.io.IOException * @throws javax.servlet.ServletException * @throws java.lang.ClassNotFoundException */ public String uploadRuns(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, ClassNotFoundException { // 3. Upload the run HashSet<String> duplicateSet = new HashSet<String>(); HashSet<String> replaceSet = new HashSet<String>(); String host = null; String key = null; boolean origin = false; // Whether the upload is to the original // run requestor. If so, key is needed. DiskFileUpload fu = new DiskFileUpload(); // No maximum size fu.setSizeMax(-1); // maximum size that will be stored in memory fu.setSizeThreshold(4096); // the location for saving data that is larger than // getSizeThreshold() fu.setRepositoryPath(Config.TMP_DIR); List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("host".equals(fieldName)) { host = item.getString(); } else if ("replace".equals(fieldName)) { replaceSet.add(item.getString()); } else if ("key".equals(fieldName)) { key = item.getString(); } else if ("origin".equals(fieldName)) { String value = item.getString(); origin = Boolean.parseBoolean(value); } continue; } if (host == null) { logger.warning("Host not received on upload request!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } // The host, origin, key info must be here before we receive // any file. if (origin) { if (Config.daemonMode != Config.DaemonModes.POLLEE) { logger.warning("Origin upload requested. Not pollee!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } if (key == null) { logger.warning("Origin upload requested. No key!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } if (!RunRetriever.authenticate(host, key)) { logger.warning("Origin upload requested. " + "Host/key mismatch: " + host + '/' + key + "!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } } if (!"jarfile".equals(fieldName)) // ignore continue; String fileName = item.getName(); if (fileName == null) // We don't process files without names continue; // Now, this name may have a path attached, dependent on the // source browser. We need to cover all possible clients... char[] pathSeparators = { '/', '\\' }; // Well, if there is another separator we did not account for, // just add it above. for (int j = 0; j < pathSeparators.length; j++) { int idx = fileName.lastIndexOf(pathSeparators[j]); if (idx != -1) { fileName = fileName.substring(idx + 1); break; } } // Ignore all non-jarfiles. if (!fileName.toLowerCase().endsWith(".jar")) continue; File uploadFile = new File(Config.TMP_DIR, host + '.' + fileName); try { item.write(uploadFile); } catch (Exception e) { throw new ServletException(e); } int runIdx = fileName.lastIndexOf("."); String runName = host + '.' + fileName.substring(0, runIdx); File runTmp = unjarTmp(uploadFile); //Check if archived recently if (checkIfArchived(runName) && !(replaceSet.contains(fileName.substring(0, runIdx)))) { //Now check if timestamps are same //Get the timestamp of run being uploaded at this point //ts is timestamp of run being uploaded String ts = getRunIdTimestamp(runName, Config.TMP_DIR); l1: while (true) { //reposTs is timestamp of run being compared in the //repository String reposTs = getRunIdTimestamp(runName, Config.OUT_DIR); if (reposTs.equals(ts)) { duplicateSet.add(fileName.substring(0, runIdx)); } else { runName = getNextRunId(runName); if (checkIfArchived(runName)) continue l1; File newRunNameFile = new File(Config.OUT_DIR, runName); if (newRunNameFile.exists()) { recursiveDelete(newRunNameFile); } if (recursiveCopy(runTmp, newRunNameFile)) { newRunNameFile.setLastModified(runTmp.lastModified()); uploadTags(runName); uploadFile.delete(); recursiveDelete(runTmp); } else { logger.warning("Origin upload requested. " + "Copy error!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); break; } response.setStatus(HttpServletResponse.SC_CREATED); } break; } } else { //File runTmp = unjarTmp(uploadFile); String runId = null; if (origin) { // Change origin file to know where this run came from. File metaInf = new File(runTmp, "META-INF"); File originFile = new File(metaInf, "origin"); if (!originFile.exists()) { logger.warning("Origin upload requested. " + "Origin file does not exist!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file does not exist!"); break; } RunId origRun; try { origRun = new RunId(readStringFromFile(originFile).trim()); } catch (IndexOutOfBoundsException e) { response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file error. " + e.getMessage()); break; } runId = origRun.getBenchName() + '.' + origRun.getRunSeq(); String localHost = origRun.getHostName(); if (!localHost.equals(Config.FABAN_HOST)) { logger.warning("Origin upload requested. Origin " + "host" + localHost + " does not match this host " + Config.FABAN_HOST + '!'); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } writeStringToFile(runTmp.getName(), originFile); } else { runId = runTmp.getName(); } File newRunFile = new File(Config.OUT_DIR, runId); if (newRunFile.exists()) { recursiveDelete(newRunFile); } if (recursiveCopy(runTmp, newRunFile)) { newRunFile.setLastModified(runTmp.lastModified()); uploadFile.delete(); uploadTags(runId); recursiveDelete(runTmp); } else { logger.warning("Origin upload requested. Copy error!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); break; } } response.setStatus(HttpServletResponse.SC_CREATED); //break; } request.setAttribute("duplicates", duplicateSet); return "/duplicates.jsp"; }
From source file:com.ecyrd.jspwiki.attachment.SilverpeasAttachmentServlet.java
/** * Serves a GET with two parameters: 'wikiname' specifying the wikiname of the attachment, * 'version' specifying the version indicator. {@inheritDoc} *///w w w . j a v a 2 s . com // FIXME: Messages would need to be localized somehow. public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { WikiContext context = m_engine.createContext(req, WikiContext.ATTACH); String version = req.getParameter(HDR_VERSION); String nextPage = req.getParameter("nextpage"); String msg = "An error occurred. Ouch."; int ver = WikiProvider.LATEST_VERSION; AttachmentManager mgr = m_engine.getAttachmentManager(); AuthorizationManager authmgr = m_engine.getAuthorizationManager(); String page = context.getPage().getName(); if (page == null) { log.info("Invalid attachment name."); res.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } OutputStream out = null; InputStream in = null; try { log.debug("Attempting to download att " + page + ", version " + version); if (version != null) { ver = Integer.parseInt(version); } Attachment att = mgr.getAttachmentInfo(page, ver); if (att != null) { // // Check if the user has permission for this attachment // Permission permission = PermissionFactory.getPagePermission(att, "view"); if (!authmgr.checkPermission(context.getWikiSession(), permission)) { log.debug("User does not have permission for this"); res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // // Check if the client already has a version of this attachment. // if (HttpUtil.checkFor304(req, att)) { log.debug("Client has latest version already, sending 304..."); res.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } String mimetype = getMimeType(context, att.getFileName()); res.setContentType(mimetype); // // We use 'inline' instead of 'attachment' so that user agents // can try to automatically open the file. // res.addHeader("Content-Disposition", "inline; filename=\"" + att.getFileName() + "\";"); res.addDateHeader("Last-Modified", att.getLastModified().getTime()); if (!att.isCacheable()) { res.addHeader("Pragma", "no-cache"); res.addHeader("Cache-control", "no-cache"); } // If a size is provided by the provider, report it. if (att.getSize() >= 0) { res.setContentLength((int) att.getSize()); } out = res.getOutputStream(); in = mgr.getAttachmentStream(context, att); int read = 0; byte[] buffer = new byte[BUFFER_SIZE]; while ((read = in.read(buffer)) > -1) { out.write(buffer, 0, read); } System.out.println("Attachment file is c:/tmp/result/" + att.getFileName()); System.out.println("Attachment " + att.getFileName() + " sent to " + req.getRemoteUser() + " on " + req.getRemoteAddr()); if (log.isDebugEnabled()) { msg = "Attachment " + att.getFileName() + " sent to " + req.getRemoteUser() + " on " + req.getRemoteAddr(); log.debug(msg); } if (nextPage != null) { res.sendRedirect(nextPage); } return; } msg = "Attachment '" + page + "', version " + ver + " does not exist."; log.info(msg); res.sendError(HttpServletResponse.SC_NOT_FOUND, msg); return; } catch (ProviderException pe) { msg = "Provider error: " + pe.getMessage(); log.debug("Provider failed while reading", pe); // // This might fail, if the response is already committed. So in that // case we just log it. // try { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } catch (IllegalStateException e) { } return; } catch (NumberFormatException nfe) { msg = "Invalid version number (" + version + ")"; res.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return; } catch (SocketException se) { // // These are very common in download situations due to aggressive // clients. No need to try and send an error. // log.debug("I/O exception during download", se); return; } catch (IOException ioe) { // // Client dropped the connection or something else happened. // We don't know where the error came from, so we'll at least // try to send an error and catch it quietly if it doesn't quite work. // msg = "Error: " + ioe.getMessage(); log.debug("I/O exception during download", ioe); try { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } catch (IllegalStateException e) { } return; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } // // Quite often, aggressive clients close the connection when they have // received the last bits. Therefore, we close the output, but ignore // any exception that might come out of it. // if (out != null) { try { out.close(); } catch (IOException e) { } } } }
From source file:net.sourceforge.subsonic.backend.controller.MultiController.java
private boolean authenticate(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException, IOException { String password = ServletRequestUtils.getRequiredStringParameter(request, "p"); if (!password.equals(Util.getPassword("backendpwd.txt"))) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return false; }//from w ww . ja va2 s .c o m return true; }
From source file:org.dasein.cloud.ibm.sce.compute.vm.SCEVirtualMachine.java
@Override public boolean isSubscribed() throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new SCEConfigException("No context was specified for this request"); }// www. j av a2 s. c o m try { ExtendedRegion region = provider.getDataCenterServices().getRegion(ctx.getRegionId()); return (region != null && region.isCompute()); } catch (CloudException e) { if (e.getHttpCode() == HttpServletResponse.SC_FORBIDDEN || e.getHttpCode() == HttpServletResponse.SC_UNAUTHORIZED) { return false; } throw e; } }