List of usage examples for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED
int SC_METHOD_NOT_ALLOWED
To view the source code for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED.
Click Source Link
Request-Line
is not allowed for the resource identified by the Request-URI
. From source file:org.gss_project.gss.server.rest.RequestHandler.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { boolean authDeferred = getAuthDeferred(req); // Strip the username part String path;// www . ja v a2 s . co m try { path = getUserPath(req); } catch (ObjectNotFoundException e) { if (authDeferred) { // We do not want to leak information if the request // was not authenticated. resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); return; } if (authDeferred && !path.startsWith(PATH_FILES)) { // Only POST to files may be authenticated without an Authorization header. resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } if (path.startsWith(PATH_OTHERS)) { resp.addHeader("Allow", methodsAllowed.get(PATH_OTHERS)); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else if (path.startsWith(PATH_SEARCH)) { resp.addHeader("Allow", methodsAllowed.get(PATH_SEARCH)); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else if (path.startsWith(PATH_TOKEN)) { resp.addHeader("Allow", methodsAllowed.get(PATH_TOKEN)); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else if (path.startsWith(PATH_USERS)) { resp.addHeader("Allow", methodsAllowed.get(PATH_USERS)); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else if (path.startsWith(PATH_SHARED)) { resp.addHeader("Allow", methodsAllowed.get(PATH_SHARED)); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else if (path.startsWith(PATH_TAGS)) { resp.addHeader("Allow", methodsAllowed.get(PATH_TAGS)); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else if (path.startsWith(PATH_GROUPS)) new GroupsHandler().postGroup(req, resp); else if (path.startsWith(PATH_TRASH)) { resp.addHeader("Allow", methodsAllowed.get(PATH_TRASH)); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else if (path.startsWith(PATH_FILES)) new FilesHandler(getServletContext()).postResource(req, resp); else if (path.equals("/")) new UserHandler().postUser(req, resp); else resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getRequestURI()); }
From source file:org.brutusin.rpc.http.RpcServlet.java
/** * * @param error/* w w w.jav a 2s . com*/ * @param resp */ private static void setStatusCode(RpcResponse.Error error, HttpServletResponse resp) { if (error.getCode() == RpcErrorCode.internalError.getCode()) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else if (error.getCode() == RpcErrorCode.methodNotFound.getCode()) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } else if (error.getCode() == RpcErrorCode.securityError.getCode()) { resp.setStatus(HttpServletResponse.SC_FORBIDDEN); } else if (error.getCode() == RpcErrorCode.applicationError.getCode()) { // Application error is considered another successful outcome } else if (error.getCode() == RpcErrorCode.invalidHttpMethodError.getCode()) { resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:de.tu_dortmund.ub.api.paaa.PaaaEndpoint.java
/** * @param httpServletRequest//from ww w.j a va2 s. com * @param httpServletResponse * @throws ServletException * @throws java.io.IOException */ protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { ObjectMapper mapper = new ObjectMapper(); this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "PathInfo = " + httpServletRequest.getPathInfo()); this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "QueryString = " + httpServletRequest.getQueryString()); String patronid = ""; String service = ""; String accept = ""; String authorization = ""; String format = "json"; String path = httpServletRequest.getPathInfo(); String[] params = path.substring(1, path.length()).split("/"); if (params.length == 1) { patronid = params[0]; service = "patron"; } else if (params.length == 2) { patronid = params[0]; service = params[1]; } if (patronid.equals("patronid")) { patronid = ""; } this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Patron: " + patronid); this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Service: " + service); if (httpServletRequest.getParameter("format") != null && !httpServletRequest.getParameter("format").equals("")) { format = httpServletRequest.getParameter("format"); } else { Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerNameKey = headerNames.nextElement(); if (headerNameKey.equals("Accept")) { this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey)); if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) { format = "html"; } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) { format = "xml"; } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) { format = "json"; } } } } this.logger.info("format = " + format); if (!format.equals("json") && !format.equals("xml")) { this.logger.error("[" + this.config.getProperty("service.name") + "] " + HttpServletResponse.SC_BAD_REQUEST + ": " + format + " not implemented!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError( this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST))); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description")); requestError.setErrorUri(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format); } else { // PAAA - function if (service.equals("signup") || service.equals("newpatron") || service.equals("updatepatron") || service.equals("blockpatron") || service.equals("unblockpatron") || service.equals("newfee")) { // get 'Accept' and 'Authorization' from Header; Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerNameKey = (String) headerNames.nextElement(); this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "headerNameKey = " + headerNameKey + " / headerNameValue = " + httpServletRequest.getHeader(headerNameKey)); if (headerNameKey.equals("Accept")) { accept = httpServletRequest.getHeader(headerNameKey); } if (headerNameKey.equals("Authorization")) { authorization = httpServletRequest.getHeader(headerNameKey); } } this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Accept: " + accept); this.logger.debug( "[" + this.config.getProperty("service.name") + "] " + "Authorization: " + authorization); // if not exists token: read request parameter if (authorization.equals("") && httpServletRequest.getParameter("access_token") != null && !httpServletRequest.getParameter("access_token").equals("")) { authorization = httpServletRequest.getParameter("access_token"); } // if not exists token if (authorization.equals("")) { // if exists PaiaService-Cookie: read content Cookie[] cookies = httpServletRequest.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("PaaaService")) { String value = URLDecoder.decode(cookie.getValue(), "UTF-8"); this.logger.info(value); LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class); // A C H T U N G: ggf. andere patronID im Cookie als in Request (UniAccount vs. BibAccount) if (loginResponse.getPatron().equals(patronid)) { authorization = loginResponse.getAccess_token(); } break; } } } } httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // check token ... boolean isAuthorized = false; if (!authorization.equals("")) { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); try { isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service, patronid, authorization); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_UNAUTHORIZED + "!"); } } else { // TODO correct error handling this.logger.error("[" + this.config.getProperty("service.name") + "] " + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": " + "Authorization Interface not implemented!"); } } this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: " + authorization + " - " + isAuthorized); // ... - if not is authorized - against DFN-AAI service if (!isAuthorized) { // TODO if exists OpenAM-Session-Cookie: read content this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: " + authorization + " - " + isAuthorized); } if (isAuthorized) { // execute query this.provideService(httpServletRequest, httpServletResponse, format, patronid, authorization, service); } else { // Authorization this.authorize(httpServletRequest, httpServletResponse, format); } } else { this.logger.error("[" + this.config.getProperty("service.name") + "] " + HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + "POST for '" + service + "' not allowed!"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\""); httpServletResponse.setContentType("application/json"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null && !httpServletRequest.getParameter("suppress_response_codes").equals("")) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED))); requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri")); StringWriter json = new StringWriter(); mapper.writeValue(json, requestError); this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json); // send response httpServletResponse.getWriter().println(json); } } }
From source file:org.dspace.app.dav.DAVBitstream.java
@Override protected int mkcolInternal(String waste) throws DAVStatusException, SQLException, AuthorizeException, IOException { throw new DAVStatusException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "MKCOL method not allowed for BitStream."); }
From source file:com.liferay.petra.json.web.service.client.BaseJSONWebServiceClientImpl.java
protected String execute(HttpRequestBase httpRequestBase) throws JSONWebServiceInvocationException, JSONWebServiceTransportException { signRequest(httpRequestBase);/*from w w w.j a v a2 s . co m*/ HttpHost httpHost = new HttpHost(_hostName, _hostPort, _protocol); try { if (_closeableHttpAsyncClient == null) { afterPropertiesSet(); } Future<HttpResponse> future = null; if (!isNull(_login) && !isNull(_password)) { HttpClientContext httpClientContext = HttpClientContext.create(); AuthCache authCache = new BasicAuthCache(); AuthScheme authScheme = null; if (!isNull(_proxyHostName)) { authScheme = new BasicScheme(ChallengeState.PROXY); } else { authScheme = new BasicScheme(ChallengeState.TARGET); } authCache.put(httpHost, authScheme); httpClientContext.setAttribute(ClientContext.AUTH_CACHE, authCache); future = _closeableHttpAsyncClient.execute(httpHost, httpRequestBase, httpClientContext, null); } else { future = _closeableHttpAsyncClient.execute(httpHost, httpRequestBase, null); } HttpResponse httpResponse = future.get(); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (_logger.isTraceEnabled()) { _logger.trace("Server returned status " + statusCode); } HttpEntity httpEntity = httpResponse.getEntity(); if ((statusCode == HttpServletResponse.SC_NO_CONTENT) || (((httpEntity == null) || (httpEntity.getContentLength() == 0)) && _isStatus2XX(statusCode))) { return null; } String content = EntityUtils.toString(httpEntity, _CHARSET); if ((httpEntity.getContentType() != null) && _isApplicationJSONContentType(httpEntity)) { content = updateJSON(content); } if (_isStatus2XX(statusCode)) { return content; } else if ((statusCode == HttpServletResponse.SC_BAD_REQUEST) || (statusCode == HttpServletResponse.SC_FORBIDDEN) || (statusCode == HttpServletResponse.SC_METHOD_NOT_ALLOWED) || (statusCode == HttpServletResponse.SC_NOT_ACCEPTABLE) || (statusCode == HttpServletResponse.SC_NOT_FOUND)) { throw new JSONWebServiceInvocationException(content, statusCode); } else if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) { throw new JSONWebServiceTransportException.AuthenticationFailure( "Not authorized to access JSON web service"); } throw new JSONWebServiceTransportException.CommunicationFailure("Server returned status " + statusCode, statusCode); } catch (ExecutionException ee) { throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ee); } catch (InterruptedException ie) { throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ie); } catch (IOException ioe) { throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ioe); } finally { httpRequestBase.releaseConnection(); } }
From source file:de.tu_dortmund.ub.api.paia.core.PaiaCoreEndpoint.java
/** * * @param httpServletRequest/*from w ww . jav a 2s. c om*/ * @param httpServletResponse * @throws ServletException * @throws IOException */ protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { ObjectMapper mapper = new ObjectMapper(); String format; String language; String redirect_url; this.logger.debug( "[" + config.getProperty("service.name") + "] " + "PathInfo = " + httpServletRequest.getPathInfo()); this.logger.debug("[" + config.getProperty("service.name") + "] " + "QueryString = " + httpServletRequest.getQueryString()); String patronid = ""; String service = ""; String accept = ""; String authorization = ""; String path = httpServletRequest.getPathInfo(); if (path != null) { String[] params = path.substring(1, path.length()).split("/"); if (params.length == 1) { patronid = params[0]; service = "patron"; } else if (params.length == 2) { patronid = params[0]; service = params[1]; } else if (params[1].equals("items") && params.length > 2) { patronid = params[0]; for (int i = 1; i < params.length; i++) { service += params[i]; if (i < params.length - 1) { service += "/"; } } } } if (patronid.equals("patronid")) { patronid = ""; } this.logger.debug("[" + config.getProperty("service.name") + "] " + "Service: " + service); this.logger.debug("[" + config.getProperty("service.name") + "] " + "Patron: " + patronid); format = "html"; if (httpServletRequest.getParameter("format") != null && !httpServletRequest.getParameter("format").equals("")) { format = httpServletRequest.getParameter("format"); } else { Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerNameKey = headerNames.nextElement(); if (headerNameKey.equals("Accept")) { this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey)); if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) { format = "html"; } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) { format = "xml"; } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) { format = "json"; } } } } this.logger.info("format = " + format); if (format.equals("html") && Lookup.lookupAll(ObjectToHtmlTransformation.class).size() == 0) { this.logger.error("[" + this.config.getProperty("service.name") + "] " + HttpServletResponse.SC_BAD_REQUEST + ": " + "html not implemented!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError( this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST))); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description")); requestError.setErrorUri(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, "", ""); } else { // read requestBody StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = httpServletRequest.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } String requestBody = jb.toString(); // read document list DocumentList documentList = null; try { // read DocumentList documentList = mapper.readValue(requestBody, DocumentList.class); } catch (Exception e) { if (!requestBody.equals("")) { String[] params = requestBody.split("&"); if (params.length > 1) { documentList = new DocumentList(); documentList.setDoc(new ArrayList<Document>()); for (String param : params) { if (param.startsWith("document_id")) { Document document = new Document(); document.setEdition(param.split("=")[1]); documentList.getDoc().add(document); } } } } else if (httpServletRequest.getParameter("document_id") != null && !httpServletRequest.getParameter("document_id").equals("")) { Document document = new Document(); document.setEdition(httpServletRequest.getParameter("document_id")); if (httpServletRequest.getParameter("storage_id") != null && !httpServletRequest.getParameter("storage_id").equals("")) { document.setStorage_id(httpServletRequest.getParameter("storage_id")); } documentList = new DocumentList(); documentList.setDoc(new ArrayList<Document>()); documentList.getDoc().add(document); } else { // if exists cookie with name "PaiaServiceDocumentList": read it Cookie[] cookies = httpServletRequest.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("PaiaServiceDocumentList")) { if (cookie.getValue() != null && !cookie.getValue().equals("") && !cookie.getValue().equals("null")) { String value = URLDecoder.decode(cookie.getValue(), "UTF-8"); this.logger.info(value); documentList = mapper.readValue(value, DocumentList.class); } break; } } } } } if (patronid.equals("")) { // Authorization this.authorize(httpServletRequest, httpServletResponse, format, documentList); } else { redirect_url = ""; if (httpServletRequest.getParameter("redirect_url") != null && !httpServletRequest.getParameter("redirect_url").equals("")) { redirect_url = httpServletRequest.getParameter("redirect_url"); } this.logger.info("redirect_url = " + redirect_url); language = ""; // PAIA core - function if ((httpServletRequest.getMethod().equals("GET") && (service.equals("patron") || service.equals("fullpatron") || service.equals("items") || service.startsWith("items/ordered") || service.startsWith("items/reserved") || service.startsWith("items/borrowed") || service.startsWith("items/borrowed/ill") || service.startsWith("items/borrowed/renewed") || service.startsWith("items/borrowed/recalled") || service.equals("fees") || service.equals("request"))) || (httpServletRequest.getMethod().equals("POST") && (service.equals("request") || service.equals("renew") || service.equals("cancel")))) { // get 'Accept' and 'Authorization' from Header Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerNameKey = (String) headerNames.nextElement(); this.logger.debug( "[" + config.getProperty("service.name") + "] " + "headerNameKey = " + headerNameKey + " / headerNameValue = " + httpServletRequest.getHeader(headerNameKey)); if (headerNameKey.equals("Accept-Language")) { language = httpServletRequest.getHeader(headerNameKey); this.logger.debug("[" + config.getProperty("service.name") + "] " + "Accept-Language: " + language); } if (headerNameKey.equals("Accept")) { accept = httpServletRequest.getHeader(headerNameKey); this.logger .debug("[" + config.getProperty("service.name") + "] " + "Accept: " + accept); } if (headerNameKey.equals("Authorization")) { authorization = httpServletRequest.getHeader(headerNameKey); } } // language if (language.startsWith("de")) { language = "de"; } else if (language.startsWith("en")) { language = "en"; } else if (httpServletRequest.getParameter("l") != null) { language = httpServletRequest.getParameter("l"); } else { language = "de"; } // if not exists token: read request parameter if ((authorization == null || authorization.equals("")) && httpServletRequest.getParameter("access_token") != null && !httpServletRequest.getParameter("access_token").equals("")) { authorization = httpServletRequest.getParameter("access_token"); } // if not exists token if (authorization == null || authorization.equals("")) { // if exists PaiaService-Cookie: read content Cookie[] cookies = httpServletRequest.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("PaiaService")) { String value = URLDecoder.decode(cookie.getValue(), "UTF-8"); this.logger.info(value); LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class); // A C H T U N G: ggf. andere patronID im Cookie als in Request (UniAccount vs. BibAccount) if (loginResponse.getPatron().equals(patronid)) { authorization = loginResponse.getAccess_token(); } break; } } // if not exists token - search for Shibboleth-Token if (authorization == null || authorization.equals("")) { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup .lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); try { authorization = authorizationInterface.getAuthCookies(cookies); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_UNAUTHORIZED + "!"); } this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: " + authorization); } } } } httpServletResponse.setHeader("Access-Control-Allow-Origin", config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control")); // check token ... boolean isAuthorized = false; if (authorization != null && !authorization.equals("")) { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup .lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); try { isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service, patronid, authorization); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_UNAUTHORIZED + "!"); } } else { // TODO correct error handling this.logger.error("[" + this.config.getProperty("service.name") + "] " + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": " + "Authorization Interface not implemented!"); } } this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: " + authorization + " - " + isAuthorized); if (isAuthorized) { // execute query this.provideService(httpServletRequest, httpServletResponse, patronid, service, format, language, redirect_url, documentList); } else { // Authorization this.authorize(httpServletRequest, httpServletResponse, format, documentList); } } else { this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + httpServletRequest.getMethod() + " for '" + service + "' not allowed!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED))); requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } } }
From source file:org.jitsi.videobridge.rest.HandlerImpl.java
/** * Handles an HTTP request for a COLIBRI-related resource (e.g. * <tt>Conference</tt>, <tt>Content</tt>, and <tt>Channel</tt>) represented * in JSON format.//from w w w . ja v a2 s . c o m * * @param target the target of the request * @param baseRequest the original unwrapped {@link Request} object * @param request the request either as the {@code Request} object or a * wrapper of that request * @param response the response either as the {@code Response} object or a * wrapper of that response * @throws IOException * @throws ServletException */ private void handleColibriJSON(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (target == null) { // TODO Auto-generated method stub } else if (target.startsWith(CONFERENCES)) { target = target.substring(CONFERENCES.length()); if (target.startsWith("/")) target = target.substring(1); String requestMethod = request.getMethod(); if ("".equals(target)) { if (GET_HTTP_METHOD.equals(requestMethod)) { // List the Conferences of Videobridge. doGetConferencesJSON(baseRequest, request, response); } else if (POST_HTTP_METHOD.equals(requestMethod)) { // Create a new Conference in Videobridge. doPostConferencesJSON(baseRequest, request, response); } else { response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else { // The target at this point of the execution is reduced to a // String which starts with a Conference ID. if (GET_HTTP_METHOD.equals(requestMethod)) { // Retrieve a representation of a Conference of Videobridge. doGetConferenceJSON(target, baseRequest, request, response); } else if (PATCH_HTTP_METHOD.equals(requestMethod)) { // Modify a Conference of Videobridge. doPatchConferenceJSON(target, baseRequest, request, response); } else { response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } } else if (target.equals(STATISTICS)) { if (GET_HTTP_METHOD.equals(request.getMethod())) { // Get the VideobridgeStatistics of Videobridge. doGetStatisticsJSON(baseRequest, request, response); } else { response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else if (target.equals(SHUTDOWN)) { if (!shutdownEnabled) { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } if (POST_HTTP_METHOD.equals(request.getMethod())) { // Get the VideobridgeStatistics of Videobridge. doPostShutdownJSON(baseRequest, request, response); } else { response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } }
From source file:org.structr.rest.servlet.JsonRestServlet.java
@Override protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // logRequest("TRACE", request); response.setContentType("application/json; charset=UTF-8;"); response.setCharacterEncoding("UTF-8"); int code = HttpServletResponse.SC_METHOD_NOT_ALLOWED; response.setStatus(code);//from w w w . ja v a 2s .c om response.getWriter().append(RestMethodResult.jsonError(code, "TRACE method not allowed")); }
From source file:de.tu_dortmund.ub.api.paaa.PaaaEndpoint.java
protected void doDelete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { ObjectMapper mapper = new ObjectMapper(); this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "PathInfo = " + httpServletRequest.getPathInfo()); this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "QueryString = " + httpServletRequest.getQueryString()); String patronid = ""; String service = ""; String accept = ""; String authorization = ""; String format = "json"; String path = httpServletRequest.getPathInfo(); String[] params = path.substring(1, path.length()).split("/"); if (params.length == 1) { patronid = params[0];// w w w . j a va 2s .co m service = "deletepatron"; } else if (params.length == 2) { patronid = params[0]; service = params[1]; } this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Patron: " + patronid); this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Service: " + service); if (httpServletRequest.getParameter("format") != null && !httpServletRequest.getParameter("format").equals("")) { format = httpServletRequest.getParameter("format"); } else { Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerNameKey = headerNames.nextElement(); if (headerNameKey.equals("Accept")) { this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey)); if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) { format = "html"; } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) { format = "xml"; } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) { format = "json"; } } } } this.logger.info("format = " + format); if (!format.equals("json") && !format.equals("xml")) { this.logger.error("[" + this.config.getProperty("service.name") + "] " + HttpServletResponse.SC_BAD_REQUEST + ": " + format + " not implemented!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError( this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST))); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description")); requestError.setErrorUri(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format); } else { // PAAA - function if (service.equals("deletepatron")) { // get 'Accept' and 'Authorization' from Header; Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerNameKey = (String) headerNames.nextElement(); this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "headerNameKey = " + headerNameKey + " / headerNameValue = " + httpServletRequest.getHeader(headerNameKey)); if (headerNameKey.equals("Accept")) { accept = httpServletRequest.getHeader(headerNameKey); } if (headerNameKey.equals("Authorization")) { authorization = httpServletRequest.getHeader(headerNameKey); } } this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Accept: " + accept); this.logger.debug( "[" + this.config.getProperty("service.name") + "] " + "Authorization: " + authorization); // if not exists token: read request parameter if (authorization.equals("") && httpServletRequest.getParameter("access_token") != null && !httpServletRequest.getParameter("access_token").equals("")) { authorization = httpServletRequest.getParameter("access_token"); } // if not exists token if (authorization.equals("")) { // if exists PaiaService-Cookie: read content Cookie[] cookies = httpServletRequest.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("PaaaService")) { String value = URLDecoder.decode(cookie.getValue(), "UTF-8"); this.logger.info(value); LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class); // A C H T U N G: ggf. andere patronID im Cookie als in Request (UniAccount vs. BibAccount) if (loginResponse.getPatron().equals(patronid)) { authorization = loginResponse.getAccess_token(); } break; } } } } httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // check token ... boolean isAuthorized = false; if (!authorization.equals("")) { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); try { isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service, patronid, authorization); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_UNAUTHORIZED + "!"); } } else { // TODO correct error handling this.logger.error("[" + this.config.getProperty("service.name") + "] " + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": " + "Authorization Interface not implemented!"); } } this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: " + authorization + " - " + isAuthorized); // ... - if not is authorized - against DFN-AAI service if (!isAuthorized) { // TODO if exists OpenAM-Session-Cookie: read content this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: " + authorization + " - " + isAuthorized); } if (isAuthorized) { // execute query this.provideService(httpServletRequest, httpServletResponse, format, patronid, authorization, service); } else { // Authorization this.authorize(httpServletRequest, httpServletResponse, format); } } else { this.logger.error("[" + this.config.getProperty("service.name") + "] " + HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + "DELETE for '" + service + "' not allowed!"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null && !httpServletRequest.getParameter("suppress_response_codes").equals("")) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED))); requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri")); StringWriter json = new StringWriter(); mapper.writeValue(json, requestError); this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json); // send response httpServletResponse.getWriter().println(json); } } }
From source file:edu.slu.action.ObjectAction.java
/** * Checks for appropriate RESTful method being used. * The action first comes to this function. It says what type of request it * is and checks the the method is appropriately RESTful. Returns false if not and * the method that calls this will handle a false response; * @param http_request the actual http request object * @param request_type a string denoting what type of request this should be * @return Boolean indicating RESTfulness * @throws Exception //from www . j a v a 2s. c om */ public Boolean methodApproval(HttpServletRequest http_request, String request_type) throws Exception { String requestMethod = http_request.getMethod(); String access_token = ""; boolean auth_verified = false; boolean restful = false; // FIXME @webanno if you notice, OPTIONS is not supported here and MUST be // for Web Annotation standards compliance. if (null != http_request.getHeader("Authorization") && !"".equals(http_request.getHeader("Authorization"))) { access_token = getTokenFromHeader(http_request.getHeader("Authorization")); } switch (request_type) { case "overwrite": auth_verified = verifyAccess(access_token); if (auth_verified) { if (requestMethod.equals("PUT")) { restful = true; } else { writeErrorResponse( "Improper request method for overwriting, please use PUT to overwrite this object.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else { if ("".equals(access_token)) { writeErrorResponse( "Improper or missing Authorization header provided on request. Required header must be 'Authorization: Bearer {token}'.", HttpServletResponse.SC_UNAUTHORIZED); } else { writeErrorResponse("Could not authorize you to perform this action. Have you registered at " + Constant.RERUM_PREFIX, HttpServletResponse.SC_UNAUTHORIZED); } } break; case "update": auth_verified = verifyAccess(access_token); if (auth_verified) { if (requestMethod.equals("PUT")) { restful = true; } else { writeErrorResponse( "Improper request method for updating, please use PUT to replace this object.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else { if ("".equals(access_token)) { writeErrorResponse( "Improper or missing Authorization header provided on request. Required header must be 'Authorization: Bearer {token}'.", HttpServletResponse.SC_UNAUTHORIZED); } else { writeErrorResponse("Could not authorize you to perform this action. Have you registered at " + Constant.RERUM_PREFIX, HttpServletResponse.SC_UNAUTHORIZED); } } break; case "patch": /** * Note that PATCH is not a standard method. Sometimes, programming languages don't have support for the method and * throw runtime errors, which forces people into using POST with a HTTP Method Override Header to say PATCH. * As a result, the API must support catching this header on these POST requests and allowing it to be treated * as PATCH throughout, which we can control here for patch, set and unset cases. */ auth_verified = verifyAccess(access_token); if (auth_verified) { if (requestMethod.equals("PATCH")) { restful = true; } else { String override = checkPatchOverrideSupport(http_request); if (override.equals("yes")) { restful = true; } else if (override.equals("no")) { writeErrorResponse( "Improper request method for updating, PATCH to remove keys from this RERUM object.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else if (override.equals("improper")) { //Error response returned by checkPatchOverrideSupport, don't double up and put one here } } } else { if ("".equals(access_token)) { writeErrorResponse( "Improper or missing Authorization header provided on request. Required header must be 'Authorization: Bearer {token}'.", HttpServletResponse.SC_UNAUTHORIZED); } else { writeErrorResponse("Could not authorize you to perform this action. Have you registered at " + Constant.RERUM_PREFIX, HttpServletResponse.SC_UNAUTHORIZED); } } break; case "set": auth_verified = verifyAccess(access_token); if (auth_verified) { if (requestMethod.equals("PATCH")) { restful = true; } else { String override = checkPatchOverrideSupport(http_request); if (override.equals("yes")) { restful = true; } else if (override.equals("no")) { writeErrorResponse( "Improper request method for updating, PATCH to remove keys from this RERUM object.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else if (override.equals("improper")) { //Error response returned by checkPatchOverrideSupport, don't double up and put one here } } } else { if ("".equals(access_token)) { writeErrorResponse( "Improper or missing Authorization header provided on request. Required header must be 'Authorization: Bearer {token}'.", HttpServletResponse.SC_UNAUTHORIZED); } else { writeErrorResponse("Could not authorize you to perform this action. Have you registered at " + Constant.RERUM_PREFIX, HttpServletResponse.SC_UNAUTHORIZED); } } break; case "unset": auth_verified = verifyAccess(access_token); if (auth_verified) { if (requestMethod.equals("PATCH")) { restful = true; } else { String override = checkPatchOverrideSupport(http_request); if (override.equals("yes")) { restful = true; } else if (override.equals("no")) { writeErrorResponse( "Improper request method for updating, PATCH to remove keys from this RERUM object.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else if (override.equals("improper")) { //Error response returned by checkPatchOverrideSupport, don't double up and put one here } } } else { if ("".equals(access_token)) { writeErrorResponse( "Improper or missing Authorization header provided on request. Required header must be 'Authorization: Bearer {token}'.", HttpServletResponse.SC_UNAUTHORIZED); } else { writeErrorResponse("Could not authorize you to perform this action. Have you registered at " + Constant.RERUM_PREFIX, HttpServletResponse.SC_UNAUTHORIZED); } } break; case "release": auth_verified = verifyAccess(access_token); if (auth_verified) { if (requestMethod.equals("PATCH")) { restful = true; } else { writeErrorResponse( "Improper request method for updating, please use PATCH to alter this RERUM object.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else { if ("".equals(access_token)) { writeErrorResponse( "Improper or missing Authorization header provided on request. Required header must be 'Authorization: Bearer {token}'.", HttpServletResponse.SC_UNAUTHORIZED); } else { writeErrorResponse("Could not authorize you to perform this action. Have you registered at " + Constant.RERUM_PREFIX, HttpServletResponse.SC_UNAUTHORIZED); } } break; case "create": auth_verified = verifyAccess(access_token); if (auth_verified) { if (requestMethod.equals("POST")) { restful = true; } else { writeErrorResponse("Improper request method for creating, please use POST.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else { if ("".equals(access_token)) { writeErrorResponse( "Improper or missing Authorization header provided on request. Required header must be 'Authorization: Bearer {token}'.", HttpServletResponse.SC_UNAUTHORIZED); } else { writeErrorResponse("Could not authorize you to perform this action. Have you registered at " + Constant.RERUM_PREFIX, HttpServletResponse.SC_UNAUTHORIZED); } } break; case "delete": System.out.println("Method delete detected"); auth_verified = verifyAccess(access_token); if (auth_verified) { if (requestMethod.equals("DELETE")) { restful = true; } else { writeErrorResponse("Improper request method for deleting, please use DELETE.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else { if ("".equals(access_token)) { writeErrorResponse( "Improper or missing Authorization header provided on request. Required header must be 'Authorization: Bearer {token}'.", HttpServletResponse.SC_UNAUTHORIZED); } else { writeErrorResponse("Could not authorize you to perform this action. Have you registered at " + Constant.RERUM_PREFIX, HttpServletResponse.SC_UNAUTHORIZED); } } break; case "get": auth_verified = true; if (requestMethod.equals("GET") || requestMethod.equals("HEAD")) { restful = true; } else { writeErrorResponse( "Improper request method for reading, please use GET or request for headers with HEAD.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } break; case "token": auth_verified = true; if (requestMethod.equals("POST")) { restful = true; } else { writeErrorResponse("Improper request method for the Auth0 proxy, please use POST.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } break; case "getProps": //This is a getByProperties request, so it acts like a GET, but has body like POST (and putting body in it forces POST method even when GET is set). auth_verified = true; if (requestMethod.equals("POST")) { restful = true; } else { writeErrorResponse( "Improper request method for requesting objects with matching properties. Use POST.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } break; default: writeErrorResponse("Improper request method for this type of request (unknown).", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } System.out.println(request_type + " approved? " + restful); return restful; }