public class CreateProjectServiceOperation extends ServiceOperation {
  private static final Logger.ALogger logger = Logger.of(CreateProjectServiceOperation.class);

  private ProjectRepository repository;

  @Inject
  public CreateProjectServiceOperation(ProjectRepository repository) {
    this.repository = repository;
  }

  @Override
  protected JsonNode doExecute(JsonNode jsonRequest) {
    Project project = new Project();

    project.setStatus(jsonRequest.findPath("status").textValue());

    project.setInfo(jsonRequest.findPath("info").textValue());

    project.setTitle(jsonRequest.findPath("title").textValue());

    project.setSummary(jsonRequest.findPath("summary").textValue());

    repository.set(project);

    return jsonRequest;
  }
}
Ejemplo n.º 2
0
public class CreateProjectOperation {
  private static final Logger.ALogger LOG = Logger.of(CreateProjectOperation.class);

  private final ProjectRepository projectRepository;
  private final EmailService emailService;

  @Inject
  public CreateProjectOperation(ProjectRepository projectRepository, EmailService emailService) {
    this.projectRepository = projectRepository;
    this.emailService = emailService;
  }

  public ServiceResult execute(final JsonNode jsonRequest) {
    final Principal principal =
        (Principal) Http.Context.current().args.get(Principal.class.getName());
    final Project project = Json.fromJson(jsonRequest, Project.class);

    final Claims claims = principal.getClaims();
    final ProjectMember ownerMember = new ProjectMember();

    ownerMember.setUserId(new Integer((String) claims.get("id")));
    ownerMember.setForename((String) claims.get("forename"));
    ownerMember.setSurname((String) claims.get("surname"));
    ownerMember.setEmail((String) claims.get("email"));
    ownerMember.setRole(ProjectMember.Role.OWNER);

    project.setOwner(ownerMember);

    final Project savedProject = projectRepository.set(project);

    // TODO email project members

    return new ServiceResult(Json.toJson(savedProject));
  }
}
Ejemplo n.º 3
0
public class CrudManager {

  private static ALogger log = Logger.of(CrudManager.class);

  DynamicRestController restController;

  GlobalSettings global;

  InjectAdapter injections = InjectAdapter.getInstance();

  public CrudManager(GlobalSettings global) {
    this.global = global;
  }

  public void initialize(Application app) {
    if (log.isDebugEnabled()) log.debug("initialize <-");
    KeyConverterRegistry converters = new ClasspathScanningKeyConverterRegistry(app);
    ModelRegistry models = new ClasspathScanningModelRegistry(app, converters);
    CrudControllerRegistry crudControllers =
        new ClasspathScanningControllerRegistry(app, global, models);
    restController = new DynamicRestController(crudControllers, models);
  }

  @SuppressWarnings("unchecked")
  public <A> A getController(Class<A> type) throws Exception {
    if (DynamicRestController.class.equals(type)) return (A) restController;

    return injections.getInstance(type);
  }
}
Ejemplo n.º 4
0
/** Created by brianzhao on 10/20/15. */
public class IPAction extends play.mvc.Action.Simple {
  private static final org.slf4j.Logger logger = Logger.of(IPAction.class).underlying();

  public F.Promise<Result> call(Http.Context ctx) throws Throwable {
    logger.debug(ctx.request().remoteAddress());
    return delegate.call(ctx);
  }
}
/**
 * Provides the interface between auth plugin and application model layer.
 *
 * <p>The application needs a registered {@link Plugin} which extends {@link AuthServicePlugin} in
 * order to provide authentication functionality.
 *
 * @author Sebastian Sachtleben
 */
public abstract class AuthServicePlugin extends Plugin implements AuthService {

  /** The logger for {@link AuthServicePlugin} class. */
  private static final Logger.ALogger log = Logger.of(AuthServicePlugin.class);

  /** Keeps {@link Application} instance. */
  protected Application app;

  /**
   * Default contructor for {@link AuthServicePlugin} and will be invoked during application
   * startup.
   *
   * @param app The {@link Application} instance.
   */
  public AuthServicePlugin(final Application app) {
    this.app = app;
  }

  /**
   * Provides the current {@link Application} instance.
   *
   * @return The {@link Application} instance.
   */
  protected Application app() {
    return app;
  }

  /*
   * (non-Javadoc)
   *
   * @see play.Plugin#onStart()
   */
  @Override
  public void onStart() {
    if (Auth.hasService()) {
      log.warn(
          "A auth service was already registered - replacing the old one, however this might hint to a configuration problem if this is a production environment.");
    }
    Auth.service(this);
  }

  /*
   * (non-Javadoc)
   *
   * @see play.Plugin#onStop()
   */
  @Override
  public void onStop() {
    Auth.service(null);
  }
}
Ejemplo n.º 6
0
/** Handles the REST requests */
public class RESTApi extends Controller {

  private static final Logger.ALogger logger = Logger.of("application.restApi");

  @Inject RedisAccess redisAccess;

  /**
   * Accepts a JSON message and publishes it on the {@link services.RedisAccess#CHANNEL_MESSAGES}
   * pub/sub channel *
   */
  public Result message() {
    Optional<JsonNode> json = getValidJson(request().body());
    if (!json.isPresent()) {
      return badRequest();
    }
    redisAccess.run(
        jedis -> {
          Long subscribers = jedis.publish(CHANNEL_MESSAGES, json.get().toString());
          logger.debug("message published to {} subscribers", subscribers);
        });
    return ok();
  }

  /** Returns all persisted JSON messages */
  public Result allMessage() {
    List<String> messages =
        redisAccess.get(
            jedis ->
                jedis
                    .lrange(KEY_MESSAGE_LIST, 0, -1)
                    .stream()
                    .map(json -> Message.fromJson(json).message)
                    .collect(toList()));
    return ok(Json.toJson(messages));
  }

  private static Optional<JsonNode> getValidJson(Http.RequestBody body) {
    JsonNode json = body.asJson();
    logger.debug("received json: {}", json);
    try {
      // validates json
      Json.fromJson(json, Message.class);
    } catch (Exception e) {
      logger.warn("Invalid json ({})", e.getCause().getMessage());
      return Optional.empty();
    }
    return Optional.of(json);
  }
}
Ejemplo n.º 7
0
public class Application extends Controller {
  private static final Logger.ALogger logger = Logger.of(Application.class);

  /** */
  public static Result index() throws Exception {
    return ok(views.html.index.render("Welcome!"));
  }

  public static Result upload() {
    try {
      Http.MultipartFormData body = request().body().asMultipartFormData();
      Http.MultipartFormData.FilePart picture = body.getFile("picture");
      if (picture != null) {
        String fileName = picture.getFilename();
        logger.info("Uploading file name: {}", fileName);

        File pictureFile = picture.getFile();
        pictureFile.getTotalSpace();
        logger.info("Total space: {}", pictureFile);

        File folder = pictureFile.getParentFile();
        File renamedFile = new File(folder, fileName);

        File result = ExifImageUtils.rotateFromOrientationData(pictureFile, renamedFile);

        // final String absolutePath = pictureFile.getAbsolutePath();
        // final String escapedPath = UrlEscapers.urlPathSegmentEscaper().escape(absolutePath);

        // return ok(views.html.main.render(escapedPath));
        return ok(views.html.main.render(result.getAbsolutePath()));
      }

      return ok("asdf");
    } catch (Exception e) {
      logger.error("Error uploading", e);
      return internalServerError(e.getMessage());
    }
  }

  public static Result getImage(final String pathToFile) throws IOException {
    File file = new File(pathToFile);
    return ok(Files.readAllBytes(file.toPath())).as("image/jpg");
  }
}
Ejemplo n.º 8
0
/**
 * Annotation definition for Play actions: logging of each action call, e.g. 'gui_access - GET
 * /jatos/19/run (admin)'
 *
 * @author Kristian Lange (2016)
 */
public class GuiAccessLoggingAction extends Action<GuiAccessLogging> {

  @With(GuiAccessLoggingAction.class)
  @Target({ElementType.TYPE, ElementType.METHOD})
  @Retention(RetentionPolicy.RUNTIME)
  public @interface GuiAccessLogging {}

  private ALogger guiLogger = Logger.of("gui_access");

  public F.Promise<Result> call(Http.Context ctx) throws Throwable {
    final Request request = ctx.request();
    guiLogger.info(
        request.method()
            + " "
            + request.uri()
            + " ("
            + Controller.session(Users.SESSION_EMAIL)
            + ")");
    return delegate.call(ctx);
  }
}
public class ConnectionsWSClient implements WSClient {
  private Logger.ALogger logger = Logger.of("connections-play");
  private WSClient client;
  private Provider<Credentials> credentials;

  @Inject
  public ConnectionsWSClient(Provider<Credentials> credentials) {
    this(credentials, WS.newClient(9000));
  }

  public ConnectionsWSClient(Provider<Credentials> credentials, WSClient client) {
    this.credentials = credentials;
    this.client = client;
  }

  @Override
  public Object getUnderlying() {
    return client.getUnderlying();
  }

  @Override
  public WSRequest url(String url) {
    WSRequest request = client.url(url);
    credentials.get().decorate(request);
    return request;
  }

  public WSRequest url(String... urlParts) {
    String url = Paths.combineToUrl(urlParts);
    logger.debug("WSClient request to url=[{}]", url);
    return url(url);
  }

  @Override
  public void close() {
    client.close();
  }
}
Ejemplo n.º 10
0
public abstract class GenericDao<T> extends GenericReadOnlyDao<T> {
  private final Logger.ALogger logger = Logger.of(this.getClass());

  public GenericDao(EntityManagerProvider emp) {
    super(emp);
  }

  public T create(final T t) {
    try {
      logger.info("About to persist the entity " + t);

      getEntityManager().persist(t);
    } catch (Throwable e) {
      logger.info("Exception creating entity " + e.getMessage(), e);

      throw new RuntimeException(e);
    }

    return t;
  }

  public void delete(final Object id) {
    getEntityManager().remove(getEntityManager().getReference(type, id));
  }

  public final T update(final T t) {
    T mergedEntity = null;

    try {
      mergedEntity = getEntityManager().merge(t);
    } catch (Throwable e) {
      throw new RuntimeException(e);
    }
    return mergedEntity;
  }
}
Ejemplo n.º 11
0
/**
 * Title: NeolixService.java
 *
 * <p>Description: 新石器手机
 *
 * <p>Company: higegou
 *
 * @author ctt date 2015年7月22日 上午11:27:51
 * @version
 */
@Named
@Singleton
public class NeolixService {

  private static final Logger.ALogger logger = Logger.of(NeolixService.class);

  public static Row rowStatic = null;

  public void run_NeolixOrder(ImportNeolixVO vo) {
    String sql =
        "{CALL run_NeolixOrder('"
            + vo.orderNum
            + "','"
            + vo.datePay
            + "','"
            + vo.mechantNum
            + "',"
            + vo.counts
            + ",'"
            + vo.receiver
            + "','"
            + vo.parentsAddress
            + "','"
            + vo.subAddress
            + "','"
            + vo.phone
            + "','','"
            + vo.totalFee
            + "','"
            + vo.price
            + "','"
            + vo.expenses
            + "','"
            + vo.dateOrder
            + "')}"; // SQL语句  //调用存储过程
    logger.debug(sql);
    JdbcOper db = JdbcOper.getInstance(); // 创建DBHelper对象
    try {
      db.getPrepareStateDao(sql);
      db.pst.executeQuery(); // 执行语句,得到结果集
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      db.close();
    }
  }

  public List<ImportNeolixVO> extractNeolixInfo(File file) {

    List<ImportNeolixVO> neolix = new LinkedList<>();
    // 解析文件
    Workbook workBook = null;
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(file);
    } catch (FileNotFoundException e) {
      throw new RuntimeException("没有找到对应的文件", e);
    }
    try {
      workBook = WorkbookFactory.create(fis);
      Sheet sheet = workBook.getSheetAt(0);
      int lastRowNumber = sheet.getLastRowNum();
      Row rowTitle = sheet.getRow(0);
      if (rowTitle == null) {
        neolix = null;
        return neolix;
      }
      // 从第1行开始(不算标题)
      for (int i = 1; i <= lastRowNumber; i++) {
        Row row = sheet.getRow(i);
        if (row == null) {
          continue;
        }
        ImportNeolixVO vo = convert(row);
        neolix.add(vo);
      }
    } catch (Exception e) {
      System.out.println(e.toString());
      neolix = null;
    }
    return neolix;
  }

  private ImportNeolixVO convert(Row row) {
    ImportNeolixVO vo = new ImportNeolixVO();
    vo.orderNum =
        row.getCell(0, Row.RETURN_NULL_AND_BLANK) == null
            ? ""
            : row.getCell(0, Row.RETURN_NULL_AND_BLANK).toString(); // 订单号
    vo.mechantNum =
        row.getCell(1, Row.RETURN_NULL_AND_BLANK) == null
            ? ""
            : row.getCell(1, Row.RETURN_NULL_AND_BLANK).toString(); // 商户商品编号
    vo.counts =
        Numbers.parseInt(
            row.getCell(3, Row.RETURN_NULL_AND_BLANK) == null
                ? ""
                : row.getCell(3, Row.RETURN_NULL_AND_BLANK).toString(),
            0); // 商品数量
    vo.price =
        row.getCell(4, Row.RETURN_NULL_AND_BLANK) == null
            ? ""
            : row.getCell(4, Row.RETURN_NULL_AND_BLANK).toString(); // 商品 单价

    if (StringUtils.isBlank(vo.orderNum)) {
      vo.orderNum = rowStatic.getCell(0, Row.RETURN_NULL_AND_BLANK).toString(); // 订单号
    } else {
      rowStatic = row;
    }

    vo.totalFee = rowStatic.getCell(5, Row.RETURN_NULL_AND_BLANK).toString(); // 总金额(不含运费)
    vo.dateOrder =
        rowStatic.getCell(6, Row.RETURN_NULL_AND_BLANK).toString(); // 订单日期 2015-04-21 17:57
    vo.expenses = rowStatic.getCell(7, Row.RETURN_NULL_AND_BLANK).toString(); // 运费
    vo.datePay =
        rowStatic.getCell(8, Row.RETURN_NULL_AND_BLANK).toString(); // 支付日期 2015-04-21 17:57
    vo.receiver = rowStatic.getCell(9, Row.RETURN_NULL_AND_BLANK).toString(); // 收货人
    vo.parentsAddress = rowStatic.getCell(10, Row.RETURN_NULL_AND_BLANK).toString(); // 收货人所在省
    vo.subAddress = rowStatic.getCell(11, Row.RETURN_NULL_AND_BLANK).toString(); // 收货人所在市

    vo.phone = rowStatic.getCell(12, Row.RETURN_NULL_AND_BLANK).toString(); // 收货人电话

    return vo;
  }

  public File exportNeolixFile(String start, String end) {

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("sheet1");
    sheet.setColumnWidth(0, 6000);
    sheet.setColumnWidth(1, 5000);
    sheet.setColumnWidth(2, 5000);
    ExcelGenerateHelper helper = ExcelGenerateHelper.getInstance(wb);

    // 获取行索引
    int rowIndex = 0;
    int colIndex = 0;

    // 表头
    String[] titles = {"订单编号", "运单号", "发货备注"};

    // 生成表头
    helper.setRowIndex(rowIndex++);
    helper.generateHeader(sheet, titles, 0, StringUtils.EMPTY, StringUtils.EMPTY);

    // 循环生成数据行
    String sql = "call get_NeolixMail('" + start + "','" + end + "')"; // SQL语句  //调用存储过程
    logger.info(sql);
    JdbcOperWithClose db = JdbcOperWithClose.getInstance(); // 创建DBHelper对象
    try {
      db.getPrepareStateDao(sql);
      ResultSet rs = db.pst.executeQuery(); // 执行语句,得到结果集
      while (rs.next()) {
        String orderCode = rs.getString("orderCode");
        String mailNum = rs.getString("mailnum");
        String remark = rs.getString("remark");
        colIndex = 0;
        Row row = sheet.createRow(rowIndex++);
        helper.createStringCell(row, colIndex++, orderCode); // 订单号
        helper.createStringCell(row, colIndex++, mailNum); // 运单号
        helper.createStringCell(row, colIndex++, remark); // 备注
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      db.close();
    }
    // 在application.conf中配置的路径
    String path = Configuration.root().getString("export.path");
    File file = new File(path);
    file.mkdir(); // 判断文件夹是否存在,不存在就创建

    FileOutputStream out = null;
    String fileName = path + "neolix" + System.currentTimeMillis() + ".xls";
    try {
      out = new FileOutputStream(fileName);
      wb.write(out);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return new File(fileName);
  }
}
Ejemplo n.º 12
0
/** Created by nookio on 15/8/13. */
public class UnionPay extends MyBasePay<String> {

  private static Logger.ALogger logger = Logger.of(UnionPay.class);

  @Override
  protected String createNewPay(Integer payerId, String host, Object... all) {
    logger.info(payerId + "正在进行银联支付");
    Integer count = (Integer) all[0];
    Integer itemId = (Integer) all[1];
    Payment payment =
        createPayment(
            payerId,
            Payment.TYPE_UNIONPAY_WAP,
            PayStatus.PREPAY.name(),
            false,
            new Normal(count, itemId));
    prePayInfo = UnionPayHelper.genUnionOrderInfo(getSignData(payment.id, payment.money, host));
    return host;
  }

  @Override
  protected String infoNotify(Map<String, String> requestParams) {
    String respCode = requestParams.get("respCode");
    if (StringUtil.isNotBlank(respCode) && respCode.equals("00")) {
      String outTradeNo = new String(requestParams.get("orderId").replaceFirst("^0*", ""));
      // 获取交易金额 txnAmt
      String totalFee = String.valueOf(Double.valueOf(requestParams.get("txnAmt")) / 100);
      // 获取付款时间
      String payedMill = requestParams.get("txnTime");
      // 获取流水号
      String tradeNo = requestParams.get("queryId");

      String tradeStatus = "SUCCESS";
      Date payedAt = DateUtil.timeMillToDate(payedMill);
      Integer id = resultOfPayment(outTradeNo, tradeNo, tradeStatus, totalFee, payedAt);

      logger.info(id + "验证签名结果[成功].");
    } else {
      logger.error("银联支付返回,失败" + "\n以下是回掉信息" + requestParams.toString());
    }
    return notifySuccess();
  }

  @Override
  protected LinkedHashMap<String, String> getSignData(Object... all) {
    Integer id = (Integer) all[0];
    BigDecimal money = (BigDecimal) all[1];
    String host = (String) all[2];

    LinkedHashMap<String, String> data = new LinkedHashMap<>();
    // 版本号
    data.put("version", "5.0.0");
    // 字符集编码 默认"UTF-8"
    data.put("encoding", "UTF-8");
    // 签名方法 01 RSA
    data.put("signMethod", "01");
    // 交易类型 01-消费
    data.put("txnType", "01");
    // 交易子类型 01:自助消费 02:订购 03:分期付款
    data.put("txnSubType", "01");
    // 业务类型
    data.put("bizType", "000201");
    // 渠道类型,07-PC,08-手机
    data.put("channelType", "08");
    // 后台通知地址
    data.put("backUrl", host + UnionpayConfig.UNIONPAY_APP_NOTIFY_URL);
    // 接入类型,商户接入填0 0- 商户 , 1: 收单, 2:平台商户
    data.put("accessType", "0");
    // 商户号码,请改成自己的商户号
    data.put("merId", UnionpayConfig.CUSTOM_ID);
    // 商户订单号,8-40位数字字母
    String orderId = id < 1000000000 ? String.format("%08d", id) : id.toString();
    data.put("orderId", orderId);
    // 订单发送时间,取系统时间
    data.put("txnTime", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
    // 交易金额,单位分
    String monenyCent =
        money.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_DOWN).toString();
    data.put("txnAmt", monenyCent);
    // 交易币种
    data.put("currencyCode", "156");
    return data;
  }

  @Override
  protected String notifySuccess() {
    return "success";
  }

  @Override
  protected String notifyFail() {
    return "fail";
  }
}
  /** Protects an action with SecureSocial */
  public static class Secured extends Action<SecuredAction> {
    private RuntimeEnvironment env;

    public Secured(RuntimeEnvironment env) {
      this.env = env;
    }

    private play.Logger.ALogger logger = play.Logger.of("securesocial.core.java.Secured");

    @Override
    public Promise<Result> call(final Http.Context ctx) throws Throwable {
      initEnv(env);
      return F.Promise.wrap(env.authenticatorService().fromRequest(ctx._requestHeader()))
          .flatMap(
              new F.Function<Option<Authenticator>, Promise<Result>>() {
                @Override
                public Promise<Result> apply(Option<Authenticator> authenticatorOption)
                    throws Throwable {
                  if (authenticatorOption.isDefined() && authenticatorOption.get().isValid()) {
                    final Authenticator authenticator = authenticatorOption.get();
                    Object user = authenticator.user();
                    Authorization authorization = configuration.authorization().newInstance();
                    if (authorization.isAuthorized(user, configuration.params())) {
                      return F.Promise.wrap(authenticator.touch())
                          .flatMap(
                              new F.Function<Authenticator, Promise<Result>>() {
                                @Override
                                public Promise<Result> apply(Authenticator touched)
                                    throws Throwable {
                                  ctx.args.put(USER_KEY, touched.user());
                                  return F.Promise.wrap(touched.touching(ctx))
                                      .flatMap(
                                          new F.Function<
                                              scala.runtime.BoxedUnit, Promise<Result>>() {
                                            @Override
                                            public Promise<Result> apply(
                                                scala.runtime.BoxedUnit unit) throws Throwable {
                                              return delegate.call(ctx);
                                            }
                                          });
                                }
                              });
                    } else {
                      return notAuthorizedResult(ctx);
                    }
                  } else {
                    if (authenticatorOption.isDefined()) {
                      return F.Promise.wrap(authenticatorOption.get().discarding(ctx))
                          .flatMap(
                              new F.Function<Authenticator, Promise<Result>>() {
                                @Override
                                public Promise<Result> apply(Authenticator authenticator)
                                    throws Throwable {
                                  return notAuthenticatedResult(ctx);
                                }
                              });
                    }
                    return notAuthenticatedResult(ctx);
                  }
                }
              });
    }
  }
Ejemplo n.º 14
0
/**
 * An abstract class which gathers useful features
 *
 * @author Pierre-Yves Cloux
 */
public abstract class Utilities {
  private static Random random = new Random(System.currentTimeMillis());
  public static final int NUMBER_OF_PAGINATION_LINKS = 8;
  public static final int FORMATS_CACHING_DURATION = 300;
  public static final String JSON_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
  public static final String CAS_SSO_LANGUAGE_COOKIE =
      "org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE";

  private static Map<String, DateFormat> dateFormatMap =
      Collections.synchronizedMap(new HashMap<String, DateFormat>());

  private static Logger.ALogger log = Logger.of(Utilities.class);

  /**
   * Return the default date pattern for this application.<br>
   * If the locale is not null then uses the format associated with this specific locale if it
   * exists
   *
   * @param locale a {@link Locale}
   * @return a String pattern
   */
  public static String getDefaultDatePattern(Locale locale) {
    if (locale == null) {
      return getDefaultDatePattern();
    }
    if (Play.application()
        .configuration()
        .keys()
        .contains("maf.default.date.format." + locale.getLanguage())) {
      return Play.application()
          .configuration()
          .getString("maf.default.date.format." + locale.getLanguage());
    }
    return getDefaultDatePattern();
  }

  /**
   * Return the default date pattern for this application.
   *
   * @return a String pattern
   */
  public static String getDefaultDatePattern() {
    return Play.application()
        .configuration()
        .getString("maf.default.date.format", IModelConstants.DATE_FORMAT);
  }

  /**
   * Return the default date format associated with the specified locale (if any)
   *
   * @param locale a {@link Locale}
   * @return a DateFormat instance
   */
  public static DateFormat getDefaultDateFormat(Locale locale) {
    String pattern = getDefaultDatePattern(locale);
    DateFormat dateFormat = dateFormatMap.get(pattern);
    if (dateFormat == null) {
      dateFormat = new SimpleDateFormat(pattern);
      dateFormatMap.put(pattern, dateFormat);
    }
    return dateFormat;
  }

  /**
   * Return a date format matching the specified pattern.<br>
   * If the pattern is null then returns a format matching the current locale.
   *
   * @param pattern the pattern for the current locale
   * @param locale the locale to be used to retrieve or compute the date format
   * @return a date format
   */
  public static DateFormat getDateFormat(String pattern, Locale locale) {
    DateFormat dateFormat = null;
    if (StringUtils.isBlank(pattern)) {
      return getDefaultDateFormat(locale);
    }
    dateFormat = (DateFormat) Cache.get(IFrameworkConstants.FORMATS_CACHE_PREFIX + pattern);
    if (dateFormat == null) {
      dateFormat = new SimpleDateFormat(pattern);
      Cache.set(
          IFrameworkConstants.FORMATS_CACHE_PREFIX + pattern, dateFormat, FORMATS_CACHING_DURATION);
    }
    return dateFormat;
  }

  /**
   * Return a date format matching the specified pattern.<br>
   * If the pattern is null then returns a format matching the current locale.
   *
   * @param pattern the pattern for the current locale
   * @return a date format
   */
  public static DateFormat getDateFormat(String pattern) {
    return getDateFormat(pattern, null);
  }

  /**
   * Return a number format matching the specified pattern.<br>
   * If the pattern is null then returns a format matching the current locale.
   *
   * @param pattern the pattern for the current locale
   * @return a number format
   */
  public static NumberFormat getNumberFormat(String pattern) {
    return getNumberFormat(pattern, false);
  }

  /**
   * Return a number format matching the specified pattern.<br>
   * If the pattern is null then returns a format matching the current locale.
   *
   * @param pattern the pattern for the current locale
   * @param signed set to true if the number must be always signed (display a + for positive
   *     numbers)
   * @return a number format
   */
  public static NumberFormat getNumberFormat(String pattern, Boolean signed) {

    NumberFormat numberFormat;

    if (pattern != null) {

      numberFormat = (NumberFormat) Cache.get(IFrameworkConstants.FORMATS_CACHE_PREFIX + pattern);
      if (numberFormat == null) {
        numberFormat = new DecimalFormat(pattern);
        Cache.set(
            IFrameworkConstants.FORMATS_CACHE_PREFIX + pattern,
            numberFormat,
            FORMATS_CACHING_DURATION);
      }

    } else if (play.mvc.Http.Context.current.get() != null) {

      numberFormat = NumberFormat.getInstance(play.mvc.Http.Context.current().lang().toLocale());

    } else {

      numberFormat = NumberFormat.getInstance(Locale.getDefault());
    }

    if (signed) {
      return new SignedNumberFormat(numberFormat);
    } else {
      return numberFormat;
    }
  }

  /**
   * Return a random unique key (to be used for session id or validation key)
   *
   * @return a one time key which is fully random
   */
  public static String getRandomID() {
    return UUID.randomUUID().toString() + String.valueOf(random.nextInt(1000000) + 1000);
  }

  /**
   * Return a date which is an offset from the current date
   *
   * @param offSet an offset integer value (0 will return the current date)
   * @return a Date
   */
  public static Date getOffSetDate(int offSet) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.add(Calendar.DATE, offSet);
    return cal.getTime();
  }

  /**
   * Send a success flash message
   *
   * @param message a String
   */
  public static void sendSuccessFlashMessage(String message) {
    Controller.flash("success", message);
  }

  /**
   * Send an error flash message
   *
   * @param message a String
   */
  public static void sendErrorFlashMessage(String message) {
    Controller.flash("error", message);
  }

  /**
   * Send an info flash message
   *
   * @param message a String
   */
  public static void sendInfoFlashMessage(String message) {
    Controller.flash("info", message);
  }

  /**
   * Send a warning flash message
   *
   * @param message a String
   */
  public static void sendWarningFlashMessage(String message) {
    Controller.flash("warning", message);
  }

  /**
   * Get a by array by serializing the specified object as XML
   *
   * @param object an object
   */
  public static byte[] marshallObject(Object object) {
    if (object == null) {
      throw new IllegalArgumentException("Null is not serializable");
    }
    if (!Serializable.class.isAssignableFrom(object.getClass())) {
      throw new IllegalArgumentException("The object must be Serializable");
    }
    ByteArrayOutputStream baOut = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(baOut);
    encoder.writeObject(object);
    encoder.flush();
    encoder.close();
    return baOut.toByteArray();
  }

  /**
   * Return an object from the specified array of bytes
   *
   * @param data an object
   */
  public static Object unmarshallObject(byte[] data) {
    if (data == null) {
      return null;
    }
    XMLDecoder decoder = null;
    try {
      ByteArrayInputStream baIn = new ByteArrayInputStream(data);
      decoder = new XMLDecoder(baIn);
      return decoder.readObject();
    } finally {
      if (decoder != null) {
        decoder.close();
      }
    }
  }

  /**
   * Convert a {@link ISelectableValueHolderCollection} into JSON.<br>
   * The structure is the following one : { "value" : {"value" : "the value", "name" : "the name",
   * "description" : "the description","url" : "the url"} }
   *
   * @param valueHoldersList a collection
   * @return a JSON object
   */
  public static <T> ObjectNode marshallAsJson(List<ISelectableValueHolder<T>> valueHoldersList) {
    ObjectNode valueHoldersAsJson = Json.newObject();
    if (valueHoldersList != null) {
      int order = 0;
      for (ISelectableValueHolder<T> valueHolder : valueHoldersList) {
        valueHoldersAsJson.set(
            String.valueOf(valueHolder.getValue()), marshallAsJson(valueHolder, order));
        order++;
      }
    }
    return valueHoldersAsJson;
  }

  /**
   * Convert a {@link ISelectableValueHolderCollection} into JSON.<br>
   * The structure is the following one : { "value" : {"value" : "the value", "name" : "the name",
   * "description" : "the description","url" : "the url"} }
   *
   * @param valueHoldersList a collection
   * @return a JSON object
   */
  public static <T> ObjectNode marshallAsJson(
      Collection<ISelectableValueHolder<T>> valueHoldersList) {
    return marshallAsJson(new ArrayList<ISelectableValueHolder<T>>(valueHoldersList));
  }

  /**
   * Convert a {@link ISelectableValueHolder} into JSON.<br>
   * The structure is the following one : {"value" : "the value", "name" : "the name", "description"
   * : "the description","url" : "the url"}
   *
   * @param valueHolder a value holder
   * @return a JSON object
   */
  public static <T> ObjectNode marshallAsJson(ISelectableValueHolder<T> valueHolder, int order) {
    ObjectNode valueHolderAsJson = Json.newObject();
    valueHolderAsJson.put("name", valueHolder.getName());
    valueHolderAsJson.put("order", order);
    valueHolderAsJson.put("value", String.valueOf(valueHolder.getValue()));
    if (valueHolder.getDescription() != null) {
      valueHolderAsJson.put("description", valueHolder.getDescription());
    }
    if (valueHolder.getUrl() != null) {
      valueHolderAsJson.put("url", valueHolder.getUrl());
    }
    return valueHolderAsJson;
  }

  /**
   * For a number of objects in the system, a i18n key must be created.<br>
   * This method create a template to be used to generate any i18n key for each resource (which need
   * so). It creates a String.format template which "expects" one %s (to be replaced by the name of
   * the attribute to be i18nized)
   *
   * @param clazz a object class name
   * @param resourceKey a unique key to be used for all the resources of a named object
   * @return a string (a valid template)
   */
  public static final String getI18nKeyTemplate(Class<?> clazz, String resourceKey) {
    return clazz.getSimpleName().toLowerCase()
        + "."
        + Base64.encodeBase64URLSafeString(resourceKey.getBytes()).toLowerCase()
        + ".%s";
  }

  /**
   * Generate a String representation of an Exception.<br>
   * It manages the embedded Exceptions.
   *
   * @param e an Exception
   * @return a String
   */
  public static String getExceptionAsString(Exception e) {
    StringBuffer sb = new StringBuffer();
    sb.append(e.getMessage());
    Throwable exp = e.getCause();
    while (exp != null) {
      sb.append(">>");
      sb.append(exp.getMessage());
      sb.append('\n');
      exp = exp.getCause();
    }
    return sb.toString();
  }

  /**
   * Update the SSO language so that it is aligned with the specified language.<br>
   * The SSO language is the one used for the login & logout page.
   *
   * @param ctx a Context (play meaning)
   * @param languageCode a language code (en, fr, de)
   */
  public static void setSsoLanguage(Context ctx, String languageCode) {
    // For CAS, the language is stored in a cookie
    // To "update" this cookie we have to override it with a different value
    ctx.response().setCookie(CAS_SSO_LANGUAGE_COOKIE, languageCode);
  }

  /**
   * Return the password strength.$ WARNING : see the JavaScript function "maf_password_rating" in
   * the main.js library.
   *
   * @param password
   * @return
   */
  public static int getPasswordStrength(String password) {
    if (password.length() < IFrameworkConstants.MINIMAL_PASSWORD_LENGTH) {
      return 0;
    }
    int categories = 0;
    if (password.matches(".*[a-z]+.*")) {
      categories++;
    }
    if (password.matches(".*[A-Z]+.*")) {
      categories++;
    }
    if (password.matches(".*[0-9]+.*")) {
      categories++;
    }
    if (password.matches(
        ".*[`~!@#\\$%\\^&\\*\\(\\)_\\-\\+=\\{\\}\\[\\]\\\\\\|:;\"'<>,\\.\\?\\/]+.*")) {
      categories++;
    }
    if (categories < 2) {
      return 0;
    }
    if (categories > 2) {
      return 2;
    }
    return 1;
  }

  /**
   * Block the execution thread during a moment
   *
   * @param duration a duration in ms
   */
  public static void wait(int duration) {
    try {
      Thread.sleep(duration);
    } catch (InterruptedException e) {
      log.error("Error while stopping the current thread", e);
    }
  }

  /**
   * Get the size (bytes) of a folder.
   *
   * @param directory the root directory
   */
  public static long folderSize(File directory) {
    long length = 0;
    for (File file : directory.listFiles()) {
      if (file.isFile()) length += file.length();
      else length += folderSize(file);
    }
    return length;
  }

  /**
   * Update the specified expression list with the specified order by structure
   *
   * @param orderBy an order by structure
   * @param expressionList an expression list
   */
  public static <T> void updateExpressionListWithOrderBy(
      OrderBy<T> orderBy, ExpressionList<T> expressionList) {
    OrderBy<T> currentOrderBy = expressionList.orderBy();
    if (orderBy.getProperties() != null) {
      for (Property property : orderBy.getProperties()) {
        currentOrderBy.add(property);
      }
    }
  }

  /**
   * Return a list of array of String from an array of string.
   *
   * <p>Deadbolt expects a certain structure for the permissions statements.<br>
   * The basic structure is a List of array of String (AND between the permissions in an array and
   * OR between the arrays in the list). This method takes an array as a parameter and creates a
   * list of array (one array per value of the array passed as a parameter). This creates a
   * permission statement of ORed permissions.
   *
   * @param values an array of permissions (to be associated with or)
   * @return
   */
  public static List<String[]> getListOfArray(String... values) {
    ArrayList<String[]> list = new ArrayList<String[]>();
    for (String value : values) {
      list.add(new String[] {value});
    }
    return list;
  }

  /**
   * Provide a String representation of the provided list of array of String
   *
   * @return
   */
  public static String toString(List<String[]> values) {
    StringBuffer sb = new StringBuffer();
    if (values != null) {
      sb.append('[');
      for (String[] array : values) {
        sb.append(ArrayUtils.toString(array));
        sb.append(',');
      }
      sb.deleteCharAt(sb.length() - 1);
      sb.append(']');
    } else {
      return null;
    }
    return sb.toString();
  }

  /**
   * Get the current object id from the context.<br>
   * This feature is mainly used for authorization purpose to get the "current" manipulated object
   * from the context.
   *
   * @param context the context
   */
  public static Long getId(Http.Context context) {
    Long id = null;

    if (context.args.containsKey(IFrameworkConstants.ID_NAME_FOR_CONTEXT)) {
      // get the id as a context argument

      id = (Long) context.args.get(IFrameworkConstants.ID_NAME_FOR_CONTEXT);
    } else if (context.request().getQueryString("id") != null) {
      // get the id as a query parameter

      id = Long.valueOf(context.request().getQueryString("id"));
    } else if (context.request().headers().get("id") != null) {
      // get the id as a header parameter

      id = Long.valueOf(context.request().headers().get("id")[0]);
    } else if (context.request().body().asFormUrlEncoded() != null
        && context.request().body().asFormUrlEncoded().get("id") != null) {
      // get the id as a form content parameter

      id = Long.valueOf(context.request().body().asFormUrlEncoded().get("id")[0]);
    } else if (context.request().body().asMultipartFormData() != null
        && context.request().body().asMultipartFormData().asFormUrlEncoded() != null
        && context.request().body().asMultipartFormData().asFormUrlEncoded().get("id") != null) {
      // get the id as a multipart form content parameter

      id =
          Long.valueOf(
              context.request().body().asMultipartFormData().asFormUrlEncoded().get("id")[0]);
    } else {
      // else try to get the id as a route parameter (only at the end of
      // the path), example: https://localhost/portfolio-entry/view/10

      try {
        id =
            Long.parseLong(
                context.request().path().substring(context.request().path().lastIndexOf('/') + 1));
      } catch (Exception e) {
        Logger.debug("impossible to find the id as a route parameter");
      }
    }

    return id;
  }
}
public class LobbyController extends Controller {
  public static Logger.ALogger logger = Logger.of("application.controllers.LobbyController");
  private RuntimeEnvironment env;
  private static final String DEFAULT_LOBBY_NAME = "public";

  private static Map<String, Lobby> lobbys = new HashMap<String, Lobby>();

  /**
   * A constructor needed to get a hold of the environment instance. This could be injected using a
   * DI framework instead too.
   *
   * @param env
   */
  @Inject()
  public LobbyController(RuntimeEnvironment env) {
    this.env = env;
  }

  @SecuredAction
  public Result getLobbys() {
    String lobbyString;
    synchronized (lobbys) {
      removeEmptyLobbys();
      List<String> lobbyList = new ArrayList<String>(lobbys.keySet());
      lobbyString = new Gson().toJson(lobbyList);
    }
    return ok(lobbyString);
  }

  @SecuredAction
  public Result getLobbysP() {
    String lobbyString;
    synchronized (lobbys) {
      removeEmptyLobbys();
      Map<String, String> lobbyList = new HashMap<String, String>();
      for (Entry<String, Lobby> entry : lobbys.entrySet()) {
        lobbyList.put("name", entry.getKey());
      }
      lobbyString = new Gson().toJson(lobbyList);
    }
    return ok(lobbyString);
  }

  @SecuredAction
  public Result play(String lobbyName) {
    logger.debug("[LobbyController:play] Play function called");
    if (lobbyName.equals("")) {
      lobbyName = DEFAULT_LOBBY_NAME;
    }

    User player = (User) ctx().args.get(SecureSocial.USER_KEY);

    synchronized (lobbys) {
      // Check if Player is already in other lobby
      for (Entry<String, Lobby> entry : lobbys.entrySet()) {
        if (entry.getValue().containsPlayer(player) && !(entry.getKey().equals(lobbyName))) {
          entry.getValue().removePlayer(player);
        }
      }

      logger.debug("[LobbyController:play] All lobbys: " + lobbys.toString());
      // Remove empty lobbys
      removeEmptyLobbys();

      if (!lobbys.containsKey(lobbyName)) {
        // Lobby does not exist
        logger.debug(
            "[LobbyController:play] Lobby '" + lobbyName + "' does not exist. Creating new one.");
        lobbys.put(lobbyName, new Lobby(lobbyName));

        logger.debug("[LobbyController:play] Adding player to lobby '" + lobbyName + "'");
        ;
        lobbys.get(lobbyName).addPlayer(player);
      } else {
        // Player is not already in Lobby
        if (!lobbys.get(lobbyName).containsPlayer(player)) {
          logger.debug(
              "[LobbyController:play] Lobby '"
                  + lobbyName
                  + "' exists but player is not in lobby.");
          ;

          if (lobbys.get(lobbyName).gameStarted()) {
            logger.debug(
                "[LobbyController:play] Lobby '" + lobbyName + "' has already started game");
            ;
          } else {
            logger.debug("[LobbyController:play] Adding player to lobby '" + lobbyName + "'");
            ;
            lobbys.get(lobbyName).addPlayer(player);
          }
        }
      }
    }

    return ok(pokerGame.render(player, SecureSocial.env(), lobbyName));
  }

  private void removeEmptyLobbys() {
    for (Entry<String, Lobby> entry : lobbys.entrySet()) {
      logger.debug(
          "[LobbyController:play] Lobby: "
              + entry.getKey()
              + " count players: "
              + entry.getValue().getPlayerCount());
      if (entry.getValue().getPlayerCount() == 0) {
        lobbys.remove(entry.getKey());
      }
    }
  }

  @SecuredAction
  public WebSocket<String> getSocket() {
    // User player = (User) ctx().args.get(SecureSocial.USER_KEY);
    User player = (User) SecureSocial.currentUser(env).get(100);
    logger.debug("[LobbyController:getSocket] getSocket called from User: "******"[LobbyController:getSocket] ...player found! Returning WebSocket for this player");
          return lobbys.get(lobbyName).getSocketForPlayer(player);
        }
      }
    }
    logger.debug(
        "[LobbyController:getSocket] ...player not found. Player didn't joined a lobby. Rejecting WebSocket.");
    return WebSocket.reject(Results.badRequest("Player didn't joined a game."));
  }
}
/**
 * Utility class which provides methods usefull system level features, namelly:
 *
 * <ul>
 *   <li>Scheduler
 *   <li>System moniotoring (memory and threads)
 * </ul>
 *
 * @author Pierre-Yves Cloux
 */
@Singleton
public class SysAdminUtilsImpl implements ISysAdminUtils {

  private static Logger.ALogger log = Logger.of(SysAdminUtilsImpl.class);
  private static final String PERMGEN_MEMORY_POOL_NAME = "PS Perm Gen";
  private ActorSystem actorSystem;
  private Cancellable automaticSystemStatus;

  private Configuration configuration;

  /**
   * Create a new SysAdminUtilsImpl
   *
   * @param lifecycle the play application lifecycle listener
   * @param configuration the play application configuration
   * @param databaseDependencyService the service which secure the availability of the database
   * @param actorSystem the Akka actor system
   */
  @Inject
  public SysAdminUtilsImpl(
      ApplicationLifecycle lifecycle,
      Configuration configuration,
      IDatabaseDependencyService databaseDependencyService,
      ActorSystem actorSystem) {
    log.info("SERVICE>>> SysAdminUtilsImpl starting...");
    this.actorSystem = actorSystem;
    this.configuration = configuration;
    initAutomatedSystemStatus();
    lifecycle.addStopHook(
        () -> {
          log.info("SERVICE>>> SysAdminUtilsImpl stopping...");
          if (automaticSystemStatus != null) {
            try {
              getAutomaticSystemStatus().cancel();
            } catch (Exception e) {
              log.error("Unable to stop the automatic system status", e);
            }
          }
          log.info("SERVICE>>> SysAdminUtilsImpl stopped");
          return Promise.pure(null);
        });
    log.info("SERVICE>>> SysAdminUtilsImpl started");
  }

  @Override
  public Cancellable scheduleOnce(
      final boolean exclusive,
      final String scheduledActionUuid,
      FiniteDuration initialDelay,
      final Runnable runnable) {
    if (log.isDebugEnabled()) {
      log.debug("Request " + (exclusive ? "EXCLUSIVE" : "STANDARD") + " " + scheduledActionUuid);
    }
    return getActorSystem()
        .scheduler()
        .scheduleOnce(
            initialDelay,
            new Runnable() {
              @Override
              public void run() {
                String transactionId = Utilities.getRandomID();
                dumpSystemStatus(
                    "ASYNC ACTION START for "
                        + scheduledActionUuid
                        + " ["
                        + (exclusive ? "EXCLUSIVE" : "STANDARD")
                        + "] and transaction "
                        + transactionId);
                try {
                  runnable.run();
                } catch (Exception e) {
                  log.error(
                      "The job "
                          + scheduledActionUuid
                          + " raised an exception within the transaction "
                          + transactionId,
                      e);
                }
                dumpSystemStatus(
                    "ASYNC ACTION STOP for "
                        + scheduledActionUuid
                        + " and transaction "
                        + transactionId);
              }
            },
            getActorSystem().dispatcher());
  }

  @Override
  public Cancellable scheduleRecurring(
      final boolean exclusive,
      final String scheduledActionUuid,
      FiniteDuration initialDelay,
      FiniteDuration interval,
      final Runnable runnable,
      final boolean logInDebug) {
    if (log.isDebugEnabled()) {
      log.debug("Request " + (exclusive ? "EXCLUSIVE" : "STANDARD") + " " + scheduledActionUuid);
    }
    return getActorSystem()
        .scheduler()
        .schedule(
            initialDelay,
            interval,
            new Runnable() {
              @Override
              public void run() {
                String transactionId = Utilities.getRandomID();
                dumpSystemStatus(
                    "SCHEDULER START for "
                        + scheduledActionUuid
                        + " ["
                        + (exclusive ? "EXCLUSIVE" : "STANDARD")
                        + "] and transaction "
                        + transactionId,
                    logInDebug);
                markAsStarted(transactionId, scheduledActionUuid);
                try {
                  runnable.run();
                } catch (Exception e) {
                  log.error(
                      "The job "
                          + scheduledActionUuid
                          + " raised an exception within the transaction "
                          + transactionId,
                      e);
                }
                markAsCompleted(transactionId, scheduledActionUuid);
                dumpSystemStatus(
                    "SCHEDULER STOP for "
                        + scheduledActionUuid
                        + " and transaction "
                        + transactionId,
                    logInDebug);
              }
            },
            getActorSystem().dispatcher());
  }

  @Override
  public Cancellable scheduleRecurring(
      final boolean exclusive,
      final String scheduledActionUuid,
      FiniteDuration initialDelay,
      FiniteDuration interval,
      final Runnable runnable) {
    return scheduleRecurring(
        exclusive, scheduledActionUuid, initialDelay, interval, runnable, false);
  }

  /**
   * Mark the specified action as completed
   *
   * @param transactionId the unique transaction id for this action
   * @param scheduledActionUuid the unique name of an action
   */
  private void markAsStarted(String transactionId, String scheduledActionUuid) {
    try {
      Ebean.beginTransaction();
      SchedulerState schedulerState = new SchedulerState();
      schedulerState.actionUuid = scheduledActionUuid;
      schedulerState.transactionId = transactionId;
      schedulerState.isRunning = true;
      schedulerState.save();
      if (log.isDebugEnabled()) {
        log.debug(
            String.format(
                "Scheduled action for %s with transaction id %s started",
                scheduledActionUuid, transactionId));
      }
      Ebean.commitTransaction();
    } catch (Exception e) {
      log.error("Failed to mark as started", e);
      rollbackTransactionSilent();
    } finally {
      endTransactionSilent();
    }
  }

  /**
   * Mark the specified action as completed
   *
   * @param transactionId the unique transaction id for this action
   * @param scheduledActionUuid the unique name of an action
   */
  private void markAsCompleted(String transactionId, String scheduledActionUuid) {
    try {
      Ebean.beginTransaction();
      SchedulerState schedulerState =
          SchedulerState.getRunningSchedulerStateFromTransactionId(transactionId);
      if (schedulerState == null) {
        log.error(
            String.format(
                "Strange ... No running scheduled action for %s with transaction id %s while one was running and mark as completed is requested",
                scheduledActionUuid, transactionId));
      } else {
        schedulerState.isRunning = false;
        schedulerState.save();
        if (log.isDebugEnabled()) {
          log.debug(
              String.format(
                  "Scheduled action for %s with transaction id %s completed",
                  scheduledActionUuid, transactionId));
        }
      }
      Ebean.commitTransaction();
    } catch (Exception e) {
      log.error("Failed to mark as complete", e);
      rollbackTransactionSilent();
    } finally {
      endTransactionSilent();
    }
  }

  @Override
  public void dumpSystemConfiguration() {
    log.info("INITIAL CONFIGURATION " + ArrayUtils.toString(getMaxSystemParameters()));
  }

  @Override
  public void dumpSystemStatus(String eventName) {
    dumpSystemStatus(eventName, false);
  }

  @Override
  public void dumpSystemStatus(String eventName, boolean logAsDebug) {
    if (logAsDebug) {
      log.debug(eventName + " " + ArrayUtils.toString(getSystemStatus()));
    } else {
      log.info(eventName + " " + ArrayUtils.toString(getSystemStatus()));
    }
  }

  @Override
  public long[] getMaxSystemParameters() {
    long[] systemData = new long[3];
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    systemData[0] = memoryMXBean.getHeapMemoryUsage().getMax();
    systemData[1] = memoryMXBean.getNonHeapMemoryUsage().getMax();
    List<MemoryPoolMXBean> mbeans = ManagementFactory.getMemoryPoolMXBeans();
    if (mbeans != null) {
      for (MemoryPoolMXBean mbean : mbeans) {
        MemoryUsage memUsage = mbean.getUsage();
        if (mbean.getName().equals(PERMGEN_MEMORY_POOL_NAME)) {
          systemData[2] = memUsage.getMax();
        }
      }
    }
    return systemData;
  }

  @Override
  public long[] getSystemStatus() {
    long[] systemData = new long[4];
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    systemData[0] = memoryMXBean.getHeapMemoryUsage().getUsed();
    systemData[1] = memoryMXBean.getNonHeapMemoryUsage().getUsed();
    List<MemoryPoolMXBean> mbeans = ManagementFactory.getMemoryPoolMXBeans();
    if (mbeans != null) {
      for (MemoryPoolMXBean mbean : mbeans) {
        MemoryUsage memUsage = mbean.getUsage();
        if (mbean.getName().equals(PERMGEN_MEMORY_POOL_NAME)) {
          systemData[2] = memUsage.getUsed();
        }
      }
    }
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    systemData[3] = threadMXBean.getThreadCount();
    return systemData;
  }

  private void rollbackTransactionSilent() {
    try {
      Ebean.rollbackTransaction();
    } catch (Exception e) {
    }
  }

  private void endTransactionSilent() {
    try {
      Ebean.endTransaction();
    } catch (Exception e) {
    }
  }

  public void flushOldStates() {
    int hours = getConfiguration().getInt("maf.flush.scheduler.states.interval");
    SchedulerState.flushOldStates(hours);
  }

  /** Initialize the automated system status. */
  private void initAutomatedSystemStatus() {
    if (this.getConfiguration().getBoolean("maf.sysadmin.dump.vmstatus.active")) {
      int frequency = this.getConfiguration().getInt("maf.sysadmin.dump.vmstatus.frequency");
      log.info(">>>>>>>>>>>>>>>> Activate automated system status, frequency " + frequency);
      automaticSystemStatus =
          scheduleRecurring(
              true,
              "AUTOMATED STATUS",
              Duration.create(frequency, TimeUnit.SECONDS),
              Duration.create(frequency, TimeUnit.SECONDS),
              new Runnable() {
                @Override
                public void run() {
                  try {
                    flushOldStates();
                  } catch (Exception e) {
                    log.error("Failed to flush the old states of recurring jobs", e);
                  }
                }
              });
      log.info(">>>>>>>>>>>>>>>> Activate automated system status (end)");
    }
  }

  private Cancellable getAutomaticSystemStatus() {
    return automaticSystemStatus;
  }

  private ActorSystem getActorSystem() {
    return actorSystem;
  }

  private Configuration getConfiguration() {
    return this.configuration;
  }
}
Ejemplo n.º 17
0
public class CountryOperations {
  public static final String COUNTRY_SESSION_KEY = "SHOP_COUNTRY";
  public static final String COUNTRY_CONFIG_LIST = "sphere.countries";
  public static final Logger.ALogger LOGGER = Logger.of(CountryOperations.class);
  private final Configuration configuration;

  private CountryOperations(Configuration configuration) {
    this.configuration = configuration;
  }

  public static CountryOperations of(Configuration configuration) {
    return new CountryOperations(configuration);
  }

  /**
   * Gets the country associated with the user.
   *
   * @return the country stored in session, or the default country of the shop if none stored.
   */
  public CountryCode country() {
    return countryInSession().orElse(defaultCountry());
  }

  /**
   * Gets the list of available countries for this shop, as defined in the configuration file.
   *
   * @return the list of available countries.
   */
  public List<CountryCode> availableCountries() {
    List<CountryCode> countries = new ArrayList<>();
    for (String configCountry : configCountryList()) {
      parseCode(configCountry).ifPresent(countries::add);
    }
    return countries;
  }

  /**
   * Gets the default country for this shop, as defined in the configuration file.
   *
   * @return the first valid country defined in the configuration file.
   * @throws DefaultCountryNotFound when a default valid country could not be found.
   */
  public CountryCode defaultCountry() {
    List<CountryCode> availableCountries = availableCountries();
    if (!availableCountries.isEmpty()) {
      return availableCountries.get(0);
    } else {
      throw new DefaultCountryNotFound();
    }
  }

  /**
   * Sets the country associated with the user, if a valid country code is provided.
   *
   * @param countryCodeAsString the string representing a country code.
   * @throws InvalidCountryCode when the country code does not correspond to a valid country.
   */
  public void changeCountry(String countryCodeAsString) {
    CountryCode countryCode =
        parseCode(countryCodeAsString)
            .orElseThrow(() -> new InvalidCountryCode(countryCodeAsString));
    changeCountry(countryCode);
  }

  /**
   * Parses a country code as string.
   *
   * @param countryCodeAsString the string representing a country code.
   * @return the country code represented in the string, or absent if it does not correspond to a
   *     valid country.
   */
  public static Optional<CountryCode> parseCode(String countryCodeAsString) {
    try {
      return Optional.of(CountryCode.valueOf(countryCodeAsString));
    } catch (IllegalArgumentException e) {
      LOGGER.debug("Invalid country " + countryCodeAsString);
      return Optional.empty();
    }
  }

  /**
   * Sets the country associated with the user.
   *
   * @param countryCode the desired country for the user.
   */
  private void changeCountry(CountryCode countryCode) {
    if (availableCountries().contains(countryCode)) {
      Http.Context.current().session().put(COUNTRY_SESSION_KEY, countryCode.getAlpha2());
    }
  }

  /**
   * Gets the country stored in session.
   *
   * @return the country stored in the session, or absent if none stored.
   */
  private Optional<CountryCode> countryInSession() {
    Http.Session session = Http.Context.current().session();
    Optional<String> code = Optional.ofNullable(session.get(COUNTRY_SESSION_KEY));
    return code.flatMap(CountryOperations::parseCode);
  }

  /**
   * Gets the list of countries for this project.
   *
   * @return the list of countries as defined in the configuration file, or empty list if none
   *     defined.
   */
  private List<String> configCountryList() {
    return configuration.getStringList(COUNTRY_CONFIG_LIST, Collections.emptyList());
  }
}
/**
 * Messaging controller.
 *
 * @author Pierre-Yves Cloux
 */
@SubjectPresent
public class MessagingController extends Controller {
  @Inject private IUserSessionManagerPlugin userSessionManagerPlugin;
  @Inject private INotificationManagerPlugin notificationManagerPlugin;
  @Inject private II18nMessagesPlugin i18nMessagesPlugin;
  @Inject private Configuration configuration;
  @Inject private IAccountManagerPlugin accountManagerPlugin;
  @Inject private ITableProvider tableProvider;

  private static Logger.ALogger log = Logger.of(MessagingController.class);
  private static Form<NotificationMessage> notificationMessageForm =
      Form.form(NotificationMessage.class);

  /** The messaging page (list of all message, form to send a message). */
  @SubjectPresent
  public Result index() {

    String loggedUser = getUserSessionManagerPlugin().getUserSessionId(ctx());

    List<MessageListView> messageListViewRows = new ArrayList<>();
    List<Notification> notifications = getNotificationManagerPlugin().getMessagesForUid(loggedUser);
    for (Notification notification : notifications) {
      messageListViewRows.add(new MessageListView(this.getAccountManagerPlugin(), notification));
    }
    Table<MessageListView> messagesTables =
        this.getTableProvider().get().message.templateTable.fill(messageListViewRows);

    NotificationMessage notificationMessage = createEmptyNotificationMessage();

    return ok(
        views.html.messaging.index.render(
            messagesTables, notificationMessageForm.fill(notificationMessage)));
  }

  /** Send a notification message. */
  public Result sendMessage() {

    try {
      Form<NotificationMessage> boundForm = notificationMessageForm.bindFromRequest();
      if (boundForm.hasErrors()) {

        String loggedUser = getUserSessionManagerPlugin().getUserSessionId(ctx());

        List<MessageListView> messageListViewRows = new ArrayList<>();
        List<Notification> notifications =
            getNotificationManagerPlugin().getMessagesForUid(loggedUser);
        for (Notification notification : notifications) {
          messageListViewRows.add(
              new MessageListView(this.getAccountManagerPlugin(), notification));
        }
        Table<MessageListView> messagesTables =
            this.getTableProvider().get().message.templateTable.fill(messageListViewRows);

        return ok(views.html.messaging.index.render(messagesTables, boundForm));
      }
      NotificationMessage notificationMessage = boundForm.get();
      getNotificationManagerPlugin()
          .sendMessage(
              getUserSessionManagerPlugin().getUserSessionId(ctx()),
              notificationMessage.principalUids,
              notificationMessage.title,
              notificationMessage.message);
      Utilities.sendSuccessFlashMessage(
          getI18nMessagesPlugin().get("messaging.send.success", notificationMessage.title));
      return redirect(routes.MessagingController.index());
    } catch (Exception e) {
      return ControllersUtils.logAndReturnUnexpectedError(
          e, log, getConfiguration(), getI18nMessagesPlugin());
    }
  }

  /** Creates an empty notification message initialized with the current user id as a sender id. */
  private static NotificationMessage createEmptyNotificationMessage() {
    NotificationMessage notificationMessage = new NotificationMessage();
    notificationMessage.principalUids = new ArrayList<String>();
    return notificationMessage;
  }

  /**
   * A class which holds a notification message sent manually by the administrator.<br>
   *
   * <ul>
   *   <li><b>senderUid</b> : the uid of the sender of the notification
   *   <li><b>message</b> : the message to be sent as a notification to the specified principals
   *   <li><b>principalUids</b> : a list of {@link Principal} uid to which the message must be sent
   * </ul>
   *
   * @author Pierre-Yves Cloux
   */
  public static class NotificationMessage {

    @Required
    @MaxLength(value = IModelConstants.MEDIUM_STRING)
    public String title;

    @MaxLength(value = IModelConstants.LARGE_STRING, message = "object.message.message.invalid")
    public String message;

    @Required public List<String> principalUids;
  }

  /** Get the user session manager service. */
  private IUserSessionManagerPlugin getUserSessionManagerPlugin() {
    return userSessionManagerPlugin;
  }

  /** Get the notification manager service. */
  private INotificationManagerPlugin getNotificationManagerPlugin() {
    return notificationManagerPlugin;
  }

  /** Get the i18n messages service. */
  private II18nMessagesPlugin getI18nMessagesPlugin() {
    return i18nMessagesPlugin;
  }

  /** Get the Play configuration service. */
  private Configuration getConfiguration() {
    return configuration;
  }

  /** Get the account manager service. */
  private IAccountManagerPlugin getAccountManagerPlugin() {
    return this.accountManagerPlugin;
  }

  /** Get the table provider. */
  private ITableProvider getTableProvider() {
    return this.tableProvider;
  }
}
Ejemplo n.º 19
0
/** This class handles all image related functionalities */
public class ImageService {

  static final Logger.ALogger logger = Logger.of(ImageService.class);

  private ImageService() {}

  public static boolean validateMinSize(File file, int min_length, int min_height) {
    BufferedImage image;
    try {
      image = ImageIO.read(file);
      if (image.getWidth() < min_length) {
        return false;
      }
      if (image.getHeight() < min_height) {
        return false;
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return true;
  }

  public static boolean validateMaxSize(File file, int max_length, int max_height) {
    BufferedImage image;
    try {
      image = ImageIO.read(file);
      if (image.getWidth() > max_length) {
        return false;
      }
      if (image.getHeight() > max_height) {
        return false;
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return true;
  }

  public static void crop(File file, int x, int y, int width, int height)
      throws FileOperationException {
    BufferedImage image;
    try {
      image = ImageIO.read(file);
      image = Scalr.crop(image, x, y, width, height);
      saveToJPG(image, file);
      image.flush();
    } catch (IOException | IllegalArgumentException e) {
      logger.error(e.getMessage(), e);
      throw new FileOperationException("Cropping failed");
    }
  }

  public static void resize(File file, int width, int height) throws FileOperationException {
    BufferedImage image;
    try {
      image = ImageIO.read(file);
      image = Scalr.resize(image, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT, width, height);
      saveToJPG(image, file);
      image.flush();
    } catch (IOException | IllegalArgumentException e) {
      logger.error(e.getMessage(), e);
      throw new FileOperationException("Resizing failed");
    }
  }

  private static void saveToJPG(BufferedImage image, File file) throws IOException {
    BufferedImage newImage =
        new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
    newImage.createGraphics().drawImage(image, 0, 0, Color.WHITE, null);
    ImageIO.write(newImage, "jpg", file);
    newImage.flush();
  }
}
Ejemplo n.º 20
0
  public void onStart(Application app) {

    Logger.info("Application started");
    String uploadPath = Configuration.getUploadPath();
    File file = new File(uploadPath);
    if (!file.exists()) {
      try {
        if (!file.mkdir()) {
          System.out.println(file.getAbsolutePath());
        }
        ;
      } catch (Exception e) {
        e.printStackTrace();
        System.out.println(
            "Error while creating directory for server files, please check 'uploadPath' value in application.conf file");
        System.exit(-1);
      }
    } else {
      if (!file.canRead() || !file.canWrite()) {
        System.out.println(
            "Error: Server have no read and write access to "
                + uploadPath
                + ", please check 'uploadPath' value in application.conf file");
        System.exit(-1);
      }
    }

    // Checking existence of main directory
    String usersFilesDir = Configuration.getUploadPath();
    File applicationDir = new File(usersFilesDir + "/users/");
    if (!applicationDir.exists()) {
      Boolean createAppDir = applicationDir.mkdir();
      if (!createAppDir) {
        Logger.warn("Error while creating users directory");
        System.exit(-1);
      } else {
        Logger.info("Users directory created");
      }
    }

    if (Configuration.isApplyNewLimits()) {
      for (Account account : Account.findAll()) {
        account.setNewLimits();
      }
    }

    if (Configuration.isCreateDefaultUsers()) {
      UserService userService = new UserService(app);
      try {
        Integer nDefault = Configuration.getnDefaultUsers();
        String nameDefault = Configuration.getNameDefaultUser();
        for (int i = 1; i <= nDefault; i++) {
          String username = nameDefault + Integer.toString(i);
          String email = username + "@vdjviz.com";
          LocalUser localUser = LocalUser.find.byId(email);
          if (localUser == null) {
            Option<PasswordHasher> bcrypt = Registry.hashers().get("bcrypt");
            SocialUser socialUser =
                new SocialUser(
                    new IdentityId(email, "userpass"),
                    username,
                    username,
                    String.format("%s %s", username, username),
                    Option.apply(email),
                    null,
                    AuthenticationMethod.UserPassword(),
                    null,
                    null,
                    Some.apply(
                        new PasswordInfo(
                            "bcrypt", BCrypt.hashpw(username, BCrypt.gensalt()), null)));
            userService.doSave(socialUser);
          }
        }
      } catch (RuntimeException e) {
        Logger.error("Error while creating default users");
        e.printStackTrace();
      }
    }

    // Deleting empty files
    for (Account account : Account.findAll()) {
      for (UserFile userFile : account.getUserfiles()) {
        File fileDir = new File(userFile.getDirectoryPath());
        if (!fileDir.exists() || !userFile.checkExist()) {
          UserFile.deleteFile(userFile);
          Logger.of("user." + account.getUserName())
              .warn(
                  "Deleted empty file "
                      + userFile.getFileName()
                      + " for user : "******"user." + account.getUserName())
                              .info("File " + userFile.getFileName() + " was deleted");
                        }
                      }
                    }
                  }
                }
              },
              Akka.system().dispatcher());
    }
  }
Ejemplo n.º 21
0
@SuppressWarnings("rawtypes")
public abstract class RouterController extends Controller {

  private static ALogger log = Logger.of(RouterController.class);

  protected ModelRegistry modelRegistry;
  protected ControllerRegistry controllerRegistry;

  protected Map<Class<?>, ControllerProxy<?, ?>> dynamicRestControllers =
      new HashMap<Class<?>, ControllerProxy<?, ?>>();
  protected Map<Class<?>, ControllerProxy<?, ?>> dynamicCrudControllers =
      new HashMap<Class<?>, ControllerProxy<?, ?>>();

  public RouterController(ControllerRegistry controllerRegistry, ModelRegistry modelRegistry) {
    this.controllerRegistry = controllerRegistry;
    this.modelRegistry = modelRegistry;
  }

  public Result list(String name) {
    if (log.isDebugEnabled()) log.debug("list <-");

    F.Either<ControllerProxy, ? extends Result> cnf = controllerOrNotFound(name);
    if (cnf.right.isDefined()) return cnf.right.get();
    ControllerProxy controller = cnf.left.get();
    if (controller == null) {
      return controllerNotFound(name);
    }
    return controller.list();
  }

  public Result create(String name) {
    if (log.isDebugEnabled()) log.debug("create <- " + name);
    F.Either<ControllerProxy, ? extends Result> cnf = controllerOrNotFound(name);
    if (cnf.right.isDefined()) return cnf.right.get();
    ControllerProxy controller = cnf.left.get();
    if (controller == null) {
      return controllerNotFound(name);
    }
    return controller.create();
  }

  public Result show(String name, String key) {
    if (log.isDebugEnabled()) log.debug("show <- " + name + ", " + key);
    F.Either<ControllerProxy, ? extends Result> cnf = controllerOrNotFound(name);
    if (cnf.right.isDefined()) return cnf.right.get();
    ControllerProxy controller = cnf.left.get();
    if (controller == null) {
      return controllerNotFound(name);
    }
    return controller.show(key);
  }

  public Result update(String name, String key) {
    if (log.isDebugEnabled()) log.debug("update <- " + name + ", " + key);
    F.Either<ControllerProxy, ? extends Result> cnf = controllerOrNotFound(name);
    if (cnf.right.isDefined()) return cnf.right.get();
    ControllerProxy controller = cnf.left.get();
    if (controller == null) {
      return controllerNotFound(name);
    }
    return controller.update(key);
  }

  public Result save(String name, String key) {
    if (StringUtils.hasLength(key)) return update(name, key);
    else return create(name);
  }

  public Result delete(String name, String key) {
    if (log.isDebugEnabled()) log.debug("delete <- " + name + ", " + key);
    F.Either<ControllerProxy, ? extends Result> cnf = controllerOrNotFound(name);
    if (cnf.right.isDefined()) return cnf.right.get();
    ControllerProxy controller = cnf.left.get();
    if (controller == null) {
      return controllerNotFound(name);
    }
    return controller.delete(key);
  }

  protected Result controllerNotFound(String name) {
    return notFound("Controller not found : " + name);
  }

  protected F.Either<ControllerProxy, ? extends Result> controllerOrNotFound(final String name) {
    F.Option<ModelMetadata> modelInfo = getModel(name);
    if (!modelInfo.isDefined())
      return F.Either.Right(notFound("Model with name " + name + " not found!"));

    ModelMetadata model = modelInfo.get();

    ControllerProxy<?, ?> crud;
    try {
      crud = getController(model);
    } catch (IncompatibleControllerException e) {
      crud = null;
    }

    if (crud == null)
      return F.Either.Right(notFound("Controller for model " + model.getType() + " not found"));

    ControllerProxy controller = crud;
    return F.Either.Left(controller);
  }

  protected F.Option<ModelMetadata> getModel(final String name) {
    ModelMetadata modelInfo = null;
    try {
      modelInfo =
          (ModelMetadata)
              Cache.getOrElse(
                  getClass().getName() + "_ModelMetadata_" + name,
                  new Callable<Object>() {

                    @Override
                    public Object call() throws Exception {
                      return Iterables.find(
                          modelRegistry.getModels(),
                          new Predicate<ModelMetadata>() {
                            @Override
                            public boolean apply(ModelMetadata model) {
                              String modelName = model.getName();
                              return modelName.equals(name);
                            }
                          },
                          null);
                    }
                  },
                  0);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return modelInfo == null ? F.Option.<ModelMetadata>None() : F.Option.Some(modelInfo);
  }

  protected ControllerProxy<?, ?> getController(ModelMetadata model)
      throws IncompatibleControllerException {
    Class<?> keyType = model.getKeyField().getType();
    Class<?> modelType = model.getType();
    ControllerProxy<?, ?> crud = getControllerProxy(keyType, modelType);
    if (crud == null) crud = getDynamicController(keyType, modelType, model);
    return crud;
  }

  protected abstract ControllerProxy<?, ?> getDynamicController(
      Class<?> keyType, Class<?> modelType, ModelMetadata model);

  protected abstract ControllerProxy<?, ?> getControllerProxy(Class<?> keyType, Class<?> modelType)
      throws IncompatibleControllerException;
}
Ejemplo n.º 22
0
public class PostAPIController extends APIController<Long, Post> {

  private static ALogger log = Logger.of(PostAPIController.class);
  private ContentReportDAO contentReportDAO;
  private PostDAO postDAO;

  @Inject
  public PostAPIController(PostDAO postDAO, ContentReportDAO contentReportDAO) {
    super(postDAO);
    this.postDAO = postDAO;
    this.contentReportDAO = contentReportDAO;
  }

  @Override
  public Result create() {
    /* TODO:
    Result check = checkRequired("url");
    if (check != null) {
    	return check;
    }

    String url = jsonText("url");
    try {
    	new URL(url );
    } catch (MalformedURLException e) {
    	return badRequest(toJson(ImmutableMap.of(
    			"status", "error",
    			"message", e.getMessage())));
    }

    Post m = new Post();
    m.setStatus(Post.Status.NEW);
    m.setUrl(url);
    Long key = postDAO.create(m);
    */
    return TODO;
  }

  public Result approve(Long key) {
    if (log.isDebugEnabled()) log.debug("approve <- " + key);

    Post post = postDAO.get(key);
    if (log.isDebugEnabled()) log.debug("post : " + post);
    if (post == null) return notFound();

    ContentStatus status = post.getStatus();
    if (status == NEW || status == UPDATED) {
      User user = HttpUtils.loginUser(ctx());
      post.setStatus(APPROVED);
      post.setApprovedBy(user);
      post.setApprovedOn(new Date());
      postDAO.update(post);

      List<ContentReport> reports = contentReportDAO.findForContent(ContentType.POST, key);
      for (ContentReport report : reports) {
        if (report.getStatus() == ContentReport.Status.NEW) {
          report.setStatus(ContentReport.Status.IGNORED);
          report.setUpdatedBy(user);
          contentReportDAO.update(report);
        }
      }
      return ok(toJson(ImmutableMap.of("status", "ok", "key", key)));
    } else {
      return badRequest(
          toJson(
              ImmutableMap.of(
                  "status", "error", "message", "wrong status", "status", status.name())));
    }
  }

  public Result remove(Long key) {
    if (log.isDebugEnabled()) log.debug("remove <- " + key);

    Post post = postDAO.get(key);
    if (log.isDebugEnabled()) log.debug("post : " + post);
    if (post == null) return notFound();

    User user = HttpUtils.loginUser(ctx());
    post.setStatus(REMOVED);
    post.setUpdatedBy(user);
    postDAO.update(post);

    List<ContentReport> reports = contentReportDAO.findForContent(ContentType.POST, key);
    for (ContentReport report : reports) {
      if (report.getStatus() == ContentReport.Status.NEW) {
        report.setStatus(ContentReport.Status.PROCESSED);
        report.setUpdatedBy(user);
        contentReportDAO.update(report);
      }
    }
    return ok(toJson(ImmutableMap.of("status", "ok", "key", key)));
  }

  public Result expire(Long key) {
    if (log.isDebugEnabled()) log.debug("expire <- " + key);

    Post post = postDAO.get(key);
    if (log.isDebugEnabled()) log.debug("post : " + post);
    if (post == null) return notFound();

    ContentStatus status = post.getStatus();
    if (status == NEW || status == UPDATED || status == APPROVED) {
      User user = HttpUtils.loginUser(ctx());
      post.setStatus(EXPIRED);
      post.setUpdatedBy(user);
      postDAO.update(post);

      List<ContentReport> reports = contentReportDAO.findForContent(ContentType.POST, key);
      for (ContentReport report : reports) {
        if (report.getStatus() == ContentReport.Status.NEW) {
          report.setStatus(ContentReport.Status.PROCESSED);
          report.setUpdatedBy(user);
          contentReportDAO.update(report);
        }
      }
      return ok(toJson(ImmutableMap.of("status", "ok", "key", key)));
    } else {
      return badRequest(
          toJson(
              ImmutableMap.of(
                  "status", "error", "message", "wrong status", "status", status.name())));
    }
  }
}
Ejemplo n.º 23
0
/** Created by Frank on 20.07.2015. */
public class FrontendCommunicatorImpl implements FrontendCommunicator {
  private static final Logger.ALogger LOGGER = play.Logger.of("colosseum.scalability");

  private ModelService<Component> componentModelService;
  private ModelService<SensorDescription> sensorDescriptionModelService;
  private ModelService<Schedule> scheduleModelService;
  private ModelService<RawMonitor> rawMonitorModelService;
  private ModelService<ComposedMonitor> composedMonitorModelService;
  private ModelService<Monitor> monitorModelService;
  private ModelService<MonitorInstance> monitorInstanceModelService;
  private ModelService<VirtualMachine> virtualMachineModelService;
  private ModelService<IpAddress> ipAddressModelService;
  private ModelService<ApplicationComponent> applicationComponentModelService;
  private ModelService<Instance> instanceModelService;

  @Inject
  public FrontendCommunicatorImpl(
      ModelService<Component> componentModelService,
      ModelService<SensorDescription> sensorDescriptionModelService,
      ModelService<Schedule> scheduleModelService,
      ModelService<RawMonitor> rawMonitorModelService,
      ModelService<ComposedMonitor> composedMonitorModelService,
      ModelService<Monitor> monitorModelService,
      ModelService<MonitorInstance> monitorInstanceModelService,
      ModelService<VirtualMachine> virtualMachineModelService,
      ModelService<IpAddress> ipAddressModelService,
      ModelService<ApplicationComponent> applicationComponentModelService,
      ModelService<Instance> instanceModelService) {
    this.componentModelService = componentModelService;
    this.sensorDescriptionModelService = sensorDescriptionModelService;
    this.scheduleModelService = scheduleModelService;
    this.rawMonitorModelService = rawMonitorModelService;
    this.composedMonitorModelService = composedMonitorModelService;
    this.monitorModelService = monitorModelService;
    this.monitorInstanceModelService = monitorInstanceModelService;
    this.virtualMachineModelService = virtualMachineModelService;
    this.ipAddressModelService = ipAddressModelService;
    this.applicationComponentModelService = applicationComponentModelService;
    this.instanceModelService = instanceModelService;
  }

  @Override
  public List<VirtualMachine> getVirtualMachines(
      Long applicationId, Long componentId, Long instanceId, Long cloudId) {
    List<VirtualMachine> vms;
    List<VirtualMachine> result = new ArrayList<VirtualMachine>();

    vms = virtualMachineModelService.getAll();

    for (VirtualMachine vm : vms) {
      boolean suitable = true;
      List<Instance> instances = null;
      List<ApplicationComponent> appComps = null;

      // Filter for application id
      if (applicationId != null) {
        instances = this.getInstances(vm.getId());
        appComps = new ArrayList<>();
        for (Instance instance : instances) {
          if (instance.getVirtualMachine().getId().equals(vm.getId())) {
            LOGGER.info("Instance " + instance.getId() + " belongs to VM " + vm.getId());
            appComps.add(
                getApplicationComponentForInstance(instance.getApplicationComponent().getId()));
          }
        }

        boolean oneInstanceFit = false;

        for (ApplicationComponent ac : appComps) {
          if (ac.getApplication().getId() == applicationId) {
            oneInstanceFit = true;
          }
        }

        suitable = oneInstanceFit;
      }

      // Filter for component id
      if (suitable && componentId != null) {
        if (instances == null) {
          instances = this.getInstances(vm.getId());
          appComps = new ArrayList<ApplicationComponent>();
          for (Instance instance : instances) {
            appComps.add(
                getApplicationComponentForInstance(instance.getApplicationComponent().getId()));
          }
        }

        boolean oneInstanceFit = false;

        for (ApplicationComponent ac : appComps) {
          if (ac.getComponent().getId() == componentId) {
            oneInstanceFit = true;
          }
        }

        suitable = oneInstanceFit;
      }

      // Filter for instance id
      if (suitable && instanceId != null) {
        if (instances == null) {
          instances = this.getInstances(vm.getId());
        }

        boolean oneInstanceFit = false;
        for (Instance instance : instances) {
          if (instance.getId() == instanceId) {
            oneInstanceFit = true;
          }
        }

        suitable = oneInstanceFit;
      }

      // Filter for cloud id
      if (suitable && cloudId != null) {
        if (vm.cloud().getId() != cloudId) {
          suitable = false;
        }
      }

      // Add to result
      if (suitable) {
        result.add(vm);
      }
    }

    return result;
  }

  @Override
  public List<Instance> getInstances(Long vm) {
    List<Instance> instances;
    List<Instance> result = new ArrayList<Instance>();

    instances = instanceModelService.getAll();

    for (Instance instance : instances) {
      boolean suitable = true;

      // Filter for application id
      if (vm > 0 && !instance.getVirtualMachine().getId().equals(vm)) {
        suitable = false;
      }

      if (suitable) {
        result.add(instance);
      }
    }

    return result;
  }

  @Override
  public ApplicationComponent getApplicationComponentForInstance(Long appCompId) {
    return applicationComponentModelService.getById(appCompId);
  }

  @Override
  public String getPublicAddressOfVM(VirtualMachine vm) {
    List<IpAddress> addresses = ipAddressModelService.getAll();

    for (IpAddress ip : addresses) {
      /*TODO Not only return ONE, but EACH address */
      if (ip.getVirtualMachine().equals(vm) && ip.getIpType().equals(IpType.PUBLIC)) {
        return ip.getIp();
      }
    }

    return null;
  }

  @Override
  public List<Component> getComponents(
      Long applicationId, Long componentId, Long instanceId, Long cloudId) {
    List<Component> result = new ArrayList<Component>();
    List<Component> components = componentModelService.getAll();
    List<Instance> instances = null;
    List<VirtualMachine> vms = null;

    List<ApplicationComponent> appComps = applicationComponentModelService.getAll();

    for (Component component : components) {
      boolean suitable = false;

      if (applicationId != null) {
        for (ApplicationComponent ac : appComps) {
          if (ac.getComponent().getId().equals(componentId)
              && ac.getApplication().getId().equals(applicationId)) {
            suitable = true;
          }
        }
      }

      if (componentId != null) {
        if (componentId.equals(component.getId())) {
          suitable = suitable && true;
        }
      }

      if (instanceId != null) {
        if (instances == null) instances = instanceModelService.getAll();
        boolean oneFits = false;

        for (Instance instance : instances) {
          if (isInstanceOf(instance, appComps, component)) {
            oneFits = true;
          }
        }

        if (oneFits) {
          suitable = suitable && true;
        } else {
          suitable = false;
        }
      }

      if (cloudId != null) {
        if (instances == null) instances = instanceModelService.getAll();
        if (vms == null) vms = virtualMachineModelService.getAll();
        boolean oneFits = false;

        for (Instance instance : instances) {
          if (isInstanceOf(instance, vms, cloudId)) {
            if (isInstanceOf(instance, appComps, component)) {
              oneFits = true;
            }
          }
        }

        if (oneFits) {
          suitable = suitable && true;
        } else {
          suitable = false;
        }
      }

      if (suitable) {
        result.add(component);
      }
    }

    return result;
  }

  public boolean isInstanceOf(
      Instance instance, List<ApplicationComponent> appComps, Component component) {
    boolean result = false;

    Long componentId = component.getId();

    for (ApplicationComponent ac : appComps) {
      Long acId = ac.getId();

      if (instance.getApplicationComponent().getId().equals(acId)
          && ac.getComponent().getId().equals(componentId)) {
        result = true;
      }
    }

    return result;
  }

  public boolean isInstanceOf(Instance instance, List<VirtualMachine> vms, long cloudId) {
    boolean result = false;

    for (VirtualMachine vm : vms) {
      Long vmId = vm.getId();

      if (vm.cloud().getId().equals(cloudId) && instance.getVirtualMachine().getId().equals(vmId)) {
        result = true;
      }
    }

    return result;
  }

  @Override
  public String getIpAddress(Long idIpAddress) {
    return ipAddressModelService.getById(idIpAddress).getIp();
  }

  @Override
  public Long getIdPublicAddressOfVM(VirtualMachine vm) {
    if (vm.publicIpAddress() != null) {
      return vm.publicIpAddress().get().getId();
    }

    return null;
  }

  @Override
  public List<MonitorInstance> getMonitorInstances(Long monitorId) {
    List<MonitorInstance> result = new ArrayList<>();

    for (MonitorInstance mi : monitorInstanceModelService.getAll()) {
      if (mi.getMonitor().getId().equals(monitorId)) {
        result.add(mi);
      }
    }

    return result;
  }

  @Override
  public MonitorInstance saveMonitorInstance(
      Long idMonitor, String apiEndpoint, Long ipAddressId, Long vmId, Long componentId) {
    MonitorInstance result =
        new MonitorInstance(
            monitorModelService.getById(idMonitor),
            apiEndpoint,
            (ipAddressId == null ? null : ipAddressModelService.getById(ipAddressId)),
            (vmId == null ? null : virtualMachineModelService.getById(vmId)),
            (componentId == null ? null : componentModelService.getById(componentId)));
    monitorInstanceModelService.save(result);
    return result;
  }

  @Override
  public MonitorInstance getMonitorInstance(Long monitorInstanceId) {
    return monitorInstanceModelService.getById(monitorInstanceId);
  }

  @Override
  public RawMonitor getRawMonitor(Long monitorId) {
    return rawMonitorModelService.getById(monitorId);
  }

  @Override
  public ComposedMonitor getComposedMonitor(Long monitorId) {
    return composedMonitorModelService.getById(monitorId);
  }

  @Override
  public Monitor getMonitor(Long id) {
    return monitorModelService.getById(id);
  }

  @Override
  public List<Monitor> getMonitors() {
    return monitorModelService.getAll();
  }

  @Override
  public void removeMonitorInstance(MonitorInstance monitorInstance) {
    monitorInstanceModelService.delete(monitorInstance);
  }
}
Ejemplo n.º 24
0
@Named
@Singleton
public class ProductRedisController extends BaseAdminController {
  private static final Logger.ALogger logger = Logger.of(ProductRedisController.class);
  private static final SimpleDateFormat CHINESE_DATE_TIME_FORMAT =
      new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  private final ProductService productService;
  private final ChannelService channelService;
  private final SubjectService subjectService;
  private final CategoryService categoryService;

  @Inject
  public ProductRedisController(
      final ProductService productService,
      final CategoryService categoryService,
      final ChannelService channelService,
      final SubjectService subjectService) {
    this.productService = productService;
    this.categoryService = categoryService;
    this.subjectService = subjectService;
    this.channelService = channelService;
  }

  private static ICacheService cache = ServiceFactory.getCacheService();
  /**
   * 跳转至redis管理商品的页面
   *
   * @return
   */
  @AdminAuthenticated()
  public Result productsManageRedis() {
    return ok(views.html.redis.productsManageRedis.render());
  }

  /**
   * 商品在redis中存在的列表
   *
   * @return
   */
  @AdminAuthenticated()
  public Result productsRedisList() {
    List<Product> productList = new ArrayList<Product>();

    if (cache instanceof JedisHelper) {
      JedisHelper redis = (JedisHelper) cache;
      Set<String> productkeys = redis.getKeys(Constants.product_KEY);
      for (String key : productkeys) {
        Product product = (Product) ServiceFactory.getCacheService().getObject(key); // 从缓存读入
        if (product != null) productList.add(product);
      }
    }
    Map<String, List<Product>> result = new HashMap<String, List<Product>>();
    result.put("data", productList);
    return ok(Json.toJson(result));
  }

  /**
   * 删除redis中的商品
   *
   * @param pid
   * @return
   */
  @AdminAuthenticated()
  public Result deleteRedisProductByPid(Long pid) {
    cache.clear(Constants.product_KEY + pid);
    ObjectNode result = Json.newObject();
    result.put("status", 1);
    return ok(Json.toJson(result));
  }

  /**
   * 跳转至redis管理频道的页面
   *
   * @return
   */
  @AdminAuthenticated()
  public Result channelContentManageRedis() {
    List<Channel> channelList = channelService.findAll();
    String selector = "";
    if (channelList != null && channelList.size() > 0) {
      selector = ChannelService.channelList2Html(channelList, channelList.get(0).getId());
    }
    return ok(views.html.redis.channelContentManageRedis.render(Html.apply(selector), channelList));
  }

  /**
   * 根据频道ID获取下面的频道卡片(reids操作)
   *
   * @return
   */
  @AdminAuthenticated()
  public Result getChannelMouldByCidRedis(Long channelId) {
    List<ChannelMould> channelMouldList = channelService.findChannelMouldListByCid(channelId);
    for (ChannelMould channelMould : channelMouldList) {
      Mould mould = channelService.findMouldByMouldId(channelMould.getMouldId());
      if (mould != null) channelMould.setMouldName(mould.getMname());
    }
    Map<String, List<ChannelMould>> result = new HashMap<String, List<ChannelMould>>();
    result.put("data", channelMouldList);
    return ok(Json.toJson(result));
  }

  /**
   * 根据频道卡片ID重置频道卡片
   *
   * @return
   */
  @AdminAuthenticated()
  public Result updateChmould(Long cmid) {
    cache.clear(Constants.channel_mould_KEY + cmid); // 将此mouldId重置
    cache.clear(Constants.channelMouldProIds_KEY + cmid); // 将此mouldId下的pro ids重置
    ObjectNode result = Json.newObject();
    result.put("status", 1);
    return ok(Json.toJson(result));
  }
  /**
   * 根据频道ID重置频道
   *
   * @return
   */
  @AdminAuthenticated()
  public Result updateChannel(Long cid) {
    cache.clear(Constants.channelMouldIds_KEY + cid); // 将此Channel下的mould ids重置
    ObjectNode result = Json.newObject();
    result.put("status", 1);
    return ok(Json.toJson(result));
  }

  /**
   * 跳转至redis管理频道内容的页面
   *
   * @return
   */
  @AdminAuthenticated()
  public Result channelMouldProManageRedis(Long cid, Long cmid) {
    List<ChannelMouldPro> chmoProList = channelService.findChMoProListByCmId(cmid, cid);
    return ok(views.html.redis.channelMouldProManageRedis.render(chmoProList));
  }

  /**
   * 根据频道内容ID重置频道内容
   *
   * @return
   */
  @AdminAuthenticated()
  public Result deleteChmouldPro(Long cmpid) {
    cache.clear(Constants.channel_mould_pro_KEY + cmpid);
    ObjectNode result = Json.newObject();
    result.put("status", 1);
    return ok(Json.toJson(result));
  }
}
Ejemplo n.º 25
0
public class RestrictCombineAction extends AbstractRestrictiveAction<RestrictCombine> {

  private static ALogger log = Logger.of(RestrictCombineAction.class);

  private boolean isAllowed(Context ctx, DeadboltHandler deadboltHandler) {
    if (log.isDebugEnabled()) log.debug("isAllowed() <-");

    Subject roleHolder = getSubject(ctx, deadboltHandler);

    boolean roleOk = false;
    if (roleHolder != null) {
      roleOk = checkRole(roleHolder, configuration.roles());
    }

    if (!roleOk) {
      roleOk = checkPermission(roleHolder, configuration.with(), ctx);
    }

    return roleOk;
  }

  private boolean checkPermission(
      Subject roleHolder, Class<? extends RequestPermission> permissionClass, Context ctx) {
    if (log.isDebugEnabled()) log.debug("checkPermission() <-");

    RequestPermission permission = null;
    try {
      permission = permissionClass.newInstance();
    } catch (Exception e) {
      log.error("cannot create permission", e);
      return false;
    }

    List<? extends Permission> permissions = roleHolder.getPermissions();

    Request request = ctx.request();
    if (log.isDebugEnabled()) log.debug("request : " + request);
    String path = request.path();
    if (log.isDebugEnabled()) log.debug("path : " + path);
    return permission.isAllowed(request, permissions);
  }

  @Override
  public Class<? extends DeadboltHandler> getDeadboltHandlerClass() {
    return configuration.handler();
  }

  @Override
  public Promise<SimpleResult> applyRestriction(Context ctx, DeadboltHandler deadboltHandler)
      throws Throwable {

    Promise<SimpleResult> result;

    if (isAllowed(ctx, deadboltHandler)) {
      markActionAsAuthorised(ctx);
      result = delegate.call(ctx);
    } else {
      markActionAsUnauthorised(ctx);
      result = onAuthFailure(deadboltHandler, configuration.content(), ctx);
    }

    return result;
  }

  @Override
  public String getHandlerKey() {
    return null;
  }
}