public static void groupsEdit(String gid) { // even if we should skip load for edition reason, we still need to load the real group for the // security check ProjectGroup group = BeanProvider.getGroupService().loadGroupById(gid, false); if (group == null || !group.isActive()) { // group does not exist! Application.index(); } else { GroupPep pep = new GroupPep(group); if (!pep.isUserAllowedToEditGroup(getSessionWrapper().getLoggedInUserProfileId())) { // user not allowed to edit this group! Application.index(); } else { if (!flash.contains(FLASH_SKIP_LOADING_GROUP)) { renderArgs.put("editedGroup", new EditedGroup(group)); } Utils.addThemesToRenderArgs(getSessionWrapper(), renderArgs); Utils.addJsonThemesToRenderArgs( getSessionWrapper(), renderArgs, getSessionWrapper().getSelectedLg()); flash.put(FLASH_GROUP_ID, gid); render(); } } }
/** Clear the entire database except for the administrator users. */ public static void clearDB() { if (!Session.user().isModerator()) { flash.error("secure.cleardberror"); Application.index(0); } Database.clearKeepAdmins(); flash.success("secure.cleardbflash"); Application.admin(); }
/** * Save profile the profile a {@link User}. * * @param name the name of the {@link User}. * @param email the email of the {@link User}. * @param fullname the fullname of the {@link User}. * @param birthday the birthday of the {@link User}. * @param website the website of the {@link User}. * @param profession the profession of the{@link User}. * @param employer the employer of the{@link User}. * @param biography the biography of the {@link User}. * @param oldPassword the old password of the {@link User}. * @param newPassword the new password of the {@link User}. * @throws ParseException */ public static void saveProfile( String name, String email, String fullname, String birthday, String website, String profession, String employer, String biography, String oldPassword, String newPassword) throws ParseException { User user = Database.users().get(name); if (!userCanEditProfile(user)) { flash.error("secure.editprofileerror"); Application.showprofile(user.getName()); } if (email != null) { user.setEmail(email); } if (fullname != null) { user.setFullname(fullname); } if (birthday != null) { user.setDateOfBirth(birthday); } if (website != null) { user.setWebsite(website); } if (profession != null) { user.setProfession(profession); } if (employer != null) { user.setEmployer(employer); } if (biography != null) { user.setBiography(biography); } if (!newPassword.isEmpty()) { if (user.checkPW(oldPassword)) { user.setSHA1Password(newPassword); } else if (!user.checkPW(oldPassword)) { flash.error("secure.passwordChangeError"); } } if (!oldPassword.isEmpty() && newPassword.isEmpty()) { flash.error("secure.passwordNewFieldEmptyError"); } flash.success("secure.editprofileflash"); Application.showprofile(user.getName()); }
public static void dashboard(@Required Long project_id) { if (Validation.hasErrors()) { Application.homepage(); } else { render(); } }
private static void cargarListas() { tipoRecorrido = new ArrayList<String>(); tipoRecorrido.add("Frecuente"); tipoRecorrido.add("Recreacion"); diaFrecuente = new TreeMap<String, Boolean>(); diaFrecuente.put("1-Lunes", false); diaFrecuente.put("2-Martes", false); diaFrecuente.put("3-Miercoles", false); diaFrecuente.put("4-Jueves", false); diaFrecuente.put("5-Viernes", false); diaFrecuente.put("6-Sabado", false); diaFrecuente.put("7-Domingo", false); horaSalida = new TreeMap<String, Boolean>(); for (int i = 0; i < 24; i++) { horaSalida.put(String.format("%02d", i) + ":00", false); horaSalida.put(String.format("%02d", i) + ":30", false); } UserDAO userDao = new UserDAO(); List<User> lstUser = userDao.listarUsuarios(); User usuarioSession = Application.getLocalUser(session()); lstAmigos = new TreeMap<String, Boolean>(); for (User usuario : lstUser) { if (usuarioSession.id != usuario.id) lstAmigos.put(usuario.name + "-" + usuario.id, false); } }
@Transactional public static Result uploadImage() { final String loggedInUser = Application.getLoggedInUser(); if (loggedInUser == null) { return ok(views.html.login.render()); } FilePart picture = request().body().asMultipartFormData().getFile("url-photo0"); String fileName = picture.getFilename(); logger.underlyingLogger().info("uploadImage. fileName=" + fileName); DateTime now = new DateTime(); File file = picture.getFile(); try { String imagePath = imageUploadUtil.getImagePath(now, fileName); FileUtils.copyFile(file, new File(imagePath)); } catch (IOException e) { logger.underlyingLogger().error(loggedInUser + " failed to upload photo", e); return status(500); } String imageUrl = imageUploadUtil.getImageUrl(now, fileName); logger.underlyingLogger().info("uploadImage. imageUrl=" + imageUrl); Map<String, String> map = new HashMap<>(); map.put("URL", imageUrl); logger.underlyingLogger().info(loggedInUser + " uploaded photo - " + imageUrl); return ok(Json.toJson(map)); }
public static void callBack4SQAuth() { String code = params.get("code"); String token = BigBrotherHelper.retrieveToken(code); System.out.println(token); Application.index(); // 4square login }
/** * @param recorrido * @param ruta * @param listUsuarioRecorrido */ private static void notificarInvitacionARecorrdo( Recorrido recorrido, Ruta ruta, List<UsuarioXRecorrido> listUsuarioRecorrido) { User usuarioSession = Application.getLocalUser(session()); String usuarioInvita = usuarioSession.name; String nombreRecorrido = recorrido.getNombre(); String lugarInicio = ruta.getLugarInicio(); String lugarFin = ruta.getLugarFin(); String descripcion = recorrido.getDescripcion(); List<String> emailsInvitados = new ArrayList<String>(); for (UsuarioXRecorrido usuarioRecorrido : listUsuarioRecorrido) { String emailPosible = usuarioRecorrido.getUsuario().email; if (emailPosible != null && !emailPosible.isEmpty()) { emailsInvitados.add(emailPosible); } } // Si alguno de los invitados tiene email if (emailsInvitados.size() > 0) { // Recorrido Frecuente if (recorrido.getTipo() == 0) { String horaFrecuente = recorrido.getHoraFrecuente(); String diaFrecuente = recorrido.getDiaFrecuente(); ICatalogoNotificaciones icn = CatalogoNotificaciones.getICatalogoInstance(); icn.notificacionInvitacionRecorridoFrecuente( usuarioInvita, nombreRecorrido, lugarInicio, lugarFin, descripcion, horaFrecuente, diaFrecuente, emailsInvitados); } // Recorrido Recreacion else if (recorrido.getTipo() == 1) { SimpleDateFormat sdf = new SimpleDateFormat("dd MMM, yyyy"); String horaRecreacion = recorrido.getHoraFrecuente(); String fechaInicio = sdf.format(ruta.getFechaInicioRuta()); String fechaFin = sdf.format(ruta.getFechaFinRuta()); ICatalogoNotificaciones icn = CatalogoNotificaciones.getICatalogoInstance(); icn.notificacionInvitacionRecorridoRecreacion( usuarioInvita, nombreRecorrido, lugarInicio, lugarFin, descripcion, horaRecreacion, fechaInicio, fechaFin, emailsInvitados); } } }
public static Result detallesRecorridos() { RecorridoDAO recorridoDAO = new RecorridoDAO(); // ojo ajustar List<Recorrido> lstRecorridos = recorridoDAO.listarRecorridos(); Form<FormularioConsultaRecorrido> form = Form.form(FormularioConsultaRecorrido.class).bindFromRequest(); if (form.hasErrors()) { flash("error", "Se encontraron errores al consultar el recorrido."); return badRequest( views.html.recorridosConsulta.render( Form.form(FormularioConsultaRecorrido.class), lstRecorridos, null, null)); } else { FormularioConsultaRecorrido formularioConsultaRecorrido = form.get(); Recorrido recorrido = recorridoDAO.consultarRecorridoPorId(formularioConsultaRecorrido.idRecorrido); FormularioRecorrido formRecorrido = new FormularioRecorrido(); formRecorrido.tipoRecorrido = String.valueOf(recorrido.getTipo()); formRecorrido.nombre = recorrido.getNombre(); formRecorrido.descripcion = recorrido.getDescripcion(); formRecorrido.horaFrecuente = recorrido.getHoraFrecuente(); String diasFrecuentes = recorrido.getDiaFrecuente(); formRecorrido.diaFrecuente = new ArrayList<String>(); if (diasFrecuentes != null) { String[] arrDias = diasFrecuentes.split(","); for (int i = 0; i < arrDias.length; i++) { formRecorrido.diaFrecuente.add(arrDias[i]); } } formRecorrido.fechaInicioRuta = String.valueOf(recorrido.getLstRuta().get(0).getFechaInicioRuta()); formRecorrido.fechaFinRuta = String.valueOf(recorrido.getLstRuta().get(0).getFechaFinRuta()); formRecorrido.latitudInicio = String.valueOf(recorrido.getLstRuta().get(0).getLatitudInicio()); formRecorrido.longitudInicio = String.valueOf(recorrido.getLstRuta().get(0).getLongitudInicio()); formRecorrido.latitudFin = String.valueOf(recorrido.getLstRuta().get(0).getLatitudFin()); formRecorrido.longitudFin = String.valueOf(recorrido.getLstRuta().get(0).getLongitudFin()); formRecorrido.lugarInicio = recorrido.getLstRuta().get(0).getLugarInicio(); formRecorrido.lugarFin = recorrido.getLstRuta().get(0).getLugarFin(); formRecorrido.lstAmigos = new ArrayList<String>(); Boolean existe = false; User usuario = Application.getLocalUser(session()); for (UsuarioXRecorrido usuarioRecorrido : recorrido.getLstUsuarioXRecorrido()) { formRecorrido.lstAmigos.add(usuarioRecorrido.getUsuario().name); if (usuario.id == usuarioRecorrido.getUsuario().id) existe = true; } formRecorrido.idRecorrido = recorrido.getIdRecorrido(); return ok(views.html.recorridosDetalle.render(formRecorrido, existe)); } }
/** * @param recorrido * @param seUnio */ private static void notificarCambioParticipacionRecorrido(Recorrido recorrido, boolean seUnio) { EstadoParticipacion estadoParticipacion = seUnio ? ICatalogoNotificaciones.EstadoParticipacion.UNIDO_A_RECORRIDO : ICatalogoNotificaciones.EstadoParticipacion.RETIRADO_DE_RECORRIDO; User usuarioSession = Application.getLocalUser(session()); Ruta ruta = recorrido.getLstRuta().get(0); String emailUsuario = usuarioSession.email; String nombreUsuario = usuarioSession.name; String nombreRecorrido = recorrido.getNombre(); String lugarInicio = ruta.getLugarInicio(); String lugarFin = ruta.getLugarFin(); String descripcion = recorrido.getDescripcion(); if (emailUsuario != null && !emailUsuario.isEmpty()) { // Recorrido Frecuente if (recorrido.getTipo() == 0) { String horaFrecuente = recorrido.getHoraFrecuente(); String diaFrecuente = recorrido.getDiaFrecuente(); ICatalogoNotificaciones icn = CatalogoNotificaciones.getICatalogoInstance(); icn.notificacionCambioParticipacionRecorridoFrecuente( estadoParticipacion, emailUsuario, nombreUsuario, nombreRecorrido, lugarInicio, lugarFin, descripcion, horaFrecuente, diaFrecuente); } // Recorrido Recreacion else if (recorrido.getTipo() == 1) { SimpleDateFormat sdf = new SimpleDateFormat("dd MMM, yyyy"); String horaRecreacion = recorrido.getHoraFrecuente(); String fechaInicio = sdf.format(ruta.getFechaInicioRuta()); String fechaFin = sdf.format(ruta.getFechaFinRuta()); ICatalogoNotificaciones icn = CatalogoNotificaciones.getICatalogoInstance(); icn.notificacionCambioParticipacionRecorridoRecreacion( estadoParticipacion, emailUsuario, nombreUsuario, nombreRecorrido, lugarInicio, lugarFin, descripcion, horaRecreacion, fechaInicio, fechaFin); } } }
public static void delete(Long project_id) { Project p = getActiveProject(); if (p == null) { notFound(); } p.delete(getLoggedin()); Application.homepage(); }
/** * Unblock a {@link User}. * * @param username the username of the {@link User} to be unblocked. */ public static void unblockUser(String username) { User user = Database.users().get(username); User mod = Session.user(); if (mod.isModerator() && mod != user) { user.unblock(); flash.success("secure.unlockuserflash"); } Application.showprofile(user.getName()); }
public static Result listarRetosUsuario() { RetoUsuarioDAO retoUsuarioDAO = new RetoUsuarioDAO(); List<RetoUsuario> retos = retoUsuarioDAO.consultarRetosUsuario(Application.getLocalUser(session())); return ok(views.html.retosUsuario.render(retos)); }
public static Result createNewUser() { Form<User> nu = userForm.bindFromRequest(); ObjectNode jsonData = Json.newObject(); String userName = null; try { userName = nu.field("firstName").value() + " " + (nu.field("middleInitial")).value() + " " + (nu.field("lastName")).value(); jsonData.put("userName", userName); jsonData.put("firstName", nu.get().getFirstName()); jsonData.put("middleInitial", nu.get().getMiddleInitial()); jsonData.put("lastName", nu.get().getLastName()); jsonData.put("password", nu.get().getPassword()); jsonData.put("affiliation", nu.get().getAffiliation()); jsonData.put("title", nu.get().getTitle()); jsonData.put("email", nu.get().getEmail()); jsonData.put("mailingAddress", nu.get().getMailingAddress()); jsonData.put("phoneNumber", nu.get().getPhoneNumber()); jsonData.put("faxNumber", nu.get().getFaxNumber()); jsonData.put("researchFields", nu.get().getResearchFields()); jsonData.put("highestDegree", nu.get().getHighestDegree()); JsonNode response = RESTfulCalls.postAPI( Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.ADD_USER, jsonData); // flash the response message Application.flashMsg(response); return redirect(routes.Application.createSuccess()); } catch (IllegalStateException e) { e.printStackTrace(); Application.flashMsg(RESTfulCalls.createResponse(ResponseType.CONVERSIONERROR)); } catch (Exception e) { e.printStackTrace(); Application.flashMsg(RESTfulCalls.createResponse(ResponseType.UNKNOWN)); } return ok(signup.render(nu)); }
@Before static void setConnectedUser() { if (Security.isConnected()) { User user = User.find("byUsername", Security.connected()).first(); if (!user.isAdmin) { flash.error(Messages.get("UserIsNotAuthorized")); Application.index(); } } }
/** Clear new notifications. Notifications will no longer appear as new. */ public static void clearNewNotifications() { User user = Session.user(); for (Notification n : user.getNewNotifications()) { n.unsetNew(); } flash.success("secure.notificationsmarkedasreadflash"); if (!redirectToCallingPage()) { Application.index(0); } }
/** * Delete a notification. * * @param id the id of the notification to be deleted. */ public static void deleteNotification(int id) { User user = Session.user(); Notification n = user.getNotification(id); if (n != null) { n.delete(); flash.success("secure.deletenotificationflash"); } if (!redirectToCallingPage()) { Application.index(0); } }
public static void index(String id) { List<Produit> listeProduit = Produit.find( "select distinct p from Produit p join p.marque as m where m.nomMarque = ?", id) .fetch(); if (listeProduit.isEmpty()) { flash.success("Il n'y a pas de telephone pour cette marque"); Application.index(); } else { render(listeProduit); } }
@Before static void setConnectedUser() { renderArgs.put("shopLogoText", Play.configuration.getProperty("bookshop.logotext")); if (Security.isConnected()) { BookShopUser user = BookShopUser.find("byEmail", Security.connected()).first(); if (user.isAdmin) { renderArgs.put("user", user.fullName); } else { Application.index(); } } }
/** * Block a {@link User}. * * @param username the username of the {@link User} to be unblocked. * @param reason the reason the {@link User} is being blocked. */ public static void blockUser(String username, String reason) { User user = Database.users().get(username); User mod = Session.user(); if (mod.isModerator() && mod != user) { if (reason.equals("")) { reason = "secure.blockreasonerror"; } user.block(reason); flash.success("secure.blockuserflash"); } Application.showprofile(user.getName()); }
/** * Deletes the {@link User} and all it's {@link Question}' {@link Answer}'s {@link Vote}'s. * * <p>Instead of deleting all {@link Entry}'s of a {@link User}, these entries can optionally be * kept in anonymized form by setting their owners to <code>null</code> first. * * @param anonymize whether to anonymize or just plain delete the user's entries * @throws Throwable */ public static void deleteUser(boolean anonymize) throws Throwable { User user = Session.user(); if (anonymize) { user.anonymize(true); } else { Cache.delete("index.questions"); } user.delete(); flash.success("secure.userdeletedflash"); Secure.logout(); Application.index(0); }
public static Result isEmailExisted() { JsonNode json = request().body().asJson(); String email = json.path("email").asText(); ObjectNode jsonData = Json.newObject(); JsonNode response = null; try { jsonData.put("email", email); response = RESTfulCalls.postAPI( Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.IS_EMAIL_EXISTED, jsonData); Application.flashMsg(response); } catch (IllegalStateException e) { e.printStackTrace(); Application.flashMsg(RESTfulCalls.createResponse(ResponseType.CONVERSIONERROR)); } catch (Exception e) { e.printStackTrace(); Application.flashMsg(RESTfulCalls.createResponse(ResponseType.UNKNOWN)); } return ok(response); }
/** * Load an XML database file * * @param xml the XML database file to be loaded. This field is mandatory. */ public static void loadXML(@Required File xml) { if (!Session.user().isModerator()) { Application.index(0); } if (xml == null) { flash.error("secure.xmlselecterror"); Application.admin(); } try { Database.importXML(xml); flash.success("secure.xmlloadflash"); } catch (Throwable e) { flash.error("secure.xmlloaderror", e.getMessage()); e.printStackTrace(); Application.admin(); } if (xml != null) { xml.delete(); } Application.index(0); }
/** * Checks the status of a friendship * * @param id the user to check friendship status with * @return a string representing the status */ public String checkFriendship(Long id) { User current = Application.user(); if (Application.user().id == id) { return ""; } Relationship r1 = Relationship.find( "SELECT r FROM Relationship r where r.from = ?1 AND r.to = ?2", current, this) .first(); Relationship r2 = Relationship.find( "SELECT r FROM Relationship r where r.to = ?1 AND r.from = ?2", current, this) .first(); if (r1 != null) { if (r1.accepted) { return "Friends"; } if (r1.requested) { return "Friendship Requested"; } } return "Request Friendship"; }
/** * Delete past race * * @return */ public static Result delete(Long raceId) { // Delete race PastRace pastRace = PastRace.find.byId(Long.valueOf(raceId)); if (pastRace == null || !pastRace.user.equals(getConnectedUser())) { Logger.error("Past race save forbidden"); return forbidden(); } else { pastRace.delete(); } // Redirect to user homepage return redirect( controllers.user.routes.UserController.index(Application.getConnectedUser().username)); }
/** * Follow notification. * * @param id the id of the notification. */ public static void followNotification(int id) { User user = Session.user(); Notification notification = user.getNotification(id); if (notification != null) { notification.unsetNew(); Entry about = notification.getAbout(); if (about instanceof Answer) { ActionDefinition action = reverse(); Answer answer = (Answer) about; Application.question(answer.getQuestion().id()); redirect(action.addRef("answer-" + answer.id()).toString()); } else if (about instanceof Question) { Application.question(((Question) about).id()); } else if (about instanceof Comment) { ActionDefinition action = reverse(); Comment comment = (Comment) about; Application.question(comment.getQuestion().id()); redirect(action.addRef("comment-" + comment.id()).toString()); } } else if (!redirectToCallingPage()) { Application.notifications(0); } }
/** * REST endpoint returns a json array containing metadata about the currently logged in user's * uploaded files. * * @return json containing file upload ids and filenames */ public Result listUploads() { List<UserUpload> uploadList = UserUpload.findUploadsByUserId(Application.getCurrentUserId()); ObjectNode response = Json.newObject(); ArrayNode uploads = response.putArray("uploads"); for (UserUpload userUpload : uploadList) { ObjectNode upload = Json.newObject(); upload.put("id", userUpload.id); upload.put("filename", userUpload.fileName); uploads.add(upload); } return ok(uploads); }
private static void startStream(List<String> terms) throws TwitterException { if (twitter != null) { twitter.cleanUp(); } if (esClient != null) { esClient.close(); esClient = null; } play.Configuration pconf = Play.application().configuration(); String elasticSearchCluster = pconf.getString("tweet.elasticsearch.cluster.name"); if (elasticSearchCluster != null) { Logger.info("Configuring ElasticSearch..."); Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", elasticSearchCluster).build(); esClient = new TransportClient(settings) .addTransportAddress( new InetSocketTransportAddress( pconf.getString("tweet.elasticsearch.transport.host"), pconf.getInt("tweet.elasticsearch.transport.port"))); } else { esClient = null; } twitter4j.conf.Configuration tconf = Application.getTwitterConfiguration(); TwitterStreamFactory tf = new TwitterStreamFactory(tconf); twitter = tf.getInstance(); StatusListener l = new TweetListener( terms, esClient, pconf.getString("tweet.elasticsearch.index"), pconf.getString("tweet.elasticsearch.type")); twitter.addListener(l); String[] tracks = new String[terms.size()]; StringBuffer termsString = new StringBuffer(); for (int i = 0; i < terms.size(); i++) { tracks[i] = terms.get(i); if (i != 0) termsString.append(","); termsString.append(terms.get(i)); } FilterQuery q = new FilterQuery().track(tracks); twitter.filter(q); Logger.info("Starting listening for tweets using terms " + termsString.toString() + "..."); }
public static void activate(String uuid) { Logger.info("用户开始进行激活,uuid" + uuid); User user = User.find("uuid", uuid).first(); Logger.info("start activate:" + user.activated + "id:" + user.id); if (user != null) { // 激活成功 user.activated = true; user.save(); Logger.info("user id:" + user.id); render("@activatesuccess"); } else { Application.index(); } }
public static void at(String location, String name, String address) { if (location != null && name != null && address != null && !location.equals("") && !name.equals("") && !address.equals("")) { new Post( user(), new Date().toString(), HTML.htmlEscape("Checked in at: " + name + "\n" + address)) .save(); Application.news(null); } else { redirect("/checkin"); } }