List of usage examples for java.sql Timestamp toString
@SuppressWarnings("deprecation") public String toString()
From source file:org.xmlactions.mapping.bean_to_xml.PopulatorFromTimestamp.java
public Element performElementAction(List<KeyValue> keyvalues, BeanToXml beanToXml, Element parent, Object object, String namespacePrefix, String elementName, String beanRef) { if (object instanceof Timestamp) { Timestamp timestamp = (Timestamp) object; String output;// w w w . jav a2 s. c o m String format = getKeyValue(keyvalues, MappingConstants.TIME_FORMAT); if (StringUtils.isNotEmpty(format)) { output = DateFormatUtils.format(timestamp.getTime(), format); } else { output = timestamp.toString(); } Element element = BeanToXmlUtils.addElement(parent, namespacePrefix, elementName); element.setText(output); return element; } else { throw new IllegalArgumentException("The object parameter must be a " + Timestamp.class.getName() + " not [" + object.getClass().getName() + "]"); } }
From source file:org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImplTests.java
@Test public void updatingTokenModifiesTokenValueAndLastUsed() { Timestamp ts = new Timestamp(System.currentTimeMillis() - 1); template.execute("insert into persistent_logins (series, username, token, last_used) values " + "('joesseries', 'joeuser', 'atoken', '" + ts.toString() + "')"); repo.updateToken("joesseries", "newtoken", new Date()); Map<String, Object> results = template .queryForMap("select * from persistent_logins where series = 'joesseries'"); assertThat(results.get("username")).isEqualTo("joeuser"); assertThat(results.get("series")).isEqualTo("joesseries"); assertThat(results.get("token")).isEqualTo("newtoken"); Date lastUsed = (Date) results.get("last_used"); assertThat(lastUsed.getTime() > ts.getTime()).isTrue(); }
From source file:org.freebxml.omar.server.persistence.rdb.AuditableEventDAO.java
/** * Returns the SQL fragment string needed by insert or update statements * within insert or update method of sub-classes. This is done to avoid code * duplication./*ww w . java2 s .c o m*/ */ protected String getSQLStatementFragment(Object ro) throws RegistryException { AuditableEventType auditableEvent = (AuditableEventType) ro; String stmtFragment = null; String requestId = auditableEvent.getRequestId(); String eventType = auditableEvent.getEventType(); if (auditableEvent.getTimestamp() == null) { Calendar timeNow = Calendar.getInstance(); auditableEvent.setTimestamp(timeNow); } Timestamp timestamp = new Timestamp(auditableEvent.getTimestamp().getTimeInMillis()); //??The timestamp is being truncated to work around a bug in PostgreSQL 7.2.2 JDBC driver String timestampStr = timestamp.toString().substring(0, 19); String aeUser = auditableEvent.getUser(); if (aeUser == null) { UserType user = context.getUser(); if (user != null) { aeUser = user.getId(); } } if (action == DAO_ACTION_INSERT) { stmtFragment = "INSERT INTO AuditableEvent " + super.getSQLStatementFragment(ro) + ", '" + requestId + "', '" + eventType + "', '" + timestampStr + "', '" + aeUser + "' ) "; } else if (action == DAO_ACTION_UPDATE) { stmtFragment = "UPDATE AuditableEvent SET " + super.getSQLStatementFragment(ro) + ", requestId='" + requestId + "', eventType='" + eventType + "', timestamp_='" + timestampStr + "', user_='" + aeUser + "' WHERE id = '" + ((RegistryObjectType) ro).getId() + "' "; } else if (action == DAO_ACTION_DELETE) { stmtFragment = super.getSQLStatementFragment(ro); } return stmtFragment; }
From source file:org.apache.drill.exec.store.hive.HiveTestDataGenerator.java
private String generateTestDataFileForPartitionInput() throws Exception { final File file = getTempFile(); PrintWriter printWriter = new PrintWriter(file); String partValues[] = { "1", "2", "null" }; for (int c = 0; c < partValues.length; c++) { for (int d = 0; d < partValues.length; d++) { for (int e = 0; e < partValues.length; e++) { for (int i = 1; i <= 5; i++) { Date date = new Date(System.currentTimeMillis()); Timestamp ts = new Timestamp(System.currentTimeMillis()); printWriter.printf("%s,%s,%s,%s,%s", date.toString(), ts.toString(), partValues[c], partValues[d], partValues[e]); printWriter.println(); }//from www . j a v a2s . c o m } } } printWriter.close(); return file.getPath(); }
From source file:org.globusonline.nexus.GlobusOnlineRestClient.java
JSONObject getAuthHeaders(String method, String url) { JSONObject oauthParams = new JSONObject(); JSONObject authHeaders = new JSONObject(); Date date = new Date(); Timestamp time = new Timestamp(date.getTime()); try {// www . j av a2 s .com oauthParams.put("oauth_version", "1.0"); oauthParams.put("oauth_nonce", generateNonce()); oauthParams.put("oauth_timestamp", Integer.valueOf(time.toString())); } catch (JSONException e) { logger.error("JSON Exception."); e.printStackTrace(); } // OAuthRequest oauthRequest = new OAuthRequest(method, url, oauthParams); // JSONObject consumer = Consumer(currentUser, oauthSecret); // oauthRequest.sign_request(SignatureMethod_HMAC_SHA1(), consumer, null); // auth_headers = oauthRequest.to_header(); // auth_headers = auth_headers['Authorization'].encode('utf-8'); return authHeaders; }
From source file:ejemplo.bean.TaskBean.java
public String login() throws IOException { Task t = new Task(); String fichero;//w w w .j av a 2s . c om Task editTarea = null; RequestContext context = RequestContext.getCurrentInstance(); FacesMessage message; boolean loggedIn = true; Timestamp insertarTiempo; insertarTiempo = new Timestamp(tiempo.getTime()); t.setNombre_tarea(titulo); t.setDescription(descripcion); t.setEstado_tarea(estadoSeleccionado); t.setTiempo_estimado(insertarTiempo.toString()); Calendar cal = Calendar.getInstance(); t.setFecha_ini(cal.getTime().toString()); t.setId_tarea(String.valueOf(System.currentTimeMillis())); t.setNombre_usuario(loginBean.user.getNombre()); if (!file.getFileName().equals("")) { byte[] bytes = IOUtils.toByteArray(file.getInputstream()); String realPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/"); t.setFichero("/resources/files/" + file.getFileName()); t.setNombre_fichero(file.getFileName()); FileOutputStream os = new FileOutputStream(realPath + "resources/files/" + file.getFileName()); os.write(bytes); os.close(); } Projects selectedProject = loginBean.getSelectedProject(); List<Task> tareas = selectedProject.getTareas(); if (tareas == null) { List<Task> tareasInsertar = new ArrayList<>(); tareasInsertar.add(t); selectedProject.setTareas(tareasInsertar); } else { selectedProject.getTareas().add(t); } dashboardView.RefreshDash(); projectsService.editProjects(selectedProject); loginBean.setSelectedProject(selectedProject); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Tarea", "La tarea se ha creado correctamente"); FacesContext.getCurrentInstance().addMessage(null, message); context.addCallbackParam("loggedIn", loggedIn); return ""; }
From source file:uk.org.funcube.fcdw.server.extract.csv.HighResCsvExtractor.java
private void writeRecord(CsvWriter csvOutput, Timestamp satelliteTime, String c1, String c2, String c3, String c4, String c5, String c6, String c7) throws IOException { for (int i = 0; i < 15; i++) { switch (i) { case 0:/*from w ww . j a v a 2s . c om*/ csvOutput.write(satelliteTime.toString()); break; case 1: csvOutput.write(c1); break; case 2: csvOutput.write(c2); break; case 3: csvOutput.write(c3); break; case 4: csvOutput.write(c4); break; case 5: csvOutput.write(c5); break; case 6: csvOutput.write(c6); break; case 7: csvOutput.write(c7); break; } } csvOutput.endRecord(); }
From source file:org.pentaho.di.trans.steps.orabulkloader.OraBulkDataOutput.java
@SuppressWarnings("ArrayToString") public void writeLine(RowMetaInterface mi, Object[] row) throws KettleException { if (first) {/*from ww w .j a va2 s . co m*/ first = false; enclosure = meta.getEnclosure(); // Setup up the fields we need to take for each of the rows // as this speeds up processing. fieldNumbers = new int[meta.getFieldStream().length]; for (int i = 0; i < fieldNumbers.length; i++) { fieldNumbers[i] = mi.indexOfValue(meta.getFieldStream()[i]); if (fieldNumbers[i] < 0) { throw new KettleException("Could not find field " + meta.getFieldStream()[i] + " in stream"); } } sdfDate = new SimpleDateFormat("yyyy-MM-dd"); sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); outbuf = new StringBuilder(); } outbuf.setLength(0); // Write the data to the output ValueMetaInterface v; int number; for (int i = 0; i < fieldNumbers.length; i++) { if (i != 0) { outbuf.append(","); } v = mi.getValueMeta(i); number = fieldNumbers[i]; if (row[number] == null) { // TODO (SB): special check for null in case of Strings. outbuf.append(enclosure); outbuf.append(enclosure); } else { switch (v.getType()) { case ValueMetaInterface.TYPE_STRING: String s = mi.getString(row, number); if (s.contains(enclosure)) { s = createEscapedString(s, enclosure); } outbuf.append(enclosure); outbuf.append(s); outbuf.append(enclosure); break; case ValueMetaInterface.TYPE_INTEGER: Long l = mi.getInteger(row, number); outbuf.append(enclosure); outbuf.append(l); outbuf.append(enclosure); break; case ValueMetaInterface.TYPE_NUMBER: Double d = mi.getNumber(row, number); outbuf.append(enclosure); outbuf.append(d); outbuf.append(enclosure); break; case ValueMetaInterface.TYPE_BIGNUMBER: BigDecimal bd = mi.getBigNumber(row, number); outbuf.append(enclosure); outbuf.append(bd); outbuf.append(enclosure); break; case ValueMetaInterface.TYPE_DATE: Date dt = mi.getDate(row, number); outbuf.append(enclosure); String mask = meta.getDateMask()[i]; if (OraBulkLoaderMeta.DATE_MASK_DATETIME.equals(mask)) { outbuf.append(sdfDateTime.format(dt)); } else { // Default is date format outbuf.append(sdfDate.format(dt)); } outbuf.append(enclosure); break; case ValueMetaInterface.TYPE_BOOLEAN: Boolean b = mi.getBoolean(row, number); outbuf.append(enclosure); if (b) { outbuf.append("Y"); } else { outbuf.append("N"); } outbuf.append(enclosure); break; case ValueMetaInterface.TYPE_BINARY: byte[] byt = mi.getBinary(row, number); outbuf.append("<startlob>"); // TODO REVIEW - implicit .toString outbuf.append(byt); outbuf.append("<endlob>"); break; case ValueMetaInterface.TYPE_TIMESTAMP: Timestamp timestamp = (Timestamp) mi.getDate(row, number); outbuf.append(enclosure); outbuf.append(timestamp.toString()); outbuf.append(enclosure); break; default: throw new KettleException("Unsupported type"); } } } outbuf.append(recTerm); try { output.append(outbuf); } catch (IOException e) { throw new KettleException("IO exception occured: " + e.getMessage(), e); } }
From source file:isl.FIMS.servlet.export.ExportXML.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.initVars(request); String username = getUsername(request); boolean isGuest = this.getRights(username).equals("guest"); if (!isGuest) { try {/*from w ww . j a va 2 s .c o m*/ String filePath = this.export_import_Folder; java.util.Date date = new java.util.Date(); Timestamp t = new Timestamp(date.getTime()); String currentDir = filePath + t.toString().replaceAll(":", "").replaceAll("\\s", ""); File saveDir = new File(currentDir); saveDir.mkdir(); Config conf = new Config("EksagwghXML"); String type = request.getParameter("type"); String id = request.getParameter("id"); request.setCharacterEncoding("UTF-8"); DBCollection col = new DBCollection(this.DBURI, this.systemDbCollection + type, this.DBuser, this.DBpassword); String collectionPath = UtilsQueries.getPathforFile(col, id + ".xml", id.split(type)[1]); col = new DBCollection(this.DBURI, collectionPath, this.DBuser, this.DBpassword); DBFile dbf = col.getFile(id + ".xml"); String isWritable = "true"; if (GetEntityCategory.getEntityCategory(type).equals("primary")) { isWritable = dbf .queryString("//admin/write='" + username + "'" + "or //admin/status='published'")[0]; } if (isWritable.equals("true")) { String[] res = dbf.queryString("//admin/refs/ref"); ServletOutputStream outStream = response.getOutputStream(); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=\"" + id + ".zip\""); writeFile(type, id, currentDir, username); for (int i = 0; i < res.length; i++) { Element e = Utils.getElement(res[i]); String sps_type = e.getAttribute("sps_type"); String sps_id = e.getAttribute("sps_id"); sps_id = sps_type + sps_id; writeFile(sps_type, sps_id, currentDir, username); } //check if any disk files to export ArrayList<String> externalFiles = new <String>ArrayList(); String q = "//*["; for (String attrSet : this.uploadAttributes) { String[] temp = attrSet.split("#"); String func = temp[0]; String attr = temp[1]; if (func.contains("text")) { q += "@" + attr + "]/text()"; } else { q = "data(//*[@" + attr + "]/@" + attr + ")"; } String[] result = dbf.queryString(q); for (String extFile : result) { externalFiles.add(extFile + "#" + attr); } } for (String extFile : externalFiles) { DBFile uploadsDBFile = new DBFile(this.DBURI, this.adminDbCollection, "Uploads.xml", this.DBuser, this.DBpassword); String attr = extFile.substring(extFile.lastIndexOf("#") + 1, extFile.length()); extFile = extFile.substring(0, extFile.lastIndexOf("#")); String mime = Utils.findMime(uploadsDBFile, extFile, attr); String path = ""; if (mime.equals("Photos")) { path = this.systemUploads + File.separator + type + File.separator + mime + File.separator + "original" + File.separator + extFile; } else { path = this.systemUploads + File.separator + type + File.separator + mime + File.separator + extFile; } File f = new File(path); if (f.exists()) { if (extFile.startsWith("../")) { extFile = extFile.replace("../", ""); File file = new File( currentDir + System.getProperty("file.separator") + id + ".xml"); if (!file.exists()) { file = new File( currentDir + System.getProperty("file.separator") + id + ".x3ml"); } if (file.exists()) { String content = FileUtils.readFileToString(file); content = content.replaceAll("../" + extFile, extFile); FileUtils.writeStringToFile(file, content); } } FileUtils.copyFile(f, new File(currentDir + System.getProperty("file.separator") + extFile)); } } File f = new File(currentDir + System.getProperty("file.separator") + "zip"); f.mkdir(); String zip = f.getAbsolutePath() + System.getProperty("file.separator") + id + ".zip"; Utils.createZip(zip, currentDir); Utils.downloadZip(outStream, new File(zip)); } else { String displayMsg = ""; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); displayMsg = Messages.ACCESS_DENIED; StringBuilder xml = new StringBuilder( this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request)); xml.append("<Display>").append(displayMsg).append("</Display>\n"); xml.append(this.xmlEnd()); String xsl = conf.DISPLAY_XSL; try { XMLTransform xmlTrans = new XMLTransform(xml.toString()); xmlTrans.transform(out, xsl); } catch (DMSException e) { } out.close(); } Utils.deleteDir(currentDir); } catch (Exception ex) { ex.printStackTrace(); } } }
From source file:org.botlibre.util.Utils.java
/** * Print the date in the form, "yyyy-MM-dd HH:mm:ss.N". *///from w ww. ja v a2 s . c o m public static String printTimestamp(Timestamp timestamp) { if (timestamp == null) { return ""; } return timestamp.toString(); }