Example usage for java.sql Timestamp valueOf

List of usage examples for java.sql Timestamp valueOf

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public static Timestamp valueOf(LocalDateTime dateTime) 

Source Link

Document

Obtains an instance of Timestamp from a LocalDateTime object, with the same year, month, day of month, hours, minutes, seconds and nanos date-time value as the provided LocalDateTime .

Usage

From source file:fedora.server.access.dissemination.DisseminationService.java

/**
 * <p>//w  w  w.j  a  va 2s . c  om
 * Datastream locations are considered privileged information by the Fedora
 * repository. To prevent disclosing physical datastream locations to
 * external mechanism services, a proxy is used to disguise the datastream
 * locations. This method generates a temporary ID that maps to the physical
 * datastream location and registers this information in a memory resident
 * hashtable for subsequent resolution of the physical datastream location.
 * The servlet <code>DatastreamResolverServlet</code> provides the proxy
 * resolution service for datastreams.
 * </p>
 * <p>
 * </p>
 * <p>
 * The format of the tempID is derived from <code>java.sql.Timestamp</code>
 * with an arbitrary counter appended to the end to insure uniqueness. The
 * syntax is of the form:
 * <ul>
 * <p>
 * YYYY-MM-DD HH:mm:ss.mmm:dddddd where
 * </p>
 * <ul>
 * <li>YYYY - year (1900-8099)</li>
 * <li>MM - month (01-12)</li>
 * <li>DD - day (01-31)</li>
 * <li>hh - hours (0-23)</li>
 * <li>mm - minutes (0-59)</li>
 * <li>ss - seconds (0-59)</li>
 * <li>mmm - milliseconds (0-999)</li>
 * <li>dddddd - incremental counter (0-999999)</li>
 * </ul>
 * </ul>
 * 
 * @param dsLocation
 *        The physical location of the datastream.
 * @param dsControlGroupType
 *        The type of the datastream.
 * @return A temporary ID used to reference the physical location of the
 *         specified datastream
 * @throws ServerException
 *         If an error occurs in registering a datastream location.
 */
public String registerDatastreamLocation(String dsLocation, String dsControlGroupType,
        String beServiceCallbackRole, String methodName) throws ServerException {

    String tempID = null;
    Timestamp timeStamp = null;
    if (counter > 999999) {
        counter = 0;
    }
    long currentTime = new Timestamp(new Date().getTime()).getTime();
    long expireLimit = currentTime - (long) datastreamExpirationLimit * 1000;
    String dsMediatedServletPath = null;
    String dsMediatedCallbackHost = null;

    try {

        // Remove any datastream registrations that have expired.
        // The expiration limit can be adjusted using the Fedora config parameter
        // named "datastreamExpirationLimit" which is in seconds.
        for (Enumeration e = dsRegistry.keys(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            timeStamp = Timestamp.valueOf(extractTimestamp(key));
            if (expireLimit > timeStamp.getTime()) {
                dsRegistry.remove(key);
                LOG.debug("DatastreamMediationKey removed from Hash: " + key);
            }
        }

        // Register datastream.
        if (tempID == null) {
            timeStamp = new Timestamp(new Date().getTime());
            tempID = timeStamp.toString() + ":" + counter++;
            DatastreamMediation dm = new DatastreamMediation();
            dm.mediatedDatastreamID = tempID;
            dm.dsLocation = dsLocation;
            dm.dsControlGroupType = dsControlGroupType;
            dm.methodName = methodName;

            // See if datastream reference is to fedora server itself or an external location.
            // M and X type datastreams always reference fedora server. With E type datastreams
            // we must examine URL to see if this is referencing a remote datastream or is
            // simply a callback to the fedora server. If the reference is remote, then use
            // the role of the backend service that will make a callback for this datastream.
            // If the referenc s to the fedora server, use the special role of "fedoraInternalCall-1" to
            // denote that the callback will come from the fedora server itself.
            String beServiceRole = null;
            if (ServerUtility.isURLFedoraServer(dsLocation) || dsControlGroupType.equals("M")
                    || dsControlGroupType.equals("X")) {
                beServiceRole = BackendPolicies.FEDORA_INTERNAL_CALL;
            } else {
                beServiceRole = beServiceCallbackRole;
            }

            // Store beSecurity info in hash 
            Hashtable beHash = m_beSS.getSecuritySpec(beServiceRole, methodName);
            boolean beServiceCallbackBasicAuth = new Boolean((String) beHash.get("callbackBasicAuth"))
                    .booleanValue();
            boolean beServiceCallBasicAuth = new Boolean((String) beHash.get("callBasicAuth")).booleanValue();
            boolean beServiceCallbackSSL = new Boolean((String) beHash.get("callbackSSL")).booleanValue();
            boolean beServiceCallSSL = new Boolean((String) beHash.get("callSSL")).booleanValue();
            String beServiceCallUsername = (String) beHash.get("callUsername");
            String beServiceCallPassword = (String) beHash.get("callPassword");
            if (LOG.isDebugEnabled()) {
                LOG.debug("******************Registering datastream dsLocation: " + dsLocation);
                LOG.debug("******************Registering datastream dsControlGroupType: " + dsControlGroupType);
                LOG.debug("******************Registering datastream beServiceRole: " + beServiceRole);
                LOG.debug("******************Registering datastream beServiceCallbackBasicAuth: "
                        + beServiceCallbackBasicAuth);
                LOG.debug("******************Registering datastream beServiceCallBasicAuth: "
                        + beServiceCallBasicAuth);
                LOG.debug("******************Registering datastream beServiceCallbackSSL: "
                        + beServiceCallbackSSL);
                LOG.debug("******************Registering datastream beServiceCallSSL: " + beServiceCallSSL);
                LOG.debug("******************Registering datastream beServiceCallUsername: "
                        + beServiceCallUsername);
                LOG.debug("******************Registering datastream beServiceCallPassword: "
                        + beServiceCallPassword);
            }
            dm.callbackRole = beServiceRole;
            dm.callUsername = beServiceCallUsername;
            dm.callPassword = beServiceCallPassword;
            dm.callbackBasicAuth = beServiceCallbackBasicAuth;
            dm.callBasicAuth = beServiceCallBasicAuth;
            dm.callbackSSL = beServiceCallbackSSL;
            dm.callSSL = beServiceCallSSL;
            dsRegistry.put(tempID, dm);
            LOG.debug("DatastreammediationKey added to Hash: " + tempID);
        }

    } catch (Throwable th) {
        throw new DisseminationException("[DisseminationService] register" + "DatastreamLocation: "
                + "returned an error. The underlying error was a " + th.getClass().getName() + " The message "
                + "was \"" + th.getMessage() + "\" .");
    }

    // Replace the blank between date and time with the character "T".
    return tempID.replaceAll(" ", "T");
}

From source file:name.livitski.databag.cli.Launcher.java

/**
 * Converts an array of one or two strings of the form
 * <code>{ "yyyy-mm-dd", "hh:mm:ss" }</code> (the second element is optional)
 * into a timestamp. //from  w  ww . ja  va2  s  .  com
 */
private Timestamp argsToTimestamp(String[] args, int offset, String command) {
    StringBuilder buf = new StringBuilder("yyyy-mm-dd hh:mm:ss.fffffffff".length());
    buf.append(args[offset++]).append(' ');
    if (offset < args.length)
        buf.append(args[offset++]);
    else
        buf.append("00:00:00");
    if (offset < args.length)
        throw new IllegalArgumentException("Extra argument to --" + command + ": " + args[offset]);
    Timestamp epoch = Timestamp.valueOf(buf.toString());
    return epoch;
}

From source file:org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils.java

static Timestamp getTimestampFromString(String s) {
    Timestamp result;/*from  w w w  . ja v a2 s .  c o  m*/
    s = s.trim();

    // Throw away extra if more than 9 decimal places
    int periodIdx = s.indexOf(".");
    if (periodIdx != -1) {
        if (s.length() - periodIdx > 9) {
            s = s.substring(0, periodIdx + 10);
        }
    }
    try {
        result = Timestamp.valueOf(s);
    } catch (IllegalArgumentException e) {
        result = null;
    }
    return result;
}

From source file:com.ca.dvs.utilities.lisamar.JDBCUtil.java

private Object isMatchedDataType(String edmType, Object dataObject) {

    String s = "";
    if (dataObject instanceof String)
        s = (String) dataObject;//  w  ww . j av a 2  s  .  c  o  m
    else
        s = dataObject.toString();

    Object retObject = null;
    try {
        switch (edmType) {
        case Edm.Int16:
            retObject = Short.parseShort(s);
            break;
        case Edm.Int32:
            retObject = Integer.parseInt(s);
            break;
        case Edm.Int64:
            retObject = Long.parseLong(s);
            break;
        case Edm.Float:
        case Edm.Single:
            retObject = Float.parseFloat(s);
            break;
        case Edm.Double:
            retObject = Double.parseDouble(s);
            break;
        case Edm.Boolean:
            retObject = Boolean.parseBoolean(s);
            break;
        case Edm.Guid:
        case Edm.String:
            retObject = "'" + s + "'";
            break;
        case Edm.Date:
        case Edm.DateTime:
        case Edm.DateTimeOffset:
            retObject = Timestamp.valueOf(s);
            break;
        case Edm.Time:
        case Edm.TimeOfDay:
            SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss a");
            retObject = df.parse(s);
            break;
        }
    } catch (ParseException e) {
        return null;
    } catch (NumberFormatException e) {
        return null;
    }

    return retObject;

}

From source file:eu.trentorise.opendata.jackan.CkanClient.java

/**
 * Parses a Ckan timestamp into a Java Timestamp.
 *
 * @throws IllegalArgumentException/*from  w  w  w .  ja  va 2s.c o  m*/
 *             if timestamp can't be parsed.
 * @see #formatTimestamp(java.sql.Timestamp) for the inverse process.
 * @since 0.4.1
 */
public static Timestamp parseTimestamp(String timestamp) {
    if (timestamp == null) {
        throw new IllegalArgumentException("Found null timestamp!");
    }

    if (NONE.equals(timestamp)) {
        throw new IllegalArgumentException("Found timestamp with 'None' inside!");
    }

    return Timestamp.valueOf(timestamp.replace("T", " "));
}

From source file:org.apache.kylin.rest.service.QueryService.java

/**
 * @param preparedState/*from   ww w  .j  a  va  2  s  .  co m*/
 * @param param
 * @throws SQLException
 */
private void setParam(PreparedStatement preparedState, int index, PrepareSqlRequest.StateParam param)
        throws SQLException {
    boolean isNull = (null == param.getValue());

    Class<?> clazz;
    try {
        clazz = Class.forName(param.getClassName());
    } catch (ClassNotFoundException e) {
        throw new InternalErrorException(e);
    }

    Rep rep = Rep.of(clazz);

    switch (rep) {
    case PRIMITIVE_CHAR:
    case CHARACTER:
    case STRING:
        preparedState.setString(index, isNull ? null : String.valueOf(param.getValue()));
        break;
    case PRIMITIVE_INT:
    case INTEGER:
        preparedState.setInt(index, isNull ? 0 : Integer.valueOf(param.getValue()));
        break;
    case PRIMITIVE_SHORT:
    case SHORT:
        preparedState.setShort(index, isNull ? 0 : Short.valueOf(param.getValue()));
        break;
    case PRIMITIVE_LONG:
    case LONG:
        preparedState.setLong(index, isNull ? 0 : Long.valueOf(param.getValue()));
        break;
    case PRIMITIVE_FLOAT:
    case FLOAT:
        preparedState.setFloat(index, isNull ? 0 : Float.valueOf(param.getValue()));
        break;
    case PRIMITIVE_DOUBLE:
    case DOUBLE:
        preparedState.setDouble(index, isNull ? 0 : Double.valueOf(param.getValue()));
        break;
    case PRIMITIVE_BOOLEAN:
    case BOOLEAN:
        preparedState.setBoolean(index, !isNull && Boolean.parseBoolean(param.getValue()));
        break;
    case PRIMITIVE_BYTE:
    case BYTE:
        preparedState.setByte(index, isNull ? 0 : Byte.valueOf(param.getValue()));
        break;
    case JAVA_UTIL_DATE:
    case JAVA_SQL_DATE:
        preparedState.setDate(index, isNull ? null : java.sql.Date.valueOf(param.getValue()));
        break;
    case JAVA_SQL_TIME:
        preparedState.setTime(index, isNull ? null : Time.valueOf(param.getValue()));
        break;
    case JAVA_SQL_TIMESTAMP:
        preparedState.setTimestamp(index, isNull ? null : Timestamp.valueOf(param.getValue()));
        break;
    default:
        preparedState.setObject(index, isNull ? null : param.getValue());
    }
}

From source file:eu.trentorise.opendata.jackan.CkanClient.java

/**
 * Formats a timestamp according to {@link #CKAN_TIMESTAMP_PATTERN}, with
 * precision up to microseconds./*  w  w w.  j  a  v a 2  s .com*/
 *
 * @see #parseTimestamp(java.lang.String) for the inverse process.
 * @since 0.4.1
 */
@Nullable
public static String formatTimestamp(Timestamp timestamp) {
    if (timestamp == null) {
        throw new IllegalArgumentException("Found null timestamp!");
    }
    Timestamp ret = Timestamp.valueOf(timestamp.toString());
    ret.setNanos((timestamp.getNanos() / 1000) * 1000);
    return Strings.padEnd(ret.toString().replace(" ", "T"), "1970-01-01T01:00:00.000001".length(), '0');
}

From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheDatabase.java

/**
 * Get the date for the last file list job.
 *
 * @param replica The replica to get the date for.
 * @return The date of the last missing files update for the replica. A null is returned if no last missing files
 * update has been performed.//from   w  w  w .  j a v  a 2  s.c  o m
 * @throws ArgumentNotValid If the replica is null.
 * @throws IllegalArgumentException If the Date of the Timestamp cannot be instantiated.
 */
@Override
public Date getDateOfLastMissingFilesUpdate(Replica replica) throws ArgumentNotValid, IllegalArgumentException {
    ArgumentNotValid.checkNotNull(replica, "Replica replica");
    Connection con = ArchiveDBConnection.get();
    String result = null;
    try {
        // sql for retrieving this replicafileinfo_guid.
        String sql = "SELECT filelist_updated FROM replica WHERE replica_id = ?";
        result = DBUtils.selectStringValue(con, sql, replica.getId());
    } finally {
        ArchiveDBConnection.release(con);
    }
    // return null if the field has no be set for this replica.
    if (result == null) {
        log.debug(
                "The 'filelist_updated' field has not been set, as no missing files update has been performed yet.");
        return null;
    } else {
        // Parse the timestamp into a date.
        return new Date(Timestamp.valueOf(result).getTime());
    }
}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

/**
 * Convert a string timestamp value to big integer.
 * //from ww  w  .ja  v  a2s. com
 * @param String timestamp
 * @return
 */
public static BigInteger TimestampToBigint(String timestamp) {
    BigInteger result = BigInteger.valueOf(new Long(Timestamp.valueOf(timestamp).getTime()));
    return result;
}

From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheDatabase.java

/**
 * Method for retrieving the date for the last update for corrupted files.
 * <p>// ww  w . ja v a 2  s.  co m
 * This method does not contact the replicas, it only retrieves the data from the last time the checksum was
 * retrieved.
 *
 * @param replica The replica to find the date for the latest update for corruption of files.
 * @return The date for the last checksum update. A null is returned if no wrong files update has been performed for
 * this replica.
 * @throws ArgumentNotValid If the replica is null.
 * @throws IllegalArgumentException If the Date of the Timestamp cannot be instantiated.
 */
@Override
public Date getDateOfLastWrongFilesUpdate(Replica replica) throws ArgumentNotValid, IllegalArgumentException {
    ArgumentNotValid.checkNotNull(replica, "Replica replica");
    Connection con = ArchiveDBConnection.get();
    String result = null;
    try {
        // The SQL statement for retrieving the date for last update of
        // checksum for the replica.
        final String sql = "SELECT checksum_updated FROM replica WHERE replica_id = ?";
        result = DBUtils.selectStringValue(con, sql, replica.getId());
    } finally {
        ArchiveDBConnection.release(con);
    }
    // return null if the field has no be set for this replica.
    if (result == null) {
        log.debug(
                "The 'checksum_updated' field has not been set, as no wrong files update has been performed yet.");
        return null;
    } else {
        // Parse the timestamp into a date.
        return new Date(Timestamp.valueOf(result).getTime());
    }
}