Example usage for java.sql Timestamp getTime

List of usage examples for java.sql Timestamp getTime

Introduction

In this page you can find the example usage for java.sql Timestamp getTime.

Prototype

public long getTime() 

Source Link

Document

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.

Usage

From source file:com.funambol.foundation.items.dao.PIMNoteDAO.java

public String updateItem(NoteWrapper nw) throws DAOException {

    Connection con = null;//from w  w  w.  j  a v  a 2s .  c o m
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {

        //
        // Note fields
        //
        Note note = nw.getNote();

        StringBuilder updateQuery = new StringBuilder();

        updateQuery.append(SQL_UPDATE_FNBL_PIM_NOTE_BEGIN);

        updateQuery.append(SQL_FIELD_LAST_UPDATE + SQL_EQUALS_QUESTIONMARK_COMMA);
        updateQuery.append(SQL_FIELD_STATUS + SQL_EQUALS_QUESTIONMARK_COMMA);

        String subject = note.getSubject().getPropertyValueAsString();
        if (subject != null) {
            updateQuery.append(SQL_FIELD_SUBJECT + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String textDescription = note.getTextDescription().getPropertyValueAsString();
        if (textDescription != null) {
            updateQuery.append(SQL_FIELD_TEXTDESCRIPTION + SQL_EQUALS_QUESTIONMARK_COMMA);

            updateQuery.append(SQL_FIELD_CRC + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String categories = note.getCategories().getPropertyValueAsString();
        if (categories != null) {
            updateQuery.append(SQL_FIELD_CATEGORIES + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String folder = note.getFolder().getPropertyValueAsString();
        if (folder != null) {
            updateQuery.append(SQL_FIELD_FOLDER + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        String color = note.getColor().getPropertyValueAsString();
        if (color != null) {
            updateQuery.append(SQL_FIELD_COLOR + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String height = note.getHeight().getPropertyValueAsString();
        if (height != null) {
            updateQuery.append(SQL_FIELD_HEIGHT + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String width = note.getWidth().getPropertyValueAsString();
        if (width != null) {
            updateQuery.append(SQL_FIELD_WIDTH + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String top = note.getTop().getPropertyValueAsString();
        if (top != null) {
            updateQuery.append(SQL_FIELD_TOP + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String left = note.getLeft().getPropertyValueAsString();
        if (left != null) {
            updateQuery.append(SQL_FIELD_LEFT_MARGIN + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        if (updateQuery.charAt(updateQuery.length() - 2) == ',') {
            updateQuery.deleteCharAt(updateQuery.length() - 2);
        }

        updateQuery.append(SQL_UPDATE_FNBL_PIM_NOTE_END);

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);

        ps = con.prepareStatement(updateQuery.toString());

        int k = 1;

        //
        // last update
        //
        Timestamp lastUpdate = (nw.getLastUpdate() == null) ? new Timestamp(System.currentTimeMillis())
                : nw.getLastUpdate();
        ps.setLong(k++, lastUpdate.getTime());

        //
        // status
        //
        ps.setString(k++, String.valueOf(Def.PIM_STATE_UPDATED));

        //
        // subject
        //
        if (subject != null) {
            ps.setString(k++, StringUtils.left(subject, SQL_SUBJECT_DIM));
        }

        //
        // textDescription
        //
        if (textDescription != null) {
            textDescription = textDescription.replace('\0', ' ');
            String truncatedTextDescription = StringUtils.left(textDescription, SQL_TEXTDESCRIPTION_DIM);

            ps.setString(k++, truncatedTextDescription);
            ps.setLong(k++, calculateCrc(truncatedTextDescription));
        }

        //
        // categories
        //
        if (categories != null) {
            ps.setString(k++, truncateCategoriesField(categories, SQL_CATEGORIES_DIM));
        }

        //
        // folder
        //
        if (folder != null) {
            ps.setString(k++, truncateFolderField(folder, SQL_FOLDER_DIM));
        }

        //
        // color
        //
        if (color != null) {
            if (color.length() == 0) {
                ps.setNull(k++, Types.INTEGER);
            } else {
                ps.setInt(k++, Integer.parseInt(color));
            }
        }

        //
        // height
        //
        if (height != null) {
            if (height.length() == 0) {
                ps.setNull(k++, Types.INTEGER);
            } else {
                ps.setInt(k++, Integer.parseInt(height));
            }
        }

        //
        // width
        //
        if (width != null) {
            if (width.length() == 0) {
                ps.setNull(k++, Types.INTEGER);
            } else {
                ps.setInt(k++, Integer.parseInt(width));
            }
        }

        //
        // top
        //
        if (top != null) {
            if (top.length() == 0) {
                ps.setNull(k++, Types.INTEGER);
            } else {
                ps.setInt(k++, Integer.parseInt(top));
            }
        }

        //
        // left
        //
        if (left != null) {
            if (left.length() == 0) {
                ps.setNull(k++, Types.INTEGER);
            } else {
                ps.setInt(k++, Integer.parseInt(left));
            }
        }

        //
        // id
        //
        ps.setLong(k++, Long.parseLong(nw.getId()));
        //
        // userId
        //
        ps.setString(k++, userId);

        ps.executeUpdate();

        DBTools.close(null, ps, null);
    } catch (Exception e) {
        throw new DAOException("Error updating note.", e);
    } finally {
        DBTools.close(con, ps, rs);
    }

    return nw.getId();
}

From source file:alter.vitro.vgw.service.VitroGatewayService.java

public VgwResponse invokeWSIService(VgwRequestObservation request) throws VitroGatewayException {
    if (!getUseIdas()) {
        VgwResponse vgwResponse = new VgwResponse();
        vgwResponse.setSuccess(false);/*  w  ww. ja  va2  s.  com*/
        return vgwResponse;
    }

    // REDUNDANT CODE FOR DEBUGGING PURPOSES (SKIPPING THE REGISTRATION). TODO: remove later (perhaps make  gwWithNodeDescriptorList a private var, although will that create any race conditions for it?)
    CGateway myGateway = new CGateway();
    myGateway.setId(getAssignedGatewayUniqueIdFromReg());
    myGateway.setName("");
    myGateway.setDescription("");

    // TODO: transfer the code for acquiring GW description, in the createWSIDescr() method
    CGatewayWithSmartDevices gwWithNodeDescriptorList = myDCon.createWSIDescr(myGateway);
    logger.debug("nodeDescriptorList = {}", gwWithNodeDescriptorList.getSmartDevVec());
    List<CSmartDevice> alterNodeDescriptorsList = gwWithNodeDescriptorList.getSmartDevVec();
    ResourceAvailabilityService.getInstance().updateCachedNodeList(alterNodeDescriptorsList,
            ResourceAvailabilityService.INIT_DISCOVERY);
    // END OF REDUNDANT CODE

    logger.debug("request = {}", request);

    //Get requested resource
    String resourceName = request.getObsType().value();
    Resource requestedResource = Resource.getResource(resourceName);
    if (requestedResource == null) {
        throw new VitroGatewayException(resourceName + " not managed by VITRO gateway");
    }

    //List<Observation> observationList = rsController.getWSIData(requestedResource);
    Vector<QueriedMoteAndSensors> motesAndTheirSensorAndFunctsVec = new Vector<QueriedMoteAndSensors>();
    Vector<ReqFunctionOverData> reqFunctionVec = new Vector<ReqFunctionOverData>();
    ReqFunctionType rftObject = new ReqFunctionType();
    rftObject.setId(BigInteger.valueOf(1));
    rftObject.setDescription(ReqFunctionOverData.lastValFunc);
    reqFunctionVec.add(new ReqFunctionOverData(rftObject));

    //List<CSmartDevice> alterNodeDescriptorsList = gwWithNodeDescriptorList.getSmartDevVec();
    for (CSmartDevice alterNodeDescriptor : alterNodeDescriptorsList) {
        QueriedMoteAndSensors tmpQueriedMoteAndSensors = new QueriedMoteAndSensors();
        tmpQueriedMoteAndSensors.setMoteid(alterNodeDescriptor.getId());

        Vector<ReqSensorAndFunctions> QueriedSensorIdsAndFuncVec = new Vector<ReqSensorAndFunctions>();
        ReqSensorAndFunctions tmpReqSensingAndFunct = new ReqSensorAndFunctions();

        Integer thedigestInt = request.getObsType().value().hashCode();
        if (thedigestInt < 0)
            thedigestInt = thedigestInt * (-1);

        tmpReqSensingAndFunct.setSensorModelid(Integer.toString(thedigestInt));
        tmpReqSensingAndFunct.getFid().add(BigInteger.valueOf(1));
        QueriedSensorIdsAndFuncVec.add(tmpReqSensingAndFunct);

        tmpQueriedMoteAndSensors.setQueriedSensorIdsAndFuncVec(QueriedSensorIdsAndFuncVec);

        motesAndTheirSensorAndFunctsVec.addElement(tmpQueriedMoteAndSensors);
    }

    Vector<ReqResultOverData> observationsList = myDCon.translateAggrQuery(motesAndTheirSensorAndFunctsVec,
            reqFunctionVec);

    if (observationsList != null && !observationsList.isEmpty()) {
        //            // we only have one function, so only one element in the observarionList
        //            ReqResultOverData observations = observationsList.elementAt(0);
        //            Vector<ResultAggrStruct> tmpResultsStructVec = observations.getAllResultsforFunct();

        for (ReqResultOverData observations : observationsList) {
            Vector<ResultAggrStruct> tmpResultsStructVec = observations.getAllResultsforFunct();
            if (tmpResultsStructVec != null && !tmpResultsStructVec.isEmpty()) {
                for (ResultAggrStruct resultStruct : tmpResultsStructVec) {
                    if (resultStruct.getVal().equalsIgnoreCase(ReqResultOverData.specialValueNoReading)
                            || resultStruct.getVal().equalsIgnoreCase(ReqResultOverData.specialValuePending)
                            || resultStruct.getVal()
                                    .equalsIgnoreCase(ReqResultOverData.specialValueNotSupported)
                            || resultStruct.getVal().equalsIgnoreCase(ReqResultOverData.specialValueBinary)
                            || resultStruct.getVal().equalsIgnoreCase(ReqResultOverData.specialValueTimedOut)) {
                        System.out.println("Special values should not be sent!!");
                        continue;
                    }
                    Observation vgwObservation = new Observation();
                    Node theNode = new Node();
                    theNode.setId(resultStruct.getMid());

                    vgwObservation.setNode(theNode);
                    vgwObservation.setResource(requestedResource);
                    // TODO PRODUCES ERROR!!!
                    //System.out.println("Error prone!!");
                    Timestamp tmpTs = resultStruct.getTis().getFromTimestamp();
                    if (tmpTs == null) {
                        java.util.Date today = new java.util.Date();
                        tmpTs = new java.sql.Timestamp(today.getTime());
                    }
                    //System.out.println("Error prone!!");

                    vgwObservation.setTimestamp(tmpTs.getTime());//????
                    vgwObservation.setValue(resultStruct.getVal());
                    //Node node = observation.getNode();
                    String assignedSensorId = idasNodeMapping.get(resultStruct.getMid());
                    logger.debug("Node {} -> assignedSensotId {}", resultStruct.getMid(), assignedSensorId);
                    InsertObservation insertObservation = sensorMLMessageAdapter.getInsertObservationMessage(
                            assignedGatewayUniqueIdFromReg, assignedSensorId, vgwObservation);
                    InsertObservationResponse insertObservationResponse = idas
                            .insertObservation(insertObservation);
                    logger.debug("insertObservationResponse = {}", insertObservationResponse);
                }
            }
        }
    }
    VgwResponse vgwResponse = new VgwResponse();
    vgwResponse.setSuccess(true);
    return vgwResponse;
}

From source file:org.imos.abos.netcdf.NetCDFfile.java

public void writeCoordinateVariables(ArrayList<Timestamp> timeArray) {
    if (timeIsDoubleDays) {
        logger.info(//from w  w w .  java2  s  . c  o m
                "writeCoordinateVariables timeArray " + timeArray.size() + " timeDim " + timeDim.toString());

        times = new ArrayDouble.D1(timeDim.getLength());
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(tz);
        for (int i = 0; i < timeDim.getLength(); i++) {
            Timestamp ts = timeArray.get(i);
            long offsetTime = (ts.getTime() - anchorTime) / 1000;
            double elapsedHours = ((double) offsetTime) / (3600 * 24);

            times.setDouble(i, elapsedHours);
        }
    } else {
        times = new ArrayInt.D1(timeDim.getLength());
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(tz);
        for (int i = 0; i < timeDim.getLength(); i++) {
            Timestamp ts = timeArray.get(i);
            long offsetTime = (ts.getTime() - anchorTime) / 1000;
            int elapsedHours = (int) offsetTime / 3600;
            times.setInt(i, elapsedHours);
        }
    }

    ArrayList<Dimension> tdlist = new ArrayList<Dimension>();
    tdlist.add(timeDim);
    if (timeIsDoubleDays) {
        vTime = dataFile.addVariable(null, "TIME", DataType.DOUBLE, tdlist);
    } else {
        vTime = dataFile.addVariable(null, "TIME", DataType.INT, tdlist);
    }

    if (addTimeBnds) {
        ArrayList<Dimension> tdbndsList = new ArrayList<Dimension>();
        tdbndsList.add(timeDim);
        tdbndsList.add(bndsDim);
        timesBnds = new ArrayDouble.D2(timeDim.getLength(), 2);
        vTimeBnds = dataFile.addVariable(null, "TIME_bnds", DataType.DOUBLE, tdbndsList);
    }
}

From source file:com.p5solutions.core.jpa.orm.ConversionUtilityImpl.java

/**
 * Convert timestamp.//w  ww . ja v  a  2s. c  om
 * 
 * @param pb
 *          the pb
 * @param timestamp
 *          the timestamp
 * @param targetType
 *          the target type
 * @return the object
 */
public Object convertTimestamp(ParameterBinder pb, Timestamp timestamp, Class<?> targetType) {
    // TODO probably needs further checking based on JPA annotations, some
    // timezone issues???
    if (ReflectionUtility.isDate(targetType)) {
        // Check for Temporal
        if (pb != null) {
            Temporal temporal = pb.getTemporal();
            if (temporal != null) {
                Date converted = timestamp;
                if (TemporalType.DATE.equals(temporal.value())) {
                    java.sql.Date dt = new java.sql.Date(timestamp.getTime());
                    return dt;
                } else if (TemporalType.TIME.equals(temporal.value())) {
                    java.sql.Time tm = new java.sql.Time(timestamp.getTime());
                    return tm;
                } else if (TemporalType.TIMESTAMP.equals(temporal.value())) {

                }

                return converted;
            }
        }

        Date test = new Date(timestamp.getTime());
        return test;

        // return (Date) timestamp;
    } else if (ReflectionUtility.isStringClass(targetType)) {
        // TODO needs to be formatted based on the Format defined by the
        // 'custom?'
        // Format annotation ????
        return timestamp.toLocaleString();
    } else if (ReflectionUtility.isLongClass(targetType)) {

    }
    return timestamp;
}

From source file:de.blizzy.backup.backup.BackupRun.java

private int findOldFileViaTimestamp(IFile file) throws IOException {
    FileTime lastModificationTime = file.getLastModificationTime();
    long length = file.getLength();
    Cursor<Record> cursor = null;
    try {//from  w  w w  .j ava 2s.c o  m
        cursor = database.factory().select(Tables.BACKUPS.ID).from(Tables.BACKUPS)
                .where(Tables.BACKUPS.ID.notEqual(Integer.valueOf(backupId)))
                .orderBy(Tables.BACKUPS.RUN_TIME.desc()).fetchLazy();
        while (cursor.hasNext()) {
            int backupId = cursor.fetchOne().getValue(Tables.BACKUPS.ID).intValue();
            int entryId = findFileOrFolderEntryInBackup(file, backupId);
            if (entryId > 0) {
                Record record = database.factory()
                        .select(Tables.ENTRIES.MODIFICATION_TIME, Tables.FILES.ID, Tables.FILES.LENGTH)
                        .from(Tables.ENTRIES).join(Tables.FILES)
                        .on(Tables.FILES.ID.equal(Tables.ENTRIES.FILE_ID))
                        .where(Tables.ENTRIES.ID.equal(Integer.valueOf(entryId)),
                                Tables.ENTRIES.TYPE.equal(Byte.valueOf((byte) EntryType.FILE.getValue())))
                        .fetchAny();
                if (record != null) {
                    Timestamp entryModTime = record.getValue(Tables.ENTRIES.MODIFICATION_TIME);
                    long entryModificationTime = (entryModTime != null) ? entryModTime.getTime() : -1;
                    long entryLength = record.getValue(Tables.FILES.LENGTH).longValue();
                    if ((entryModificationTime > 0) && (lastModificationTime != null)
                            && (entryModificationTime == lastModificationTime.toMillis())
                            && (entryLength == length)) {

                        return record.getValue(Tables.FILES.ID).intValue();
                    }
                }
            }
        }
    } finally {
        database.closeQuietly(cursor);
    }

    return -1;
}

From source file:org.opentaps.common.util.UtilCommon.java

/**
 * Gets the <code>Timestamp</code> which time is the given milliseconds before the given <code>Timestamp</code>.
 * @param ts the reference <code>Timestamp</code>
 * @param milliseconds number of milliseconds before ts for which to return
 * @return a <code>Timestamp</code>, <code>null</code> if ts is <code>null</code>
 *//*  w  ww .  j  a  va  2  s .c o  m*/
public static Timestamp beforeMillisecs(Timestamp ts, long milliseconds) {
    if (ts != null) {
        return new Timestamp(ts.getTime() - milliseconds);
    } else {
        return null;
    }
}

From source file:org.opentaps.common.util.UtilCommon.java

/**
 * Gets the <code>Timestamp</code> which time is the given milliseconds after the given <code>Timestamp</code>.
 * @param ts the reference <code>Timestamp</code>
 * @param milliseconds number of milliseconds after ts for which to return
 * @return a <code>Timestamp</code>, <code>null</code> if ts is <code>null</code>
 *//*from  w w  w.j  av a  2  s . c  o  m*/
public static Timestamp afterMillisecs(Timestamp ts, long milliseconds) {
    if (ts != null) {
        return new Timestamp(ts.getTime() + milliseconds);
    } else {
        return null;
    }
}

From source file:org.kuali.rice.kim.impl.role.RoleInternalServiceImpl.java

protected void inactivatePrincipalGroupMemberships(List<String> groupIds, Timestamp yesterday) {
    if (groupIds == null || groupIds.isEmpty()) {
        return;//from www.j ava2s  .  co  m
    }
    Collection<GroupMember> groupMemberships = getGroupService().getMembers(groupIds);
    if (groupMemberships.isEmpty()) {
        return;
    }
    List<GroupMember> groupMembers = new ArrayList<GroupMember>();
    for (GroupMember groupMembershipInfo : groupMemberships) {
        if (MemberType.GROUP.equals(groupMembershipInfo.getType())
                && groupMembershipInfo.isActive(new DateTime())) {
            groupMembers.add(groupMembershipInfo);
        }
    }
    // FIXME: Is there a reason we are doing this directly and *not* calling the group service???
    for (GroupMember groupMember : groupMembers) {
        GroupMember.Builder builder = GroupMember.Builder.create(groupMember);
        builder.setActiveToDate(new DateTime(yesterday.getTime()));
        getDataObjectService().save(GroupMemberBo.from(builder.build()));
    }
}

From source file:gobblin.metastore.database.DatabaseJobHistoryStoreV101.java

private JobExecutionInfo resultSetToJobExecutionInfo(ResultSet rs) throws SQLException {
    JobExecutionInfo jobExecutionInfo = new JobExecutionInfo();

    jobExecutionInfo.setJobName(rs.getString("job_name"));
    jobExecutionInfo.setJobId(rs.getString("job_id"));
    try {/*from  ww  w. j  a  va2 s  .  c om*/
        Timestamp startTime = rs.getTimestamp("start_time");
        if (startTime != null) {
            jobExecutionInfo.setStartTime(startTime.getTime());
        }
    } catch (SQLException se) {
        jobExecutionInfo.setStartTime(0);
    }
    try {
        Timestamp endTime = rs.getTimestamp("end_time");
        if (endTime != null) {
            jobExecutionInfo.setEndTime(endTime.getTime());
        }
    } catch (SQLException se) {
        jobExecutionInfo.setEndTime(0);
    }
    jobExecutionInfo.setDuration(rs.getLong("duration"));
    String state = rs.getString("state");
    if (!Strings.isNullOrEmpty(state)) {
        jobExecutionInfo.setState(JobStateEnum.valueOf(state));
    }
    jobExecutionInfo.setLaunchedTasks(rs.getInt("launched_tasks"));
    jobExecutionInfo.setCompletedTasks(rs.getInt("completed_tasks"));
    String launcherType = rs.getString("launcher_type");
    if (!Strings.isNullOrEmpty(launcherType)) {
        jobExecutionInfo.setLauncherType(LauncherTypeEnum.valueOf(launcherType));
    }
    String trackingUrl = rs.getString("tracking_url");
    if (!Strings.isNullOrEmpty(trackingUrl)) {
        jobExecutionInfo.setTrackingUrl(trackingUrl);
    }
    return jobExecutionInfo;
}

From source file:gobblin.metastore.database.DatabaseJobHistoryStoreV101.java

private TaskExecutionInfo resultSetToTaskExecutionInfo(ResultSet rs) throws SQLException {
    TaskExecutionInfo taskExecutionInfo = new TaskExecutionInfo();

    taskExecutionInfo.setTaskId(rs.getString("task_id"));
    taskExecutionInfo.setJobId(rs.getString("job_id"));
    try {//from  w  w  w . java 2 s. c o  m
        Timestamp startTime = rs.getTimestamp("start_time");
        if (startTime != null) {
            taskExecutionInfo.setStartTime(startTime.getTime());
        }
    } catch (SQLException se) {
        taskExecutionInfo.setStartTime(0);
    }
    try {
        Timestamp endTime = rs.getTimestamp("end_time");
        if (endTime != null) {
            taskExecutionInfo.setEndTime(endTime.getTime());
        }
    } catch (SQLException se) {
        taskExecutionInfo.setEndTime(0);
    }
    taskExecutionInfo.setDuration(rs.getLong("duration"));
    String state = rs.getString("state");
    if (!Strings.isNullOrEmpty(state)) {
        taskExecutionInfo.setState(TaskStateEnum.valueOf(state));
    }
    String failureException = rs.getString("failure_exception");
    if (!Strings.isNullOrEmpty(failureException)) {
        taskExecutionInfo.setFailureException(failureException);
    }
    taskExecutionInfo.setLowWatermark(rs.getLong("low_watermark"));
    taskExecutionInfo.setHighWatermark(rs.getLong("high_watermark"));
    Table table = new Table();
    String namespace = rs.getString("table_namespace");
    if (!Strings.isNullOrEmpty(namespace)) {
        table.setNamespace(namespace);
    }
    String name = rs.getString("table_name");
    if (!Strings.isNullOrEmpty(name)) {
        table.setName(name);
    }
    String type = rs.getString("table_type");
    if (!Strings.isNullOrEmpty(type)) {
        table.setType(TableTypeEnum.valueOf(type));
    }
    taskExecutionInfo.setTable(table);

    return taskExecutionInfo;
}