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()); } }
/** * 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(); } }
/** * 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 void dumpSystemStatus(String eventName, boolean logAsDebug) { if (logAsDebug) { log.debug(eventName + " " + ArrayUtils.toString(getSystemStatus())); } else { log.info(eventName + " " + ArrayUtils.toString(getSystemStatus())); } }
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); }
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; }
@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()); }
/** * 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); } }
/** * 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(); } }
/* * (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); }
@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.")); }
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 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()); } } }
/** * 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(); }
@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)); }
/** * 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(); } }
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"); } }
@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(); }
/** 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)"); } }
@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; }
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(); } }
@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; }
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); }
public WSRequest url(String... urlParts) { String url = Paths.combineToUrl(urlParts); logger.debug("WSClient request to url=[{}]", url); return url(url); }
@Override public void dumpSystemConfiguration() { log.info("INITIAL CONFIGURATION " + ArrayUtils.toString(getMaxSystemParameters())); }