List of usage examples for java.sql Timestamp valueOf
@SuppressWarnings("deprecation") public static Timestamp valueOf(LocalDateTime dateTime)
From source file:org.apache.hadoop.hive.ql.io.sarg.ConvertAstToSearchArg.java
private static Object boxLiteral(ExprNodeConstantDesc constantDesc, PredicateLeaf.Type type) { Object lit = constantDesc.getValue(); if (lit == null) { return null; }/*w ww.j a v a2s. co m*/ switch (type) { case LONG: if (lit instanceof HiveDecimal) { HiveDecimal dec = (HiveDecimal) lit; if (!dec.isLong()) { throw new ArithmeticException("Overflow"); } return dec.longValue(); } return ((Number) lit).longValue(); case STRING: if (lit instanceof HiveChar) { return ((HiveChar) lit).getPaddedValue(); } else if (lit instanceof String) { return lit; } else { return lit.toString(); } case FLOAT: if (lit instanceof HiveDecimal) { // HiveDecimal -> Float -> Number -> Double return ((Number) ((HiveDecimal) lit).floatValue()).doubleValue(); } else { return ((Number) lit).doubleValue(); } case TIMESTAMP: return Timestamp.valueOf(lit.toString()); case DATE: return Date.valueOf(lit.toString()); case DECIMAL: return new HiveDecimalWritable(lit.toString()); case BOOLEAN: return lit; default: throw new IllegalArgumentException("Unknown literal " + type); } }
From source file:net.niyonkuru.koodroid.ui.AccountFragment.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { int id = loader.getId(); switch (id) { case PLAN_TOKEN: { if (!data.moveToFirst()) return; mPlanCost.setText(formatMoney(data.getString(PlansQuery.COST))); mPlanName.setText(data.getString(PlansQuery.NAME)); mPlanUpdateTime.setTag(Timestamp.valueOf(data.getString(PlansQuery.UPDATED))); break;/*from w w w . j a v a2 s .c om*/ } case ADDONS_TOKEN: { mAddonsList.removeAllViews(); double total_cost = 0.0; while (data.moveToNext()) { View addon = mLayoutInflater.inflate(R.layout.addon_list_item, null); final TextView addonName = (TextView) addon.findViewById(R.id.addon_name); addonName.setText(data.getString(AddonsQuery.NAME)); double cost = data.getDouble(AddonsQuery.COST); total_cost += cost; final TextView addonCost = (TextView) addon.findViewById(R.id.addon_cost); addonCost.setText(formatMoney(cost)); mAddonsList.addView(addon); } View addonsTitle = getView().findViewById(R.id.addons_content); if (mAddonsList.getChildCount() > 0) { mAddonsCost.setText(formatMoney(total_cost)); addonsTitle.setVisibility(View.VISIBLE); } else { /* make the list visible when there's at least one addon */ addonsTitle.setVisibility(View.GONE); } break; } } updateTimestamps(); }
From source file:com.fluke.realtime.data.RediffParser.java
private Timestamp getTime(String time) { String timepart = time.split(",")[1]; return Timestamp.valueOf(date + " " + timepart + ""); }
From source file:libepg.epg.section.body.eventinformationtable.EventInformationTableRepeatingPartTest.java
/** * Test of getStart_time_Object method, of class * EventInformationTableRepeatingPart.//from ww w .j a v a2 s. co m */ @Test public void testGetStart_time_Object() throws Exception { LOG.info("getStart_time_Object"); EventInformationTableRepeatingPart instance = target; Timestamp expResult = Timestamp.valueOf("2016-03-21 18:00:00.0"); Timestamp result = instance.getStart_time_Object(); assertEquals(expResult, result); }
From source file:se.nrm.dina.logic.DinaDataLogic.java
/** * Creates an entity in database// ww w . ja va 2s.c o m * * @param entityName * @param json * @param agentId * @return EntityBean */ public EntityBean createEntity(String entityName, String json, int agentId) { logger.info("createEntity : {} ", entityName); LocalDateTime ld = LocalDateTime.now(); date = Timestamp.valueOf(ld); System.out.println("bean : " + bean); try { bean = mappObject(entityName, json); System.out.println("bean 1 .. " + bean); Class clazz = JpaReflectionHelper.getInstance().getCreatedByClazz(); createdByUserBean = dao.findById(agentId, clazz, JpaReflectionHelper.getInstance().isVersioned(clazz)); Field[] fields = bean.getClass().getDeclaredFields(); Arrays.stream(fields).forEach(f -> { setValueToBean(bean, f); }); setTimeStampCreated(bean); setCreatedByUser(bean, createdByUserBean); return dao.create(bean); } catch (DinaConstraintViolationException ex) { throw ex; } catch (DinaException ex) { throw ex; } }
From source file:at.ac.tuwien.qse.sepm.dao.impl.JDBCPhotoDAO.java
@Override public void update(Photo photo) throws DAOException { if (photo == null) throw new IllegalArgumentException(); if (photo.getId() == null) throw new IllegalArgumentException(); logger.debug("Updating photo {}", photo); try {//from w w w . j a v a 2 s . c o m Place place = photo.getData().getPlace(); Journey journey = photo.getData().getJourney(); Photographer photographer = photo.getData().getPhotographer(); jdbcTemplate.update(UPDATE_STATEMENT, photographer != null ? photographer.getId() : null, photo.getPath(), photo.getData().getRating().ordinal(), Timestamp.valueOf(photo.getData().getDatetime()), photo.getData().getLatitude(), photo.getData().getLongitude(), place != null ? place.getId() : null, journey != null ? journey.getId() : null, photo.getId()); logger.debug("Successfully update photo {}", photo); } catch (DataAccessException e) { logger.debug("Failed updating photo {}", photo); throw new DAOException("Failed to update photo", e); } }
From source file:libepg.epg.section.eventinformationtable.EventInformationTableRepeatingPartTest.java
/** * Test of getStart_time_Object method, of class * EventInformationTableRepeatingPart./* ww w . j a v a2 s. com*/ */ @Test public void testGetStart_time_Object() throws Exception { LOG.debug("getStart_time_Object"); EventInformationTableRepeatingPart instance = target; Timestamp expResult = Timestamp.valueOf("2016-03-21 18:00:00.0"); Timestamp result = instance.getStart_time_Object(); assertEquals(expResult, result); }
From source file:org.apache.ddlutils.platform.oracle.Oracle8ModelReader.java
/** * {@inheritDoc}/*from ww w . j av a 2 s. c o m*/ */ protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException { Column column = super.readColumn(metaData, values); if (column.getDefaultValue() != null) { // Oracle pads the default value with spaces column.setDefaultValue(column.getDefaultValue().trim()); } if (column.getTypeCode() == Types.DECIMAL) { // We're back-mapping the NUMBER columns returned by Oracle // Note that the JDBC driver returns DECIMAL for these NUMBER columns switch (column.getSizeAsInt()) { case 1: if (column.getScale() == 0) { column.setTypeCode(Types.BIT); } break; case 3: if (column.getScale() == 0) { column.setTypeCode(Types.TINYINT); } break; case 5: if (column.getScale() == 0) { column.setTypeCode(Types.SMALLINT); } break; case 18: column.setTypeCode(Types.REAL); break; case 22: if (column.getScale() == 0) { column.setTypeCode(Types.INTEGER); } break; case 38: if (column.getScale() == 0) { column.setTypeCode(Types.BIGINT); } else { column.setTypeCode(Types.DOUBLE); } break; } } else if (column.getTypeCode() == Types.FLOAT) { // Same for REAL, FLOAT, DOUBLE PRECISION, which all back-map to FLOAT but with // different sizes (63 for REAL, 126 for FLOAT/DOUBLE PRECISION) switch (column.getSizeAsInt()) { case 63: column.setTypeCode(Types.REAL); break; case 126: column.setTypeCode(Types.DOUBLE); break; } } else if ((column.getTypeCode() == Types.DATE) || (column.getTypeCode() == Types.TIMESTAMP)) { // Oracle has only one DATE/TIME type, so we can't know which it is and thus map // it back to TIMESTAMP column.setTypeCode(Types.TIMESTAMP); // we also reverse the ISO-format adaptation, and adjust the default value to timestamp if (column.getDefaultValue() != null) { Matcher matcher = _oracleIsoTimestampPattern.matcher(column.getDefaultValue()); Timestamp timestamp = null; if (matcher.matches()) { String timestampVal = matcher.group(1); timestamp = Timestamp.valueOf(timestampVal); } else { matcher = _oracleIsoDatePattern.matcher(column.getDefaultValue()); if (matcher.matches()) { String dateVal = matcher.group(1); timestamp = new Timestamp(Date.valueOf(dateVal).getTime()); } else { matcher = _oracleIsoTimePattern.matcher(column.getDefaultValue()); if (matcher.matches()) { String timeVal = matcher.group(1); timestamp = new Timestamp(Time.valueOf(timeVal).getTime()); } } } if (timestamp != null) { column.setDefaultValue(timestamp.toString()); } } } else if (TypeMap.isTextType(column.getTypeCode())) { column.setDefaultValue(unescape(column.getDefaultValue(), "'", "''")); } return column; }
From source file:mtsar.resources.WorkerResource.java
@PATCH @Path("{worker}/answers") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response postAnswers(@Context Validator validator, @Context UriInfo uriInfo, @PathParam("worker") Integer id, @FormParam("type") @DefaultValue(AnswerDAO.ANSWER_TYPE_DEFAULT) String type, @FormParam("tags") List<String> tags, @FormParam("datetime") String datetimeParam, MultivaluedMap<String, String> params) { final Timestamp datetime = (datetimeParam == null) ? DateTimeUtils.now() : Timestamp.valueOf(datetimeParam); final Worker worker = fetchWorker(id); final Map<String, List<String>> nested = ParamsUtils.nested(params, "answers"); final Map<Answer, Set<ConstraintViolation<Object>>> answers = nested.entrySet().stream().map(entry -> { final Integer taskId = Integer.valueOf(entry.getKey()); final Task task = fetchTask(taskId); final Answer answer = new Answer.Builder().setStage(stage.getId()).addAllTags(tags).setType(type) .setTaskId(task.getId()).setWorkerId(worker.getId()).addAllAnswers(entry.getValue()) .setDateTime(datetime).build(); final Set<ConstraintViolation<Object>> violations = ParamsUtils.validate(validator, new TaskAnswerValidation.Builder().setTask(task).setAnswer(answer).build(), new AnswerValidation.Builder().setAnswer(answer).setAnswerDAO(answerDAO).build()); return Pair.of(answer, violations); }).collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); final Set<ConstraintViolation<Object>> violations = answers.values().stream().flatMap(Set::stream) .collect(Collectors.toSet()); if (!violations.isEmpty()) throw new ConstraintViolationException(violations); final List<Answer> inserted = AnswerDAO.insert(answerDAO, answers.keySet()); return Response.ok(inserted).build(); }
From source file:org.apache.stratos.usage.summary.helper.util.DataAccessObject.java
public String getAndUpdateLastUsageMonthlyTimestamp() throws SQLException { Timestamp lastSummaryTs = null; Connection connection = null; try {// ww w .j a v a2 s .c om connection = dataSource.getConnection(); String sql = "SELECT TIMESTMP FROM USAGE_LAST_MONTHLY_TS WHERE ID='LatestTS'"; PreparedStatement ps = connection.prepareStatement(sql); ResultSet resultSet = ps.executeQuery(); if (resultSet.next()) { lastSummaryTs = resultSet.getTimestamp("TIMESTMP"); } else { lastSummaryTs = new Timestamp(0); } DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 00:00:00"); Timestamp currentTs = Timestamp.valueOf(formatter.format(new Date())); String currentSql = "INSERT INTO USAGE_LAST_MONTHLY_TS (ID, TIMESTMP) VALUES('LatestTS',?) ON DUPLICATE KEY UPDATE TIMESTMP=?"; PreparedStatement ps1 = connection.prepareStatement(currentSql); ps1.setTimestamp(1, currentTs); ps1.setTimestamp(2, currentTs); ps1.execute(); } catch (SQLException e) { log.error("Error occurred while trying to get and update the last monthly timestamp. ", e); } finally { if (connection != null) { connection.close(); } } return lastSummaryTs.toString(); }