/** Test that the left column gets refreshed properly. */ @Test public void testRefreshLeftColumn() { context.turnOffAuthorization(); Person person = personRepo.findPersonByEmail("*****@*****.**"); Submission submission = subRepo.createSubmission(person); submission.setDocumentTitle("My Document Title"); State state = stateManager.getState("InReview"); submission.setState(state); EmbargoType embargo = settingRepo.findAllEmbargoTypes().get(0); submission.addEmbargoType(embargo); submission.save(); Long id = submission.getId(); assertEquals("My Document Title", submission.getDocumentTitle()); JPA.em().getTransaction().commit(); JPA.em().clear(); JPA.em().getTransaction().begin(); LOGIN(); String UPDATE_URL = Router.reverse("ViewTab.updateJSON").url; Map<String, String> params = new HashMap<String, String>(); params.put("subId", id.toString()); params.put("field", "title"); params.put("value", "This is a new title"); Response response = POST(UPDATE_URL, params); assertIsOk(response); assertContentMatch("\"success\": true,", response); submission = subRepo.findSubmission(id); UPDATE_URL = Router.reverse("ViewTab.refreshLeftColumn").url; params.clear(); params.put("id", id.toString()); response = POST(UPDATE_URL, params); assertIsOk(response); assertContentMatch("Document title changed to", response); submission.delete(); context.restoreAuthorization(); }
/** Detect sources modifications */ public static synchronized void detectChanges() { if (mode == Mode.PROD) { return; } try { pluginCollection.beforeDetectingChanges(); if (!pluginCollection.detectClassesChange()) { classloader.detectChanges(); } Router.detectChanges(ctxPath); for (VirtualFile conf : confs) { if (conf.lastModified() > startedAt) { start(); return; } } pluginCollection.detectChange(); if (!Play.started) { throw new RuntimeException("Not started"); } } catch (PlayException e) { throw e; } catch (Exception e) { // We have to do a clean refresh start(); } }
/** Test that an email template returns successful with a subject and message */ @Test public void testRetrieveTemplateJSON() { context.turnOffAuthorization(); EmailTemplate template = settingRepo.createEmailTemplate( "newTemplate", "New Template Subject", "New Template Message"); template.save(); Long id = template.getId(); JPA.em().getTransaction().commit(); JPA.em().clear(); JPA.em().getTransaction().begin(); LOGIN(); String UPDATE_URL = Router.reverse("ViewTab.retrieveTemplateJSON").url; Map<String, String> params = new HashMap<String, String>(); params.put("id", id.toString()); Response response = POST(UPDATE_URL, params); assertIsOk(response); assertContentMatch("\"success\": true,", response); template = settingRepo.findEmailTemplate(id); template.delete(); context.restoreAuthorization(); }
@Override public String getShowUrl() { return Router.reverse("LightningTalks.show") .add("sessionId", this.id) .add("slugify", JavaExtensions.slugify(this.title)) .url; }
@Override public boolean init() { Logger.trace("init: begin"); Request.current.set(request); Response.current.set(response); try { super.init(); if (Play.mode == Play.Mode.PROD && staticPathsCache.containsKey(request.path)) { RenderStatic rs = null; synchronized (staticPathsCache) { rs = staticPathsCache.get(request.path); } serveStatic(rs, ctx, request, response, nettyRequest, event); Logger.trace("init: end false"); return false; } Router.routeOnlyStatic(request); } catch (NotFound nf) { serve404(nf, ctx, request, nettyRequest); Logger.trace("init: end false"); return false; } catch (RenderStatic rs) { if (Play.mode == Play.Mode.PROD) { synchronized (staticPathsCache) { staticPathsCache.put(request.path, rs); } } serveStatic(rs, ctx, request, response, nettyRequest, this.event); Logger.trace("init: end false"); return false; } Logger.trace("init: end true"); return true; }
private static void edit(PrintWriter out, String name) throws Throwable { if (!Profiler.canEdit(name)) return; HashMap<String, Object> args = new HashMap<String, Object>(); args.put("pageName", name); out.print("<a href=\"" + Router.getFullUrl("cms.Admin.editPage", args) + "\">"); out.print("<img alt=\"Edit\" src=\"/public/images/edit.gif\">"); out.print("</a>"); }
/** * Gets the service. * * @return the service */ private static OAuthService getService() { return new ServiceBuilder() .provider(LinkedInApi.class) .apiKey(getApiKey()) .apiSecret(getSecret()) .callback(Router.getFullUrl("LinkedInController.callback")) .build(); }
/** * Parses the playframework action expressions. The string inside "()" is evaluated by OGNL in the * current context. * * @param arguments * @param attributeValue e.g. "Application.show(obj.id)" * @return parsed action path */ @SuppressWarnings("unchecked") static String toActionString(final Arguments arguments, String attributeValue) { Matcher matcher = PARAM_PATTERN.matcher(attributeValue); if (!matcher.matches()) { return Router.reverse(attributeValue).toString(); } String exp = matcher.group(1); if (StringUtils.isBlank(exp)) { return Router.reverse(attributeValue).toString(); } Object obj = PlayOgnlVariableExpressionEvaluator.INSTANCE.evaluate( arguments.getConfiguration(), arguments, exp, false); if (obj instanceof Map) { return Router.reverse(attributeValue, (Map<String, Object>) obj).toString(); } List<?> list = obj instanceof List ? (List<?>) obj : Arrays.asList(obj); Map<String, Object> paramMap = new HashMap<String, Object>(); String extracted = StringUtils.substringBefore(attributeValue, "("); if (!extracted.contains(".")) { extracted = Request.current().controller + "." + extracted; } Object[] actionMethods = ActionInvoker.getActionMethod(extracted); String[] paramNames = null; try { paramNames = Java.parameterNames((Method) actionMethods[1]); } catch (Exception e) { throw new RuntimeException(e); } if (paramNames.length < list.size()) { Logger.warn("param length unmatched. %s", Arrays.toString(paramNames)); throw new ActionNotFoundException(attributeValue, null); } for (int i = 0; i < list.size(); i++) { paramMap.put(paramNames[i], list.get(i)); } return Router.reverse(extracted, paramMap).toString(); }
private static synchronized void loadRouter(String contextPath) { // Reload the rules, but this time with the context. Not really efficient through... // Servlet 2.4 does not allow you to get the context path from the servletcontext... if (routerInitializedWithContext) return; Play.ctxPath = contextPath; Router.load(contextPath); routerInitializedWithContext = true; }
/** * Redirect to task by given parameters * * @param task * @param user * @param time */ public static void gotoSolution(Long task, Long user, Integer time) { Solution first = Solution.find("task.id = ? AND user.id=? AND timeLength=?", task, user, time).first(); notFoundIfNull(first); Map<String, Object> map = new HashMap<String, Object>(); map.put("id", first); redirect(Router.getFullUrl("admin.Solutions.show", map)); }
/** * Test uploading a "primary" file * * @throws IOException */ @Test public void testUploadPrimary() throws IOException { context.turnOffAuthorization(); Person person = personRepo.findPersonByEmail("*****@*****.**"); Submission submission = subRepo.createSubmission(person); submission.setAssignee(person); submission.save(); File file = getResourceFile("SamplePrimaryDocument.pdf"); Long id = submission.getId(); JPA.em().getTransaction().commit(); JPA.em().clear(); JPA.em().getTransaction().begin(); LOGIN(); String UPDATE_URL = Router.reverse("ViewTab.view").url; // Update a primary document Map<String, String> params = new HashMap<String, String>(); params.put("subId", id.toString()); params.put("uploadType", "primary"); params.put("addFile", "true"); Map<String, File> files = new HashMap<String, File>(); files.put("primaryAttachment", file); Response response = POST(UPDATE_URL, params, files); assertIsOk(response); // Re-upload a primary document params = new HashMap<String, String>(); params.put("subId", id.toString()); params.put("uploadType", "primary"); params.put("status_change", "true"); params.put("addFile", "true"); files = new HashMap<String, File>(); files.put("primaryAttachment", file); response = POST(UPDATE_URL, params, files); assertIsOk(response); file.delete(); // Verify the files were uploaded and archived submission = subRepo.findSubmission(id); assertEquals("PRIMARY-DOCUMENT.pdf", submission.getPrimaryDocument().getName()); assertEquals( "PRIMARY-DOCUMENT-archived-on-" + JpaAttachmentImpl.dateFormat.format(new Date()) + ".pdf", submission.getAttachmentsByType(AttachmentType.ARCHIVED).get(0).getName()); assertEquals(submission.getState(), stateManager.getState("NeedsCorrection")); submission.delete(); context.restoreAuthorization(); }
public static void austh4SQ() { String redirect = Router.getFullUrl("Application.callBack4SQAuth"); String url = "https://foursquare.com/oauth2/authenticate?client_id=" + BigBrotherHelper.CLIENT_ID + "&response_type=code&redirect_uri=" + redirect; throw new Redirect(url); }
public static void delete(String name) throws Throwable { if (!Profiler.canEnter()) forbidden(); checkAuthenticity(); CMSImage image = CMSImage.findById(name); image.delete(); Extension.invoke("afterDelete", image); redirect(Router.reverse("cms.Admin.imagelist").url + "?" + request.querystring); }
public static void deleteAccount(String password) { checkAuthenticity(); User user = User.findByEmail(session.get("username")); if (Passwords.matches(password, user.password)) { user.remove(); renderJSON("{\"next\":\"" + Router.reverse("Secure.logout").url + "\"}"); } else { validation.addError("password", "Chybné heslo"); Gson gson = new Gson(); error(Http.StatusCode.BAD_REQUEST, gson.toJson(validation.errorsMap())); } }
@Override public void insert() { super.insert(); TipoAzione tp = TipoAzione.find("votato un evento"); try { new Action(user, tp, new Date(), Router.getFullUrl("Events.show") + "?id=" + this.event.id) .insert(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@SuppressWarnings("unchecked") public static void resolve(Http.Request request, Http.Response response) throws NotFound, RenderStatic { if (!Play.started) { return; } Http.Request.current.set(request); Http.Response.current.set(response); Scope.Params.current.set(request.params); Scope.RenderArgs.current.set(new Scope.RenderArgs()); Scope.RouteArgs.current.set(new Scope.RouteArgs()); Scope.Session.current.set(Scope.Session.restore()); Scope.Flash.current.set(Scope.Flash.restore()); CachedBoundActionMethodArgs.init(); ControllersEnhancer.currentAction.set(new Stack<String>()); if (request.resolved) { return; } // Route and resolve format if not already done if (request.action == null) { Play.pluginCollection.routeRequest(request); Route route = Router.route(request); Play.pluginCollection.onRequestRouting(route); } request.resolveFormat(); // Find the action method try { Method actionMethod = null; Object[] ca = getActionMethod(request.action); actionMethod = (Method) ca[1]; request.controller = ((Class) ca[0]).getName().substring(12).replace("$", ""); request.controllerClass = ((Class) ca[0]); request.actionMethod = actionMethod.getName(); request.action = request.controller + "." + request.actionMethod; request.invokedMethod = actionMethod; if (Logger.isTraceEnabled()) { Logger.trace("------- %s", actionMethod); } request.resolved = true; } catch (ActionNotFoundException e) { // Logger.error(e, "%s action not found", e.getAction()); // bran: avoid excessive messages Logger.error("%s action not found", e.getAction()); throw new NotFound(String.format("%s action not found", e.getAction())); } }
@Util private static String redirectToFirstPage(Long idSolicitud) { // Url Primera pagina de la solicitud String firstPage = FapProperties.get("fap.app.firstPage"); if (firstPage == null) { play.Logger.error( "No está definida la property fap.app.firstPage que identifica la primera página."); Messages.fatal("Se ha producido un error"); } String expedienteUrl = Router.reverse(firstPage + "Controller.index").add("idSolicitud", idSolicitud).url; return expedienteUrl; }
/** Test uploading an "additonal" file */ @Test public void testUploadAdditonal() { context.turnOffAuthorization(); Person person = personRepo.findPersonByEmail("*****@*****.**"); Submission submission = subRepo.createSubmission(person); submission.setAssignee(person); submission.save(); Long id = submission.getId(); JPA.em().getTransaction().commit(); JPA.em().clear(); JPA.em().getTransaction().begin(); LOGIN(); String UPDATE_URL = Router.reverse("ViewTab.view").url; Map<String, String> params = new HashMap<String, String>(); params.put("subId", id.toString()); params.put("uploadType", "additional"); params.put("attachmentType", "SUPPLEMENTAL"); params.put("status_change", "true"); params.put("addFile", "true"); Map<String, File> files = new HashMap<String, File>(); File file = null; try { file = getResourceFile("SampleSupplementalDocument.doc"); files.put("additionalAttachment", file); } catch (IOException ioe) { fail("Test upload file not found."); } Response response = POST(UPDATE_URL, params, files); assertIsOk(response); submission = subRepo.findSubmission(id); assertNotNull(submission.getSupplementalDocuments().get(0)); assertEquals(submission.getState(), stateManager.getState("NeedsCorrection")); Attachment attachment = submission.getSupplementalDocuments().get(0); attachment.delete(); submission.delete(); context.restoreAuthorization(); }
/** Test that an admin can update a committee member */ @Test public void testUpdateCommitteeMemberJSON() { context.turnOffAuthorization(); Person person = personRepo.findPersonByEmail("*****@*****.**"); Submission submission = subRepo.createSubmission(person).save(); CommitteeMember member = submission.addCommitteeMember("John", "Doe", "T").save(); member.addRole("Committee Member"); submission.save(); Long subId = submission.getId(); Long id = member.getId(); assertEquals(1, submission.getCommitteeMembers().size()); assertEquals("John", member.getFirstName()); assertEquals("Doe", member.getLastName()); assertEquals("T", member.getMiddleName()); assertEquals("Committee Member", member.getRoles().get(0)); JPA.em().getTransaction().commit(); JPA.em().clear(); JPA.em().getTransaction().begin(); LOGIN(); final String UPDATE_URL = Router.reverse("ViewTab.updateCommitteeMemberJSON").url; Map<String, String> params = new HashMap<String, String>(); params.put("id", id.toString()); params.put("firstName", "Jill"); params.put("lastName", "Duck"); params.put("middleName", "M"); params.put("roles", "Committee Chair"); Response response = POST(UPDATE_URL, params); assertIsOk(response); assertContentMatch("\"success\": true,", response); submission = subRepo.findSubmission(subId); member = subRepo.findCommitteeMember(id); assertEquals("Jill", member.getFirstName()); assertEquals("Duck", member.getLastName()); assertEquals("M", member.getMiddleName()); assertEquals("Committee Chair", member.getRoles().get(0)); member.delete(); submission.delete(); context.restoreAuthorization(); }
public static void register(@Required String username, @Required String password) { response.contentType = "text/javascript"; try { new User(username, Codec.hexSHA1(password)).save(); session.put("username", username); renderText( "top.location.href='" + Router.reverse("Application.index").url + "'"); // redirect to index page via ajax reload } catch (PersistenceException e) { // Username already exists renderText( "$('#name').addClass( 'ui-state-error' );updateTips('Benutzerkonto besteht bereits.')"); } }
/** * Remove all evaluations from single solutions of this task * * @param id */ public static void unevaluate(Long id) { Task task = Task.findById(id); notFoundIfNull(task); List<models.Solution> solutions = models.Solution.find("task=?", task).fetch(); for (models.Solution solution : solutions) { solution.unevaluate(); solution.save(); } Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("search_task", task.id); redirect(Router.getFullUrl("admin.Solutions.list", parameters)); }
@Override public Object invokeMethod(String name, Object param) { try { if (controller == null) { controller = Request.current().controller; } String action = controller + "." + name; if (action.endsWith(".call")) { action = action.substring(0, action.length() - 5); } try { Map<String, Object> r = new HashMap<String, Object>(); Method actionMethod = (Method) ActionInvoker.getActionMethod(action)[1]; String[] names = (String[]) actionMethod.getDeclaringClass().getDeclaredField("$" + actionMethod.getName() + LocalVariablesNamesTracer.computeMethodHash(actionMethod.getParameterTypes())).get(null); if (param instanceof Object[]) { // too many parameters versus action, possibly a developer error. we must warn him. if (names.length < ((Object[]) param).length) { throw new NoRouteFoundException(action, null); } for (int i = 0; i < ((Object[]) param).length; i++) { if (((Object[]) param)[i] instanceof Router.ActionDefinition && ((Object[]) param)[i] != null) { Unbinder.unBind(r, ((Object[]) param)[i].toString(), i < names.length ? names[i] : ""); } else if (isSimpleParam(actionMethod.getParameterTypes()[i])) { if (((Object[]) param)[i] != null) { Unbinder.unBind(r, ((Object[]) param)[i].toString(), i < names.length ? names[i] : ""); } } else { Unbinder.unBind(r, ((Object[]) param)[i], i < names.length ? names[i] : ""); } } } Router.ActionDefinition def = Router.reverse(action, r); if (absolute) { def.absolute(); } if (template.template.name.endsWith(".html") || template.template.name.endsWith(".xml")) { def.url = def.url.replace("&", "&"); } return def; } catch (ActionNotFoundException e) { throw new NoRouteFoundException(action, null); } } catch (Exception e) { if (e instanceof PlayException) { throw (PlayException) e; } throw new UnexpectedException(e); } }
public static void upload(File data) throws Throwable { if (!Profiler.canEnter()) forbidden(); checkAuthenticity(); CMSImage image = CMSImage.findById(data.getName()); if (image == null) { image = new CMSImage(); image.name = data.getName(); } image.lastModified = new Date(); image.data = IOUtils.toByteArray(new FileInputStream(data)); image.save(); Extension.invoke("afterSave", image); redirect(Router.reverse("cms.Admin.imagelist").url + "?" + request.querystring); }
@Before public static void checkAuth() { if (request.url.startsWith(Router.reverse("GuiController.signIn").url) || request.url.startsWith(Router.reverse("GuiController.signUp").url) || request.url.startsWith(Router.reverse("GuiController.home").url)) { renderArgs.put("menu", MenuManager.hardCode(User.GUEST)); return; } apiKey = session.get("api_key"); // apiKey = params.get( "api_key" ); currentUser = securityManager.getUser(apiKey); renderArgs.put("menu", MenuManager.hardCode(currentUser)); if (currentUser != null && !currentUser.isGuest()) { Logger.info(currentUser + "[" + request.domain + "] " + request.url); renderArgs.put("currentUser", currentUser); renderArgs.put("api_key", apiKey); return; } Logger.debug("An unauthorized user tried to access " + request.url); home(); }
public static void signIn(String url, String email, String password) { if (url == null || url.isEmpty()) { url = Router.reverse("Application.app").url; } if (email != null && !email.isEmpty() && password != null && !password.isEmpty()) { SecurityModel securityModel = securityManager.signIn(email, password); if (securityModel != null) { currentUser = securityModel.user; session.put("api_key", securityModel.securityKey); redirect(url); } } home(); }
public static String url(IMenu menu) { String s = menu.getUrl(); if (null == s) return null; s = s.trim(); Matcher m = p1_.matcher(s); if (m.find()) { s = m.group(1); } m = p2_.matcher(s); if (m.find()) { s = m.group(1); return Router.reverse(s).url; } else { return s; } }
@Override public void onRoutesLoaded() { if (Play.mode.isDev()) { Router.addRoute("GET", "/@cukes/run.cli", "Cucumber.runAllFromCommandLine"); Router.addRoute("GET", "/@cukes/run", "Cucumber.runAll"); Router.addRoute("GET", "/@cukes/run/{<.*>uri}", "Cucumber.runFeature"); Router.addRoute("GET", "/@cukes/result/{<.*>uri}", "Cucumber.showFeatureExecResult"); Router.addRoute("GET", "/@cukes/feature/{<.*>uri}", "Cucumber.showFeature"); Router.addRoute("GET", "/@cukes", "Cucumber.index"); } }
/** Test that an admin can add an action log comment */ @Test public void testAddActionLogComment() { context.turnOffAuthorization(); Person person = personRepo.findPersonByEmail("*****@*****.**"); Submission submission = subRepo.createSubmission(person); submission.setAssignee(person); submission.save(); Long id = submission.getId(); int numActionLogs = subRepo.findActionLog(submission).size(); assertEquals(submission.getAssignee().getCurrentEmailAddress(), "*****@*****.**"); JPA.em().getTransaction().commit(); JPA.em().clear(); JPA.em().getTransaction().begin(); LOGIN(); String UPDATE_URL = Router.reverse("ViewTab.view").url; Map<String, String> params = new HashMap<String, String>(); params.put("primary_recipients", "Student, Librarians, [email protected]"); params.put("cc_recipients", "Advisor, [email protected]"); params.put("subId", id.toString()); params.put("subject", "The subject"); params.put("comment", "This is the comment."); params.put("visibility", "public"); params.put("status_change", "true"); params.put("addActionLogComment", "true"); Response response = POST(UPDATE_URL, params); assertIsOk(response); submission = subRepo.findSubmission(id); assertTrue(subRepo.findActionLog(submission).size() > numActionLogs); assertEquals( "Submission status changed to 'Needs Correction'", subRepo.findActionLog(submission).get(0).getEntry()); assertEquals(submission.getState(), stateManager.getState("NeedsCorrection")); submission.delete(); context.restoreAuthorization(); }
public static void login(@Required String username, @Required String password) { response.contentType = "text/javascript"; if (authenticate(username, password)) { // Mark user as connected session.put("username", username); renderText( "top.location.href='" + Router.reverse("Application.index").url + "'"); // redirect to index page via ajax reload } else { // Username already exists renderText( "$('#name').addClass( 'ui-state-error' );updateTips('Benutzername oder Kennwort unbekannt.')"); } }
/** Test that an admin can change the custom action values. */ @Test public void testUpdateCustomActionsJSON() { context.turnOffAuthorization(); Person person = personRepo.findPersonByEmail("*****@*****.**"); Submission submission = subRepo.createSubmission(person); submission.setAssignee(person); submission.save(); Long id = submission.getId(); assertEquals(submission.getAssignee().getCurrentEmailAddress(), "*****@*****.**"); CustomActionDefinition actionDef = settingRepo.createCustomActionDefinition("Passed Classes", false).save(); Long actionId = actionDef.getId(); JPA.em().getTransaction().commit(); JPA.em().clear(); JPA.em().getTransaction().begin(); LOGIN(); String UPDATE_URL = Router.reverse("ViewTab.updateCustomActionsJSON").url; Map<String, String> params = new HashMap<String, String>(); params.put("id", id.toString()); params.put("action", actionId.toString()); params.put("value", "true"); Response response = POST(UPDATE_URL, params); assertIsOk(response); submission = subRepo.findSubmission(id); actionDef = settingRepo.findCustomActionDefinition(actionId); assertTrue(submission.getCustomAction(actionDef).getValue()); submission.delete(); actionDef.delete(); context.restoreAuthorization(); }