Example usage for java.util Date setTime

List of usage examples for java.util Date setTime

Introduction

In this page you can find the example usage for java.util Date setTime.

Prototype

public void setTime(long time) 

Source Link

Document

Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

Usage

From source file:org.silverpeas.components.resourcesmanager.model.Reservation.java

public Date getCreationDate() {
    if (StringUtil.isLong(creationDate)) {
        Date creation = new Date();
        creation.setTime(Long.parseLong(creationDate));
        return creation;
    }/*from w  w w.java  2 s  .c  o m*/
    return null;
}

From source file:org.transdroid.search.hdbitsorg.HdBitsOrgAdapter.java

protected List<SearchResult> parseHtml(String html, int maxResults) throws Exception {
    Log.d(LOG_TAG, "Parsing search results.");

    List<SearchResult> results = new ArrayList<SearchResult>();
    int matchCount = 0;
    int errorCount = 0;

    Pattern regex = Pattern.compile(SEARCH_REGEX, Pattern.DOTALL);
    Matcher match = regex.matcher(html);
    while (match.find() && matchCount < maxResults) {
        matchCount++;//from   w w w  . j  av  a2 s . c om
        if (match.groupCount() != 11) {
            errorCount++;
            continue;
        }

        String detailsUrl = URL_PREFIX + match.group(1);
        String title = match.group(2);
        String torrentUrl = URL_PREFIX + match.group(3);
        String size = match.group(8) + match.group(9); // size + unit
        int seeders = Integer.parseInt(match.group(10));
        int leechers = Integer.parseInt(match.group(11));

        int time1 = Integer.parseInt(match.group(4));
        String timeUnit1 = match.group(5);
        int time2 = Integer.parseInt(match.group(6));
        String timeUnit2 = match.group(7);

        // hdbits.org lists "added date" in a relative format (i.e. 8 months 7 days ago)
        // we roughly calculate the number of MS elapsed then subtract that from "now"
        // could be a day or two off depending on month lengths, it's just imprecise data
        long elapsedTime = 0;
        if (timeUnit1.startsWith("month"))
            elapsedTime += time1 * 1000L * 60L * 60L * 24L * 30L;
        if (timeUnit1.startsWith("day"))
            elapsedTime += time1 * 1000L * 60L * 60L * 24L;
        if (timeUnit2.startsWith("day"))
            elapsedTime += time2 * 1000L * 60L * 60L * 24L;
        if (timeUnit2.startsWith("hour"))
            elapsedTime += time2 * 1000L * 60L * 60L;

        Date addedDate = new Date();
        addedDate.setTime(addedDate.getTime() - elapsedTime);

        // build our search result
        SearchResult torrent = new SearchResult(title, torrentUrl, detailsUrl, size, addedDate, seeders,
                leechers);
        results.add(torrent);
    }

    Log.d(LOG_TAG, "Found " + matchCount + " matches and successfully parsed " + (matchCount - errorCount)
            + " of those matches.");
    return results;
}

From source file:UserInterface.SecurityAdministratorRole.SecurityAdministratorWorkArea.java

private void userJButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_userJButton1ActionPerformed
    // TODO add your handling code here:
    //        IncidentsAnalysisJPanel incidentsAnalysisJPanel = new IncidentsAnalysisJPanel(userProcessContainer, securityAuthorityEnterprise);
    //        userProcessContainer.add("IncidentsAnalysisJPanel", incidentsAnalysisJPanel);
    //        CardLayout layout = (CardLayout) userProcessContainer.getLayout();
    //        layout.next(userProcessContainer);
    //        //ww  w .j a  v a  2 s. c  o  m
    //        
    // SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE, MMM d, yyyy");  
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    Date today = new Date();
    Date weekBefore = new Date();
    weekBefore.setTime(today.getTime() + (long) (-7) * 1000 * 60 * 60 * 24);

    long todayDate = (today.getTime()) / (1000 * 60 * 60 * 24);
    long weekDate = (weekBefore.getTime()) / (1000 * 60 * 60 * 24);
    //ArrayList<Date> incidentDatesList = new ArrayList<Date>();

    int cong1 = 0;
    int cong2 = 0;
    int cong3 = 0;
    int cong4 = 0;

    int counter1 = 0;
    int counter2 = 0;
    int counter3 = 0;
    int counter4 = 0;

    for (WorkRequest request : securityAuthorityEnterprise.getWorkQueue().getWorkRequestList()) {
        IncidentWorkRequest incidentRequest = (IncidentWorkRequest) request;
        long requestDate = (request.getRequestDate().getTime()) / (1000 * 60 * 60 * 24);
        if (requestDate >= weekDate && requestDate <= todayDate) {

            if (incidentRequest.getTypeOfEmergency().equals("Medical")) {
                cong1 += incidentRequest.getCrowdednessLevel();
                counter1++;
            } else if (incidentRequest.getTypeOfEmergency().equals("Accidental")) {
                cong2 += incidentRequest.getCrowdednessLevel();
                counter2++;
            } else if (incidentRequest.getTypeOfEmergency().equals("Security")) {
                cong3 += incidentRequest.getCrowdednessLevel();
                counter3++;
            } else {
                cong4 += incidentRequest.getCrowdednessLevel();
                counter4++;
            }

        }
    }

    if (counter4 == 0) {
        counter4 = 1;
    }
    if (counter3 == 0) {
        counter3 = 1;
    }
    if (counter2 == 0) {
        counter2 = 1;
    }
    if (counter1 == 0) {
        counter1 = 1;
    }

    dataset.setValue(cong1 / counter1, "Incident Types", "Medical");
    dataset.setValue(cong2 / counter2, "Incident Types", "Accidental");
    dataset.setValue(cong3 / counter3, "Incident Types", "Security");
    dataset.setValue(cong4 / counter4, "Incident Types", "Other");

    JFreeChart chart = ChartFactory.createBarChart("Incident Type v/s Average Congestion", "Incident Types",
            "Average Congestion Levels", dataset, PlotOrientation.VERTICAL, false, true, false);
    CategoryPlot plot = chart.getCategoryPlot();
    plot.setRangeGridlinePaint(Color.BLUE);
    ChartFrame frame = new ChartFrame("Bar Chart for Congestion Analysis", chart);
    frame.setVisible(true);
    frame.setSize(750, 750);

}

From source file:com.careme.apvereda.careme.AccumulatorService.java

private void monitor(Location loc) {
    // We suppose the user can move 200m in 5 minutes
    SharedPreferences shared = getApplicationContext().getSharedPreferences("monitor", Context.MODE_PRIVATE);
    Date date = new Date();
    date.setTime(shared.getLong("date", 0));
    Date act = new Date();
    if (act.getTime() - date.getTime() > 900000) {
        SharedPreferences.Editor editor = shared.edit();
        editor.putInt("measurements", 0);
        editor.commit();//from w  w w  .  j  av a2 s. c o  m
    }
    if (act.getTime() - date.getTime() > 300000) {
        int measurements = shared.getInt("measurements", 0);
        if (measurements >= 6) {
            // Walking, update the list
            updateList(loc);
        } else {
            // Has stopped, reset the list
            resetList(loc);
        }
        // Update the date
        SharedPreferences.Editor editor = shared.edit();
        act = new Date();
        editor.putLong("date", act.getTime());
        editor.commit();
    } else {
        int measurements = shared.getInt("measurements", 0);
        SharedPreferences.Editor editor = shared.edit();
        editor.putInt("measurements", measurements + 1);
        editor.commit();
    }

}

From source file:org.openhab.io.cv.internal.resources.RrdResource.java

@GET
@Produces({ MediaType.APPLICATION_JSON })
public Response getRrd(@Context HttpHeaders headers, @QueryParam("rrd") String itemName,
        @QueryParam("ds") String consFunction, @QueryParam("start") String start, @QueryParam("end") String end,
        @QueryParam("res") long resolution) {

    if (logger.isDebugEnabled())
        logger.debug("Received GET request at '{}' for rrd '{}'.", uriInfo.getPath(), itemName);
    String responseType = MediaTypeHelper.getResponseMediaType(headers.getAcceptableMediaTypes());

    if (responseType != null) {

        // RRD specific: no equivalent in PersistenceService known
        ConsolFun consilidationFunction = ConsolFun.valueOf(consFunction);

        // read the start/end time as they are provided in the RRD-way, we
        // use/*from w ww  . j  a  va2  s  .  c om*/
        // the RRD4j to read them
        long[] times = Util.getTimestamps(start, end);
        Date startTime = new Date();
        startTime.setTime(times[0] * 1000L);
        Date endTime = new Date();
        endTime.setTime(times[1] * 1000L);

        if (itemName.endsWith(".rrd"))
            itemName = itemName.substring(0, itemName.length() - 4);
        String[] parts = itemName.split(":");
        String service = "rrd4j";

        if (parts.length == 2) {
            itemName = parts[1];
            service = parts[0];
        }

        Item item;
        try {
            item = CVApplication.getItemUIRegistry().getItem(itemName);
            logger.debug("item '{}' found ", item);

            // Prefer RRD-Service
            QueryablePersistenceService persistenceService = CVApplication.getPersistenceServices()
                    .get(service);
            // Fallback to first persistenceService from list
            if (persistenceService == null) {
                Iterator<Entry<String, QueryablePersistenceService>> pit = CVApplication
                        .getPersistenceServices().entrySet().iterator();
                if (pit.hasNext()) {
                    persistenceService = pit.next().getValue();
                } else {
                    throw new IllegalArgumentException("No Persistence service found.");
                }
            }
            Object data = null;
            if (persistenceService.getName().equals("rrd4j")) {
                data = getRrdSeries(persistenceService, item, consilidationFunction, startTime, endTime,
                        resolution);
            } else {
                data = getPersistenceSeries(persistenceService, item, startTime, endTime, resolution);
            }
            return Response.ok(data, responseType).build();
        } catch (ItemNotFoundException e) {
            logger.error("Item '{}' not found error while requesting series data.", itemName);
        }
        return Response.serverError().build();
    } else {
        return Response.notAcceptable(null).build();
    }
}

From source file:com.climate.oada.dao.impl.S3ResourceDAO.java

@Override
public List<FileResource> getFileUrls(Long userId, String type) {
    List<FileResource> retval = new ArrayList<FileResource>();
    long validfor = new Long(validHours).longValue() * HOURS_TO_MILLISECONDS;
    try {/*www  .  j  a  v a 2 s .c o  m*/
        AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
        String prefix = userId.toString() + S3_SEPARATOR + type;

        LOG.debug("Listing objects from bucket " + bucketName + " with prefix " + prefix);

        ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName)
                .withPrefix(prefix);
        ObjectListing objectListing;
        do {
            objectListing = s3client.listObjects(listObjectsRequest);
            for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                LOG.debug(" - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");

                Date expiration = new Date();
                long milliSeconds = expiration.getTime();
                milliSeconds += validfor;
                expiration.setTime(milliSeconds);

                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                        bucketName, objectSummary.getKey());
                generatePresignedUrlRequest.setMethod(HttpMethod.GET);
                generatePresignedUrlRequest.setExpiration(expiration);

                FileResource res = new FileResource();
                res.setFileURL(s3client.generatePresignedUrl(generatePresignedUrlRequest));
                retval.add(res);
            }
            listObjectsRequest.setMarker(objectListing.getNextMarker());
        } while (objectListing.isTruncated());
    } catch (AmazonServiceException ase) {
        logAWSServiceException(ase);
    } catch (AmazonClientException ace) {
        logAWSClientException(ace);
    } catch (Exception e) {
        LOG.error("Unable to retrieve S3 file URLs " + e.getMessage());
    }
    return retval;
}

From source file:org.jfrog.build.extractor.gradle.GradleBuildInfoExtractor.java

public Build extract(BuildInfoRecorderTask buildInfoTask, BuildInfoExtractorSpec spec) {
    Project rootProject = buildInfoTask.getRootProject();
    long startTime = Long.parseLong(System.getProperty("build.start"));
    String buildName = ArtifactoryPluginUtils.getProperty(PROP_BUILD_NAME, rootProject);
    if (StringUtils.isBlank(buildName)) {
        buildName = rootProject.getName().replace(' ', '-');
    } else {//from  w w  w. j  ava  2s  .co m
        buildName = buildName.replace(' ', '-');
    }
    BuildInfoBuilder buildInfoBuilder = new BuildInfoBuilder(buildName);
    Date startedDate = new Date();
    startedDate.setTime(startTime);
    buildInfoBuilder.type(BuildType.GRADLE);
    String buildNumber = ArtifactoryPluginUtils.getProperty(PROP_BUILD_NUMBER, rootProject);
    if (buildNumber == null) {
        buildNumber = System.getProperty("timestamp", Long.toString(System.currentTimeMillis()));
    }
    GradleInternal gradleInternals = (GradleInternal) rootProject.getGradle();
    BuildAgent buildAgent = new BuildAgent("Gradle", gradleInternals.getGradleVersion());
    // If
    String agentString = buildAgent.toString();
    String buildAgentProp = ArtifactoryPluginUtils.getProperty(BuildInfoProperties.PROP_BUILD_AGENT,
            rootProject);
    if (StringUtils.isNotBlank(buildAgentProp)) {
        agentString = buildAgentProp;
    }
    Agent agent = new Agent(agentString);
    buildInfoBuilder.agent(agent).durationMillis(System.currentTimeMillis() - startTime)
            .startedDate(startedDate).number(buildNumber).buildAgent(buildAgent);
    for (Project subProject : rootProject.getSubprojects()) {
        BuildInfoRecorderTask birTask = (BuildInfoRecorderTask) subProject.getTasks().getByName("buildInfo");
        buildInfoBuilder.addModule(extractModule(birTask.getConfiguration(), subProject));
    }
    String parentName = ArtifactoryPluginUtils.getProperty(PROP_PARENT_BUILD_NAME, rootProject);
    String parentNumber = ArtifactoryPluginUtils.getProperty(PROP_PARENT_BUILD_NUMBER, rootProject);
    if (parentName != null && parentNumber != null) {
        buildInfoBuilder.parentName(parentName);
        buildInfoBuilder.parentNumber(parentNumber);
    }
    String principal = ArtifactoryPluginUtils.getProperty(ClientProperties.PROP_PRINCIPAL, rootProject);
    if (StringUtils.isBlank(principal)) {
        principal = System.getProperty("user.name");
    }
    buildInfoBuilder.principal(principal);
    String artifactoryPrincipal = ArtifactoryPluginUtils.getProperty(ClientProperties.PROP_PUBLISH_USERNAME,
            rootProject);
    if (StringUtils.isBlank(artifactoryPrincipal)) {
        artifactoryPrincipal = System.getProperty("user.name");
    }
    buildInfoBuilder.artifactoryPrincipal(artifactoryPrincipal);
    String buildUrl = ArtifactoryPluginUtils.getProperty(BuildInfoProperties.PROP_BUILD_URL, rootProject);
    if (StringUtils.isNotBlank(buildUrl)) {
        buildInfoBuilder.url(buildUrl);
    }
    String vcsRevision = ArtifactoryPluginUtils.getProperty(BuildInfoProperties.PROP_VCS_REVISION, rootProject);
    if (StringUtils.isNotBlank(vcsRevision)) {
        buildInfoBuilder.vcsRevision(vcsRevision);
    }
    Properties properties = gatherSysPropInfo();
    properties.putAll(buildInfoProps);
    properties.putAll(BuildInfoExtractorUtils.getEnvProperties(startParamProps));
    properties.putAll(BuildInfoExtractorUtils.filterEnvProperties(startParamProps));
    buildInfoBuilder.properties(properties);
    log.debug("buildInfoBuilder = " + buildInfoBuilder);
    // for backward compatibility for Artifactory 2.2.3
    Build build = buildInfoBuilder.build();
    if (parentName != null && parentNumber != null) {
        build.setParentBuildId(parentName);
    }
    return build;
}

From source file:org.openvpms.web.component.property.AbstractDateTimePropertyTransformer.java

/**
 * Zeroes any seconds (and milliseconds) from the date.
 *
 * @param date the date//w  w  w  . j a v  a  2 s .  com
 * @return the modified date
 */
private Date removeSeconds(Date date) {
    long ms = date.getTime();
    long seconds = ms % (60 * 1000);
    if (seconds != 0) {
        date.setTime(ms - seconds);
    }
    return date;
}

From source file:pl.touk.wonderfulsecurity.dao.WsecBaseDaoImpl.java

private void applyFilters(String key, Object filter, DetachedCriteria criteria) {
    if (key.endsWith(LIKE_SUFFIX)) {
        criteria.add(//from  ww  w  .ja  v a 2s  .  com
                Restrictions.like(key.substring(0, key.length() - LIKE_SUFFIX.length()), "%" + filter + "%"));
    } else if (key.endsWith(I_LIKE_SUFFIX)) {
        criteria.add(Restrictions.ilike(key.substring(0, key.length() - I_LIKE_SUFFIX.length()),
                "%" + filter + "%"));
    } else if (key.endsWith(LIKE_DATE_SUFFIX)) {
        String realKey = key.substring(0, key.length() - LIKE_DATE_SUFFIX.length());
        Date dateFilter = ((Date) filter);
        Date plus24h = new Date();
        plus24h.setTime(dateFilter.getTime() + 86399999l);
        criteria.add(Restrictions.between(realKey, dateFilter, plus24h));
    } else if (key.endsWith(NULL_END_SUFFIX)) {
        criteria.add(Restrictions.isNull(key.substring(0, key.length() - NULL_END_SUFFIX.length())));
    } else if (key.endsWith(NOT_NULL_END_SUFFIX)) {
        criteria.add(Restrictions.isNotNull(key.substring(0, key.length() - NOT_NULL_END_SUFFIX.length())));
    } else if (key.endsWith(LIKE_MATCH_START_SUFFIX)) {
        criteria.add(Restrictions.like(key.substring(0, key.length() - LIKE_MATCH_START_SUFFIX.length()),
                filter + "%"));
    } else if (key.endsWith(I_LIKE_MATCH_START_SUFFIX)) {
        criteria.add(Restrictions.ilike(key.substring(0, key.length() - I_LIKE_MATCH_START_SUFFIX.length()),
                filter + "%"));
    } else if (key.endsWith(NOT_LIKE_END_SUFFIX)) {
        criteria.add(Restrictions.not(Restrictions
                .like(key.substring(0, key.length() - NOT_LIKE_END_SUFFIX.length()), "%" + filter + "%")));
    } else if (key.endsWith(LIKE_MATCH_END_SUFFIX)) {
        criteria.add(Restrictions.like(key.substring(0, key.length() - LIKE_MATCH_END_SUFFIX.length()),
                "%" + filter));
    } else if (key.endsWith(I_LIKE_MATCH_END_SUFFIX)) {
        criteria.add(Restrictions.ilike(key.substring(0, key.length() - I_LIKE_MATCH_END_SUFFIX.length()),
                "%" + filter));
    } else if (key.endsWith(BETWEEN_DATES_END_SUFFIX)) {
        String realKeyWithUpperLimit = key.substring(0, key.length() - BETWEEN_DATES_END_SUFFIX.length());
        String upperLimitAsStr = realKeyWithUpperLimit.substring(realKeyWithUpperLimit.indexOf("|") + 1);
        try {
            Date upperLimit = new Timestamp(dateFormat.parse(upperLimitAsStr).getTime());
            String realKey = realKeyWithUpperLimit.substring(0, realKeyWithUpperLimit.indexOf("|"));
            criteria.add(Restrictions.between(realKey, new Timestamp(((Date) filter).getTime()), upperLimit));
        } catch (ParseException e) {
            throw new IllegalArgumentException("for the key '" + key + "' the date '" + upperLimitAsStr
                    + "' can't be parsed according to the format '" + dateFormatAsStr, e);
        }
    } else if (key.endsWith(EVERYTHING_EXCEPT_END_SUFFIX)) {
        criteria.add(Restrictions.or(
                Restrictions.ne(key.substring(0, key.length() - EVERYTHING_EXCEPT_END_SUFFIX.length()), filter),
                Restrictions.isNull(key.substring(0, key.length() - EVERYTHING_EXCEPT_END_SUFFIX.length()))));
    } else if (filter == null) {
        criteria.add(Restrictions.isNull(key));
    } else if (filter instanceof Collection) {
        criteria.add(Restrictions.in(key, (Collection) filter));
    } else {
        criteria.add(Restrictions.eq(key, filter));
    }
}

From source file:org.mobicents.applications.ussd.examples.http.push.HTTPPush.java

protected void addStatusEntry(String entry) {
    Date d = new Date();
    d.setTime(System.currentTimeMillis());
    StringBuilder sb = new StringBuilder();
    sb.append(d.toString()).append(">").append(entry);
    sb.append("\n");
    sb.append("---------------------------------");
    logger.info(sb.toString());//from   w w  w. j  a  v  a2 s  .  co m
    this.status.append(sb.toString().replaceAll("<", "-").replaceAll(">", "-"));
}