/** * Handles a GET call. * * @param request The request to answer. * @param response The response to update. * @param file The Zip archive file. * @param entryName The Zip archive entry name. * @param metadataService The metadata service. */ protected void handleGet( Request request, Response response, File file, String entryName, final MetadataService metadataService) { if (!file.exists()) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { ZipFile zipFile; try { zipFile = new ZipFile(file); } catch (Exception e) { response.setStatus(Status.SERVER_ERROR_INTERNAL, e); return; } Entity entity = new ZipEntryEntity(zipFile, entryName, metadataService); if (!entity.exists()) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { final Representation output; if (entity.isDirectory()) { // Return the directory listing final Collection<Entity> children = entity.getChildren(); final ReferenceList rl = new ReferenceList(children.size()); String fileUri = LocalReference.createFileReference(file).toString(); String scheme = request.getResourceRef().getScheme(); String baseUri = scheme + ":" + fileUri + "!/"; for (final Entity entry : children) { rl.add(baseUri + entry.getName()); } output = rl.getTextRepresentation(); try { zipFile.close(); } catch (IOException e) { // Do something ??? } } else { // Return the file content output = entity.getRepresentation(metadataService.getDefaultMediaType(), getTimeToLive()); output.setLocationRef(request.getResourceRef()); Entity.updateMetadata(entity.getName(), output, true, getMetadataService()); } response.setStatus(Status.SUCCESS_OK); response.setEntity(output); } } }
/** Tests resource reference getting/setting. */ public void testResourceRef() throws Exception { final Request request = getRequest(); String uri = "http://www.restlet.org/"; Reference reference = getReference(uri); request.setResourceRef(uri); assertEquals(reference, request.getResourceRef()); uri = "http://www.restlet.org/something"; reference = getReference(uri); request.setResourceRef(reference); assertEquals(reference, request.getResourceRef()); }
@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); }
@Before public void setUp() throws Exception { contactsRepository = ContactsRepository.getInstance(); contactsRepository.setDbService(dbService); attributes = new ConcurrentHashMap<String, Object>(); Subject subjectUnderTest = Mockito.mock(Subject.class); setSubject(subjectUnderTest); request = Mockito.mock(Request.class); Mockito.when(request.getClientInfo()).thenReturn(new ClientInfo()); Mockito.when(request.getAttributes()).thenReturn(attributes); Reference targetRef = Mockito.mock(Reference.class); Reference resourceRef = Mockito.mock(Reference.class); Mockito.when(request.getResourceRef()).thenReturn(resourceRef); Mockito.when(resourceRef.getTargetRef()).thenReturn(targetRef); response = new Response(request); ValidatorService validatorService = Mockito.mock(ValidatorService.class); Validator validator = Mockito.mock(Validator.class); Mockito.when(validatorService.getValidator()).thenReturn(validator); Mockito.when(clipboardApplication.getValidatorService()).thenReturn(validatorService); RouteBuilder routeBuilder = Mockito.mock(RouteBuilder.class); Mockito.when(clipboardApplication.getRouteBuilders(Mockito.any())) .thenReturn(Arrays.asList(routeBuilder)); }
@Override public void formatResponse( ChallengeWriter cw, ChallengeResponse challenge, Request request, Series<Header> httpHeaders) { if (challenge.getIdentifier() != null) { cw.appendQuotedChallengeParameter("username", challenge.getIdentifier()); } if (challenge.getRealm() != null) { cw.appendQuotedChallengeParameter("realm", challenge.getRealm()); } if (challenge.getServerNonce() != null) { cw.appendQuotedChallengeParameter("nonce", challenge.getServerNonce()); } if (challenge.getDigestRef() != null) { challenge.setDigestRef(new Reference(request.getResourceRef().getPath())); cw.appendQuotedChallengeParameter("uri", challenge.getDigestRef().toString()); } char[] responseDigest = formatResponseDigest(challenge, request); if (responseDigest != null) { cw.appendQuotedChallengeParameter("response", new String(responseDigest)); } if ((challenge.getDigestAlgorithm() != null) && !Digest.ALGORITHM_MD5.equals(challenge.getDigestAlgorithm())) { cw.appendChallengeParameter("algorithm", challenge.getDigestAlgorithm()); } if (challenge.getClientNonce() != null) { cw.appendQuotedChallengeParameter("cnonce", challenge.getClientNonce()); } if (challenge.getOpaque() != null) { cw.appendQuotedChallengeParameter("opaque", challenge.getOpaque()); } if (challenge.getQuality() != null) { cw.appendChallengeParameter("qop", challenge.getQuality()); } if ((challenge.getQuality() != null) && (challenge.getServerNounceCount() > 0)) { cw.appendChallengeParameter("nc", challenge.getServerNounceCountAsHex()); } for (Parameter param : challenge.getParameters()) { if (HeaderUtils.isToken(param.getValue())) { cw.appendChallengeParameter(param); } else { cw.appendQuotedChallengeParameter(param); } } }
@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 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(); } }
private String extractTokenFromRequest(Request request) { String token = null; if (request != null) { log.debug(request); if (request.getResourceRef() != null && request.getResourceRef().getQueryAsForm() != null) { token = request.getResourceRef().getQueryAsForm().getFirstValue("token"); log.trace("Found token from query string: " + token); } else { log.info("ResourceRef is null"); } for (Cookie cookie : request.getCookies()) { log.trace(cookie.getName() + " - " + cookie.getValue()); if (RestAuthenticationService.ES_DMS_TICKET.equals(cookie.getName())) { token = cookie.getValue(); log.trace("Found token from cookie: " + token); break; } } } return token; }
/** * Returns the target reference to redirect to by automatically resolving URI template variables * found using the {@link Template} class using the request and response as data models. * * @param request The request to handle. * @param response The response to update. * @return The target reference to redirect to. */ protected Reference getTargetRef(Request request, Response response) { // Create the template Template rt = new Template(this.targetTemplate); rt.setLogger(getLogger()); // Return the formatted target URI if (new Reference(this.targetTemplate).isRelative()) { // Be sure to keep the resource's base reference. return new Reference(request.getResourceRef(), rt.format(request, response)); } return new Reference(rt.format(request, response)); }
@Post("application/x-www-form-urlencoded|multipart/form-data") public Representation postWebFormMedia(Representation entity) { setServerHeader(); Request request = getRequest(); // The HTTP API sets the headers // addCORSHeaders(request); String auth = getQueryValue(Constants.AUTH_QUERY); String userId = null; String token = null; try { userId = getUserId(request, auth); token = getTransactionId(request, auth); } catch (Throwable t) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return new StringRepresentation(t.getLocalizedMessage(), MediaType.APPLICATION_JSON); } Representation checkRequest = checkRequest(userId, token, request.getResourceRef().getIdentifier()); if (checkRequest != null) { return checkRequest; } MediaDAO mediaDAO = DAOFactory.getInstance().getDAO(); String entityId = (String) request.getAttributes().get(Constants.ENTITY_ARG); String result = ""; try { if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { result = mediaDAO.insertFormDataMedia(userId, entityId, getRequest(), false); } else { result = mediaDAO.insertWebFormMedia(userId, entityId, new Form(entity), false); } setStatus(Status.SUCCESS_CREATED); } catch (FileUploadException e) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } catch (UserNotAllowedException e) { setStatus(Status.CLIENT_ERROR_FORBIDDEN); } catch (Throwable t) { return unexpectedError(t); } return new StringRepresentation(result, MediaType.APPLICATION_JSON); }
/** * Redirects a given call to a target reference. In the default implementation, the request HTTP * headers, stored in the request's attributes, are removed before dispatching. After dispatching, * the response HTTP headers are also removed to prevent conflicts with the main call. * * @param targetRef The target reference with URI variables resolved. * @param request The request to handle. * @param response The response to update. */ protected void outboundServerRedirect(Reference targetRef, Request request, Response response) { Restlet next = (getApplication() == null) ? null : getApplication().getOutboundRoot(); if (next == null) { next = getContext().getClientDispatcher(); } serverRedirect(next, targetRef, request, response); if (response.getEntity() != null && !request.getResourceRef().getScheme().equalsIgnoreCase(targetRef.getScheme())) { // Distinct protocol, this data cannot be exposed. response.getEntity().setLocationRef((Reference) null); } }
@Override public FilterResult doHandle(R resource, Request request, ResponseWrapper<T> response) { logger.debug("entering {}#doHandle", this.getClass().getSimpleName()); if (request == null || request.getResourceRef() == null) { response.setSkysailResponse(new FailureResponse<T>("request or resource reference was null")); return FilterResult.STOP; } Form form = (Form) request.getAttributes().get(EntityServerResource.SKYSAIL_SERVER_RESTLET_FORM); T data = (T) resource.getData(form); response.getSkysailResponse().setMessage(resource.getMessage("tobedone")); response.getSkysailResponse().setData(data); super.doHandle(resource, request, response); return FilterResult.CONTINUE; }
/** Tests context's base reference getting/setting. */ public void testBaseRef() throws Exception { final Request request = getRequest(); final String resourceRefURI = "http://www.restlet.org/path/to/resource"; final Reference resourceRef = getReference(resourceRefURI); request.setResourceRef(resourceRefURI); assertEquals(resourceRef, request.getResourceRef()); String uri = "http://www.restlet.org/path"; Reference reference = getReference(uri); request.getResourceRef().setBaseRef(uri); assertEquals(uri, request.getResourceRef().getBaseRef().toString()); assertEquals(reference, request.getResourceRef().getBaseRef()); uri = "http://www.restlet.org/path/to"; reference = getReference(uri); request.getResourceRef().setBaseRef(uri); assertEquals(uri, request.getResourceRef().getBaseRef().toString()); assertEquals(reference, request.getResourceRef().getBaseRef()); }
@Override public void handle(Request request, Response response) { Form form = request.getResourceRef().getQueryAsForm(); List<Range> ranges = request.getRanges(); boolean match = false; for (Parameter parameter : form) { long index = 0; long length = 0; String value = parameter.getValue(); if (value.startsWith("-")) { index = Range.INDEX_LAST; length = Long.parseLong(value.substring(1)); } else if (value.endsWith("-")) { index = Long.parseLong(value.substring(0, value.length() - 1)); length = Range.SIZE_MAX; } else { String[] tab = value.split("-"); if (tab.length == 2) { index = Long.parseLong(tab[0]); length = Long.parseLong(tab[1]) - index; } } boolean found = false; for (Range range : ranges) { found = (index == range.getIndex()) && (length == range.getSize()); if (found) { break; } } if (!found) { break; } match = true; } if (match) { response.setStatus(Status.SUCCESS_OK); response.setEntity(str1000, MediaType.TEXT_PLAIN); } else { response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } }
@Override public void formatResponse( ChallengeWriter cw, ChallengeResponse challenge, Request request, Series<Header> httpHeaders) { // Setup the Date header String date = ""; if (httpHeaders.getFirstValue("x-ms-date", true) == null) { // X-ms-Date header didn't override the standard Date header date = httpHeaders.getFirstValue(HeaderConstants.HEADER_DATE, true); if (date == null) { // Add a fresh Date header date = DateUtils.format(new Date(), DateUtils.FORMAT_RFC_1123.get(0)); httpHeaders.add(HeaderConstants.HEADER_DATE, date); } } else { date = httpHeaders.getFirstValue("x-ms-date", true); } // Setup the canonicalized path String canonicalizedResource = getCanonicalizedResourceName(request.getResourceRef()); // Setup the message part StringBuilder rest = new StringBuilder(); rest.append(date) .append('\n') .append('/') .append(challenge.getIdentifier()) .append(canonicalizedResource); // Append the SharedKey credentials cw.append(challenge.getIdentifier()) .append(':') .append( Base64.encode( DigestUtils.toHMacSha256(rest.toString(), Base64.decode(challenge.getSecret())), true)); }
/** * Redirects a given call on the server-side to a next Restlet with a given target reference. In * the default implementation, the request HTTP headers, stored in the request's attributes, are * removed before dispatching. After dispatching, the response HTTP headers are also removed to * prevent conflicts with the main call. * * @param next The next Restlet to forward the call to. * @param targetRef The target reference with URI variables resolved. * @param request The request to handle. * @param response The response to update. */ protected void serverRedirect( Restlet next, Reference targetRef, Request request, Response response) { if (next == null) { getLogger().warning("No next Restlet provided for server redirection to " + targetRef); } else { // Save the base URI if it exists as we might need it for // redirections Reference resourceRef = request.getResourceRef(); Reference baseRef = resourceRef.getBaseRef(); // Reset the protocol and let the dispatcher handle the protocol request.setProtocol(null); // Update the request to cleanly go to the target URI request.setResourceRef(targetRef); request.getAttributes().remove(HeaderConstants.ATTRIBUTE_HEADERS); next.handle(request, response); // Allow for response rewriting and clean the headers response.setEntity(rewrite(response.getEntity())); response.getAttributes().remove(HeaderConstants.ATTRIBUTE_HEADERS); request.setResourceRef(resourceRef); // In case of redirection, we may have to rewrite the redirect URI if (response.getLocationRef() != null) { Template rt = new Template(this.targetTemplate); rt.setLogger(getLogger()); int matched = rt.parse(response.getLocationRef().toString(), request); if (matched > 0) { String remainingPart = (String) request.getAttributes().get("rr"); if (remainingPart != null) { response.setLocationRef(baseRef.toString() + remainingPart); } } } } }
/** * Decodes form parameters that are sent double encoded by performing one decode step on their * values, if their restlet framework decoded value starts with an "%". * * @param request a restlet request * @throws IOException did not occur during tests but may. * @throws IllegalArgumentException if an Encode representation is received. */ void decodeFormParamsIfDoubleEncoded(Request request) throws IOException { Representation r = request.getEntity(); if (r instanceof EncodeRepresentation) throw new IllegalArgumentException( "Received an Encode representation." + " This filter must be after the Encoder filter. please check your filter chain order."); if (!(r instanceof EmptyRepresentation)) { ContentType c = new ContentType(r); if (MediaType.APPLICATION_WWW_FORM.equals(c.getMediaType(), true)) { Form form = new Form(r); Form newform = new Form(r); Map<String, String> valuesMap = form.getValuesMap(); for (Map.Entry<String, String> e : valuesMap.entrySet()) { if (DBG) ThreadLocalStopwatch.now("" + e.getKey() + " - " + e.getValue()); String shouldBeDecodedValue = e.getValue(); if (shouldBeDecodedValue.startsWith("%")) { shouldBeDecodedValue = URLDecoder.decode(e.getValue(), DECODER_CHAR_SET); totalDecodings.incrementAndGet(); if (DBG) { ThreadLocalStopwatch.now("DECODED " + request.getResourceRef()); ThreadLocalStopwatch.now( "DECODED " + totalDecodings.get() + " : " + e.getKey() + " - " + shouldBeDecodedValue); } } newform.add(e.getKey(), shouldBeDecodedValue); } // we must always set the entity, because above getEntitiy call causes // NPEs later if repeated by the framework. request.setEntity(newform.encode(), c.getMediaType()); } } }
/** * 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"); } }
@Override public List<Predicat> createPredicats(Request request, List<Predicat> predicats) throws Exception { // Get the dataset DataSetApplication dsApplication = null; DataSet ds = null; boolean isConcept = true; Form params = request.getResourceRef().getQueryAsForm(); boolean filterExists = true; int i = 0; // Build predicat for filters param while (filterExists) { // first check if the filter is applied on a Concept or not String index = TEMPLATE_PARAM_CONCEPT.replace("#", Integer.toString(i)); String formParam = params.getFirstValue(index); if (formParam == null) { isConcept = false; index = TEMPLATE_PARAM.replace("#", Integer.toString(i)); formParam = params.getFirstValue(index); } i++; if (formParam != null) { String[] parameters = formParam.split("\\|"); TYPE_COMPONENT[] types = TYPE_COMPONENT.values(); Boolean trouve = false; for (TYPE_COMPONENT typeCmp : types) { if (typeCmp.name().equals(parameters[TYPE])) { trouve = true; } } if (trouve) { if (dsApplication == null) { dsApplication = (DataSetApplication) getContext().getAttributes().get("DataSetApplication"); ds = dsApplication.getDataSet(); } String columnAlias = null; if (parameters.length >= VALUES) { /* * columnsAlias = parameters[COLUMN].split(","); ArrayList<Column> columns = new ArrayList<Column>(); for * (String columnAlias : columnsAlias) { Column col = ds.findByColumnAlias(columnAlias); if (col != null) { * columns.add(col); } * * } */ columnAlias = getColumnAlias(isConcept, parameters, dsApplication); if (columnAlias != null) { Column col = ds.findByColumnAlias(columnAlias); if (col != null && col.getFilter() != null && col.getFilter() && checkValues(parameters, col)) { Predicat predicat = new Predicat(); predicat.setLeftAttribute(col); predicat.setNbOpenedParanthesis(1); predicat.setNbClosedParanthesis(0); predicat.setCompareOperator(Operator.GTE); predicat.setRightValue(numericBetween.getFrom()); predicats.add(predicat); predicat = new Predicat(); predicat.setLeftAttribute(col); predicat.setNbOpenedParanthesis(0); predicat.setNbClosedParanthesis(1); predicat.setCompareOperator(Operator.LTE); predicat.setRightValue(numericBetween.getTo()); predicats.add(predicat); } } } } } else { filterExists = false; } } return predicats; }
/** * 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"; } } }
/** * Tests partial Put requests. * * @throws Exception */ public void testPut() throws Exception { if (!SystemUtils.isWindows()) { Request request; Response response; BioUtils.delete(testDir, true); Client client = new Client(new Context(), Protocol.HTTP); client.getContext().getParameters().add("tracing", "true"); // PUT on a file that does not exist request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt"); request.setEntity(new StringRepresentation("1234567890")); request.setRanges(Arrays.asList(new Range(0, 10))); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = client.handle(new Request(Method.GET, request.getResourceRef())); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("1234567890", response.getEntity().getText()); // Partial PUT on a file, the provided representation overflowed the // existing file request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt"); request.setEntity(new StringRepresentation("0000000000")); request.setRanges(Arrays.asList(new Range(1, 10))); response = client.handle(request); System.out.println(response.getStatus() + " / " + response.getStatus().getThrowable()); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = client.handle(new Request(Method.GET, request.getResourceRef())); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("10000000000", response.getEntity().getText()); // Partial PUT on a file that does not exists, the provided range // does not start at the 0 index. request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai2.txt"); request.setEntity(new StringRepresentation("0000000000")); request.setRanges(Arrays.asList(new Range(1, 10))); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); request.setMethod(Method.GET); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("0000000000", response.getEntity().getText()); // Partial PUT on a file, simple range request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt"); request.setEntity(new StringRepresentation("22")); request.setRanges(Arrays.asList(new Range(2, 2))); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = client.handle(new Request(Method.GET, request.getResourceRef())); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("10220000000", response.getEntity().getText()); // Partial PUT on a file, the provided representation will be padded // at the very end of the file. request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt"); request.setEntity(new StringRepresentation("888")); request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX))); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = client.handle(new Request(Method.GET, request.getResourceRef())); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("10220000888", response.getEntity().getText()); // Partial PUT on a file that does not exist, the range does not // specify the range size. request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai3.txt"); request.setEntity(new StringRepresentation("888")); request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX))); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); request.setMethod(Method.GET); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("888", response.getEntity().getText()); // Partial PUT on a file, the provided representation will be padded // just before the end of the file. request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt"); request.setEntity(new StringRepresentation("99")); request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX))); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); response = client.handle(new Request(Method.GET, request.getResourceRef())); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("10220000998", response.getEntity().getText()); request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/testPut/essai.txt"); request.setRanges(Arrays.asList(new Range(3, Range.SIZE_MAX))); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("20000998", response.getEntity().getText()); BioUtils.delete(testDir, true); client.stop(); } }
/** Gets media's information list (GET /<channel>) */ @Get public Representation getMediasInfo() { setServerHeader(); // The HTTP API sets the headers // addCORSHeaders(); Request request = getRequest(); String userId = null; String token = null; String entityId = (String) request.getAttributes().get(Constants.ENTITY_ARG); boolean isChannelPublic = XMPPToolBox.getInstance().getPubSubClient().isChannelPublic(entityId); if (!isChannelPublic) { String auth = getQueryValue(Constants.AUTH_QUERY); try { userId = getUserId(request, auth); token = getTransactionId(request, auth); } catch (Throwable t) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return new StringRepresentation( "Error while getting auth params", MediaType.APPLICATION_JSON); } Representation verifyRequest = checkRequest(userId, token, request.getResourceRef().getIdentifier()); if (verifyRequest != null) { return verifyRequest; } } Integer max = null; String after = null; try { String queryValue = getQueryValue(Constants.MAX_QUERY); if (queryValue != null) { max = Integer.valueOf(queryValue); } after = getQueryValue(Constants.AFTER_QUERY); } catch (Throwable t) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return new StringRepresentation("Invalid query value!", MediaType.APPLICATION_JSON); } MediaDAO mediaDAO = DAOFactory.getInstance().getDAO(); try { return new StringRepresentation( mediaDAO.getMediasInfo(userId, entityId, max, after), MediaType.APPLICATION_JSON); } catch (MetadataSourceException e) { setStatus(Status.SERVER_ERROR_INTERNAL); } catch (UserNotAllowedException e) { setStatus(Status.CLIENT_ERROR_FORBIDDEN); } catch (Throwable t) { return unexpectedError(t); } return new EmptyRepresentation(); }