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:eu.betaas.service.securitymanager.service.impl.AuthorizationService.java

/**
 * Method to form an ExternalCapability especially in Apps. installation
 * @param thingServiceId//w  w w.j  ava2  s.c  om
 * @param subjectType
 * @param appId
 * @param myCertByte
 * @return
 * @throws JAXBException
 * @throws OperatorCreationException
 * @throws CMSException
 * @throws IOException
 */
private CapabilityExternal getTokenAppsLocal(String thingServiceId, String subjectType, String appId,
        byte[] myCertByte) throws Exception {

    log.debug("Start creating capability external...");
    CapabilityExternal exCap = new CapabilityExternal();

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

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

    // create SubjectInfo class and then add it to the exCap
    SubjectInfo si = new SubjectInfo();
    si.setSubjectType(subjectType);
    // get SubjectPublicKeyInfo from apps certificate --> from appId
    X509CertificateHolder appsCert = appCertCatalog.getAppCertCatalog(appId);
    byte[] pubKeyInfo = appsCert.getSubjectPublicKeyInfo().getEncoded();
    si.setPublicKeyInfo(pubKeyInfo);
    //      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
    log.info("Will read condition for access right from a 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);
    log.info("The access rights have been set!!");

    // 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);
    log.info("The digital signature has been generated!!");

    return exCap;
}

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

/**
 * Formats a timestamp according to {@link #CKAN_TIMESTAMP_PATTERN}, with
 * precision up to microseconds./*from  www .java 2s.c  o  m*/
 *
 * @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:com.alibaba.wasp.jdbc.TestPreparedStatement.java

public void testDate() throws SQLException {
    PreparedStatement prep = conn.prepareStatement("SELECT ?");
    Timestamp ts = Timestamp.valueOf("2001-02-03 04:05:06");
    prep.setObject(1, new java.util.Date(ts.getTime()));
    ResultSet rs = prep.executeQuery();
    rs.next();/*from  w w w  .  j  av  a2s  .c om*/
    Timestamp ts2 = rs.getTimestamp(1);
    assertEquals(ts.toString(), ts2.toString());
}

From source file:isl.FIMS.servlet.imports.ImportXML.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    this.initVars(request);
    String username = getUsername(request);

    Config conf = new Config("EisagwghXML_RDF");
    String xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl";
    String displayMsg = "";
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    StringBuilder xml = new StringBuilder(
            this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request));
    //  ArrayList<String> notValidMXL = new ArrayList<String>();
    HashMap<String, ArrayList> notValidMXL = new <String, ArrayList>HashMap();
    if (!ServletFileUpload.isMultipartContent(request)) {
        displayMsg = "form";
    } else {/*  w w w . j a  v  a  2s.  co  m*/
        // configures some settings
        String filePath = this.export_import_Folder;
        java.util.Date date = new java.util.Date();
        Timestamp t = new Timestamp(date.getTime());
        String currentDir = filePath + t.toString().replaceAll(":", "");
        File saveDir = new File(currentDir);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        factory.setRepository(saveDir);
        ArrayList<String> savedIDs = new ArrayList<String>();

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(REQUEST_SIZE);
        // constructs the directory path to store upload file
        String uploadPath = currentDir;
        int xmlCount = 0;
        String[] id = null;
        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();
            // iterates over form's fields
            File storeFile = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    filePath = uploadPath + File.separator + fileName;
                    storeFile = new File(filePath);
                    item.write(storeFile);
                    Utils.unzip(fileName, uploadPath);
                    File dir = new File(uploadPath);

                    String[] extensions = new String[] { "xml", "x3ml" };
                    List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
                    xmlCount = files.size();
                    for (File file : files) {
                        // saves the file on disk
                        Document doc = ParseXMLFile.parseFile(file.getPath());
                        String xmlContent = doc.getDocumentElement().getTextContent();
                        String uri_name = "";
                        try {
                            uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0];
                        } catch (DMSException ex) {
                            ex.printStackTrace();
                        }
                        String uriValue = this.URI_Reference_Path + uri_name + "/";
                        boolean insertEntity = false;
                        if (xmlContent.contains(uriValue) || file.getName().contains(type)) {
                            insertEntity = true;
                        }
                        Element root = doc.getDocumentElement();
                        Node admin = Utils.removeNode(root, "admin", true);

                        //  File rename = new File(uploadPath + File.separator + id[0] + ".xml");
                        //  boolean isRename = storeFile.renameTo(rename);
                        //   ParseXMLFile.saveXMLDocument(rename.getPath(), doc);
                        String schemaFilename = "";
                        schemaFilename = type;

                        SchemaFile sch = new SchemaFile(schemaFolder + schemaFilename + ".xsd");
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer transformer = tf.newTransformer();
                        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                        StringWriter writer = new StringWriter();
                        transformer.transform(new DOMSource(doc), new StreamResult(writer));
                        String xmlString = writer.getBuffer().toString().replaceAll("\r", "");

                        //without admin
                        boolean isValid = sch.validate(xmlString);
                        if ((!isValid && insertEntity)) {
                            notValidMXL.put(file.getName(), null);
                        } else if (insertEntity) {
                            id = initInsertFile(type, false);
                            doc = createAdminPart(id[0], type, doc, username);
                            writer = new StringWriter();
                            transformer.transform(new DOMSource(doc), new StreamResult(writer));
                            xmlString = writer.getBuffer().toString().replaceAll("\r", "");
                            DBCollection col = new DBCollection(this.DBURI, id[1], this.DBuser,
                                    this.DBpassword);
                            DBFile dbF = col.createFile(id[0] + ".xml", "XMLDBFile");
                            dbF.setXMLAsString(xmlString);
                            dbF.store();
                            ArrayList<String> externalFiles = new <String>ArrayList();
                            ArrayList<String> externalDBFiles = new <String>ArrayList();

                            String q = "//*[";
                            for (String attrSet : this.uploadAttributes) {
                                String[] temp = attrSet.split("#");
                                String func = temp[0];
                                String attr = temp[1];
                                if (func.contains("text")) {
                                    q += "@" + attr + "]/text()";
                                } else {
                                    q = "data(//*[@" + attr + "]/@" + attr + ")";
                                }
                                String[] res = dbF.queryString(q);
                                for (String extFile : res) {
                                    externalFiles.add(extFile + "#" + attr);
                                }
                            }
                            q = "//";
                            if (!dbSchemaPath[0].equals("")) {
                                for (String attrSet : this.dbSchemaPath) {
                                    String[] temp = attrSet.split("#");
                                    String func = temp[0];
                                    String path = temp[1];
                                    if (func.contains("text")) {
                                        q += path + "//text()";
                                    } else {
                                        q = "data(//" + path + ")";
                                    }
                                    String[] res = dbF.queryString(q);
                                    for (String extFile : res) {
                                        externalDBFiles.add(extFile);
                                    }
                                }
                            }
                            ArrayList<String> missingExternalFiles = new <String>ArrayList();
                            for (String extFile : externalFiles) {
                                extFile = extFile.substring(0, extFile.lastIndexOf("#"));

                                List<File> f = (List<File>) FileUtils.listFiles(dir,
                                        FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE);
                                if (f.size() == 0) {
                                    missingExternalFiles.add(extFile);
                                }
                            }
                            if (missingExternalFiles.size() > 0) {
                                notValidMXL.put(file.getName(), missingExternalFiles);
                            }

                            XMLEntity xmlNew = new XMLEntity(this.DBURI, this.systemDbCollection + type,
                                    this.DBuser, this.DBpassword, type, id[0]);

                            ArrayList<String> worngFiles = Utils.checkReference(xmlNew, this.DBURI, id[0], type,
                                    this.DBuser, this.DBpassword);
                            if (worngFiles.size() > 0) {
                                //dbF.remove();
                                notValidMXL.put(file.getName(), worngFiles);
                            }
                            //remove duplicates from externalFiles if any
                            HashSet hs = new HashSet();
                            hs.addAll(missingExternalFiles);
                            missingExternalFiles.clear();
                            missingExternalFiles.addAll(hs);
                            if (missingExternalFiles.isEmpty() && worngFiles.isEmpty()) {

                                for (String extFile : externalFiles) {
                                    String attr = extFile.substring(extFile.lastIndexOf("#") + 1,
                                            extFile.length());
                                    extFile = extFile.substring(0, extFile.lastIndexOf("#"));

                                    List<File> f = (List<File>) FileUtils.listFiles(dir,
                                            FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE);
                                    File uploadFile = f.iterator().next();
                                    String content = FileUtils.readFileToString(uploadFile);

                                    DBFile uploadsDBFile = new DBFile(this.DBURI, this.adminDbCollection,
                                            "Uploads.xml", this.DBuser, this.DBpassword);
                                    String mime = Utils.findMime(uploadsDBFile, uploadFile.getName(), attr);
                                    String uniqueName = Utils.createUniqueFilename(uploadFile.getName());
                                    File uploadFileUnique = new File(uploadFile.getPath().substring(0,
                                            uploadFile.getPath().lastIndexOf(File.separator)) + File.separator
                                            + uniqueName);
                                    uploadFile.renameTo(uploadFileUnique);
                                    xmlString = xmlString.replaceAll(uploadFile.getName(), uniqueName);
                                    String upload_path = this.systemUploads + type;
                                    File upload_dir = null;
                                    ;
                                    if (mime.equals("Photos")) {
                                        upload_path += File.separator + mime + File.separator + "original"
                                                + File.separator;
                                        upload_dir = new File(upload_path + uniqueName);
                                        FileUtils.copyFile(uploadFileUnique, upload_dir);
                                        Utils.resizeImage(uniqueName, upload_path,
                                                upload_path.replaceAll("original", "thumbs"), thumbSize);
                                        Utils.resizeImage(uniqueName, upload_path,
                                                upload_path.replaceAll("original", "normal"), normalSize);
                                        xmlString = xmlString.replace("</versions>",
                                                "</versions>" + "\n" + "<type>Photos</type>");
                                    } else {
                                        upload_path += File.separator + mime + File.separator;
                                        upload_dir = new File(upload_path + uniqueName);
                                        FileUtils.copyFile(uploadFileUnique, upload_dir);
                                    }
                                    if (!dbSchemaFolder.equals("")) {
                                        if (externalDBFiles.contains(extFile)) {
                                            try {
                                                DBCollection colSchema = new DBCollection(this.DBURI,
                                                        dbSchemaFolder, this.DBuser, this.DBpassword);
                                                DBFile dbFSchema = colSchema.createFile(uniqueName,
                                                        "XMLDBFile");
                                                dbFSchema.setXMLAsString(content);
                                                dbFSchema.store();
                                            } catch (Exception e) {
                                            }
                                        }
                                    }
                                    uploadFileUnique.renameTo(uploadFile);

                                }
                                dbF.setXMLAsString(xmlString);
                                dbF.store();
                                Utils.updateReferences(xmlNew, this.DBURI, id[0].split(type)[1], type,
                                        this.DBpassword, this.DBuser);
                                Utils.updateVocabularies(xmlNew, this.DBURI, id[0].split(type)[1], type,
                                        this.DBpassword, this.DBuser, lang);
                                savedIDs.add(id[0]);
                            } else {
                                dbF.remove();
                            }

                        }
                    }

                }
            }
            Document doc = ParseXMLFile.parseFile(ApplicationConfig.SYSTEM_ROOT + "formating/multi_lang.xml");
            Element root = doc.getDocumentElement();
            Element contextTag = (Element) root.getElementsByTagName("context").item(0);
            String uri_name = "";
            try {
                uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0];
            } catch (DMSException ex) {
            }
            if (notValidMXL.size() == 0) {
                xsl = conf.DISPLAY_XSL;
                displayMsg = Messages.ACTION_SUCCESS;
                displayMsg += Messages.NL + Messages.NL + Messages.URI_ID;
                String uriValue = "";
                xml.append("<Display>").append(displayMsg).append("</Display>\n");
                xml.append("<backPages>").append('2').append("</backPages>\n");

                for (String saveId : savedIDs) {
                    uriValue = this.URI_Reference_Path + uri_name + "/" + saveId + Messages.NL;
                    xml.append("<codeValue>").append(uriValue).append("</codeValue>\n");

                }

            } else if (notValidMXL.size() >= 1) {
                xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl";

                Iterator it = notValidMXL.keySet().iterator();
                while (it.hasNext()) {

                    String key = (String) it.next();
                    ArrayList<String> value = notValidMXL.get(key);

                    if (value != null) {
                        displayMsg += "<line>";
                        Element select = (Element) contextTag.getElementsByTagName("missingReferences").item(0);
                        displayMsg += select.getElementsByTagName(lang).item(0).getTextContent();
                        displayMsg = displayMsg.replace("?", key);
                        for (String mis_res : value) {

                            displayMsg += mis_res + ",";
                        }
                        displayMsg = displayMsg.substring(0, displayMsg.length() - 1);
                        displayMsg += ".";
                        displayMsg += "</line>";

                    } else {
                        displayMsg += "<line>";
                        Element select = (Element) contextTag.getElementsByTagName("NOT_VALID_XML").item(0);
                        displayMsg += select.getElementsByTagName(lang).item(0).getTextContent();
                        displayMsg = displayMsg.replace(";", key);
                        displayMsg += "</line>";
                    }
                    displayMsg += "<line>";
                    displayMsg += "</line>";
                }
                if (notValidMXL.size() < xmlCount) {
                    displayMsg += "<line>";
                    Element select = (Element) contextTag.getElementsByTagName("rest_valid").item(0);
                    displayMsg += select.getElementsByTagName(lang).item(0).getTextContent();
                    displayMsg += "</line>";
                    for (String saveId : savedIDs) {
                        displayMsg += "<line>";
                        String uriValue = this.URI_Reference_Path + uri_name + "/" + saveId;
                        select = (Element) contextTag.getElementsByTagName("URI_ID").item(0);
                        displayMsg += select.getElementsByTagName(lang).item(0).getTextContent() + ": "
                                + uriValue;
                        displayMsg += "</line>";
                    }
                }
            }
            Utils.deleteDir(currentDir);
        } catch (Exception ex) {
            ex.printStackTrace();
            displayMsg += Messages.NOT_VALID_IMPORT;
        }

    }
    xml.append("<Display>").append(displayMsg).append("</Display>\n");
    xml.append("<EntityType>").append(type).append("</EntityType>\n");
    xml.append(this.xmlEnd());
    try {
        XMLTransform xmlTrans = new XMLTransform(xml.toString());
        xmlTrans.transform(out, xsl);
    } catch (DMSException e) {
        e.printStackTrace();
    }
    out.close();
}

From source file:org.apache.hadoop.hive.ql.exec.vector.expressions.TestVectorTimestampExpressions.java

private void compareToUDFUnixTimeStampLong(Timestamp ts, long y) {
    long seconds = ts.getTime() / 1000;
    if (seconds != y) {
        System.out.printf("%d vs %d for %s\n", seconds, y, ts.toString());
        Assert.assertTrue(false);//  ww w  . j  ava  2 s .  c  o  m
    }
}

From source file:uk.ac.soton.itinnovation.sad.service.controllers.ExecutionsController.java

/**
 * Returns all executions on the service, url mapping: /executions
 *
 * @return all executions as JSON/*from   w w  w.  j av  a2s.  c  o m*/
 */
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public JsonResponse getExecutions() {

    logger.debug("Returning all executions");

    schedulingService.pushMethodCalledName("executions");

    long startTime = System.currentTimeMillis();

    try {
        JSONObject response = new JSONObject();

        ArrayList<SADJobExecution> allExecutions = schedulingService.getExecutions();

        if (allExecutions.isEmpty()) {
            logger.debug("No executions were found.");
            response.put("message", "No executions were found.");
            return new JsonResponse("error", response);
        } else {
            int allExecutionsSize = allExecutions.size();
            response.put("num", allExecutionsSize);
            JSONArray allExecutionsAsJsonArray = new JSONArray();

            JSONObject executionAsJson;
            Timestamp tempTimestamp;
            for (SADJobExecution execution : allExecutions) {
                executionAsJson = new JSONObject();

                executionAsJson.put("DatabaseId", execution.getCountID());
                executionAsJson.put("ID", execution.getId());
                executionAsJson.put("SADJobID", execution.getSADJobID());
                executionAsJson.put("Description", execution.getDescription());
                executionAsJson.put("Status", execution.getStatus());

                tempTimestamp = execution.getWhenStarted();
                if (tempTimestamp == null) {
                    executionAsJson.put("WhenStarted_as_string", "");
                    executionAsJson.put("WhenStarted_in_msec", "");
                } else {
                    executionAsJson.put("WhenStarted_as_string", tempTimestamp.toString());
                    executionAsJson.put("WhenStarted_in_msec", tempTimestamp.getTime());
                }

                tempTimestamp = execution.getWhenFinished();
                if (tempTimestamp == null) {
                    executionAsJson.put("WhenFinished_as_string", "");
                    executionAsJson.put("WhenFinished_in_msec", "");
                } else {
                    executionAsJson.put("WhenFinished_as_string", tempTimestamp.toString());
                    executionAsJson.put("WhenFinished_in_msec", tempTimestamp.getTime());
                }

                allExecutionsAsJsonArray.add(executionAsJson);
            }

            if (allExecutionsSize < 2) {
                logger.debug("Returning " + allExecutions.size() + " execution");
            } else {
                logger.debug("Returning " + allExecutions.size() + " executions");
            }
            response.put("list", allExecutionsAsJsonArray);
            return new JsonResponse("ok", response);
        }
    } catch (Throwable ex) {
        return new JsonResponse("error", Util.dealWithException("Failed to return all executions", ex, logger));
    } finally {
        schedulingService.pushTimeSpent(Long.toString(System.currentTimeMillis() - startTime));
    }
}

From source file:com.twinsoft.convertigo.engine.Context.java

public String getLogFilename() {
    Timestamp ts = new Timestamp(System.currentTimeMillis());
    String escapedContextID = contextID;
    escapedContextID = escapedContextID.substring(0, escapedContextID.indexOf("_"));
    escapedContextID = escapedContextID.replace('/', '_');
    escapedContextID = escapedContextID.replace('\\', '_');
    String logFilename = ts.toString().substring(0, 10) + "_context_" + escapedContextID + ".log";
    return logFilename;
}

From source file:org.plos.repo.RepoServiceSpringTest.java

@Test
public void deleteObject() throws Exception {
    repoService.createBucket(bucket1.getBucketName(), CREATION_DATE_TIME_STRING);

    try {/*  ww w. j  a v  a 2  s .  c  o  m*/
        InputRepoObject inputRepoObject = createInputRepoObject();
        inputRepoObject.setContentType(null);
        inputRepoObject.setDownloadName(null);
        repoService.createObject(RepoService.CreateMethod.NEW, inputRepoObject);

        Timestamp creationDateObj2 = new Timestamp(new Date().getTime());
        inputRepoObject.setUploadedInputStream(IOUtils.toInputStream("data2"));
        inputRepoObject.setTimestamp(creationDateObj2.toString());
        inputRepoObject.setCreationDateTime(creationDateObj2.toString());
        repoService.createObject(RepoService.CreateMethod.VERSION, inputRepoObject);

        repoService.deleteObject(bucket1.getBucketName(), KEY, false, new ElementFilter(1, null, null));
    } catch (RepoException e) {
        Assert.fail(e.getMessage());
    }

    // check state
    sqlService.getReadOnlyConnection();

    RepoObject objFromDb = sqlService.getObject(bucket1.getBucketName(), KEY);
    Assert.assertTrue(objFromDb.getKey().equals(KEY));
    List<Audit> auditList = sqlService.listAudit(bucket1.getBucketName(), KEY, null, Operation.DELETE_OBJECT,
            null);
    Assert.assertTrue(auditList.size() > 0);
    Assert.assertTrue(auditList.get(0).getOperation().equals(Operation.DELETE_OBJECT));
    sqlService.releaseConnection();

    Assert.assertTrue(objectStore.objectExists(objFromDb));
    Assert.assertTrue(IOUtils.toString(objectStore.getInputStream(objFromDb)).equals("data1"));

    Assert.assertTrue(repoService.getObjectVersions(objFromDb.getBucketName(), objFromDb.getKey()).size() == 1);

    Assert.assertTrue(
            repoService.listObjects(bucket1.getBucketName(), null, null, false, false, null).size() == 1);
    Assert.assertTrue(
            repoService.listObjects(bucket1.getBucketName(), null, null, true, false, null).size() == 2);
}

From source file:org.apache.hadoop.hive.ql.exec.vector.expressions.TestVectorTimestampExpressions.java

private void compareToUDFYearLong(Timestamp t, int y) {
    UDFYear udf = new UDFYear();
    TimestampWritable tsw = new TimestampWritable(t);
    IntWritable res = udf.evaluate(tsw);
    if (res.get() != y) {
        System.out.printf("%d vs %d for %s, %d\n", res.get(), y, t.toString(),
                tsw.getTimestamp().getTime() / 1000);
    }/*w  w w.j a  v a 2 s . com*/
    Assert.assertEquals(res.get(), y);
}

From source file:org.plos.repo.RepoServiceSpringTest.java

@Test
public void getLatestObjectTest() throws RepoException {
    repoService.createBucket(bucket1.getBucketName(), CREATION_DATE_TIME_STRING);

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(0);//from   w w  w. j a v a 2s.c  om
    cal.set(2014, 10, 30, 1, 1, 1);
    Timestamp creationDateTime1 = new Timestamp(cal.getTime().getTime());

    // create object with creation date time
    InputRepoObject inputRepoObject = createInputRepoObject();
    inputRepoObject.setCreationDateTime(creationDateTime1.toString());
    inputRepoObject.setTimestamp(creationDateTime1.toString());
    repoService.createObject(RepoService.CreateMethod.NEW, inputRepoObject);

    cal.set(2014, 10, 20, 1, 1, 1);
    Timestamp creationDateTime2 = new Timestamp(cal.getTime().getTime());
    // create object with creation date time before object 1 creation date time
    inputRepoObject.setCreationDateTime(creationDateTime2.toString());
    inputRepoObject.setTimestamp(creationDateTime2.toString());
    inputRepoObject.setUploadedInputStream(IOUtils.toInputStream("data2"));
    repoService.createObject(RepoService.CreateMethod.VERSION, inputRepoObject);

    // get the latest object
    RepoObject repoObject = repoService.getObject(bucket1.getBucketName(), KEY, null);

    // object must match the one with the oldest creation time
    Assert.assertEquals(new Integer(0), repoObject.getVersionNumber());
    Assert.assertEquals(creationDateTime1, repoObject.getCreationDate());
}