Example usage for java.sql Timestamp Timestamp

List of usage examples for java.sql Timestamp Timestamp

Introduction

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

Prototype

public Timestamp(long time) 

Source Link

Document

Constructs a Timestamp object using a milliseconds time value.

Usage

From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.idea.IdeaDAO.java

@Override
public void insertIdea(IIdea idea) {
    Connection conn = null;/*  w  w  w. j a va2s.  co m*/
    PreparedStatement stat = null;
    try {
        conn = this.getConnection();
        conn.setAutoCommit(false);
        stat = conn.prepareStatement(INSERT_IDEA);
        int index = 1;
        stat.setString(index++, idea.getId());
        stat.setString(index++, idea.getTitle());
        stat.setString(index++, idea.getDescr());
        stat.setTimestamp(index++, new Timestamp(idea.getPubDate().getTime()));
        stat.setString(index++, idea.getUsername());
        stat.setInt(index++, idea.getStatus());
        stat.setInt(index++, idea.getVotePositive());
        stat.setInt(index++, idea.getVoteNegative());
        stat.setString(index++, idea.getInstanceCode());
        stat.executeUpdate();

        this.updateTags(idea, conn);

        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error adding Idea", t);
        throw new RuntimeException("Error adding Idea", t);
    } finally {
        closeDaoResources(null, stat, conn);
    }
}

From source file:eionet.webq.task.RemoveExpiredUserFilesTaskIntegrationTest.java

private void setFileAsExpired() {
    Date expired = DateUtils.addSeconds(DateUtils.addHours(new Date(), -task.getExpirationHours()), -1);
    factory.getCurrentSession().createQuery("UPDATE UserFile SET updated=:updated")
            .setTimestamp("updated", new Timestamp(expired.getTime())).executeUpdate();
}

From source file:infowall.domain.persistence.sql.ItemValueDao.java

private static Timestamp toTimestamp(DateTime dateTime) {
    return new Timestamp(dateTime.getMillis());
}

From source file:com.msopentech.odatajclient.engine.data.ODataTimestamp.java

private ODataTimestamp(final SimpleDateFormat sdf, final Date date, final boolean offset) {
    this.sdf = sdf;
    this.timestamp = new Timestamp(date.getTime());
    this.offset = offset;
}

From source file:com.bitranger.parknshop.buyer.controller.ManageFavourite.java

@RequestMapping("/addFavourite")
public String addFavourite(HttpServletRequest req, Integer psItemId) {
    PsCustomer currentCustomer = (PsCustomer) req.getSession().getAttribute("currentCustomer");

    if (currentCustomer == null) {
        return Utility.error("User haven't logged in.");
    }/*from  w w  w.j  a v  a  2  s.  co m*/

    PsItem psItem = psItemDao.findById(psItemId);
    if (psItem == null)
        return Utility.error("Wrong ItemId");
    CustomerFavouriteItem customerFavouriteItem = psCustomerFavouriteItemDao
            .findById(new CustomerFavouriteItemId(currentCustomer.getId(), psItemId));
    if (customerFavouriteItem == null) {
        customerFavouriteItem = new CustomerFavouriteItem();
        customerFavouriteItem.setPsCustomer(currentCustomer);
        customerFavouriteItem.setPsItem(psItem);
        customerFavouriteItem.setTimeCreated(new Timestamp(System.currentTimeMillis()));
        customerFavouriteItem.setId(new CustomerFavouriteItemId(currentCustomer.getId(), psItemId));
        psCustomerFavouriteItemDao.save(customerFavouriteItem);
    }
    return "redirect:/";
}

From source file:edu.umd.cs.submitServer.servlets.UploadSubmission.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    long now = System.currentTimeMillis();
    Timestamp submissionTimestamp = new Timestamp(now);

    // these are set by filters or previous servlets
    Project project = (Project) request.getAttribute(PROJECT);
    StudentRegistration studentRegistration = (StudentRegistration) request.getAttribute(STUDENT_REGISTRATION);
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    boolean webBasedUpload = ((Boolean) request.getAttribute("webBasedUpload")).booleanValue();
    String clientTool = multipartRequest.getCheckedParameter("submitClientTool");
    String clientVersion = multipartRequest.getOptionalCheckedParameter("submitClientVersion");
    String cvsTimestamp = multipartRequest.getOptionalCheckedParameter("cvstagTimestamp");

    Collection<FileItem> files = multipartRequest.getFileItems();
    Kind kind;/*  w w w.  j a  va2 s .c o  m*/

    byte[] zipOutput = null; // zipped version of bytesForUpload
    boolean fixedZip = false;
    try {

        if (files.size() > 1) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(bos);
            for (FileItem item : files) {
                String name = item.getName();
                if (name == null || name.length() == 0)
                    continue;
                byte[] bytes = item.get();
                ZipEntry zentry = new ZipEntry(name);
                zentry.setSize(bytes.length);
                zentry.setTime(now);
                zos.putNextEntry(zentry);
                zos.write(bytes);
                zos.closeEntry();
            }
            zos.flush();
            zos.close();
            zipOutput = bos.toByteArray();
            kind = Kind.MULTIFILE_UPLOAD;

        } else {
            FileItem fileItem = multipartRequest.getFileItem();
            if (fileItem == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "There was a problem processing your submission. "
                                + "No files were found in your submission");
                return;
            }
            // get size in bytes
            long sizeInBytes = fileItem.getSize();
            if (sizeInBytes == 0 || sizeInBytes > Integer.MAX_VALUE) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Trying upload file of size " + sizeInBytes);
                return;
            }

            // copy the fileItem into a byte array
            byte[] bytesForUpload = fileItem.get();
            String fileName = fileItem.getName();

            boolean isSpecialSingleFile = OfficeFileName.matcher(fileName).matches();

            FormatDescription desc = FormatIdentification.identify(bytesForUpload);
            if (!isSpecialSingleFile && desc != null && desc.getMimeType().equals("application/zip")) {
                fixedZip = FixZip.hasProblem(bytesForUpload);
                kind = Kind.ZIP_UPLOAD;
                if (fixedZip) {
                    bytesForUpload = FixZip.fixProblem(bytesForUpload,
                            studentRegistration.getStudentRegistrationPK());
                    kind = Kind.FIXED_ZIP_UPLOAD;
                }
                zipOutput = bytesForUpload;

            } else {

                // ==========================================================================================
                // [NAT] [Buffer to ZIP Part]
                // Check the type of the upload and convert to zip format if
                // possible
                // NOTE: I use both MagicMatch and FormatDescription (above)
                // because MagicMatch was having
                // some trouble identifying all zips

                String mime = URLConnection.getFileNameMap().getContentTypeFor(fileName);

                if (!isSpecialSingleFile && mime == null)
                    try {
                        MagicMatch match = Magic.getMagicMatch(bytesForUpload, true);
                        if (match != null)
                            mime = match.getMimeType();
                    } catch (Exception e) {
                        // leave mime as null
                    }

                if (!isSpecialSingleFile && "application/zip".equalsIgnoreCase(mime)) {
                    zipOutput = bytesForUpload;
                    kind = Kind.ZIP_UPLOAD2;
                } else {
                    InputStream ins = new ByteArrayInputStream(bytesForUpload);
                    if ("application/x-gzip".equalsIgnoreCase(mime)) {
                        ins = new GZIPInputStream(ins);
                    }

                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    ZipOutputStream zos = new ZipOutputStream(bos);

                    if (!isSpecialSingleFile && ("application/x-gzip".equalsIgnoreCase(mime)
                            || "application/x-tar".equalsIgnoreCase(mime))) {

                        kind = Kind.TAR_UPLOAD;

                        TarInputStream tins = new TarInputStream(ins);
                        TarEntry tarEntry = null;
                        while ((tarEntry = tins.getNextEntry()) != null) {
                            zos.putNextEntry(new ZipEntry(tarEntry.getName()));
                            tins.copyEntryContents(zos);
                            zos.closeEntry();
                        }
                        tins.close();
                    } else {
                        // Non-archive file type
                        if (isSpecialSingleFile)
                            kind = Kind.SPECIAL_ZIP_FILE;
                        else
                            kind = Kind.SINGLE_FILE;
                        // Write bytes to a zip file
                        ZipEntry zentry = new ZipEntry(fileName);
                        zos.putNextEntry(zentry);
                        zos.write(bytesForUpload);
                        zos.closeEntry();
                    }
                    zos.flush();
                    zos.close();
                    zipOutput = bos.toByteArray();
                }

                // [END Buffer to ZIP Part]
                // ==========================================================================================

            }
        }

    } catch (NullPointerException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "There was a problem processing your submission. "
                        + "You should submit files that are either zipped or jarred");
        return;
    } finally {
        for (FileItem fItem : files)
            fItem.delete();
    }

    if (webBasedUpload) {
        clientTool = "web";
        clientVersion = kind.toString();
    }

    Submission submission = uploadSubmission(project, studentRegistration, zipOutput, request,
            submissionTimestamp, clientTool, clientVersion, cvsTimestamp, getDatabaseProps(),
            getSubmitServerServletLog());

    request.setAttribute("submission", submission);

    if (!webBasedUpload) {

        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("Successful submission #" + submission.getSubmissionNumber() + " received for project "
                + project.getProjectNumber());

        out.flush();
        out.close();
        return;
    }
    boolean instructorUpload = ((Boolean) request.getAttribute("instructorViewOfStudent")).booleanValue();
    // boolean
    // isCanonicalSubmission="true".equals(request.getParameter("isCanonicalSubmission"));
    // set the successful submission as a request attribute
    String redirectUrl;

    if (fixedZip) {
        redirectUrl = request.getContextPath() + "/view/fixedSubmissionUpload.jsp?submissionPK="
                + submission.getSubmissionPK();
    }
    if (project.getCanonicalStudentRegistrationPK() == studentRegistration.getStudentRegistrationPK()) {
        redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
    } else if (instructorUpload) {
        redirectUrl = request.getContextPath() + "/view/instructor/project.jsp?projectPK="
                + project.getProjectPK();
    } else {
        redirectUrl = request.getContextPath() + "/view/project.jsp?projectPK=" + project.getProjectPK();
    }

    response.sendRedirect(redirectUrl);

}

From source file:org.cloudfoundry.identity.uaa.audit.JdbcFailedLoginCountingAuditServiceTests.java

@Test
public void userAuthenticationFailureDeletesOldData() throws Exception {
    long now = System.currentTimeMillis();
    auditService.log(getAuditEvent(UserAuthenticationFailure, "1", "joe"));
    assertEquals(1, template.queryForInt("select count(*) from sec_audit where principal_id='1'"));
    // Set the created column to 3 hours past
    template.update("update sec_audit set created=?", new Timestamp(now - 3 * 3600 * 1000));
    auditService.log(getAuditEvent(UserAuthenticationFailure, "1", "joe"));
    assertEquals(1, template.queryForInt("select count(*) from sec_audit where principal_id='1'"));
}

From source file:at.alladin.rmbt.statisticServer.UsageJSONResource.java

@Get("json")
public String request(final String entity) {
    JSONObject result = new JSONObject();
    int month = -1;
    int year = -1;
    try {//w ww  . ja va2  s  .co m
        //parameters
        final Form getParameters = getRequest().getResourceRef().getQueryAsForm();
        try {

            if (getParameters.getNames().contains("month")) {
                month = Integer.parseInt(getParameters.getFirstValue("month"));
                if (month > 11 || month < 0) {
                    throw new NumberFormatException();
                }
            }
            if (getParameters.getNames().contains("year")) {
                year = Integer.parseInt(getParameters.getFirstValue("year"));
                if (year < 0) {
                    throw new NumberFormatException();
                }
            }
        } catch (NumberFormatException e) {
            return "invalid parameters";
        }

        Calendar now = new GregorianCalendar();
        Calendar monthBegin = new GregorianCalendar((year > 0) ? year : now.get(Calendar.YEAR),
                (month >= 0) ? month : now.get(Calendar.MONTH), 1);
        Calendar monthEnd = new GregorianCalendar((year > 0) ? year : now.get(Calendar.YEAR),
                (month >= 0) ? month : now.get(Calendar.MONTH),
                monthBegin.getActualMaximum(Calendar.DAY_OF_MONTH));
        //if now -> do not use the last day
        if (month == now.get(Calendar.MONTH) && year == now.get(Calendar.YEAR)) {
            monthEnd = now;
            monthEnd.add(Calendar.DATE, -1);
        }

        JSONObject platforms = getPlatforms(new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject usage = getClassicUsage(new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject versionsIOS = getVersions("iOS", new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject versionsAndroid = getVersions("Android", new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject versionsApplet = getVersions("Applet", new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject networkGroupNames = getNetworkGroupName(new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject networkGroupTypes = getNetworkGroupType(new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        result.put("platforms", platforms);
        result.put("usage", usage);
        result.put("versions_ios", versionsIOS);
        result.put("versions_android", versionsAndroid);
        result.put("versions_applet", versionsApplet);
        result.put("network_group_names", networkGroupNames);
        result.put("network_group_types", networkGroupTypes);
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result.toString();
}

From source file:daos.BetalingDaoTest.java

@Test
public void testDeleteBetaling() throws Exception {
    LOG.info("deleteBetalingTest");
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();// w  w  w .j a  v a 2 s.  c om
    testBetaling.setBetaalDatum(new Timestamp(date.getTime()));
    testBetaling.setBetaalwijze(bw);
    testBetaling.setKlant(klant);
    testBetaling.setFactuur(f1);
    session.getTransaction().commit();
    session.close();
    instance.deleteEntity(testBetaling);
    assertNull(instance.readEntity(1));
}

From source file:corner.hadoop.services.impl.LocalFileAccessorProxy.java

@Override
public List<FileDesc> list(String dirPath) throws IOException {
    String _path = addRootPath(dirPath);
    if (dirPath.endsWith(File.separator)) {
        _path = dirPath.substring(0, dirPath.length() - 1);
    }//from   w  w  w  .  j  a v  a  2 s  .co m
    File dir = new File(_path);
    if (!dir.isDirectory()) {
        throw new IllegalArgumentException("The path [" + dirPath + "] is not dir.");
    }
    File[] files = dir.listFiles();
    if (files != null && files.length > 0) {
        List<FileDesc> ret = new LinkedList<FileDesc>();
        for (File file : files) {
            ret.add(new FileDesc(_path + File.separator + file.getName(), file.isDirectory(),
                    new Timestamp(file.lastModified()), file.length()));
        }
        return ret;
    }
    return null;
}