@Provides(type = Core.Type.SECURITY, with = Core.With.AUTHORIZATION_FAILURE) public static Result handleAuthFailure(Node node, String withType, Map<String, Object> args) throws NodeLoadException, ModuleException { User user = SecurityEventGenerator.triggerCurrentUserInterceptor(); SecurityEventGenerator.triggerBeforeAuthorizationFailure(user); try { String unauthorizedPage = Settings.load().getValue(CoreSettingsHelper.Keys.UNAUTHORIZED_PAGE); try { if (StringUtils.isNotBlank(unauthorizedPage)) { Content content = CoreLoader.loadAndDecorateNode(unauthorizedPage, 0); if (user != null) { return Controller.forbidden(content); } else { return Controller.unauthorized(content); } } } catch (NodeNotFoundException | NodeLoadException | ModuleException e) { ExceptionUtil.assertExceptionHandling(e); return CoreLoader.redirectToPageLoadErrorPage(); } if (user != null) { Logger.warn("Using fallback forbidden handling, sending 403 with no content"); return Controller.forbidden(); } else { Logger.warn("Using fallback unauthorized handling, sending 401 with no content"); return Controller.unauthorized(); } } finally { SecurityEventGenerator.triggerAfterAuthorizationFailure(user); } }
/** * Saves user response. * * <p>This action builds a Response object from request by creating and parsing DynamicForm data. * Built Response object is then validated and returned back to client as a JSON object. * * <p>If response object is not valid - returns BAD_REQUEST status code to client as well as JSON * object with validation errors. * * <p>If response data is outdated - returns BAD_REQUEST status code to client as well as JSON * object with global errors. * * <p>This action requires CSRF token. * * @return 200-OK with saved response object as JSON 400-BAD_REQUEST with errors as JSON */ @RequireCSRFCheck @Transactional public Result createResponse() { DynamicForm form = form().bindFromRequest(); List<Field> activeFields = fieldService.getAllActiveFields(); Response response = new Response(form.data(), activeFields); Logger.info("User send response: {}.", response); List<ValidationError> errors = response.validate(); if (errors != null) { errors.forEach(form::reject); Logger.warn("User response contains validation errors: {}.", errors); return badRequest(form.errorsAsJson()); } Response result = responseService.saveResponse(response); if (result == null) { form.reject("global", "Some options are outdated!"); Logger.warn("Users response contains outdated data."); return badRequest(form.errorsAsJson()); } else { Logger.info("Response saved: {}.", response); return ok(toJson(response)); } }
public static void log( String level, String clazz, String clazzSimpleName, String packageName, String method, String signature, String fileName, String relativeFileName, int line, Object[] args) { Throwable throwable = null; String pattern = ""; if (args[0] instanceof Throwable) { throwable = (Throwable) args[0]; pattern = (String) args[1]; } else { pattern = (String) args[0]; } pattern = stringFormatPrefix + pattern; Object[] betterLogsArgs = new Object[argsPrefix.size()]; int i = 0; for (String argName : argsPrefix) { if ("class".equals(argName)) betterLogsArgs[i] = clazz; if ("simpleClass".equals(argName)) betterLogsArgs[i] = clazzSimpleName; if ("package".equals(argName)) betterLogsArgs[i] = packageName; if ("method".equals(argName)) betterLogsArgs[i] = method; if ("file".equals(argName)) betterLogsArgs[i] = fileName; if ("line".equals(argName)) betterLogsArgs[i] = line; if ("relativeFile".equals(argName)) betterLogsArgs[i] = relativeFileName; if ("signature".equals(argName)) betterLogsArgs[i] = signature; i++; } if ("trace".equals(level)) { Logger.trace(pattern, handleLogArgs(betterLogsArgs, args, 1)); } else if ("debug".equals(level)) { if (throwable != null) Logger.debug(throwable, pattern, handleLogArgs(betterLogsArgs, args, 2)); else Logger.debug(pattern, handleLogArgs(betterLogsArgs, args, 1)); } else if ("info".equals(level)) { if (throwable != null) Logger.info(throwable, pattern, handleLogArgs(betterLogsArgs, args, 2)); else Logger.info(pattern, handleLogArgs(betterLogsArgs, args, 1)); } else if ("warn".equals(level)) { if (throwable != null) Logger.warn(throwable, pattern, handleLogArgs(betterLogsArgs, args, 2)); else Logger.warn(pattern, handleLogArgs(betterLogsArgs, args, 1)); } else if ("error".equals(level)) { if (throwable != null) Logger.error(throwable, pattern, handleLogArgs(betterLogsArgs, args, 2)); else Logger.error(pattern, handleLogArgs(betterLogsArgs, args, 1)); } else if ("fatal".equals(level)) { if (throwable != null) Logger.fatal(throwable, pattern, handleLogArgs(betterLogsArgs, args, 2)); else Logger.fatal(pattern, handleLogArgs(betterLogsArgs, args, 1)); } }
@Override public void onApplicationStart() { if (!isDisabled() && Play.mode.isProd()) { try { checkEvolutionsState(); } catch (InvalidDatabaseRevision e) { Logger.warn(""); Logger.warn("Your database is not up to date."); Logger.warn("Use `play evolutions` command to manage database evolutions."); throw e; } } }
public static boolean isModified(String etag, long last, HttpRequest nettyRequest) { if (nettyRequest.containsHeader(IF_NONE_MATCH)) { final String browserEtag = nettyRequest.getHeader(IF_NONE_MATCH); if (browserEtag.equals(etag)) { return false; } return true; } if (nettyRequest.containsHeader(IF_MODIFIED_SINCE)) { final String ifModifiedSince = nettyRequest.getHeader(IF_MODIFIED_SINCE); if (!StringUtils.isEmpty(ifModifiedSince)) { try { Date browserDate = Utils.getHttpDateFormatter().parse(ifModifiedSince); if (browserDate.getTime() >= last) { return false; } } catch (ParseException ex) { Logger.warn("Can't parse HTTP date", ex); } return true; } } return true; }
public static Integer readImageOrientation(File imageFile) { Metadata metadata = null; try { metadata = ImageMetadataReader.readMetadata(imageFile); } catch (Exception e) { // Any exception here is handled as if image // format doesn't support EXIF return null; } Directory directory = metadata.getDirectory(ExifIFD0Directory.class); JpegDirectory jpegDirectory = (JpegDirectory) metadata.getDirectory(JpegDirectory.class); int orientation = 1; try { orientation = directory.getInt(ExifIFD0Directory.TAG_ORIENTATION); /*int width = jpegDirectory.getImageWidth(); int height = jpegDirectory.getImageHeight();*/ } catch (Exception e) { Logger.warn("Could not get orientation"); } return orientation; }
@Override public void onConfigurationRead() { disabled = "true".equals(Play.configuration.getProperty("betterlogs.disabled")); if (disabled) Logger.warn( "BetterLogs is disabled. The classes are no more enhanced. If you enable it again, don't forget to clean your app before to force Play to enhance all the classes."); ArrayList<String> newArgsPrefix = new ArrayList<String>(); String prefix = Play.configuration.getProperty("betterlogs.prefix", "[%relativeFile:%line] %method() ::"); Matcher matcher = PREFIX_PATTERN.matcher(prefix); StringBuffer sb = new StringBuffer(); if (matcher.find()) { int lastEnd = 0; do { newArgsPrefix.add(matcher.group().substring(1)); sb.append(prefix.substring(lastEnd, matcher.start()).replace("%", "%%")).append("%s"); lastEnd = matcher.end(); } while (matcher.find()); sb.append(prefix.substring(lastEnd)); } String trailingSpaces = Play.configuration.getProperty("betterlogs.prefix.trailingSpaces", "1ws"); matcher = TRAILING_SPACES_PATTERN.matcher(trailingSpaces); if (matcher.matches()) { int nb = Integer.parseInt(matcher.group(1)); char c = "t".equals(matcher.group(2)) ? '\t' : ' '; while (nb > 0) { sb.append(c); nb--; } } argsPrefix = newArgsPrefix; stringFormatPrefix = sb.toString(); }
/** Allow some code to run very early in Play - Use with caution ! */ public static void initStaticStuff() { // Play! plugings Enumeration<URL> urls = null; try { urls = Play.class.getClassLoader().getResources("play.static"); } catch (Exception e) { } while (urls != null && urls.hasMoreElements()) { URL url = urls.nextElement(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { try { Class.forName(line); } catch (Exception e) { Logger.warn("! Cannot init static: " + line); } } } catch (Exception ex) { Logger.error(ex, "Cannot load %s", url); } } }
protected String getEmailTemplate(final String template, final String email, String promoCode) { Class<?> cls = null; String ret = null; try { cls = Class.forName(template); } catch (ClassNotFoundException e) { Logger.warn( "Template: '" + template + "' was not found! Trying to use English fallback template instead."); } if (cls == null) { try { cls = Class.forName(template); } catch (ClassNotFoundException e) { Logger.error("Fallback template: '" + template + "' was not found either!"); } } if (cls != null) { Method htmlRender = null; try { String url = controllers.Application.APPLICATION_BASE_URL + "/signup-code/" + promoCode; htmlRender = cls.getMethod("render", String.class, String.class); ret = htmlRender.invoke(null, email, url).toString(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return ret; }
protected String getEmailTemplate(final String template, final String name) { Class<?> cls = null; String ret = null; try { cls = Class.forName(template); } catch (ClassNotFoundException e) { Logger.warn( "Template: '" + template + "' was not found! Trying to use English fallback template instead."); } if (cls == null) { try { cls = Class.forName(template); } catch (ClassNotFoundException e) { Logger.error("Fallback template: '" + template + "' was not found either!"); } } if (cls != null) { Method htmlRender = null; try { htmlRender = cls.getMethod("render", String.class); ret = htmlRender.invoke(null, name).toString(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return ret; }
private List<Chart> getCharts( DataSource datasource, ChartType type, List<Region> regions, Map<String, String> parameters) { final List<Chart> result = Lists.newLinkedList(); for (final ChartTypeBuilder builder : builders) { try { List<Chart> charts = builder.build(datasource, type, regions, parameters); if (!charts.isEmpty()) { result.addAll(charts); } } catch (Exception e) { Logger.warn( String.format( "caught exception while building charts (type %s," + " regions %s, parameters %s)", type, regions, parameters), e); } } // make sure charts are sorted by region // https://github.com/uq-eresearch/aorra/issues/44 Collections.sort( result, new Comparator<Chart>() { @Override public int compare(Chart c1, Chart c2) { return getRegion(c1).compareTo(getRegion(c2)); } private Region getRegion(Chart c) { return c.getDescription().getRegion(); } }); return result; }
protected static SortedSet<Widget> findAllWidgets() { String ext = ".java"; Logger.debug("Scanning for widgets..."); SortedSet<Widget> all = new TreeSet<Widget>(); for (VirtualFile f : Play.javaPath) { VirtualFile widgets = f.child("widgets"); if (widgets.exists()) { Logger.debug("Searching " + widgets.getName()); for (VirtualFile pkg : widgets.list()) { if (pkg != null && pkg.isDirectory()) { for (VirtualFile w : pkg.list()) { if (w.getName().endsWith(ext)) { String className = w.getName().substring(0, w.getName().length() - ext.length()); String widgetName = pkg.getName() + "." + className; if (isWidget(widgetName)) try { all.add(getWidget(widgetName)); Logger.debug("Found " + widgetName); } catch (InvalidWidgetException e) { Logger.error(e, widgetName + " is not a widget?!"); } else Logger.warn(widgetName + " is not a widget."); } } } } } } Logger.info("Found " + all.size() + " widgets"); return all; }
public static void populateConfiguration(OGraphDatabase db) throws IOException, ConfigurationException { Logger.info("Load initial configuration..."); InputStream is; if (Play.application().isProd()) is = Play.application().resourceAsStream(CONFIGURATION_FILE_NAME); else is = new FileInputStream(Play.application().getFile("conf/" + CONFIGURATION_FILE_NAME)); HierarchicalINIConfiguration c = new HierarchicalINIConfiguration(); c.setEncoding("UTF-8"); c.load(is); CharSequence doubleDot = ".."; CharSequence dot = "."; Set<String> sections = c.getSections(); for (String section : sections) { Class en = PropertiesConfigurationHelper.configurationSections.get(section); if (en == null) { Logger.warn(section + " is not a valid configuration section, it will be skipped!"); continue; } SubnodeConfiguration subConf = c.getSection(section); Iterator<String> it = subConf.getKeys(); while (it.hasNext()) { String key = (it.next()); Object value = subConf.getString(key); key = key.replace( doubleDot, dot); // bug on the Apache library: if the key contain a dot, it will be doubled! try { PropertiesConfigurationHelper.setByKey(en, key, value); } catch (Exception e) { Logger.warn( "Error loading initial configuration: Section " + section + ", key: " + key + ", value: " + value, e); } } } is.close(); Logger.info("...done"); }
@Transactional protected static ReviewComment saveReviewComment( Resource target, User sender, Content content, String messageID, Address[] allRecipients) throws MessagingException, IOException, NoSuchAlgorithmException { ReviewComment comment; CommentThread thread = CommentThread.find.byId(Long.valueOf(target.getId())); if (thread == null) { throw new IllegalArgumentException(); } comment = new ReviewComment(); comment.setContents(content.body); comment.author = new UserIdent(sender); comment.thread = thread; comment.save(); Map<String, Attachment> relatedAttachments = saveAttachments(content.attachments, comment.asResource()); if (new ContentType(content.type).match(MimeType.HTML)) { // replace cid with attachments comment.setContents(replaceCidWithAttachments(comment.getContents(), relatedAttachments)); comment.update(); } new OriginalEmail(messageID, comment.asResource()).save(); // Add the event if (thread.isOnPullRequest()) { addEvent( NotificationEvent.forNewComment(sender, thread.pullRequest, comment), allRecipients, sender); } else { try { String commitId; if (thread instanceof CodeCommentThread) { commitId = ((CodeCommentThread) thread).commitId; } else if (thread instanceof NonRangedCodeCommentThread) { commitId = ((NonRangedCodeCommentThread) thread).commitId; } else { throw new IllegalArgumentException(); } addEvent( NotificationEvent.forNewCommitComment(target.getProject(), comment, commitId, sender), allRecipients, sender); } catch (Exception e) { Logger.warn("Failed to send a notification", e); } } return comment; }
public static List<Song> byKeywords(String keywords) { try { List<Song> songs = Song.find("byKeywordsIlike", "%" + keywords + "%").fetch(); return songs; } catch (Exception x) { Logger.warn(x, "曲リストの準備中です。"); return null; } }
static boolean authenticate(String username, String password) { Logger.info("Authenticating %s ...", username); boolean valid = (User.authenticate(username, password) != null); if (!valid) { Logger.warn("Invalid combination of username (%s) and password: %s", username, request.path); } else { Logger.info("Successfully authenticated user '%s'", username); } return valid; }
private static Text getTextByType(int type) { List<Text> texts = Text.find.where().eq("type", type).findList(); int size = texts.size(); if (size != 0) { int i = Random.randomInt(size - 1); return texts.get(i); } Logger.warn("Text.getTextByType - found no texts"); return null; }
/** * Check that no SQL database is configured. * * @param p Play configuration. * @return <code>true</code> if no Play SQL configuration is defined, <code>false</code> * otherwise. * @since 2011.09.07 */ private boolean checkPlaySQLConfig(Properties p) { // We configure the Cloud Foundry SQL database only if no other Play DB // is configured. if (p.containsKey("db") || p.containsKey("db.url")) { Logger.warn( "[CloudFoundry] A SQL database configuration already exists. It will not be overriden."); return false; } return true; }
public static List<Song> byKeywords(String keywords, boolean isVocaloid, boolean isToho) { try { List<Song> songs = Song.find( "byKeywordsIlikeAndIsVocaloidAndIsToho", "%" + keywords + "%", isVocaloid, isToho) .fetch(); return songs; } catch (Exception x) { Logger.warn(x, "曲リストの準備中です。"); return null; } }
@With({ AdminCredentialWrapFilter.class, ConnectToDBFilter.class, }) @BodyParser.Of(BodyParser.Json.class) public static Result signUp() { Logger.trace("Method Start"); Http.RequestBody body = request().body(); JsonNode bodyJson = body.asJson(); Logger.trace("signUp bodyJson: " + bodyJson); if (bodyJson == null) return badRequest( "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json"); // check and validate input if (!bodyJson.has("username")) return badRequest("The 'username' field is missing"); if (!bodyJson.has("password")) return badRequest("The 'password' field is missing"); // extract mandatory fields JsonNode nonAppUserAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER); JsonNode privateAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER); JsonNode friendsAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER); JsonNode appUsersAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER); String username = (String) bodyJson.findValuesAsText("username").get(0); String password = (String) bodyJson.findValuesAsText("password").get(0); if (privateAttributes != null && privateAttributes.has("email")) { // check if email address is valid if (!Util.validateEmail((String) privateAttributes.findValuesAsText("email").get(0))) return badRequest("The email address must be valid."); } // try to signup new user try { UserService.signUp( username, password, nonAppUserAttributes, privateAttributes, friendsAttributes, appUsersAttributes); } catch (UserAlreadyExistsException e) { Logger.debug("signUp", e); return badRequest(username + " already exists"); } catch (Throwable e) { Logger.warn("signUp", e); if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e)); else return internalServerError(e.getMessage()); } Logger.trace("Method End"); return created(); }
/** * check if user is at least in one group * * @param groupname One or more group names (separated by comma) */ static boolean check(String groupname) { String username = connected(); if (username == null) { Logger.warn("User is not logged in, cannot check group membership."); return false; } // TODO: cache user info to avoid look up on every single secure.cache tag User user = User.findByUserName(username); Logger.debug("check if user %s is member of group %s", user, groupname); if (user != null) { String[] reqGroup = groupname.split(","); if (user.isMemberOfAtLeastOne(reqGroup)) { return true; } else { // Logger.debug("User '%s' is not assigned to group '%s': %s", username, groupname, // request.path); } } else { Logger.warn("Unknown user name '%s' specified: %s", username, request.path); } return false; }
protected void onStart() { if (this.auth.hasUserService()) { final String oldServiceClass = this.auth.getUserService().getClass().getName(); Logger.warn( "A user service was already registered - replacing the old one (" + oldServiceClass + ") with the new one (" + getClass().getName() + "), " + "however this might hint to a configuration problem if this is a production environment."); } this.auth.setUserService(this); }
public static void removeEventStream(String username, EventStream<ChatEvent.Event> eventStream) { synchronized (eventStreamsMap) { if (eventStreamsMap.containsKey(username)) { List<EventStream<Event>> streams = eventStreamsMap.get(username); streams.remove(eventStream); if (streams.size() == 0) { eventStreamsMap.remove(username); // NOTE: ここでオフラインイベント発生でいいんじゃないか? } } else { Logger.warn("Failed to releaseEventStream. username: %s", username); } } }
public void addParams(String params) { if (params == null || params.length() < 1) { return; } params = params.substring(1, params.length() - 1); for (String param : params.split(",")) { Matcher matcher = paramPattern.matcher(param); if (matcher.matches()) { staticArgs.put(matcher.group(1), matcher.group(2)); } else { Logger.warn("Ignoring %s (static params must be specified as key:'value',...)", params); } } }
public static Text create( int type, int chronology, int prerequisite, String text, String sound_url, int lines) { if (text == null) { return null; } Text item = new Text(type, text, sound_url, prerequisite, chronology, lines); try { item.save(); } catch (PersistenceException pe) { Logger.warn("Text.create - caught PersistenceException: " + pe.getMessage()); Text text_comp = Text.find.where().eq("text", text).findUnique(); if (text_comp != null) { Logger.warn("Text.create - found alternative \"Text\""); return text_comp; } Logger.error("Text.create - no alternative \"Text\" found"); return null; } return item; }
/** * Configuration of MongoDB, if at least one CloudFoundry MongoDB service is bound to the * instance. * * @param p Play configuration. * @since 2011.07.11 */ private void mongoDBServiceConfig(Properties p) { if (!checkServiceList(mongoServices, "MongoDB")) { return; } MongoServiceInfo mongoServiceInfo = mongoServices.get(0); // We configure the Cloud Foundry Morphia plugin only if it is not configured yet. if (p.containsKey("morphia.db.host")) { Logger.warn( "[CloudFoundry] A Morphia configuration already exists. It will not be overriden."); } else { morphiaPluginConfig(p, mongoServiceInfo); } // We configure the Cloud Foundry MongoDB plugin only if it is not configured yet. if (p.containsKey("mongo.host")) { Logger.warn( "[CloudFoundry] A MongoDB configuration already exists. It will not be overriden."); } else { mongoPluginConfig(p, mongoServiceInfo); } }
/** * 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(); }
@JsonProperty("nickname") public String getNickname() { if (nickname == null) try { List<UserInfo> profileInfo = cookieToList(UserInfo.class, Post.request().cookie(PROFILE_COOKIE)); this.nickname = (profileInfo == null || profileInfo.isEmpty()) ? NICKNAME_DEFAULT : profileInfo.get(0).getNickname(); Logger.debug(profileInfo.toString()); } catch (IOException e) { Logger.warn("Unable to read cookie; using default"); } return (nickname == null) ? NICKNAME_DEFAULT : nickname; }
private static synchronized boolean isOracleDialectInUse() { boolean isOracle = false; String jpaDialect = Play.configuration.getProperty("jpa.dialect"); if (jpaDialect != null) { try { Class<?> dialectClass = Play.classloader.loadClass(jpaDialect); // Oracle 8i dialect is the base class for oracle dialects (at least for now) isOracle = org.hibernate.dialect.Oracle8iDialect.class.isAssignableFrom(dialectClass); } catch (ClassNotFoundException e) { // swallow Logger.warn("jpa.dialect class %s not found", jpaDialect); } } return isOracle; }
@Override public void run() { while (true) { try { if (!queue.isEmpty()) { for (Future<?> task : new HashSet<Future<?>>(queue.keySet())) { if (task.isDone()) { executor.submit(queue.get(task)); queue.remove(task); } } } Thread.sleep(10); } catch (InterruptedException ex) { Logger.warn(ex, "While waiting for task completions"); } } }