示例#1
0
 /*
  * 시스템 설정에서 가입 승인 여부 조회
  */
 private static boolean isUseSignUpConfirm() {
   Configuration config = play.Play.application().configuration();
   String useSignUpConfirm = config.getString("signup.require.confirm");
   if (useSignUpConfirm != null && useSignUpConfirm.equals("true")) {
     return true;
   } else {
     return false;
   }
 }
  protected OAuthCalculator getOAuthCalculator(final OAuth1AuthInfo info) {
    final RequestToken token = new RequestToken(info.getAccessToken(), info.getAccessTokenSecret());
    final Configuration c = getConfiguration();
    final ConsumerKey cK =
        new ConsumerKey(
            c.getString(SettingKeys.CONSUMER_KEY), c.getString(SettingKeys.CONSUMER_SECRET));

    final OAuthCalculator op = new OAuthCalculator(cK, token);
    return op;
  }
示例#3
0
  public static String getValueStr(String name) {
    Configuration root = Configuration.root();

    if (root == null || root.getString(name) == null) {
      return null;
    }

    String value = root.getString(name);
    Logger.info(name + ":" + value);

    return value;
  }
示例#4
0
  /**
   * 默认false
   *
   * @param name
   * @return
   */
  public static boolean getValueBoolean(String name) {
    Configuration root = Configuration.root();

    if (root.getBoolean(name) == null) {
      return false;
    }

    boolean value = root.getBoolean(name);
    Logger.info(name + ":" + value);

    return value;
  }
示例#5
0
  public static int getValueInt(String name) {
    Configuration root = Configuration.root();

    if (root.getInt(name) == null) {
      return -1;
    }

    int value = root.getInt(name);
    Logger.info(name + ":" + value);

    return value;
  }
示例#6
0
  public static Result writeMail(String errorMessage, boolean sended) {
    Configuration config = play.Play.application().configuration();
    List<String> notConfiguredItems = new ArrayList<String>();
    String[] requiredItems = {"smtp.host", "smtp.user", "smtp.password"};
    for (String key : requiredItems) {
      if (config.getString(key) == null) {
        notConfiguredItems.add(key);
      }
    }

    String sender = config.getString("smtp.user");

    return ok(mail.render("title.sendMail", notConfiguredItems, sender, errorMessage, sended));
  }
 private Mongo connect(String seeds) {
   String[] sa = seeds.split("[;,\\s]+");
   List<ServerAddress> addrs = new ArrayList<ServerAddress>(sa.length);
   for (String s : sa) {
     String[] hp = s.split(":");
     if (0 == hp.length) {
       continue;
     }
     String host = hp[0];
     int port = 27017;
     if (hp.length > 1) {
       port = Integer.parseInt(hp[1]);
     }
     try {
       addrs.add(new ServerAddress(host, port));
     } catch (UnknownHostException e) {
       MorphiaLogger.error(e, "Error creating mongo connection to %s:%s", host, port);
     }
   }
   if (addrs.isEmpty()) {
     throw Configuration.root()
         .reportError(
             ConfigKey.DB_SEEDS.getKey(),
             "Cannot connect to mongodb: no replica can be connected",
             null);
   }
   return new Mongo(addrs);
 }
  /**
   * This handles the login form submission for the Web IDE.
   *
   * @return The result of rendering the page.
   */
  @AddCSRFToken
  @RequireCSRFCheck
  @Transactional
  public CompletionStage<Result> login() {
    Form<LoginForm> userForm = myFormFactory.form(LoginForm.class).bindFromRequest();

    // Perform the basic validation checks.
    if (userForm.hasErrors()) {
      // Render the page with the login form with the errors fields
      String token = CSRF.getToken(request()).map(t -> t.value()).orElse("no token");
      return CompletableFuture.supplyAsync(
          () -> badRequest(index.render(userForm, token)), myHttpExecutionContext.current());
    } else {
      LoginForm form = userForm.get();

      // Check for a registered user with the same email.
      // Note that "connect" expects a JPA entity manager,
      // which is not present if we don't wrap the call using
      // "withTransaction()".
      User user = myJpaApi.withTransaction(() -> User.connect(form.getEmail(), form.getPassword()));
      if (user != null) {
        // Check to see if this account has been authenticated or not.
        boolean hasAuthenticated =
            myJpaApi.withTransaction(() -> User.hasAuthenticated(form.getEmail()));
        if (hasAuthenticated) {
          // Update the login date
          final User updatedUser = myJpaApi.withTransaction(() -> User.lastLogin(form.getEmail()));

          // Add a new user event
          myJpaApi.withTransaction(() -> UserEvent.addRegularEvent("login", "", updatedUser));

          // Stores the email as session value
          session("connected", form.getEmail());

          // Obtain the http context from the configuration file
          String context = myConfiguration.getString("play.http.context");
          if (context == null) {
            context = "";
          }

          // Redirect back to the home page
          final String finalContext = context;
          return CompletableFuture.supplyAsync(
              () -> redirect(finalContext + "/"), myHttpExecutionContext.current());
        } else {
          // Render the not authenticated page
          return CompletableFuture.supplyAsync(
              () -> ok(notAuthenticated.render(form.getEmail())), myHttpExecutionContext.current());
        }
      } else {
        // The email and/or password does not match, so we add a new validation error.
        userForm.reject(new ValidationError("loginError", "Could not login."));

        // Render the page with the login form with the errors fields
        String token = CSRF.getToken(request()).map(t -> t.value()).orElse("no token");
        return CompletableFuture.supplyAsync(
            () -> badRequest(index.render(userForm, token)), myHttpExecutionContext.current());
      }
    }
  }
  private String getRequestToken(final Request request) throws AuthException {
    final Configuration c = getConfiguration();
    final List<NameValuePair> params = getRequestTokenParams(request, c);
    final Response r =
        WS.url(c.getString(SettingKeys.REQUEST_TOKEN_URL))
            .setHeader("Content-Type", "application/json")
            .setHeader("X-Accept", "application/json")
            .post(encodeParamsAsJson(params))
            .get(getTimeout());

    if (r.getStatus() >= 400) {
      throw new AuthException(r.asJson().asText());
    } else {
      return r.asJson().get(PocketConstants.CODE).asText();
    }
  }
  @Inject
  public MorphiumConnection(ApplicationLifecycle lifecycle, Configuration configuration) {
    final String dbName = configuration.getString("mongodb.name");
    final String dbHostName = configuration.getString("mongodb.host.name");
    final Integer dbHostPort = configuration.getInt("mongodb.host.port");

    final String username = configuration.getString("mongodb.username");
    final String password = configuration.getString("mongodb.password");

    Logger.info(
        "Mong db name: "
            + dbName
            + ", host : "
            + dbHostName
            + ", port : "
            + dbHostPort
            + ", username:"******", passsword:"
            + password);

    cfg = new MorphiumConfig();
    cfg.setDatabase(dbName);
    try {
      cfg.addHost(dbHostName, dbHostPort);
      if (StringUtils.isNotEmpty(username)) {
        cfg.setMongoLogin(username);
      }
      if (StringUtils.isNotEmpty(password)) {
        cfg.setMongoPassword(password);
      }
      m = new Morphium(cfg);

    } catch (UnknownHostException e) {
      e.printStackTrace();
      m = null;
      cfg = null;
    }

    lifecycle.addStopHook(
        () -> {
          if (m != null) {
            m.close();
          }
          return F.Promise.pure(null);
        });
  }
 private List<NameValuePair> getRequestTokenParams(final Request request, final Configuration c) {
   final List<NameValuePair> params = new ArrayList<NameValuePair>();
   params.add(
       new BasicNameValuePair(
           PocketConstants.CONSUMER_KEY, c.getString(SettingKeys.CONSUMER_KEY)));
   params.add(new BasicNameValuePair(getRedirectUriKey(), getRedirectUrl(request)));
   return params;
 }
示例#12
0
  @Inject
  public AmazonS3Storage(Configuration configuration) {
    bucketName = configuration.getString("storage.s3.bucket");

    String accessKey = configuration.getString("storage.s3.accesskey");
    String secretKey = configuration.getString("storage.s3.secretkey");
    credentials = new BasicAWSCredentials(accessKey, secretKey);

    AmazonS3 amazonS3 = new AmazonS3Client(credentials);

    try {
      if (!(amazonS3.doesBucketExist(bucketName))) {
        amazonS3.createBucket(new CreateBucketRequest(bucketName));
      }

      String bucketLocation = amazonS3.getBucketLocation(new GetBucketLocationRequest(bucketName));
      Logger.info("Amazon S3 bucket created at " + bucketLocation);
    } catch (AmazonServiceException ase) {
      Logger.error(
          "Caught an AmazonServiceException, which "
              + "means your request made it "
              + "to Amazon S3, but was rejected with an error response "
              + "for some reason."
              + " Error Message: "
              + ase.getMessage()
              + " HTTP Status Code: "
              + ase.getStatusCode()
              + " AWS Error Code: "
              + ase.getErrorCode()
              + " Error Type: "
              + ase.getErrorType()
              + " Request ID: "
              + ase.getRequestId());
    } catch (AmazonClientException ace) {
      Logger.error(
          "Caught an AmazonClientException, which "
              + "means the client encountered "
              + "an internal error while trying to "
              + "communicate with S3, "
              + "such as not being able to access the network."
              + " Error Message: "
              + ace.getMessage());
    }
  }
  @Override
  protected String getAccessTokenParams(
      final Configuration c, final String code, final Request request) {
    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(
        new BasicNameValuePair(
            PocketConstants.CONSUMER_KEY, c.getString(SettingKeys.CONSUMER_KEY)));
    params.add(new BasicNameValuePair(Constants.CODE, code));

    return URLEncodedUtils.format(params, "UTF-8");
  }
示例#14
0
  /** This handles the logout action for the Web IDE. */
  public Result logout() {
    // Clear the session
    session().clear();

    // Obtain the http context from the configuration file
    String context = myConfiguration.getString("play.http.context");
    if (context == null) {
      context = "";
    }

    return redirect(context + "/");
  }
示例#15
0
  @Override
  public Object authenticate(final Context context, final Object payload) throws AuthException {

    final Request request = context.request();
    final String uri = request.uri();

    if (Logger.isDebugEnabled()) {
      Logger.debug("Returned with URL: '" + uri + "'");
    }

    final Configuration c = getConfiguration();

    final ConsumerKey key =
        new ConsumerKey(
            c.getString(SettingKeys.CONSUMER_KEY), c.getString(SettingKeys.CONSUMER_SECRET));
    final String requestTokenURL = c.getString(SettingKeys.REQUEST_TOKEN_URL);
    final String accessTokenURL = c.getString(SettingKeys.ACCESS_TOKEN_URL);
    final String authorizationURL = c.getString(SettingKeys.AUTHORIZATION_URL);
    final ServiceInfo info =
        new ServiceInfo(requestTokenURL, accessTokenURL, authorizationURL, key);
    final OAuth service = new OAuth(info, true);

    checkError(request);

    if (uri.contains(Constants.OAUTH_VERIFIER)) {

      final RequestToken rtoken =
          (RequestToken) PlayAuthenticate.removeFromCache(context.session(), CACHE_TOKEN);
      final String verifier = Authenticate.getQueryString(request, Constants.OAUTH_VERIFIER);
      final Either<OAuthException, RequestToken> retrieveAccessToken =
          service.retrieveAccessToken(rtoken, verifier);

      if (retrieveAccessToken.isLeft()) {
        throw new AuthException(retrieveAccessToken.left().get().getLocalizedMessage());
      } else {
        final I i = buildInfo(retrieveAccessToken.right().get());
        return transform(i);
      }
    } else {

      final String callbackURL = getRedirectUrl(request);

      final Either<OAuthException, RequestToken> reponse =
          service.retrieveRequestToken(callbackURL);

      if (reponse.isLeft()) {
        // Exception happened
        throw new AuthException(reponse.left().get().getLocalizedMessage());
      } else {
        // All good, we have the request token
        final RequestToken rtoken = reponse.right().get();

        final String token = rtoken.token();
        final String redirectUrl = service.redirectUrl(token);

        PlayAuthenticate.storeInCache(context.session(), CACHE_TOKEN, rtoken);
        return redirectUrl;
      }
    }
  }
  /*
   * mongo.local.hostname=localhost
   * mongo.local.port=27017
   * mongo.remote.hostname=
   * mongo.remote.port=25189
   * mongo.remote.username=
   * mongo.remote.password=
   */
  private static DB getDb() {
    String userName = play.Configuration.root().getString("mongo.remote.username");
    String password = play.Configuration.root().getString("mongo.remote.password");
    boolean local = true;

    String localHostName = play.Configuration.root().getString("mongo.local.hostname");
    Integer localPort = play.Configuration.root().getInt("mongo.local.port");

    String remoteHostName = play.Configuration.root().getString("mongo.remote.hostname");
    Integer remotePort = play.Configuration.root().getInt("mongo.remote.port");

    Mongo m;
    DB db = null;
    if (local) {
      String hostname = localHostName;
      int port = localPort;
      try {
        m = new Mongo(hostname, port);
        db = m.getDB("db");
      } catch (Exception e) {
        Logger.error("Exception while intiating Local MongoDB", e);
      }
    } else {
      String hostname = remoteHostName;
      int port = remotePort;
      try {
        m = new Mongo(hostname, port);
        db = m.getDB("db");
        boolean auth = db.authenticate(userName, password.toCharArray());
      } catch (Exception e) {
        Logger.error("Exception while intiating Local MongoDB", e);
      }
    }
    return db;
  }
 private Mongo connect(String host, String port) {
   String[] ha = host.split("[,\\s;]+");
   String[] pa = port.split("[,\\s;]+");
   int len = ha.length;
   if (len != pa.length) {
     throw Configuration.root()
         .reportError(
             ConfigKey.DB_HOST.getKey() + "-" + ConfigKey.DB_PORT.getKey(),
             "host and ports number does not match",
             null);
   }
   if (1 == len) {
     try {
       return new Mongo(ha[0], Integer.parseInt(pa[0]));
     } catch (Exception e) {
       throw Configuration.root()
           .reportError(
               ConfigKey.DB_HOST.getKey() + "-" + ConfigKey.DB_PORT.getKey(),
               String.format("Cannot connect to mongodb at %s:%s", host, port),
               e);
     }
   }
   List<ServerAddress> addrs = new ArrayList<ServerAddress>(ha.length);
   for (int i = 0; i < len; ++i) {
     try {
       addrs.add(new ServerAddress(ha[i], Integer.parseInt(pa[i])));
     } catch (Exception e) {
       MorphiaLogger.error(e, "Error creating mongo connection to %s:%s", host, port);
     }
   }
   if (addrs.isEmpty()) {
     throw Configuration.root()
         .reportError(
             ConfigKey.DB_HOST.getKey() + "-" + ConfigKey.DB_PORT.getKey(),
             "Cannot connect to mongodb: no replica can be connected",
             null);
   }
   return new Mongo(addrs);
 }
 @Inject
 public ExecutionContextProvider(final Configuration config, final Application application) {
   boolean customEcEnabled =
       config.getBoolean(ConfigKeys.CUSTOM_EC_DEFAULT._1, ConfigKeys.CUSTOM_EC_DEFAULT._2);
   DeadboltExecutionContextProvider defaultProvider =
       new DefaultDeadboltExecutionContextProvider();
   DeadboltExecutionContextProvider ecp = defaultProvider;
   if (customEcEnabled) {
     try {
       ecp = application.injector().instanceOf(DeadboltExecutionContextProvider.class);
       LOGGER.debug("Custom execution context provider found");
     } catch (Exception e) {
       LOGGER.debug("No custom execution context found.");
     }
     this.ecProvider = ecp;
   } else {
     ecProvider = defaultProvider;
   }
 }
示例#19
0
  /**
   * This renders the login page for the Web IDE.
   *
   * @return The result of rendering the page.
   */
  @AddCSRFToken
  public Result index() {
    // Check the session to see if the request comes from an user
    // that has logged in already.
    String user = session().remove("connected");
    if (user != null) {
      // Obtain the http context from the configuration file
      String context = myConfiguration.getString("play.http.context");
      if (context == null) {
        context = "";
      }

      // Redirect back to the home page
      return redirect(context + "/");
    } else {
      // Render the page with the login form
      String token = CSRF.getToken(request()).map(t -> t.value()).orElse("no token");
      return ok(index.render(myFormFactory.form(LoginForm.class), token));
    }
  }
示例#20
0
  private static void startStream(List<String> terms) throws TwitterException {
    if (twitter != null) {
      twitter.cleanUp();
    }
    if (esClient != null) {
      esClient.close();
      esClient = null;
    }

    play.Configuration pconf = Play.application().configuration();
    String elasticSearchCluster = pconf.getString("tweet.elasticsearch.cluster.name");
    if (elasticSearchCluster != null) {
      Logger.info("Configuring ElasticSearch...");
      Settings settings =
          ImmutableSettings.settingsBuilder().put("cluster.name", elasticSearchCluster).build();

      esClient =
          new TransportClient(settings)
              .addTransportAddress(
                  new InetSocketTransportAddress(
                      pconf.getString("tweet.elasticsearch.transport.host"),
                      pconf.getInt("tweet.elasticsearch.transport.port")));
    } else {
      esClient = null;
    }

    twitter4j.conf.Configuration tconf = Application.getTwitterConfiguration();
    TwitterStreamFactory tf = new TwitterStreamFactory(tconf);
    twitter = tf.getInstance();
    StatusListener l =
        new TweetListener(
            terms,
            esClient,
            pconf.getString("tweet.elasticsearch.index"),
            pconf.getString("tweet.elasticsearch.type"));
    twitter.addListener(l);

    String[] tracks = new String[terms.size()];
    StringBuffer termsString = new StringBuffer();
    for (int i = 0; i < terms.size(); i++) {
      tracks[i] = terms.get(i);
      if (i != 0) termsString.append(",");
      termsString.append(terms.get(i));
    }
    FilterQuery q = new FilterQuery().track(tracks);
    twitter.filter(q);
    Logger.info("Starting listening for tweets using terms " + termsString.toString() + "...");
  }
  @Override
  protected List<NameValuePair> getAuthParams(
      final Configuration c, final Request request, final String state) throws AuthException {
    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(
        new BasicNameValuePair(
            PocketConstants.CONSUMER_KEY, c.getString(SettingKeys.CONSUMER_KEY)));

    final String requestToken = this.getRequestToken(request);
    params.add(new BasicNameValuePair(PocketConstants.REQUEST_TOKEN, requestToken));

    if (state != null) {
      params.add(new BasicNameValuePair(PocketConstants.STATE, state));
    }

    // with this we fake the response to contain the response to Play!
    // Authenticate to contain the request token in the "code" parameter
    final String redirectUrl =
        getRedirectUrl(
            request, Arrays.asList(new BasicNameValuePair(PocketConstants.CODE, requestToken)));

    params.add(new BasicNameValuePair(getRedirectUriKey(), redirectUrl));
    return params;
  }
 @Override
 public String getServerInfo() {
   return play.Configuration.root().getString("application.server");
 }
 /**
  * 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());
 }
  @Override
  public void onStart() {
    if (!isEnabled) {
      return;
    }
    // Register SLF4JLogrImplFactory as Logger
    // @see http://nesbot.com/2011/11/28/play-2-morphia-logging-error
    MorphiaLoggerFactory.reset();
    MorphiaLoggerFactory.registerLogger(SLF4JLogrImplFactory.class);

    try {
      Configuration morphiaConf = Configuration.root().getConfig(ConfigKey.PREFIX);
      if (morphiaConf == null) {
        throw Configuration.root()
            .reportError(ConfigKey.PREFIX, "Missing Morphia configuration", null);
      }

      MorphiaLogger.debug(morphiaConf);

      String dbName = morphiaConf.getString(ConfigKey.DB_NAME.getKey());
      if (StringUtils.isBlank(dbName)) {
        throw morphiaConf.reportError(
            ConfigKey.DB_NAME.getKey(), "Missing Morphia configuration", null);
      }

      // Connect to MongoDB
      String seeds = morphiaConf.getString(ConfigKey.DB_SEEDS.getKey());

      if (StringUtils.isNotBlank(seeds)) {
        mongo = connect(seeds);
      } else {
        mongo =
            connect(
                morphiaConf.getString(ConfigKey.DB_HOST.getKey()),
                morphiaConf.getString(ConfigKey.DB_PORT.getKey()));
      }

      morphia = new Morphia();
      // To prevent problem during hot-reload
      if (application.isDev()) {
        morphia.getMapper().getOptions().objectFactory = new PlayCreator();
      }
      // Configure validator
      new ValidationExtension(morphia);

      // Check if credentials parameters are present
      String username = morphiaConf.getString(ConfigKey.DB_USERNAME.getKey());
      String password = morphiaConf.getString(ConfigKey.DB_PASSWORD.getKey());

      if (StringUtils.isNotBlank(username) ^ StringUtils.isNotBlank(password)) {
        throw morphiaConf.reportError(
            ConfigKey.DB_NAME.getKey(), "Missing username or password", null);
      }

      // Create datastore
      if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
        ds = morphia.createDatastore(mongo, dbName, username, password.toCharArray());
      } else {
        ds = morphia.createDatastore(mongo, dbName);
      }

      MorphiaLogger.debug("Datastore [%s] created", dbName);
      // Create GridFS
      String uploadCollection = morphiaConf.getString(ConfigKey.COLLECTION_UPLOADS.getKey());
      if (StringUtils.isBlank(dbName)) {
        uploadCollection = "uploads";
        MorphiaLogger.warn(
            "Missing Morphia configuration key [%s]. Use default value instead [%s]",
            ConfigKey.COLLECTION_UPLOADS, "uploads");
      }
      gridfs = new GridFS(ds.getDB(), uploadCollection);
      MorphiaLogger.debug("GridFS created", "");
      MorphiaLogger.debug("Add Interceptor...", "");
      morphia
          .getMapper()
          .addInterceptor(
              new AbstractEntityInterceptor() {

                @Override
                public void postLoad(final Object ent, final DBObject dbObj, final Mapper mapr) {
                  if (ent instanceof Model) {
                    Model m = (Model) ent;
                    m._post_Load();
                  }
                }
              });
      MorphiaLogger.debug("Classes mapping...", "");
      mapClasses();
      MorphiaLogger.debug("End of initializing Morphia", "");
    } catch (MongoException e) {
      MorphiaLogger.error(e, "Problem connecting MongoDB");
      throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
      MorphiaLogger.error(e, "Problem mapping class");
      throw new RuntimeException(e);
    }
  }
 @Override
 public void onReceive(Object message) throws Exception {
   if (message instanceof ConfiguredChildActorProtocol.GetConfig) {
     sender().tell(configuration.getString(key), self());
   }
 }
示例#26
0
  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);
  }
示例#27
0
文件: Global.java 项目: hyuni/yobi
 private boolean equalsDefaultSecret() {
   return DEFAULT_SECRET.equals(play.Configuration.root().getString("application.secret"));
 }