@Override protected IQueryRetrieval<IStructureRecord> createQuery( Context context, Request request, Response response) throws ResourceException { Form form = getParams(); setTemplate(createTemplate(form)); setGroupProperties(context, request, response); STRUCTURE_RELATION relation = null; try { Object cmp = request.getAttributes().get(compositionType); relation = STRUCTURE_RELATION.valueOf(cmp.toString().toUpperCase()); } catch (Exception x) { } Object key = request.getAttributes().get(SubstanceResource.idsubstance); if (key == null) return new ReadSubstanceRelation(relation, null); try { return new ReadSubstanceRelation( relation, new SubstanceRecord(Integer.parseInt(key.toString()))); } catch (Exception x) { int len = key.toString().trim().length(); if ((len > 40) && (len <= 45)) { return new ReadSubstanceRelation(relation, new SubstanceRecord(key.toString())); } throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST); } }
@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); } } }
/** * Allows filtering before its handling by the target Restlet. By default it parses the template * variable, adjust the base reference, then extracts the attributes from form parameters (query, * cookies, entity) and finally tries to validate the variables as indicated by the {@link * #validate(String, boolean, String)} method. * * @param request The request to filter. * @param response The response to filter. * @return The {@link Filter#CONTINUE} status. */ @Override protected int beforeHandle(Request request, Response response) { if (this.validations != null) { for (ValidateInfo validate : getValidations()) { if (validate.required && !request.getAttributes().containsKey(validate.attribute)) { response.setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Unable to find the \"" + validate.attribute + "\" attribute in the request. Please check your request."); } else if (validate.format != null) { Object value = request.getAttributes().get(validate.attribute); if ((value != null) && !Pattern.matches(validate.format, value.toString())) { response.setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Unable to validate the value of the \"" + validate.attribute + "\" attribute. The expected format is: " + validate.format + " (Java Regex). Please check your request."); } } } } return CONTINUE; }
@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); } } }
/* * POST request to webServiceURL/version/devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}/{serialNumber} */ @Post("json") public final void registerDeviceRequest(final Representation entity) { Request request = getRequest(); Map<String, Object> requestAttributes = request.getAttributes(); String deviceLibraryIdentifier = (String) requestAttributes.get("deviceLibraryIdentifier"); String passTypeIdentifier = (String) requestAttributes.get("passTypeIdentifier"); String serialNumber = (String) requestAttributes.get("serialNumber"); String authString = request.getChallengeResponse().getRawValue(); Status responseStatus; try { String jsonPushToken = entity.getText(); PKPushToken pkPushToken = jsonObjectMapper.readValue(jsonPushToken, PKPushToken.class); LOGGER.debug("registerDeviceRequest - deviceLibraryIdentifier: {}", deviceLibraryIdentifier); LOGGER.debug("registerDeviceRequest - passTypeIdentifier: {}", passTypeIdentifier); LOGGER.debug("registerDeviceRequest - serialNumber: {}", serialNumber); LOGGER.debug("registerDeviceRequest - authString: {}", authString); LOGGER.debug("registerDeviceRequest - jsonPushToken: {}", jsonPushToken); LOGGER.debug("registerDeviceRequest - pkPushToken: {}", pkPushToken); responseStatus = handleRegisterDeviceRequest( deviceLibraryIdentifier, passTypeIdentifier, serialNumber, authString, pkPushToken); } catch (PKAuthTokenNotValidException e) { responseStatus = Status.CLIENT_ERROR_UNAUTHORIZED; } catch (IOException e) { responseStatus = Status.SERVER_ERROR_INTERNAL; } setStatusIntoResponse(responseStatus, getResponse()); }
/* * GET request to webServiceURL/version/devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}?passesUpdatedSince=tag */ @Get("json") public final Representation getSerialNumbersForPasses(final Representation entity) { Request request = getRequest(); Map<String, Object> requestAttributes = request.getAttributes(); String deviceLibraryIdentifier = (String) requestAttributes.get("deviceLibraryIdentifier"); String passTypeIdentifier = (String) requestAttributes.get("passTypeIdentifier"); String passesUpdatedSince = (String) requestAttributes.get("passesUpdatedSince"); LOGGER.debug( "getSerialNumbersForPasses - deviceLibraryIdentifier: {}", deviceLibraryIdentifier); LOGGER.debug("getSerialNumbersForPasses - passTypeIdentifier: {}", passTypeIdentifier); LOGGER.debug("getSerialNumbersForPasses - passesUpdatedSince: {}", passesUpdatedSince); PKSerialNumbersOfPassesForDeviceResponse serialNumbersOfPassesForDevice = getSerialNumberOfPassesForDevice( deviceLibraryIdentifier, passTypeIdentifier, passesUpdatedSince); if (serialNumbersOfPassesForDevice == null || serialNumbersOfPassesForDevice.getSerialNumbers() == null) { setStatusIntoResponse(Status.SUCCESS_NO_CONTENT, getResponse()); return null; } String responseJSONString; try { responseJSONString = jsonObjectMapper.writeValueAsString(serialNumbersOfPassesForDevice); return new StringRepresentation(responseJSONString, MediaType.APPLICATION_JSON); } catch (Exception e) { LOGGER.error("Error when parsing response to JSON:", e); } setStatusIntoResponse(Status.SERVER_ERROR_INTERNAL, getResponse()); return null; }
/* * DELETE request to webServiceURL/version/devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}/{serialNumber} */ @Delete("json") public final void deleteDeviceRegistrationRequest(final Representation entity) { Request request = getRequest(); Map<String, Object> requestAttributes = request.getAttributes(); String deviceLibraryIdentifier = (String) requestAttributes.get("deviceLibraryIdentifier"); String passTypeIdentifier = (String) requestAttributes.get("passTypeIdentifier"); String serialNumber = (String) requestAttributes.get("serialNumber"); ChallengeResponse authString = request.getChallengeResponse(); LOGGER.debug( "deleteDeviceRegistrationRequest - deviceLibraryIdentifier: {}", deviceLibraryIdentifier); LOGGER.debug("deleteDeviceRegistrationRequest - passTypeIdentifier: {}", passTypeIdentifier); LOGGER.debug("deleteDeviceRegistrationRequest - serialNumber: {}", serialNumber); LOGGER.debug("deleteDeviceRegistrationRequest - authString: {}", authString); Status responseStatus; try { responseStatus = handleUnregisterDeviceRequest( deviceLibraryIdentifier, passTypeIdentifier, serialNumber, authString); } catch (PKAuthTokenNotValidException e) { responseStatus = Status.CLIENT_ERROR_UNAUTHORIZED; } setStatusIntoResponse(responseStatus, getResponse()); }
@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 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 protected ReadRegistration createUpdateQuery( Method method, Context context, Request request, Response response) throws ResourceException { Object key = request.getAttributes().get(UserDBResource.resourceKey); if (Method.POST.equals(method)) { if (key == null) return null; // post allowed only on /user level, not on /user/id } else if (Method.PUT.equals(method)) { return createQuery(context, request, response); } throw new ResourceException(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); }
/** * 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); } } } } }
@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); } } }
@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); }
@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(); } } }
@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 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; }
@BeforeMethod public void setUp() { resource = mock(ClientResource.class); restClient = new RestletRestClient() { @Override ClientResource createResource(final String uri) { return resource; } }; Request request = mock(Request.class); ConcurrentHashMap<String, Object> requestAttributes = new ConcurrentHashMap<String, Object>(); requestHeaders = mock(Series.class); given(resource.getRequest()).willReturn(request); given(request.getAttributes()).willReturn(requestAttributes); given(resource.getRequestAttributes()).willReturn(requestAttributes); requestAttributes.put("org.restlet.http.headers", requestHeaders); }
@Override protected int doHandle(final Request request, final Response response) { int result = super.doHandle(request, response); Map<String, Object> requestAttributes = request.getAttributes(); Map<String, Object> responseAttributes = response.getAttributes(); Series<Header> requestHeaders = (Series<Header>) requestAttributes.computeIfAbsent( "org.restlet.http.headers", key -> new Series<Header>(Header.class)); Series<Header> responseHeaders = (Series<Header>) responseAttributes.computeIfAbsent( "org.restlet.http.headers", key -> new Series<Header>(Header.class)); // TODO fix me responseHeaders.add("Access-Control-Allow-Origin", requestHeaders.getFirstValue("Origin")); responseHeaders.add("Access-Control-Allow-Credentials", "true"); responseHeaders.add( "Access-Control-Allow-Methods", "HEAD, GET, PUT, POST, DELETE, OPTIONS, TRACE"); responseHeaders.add("Access-Control-Allow-Headers", "Content-Type, X-Requested-With"); return result; }
/** * 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"; } } }
/** 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(); }