List of usage examples for java.sql ResultSet getTimestamp
java.sql.Timestamp getTimestamp(String columnLabel) throws SQLException;
ResultSet
object as a java.sql.Timestamp
object in the Java programming language. From source file:org.cbarrett.lcbo.db.mapper.LCBOProductExtractor.java
@Override public Product extractData(ResultSet rs) throws SQLException { Product prod = new Product(); prod.setId(rs.getString(1));/*from w w w. j a v a 2s . c o m*/ prod.setProducer_name(rs.getString(2)); prod.setName(rs.getString(3)); prod.setDescription(rs.getString(4)); prod.setAlcohol_content(rs.getInt(5)); prod.setIs_dead(rs.getBoolean(6)); prod.setIs_discontinued(rs.getBoolean(7)); if (rs.getString(8) != null) { prod.setStock_type(StockType.valueOf(rs.getString(8))); } prod.setPrice_in_cents(rs.getInt(9)); prod.setOrigin(rs.getString(10)); prod.setPrimary_category(rs.getString(11)); prod.setSecondary_category(rs.getString(12)); if (rs.getTimestamp(13) != null) { prod.setReleasedOn(new DateTime((rs.getTimestamp(13)).getTime())); } prod.setInventory_count(rs.getInt(14)); if (rs.getTimestamp(15) != null) { prod.setUpdatedAt(new DateTime((rs.getTimestamp(15)).getTime())); } prod.setImageThumbUrl(rs.getString(15)); prod.setImageUrl(rs.getString(16)); return prod; }
From source file:dhbw.clippinggorilla.objects.user.UserUtils.java
/** * Get a User via given id/* w w w . j a v a 2 s. c om*/ * * @param id The id of the requested User * @return The requested User (or a exception is thrown) */ public static User getUser(int id) throws UserNotFoundException { if (USERS_PER_ID.containsKey(id)) { User u = USERS_PER_ID.get(id); addUser(u); return u; } String sql = "SELECT * FROM " + Tables.USER + " WHERE " + Columns.ID + " = ?"; User u = new User(); try { PreparedStatement stat = Database.getConnection().prepareStatement(sql); stat.setInt(1, id); ResultSet result = stat.executeQuery(); if (result.next()) { u.setId(result.getInt(Columns.ID)); u.setUsername(result.getString(Columns.USERNAME)); u.setPassword(result.getString(Columns.PASSWORD)); u.setSalt(result.getString(Columns.SALT)); u.setEmail(result.getString(Columns.EMAIL)); u.setFirstName(result.getString(Columns.FIRST_NAME)); u.setLastName(result.getString(Columns.LAST_NAME)); u.setRegistrationDate(result.getTimestamp(Columns.REGISTRATION_DATE).toLocalDateTime()); u.setAccessLevel(result.getInt(Columns.STATUS)); u.setActivationKey(result.getString(Columns.ACTIVATION_KEY)); if (result.getInt(Columns.SEND_CLIPPING_MAIL) == 1) { u.setSendClippingMail(true); } else { u.setSendClippingMail(false); } u.setClippingTime(loadAllClippingSendTimes(u)); if (u.getClippingTime().size() < 1) { addClippingSendTime(u, LocalTime.of(8, 0)); } } else { throw new UserNotFoundException(); } } catch (SQLException ex) { throw new UserNotFoundException(); } UserUtils.addUser(u); u.setLastClipping(ClippingUtils.getLastClipping(u)); return u; }
From source file:org.mayocat.shop.catalog.store.jdbi.mapper.ProductMapper.java
@Override public Product map(int index, ResultSet resultSet, StatementContext statementContext) throws SQLException { try {//ww w.j a v a2 s . c om Product product = new Product((UUID) resultSet.getObject("id")); product.setTenantId((UUID) resultSet.getObject("tenant_id")); if (resultSet.getObject("parent_id") != null) { product.setParentId((UUID) resultSet.getObject("parent_id")); } product.setSlug(resultSet.getString("slug")); product.setTitle(resultSet.getString("title")); product.setDescription(resultSet.getString("description")); product.setCreationDate(resultSet.getTimestamp("creation_date")); if (resultSet.getObject("on_shelf") != null) { product.setOnShelf(resultSet.getBoolean("on_shelf")); } product.setPrice(resultSet.getBigDecimal("price")); if (!Strings.isNullOrEmpty(resultSet.getString("taxes"))) { ObjectMapper mapper = new ObjectMapper(); Map<String, String> taxes = mapper.readValue(resultSet.getString("taxes"), new TypeReference<Map<String, String>>() { }); if (taxes.containsKey("vat")) { product.setVatRateId(taxes.get("vat")); } } product.setWeight(resultSet.getBigDecimal("weight")); if (resultSet.getObject("stock") != null) { product.setStock(resultSet.getInt("stock")); } product.setVirtual(resultSet.getBoolean("virtual")); UUID featuredImageId = (UUID) resultSet.getObject("featured_image_id"); if (featuredImageId != null) { product.setFeaturedImageId(featuredImageId); } if (MapperUtils.hasColumn("localization_data", resultSet) && !Strings.isNullOrEmpty(resultSet.getString("localization_data"))) { ObjectMapper mapper = new ObjectMapper(); Map<Locale, Map<String, Object>> localizedVersions = Maps.newHashMap(); Map[] data = mapper.readValue(resultSet.getString("localization_data"), Map[].class); for (Map map : data) { localizedVersions.put(Locale.forLanguageTag((String) map.get("locale")), (Map) map.get("entity")); } product.setLocalizedVersions(localizedVersions); } String model = resultSet.getString("model"); if (!Strings.isNullOrEmpty(model)) { product.setModel(model); } String type = resultSet.getString("product_type"); if (!Strings.isNullOrEmpty(type)) { product.setType(type); } if (resultSet.getArray("features") != null) { // There's no support for getting the pg uuid array as a Java UUID array (or even String array) at the time // this is written, we have to iterate over the array own result set and construct the Java array ourselves List<UUID> ids = new ArrayList<>(); Array array = resultSet.getArray("features"); if (array != null) { ResultSet featuresResultSet = array.getResultSet(); while (featuresResultSet.next()) { ids.add((UUID) featuresResultSet.getObject("value")); } product.setFeatures(ids); } } return product; } catch (IOException e) { throw new SQLException("Failed to de-serialize JSON data", e); } }
From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java
public void testDate() throws SQLException { PreparedStatement prep = conn.prepareStatement("SELECT ?"); Timestamp ts = Timestamp.valueOf("2001-02-03 04:05:06"); prep.setObject(1, new java.util.Date(ts.getTime())); ResultSet rs = prep.executeQuery(); rs.next();/* w w w. j a va 2 s .c o m*/ Timestamp ts2 = rs.getTimestamp(1); assertEquals(ts.toString(), ts2.toString()); }
From source file:dhbw.clippinggorilla.objects.user.UserUtils.java
/** * Get a User via given username or email * * @param input can be an email or username * @return The requested User (or a exception is thrown) *//*from w w w . j a va2s. co m*/ public static User getUser(String input) throws UserNotFoundException { String sql; if (input.contains("@")) { if (USERS_PER_EMAIL.containsKey(input)) { User u = USERS_PER_EMAIL.get(input); addUser(u); return u; } sql = "SELECT * FROM " + Tables.USER + " WHERE " + Columns.EMAIL + " = ?"; } else { if (USERS_PER_USERNAME.containsKey(input)) { User u = USERS_PER_USERNAME.get(input); addUser(u); return u; } sql = "SELECT * FROM " + Tables.USER + " WHERE " + Columns.USERNAME + " = ?"; } User u = new User(); try { PreparedStatement stat = Database.getConnection().prepareStatement(sql); stat.setString(1, input); ResultSet result = stat.executeQuery(); if (result.next()) { u.setId(result.getInt(Columns.ID)); u.setUsername(result.getString(Columns.USERNAME)); u.setPassword(result.getString(Columns.PASSWORD)); u.setSalt(result.getString(Columns.SALT)); u.setEmail(result.getString(Columns.EMAIL)); u.setFirstName(result.getString(Columns.FIRST_NAME)); u.setLastName(result.getString(Columns.LAST_NAME)); u.setRegistrationDate(result.getTimestamp(Columns.REGISTRATION_DATE).toLocalDateTime()); u.setAccessLevel(result.getInt(Columns.STATUS)); u.setActivationKey(result.getString(Columns.ACTIVATION_KEY)); if (result.getInt(Columns.SEND_CLIPPING_MAIL) == 1) { u.setSendClippingMail(true); } else { u.setSendClippingMail(false); } u.setClippingTime(loadAllClippingSendTimes(u)); if (u.getClippingTime().size() < 1) { addClippingSendTime(u, LocalTime.of(8, 0)); } } else { throw new UserNotFoundException(); } } catch (SQLException ex) { throw new UserNotFoundException(); } UserUtils.addUser(u); u.setLastClipping(ClippingUtils.getLastClipping(u)); return u; }
From source file:at.alladin.rmbt.controlServer.HistoryResource.java
@Post("json") public String request(final String entity) { long startTime = System.currentTimeMillis(); addAllowOrigin();//w w w .j a v a 2 s. co m JSONObject request = null; final ErrorList errorList = new ErrorList(); final JSONObject answer = new JSONObject(); String answerString; final String clientIpRaw = getIP(); System.out.println(MessageFormat.format(labels.getString("NEW_HISTORY"), clientIpRaw)); if (entity != null && !entity.isEmpty()) // try parse the string to a JSON object try { request = new JSONObject(entity); String lang = request.optString("language"); // Load Language Files for Client final List<String> langs = Arrays .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*")); if (langs.contains(lang)) { errorList.setLanguage(lang); labels = ResourceManager.getSysMsgBundle(new Locale(lang)); } else lang = settings.getString("RMBT_DEFAULT_LANGUAGE"); // System.out.println(request.toString(4)); if (conn != null) { final Client client = new Client(conn); if (request.optString("uuid").length() > 0 && client.getClientByUuid(UUID.fromString(request.getString("uuid"))) > 0) { final Locale locale = new Locale(lang); final Format format = new SignificantFormat(2, locale); String limitRequest = ""; if (request.optInt("result_limit", 0) != 0) { final int limit = request.getInt("result_limit"); //get offset string if there is one String offsetString = ""; if ((request.optInt("result_offset", 0) != 0) && (request.getInt("result_offset") >= 0)) { offsetString = " OFFSET " + request.getInt("result_offset"); } limitRequest = " LIMIT " + limit + offsetString; } final ArrayList<String> deviceValues = new ArrayList<>(); String deviceRequest = ""; if (request.optJSONArray("devices") != null) { final JSONArray devices = request.getJSONArray("devices"); boolean checkUnknown = false; final StringBuffer sb = new StringBuffer(); for (int i = 0; i < devices.length(); i++) { final String device = devices.getString(i); if (device.equals("Unknown Device")) checkUnknown = true; else { if (sb.length() > 0) sb.append(','); deviceValues.add(device); sb.append('?'); } } if (sb.length() > 0) deviceRequest = " AND (COALESCE(adm.fullname, t.model) IN (" + sb.toString() + ")" + (checkUnknown ? " OR model IS NULL OR model = ''" : "") + ")"; // System.out.println(deviceRequest); } final ArrayList<String> filterValues = new ArrayList<>(); String networksRequest = ""; if (request.optJSONArray("networks") != null) { final JSONArray tmpArray = request.getJSONArray("networks"); final StringBuilder tmpString = new StringBuilder(); if (tmpArray.length() >= 1) { tmpString.append("AND nt.group_name IN ("); boolean first = true; for (int i = 0; i < tmpArray.length(); i++) { if (first) first = false; else tmpString.append(','); tmpString.append('?'); filterValues.add(tmpArray.getString(i)); } tmpString.append(')'); } networksRequest = tmpString.toString(); } final JSONArray historyList = new JSONArray(); final PreparedStatement st; try { if (client.getSync_group_id() == 0) { //use faster request ignoring sync-group as user is not synced (id=0) st = conn.prepareStatement(String.format( "SELECT DISTINCT" + " t.uuid, time, timezone, speed_upload, speed_download, ping_median, network_type, nt.group_name network_type_group_name," + " COALESCE(adm.fullname, t.model) model" + " FROM test t" + " LEFT JOIN device_map adm ON adm.codename=t.model" + " LEFT JOIN network_type nt ON t.network_type=nt.uid" + " WHERE t.deleted = false AND t.implausible = false AND t.status = 'FINISHED'" + " AND client_id = ?" + " %s %s" + " ORDER BY time DESC" + " %s", deviceRequest, networksRequest, limitRequest)); } else { //use slower request including sync-group if client is synced st = conn.prepareStatement(String.format("SELECT DISTINCT" + " t.uuid, time, timezone, speed_upload, speed_download, ping_median, network_type, nt.group_name network_type_group_name," + " COALESCE(adm.fullname, t.model) model" + " FROM test t" + " LEFT JOIN device_map adm ON adm.codename=t.model" + " LEFT JOIN network_type nt ON t.network_type=nt.uid" + " WHERE t.deleted = false AND t.implausible = false AND t.status = 'FINISHED'" + " AND (t.client_id IN (SELECT ? UNION SELECT uid FROM client WHERE sync_group_id = ? ))" + " %s %s" + " ORDER BY time DESC" + " %s", deviceRequest, networksRequest, limitRequest)); } int i = 1; st.setLong(i++, client.getUid()); if (client.getSync_group_id() != 0) st.setInt(i++, client.getSync_group_id()); for (final String value : deviceValues) st.setString(i++, value); for (final String filterValue : filterValues) st.setString(i++, filterValue); //System.out.println(st.toString()); final ResultSet rs = st.executeQuery(); while (rs.next()) { final JSONObject jsonItem = new JSONObject(); jsonItem.put("test_uuid", rs.getString("uuid")); final Date date = rs.getTimestamp("time"); final long time = date.getTime(); final String tzString = rs.getString("timezone"); final TimeZone tz = TimeZone.getTimeZone(tzString); jsonItem.put("time", time); jsonItem.put("timezone", tzString); final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale); dateFormat.setTimeZone(tz); jsonItem.put("time_string", dateFormat.format(date)); jsonItem.put("speed_upload", format.format(rs.getInt("speed_upload") / 1000d)); jsonItem.put("speed_download", format.format(rs.getInt("speed_download") / 1000d)); final long ping = rs.getLong("ping_median"); jsonItem.put("ping", format.format(ping / 1000000d)); // backwards compatibility for old clients jsonItem.put("ping_shortest", format.format(ping / 1000000d)); jsonItem.put("model", rs.getString("model")); jsonItem.put("network_type", rs.getString("network_type_group_name")); //for appscape-iPhone-Version: also add classification to the response jsonItem.put("speed_upload_classification", Classification .classify(classification.THRESHOLD_UPLOAD, rs.getInt("speed_upload"))); jsonItem.put("speed_download_classification", Classification .classify(classification.THRESHOLD_DOWNLOAD, rs.getInt("speed_download"))); jsonItem.put("ping_classification", Classification .classify(classification.THRESHOLD_PING, rs.getLong("ping_median"))); // backwards compatibility for old clients jsonItem.put("ping_shortest_classification", Classification .classify(classification.THRESHOLD_PING, rs.getLong("ping_median"))); historyList.put(jsonItem); } if (historyList.length() == 0) errorList.addError("ERROR_DB_GET_HISTORY"); // errorList.addError(MessageFormat.format(labels.getString("ERROR_DB_GET_CLIENT"), // new Object[] {uuid})); rs.close(); st.close(); } catch (final SQLException e) { e.printStackTrace(); errorList.addError("ERROR_DB_GET_HISTORY_SQL"); // errorList.addError("ERROR_DB_GET_CLIENT_SQL"); } answer.put("history", historyList); } else errorList.addError("ERROR_REQUEST_NO_UUID"); } else errorList.addError("ERROR_DB_CONNECTION"); } catch (final JSONException e) { errorList.addError("ERROR_REQUEST_JSON"); System.out.println("Error parsing JSDON Data " + e.toString()); } catch (final IllegalArgumentException e) { errorList.addError("ERROR_REQUEST_NO_UUID"); } else errorList.addErrorString("Expected request is missing."); try { answer.putOpt("error", errorList.getList()); } catch (final JSONException e) { System.out.println("Error saving ErrorList: " + e.toString()); } answerString = answer.toString(); long elapsedTime = System.currentTimeMillis() - startTime; System.out.println(MessageFormat.format(labels.getString("NEW_HISTORY_SUCCESS"), clientIpRaw, Long.toString(elapsedTime))); return answerString; }
From source file:net.bhira.sample.api.jdbc.EmployeeRowMapper.java
/** * Constructor for EmployeeRowMapper that creates an instance of * {@link net.bhira.sample.model.Employee} from row represented by rowNum in the given * ResultSet.//from w ww . jav a 2 s.co m * * @param rs * an instance of ResultSet to be processed. * @param rowNum * integer representing the row number in ResultSet. */ @Override public Employee mapRow(ResultSet rs, int rowNum) throws SQLException { Employee employee = new Employee(); employee.setId(rs.getLong("id")); employee.setCompanyId(rs.getLong("companyid")); employee.setDepartmentId(rs.getLong("departmentid")); employee.setName(rs.getString("name")); employee.setManagerId(rs.getLong("managerid")); employee.setSalutation(rs.getString("salutation")); employee.setDOB(rs.getDate("dob")); employee.setTitle(rs.getString("title")); String sex = rs.getString("sex"); if (sex != null) { employee.setSex(Employee.Sex.valueOf(sex)); } employee.setAddress(rs.getString("addr")); employee.setCreated(rs.getTimestamp("created")); employee.setModified(rs.getTimestamp("modified")); employee.setCreatedBy(rs.getString("createdby")); employee.setModifiedBy(rs.getString("modifiedby")); return employee; }
From source file:com.sfs.whichdoctor.dao.TagDAOImpl.java
/** * Load the tag./*from ww w . ja va 2 s . c o m*/ * * @param rs the rs * @param fullResults the full results * @return the tag bean * @throws SQLException the sQL exception */ private TagBean loadTag(final ResultSet rs, final boolean fullResults) throws SQLException { final TagBean tag = new TagBean(); tag.setId(rs.getInt("TagId")); tag.setGUID(rs.getInt("GUID")); tag.setTagName(rs.getString("TagName")); tag.setTagType(rs.getString("TagType")); if (fullResults) { try { tag.setCreatedDate(rs.getTimestamp("CreatedDate")); } catch (SQLException sqe) { dataLogger.debug("Error parsing tag creation date: " + sqe.getMessage()); } tag.setCreatedBy(rs.getString("CreatedBy")); if (StringUtils.isNotBlank(tag.getCreatedBy())) { try { tag.setCreatedUser(this.userDAO.loadCached(tag.getCreatedBy())); } catch (SFSDaoException sfde) { dataLogger.debug("Error loading tag creator: " + sfde.getMessage()); } } } return tag; }
From source file:pl.edu.agh.samm.db.impl.mapper.ActionExecutionExtractor.java
@Override public Object extractData(ResultSet rs) throws SQLException, DataAccessException { List<ActionExecution> ael = new LinkedList<ActionExecution>(); ActionExecution currentActionExecution = null; HashMap<String, String> currentParameters = null; Action currentAction = null;/*w w w . jav a 2 s .c o m*/ Integer currentActionExecId = null; while (rs.next()) { Integer id = rs.getInt("id"); if (!id.equals(currentActionExecId)) { if (currentActionExecution != null) { ael.add(currentActionExecution); } // this is new execution currentActionExecId = id; Date start = new Date(rs.getTimestamp("start_time").getTime());// FIXME // why // the // heck // it // has // to // be // like // that // to // get // correct // date?? // HSQL? Date end = new Date(rs.getTimestamp("end_time").getTime()); currentAction = new Action(); currentAction.setActionURI(rs.getString("action_uri")); currentParameters = new HashMap<String, String>(); currentAction.setParameterValues(currentParameters); currentActionExecution = new ActionExecution(currentAction, start, end); } String paramName = rs.getString("param_name"); String paramValue = rs.getString("param_value"); currentParameters.put(paramName, paramValue); } if (!ael.contains(currentActionExecution)) { ael.add(currentActionExecution); } return ael; }
From source file:dao.CollBlobSearchQuery.java
/** * This method lists all the results for the search text from directories * @param conn the connection/*from www. j a va 2s .com*/ * @param collabrumId the collabrumid * @return HashSet the set that has the list of moderators for these collabrums. * @throws BaseDaoException - when error occurs **/ public HashSet run(Connection conn, String sString) throws BaseDaoException { if ((RegexStrUtil.isNull(sString) || conn == null)) { return null; } StringBuffer sb = new StringBuffer( "select blobtype, entrydate, collblob.collabrumid, collblob.entryid, btitle from collblob left join collblobtags on collblob.entryid=collblobtags.entryid where "); ArrayList columns = new ArrayList(); columns.add("usertags"); sb.append(sqlSearch.getConstraint(columns, sString)); try { PreparedStatement stmt = conn.prepareStatement(sb.toString()); ResultSet rs = stmt.executeQuery(); Vector columnNames = null; Photo photo = null; HashSet pendingSet = new HashSet(); if (rs != null) { columnNames = dbutils.getColumnNames(rs); } while (rs.next()) { photo = (Photo) eop.newObject(DbConstants.PHOTO); for (int j = 0; j < columnNames.size(); j++) { if (((String) (columnNames.elementAt(j))).equalsIgnoreCase(DbConstants.ENTRY_DATE)) { try { photo.setValue(DbConstants.ENTRY_DATE, GlobalConst.dncalendar.getDisplayDate(rs.getTimestamp(DbConstants.ENTRY_DATE))); } catch (ParseException e) { throw new BaseDaoException("could not parse the date for entrydate in collabrum" + rs.getTimestamp(DbConstants.ENTRY_DATE), e); } } else { photo.setValue((String) columnNames.elementAt(j), (String) rs.getString((String) columnNames.elementAt(j))); } } pendingSet.add(photo); } return pendingSet; } catch (Exception e) { throw new BaseDaoException("Error occured while executing collblobsearch run query " + sb.toString(), e); } }