List of usage examples for java.sql Timestamp Timestamp
public Timestamp(long time)
From source file:gov.nih.nci.cadsrapi.dao.orm.CleanerDAO.java
public void clean() { if (sessionFactory == null) { setFactory();/*from w w w . j av a2 s . c o m*/ this.setSessionFactory(sessionFactory); } Session session = getSession(); Transaction tx = session.beginTransaction(); //Check for unexpired carts that have been active within the expiration interval and reset expiration time. int expirationInterval = 4 * 24 * 60; //Four days, in minutes int sleepTime = 60; //One hour, in minutes //Defaults int publicEmptyExpirationDays = 4 * 24 * 60; String emptyExpirationSQL = " (SYSDATE + INTERVAL '" + publicEmptyExpirationDays + "' MINUTE)"; int publicFullExpirationDays = 30 * 24 * 60; //30 days, in minutes String fullExpirationSQL = " (SYSDATE + INTERVAL '" + publicFullExpirationDays + "' MINUTE)"; try { int temp = Integer.valueOf(PropertiesLoader.getProperty("cart.time.expiration.minutes")); expirationInterval = temp; } catch (Exception e) { log.error(e); } try { int temp = Integer.valueOf(PropertiesLoader.getProperty("cart.cleaner.sleep.minutes")); sleepTime = temp; } catch (Exception e) { log.error(e); } try { int temp = Integer.valueOf(PropertiesLoader.getProperty("cart.public.empty.expiration.minutes")); publicEmptyExpirationDays = temp; } catch (Exception e) { log.error(e); } try { int temp = Integer.valueOf(PropertiesLoader.getProperty("cart.public.full.expiration.minutes")); publicFullExpirationDays = temp; } catch (Exception e) { log.error(e); } //Timestamps are in milliseconds Timestamp now = new Timestamp(System.currentTimeMillis()); Timestamp nowMinusTwiceSleep = new Timestamp(now.getTime() - sleepTime * 60 * 1000 * 2); //Converting minutes to milliseconds Timestamp nowPlusExpirationInterval = new Timestamp(now.getTime() + expirationInterval * 60 * 1000); //Converting minutes to milliseconds Query updateActiveCarts = session.createQuery( "update gov.nih.nci.cadsr.objectcart.domain.Cart set expirationDate = :nowPlusExpirationInterval" + " where (lastWriteDate > :nowMinusTwiceSleep or lastReadDate > :nowMinusTwiceSleep) and expirationDate > :now and expirationDate < :nowPlusExpirationInterval"); updateActiveCarts.setTimestamp("nowPlusExpirationInterval", nowPlusExpirationInterval); updateActiveCarts.setTimestamp("nowMinusTwiceSleep", nowMinusTwiceSleep); updateActiveCarts.setTimestamp("now", now); if (publicEmptyExpirationDays > 0 && publicEmptyExpirationDays < 365 * 24 * 60) //Check expiration is within a year emptyExpirationSQL = " (SYSDATE + INTERVAL '" + publicEmptyExpirationDays + "' MINUTE)"; else if (publicEmptyExpirationDays == 0) emptyExpirationSQL = "SYSDATE"; if (publicFullExpirationDays > 0 && publicFullExpirationDays < 365) //Check expiration is within a year fullExpirationSQL = " (SYSDATE + INTERVAL '" + publicFullExpirationDays + "' MINUTE)"; else if (publicFullExpirationDays == 0) fullExpirationSQL = "SYSDATE"; //Set expiration date to emptyExpirationSQL if the user starts with 'PublicUser' and the current expiration date is null String initializeSessionCartSql = "UPDATE cart c" + " set expiration_Date = " + emptyExpirationSQL + " where" + " (c.user_Id like 'PublicUser%') and " + " (c.expiration_Date is null)"; Query initPublicCarts = session.createSQLQuery(initializeSessionCartSql); //Set expiration date to fullExpiration if the user starts with 'PublicUser', the cart has been active (read or written to) in the last day and the cart has items //String nonEmptyCartSql = "UPDATE cart c left join cart_object co on c.id = co.cart_id " + //" set expiration_Date = "+fullExpirationSQL+" where" + //" (c.user_Id like 'PublicUser%') and " + //" (c.last_write_date > DATE_SUB(SYSDATE, INTERVAL "+ (sleepTime * 2)+" MINUTE) OR c.last_read_date > DATE_SUB(SYSDATE, INTERVAL "+ (sleepTime * 2) +" MINUTE)) and" + //" (co.id is not null)"; String nonEmptyCartSql = "UPDATE cart c " + " set expiration_Date = " + fullExpirationSQL + " where" + " (c.user_Id like 'PublicUser%') and " + " (c.last_write_date > (SYSDATE - INTERVAL '" + (sleepTime * 2) + "' MINUTE) OR c.last_read_date > (SYSDATE - INTERVAL '" + (sleepTime * 2) + "' MINUTE)) and" + " EXISTS (select id from cart_object co where co.id is not null and co.cart_id = c.id)"; Query expNonEmptyPublicCarts = session.createSQLQuery(nonEmptyCartSql); //Now delete expired carts (carts where expiration date is in the past) //REQUIRES ON-DELETE Cascade support in underlying database on the //CartObject cart_id FK constraint Query deleteCartQuery = session.createQuery( "delete from gov.nih.nci.cadsr.objectcart.domain.Cart " + "where expirationDate <=:now"); deleteCartQuery.setTimestamp("now", now); try { int resetResults = updateActiveCarts.executeUpdate(); if (resetResults > 0) log.debug("Reset expiration date for " + resetResults + "active carts"); log.debug("Reset expiration date for " + resetResults + "active carts"); /* GF 28500 */ int expResults = initPublicCarts.executeUpdate(); if (expResults > 0) log.debug("Expiration date set for " + expResults + " PublicUser carts"); int expNEPCResults = expNonEmptyPublicCarts.executeUpdate(); if (expNEPCResults > 0) log.debug("Expiration date set for " + expNEPCResults + " PublicUser carts"); /* GF 28500 */ int results = deleteCartQuery.executeUpdate(); if (results > 0) log.debug("Deleted " + results + " carts at " + now.toString()); } catch (JDBCException ex) { log.error("JDBC Exception in ORMDAOImpl ", ex); ex.printStackTrace(); } catch (org.hibernate.HibernateException hbmEx) { log.error(hbmEx.getMessage()); hbmEx.printStackTrace(); } catch (Exception e) { log.error("Exception ", e); e.printStackTrace(); } finally { try { tx.commit(); session.close(); } catch (Exception eSession) { log.error("Could not close the session - " + eSession.getMessage()); eSession.printStackTrace(); } } }
From source file:com.sae.event.resources.SessionsResource.java
@POST @ApiOperation(value = "Creates a new session", response = SessionItem.class) @ApiResponses(value = { @ApiResponse(code = 403, message = "Not allowed."), @ApiResponse(code = 404, message = "User or team not found."), @ApiResponse(code = 500, message = "Internal server error") }) @UnitOfWork/* w ww . j a va2 s . c o m*/ @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public SessionItem newSession(@ApiParam(value = "User credentials", required = true) UserCredential credential, @ApiParam(access = "internal") @Context HttpServletRequest request) { User currentUser = serviceDAO.findUniqueWithNamedQuery(User.findByUser, QueryParameters.with("USER", credential.getUsername().toLowerCase()).parameters()); if (currentUser == null) { throw new NotFoundException("User not found"); } //Simple password comparation. Not recommended. Password digest is a better aproach. if (!credential.getUserpassword().contentEquals(currentUser.getPassword_digest())) { throw new ForbiddenException("Invalid password"); } Session session = serviceDAO.findUniqueWithNamedQuery(Session.findByUser, QueryParameters.with("USER", currentUser).parameters()); if (session == null) { session = new Session(); session.setUser(currentUser); session.setCreated_at(new Timestamp(Calendar.getInstance().getTimeInMillis())); session.setUpdated_at(session.getCreated_at()); session.setApp(credential.getApp()); session.setDevice(credential.getDevice()); session.setIp(request.getRemoteAddr()); Token token = Token.buildNewToken(); session.setToken(token.getToken()); serviceDAO.create(session); return new SessionItem(session); } if (session.getToken() == null || session.getToken().isEmpty()) { Token token = Token.buildNewToken(); session.setToken(token.getToken()); session.setUpdated_at(new Timestamp(Calendar.getInstance().getTimeInMillis())); serviceDAO.update(session); return new SessionItem(session); } session.setUpdated_at(new Timestamp(Calendar.getInstance().getTimeInMillis())); session.setApp(credential.getApp()); session.setDevice(credential.getDevice()); session.setIp(request.getRemoteAddr()); serviceDAO.update(session); return new SessionItem(session); }
From source file:ltistarter.model.LtiResultEntity.java
/** * @param sourcedid the external key sourcedid * @param user the user for this grade result * @param link the link which this is a grade for * @param retrievedAt the date the grade was retrieved (null indicates now) * @param grade [OPTIONAL] the grade value */// ww w . j a v a 2s . c om public LtiResultEntity(String sourcedid, LtiUserEntity user, LtiLinkEntity link, Date retrievedAt, Float grade) { assert StringUtils.isNotBlank(sourcedid); assert user != null; assert link != null; if (retrievedAt == null) { retrievedAt = new Date(); } this.sourcedid = sourcedid; this.sourcedidSha256 = makeSHA256(sourcedid); this.retrievedAt = new Timestamp(retrievedAt.getTime()); this.user = user; this.link = link; this.grade = grade; }
From source file:com.automaster.autoview.server.servlet.ExcelServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=filename.xls"); HSSFWorkbook workbook = new HSSFWorkbook(); // .../*from www . ja v a 2 s .c o m*/ // Now populate workbook the usual way. // ... OutputStream arqSaida = response.getOutputStream(); workbook.write(arqSaida); // Write workbook to response. arqSaida.flush(); arqSaida.close();*/ //getServletContext().getRealPath("/") String tempoDecorrido = " 0"; String url = getServletContext().getRealPath("/"); String placa = request.getParameter("placa"); //TimeZone timeZoneMundial = TimeZone.getTimeZone(ZoneId.ofOffset("UTC", ZoneOffset.UTC)); Timestamp dataInicio = new Timestamp(Long.parseLong(request.getParameter("dataInicio"))); Timestamp dataFim = new Timestamp(Long.parseLong(request.getParameter("dataFim"))); //String timeZoneInterface = request.getParameter("timeZone"); /*String timeZone = "Z"; if(timeZoneInterface.equalsIgnoreCase("0")){ timeZone = "Z"; } else { timeZone = String.valueOf((-1) * (Integer.parseInt(timeZoneInterface) / 60)); } */ TimeZone timeZonePadrao = TimeZone.getTimeZone(ZoneId.of("-3")); System.out.println("Time zone Cliente : " + timeZonePadrao); //System.out.println("timeZoneInterface: "+timeZoneInterface); //System.out.println("timeZone: "+timeZone); //String ign = request.getParameter("ign"); ZzzPosPlacaVeiculoDAO zzzPosPlacaVeiculoDAO = new ZzzPosPlacaVeiculoDAO(); ArrayList<TreeMap<String, String>> posicoes = zzzPosPlacaVeiculoDAO.buscarPosicoesPorIntervaloData(placa, dataInicio, dataFim); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", "attachment; filename=Historico-" + placa + ".xlsx"); Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("Histrico - " + placa); int pictureIdx; try ( //add picture data to this workbook. InputStream is = new FileInputStream(url + "/imagens/logo.jpg")) { byte[] bytes = IOUtils.toByteArray(is); pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG); } CreationHelper helper = wb.getCreationHelper(); // Create the drawing patriarch. This is the top level container for all shapes. Drawing drawing = sheet.createDrawingPatriarch(); //add a picture shape ClientAnchor anchor = helper.createClientAnchor(); //set top-left corner of the picture, //subsequent call of Picture#resize() will operate relative to it anchor.setCol1(1); anchor.setRow1(0); Picture pict = drawing.createPicture(anchor, pictureIdx); //auto-size picture relative to its top-left corner pict.resize(3, 3); //pict.resize(); //sheet.setColumnWidth(0, 200); Font fonte = wb.createFont(); fonte.setFontHeightInPoints((short) 24); fonte.setFontName("Arial"); fonte.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); fonte.setItalic(true); CellStyle estiloTitulo = wb.createCellStyle(); estiloTitulo.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloTitulo.setFont(fonte); Font fonteCabecalho = wb.createFont(); fonteCabecalho.setFontHeightInPoints((short) 14); fonteCabecalho.setFontName("Arial"); fonteCabecalho.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //fonteCabecalho.setItalic(true); CellStyle estiloCabecalho = wb.createCellStyle(); estiloCabecalho.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloCabecalho.setFont(fonteCabecalho); Font fonteTituloTabela = wb.createFont(); //fonteTituloTabela.setFontHeightInPoints((short) 14); fonteTituloTabela.setFontName("Arial"); fonteTituloTabela.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); CellStyle estilo = wb.createCellStyle(); estilo.setAlignment(HSSFCellStyle.ALIGN_CENTER); estilo.setFont(fonteTituloTabela); CellStyle estiloCorpo = wb.createCellStyle(); estiloCorpo.setAlignment(HSSFCellStyle.ALIGN_CENTER); //estiloCorpo.setFillBackgroundColor(HSSFColor.WHITE.index); //estiloCorpo.setFont(fonteTituloTabela); XSSFRow linha6 = (XSSFRow) sheet.createRow(6); XSSFCell cell046 = linha6.createCell(3); cell046.setCellValue("Relatrio de Posies"); cell046.setCellStyle(estiloTitulo); //sheet.addMergedRegion(new CellRangeAddress(6, 6, 0, 3)); XSSFRow linha7 = (XSSFRow) sheet.createRow(7); XSSFCell cell047 = linha7.createCell(3); cell047.setCellValue("Veculo : " + placa); cell047.setCellStyle(estiloCabecalho); //sheet.addMergedRegion(new CellRangeAddress(7, 7, 0, 3)); XSSFRow linha8 = (XSSFRow) sheet.createRow(8); XSSFCell cell038 = linha8.createCell(3); //TimeZone.setDefault(timeZoneMundial); //Date dataHoraInicio0 = new Date(Long.parseLong(request.getParameter("dataInicio"))); //TimeZone.setDefault(timeZoneCliente); //Date dataHoraInicio = new Date(dataHoraInicio0.getTime()); SimpleDateFormat dataFormatadaCabecalho = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); dataFormatadaCabecalho.setTimeZone(timeZonePadrao); cell038.setCellValue("Perodo: De: " + dataFormatadaCabecalho.format(dataInicio) + " at: " + dataFormatadaCabecalho.format(dataFim)); cell038.setCellStyle(estiloCabecalho); //sheet.addMergedRegion(new CellRangeAddress(8, 8, 0, 3)); sheet.setColumnWidth(0, 5000); sheet.setColumnWidth(1, 3000); sheet.setColumnWidth(2, 3500); //sheet.setColumnWidth(3, 4000); sheet.setColumnWidth(3, 30000); //sheet.setColumnWidth(4, 4000); //sheet.setColumnWidth(4, 30000); sheet.setColumnWidth(5, 3000); sheet.setColumnWidth(6, 3000); sheet.setColumnWidth(7, 3000); sheet.setColumnWidth(8, 3000); sheet.setColumnWidth(9, 3000); //sheet.setColumnWidth(10, 20000); sheet.setColumnWidth(11, 3000); XSSFRow linha9 = (XSSFRow) sheet.createRow(10); XSSFCell cell0 = linha9.createCell(0); cell0.setCellValue("Data e hora"); cell0.setCellStyle(estilo); XSSFCell cell1 = linha9.createCell(1); cell1.setCellValue("Velocidade"); cell1.setCellStyle(estilo); XSSFCell cell2 = linha9.createCell(2); cell2.setCellValue("Ignio"); cell2.setCellStyle(estilo); //XSSFCell cell3 = linha9.createCell(3); //cell3.setCellValue("Latitude"); //cell3.setCellStyle(estilo); //XSSFCell cell4 = linha9.createCell(4); //cell4.setCellValue("Longitude"); //cell4.setCellStyle(estilo); //XSSFCell cell5 = linha9.createCell(5); //cell5.setCellValue("Satlite"); //cell5.setCellStyle(estilo); //XSSFCell cell6 = linha9.createCell(6); //cell6.setCellValue("GPS"); //cell6.setCellStyle(estilo); //XSSFCell cell7 = linha9.createCell(7); //cell7.setCellValue("Entrada"); //cell7.setCellStyle(estilo); //XSSFCell cell8 = linha9.createCell(8); //cell8.setCellValue("Sada"); //cell8.setCellStyle(estilo); //XSSFCell cell9 = linha9.createCell(9); //cell9.setCellValue("Evento"); //cell9.setCellStyle(estilo); XSSFCell cell10 = linha9.createCell(3); cell10.setCellValue("Endereo"); cell10.setCellStyle(estilo); //sheet.addMergedRegion(new CellRangeAddress(11, 11, 4, 8)); //XSSFCell cell11 = linha9.createCell(11); //cell11.setCellValue("Direo"); //cell11.setCellStyle(estilo); int linha = 0; int j = 11; double latAnt = 0; double lonAnt = 0; double latAtual = 0; double lonAtual = 0; double distancia = 0; double distanciaTotal = 0; for (int i = 0; i < posicoes.size(); i++) { XSSFRow row = (XSSFRow) sheet.createRow(j); if (i == 0) { distancia = 0; //System.out.println("linha 00 - EXCEL"); } else { //System.out.println("linha 01 - EXCEL"); latAnt = Double.parseDouble(posicoes.get(i - 1).get("lat")); lonAnt = Double.parseDouble(posicoes.get(i - 1).get("lon")); latAtual = Double.parseDouble(posicoes.get(i).get("lat")); lonAtual = Double.parseDouble(posicoes.get(i).get("lon")); //System.out.println("linha 02 - PDF"); if (latAnt == latAtual && lonAnt == lonAtual) { distancia = 0; } else { distancia = caculaDistanciaEntreDoisPontos(latAnt, lonAnt, latAtual, lonAtual); //System.out.println("linha 03 - PDF"); } } distanciaTotal = distanciaTotal + distancia; /*if(i==0) { latAnt = Double.parseDouble(posicoes.get(i).get("lat")); lonAnt = Double.parseDouble(posicoes.get(i).get("lon")); } else{ latAnt = Double.parseDouble(posicoes.get(i-1).get("lat")); lonAnt = Double.parseDouble(posicoes.get(i-1).get("lon")); } double latAtual = Double.parseDouble(posicoes.get(i).get("lat")); double lonAtual = Double.parseDouble(posicoes.get(i).get("lon")); double distancia = caculaDistanciaEntreDoisPontos(latAnt, lonAnt, latAtual, lonAtual); distanciaTotal = distanciaTotal + distancia;*/ for (int col = 0; col < posicoes.get(linha).size(); col++) { XSSFCell cell = row.createCell(col); cell.setCellStyle(estiloCorpo); switch (col) { case 0: Date dataHora0 = new Date(Long.parseLong(posicoes.get(i).get("dataHora"))); Date dataHora = new Date(dataHora0.getTime()); SimpleDateFormat dataFormatada = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); dataFormatada.setTimeZone(timeZonePadrao); cell.setCellValue(dataFormatada.format(dataHora)); break; case 1: cell.setCellValue(posicoes.get(linha).get("vel")); break; case 2: cell.setCellValue( posicoes.get(linha).get("ign").equalsIgnoreCase("True") ? "Ligada" : "Desligada"); break; /*case 3: cell.setCellValue(posicoes.get(linha).get("lat")); break; case 4: cell.setCellValue(posicoes.get(linha).get("lon")); break; case 5: cell.setCellValue(posicoes.get(linha).get("sat")); break; case 6: cell.setCellValue(posicoes.get(linha).get("gps")); break; case 7: cell.setCellValue(posicoes.get(linha).get("entrada")); break; case 8: cell.setCellValue(posicoes.get(linha).get("saida")); break; case 9: cell.setCellValue(posicoes.get(linha).get("evento")); break;*/ case 3: cell.setCellValue(posicoes.get(linha).get("endereco") == null ? "Sem endereo" : posicoes.get(linha).get("endereco")); break; /*case 11: cell.setCellValue(posicoes.get(linha).get("direcao")); break;*/ } } j = j + 1; linha = linha + 1; } tempoDecorrido = calculaDatas(Long.parseLong(posicoes.get(0).get("dataHora")), Long.parseLong(posicoes.get(posicoes.size() - 1).get("dataHora"))); int index = 0; String kms = "0"; String m = ""; double metros = 0; if (distanciaTotal > 0) { BigDecimal decimalFormatado = new BigDecimal(distanciaTotal).setScale(2, RoundingMode.HALF_EVEN); index = String.valueOf(decimalFormatado).indexOf("."); kms = String.valueOf(decimalFormatado).substring(0, index); m = "0" + (String.valueOf(decimalFormatado).substring(index)); metros = Double.parseDouble(m) * 1000; } //String formatted = NumberFormat.getFormat("000.00").format(metros); //System.out.println("Percorridos aproximadamente : "+kms+" KM e "+metros+" metros"); XSSFRow linhaX = (XSSFRow) sheet.createRow(linha + 12); XSSFCell cellX = linhaX.createCell(0); sheet.addMergedRegion(new CellRangeAddress(linha + 12, linha + 12, 0, 3)); cellX.setCellStyle(estilo); cellX.setCellValue( "Percorridos: " + kms + " KM e " + String.valueOf(metros) + " metros. Tempo: " + tempoDecorrido); ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); wb.write(outByteStream); byte[] outArray = outByteStream.toByteArray(); OutputStream outStream = response.getOutputStream(); outStream.write(outArray); outStream.flush(); }
From source file:iddb.web.security.dao.SessionDAO.java
public void cleanUp(Long expire) { String sql;/*from www.j a va2 s.c o m*/ sql = "delete from user_session where created < ?"; Connection conn = null; try { conn = ConnectionFactory.getMasterConnection(); PreparedStatement st = conn.prepareStatement(sql); st.setTimestamp(1, new Timestamp(DateUtils.addDays(new Date(), expire.intValue() * -1).getTime())); int r = st.executeUpdate(); log.debug("Removed {} sessions", Integer.toString(r)); } catch (SQLException e) { log.error("cleanUp", e); } catch (IOException e) { log.error("cleanUp", e); } finally { try { if (conn != null) conn.close(); } catch (Exception e) { } } }
From source file:org.cloudfoundry.identity.uaa.codestore.CodeStoreEndpointsTests.java
@Test public void testGenerateCodeWithNullData() throws Exception { Timestamp expiresAt = new Timestamp(System.currentTimeMillis() + 60000); ExpiringCode expiringCode = new ExpiringCode(null, expiresAt, null); try {//from ww w . j a v a2 s . co m codeStoreEndpoints.generateCode(expiringCode); fail("code is null, should throw CodeStoreException."); } catch (CodeStoreException e) { assertEquals(e.getStatus(), HttpStatus.BAD_REQUEST); } }
From source file:ru.org.linux.auth.BanIPController.java
@RequestMapping(value = "/banip.jsp", method = RequestMethod.POST) public ModelAndView banIP(HttpServletRequest request, @RequestParam("ip") String ip, @RequestParam("reason") String reason, @RequestParam("time") String time, @RequestParam(value = "allow_posting", required = false, defaultValue = "false") boolean allowPosting, @RequestParam(value = "captcha_required", required = false, defaultValue = "false") boolean captchaRequired) throws Exception { Template tmpl = Template.getTemplate(request); if (!tmpl.isModeratorSession()) { throw new IllegalAccessException("Not authorized"); }//from w w w. j av a 2s . c o m Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); if ("hour".equals(time)) { calendar.add(Calendar.HOUR_OF_DAY, 1); } else if ("day".equals(time)) { calendar.add(Calendar.DAY_OF_MONTH, 1); } else if ("month".equals(time)) { calendar.add(Calendar.MONTH, 1); } else if ("3month".equals(time)) { calendar.add(Calendar.MONTH, 3); } else if ("6month".equals(time)) { calendar.add(Calendar.MONTH, 6); } else if ("remove".equals(time)) { } else if ("custom".equals(time)) { int days = ServletRequestUtils.getRequiredIntParameter(request, "ban_days"); if (days <= 0 || days > 180) { throw new UserErrorException("Invalid days count"); } calendar.add(Calendar.DAY_OF_MONTH, days); } Timestamp ts; if ("unlim".equals(time)) { ts = null; } else { ts = new Timestamp(calendar.getTimeInMillis()); } User user = tmpl.getCurrentUser(); user.checkCommit(); ipBlockDao.blockIP(ip, user, reason, ts, allowPosting, captchaRequired); return new ModelAndView(new RedirectView("sameip.jsp?ip=" + URLEncoder.encode(ip, "UTF-8"))); }
From source file:com.hangum.tadpole.sql.query.TadpoleSystem_SchemaHistory.java
/** * save schema_history /* w w w .ja v a2 s.co m*/ * * @param user_seq * @param userDB * @param strSQL */ public static SchemaHistoryDAO save(int user_seq, UserDBDAO userDB, String strSQL) { SchemaHistoryDAO schemaDao = new SchemaHistoryDAO(); try { // // // String strWorkSQL = strSQL.replaceAll("(\r\n|\n|\r)", ""); // ? . strWorkSQL = strWorkSQL.replaceAll("\\p{Space}", " "); // ? . if (logger.isDebugEnabled()) logger.debug("[start sql]\t" + strWorkSQL); String[] arrSQL = StringUtils.split(strWorkSQL); String strWorkType = arrSQL[0]; // object type String strObjecType = arrSQL[1]; // objectId String strObjectId = StringUtils.remove(arrSQL[2], "("); if (StringUtils.equalsIgnoreCase("or", strObjecType)) { strObjecType = arrSQL[3]; strObjectId = StringUtils.remove(arrSQL[4], "("); } schemaDao = new SchemaHistoryDAO(); schemaDao.setDb_seq(userDB.getSeq()); schemaDao.setUser_seq(user_seq); schemaDao.setWork_type(strWorkType); schemaDao.setObject_type(strObjecType); schemaDao.setObject_id(strObjectId); schemaDao.setCreate_date(new Timestamp(System.currentTimeMillis())); SqlMapClient sqlClient = TadpoleSQLManager.getInstance(TadpoleSystemInitializer.getUserDB()); SchemaHistoryDAO schemaHistoryDao = (SchemaHistoryDAO) sqlClient.insert("sqlHistoryInsert", schemaDao); //$NON-NLS-1$ insertResourceData(schemaHistoryDao, strSQL); } catch (Exception e) { logger.error("Schema histor save error", e); } return schemaDao; }
From source file:com.leixl.easyframework.system.service.impl.EUserServiceImpl.java
public EUser registMember(String email, String password, String nickName, String ip, HttpServletRequest request, HttpServletResponse response) {//from w w w . j av a 2 s . c om Date now = new Timestamp(System.currentTimeMillis()); EUser user = new EUser(); user.setEmail(email); user.setPassword(pwdEncoder.encodePassword(password)); user.setRegisterIp(ip); user.setRegisterTime(now); user.setLastLoginIp(ip); user.setLastLoginTime(now); user.setAdmin(false); //?? user.setActivation(true); user.init(); dao.save(user); session.setAttribute(request, response, AUTH_KEY, user.getId()); return user; }
From source file:ke.co.tawi.babblesms.server.persistence.logs.OutgoingLogDAO.java
/** * @see ke.co.tawi.babblesms.server.persistence.logs.BabbleOutgoingLogDAO#put(ke.co.tawi.babblesms.server.beans.log.OutgoingLog) *///from w w w . j av a 2 s. c om @Override public boolean put(OutgoingLog outgoingLog) { boolean success = true; try (Connection conn = dbCredentials.getConnection(); PreparedStatement pstmt = conn.prepareStatement("INSERT INTO OutgoingLog " + "(Uuid, origin, destination, message, logtime, networkuuid, sender, messagestatusuuid, phoneuuid) " + "VALUES (?,?,?,?,?,?,?,?,?);");) { pstmt.setString(1, outgoingLog.getUuid()); pstmt.setString(2, outgoingLog.getOrigin()); pstmt.setString(3, outgoingLog.getDestination()); pstmt.setString(4, outgoingLog.getMessage()); pstmt.setTimestamp(5, new Timestamp(outgoingLog.getLogTime().getTime())); pstmt.setString(6, outgoingLog.getNetworkUuid()); pstmt.setString(7, outgoingLog.getSender()); pstmt.setString(8, outgoingLog.getMessagestatusuuid()); pstmt.setString(9, outgoingLog.getPhoneUuid()); pstmt.execute(); } catch (SQLException e) { logger.error("SQL Exception when trying to put " + outgoingLog); logger.error(ExceptionUtils.getStackTrace(e)); success = false; } return success; }