Example usage for java.sql Timestamp toString

List of usage examples for java.sql Timestamp toString

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public String toString() 

Source Link

Document

Formats a timestamp in JDBC timestamp escape format.

Usage

From source file:org.fosstrak.epcis.repository.query.QuerySubscription.java

/**
 * Updates the subscription in the database. This is required in order to
 * correctly re-initialize the subscriptions, especially the
 * lastTimeExecuted field, after a context restart.
 * <p>/*from  w w  w  .j  av a  2 s .c  o  m*/
 * TODO: This is a back-end method: move this method to the
 * QueryOperationsBackend and delegate to it (thus we would need a reference
 * to the QueryOperationsBackend in this class).
 * 
 * @param lastTimeExecuted
 *            The new lastTimeExecuted.
 */
private void updateSubscription(final Calendar lastTimeExecuted) {
    String jndiName = getProperties().getProperty("jndi.datasource.name", "java:comp/env/jdbc/EPCISDB");
    try {
        // open a database connection
        Context ctx = new InitialContext();
        DataSource db = (DataSource) ctx.lookup(jndiName);
        Connection dbconnection = db.getConnection();

        // update the subscription in the database
        String update = "UPDATE subscription SET lastexecuted=(?), params=(?)" + " WHERE subscriptionid=(?);";
        PreparedStatement stmt = dbconnection.prepareStatement(update);
        LOG.debug("SQL: " + update);
        Timestamp ts = new Timestamp(lastTimeExecuted.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(1, time);
        LOG.debug("       query param 1: " + time);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");
        stmt.setString(3, subscriptionID);
        LOG.debug("       query param 3: " + subscriptionID);
        stmt.executeUpdate();
        dbconnection.commit();

        // close the database connection
        dbconnection.close();
    } catch (SQLException e) {
        String msg = "An SQL error occurred while updating the subscriptions in the database.";
        LOG.error(msg, e);
    } catch (IOException e) {
        String msg = "Unable to update the subscription in the database: " + e.getMessage();
        LOG.error(msg, e);
    } catch (NamingException e) {
        String msg = "Unable to find JNDI data source with name " + jndiName;
        LOG.error(msg, e);
    }
}

From source file:org.accada.epcis.repository.query.QuerySubscription.java

/**
 * Updates the subscription in the database. This is required in order to
 * correctly re-initialize the subscriptions, especially the
 * lastTimeExecuted field, after a context restart.
 * <p>/*from  w ww  .j  av a  2 s. c  o  m*/
 * TODO: This is a back-end method: move this method to the
 * QueryOperationsBackend and delegate to it (thus we would need a reference
 * to the QueryOperationsBackend in this class).
 * 
 * @param lastTimeExecuted
 *            The new lastTimeExecuted.
 */
private void updateSubscription(final GregorianCalendar lastTimeExecuted) {
    String jndiName = getProperties().getProperty("jndi.datasource.name", "java:comp/env/jdbc/EPCISDB");
    try {
        // open a database connection
        Context ctx = new InitialContext();
        DataSource db = (DataSource) ctx.lookup(jndiName);
        Connection dbconnection = db.getConnection();

        // update the subscription in the database
        String update = "UPDATE subscription SET lastexecuted=(?), params=(?)" + " WHERE subscriptionid=(?);";
        PreparedStatement stmt = dbconnection.prepareStatement(update);
        LOG.debug("SQL: " + update);
        Timestamp ts = new Timestamp(lastTimeExecuted.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(1, time);
        LOG.debug("       query param 1: " + time);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");
        stmt.setString(3, subscriptionID);
        LOG.debug("       query param 3: " + subscriptionID);
        stmt.executeUpdate();

        // close the database connection
        dbconnection.close();
    } catch (SQLException e) {
        String msg = "An SQL error occurred while updating the subscriptions in the database.";
        LOG.error(msg, e);
    } catch (IOException e) {
        String msg = "Unable to update the subscription in the database: " + e.getMessage();
        LOG.error(msg, e);
    } catch (NamingException e) {
        String msg = "Unable to find JNDI data source with name " + jndiName;
        LOG.error(msg, e);
    }
}

From source file:com.commander4j.util.JUtility.java

public static String getTimeStampStringFormat(Timestamp ts, String fmt) {
    String result = "";
    LinkedList<String> fmtList = new LinkedList<String>();
    LinkedList<String> valList = new LinkedList<String>();
    fmtList.clear();//  w  w  w .java 2s  .  c o m
    valList.clear();

    result = ts.toString();

    fmtList.add("yyyy");
    valList.add(result.substring(0, 4));

    fmtList.add("yy");
    valList.add(result.substring(2, 4));

    fmtList.add("mm");
    valList.add(result.substring(5, 7));

    fmtList.add("dd");
    valList.add(result.substring(8, 10));

    fmtList.add("hh");
    valList.add(result.substring(11, 13));

    fmtList.add("mi");
    valList.add(result.substring(14, 16));

    fmtList.add("ss");
    valList.add(result.substring(17, 19));

    fmtList.add("yymmdd");
    valList.add(result.substring(2, 4) + result.substring(5, 7) + result.substring(8, 10));

    int pos = fmtList.indexOf(fmt);

    if (pos >= 0) {
        result = valList.get(pos);
    } else {
        result = "";
    }

    return result;
}

From source file:org.jumpmind.db.platform.mssql.MsSqlDdlReader.java

@Override
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map<String, Object> values) throws SQLException {
    Column column = super.readColumn(metaData, values);
    String defaultValue = column.getDefaultValue();

    // Sql Server tends to surround the returned default value with one or
    // two sets of parentheses
    if (defaultValue != null) {
        while (defaultValue.startsWith("(") && defaultValue.endsWith(")")) {
            defaultValue = defaultValue.substring(1, defaultValue.length() - 1);
        }/* w w  w  .  j av  a2  s  . c om*/

        if (column.getMappedTypeCode() == Types.TIMESTAMP) {
            // Sql Server maintains the default values for DATE/TIME jdbc
            // types, so we have to
            // migrate the default value to TIMESTAMP
            Matcher matcher = isoDatePattern.matcher(defaultValue);
            Timestamp timestamp = null;

            if (matcher.matches()) {
                timestamp = new Timestamp(Date.valueOf(matcher.group(1)).getTime());
            } else {
                matcher = isoTimePattern.matcher(defaultValue);
                if (matcher.matches()) {
                    timestamp = new Timestamp(Time.valueOf(matcher.group(1)).getTime());
                }
            }
            if (timestamp != null) {
                defaultValue = timestamp.toString();
            }
        } else if (column.getMappedTypeCode() == Types.DECIMAL || column.getMappedTypeCode() == Types.BIGINT) {
            // For some reason, Sql Server 2005 always returns DECIMAL
            // default values with a dot
            // even if the scale is 0, so we remove the dot
            if ((column.getScale() == 0) && defaultValue.endsWith(".")) {
                defaultValue = defaultValue.substring(0, defaultValue.length() - 1);
            }
        } else if (TypeMap.isTextType(column.getMappedTypeCode())) {
            if (defaultValue.startsWith("N'") && defaultValue.endsWith("'")) {
                defaultValue = defaultValue.substring(2, defaultValue.length() - 1);
            }
            defaultValue = unescape(defaultValue, "'", "''");
        }

        column.setDefaultValue(defaultValue);
    }

    if ((column.getMappedTypeCode() == Types.DECIMAL) && (column.getSizeAsInt() == 19)
            && (column.getScale() == 0)) {
        column.setMappedTypeCode(Types.BIGINT);
    }

    // These columns return sizes and/or decimal places with the metat data from MSSql Server however
    // the values are not adjustable through the create table so they are omitted 
    if (column.getJdbcTypeName() != null && (column.getJdbcTypeName().equals("smallmoney")
            || column.getJdbcTypeName().equals("money") || column.getJdbcTypeName().equals("timestamp")
            || column.getJdbcTypeName().equals("uniqueidentifier") || column.getJdbcTypeName().equals("time")
            || column.getJdbcTypeName().equals("datetime2") || column.getJdbcTypeName().equals("date"))) {
        removePlatformSizeAndDecimal(column);
    }
    return column;
}

From source file:com.mothsoft.alexis.web.ChartServlet.java

private void doLineGraph(final HttpServletRequest request, final HttpServletResponse response,
        final String title, final String[] dataSetIds, final Integer width, final Integer height,
        final Integer numberOfSamples) throws ServletException, IOException {

    final DataSetService dataSetService = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext()).getBean(DataSetService.class);

    final OutputStream out = response.getOutputStream();
    response.setContentType("image/png");
    response.setHeader("Cache-Control", "max-age: 5; must-revalidate");

    final XYSeriesCollection seriesCollection = new XYSeriesCollection();

    final DateAxis dateAxis = new DateAxis(title != null ? title : "Time");
    final DateTickUnit unit = new DateTickUnit(DateTickUnit.HOUR, 1);
    final DateFormat chartFormatter = new SimpleDateFormat("ha");
    dateAxis.setDateFormatOverride(chartFormatter);
    dateAxis.setTickUnit(unit);/*from   ww w  . j  a  va 2  s  .  c  o m*/
    dateAxis.setLabelFont(DEFAULT_FONT);
    dateAxis.setTickLabelFont(DEFAULT_FONT);

    if (numberOfSamples > 12) {
        dateAxis.setTickLabelFont(
                new Font(DEFAULT_FONT.getFamily(), Font.PLAIN, (int) (DEFAULT_FONT.getSize() * .8)));
    }

    final NumberAxis yAxis = new NumberAxis("Activity");

    final StandardXYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES_AND_LINES);

    int colorCounter = 0;

    if (dataSetIds != null) {
        for (final String dataSetIdString : dataSetIds) {
            final Long dataSetId = Long.valueOf(dataSetIdString);
            final DataSet dataSet = dataSetService.get(dataSetId);

            // go back for numberOfSamples, but include current hour
            final Calendar calendar = new GregorianCalendar();
            calendar.add(Calendar.HOUR_OF_DAY, -1 * (numberOfSamples - 1));
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            final Timestamp startDate = new Timestamp(calendar.getTimeInMillis());

            calendar.add(Calendar.HOUR_OF_DAY, numberOfSamples);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            final Timestamp endDate = new Timestamp(calendar.getTimeInMillis());

            logger.debug(String.format("Generating chart for period: %s to %s", startDate.toString(),
                    endDate.toString()));

            final List<DataSetPoint> dataSetPoints = dataSetService
                    .findAndAggregatePointsGroupedByUnit(dataSetId, startDate, endDate, TimeUnits.HOUR);

            final boolean hasData = addSeries(seriesCollection, dataSet.getName(), dataSetPoints, startDate,
                    numberOfSamples, renderer);

            if (dataSet.isAggregate()) {
                renderer.setSeriesPaint(seriesCollection.getSeriesCount() - 1, Color.BLACK);
            } else if (hasData) {
                renderer.setSeriesPaint(seriesCollection.getSeriesCount() - 1,
                        PAINTS[colorCounter++ % PAINTS.length]);
            } else {
                renderer.setSeriesPaint(seriesCollection.getSeriesCount() - 1, Color.LIGHT_GRAY);
            }
        }
    }

    final XYPlot plot = new XYPlot(seriesCollection, dateAxis, yAxis, renderer);

    // create the chart...
    final JFreeChart chart = new JFreeChart(plot);

    // set the background color for the chart...
    chart.setBackgroundPaint(Color.white);

    // get a reference to the plot for further customisation...
    plot.setBackgroundPaint(new Color(253, 253, 253));
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

    // set the range axis to display integers only...
    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setLabelFont(DEFAULT_FONT);
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setLowerBound(0.00d);

    ChartUtilities.writeChartAsPNG(out, chart, width, height);
}

From source file:com.funambol.tools.test.PostSyncML.java

public void syncAndTest() throws IOException, TestFailedException {
    ////from   w  ww  .j a  v  a  2s .c o m
    // First of all clean up!
    //
    clean();

    SyncML response = null;
    String respURI = null;

    File responseFile = null;
    boolean firstMessage = false;

    File fb = new File(baseDir, "header.properties");
    if (fb.exists()) {
        propsHeader = new Properties();
        propsHeader.load(new FileInputStream(fb));
    }

    existResponseProcessor();

    int msgCount = 0;
    for (int i = 0; i < msgs.length; ++i) {
        msgCount++;

        firstMessage = msgs[i].indexOf("<MsgID>1</MsgID>") != -1;

        if (firstMessage) {
            try {
                Thread.currentThread().sleep(sessionsDelay);
            } catch (InterruptedException ex) {
            }
        }

        try {
            log.info("Trying to execute target: " + msgFiles[i]);
            AntUtil.runAntTarget(antProject, baseDir, xmlBuildFile, msgFiles[i]);
            log.info("Target " + msgFiles[i] + " executed");
        } catch (Exception ex) {

            boolean isIn = containsException(ex.getCause(), ComparisonFailure.class.getName());

            if (isIn) {
                try {
                    log.info("Comparison Failure ");
                    saveEndTestError("Actual Report different than expected.\n" + ex.getLocalizedMessage(),
                            new File(errorDir, "msg-end-test-error.xml"));
                } catch (IOException e) {
                }
            }
            log.info("Error executing target " + msgFiles[i] + " (" + ex + ")");
            //do nothing
        }

        //
        // Read ant properties
        //
        Properties prop = new Properties();

        File f = new File(baseDir, msgFiles[i] + ".properties");
        if (f.exists()) {
            prop.load(new FileInputStream(f));
        }

        String propertiesValues = prop.getProperty("replace");

        //
        // Replace value_N into message before sending response
        //
        if (propertiesValues != null) {
            StringTokenizer values = new StringTokenizer(propertiesValues, ",");
            int y = 1;
            while (values.hasMoreTokens()) {
                String v = values.nextToken();
                msgs[i] = msgs[i].replaceAll("VALUE_" + y, v);
                y++;
            }
        }

        File header = new File(baseDir, "header" + msgCount + ".properties");

        if (header.exists()) {
            propsHeader = new Properties();
            propsHeader.load(new FileInputStream(header));
        }
        log.info("Sending " + msgFiles[i]);

        if (firstMessage) {
            //
            // It is a first message so we can set the
            // respURI to empty string
            //
            log.info("Message with id 1. Start new session");

            nextURL = initialURL;
        }

        try {
            response = postRequest(msgs[i]);
        } catch (RepresentationException e) {
            Timestamp t = new Timestamp(System.currentTimeMillis());
            String message = "<!-- " + t.toString() + " -->\n" + e.getMessage();
            IOTools.writeFile(message, new File(errorDir, msgFiles[i]));
            throw new TestFailedException("XML syntax error: " + e.getMessage(), e);
        } catch (Sync4jException e) {
            Timestamp t = new Timestamp(System.currentTimeMillis());
            String message = "<!-- " + t.toString() + " -->\n" + e.getMessage();
            IOTools.writeFile(message, new File(errorDir, msgFiles[i]));
            throw new TestFailedException("XML syntax error: " + e.getMessage(), e);
        }

        //
        // Write the messages responded by the server, than read the reference
        // and make the comparison (excluding the XPaths specified by
        // ignoreXPaths
        //
        responseFile = new File(responseDir, msgFiles[i]);
        log.info("Writing the response into " + responseFile);

        try {

            String xmlMsg = marshallSyncML(response);

            // Preprocess response message before comparing it with the
            // reference message
            if (preProcessResp) {
                xmlMsg = preProcessResponse(responseProcessor, xmlMsg);
            }

            IOTools.writeFile(xmlMsg, responseFile);

        } catch (Exception e) {
            e.printStackTrace();
            throw new TestFailedException("XML syntax error: " + e.getMessage(), e);
        }

        compare(msgFiles[i]);

        respURI = response.getSyncHdr().getRespURI();

        if (respURI != null) {
            nextURL = respURI;
        }
    }
}

From source file:org.plos.repo.service.ObjectLockTest.java

private InputRepoObject createInputRepoObject(Callback cb, int threadNumber) {
    Timestamp creationDateTime = new Timestamp(new Date().getTime());
    InputRepoObject inputRepoObject = new InputRepoObject();
    inputRepoObject.setKey(cb.getKeyname(threadNumber));
    inputRepoObject.setBucketName(BUCKET_NAME);
    inputRepoObject.setTimestamp(creationDateTime.toString());
    inputRepoObject.setUploadedInputStream(IOUtils.toInputStream(cb.getData(threadNumber)));
    inputRepoObject.setCreationDateTime(creationDateTime.toString());
    inputRepoObject.setTag(cb.getTag(threadNumber));
    return inputRepoObject;
}

From source file:de.iisys.schub.processMining.similarity.AlgoController.java

private double printTimestamp(boolean showDuration) {
    DecimalFormat df = new DecimalFormat("#0.000");
    double duration = 0;
    Timestamp time = new Timestamp(Calendar.getInstance().getTime().getTime());
    if (showDuration && this.lastTimestamp != null) {
        duration = (time.getTime() - this.lastTimestamp.getTime()) / 1000f;
        System.out.print(time.toString() + " (" + df.format((Math.round(duration * 1000) / 1000.0)) + " s)");
    } else/*from w  ww  . ja  va  2s . c  om*/
        System.out.print(time);

    this.lastTimestamp = time;
    return Math.round(duration * 1000) / 1000.0;
}

From source file:airport.database.services.chat.ChatDaoImpl.java

@Override
public void addMessage(User user, String text, Timestamp timestampMessage) {
    SqlParameterSource parameterUser = new MapSqlParameterSource(PARAMETER_SQL_QUERY_LOGIN, user.getLogin());

    int numberUser = jdbcTemplate.queryForObject(SQL_QUERY_SEEK_USER, parameterUser, Integer.class);

    MapSqlParameterSource parameterMessage = new MapSqlParameterSource();
    parameterMessage.addValue(PARAMETER_SQL_QUERY_USER_ID, numberUser);
    parameterMessage.addValue(PARAMETER_SQL_QUERY_TEXT, text);
    parameterMessage.addValue(PARAMETER_SQL_QUERY_DATE, timestampMessage);

    jdbcTemplate.update(SQL_QUERY_ADD_MESSAGE, parameterMessage);

    if (LOG.isInfoEnabled()) {
        LOG.info(//from  w w  w.  j a v  a 2 s  . c  om
                "add message. User : " + user + ". Text : " + text + ". Time : " + timestampMessage.toString());
    }
}

From source file:eu.betaas.service.securitymanager.service.impl.AuthorizationService.java

/**
 * Method to form an ExternalCapability for local GW (this GW)
 * @param thingServiceId/*ww  w.jav  a2  s .  c o  m*/
 * @param subjectType
 * @param subjectPublicKeyInfo
 * @param myCertByte
 * @return
 * @throws JAXBException
 * @throws OperatorCreationException
 * @throws CMSException
 * @throws IOException
 */
private CapabilityExternal getTokenLocal(String thingServiceId, String subjectType, byte[] subjectPublicKeyInfo,
        byte[] myCertByte) throws JAXBException, OperatorCreationException, CMSException, IOException {
    CapabilityExternal exCap = new CapabilityExternal();

    exCap.setResourceId(thingServiceId);
    exCap.setRevocationUrl(REVOCATION_URL);

    // Issuer Info
    IssuerInfo ii = new IssuerInfo();
    ii.setIssuerCertificate(myCertByte);
    ii.setIssuerType(IssuerType.APPLICATION_TYPE);
    exCap.setIssuerInfo(ii);

    // create SubjectInfo class and then add it to the exCap
    SubjectInfo si = new SubjectInfo();
    si.setSubjectType(subjectType);
    //      si.setPublicKeyInfo(publicKey);
    exCap.setSubjectInfo(si);

    // set validity condition (validity time) of the exCap
    ValidityCondition vc = new ValidityCondition();
    Timestamp ts1 = new Timestamp(System.currentTimeMillis());
    Timestamp ts2 = new Timestamp(System.currentTimeMillis() + VALIDITY_PERIOD);
    vc.setValidAfter(ts1.toString());
    vc.setValidBefore(ts2.toString());
    exCap.setValidityCondition(vc);

    AccessRights accessRights = new AccessRights();
    AccessRight ar1 = new AccessRight();
    //      ar1.setAccessType(AccessType.REALTIME_PULL);
    // create condition --> read from XML file
    // right now we assume only 1 condition exists
    final File conditionFolder = new File(conditionPath);
    for (File condFile : conditionFolder.listFiles()) {
        if (!condFile.isDirectory() && condFile.getName() != null
                && (condFile.getName().endsWith(".xml") || condFile.getName().endsWith(".xml"))) {
            ConditionType condition = CapabilityUtils.xmlToConditionType(condFile);
            ar1.setCondition(condition);
        }
    }
    //      accessRights.getAccessRight().add(ar1);
    //      exCap.setAccessRights(accessRights);

    // creating digital signature
    String iiJson = CapToXmlUtils.createIssuerInfoXml(ii);
    String siJson = CapToXmlUtils.createSubjectInfoXml(si);
    String arJson = CapToXmlUtils.createAccessRightsXml(accessRights);
    String riJson = CapToXmlUtils.createResourceIdXml(thingServiceId);
    String vcJson = CapToXmlUtils.createValidityConditionXml(vc);
    String revUrlJson = CapToXmlUtils.createRevocationUrlXml(REVOCATION_URL);
    String capContents = iiJson + "," + siJson + "," + arJson + riJson + "," + vcJson + "," + revUrlJson;

    // set the digital signature
    byte[] sign = CapabilityUtils.createCapSignature(myCredential, capContents);
    exCap.setDigitalSignature(sign);

    return exCap;
}