/** Tests method getting/setting. */ public void testMethod() throws Exception { final Request request = getRequest(); request.setMethod(Method.GET); assertEquals(Method.GET, request.getMethod()); request.setMethod(Method.POST); assertEquals(Method.POST, request.getMethod()); }
/** * Handles a call for a local entity. By default, only GET and HEAD methods are implemented. * * @param request The request to handle. * @param response The response to update. * @param decodedPath The URL decoded entity path. */ @Override protected void handleLocal(Request request, Response response, String decodedPath) { int spi = decodedPath.indexOf("!/"); String fileUri; String entryName; if (spi != -1) { fileUri = decodedPath.substring(0, spi); entryName = decodedPath.substring(spi + 2); } else { fileUri = decodedPath; entryName = ""; } LocalReference fileRef = new LocalReference(fileUri); if (Protocol.FILE.equals(fileRef.getSchemeProtocol())) { final File file = fileRef.getFile(); if (Method.GET.equals(request.getMethod()) || Method.HEAD.equals(request.getMethod())) { handleGet(request, response, file, entryName, getMetadataService()); } else if (Method.PUT.equals(request.getMethod())) { handlePut(request, response, file, entryName); } else { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); response.getAllowedMethods().add(Method.GET); response.getAllowedMethods().add(Method.HEAD); response.getAllowedMethods().add(Method.PUT); } } else { response.setStatus(Status.SERVER_ERROR_NOT_IMPLEMENTED, "Only works on local files."); } }
@Override public void handle(Request request, Response response) { String dbName = (String) request.getAttributes().get("dbname"); String collection = (String) request.getAttributes().get("collection"); if (request.getMethod() == Method.POST) { try { String query = request.getEntityAsText(); System.out.println(query); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; Map<String, Object> map = null; try { map = om.readValue(query, typeRef); } catch (Exception e) { Logger.stderr(OBJECT_MAPPING_ERROR_MESSAGE + e); return; } ObjectMapper om = new ObjectMapper(); String r = null; try { r = om.writeValueAsString(map); } catch (IOException e) { e.printStackTrace(); } storageInstance.insert(dbName, collection, (Map<String, Object>) map); response.setEntity(r, MediaType.APPLICATION_JSON); } catch (StorageException e) { Logger.stderr(INSERTING_ERROR_MESSAGE + e); } } }
@Override protected int beforeHandle(Request request, Response response) { if (Method.OPTIONS.equals(request.getMethod())) { Series<Header> requestHeaders = (Series<Header>) request.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); String origin = requestHeaders.getFirstValue("Origin", false, "*"); String rh = requestHeaders.getFirstValue("Access-Control-Request-Headers", false, "*"); Series<Header> responseHeaders = (Series<Header>) response.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); if (responseHeaders == null) { responseHeaders = new Series<Header>(Header.class); } responseHeaders.add("Access-Control-Allow-Origin", origin); responseHeaders.set("Access-Control-Expose-Headers", "Authorization, Link"); responseHeaders.add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); responseHeaders.add("Access-Control-Allow-Headers", rh); responseHeaders.add("Access-Control-Allow-Credentials", "true"); responseHeaders.add("Access-Control-Max-Age", "60"); response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, responseHeaders); response.setEntity(new EmptyRepresentation()); return SKIP; } return super.beforeHandle(request, response); }
@Override public void handle(Request request, Response response) { if (request.getMethod() == Method.GET) { List<String> listDBs = null; String r = null; try { listDBs = storageInstance.retrieveDBs(); // Logger.stderr(listDBs.toString()); } catch (StorageException e) { e.printStackTrace(); } ObjectMapper om = new ObjectMapper(); try { r = om.writeValueAsString(listDBs); response.setEntity(r, MediaType.APPLICATION_JSON); } catch (Exception e) { Logger.stderr(OBJECT_MAPPING_ERROR_MESSAGE + e); return; } response.setEntity(r, MediaType.APPLICATION_JSON); } }
@Override protected int doHandle(Request request, Response response) { super.doHandle(request, response); if (response.getStatus().isSuccess() && request.getMethod().equals(Method.GET)) { boolean isHtml = false; for (Preference<MediaType> mt : request.getClientInfo().getAcceptedMediaTypes()) { if (mt.getMetadata().includes(MediaType.APPLICATION_XHTML) || mt.getMetadata().includes(MediaType.TEXT_HTML)) { isHtml = true; break; } } if (isHtml) { try { response.setEntity(toHtml(request, response)); } catch (SlipStreamException e) { // ok it failed generating html... do we care? } } } return CONTINUE; }
@Override protected int beforeHandle(Request request, Response response) { Cookie cookie = request.getCookies().getFirst("Credentials"); if (cookie != null) { // Extract the challenge response from the cookie String[] credentials = cookie.getValue().split("="); if (credentials.length == 2) { String identifier = credentials[0]; String secret = credentials[1]; request.setChallengeResponse( new ChallengeResponse(ChallengeScheme.HTTP_COOKIE, identifier, secret)); } } else if (Method.POST.equals(request.getMethod()) && request.getResourceRef().getQueryAsForm().getFirst("login") != null) { // Intercepting a login form Form credentials = new Form(request.getEntity()); String identifier = credentials.getFirstValue("identifier"); String secret = credentials.getFirstValue("secret"); request.setChallengeResponse( new ChallengeResponse(ChallengeScheme.HTTP_COOKIE, identifier, secret)); // Continue call processing to return the target representation if // authentication is successful or a new login page request.setMethod(Method.GET); } return super.beforeHandle(request, response); }
@Override public void handle(Request request, Response response) { String dbName = (String) request.getAttributes().get("dbname"); String collection = (String) request.getAttributes().get("collection"); if (request.getMethod() == Method.POST) { try { String query = request.getEntityAsText(); System.out.println(query); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; Map<String, Object> map = null; try { map = om.readValue(query, typeRef); } catch (Exception e) { Logger.stderr(OBJECT_MAPPING_ERROR_MESSAGE + e); return; } storageInstance.dropIndex(dbName, collection, map); response.setEntity(query, MediaType.APPLICATION_JSON); } catch (StorageException e) { Logger.stderr(DROP_INDEX_ERROR_MESSAGE + e); } } }
/** * Formats the response digest. * * @param challengeResponse The challenge response. * @param request The request if available. * @return The formatted secret of a challenge response. */ public char[] formatResponseDigest(ChallengeResponse challengeResponse, Request request) { String a1 = null; if (!Digest.ALGORITHM_HTTP_DIGEST.equals(challengeResponse.getSecretAlgorithm())) { if (!AuthenticatorUtils.anyNull( challengeResponse.getIdentifier(), challengeResponse.getSecret(), challengeResponse.getRealm())) { a1 = DigestUtils.toHttpDigest( challengeResponse.getIdentifier(), challengeResponse.getSecret(), challengeResponse.getRealm()); } } else { a1 = new String(challengeResponse.getSecret()); } if (a1 != null && !AuthenticatorUtils.anyNull(request.getMethod(), challengeResponse.getDigestRef())) { String a2 = DigestUtils.toMd5( request.getMethod().toString() + ":" + challengeResponse.getDigestRef().toString()); StringBuilder sb = new StringBuilder().append(a1).append(':').append(challengeResponse.getServerNonce()); if (!AuthenticatorUtils.anyNull( challengeResponse.getQuality(), challengeResponse.getClientNonce(), challengeResponse.getServerNounceCount())) { sb.append(':') .append(AuthenticatorUtils.formatNonceCount(challengeResponse.getServerNounceCount())) .append(':') .append(challengeResponse.getClientNonce()) .append(':') .append(challengeResponse.getQuality()); } sb.append(':').append(a2); return DigestUtils.toMd5(sb.toString()).toCharArray(); } return null; }
@Override public void handle(Request request, Response response) { super.handle(request, response); if (Method.GET.equals(request.getMethod())) { response.setEntity(getSwagger()); } else { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } }
@Override protected void writeStartLine() throws IOException { Request request = getMessage().getRequest(); getLineBuilder().append(request.getMethod().getName()); getLineBuilder().append(' '); getLineBuilder() .append(ReferenceUtils.format(request.getResourceRef(), getHelper().isProxying(), request)); getLineBuilder().append(' '); getLineBuilder().append(getVersion(request)); getLineBuilder().append("\r\n"); }
@Override public void init(Context context, Request request, Response response) { // System.out.println("init" + request + " " + response); // System.out.println("Content-Type: " + // request.getEntity().getMediaType()); if (request.getMethod().compareTo(Method.GET) == 0) { Representation entity = request.getEntity(); System.out.println( "Entity " + entity + " Content-Type: " + request.getEntity().getMediaType()); request.setEntity(new StringRepresentation("")); } super.init(context, request, response); }
@Override public void handle(Request request, Response response) { if (request.getMethod() == Method.GET) { String dbName = (String) request.getAttributes().get("dbname"); try { storageInstance.dropDB(dbName); // Logger.stderr(dbName + " db dropped."); } catch (StorageException e) { e.printStackTrace(); } String r = "{\"dropped dbName\" : \"" + dbName + "\"}"; response.setEntity(r, MediaType.APPLICATION_JSON); } }
@Override public void handle(Request request, Response response) { super.handle(request, response); try { if (request.getMethod().equals(Method.GET)) { try { if ("users".equalsIgnoreCase(request.getResourceRef().getLastSegment())) { UserListValue users = importer.users(); StringRepresentation result = new StringRepresentation( users.toJSON(), MediaType.APPLICATION_JSON, Language.DEFAULT, CharacterSet.UTF_8); response.setStatus(Status.SUCCESS_OK); response.setEntity(result); } else if ("groups".equalsIgnoreCase(request.getResourceRef().getLastSegment())) { GroupListValue groups = importer.groups(); StringRepresentation result = new StringRepresentation( groups.toJSON(), MediaType.APPLICATION_JSON, Language.DEFAULT, CharacterSet.UTF_8); response.setStatus(Status.SUCCESS_OK); response.setEntity(result); } } catch (ResourceException e) { response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); response.setEntity(e.getStatus().getDescription(), MediaType.TEXT_PLAIN); } } else { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } } finally { request.release(); } }
@Override public void handle(Request request, Response response) { String dbName = (String) request.getAttributes().get("dbname"); String collection = (String) request.getAttributes().get("collection"); if (request.getMethod() == Method.GET) { try { List<Map<String, Object>> list = storageInstance.getIndex(dbName, collection); ObjectMapper om = new ObjectMapper(); String r = null; try { r = om.writeValueAsString(list); } catch (IOException e) { e.printStackTrace(); } response.setEntity(r, MediaType.APPLICATION_JSON); } catch (StorageException e) { Logger.stderr(GET_INDEX_ERROR_MESSAGE + e); } } }
@Override public void handle(Request request, Response response) { String dbName = (String) request.getAttributes().get("dbname"); String collection = (String) request.getAttributes().get("collection"); if (request.getMethod() == Method.POST) { try { String text = request.getEntityAsText(); System.out.println(text); TypeReference<List<Map<String, Object>>> typeRef = new TypeReference<List<Map<String, Object>>>() {}; List<Map<String, Object>> list = null; Map<String, Object> key = null; Map<String, Object> query = null; try { list = om.readValue(text, typeRef); if (list.size() != 2) { Logger.stderr(TYPE_ERROR_MESSAGE); return; } key = list.get(0); query = list.get(1); } catch (Exception e) { Logger.stderr(OBJECT_MAPPING_ERROR_MESSAGE + e); return; } storageInstance.update(dbName, collection, key, query); response.setEntity(text, MediaType.APPLICATION_JSON); } catch (StorageException e) { e.printStackTrace(); } } }
/** * Handle the call and follow redirection for safe methods. * * @param request The request to send. * @param response The response to update. * @param references The references that caused a redirection to prevent infinite loops. * @param retryAttempt The number of remaining attempts. * @param next The next handler handling the call. */ private void handle( Request request, Response response, List<Reference> references, int retryAttempt, Uniform next) { if (next != null) { // Actually handle the call next.handle(request, response); // Check for redirections if (isFollowingRedirects() && response.getStatus().isRedirection() && (response.getLocationRef() != null)) { boolean doRedirection = false; if (request.getMethod().isSafe()) { doRedirection = true; } else { if (Status.REDIRECTION_SEE_OTHER.equals(response.getStatus())) { // The user agent is redirected using the GET method request.setMethod(Method.GET); request.setEntity(null); doRedirection = true; } else if (Status.REDIRECTION_USE_PROXY.equals(response.getStatus())) { doRedirection = true; } } if (doRedirection) { Reference newTargetRef = response.getLocationRef(); if ((references != null) && references.contains(newTargetRef)) { getLogger().warning("Infinite redirection loop detected with URI: " + newTargetRef); } else if (request.getEntity() != null && !request.isEntityAvailable()) { getLogger() .warning( "Unable to follow the redirection because the request entity isn't available anymore."); } else { if (references == null) { references = new ArrayList<Reference>(); } // Add to the list of redirection reference // to prevent infinite loops references.add(request.getResourceRef()); request.setResourceRef(newTargetRef); handle(request, response, references, 0, next); } } } else if (isRetryOnError() && response.getStatus().isRecoverableError() && request.getMethod().isIdempotent() && (retryAttempt < getRetryAttempts()) && ((request.getEntity() == null) || request.getEntity().isAvailable())) { getLogger() .log( Level.INFO, "A recoverable error was detected (" + response.getStatus().getCode() + "), attempting again in " + getRetryDelay() + " ms."); // Wait before attempting again if (getRetryDelay() > 0) { try { Thread.sleep(getRetryDelay()); } catch (InterruptedException e) { getLogger().log(Level.FINE, "Retry delay sleep was interrupted", e); } } // Retry the call handle(request, response, references, ++retryAttempt, next); } } }
/** * Handles a call. * * @param request The request to handle. * @param response The response to update. */ @Override public void handle(Request request, Response response) { Connection connection = null; if (request.getMethod().equals(Method.POST)) { try { // Parse the JDBC URI String connectionURI = request.getResourceRef().toString(); // Parse the request to extract necessary info DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document requestDoc = docBuilder.parse(new InputSource(request.getEntity().getReader())); Element rootElt = (Element) requestDoc.getElementsByTagName("request").item(0); Element headerElt = (Element) rootElt.getElementsByTagName("header").item(0); Element connectionElt = (Element) headerElt.getElementsByTagName("connection").item(0); // Read the connection pooling setting Node usePoolingNode = connectionElt.getElementsByTagName("usePooling").item(0); boolean usePooling = usePoolingNode.getTextContent().equals("true") ? true : false; // Read the paging setting Node startNode = headerElt.getElementsByTagName("start").item(0); int start = startNode != null && startNode.getTextContent().trim().length() > 0 ? Integer.parseInt(startNode.getTextContent()) : 0; Node limitNode = headerElt.getElementsByTagName("limit").item(0); int limit = limitNode != null && limitNode.getTextContent().trim().length() > 0 ? Integer.parseInt(limitNode.getTextContent()) : -1; // Read the connection properties NodeList propertyNodes = connectionElt.getElementsByTagName("property"); Node propertyNode = null; Properties properties = null; String name = null; String value = null; for (int i = 0; i < propertyNodes.getLength(); i++) { propertyNode = propertyNodes.item(i); if (properties == null) { properties = new Properties(); } name = propertyNode.getAttributes().getNamedItem("name").getTextContent(); value = propertyNode.getTextContent(); properties.setProperty(name, value); } Node returnGeneratedKeysNode = headerElt.getElementsByTagName("returnGeneratedKeys").item(0); boolean returnGeneratedKeys = returnGeneratedKeysNode.getTextContent().equals("true") ? true : false; // Read the SQL body and get the list of sql statements Element bodyElt = (Element) rootElt.getElementsByTagName("body").item(0); NodeList statementNodes = bodyElt.getElementsByTagName("statement"); List<String> sqlRequests = new ArrayList<String>(); for (int i = 0; i < statementNodes.getLength(); i++) { String sqlRequest = statementNodes.item(i).getTextContent(); sqlRequests.add(sqlRequest); } // Execute the List of SQL requests connection = getConnection(connectionURI, properties, usePooling); JdbcResult result = handleSqlRequests(connection, returnGeneratedKeys, sqlRequests); response.setEntity(new RowSetRepresentation(result, start, limit)); } catch (SQLException se) { getLogger().log(Level.WARNING, "Error while processing the SQL request", se); response.setStatus(Status.SERVER_ERROR_INTERNAL, se); } catch (ParserConfigurationException pce) { getLogger().log(Level.WARNING, "Error with XML parser configuration", pce); response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, pce); } catch (SAXException se) { getLogger().log(Level.WARNING, "Error while parsing the XML document", se); response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, se); } catch (IOException ioe) { getLogger().log(Level.WARNING, "Input/Output exception", ioe); response.setStatus(Status.SERVER_ERROR_INTERNAL, ioe); } } else { throw new IllegalArgumentException("Only the POST method is supported"); } }
/** * ShareResource * * @param context * @param request * @param response * @throws UnsupportedEncodingException */ @Override public void doInit() { Request request = this.getRequest(); Map<String, Object> attributes = request.getAttributes(); urlStr = request.getResourceRef().toString(); // Every user must pass in their cookies cookie = request.getCookies().getFirstValue("infinitecookie", true); // Method.POST if (request.getMethod() == Method.POST) { if (RESTTools.decodeRESTParam("id", attributes) != null) id = RESTTools.decodeRESTParam("id", attributes); if (RESTTools.decodeRESTParam("type", attributes) != null) type = RESTTools.decodeRESTParam("type", attributes); if (RESTTools.decodeRESTParam("title", attributes) != null) title = RESTTools.decodeRESTParam("title", attributes); if (RESTTools.decodeRESTParam("description", attributes) != null) description = RESTTools.decodeRESTParam("description", attributes); } // Method.GET if (request.getMethod() == Method.GET) { // Method.GET Map<String, String> queryOptions = this.getQuery().getValuesMap(); // Query String Values if (queryOptions.get("id") != null) id = queryOptions.get("id"); if (queryOptions.get("skip") != null) skip = queryOptions.get("skip"); if (queryOptions.get("limit") != null) limit = queryOptions.get("limit"); if (queryOptions.get("searchby") != null) searchby = queryOptions.get("searchby"); if (queryOptions.get("json") != null) json = queryOptions.get("json"); if (queryOptions.get("type") != null) type = queryOptions.get("type"); if ((queryOptions.get("ignoreAdmin") != null) && (queryOptions.get("ignoreAdmin").equalsIgnoreCase("true"))) { ignoreAdmin = true; } if ((queryOptions.get("nocontent") != null) && (queryOptions.get("nocontent").equalsIgnoreCase("true"))) { returnContent = false; } if ((queryOptions.get("nometa") != null) && (queryOptions.get("nometa").equalsIgnoreCase("true"))) { jsonOnly = true; } // Get Share by ID if (urlStr.contains("/share/get/")) { shareId = RESTTools.decodeRESTParam("id", attributes); action = "getShare"; } // Search Shares by Owner, Community, Type else if (urlStr.contains("/share/search")) { action = "searchShares"; } // Save a JSON share object to the DB // /social/share/save/json/{id}/{type}/{title}/{description}/?json={...} else if (urlStr.contains("/share/save/json/") || urlStr.contains("/share/add/json/") || urlStr.contains("/share/update/json/")) { if (RESTTools.decodeRESTParam("id", attributes) != null) id = RESTTools.decodeRESTParam("id", attributes); type = RESTTools.decodeRESTParam("type", attributes); title = RESTTools.decodeRESTParam("title", attributes); description = RESTTools.decodeRESTParam("description", attributes); // Use URLDecoder on the json string try { json = URLDecoder.decode(json, "UTF-8"); action = "saveJson"; } catch (UnsupportedEncodingException e) { // TODO can't throw exceptions // set to failed so it doesn't run // throw e; action = "failed"; } } else if (urlStr.contains("/share/add/binary/")) { action = "addBinaryGET"; } else if (urlStr.contains("/share/update/binary/")) { action = "updateBinaryGET"; } // Add a Ref (Pointer to a record within a collection) else if (urlStr.contains("/share/add/ref/")) { type = RESTTools.decodeRESTParam("type", attributes); documentId = RESTTools.decodeRESTParam("documentid", attributes); title = RESTTools.decodeRESTParam("title", attributes); description = RESTTools.decodeRESTParam("description", attributes); action = "addRef"; } // Add a Ref (Pointer to a record within a collection) else if (urlStr.contains("/share/update/ref/")) { id = RESTTools.decodeRESTParam("id", attributes); type = RESTTools.decodeRESTParam("type", attributes); documentId = RESTTools.decodeRESTParam("documentid", attributes); title = RESTTools.decodeRESTParam("title", attributes); description = RESTTools.decodeRESTParam("description", attributes); action = "updateRef"; } // Share - Remove a community from a share else if (urlStr.contains("/share/remove/community/")) { shareId = RESTTools.decodeRESTParam("shareid", attributes); communityId = RESTTools.decodeRESTParam("communityid", attributes); action = "removeCommunity"; } // Remove share else if (urlStr.contains("/share/remove/")) { shareId = RESTTools.decodeRESTParam("shareid", attributes); action = "removeShare"; } // Endorse share else if (urlStr.contains("/share/endorse/")) { shareId = RESTTools.decodeRESTParam("shareid", attributes); communityId = RESTTools.decodeRESTParam("communityid", attributes); isEndorsed = Boolean.parseBoolean(RESTTools.decodeRESTParam("isendorsed", attributes)); action = "endorseShare"; } // Share - Add a community so that members can view the share else if (urlStr.contains("/share/add/community/")) { shareId = RESTTools.decodeRESTParam("shareid", attributes); communityId = RESTTools.decodeRESTParam("communityid", attributes); comment = RESTTools.decodeRESTParam("comment", attributes); action = "addCommunity"; } } }