Example usage for java.util Calendar MILLISECOND

List of usage examples for java.util Calendar MILLISECOND

Introduction

In this page you can find the example usage for java.util Calendar MILLISECOND.

Prototype

int MILLISECOND

To view the source code for java.util Calendar MILLISECOND.

Click Source Link

Document

Field number for get and set indicating the millisecond within the second.

Usage

From source file:com.liferay.ide.server.remote.AbstractRemoteServerPublisher.java

protected void addToZip(IPath path, IResource resource, ZipOutputStream zip, boolean adjustGMTOffset)
        throws IOException, CoreException {
    switch (resource.getType()) {
    case IResource.FILE:
        ZipEntry zipEntry = new ZipEntry(path.toString());

        zip.putNextEntry(zipEntry);/*ww  w.  j ava 2  s .co m*/

        InputStream contents = ((IFile) resource).getContents();

        if (adjustGMTOffset) {
            TimeZone currentTimeZone = TimeZone.getDefault();
            Calendar currentDt = new GregorianCalendar(currentTimeZone, Locale.getDefault());

            // Get the Offset from GMT taking current TZ into account
            int gmtOffset = currentTimeZone.getOffset(currentDt.get(Calendar.ERA), currentDt.get(Calendar.YEAR),
                    currentDt.get(Calendar.MONTH), currentDt.get(Calendar.DAY_OF_MONTH),
                    currentDt.get(Calendar.DAY_OF_WEEK), currentDt.get(Calendar.MILLISECOND));

            zipEntry.setTime(System.currentTimeMillis() + (gmtOffset * -1));
        }

        try {
            IOUtils.copy(contents, zip);
        } finally {
            contents.close();
        }

        break;

    case IResource.FOLDER:
    case IResource.PROJECT:
        IContainer container = (IContainer) resource;

        IResource[] members = container.members();

        for (IResource res : members) {
            addToZip(path.append(res.getName()), res, zip, adjustGMTOffset);
        }
    }
}

From source file:com.autodomum.daylight.algorithm.DaylightAlgorithm.java

@Override
public Date sunset(final Coordinate coordinate, final Date date) {
    final Calendar calendar = GregorianCalendar.getInstance();
    calendar.setTime(date);//from   w  ww.ja  va  2  s. c o m

    final int day = calendar.get(Calendar.DAY_OF_YEAR);

    final double total = length(coordinate.getLatitude(), day);

    final int hours = (int) total;
    final int minutes = (int) ((((double) total) - ((double) hours)) * 60d);

    calendar.set(Calendar.HOUR_OF_DAY, 12);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    calendar.add(Calendar.HOUR_OF_DAY, hours / 2);
    calendar.add(Calendar.MINUTE, minutes / 2);
    calendar.add(Calendar.MINUTE, (int) localSolarTime(day));

    final TimeZone timeZone = TimeZone.getDefault();

    if (timeZone.inDaylightTime(date)) {
        calendar.add(Calendar.MILLISECOND, timeZone.getDSTSavings());
    }

    return calendar.getTime();
}

From source file:com.ancientprogramming.fixedformat4j.format.impl.TestFixedFormatManagerImpl.java

public void testExportMultibleFieldRecordObject() {
    Calendar someDay = Calendar.getInstance();
    someDay.set(2008, 9, 13, 0, 0, 0);/*  ww  w  . j a va 2s . c  o m*/
    someDay.set(Calendar.MILLISECOND, 0);

    MultibleFieldsRecord multibleFieldsRecord = new MultibleFieldsRecord();
    multibleFieldsRecord.setDateData(someDay.getTime());
    multibleFieldsRecord.setStringData("some      ");
    multibleFieldsRecord.setIntegerdata(100);
    manager.export(multibleFieldsRecord);
    Assert.assertEquals("wrong record exported", MULTIBLE_RECORD_DATA, manager.export(multibleFieldsRecord));
}

From source file:org.zlogic.vogon.web.data.TransactionFilterSpecification.java

/**
 * Sets the date filter//from www.ja  va  2 s .c om
 *
 * @param filterDate the date to be filtered
 */
public void setFilterDate(Date filterDate) {
    //Convert to local time (OpenShift and other non-UTC servers workaround)
    if (filterDate != null) {
        Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); //NOI18N
        calendar.setTime(filterDate);
        Calendar newCalendar = new GregorianCalendar();
        newCalendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE),
                0, 0, 0);
        newCalendar.set(Calendar.MILLISECOND, 0);
        filterDate = newCalendar.getTime();
    }
    this.filterDate = filterDate;
}

From source file:sk.lazyman.gizmo.util.GizmoUtils.java

public static Date createWorkDefaultTo() {
    Calendar cal = Calendar.getInstance();
    cal.setTime(createWorkDefaultFrom());

    cal.add(Calendar.MONTH, 1);//from w  ww  .  jav  a  2  s .  c o  m
    cal.add(Calendar.MILLISECOND, -1);

    return cal.getTime();
}

From source file:com.maydesk.base.util.PDUtil.java

public static Calendar getDateOnlyCalendar(Calendar cal) {
    Calendar ret;//from w w w  .j  av  a 2  s .  c o  m

    if (cal == null) {
        ret = Calendar.getInstance();
    } else {
        ret = (Calendar) cal.clone();
    }

    ret.set(Calendar.HOUR_OF_DAY, 0);
    ret.set(Calendar.MINUTE, 0);
    ret.set(Calendar.SECOND, 0);
    ret.set(Calendar.MILLISECOND, 0);

    return ret;
}

From source file:com.openhr.UploadFile.java

@Override
public ActionForward execute(ActionMapping map, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();/*from w w w . j av a 2s .c  o  m*/
        return map.findForward("masteradmin");
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    String uploadPath = UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        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();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);

                // saves the file on disk
                item.write(storeFile);

                // Read the file object contents and parse it and store it in the repos
                FileInputStream fstream = new FileInputStream(storeFile);
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
                Company comp = null;
                Branch branch = null;
                Calendar currDtCal = Calendar.getInstance();

                // Zero out the hour, minute, second, and millisecond
                currDtCal.set(Calendar.HOUR_OF_DAY, 0);
                currDtCal.set(Calendar.MINUTE, 0);
                currDtCal.set(Calendar.SECOND, 0);
                currDtCal.set(Calendar.MILLISECOND, 0);

                Date now = currDtCal.getTime();

                //Read File Line By Line
                while ((strLine = br.readLine()) != null) {
                    System.out.print("Processing line - " + strLine);

                    String[] lineColumns = strLine.split(COMMA);

                    if (lineColumns.length < 16) {
                        br.close();
                        in.close();
                        fstream.close();
                        throw new Exception("The required columns are missing in the line - " + strLine);
                    }

                    // Format is - 
                    // CompID,BranchName,EmpID,EmpFullName,EmpNationalID,BankName,BankBranch,RoutingNo,AccountNo,NetPay,Currency,
                    // residenttype,TaxAmount,EmployerSS,EmployeeSS
                    if (comp == null || comp.getId() != Integer.parseInt(lineColumns[0])) {
                        List<Company> comps = CompanyFactory.findById(Integer.parseInt(lineColumns[0]));

                        if (comps != null && comps.size() > 0) {
                            comp = comps.get(0);
                        } else {
                            br.close();
                            in.close();
                            fstream.close();

                            throw new Exception("Unable to get the details of the company");
                        }

                        // Check for licenses
                        List<Licenses> compLicenses = LicenseFactory.findByCompanyId(comp.getId());
                        for (Licenses lis : compLicenses) {
                            if (lis.getActive() == 1) {
                                Date endDate = lis.getTodate();
                                if (!isLicenseActive(now, endDate)) {
                                    br.close();
                                    in.close();
                                    fstream.close();

                                    // License has expired and throw an error
                                    throw new Exception("License has expired");

                                    //TODO remove the below code and enable above
                                    /*List<Branch> branches = BranchFactory.findByCompanyId(comp.getId());
                                    String branchName = lineColumns[1];
                                    if(branches != null && !branches.isEmpty()) {
                                      for(Branch bb: branches) {
                                         if(branchName.equalsIgnoreCase(bb.getName())) {
                                            branch = bb;
                                            break;
                                         }
                                      }
                                              
                                      if(branch == null) {
                                         Branch bb = new Branch();
                                    bb.setName(branchName);
                                    bb.setAddress("NA");
                                    bb.setCompanyId(comp);
                                            
                                    BranchFactory.insert(bb);
                                            
                                    List<Branch> lbranches = BranchFactory.findByName(branchName);
                                    branch = lbranches.get(0);
                                      }
                                    }*/
                                    //TODO
                                } else {
                                    // License enddate is valid, so lets check the key.
                                    String compName = comp.getName();
                                    String licenseKeyStr = LicenseValidator.formStringToEncrypt(compName,
                                            endDate);
                                    if (LicenseValidator.encryptAndCompare(licenseKeyStr,
                                            lis.getLicensekey())) {
                                        // License key is valid, so proceed.
                                        List<Branch> branches = BranchFactory.findByCompanyId(comp.getId());
                                        String branchName = lineColumns[1];
                                        if (branches != null && !branches.isEmpty()) {
                                            for (Branch bb : branches) {
                                                if (branchName.equalsIgnoreCase(bb.getName())) {
                                                    branch = bb;
                                                    break;
                                                }
                                            }

                                            if (branch == null) {
                                                Branch bb = new Branch();
                                                bb.setName(branchName);
                                                bb.setAddress("NA");
                                                bb.setCompanyId(comp);

                                                BranchFactory.insert(bb);

                                                List<Branch> lbranches = BranchFactory.findByName(branchName);
                                                branch = lbranches.get(0);
                                            }
                                        }
                                        break;
                                    } else {
                                        br.close();
                                        in.close();
                                        fstream.close();

                                        throw new Exception("License is tampered. Contact Support.");
                                    }
                                }
                            }
                        }
                    }

                    // CompID,BranchName,EmpID,EmpFullName,EmpNationalID,DeptName,BankName,BankBranch,RoutingNo,AccountNo,NetPay,currency,TaxAmt,emprSS,empess,basesalary                       
                    CompanyPayroll compPayroll = new CompanyPayroll();
                    compPayroll.setBranchId(branch);
                    compPayroll.setEmployeeId(lineColumns[2]);
                    compPayroll.setEmpFullName(lineColumns[3]);
                    compPayroll.setEmpNationalID(lineColumns[4]);
                    compPayroll.setDeptName(lineColumns[5]);
                    compPayroll.setBankName(lineColumns[6]);
                    compPayroll.setBankBranch(lineColumns[7]);
                    compPayroll.setRoutingNo(lineColumns[8]);
                    compPayroll.setAccountNo(lineColumns[9]);
                    compPayroll.setNetPay(Double.parseDouble(lineColumns[10]));
                    compPayroll.setCurrencySym(lineColumns[11]);
                    compPayroll.setResidentType(lineColumns[12]);
                    compPayroll.setTaxAmount(Double.parseDouble(lineColumns[13]));
                    compPayroll.setEmprSocialSec(Double.parseDouble(lineColumns[14]));
                    compPayroll.setEmpeSocialSec(Double.parseDouble(lineColumns[15]));
                    compPayroll.setBaseSalary(Double.parseDouble(lineColumns[16]));
                    compPayroll.setProcessedDate(now);
                    CompanyPayrollFactory.insert(compPayroll);
                }

                //Close the input stream
                br.close();
                in.close();
                fstream.close();
            }
        }
        System.out.println("Upload has been done successfully!");
    } catch (Exception ex) {
        System.out.println("There was an error: " + ex.getMessage());
        ex.printStackTrace();
    }

    return map.findForward("MasterHome");
}

From source file:de.kurashigegollub.dev.gcatest.Utils.java

public static DateTime getDateTimeNow() {
    Calendar c = Calendar.getInstance();
    c.setTime(new Date());
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);/*from  w  ww .  j ava  2 s .c om*/
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    //Google's DateTime class works with GMT timezone internally and converts all passed in Date values to it.
    //see code here:
    //http://code.google.com/p/google-api-java-client/source/browse/google-api-client/src/main/java/com/google/api/client/util/DateTime.java?spec=svnf7334c6f6f7c0941306e18de989c90a053941669&r=f7334c6f6f7c0941306e18de989c90a053941669
    //Therefore we have to apply our local timezone here so the calculated time will
    DateTime dtg = new DateTime(c.getTime(), TimeZone.getDefault());
    //        log.info("TimeZone: " + c.getTimeZone().getDisplayName());
    //        log.info("TimeZone: " + c.getTimeZone().getID());
    //        log.info("Date: " + getDateAsString(c.getTime()));
    //        log.info("DateTime: " + getDateAsString(dtg));
    //        log.info("DateTime: " + dtg.toString());
    //        log.info("DateTime: " + dtg.toStringRfc3339());
    return dtg;
}

From source file:com.linuxbox.enkive.statistics.gathering.past.PastGatherer.java

public void consolidatePastHours() {
    Calendar c = Calendar.getInstance();
    c.setTime(statDate);/* w  w w  .  j a va2  s.c o m*/
    c.set(Calendar.MILLISECOND, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MINUTE, 0);
    setEndDate(CONSOLIDATION_HOUR);

    if (c.getTimeInMillis() > endDate.getTime()) {
        client.storeData(consolidatePast(CONSOLIDATION_HOUR, c));
    }
}

From source file:org.apache.taverna.robundle.manifest.TestManifestJSON.java

@Test
public void createBundle() throws Exception {
    // Create bundle as in Example 3 of the specification
    // http://wf4ever.github.io/ro/bundle/2013-05-21/
    try (Bundle bundle = Bundles.createBundle()) {
        Calendar createdOnCal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ENGLISH);
        // "2013-03-05T17:29:03Z"
        // Remember months are 0-based in java.util.Calendar!
        createdOnCal.set(2013, 3 - 1, 5, 17, 29, 03);
        createdOnCal.set(Calendar.MILLISECOND, 0);
        FileTime createdOn = FileTime.fromMillis(createdOnCal.getTimeInMillis());
        Manifest manifest = bundle.getManifest();
        manifest.setCreatedOn(createdOn);
        Agent createdBy = new Agent("Alice W. Land");
        createdBy.setUri(URI.create("http://example.com/foaf#alice"));
        createdBy.setOrcid(URI.create("http://orcid.org/0000-0002-1825-0097"));

        manifest.setCreatedBy(createdBy);

        Path evolutionPath = bundle.getPath(".ro/evolution.ttl");
        Files.createDirectories(evolutionPath.getParent());
        Bundles.setStringValue(evolutionPath, "<manifest.json> < http://purl.org/pav/retrievedFrom> "
                + "<http://wf4ever.github.io/ro/bundle/2013-05-21/example/.ro/manifest.json> .");
        manifest.getHistory().add(evolutionPath);

        Path jpeg = bundle.getPath("folder/soup.jpeg");
        Files.createDirectory(jpeg.getParent());
        Files.createFile(jpeg);/*from  w  ww.  j a  v  a2  s. c o m*/
        // register in manifest first
        bundle.getManifest().getAggregation(jpeg);

        URI blog = URI.create("http://example.com/blog/");
        bundle.getManifest().getAggregation(blog);

        Path readme = bundle.getPath("README.txt");
        Files.createFile(readme);
        PathMetadata readmeMeta = bundle.getManifest().getAggregation(readme);
        readmeMeta.setMediatype("text/plain");
        Agent readmeCreatedby = new Agent("Bob Builder");
        readmeCreatedby.setUri(URI.create("http://example.com/foaf#bob"));
        readmeMeta.setCreatedBy(readmeCreatedby);

        // 2013-02-12T19:37:32.939Z
        createdOnCal.set(2013, 2 - 1, 12, 19, 37, 32);
        createdOnCal.set(Calendar.MILLISECOND, 939);
        createdOn = FileTime.fromMillis(createdOnCal.getTimeInMillis());
        Files.setLastModifiedTime(readme, createdOn);
        readmeMeta.setCreatedOn(createdOn);

        PathMetadata comments = bundle.getManifest()
                .getAggregation(URI.create("http://example.com/comments.txt"));
        comments.getOrCreateBundledAs().setURI(URI.create("urn:uuid:a0cf8616-bee4-4a71-b21e-c60e6499a644"));
        comments.getOrCreateBundledAs().setFolder(bundle.getPath("/folder/"));
        comments.getOrCreateBundledAs().setFilename("external.txt");

        PathAnnotation jpegAnn = new PathAnnotation();
        jpegAnn.setAbout(jpeg);
        Path soupProps = Bundles.getAnnotations(bundle).resolve("soup-properties.ttl");
        Bundles.setStringValue(soupProps, "</folder/soup.jpeg> <http://xmlns.com/foaf/0.1/depicts> "
                + "<http://example.com/menu/tomato-soup> .");
        jpegAnn.setContent(soupProps);
        // jpegAnn.setContent(URI.create("annotations/soup-properties.ttl"));
        jpegAnn.setUri(URI.create("urn:uuid:d67466b4-3aeb-4855-8203-90febe71abdf"));
        manifest.getAnnotations().add(jpegAnn);

        PathAnnotation proxyAnn = new PathAnnotation();
        proxyAnn.setAbout(comments.getBundledAs().getURI());
        proxyAnn.setContent(URI.create("http://example.com/blog/they-aggregated-our-file"));
        manifest.getAnnotations().add(proxyAnn);

        Path metaAnn = Bundles.getAnnotations(bundle).resolve("a-meta-annotation-in-this-ro.txt");
        Bundles.setStringValue(metaAnn, "This bundle contains an annotation about /folder/soup.jpeg");

        PathAnnotation metaAnnotation = new PathAnnotation();
        metaAnnotation.setAbout(bundle.getRoot());
        metaAnnotation.getAboutList().add(URI.create("urn:uuid:d67466b4-3aeb-4855-8203-90febe71abdf"));

        metaAnnotation.setContent(metaAnn);
        manifest.getAnnotations().add(metaAnnotation);

        Path jsonPath = bundle.getManifest().writeAsJsonLD();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = Bundles.getStringValue(jsonPath);
        //System.out.println(jsonStr);
        JsonNode json = objectMapper.readTree(jsonStr);
        checkManifestJson(json);
    }
}