Example usage for org.joda.time DateTime withMillisOfSecond

List of usage examples for org.joda.time DateTime withMillisOfSecond

Introduction

In this page you can find the example usage for org.joda.time DateTime withMillisOfSecond.

Prototype

public DateTime withMillisOfSecond(int millis) 

Source Link

Document

Returns a copy of this datetime with the millis of second field updated.

Usage

From source file:org.apache.marmotta.kiwi.persistence.KiWiConnection.java

License:Apache License

/**
 * Load a literal with the date value given as argument if it exists. The method will first look in
 * the node cache for cached nodes. If no cache entry is found, it will run a database query ("load.literal_by_tv")
 * on the NODES table and construct a new KiWiLiteral using the values of the literal columns
 * (svalue, ivalue, ...). The type of literal returned depends on the value of the ntype column.
 * <p/>/*w w  w.jav  a2  s  . c  om*/
 * When a node is loaded from the database, it will be added to the different caches to speed up
 * subsequent requests.
 *
 * @param date the date of the date literal to load
 * @return a KiWiDateLiteral with the correct date, or null if it does not exist
 * @throws SQLException
 */
public KiWiDateLiteral loadLiteral(DateTime date) throws SQLException {
    // look in cache
    KiWiLiteral element = literalCache
            .get(LiteralCommons.createCacheKey(date.withMillisOfSecond(0), Namespaces.NS_XSD + "dateTime"));
    if (element != null && element instanceof KiWiDateLiteral) {
        return (KiWiDateLiteral) element;
    }

    requireJDBCConnection();

    KiWiUriResource ltype = loadUriResource(Namespaces.NS_XSD + "dateTime");

    if (ltype == null || ltype.getId() < 0) {
        return null;
    }

    literalLock.lock();
    try {

        // otherwise prepare a query, depending on the parameters given
        PreparedStatement query = getPreparedStatement("load.literal_by_tv");
        query.setTimestamp(1, new Timestamp(date.getMillis()), calendarUTC);
        query.setInt(2, date.getZone().getOffset(date) / 1000);
        query.setLong(3, ltype.getId());

        // run the database query and if it yields a result, construct a new node; the method call will take care of
        // caching the constructed node for future calls
        ResultSet result = query.executeQuery();
        try {
            if (result.next()) {
                return (KiWiDateLiteral) constructNodeFromDatabase(result);
            } else {
                return null;
            }
        } finally {
            result.close();
        }
    } finally {
        literalLock.unlock();
    }
}

From source file:org.codehaus.httpcache4j.Conditionals.java

License:Open Source License

/**
 * You should use the server's time here. Otherwise you might get unexpected results.
 * The typical use case is: <br/>//from  w w  w.ja va  2 s  .  co m
 * <pre>
 *   HTTPResponse response = ....
 *   HTTPRequest request = createRequest();
 *   request = request.conditionals(new Conditionals().ifModifiedSince(response.getLastModified());
 * </pre>
 *
 * @param time the time to check.
 * @return the conditionals with the If-Modified-Since date set.
 */
public Conditionals ifModifiedSince(DateTime time) {
    Validate.isTrue(match.isEmpty(),
            String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH));
    Validate.isTrue(unModifiedSince == null, String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE,
            HeaderConstants.IF_UNMODIFIED_SINCE));
    time = time.toDateTime(DateTimeZone.forID("UTC"));
    time = time.withMillisOfSecond(0);
    return new Conditionals(empty(), noneMatch, time, null);
}

From source file:org.codehaus.httpcache4j.Conditionals.java

License:Open Source License

/**
 * You should use the server's time here. Otherwise you might get unexpected results.
 * The typical use case is: <br/>//from   ww w . jav  a2 s  .  com
 * <pre>
 *   HTTPResponse response = ....
 *   HTTPRequest request = createRequest();
 *   request = request.conditionals(new Conditionals().ifUnModifiedSince(response.getLastModified());
 * </pre>
 *
 * @param time the time to check.
 * @return the conditionals with the If-Unmodified-Since date set.
 */
public Conditionals ifUnModifiedSince(DateTime time) {
    Validate.isTrue(noneMatch.isEmpty(),
            String.format(ERROR_MESSAGE, HeaderConstants.IF_UNMODIFIED_SINCE, HeaderConstants.IF_NON_MATCH));
    Validate.isTrue(modifiedSince == null, String.format(ERROR_MESSAGE, HeaderConstants.IF_UNMODIFIED_SINCE,
            HeaderConstants.IF_MODIFIED_SINCE));
    time = time.toDateTime(DateTimeZone.forID("UTC"));
    time = time.withMillisOfSecond(0);
    return new Conditionals(match, empty(), null, time);
}

From source file:org.everit.jira.timetracker.plugin.util.DateTimeConverterUtil.java

License:Apache License

/**
 * Return a Calendar with time set by the start of the given day.
 *
 * @param date/*  w w w.j  av a  2 s .  com*/
 *          The time to set the calendar
 * @return The calendar which represents the start of the day
 */
public static DateTime setDateToDayStart(final DateTime date) {
    DateTime dateStartOfTheDay = date.withHourOfDay(0);
    dateStartOfTheDay = dateStartOfTheDay.withMinuteOfHour(0);
    dateStartOfTheDay = dateStartOfTheDay.withSecondOfMinute(0);
    dateStartOfTheDay = dateStartOfTheDay.withMillisOfSecond(0);
    return dateStartOfTheDay;
}

From source file:org.jruby.CompatVersion.java

License:LGPL

protected static RubyTime s_mload(IRubyObject recv, RubyTime time, IRubyObject from) {
        Ruby runtime = recv.getRuntime();

        DateTime dt = new DateTime(DateTimeZone.UTC);

        byte[] fromAsBytes = null;
        fromAsBytes = from.convertToString().getBytes();
        if (fromAsBytes.length != 8) {
            throw runtime.newTypeError("marshaled time format differ");
        }/*  w w  w . j a v a 2  s .c o  m*/
        int p = 0;
        int s = 0;
        for (int i = 0; i < 4; i++) {
            p |= ((int) fromAsBytes[i] & 0xFF) << (8 * i);
        }
        for (int i = 4; i < 8; i++) {
            s |= ((int) fromAsBytes[i] & 0xFF) << (8 * (i - 4));
        }
        if ((p & (1 << 31)) == 0) {
            dt = dt.withMillis(p * 1000L + s);
        } else {
            p &= ~(1 << 31);
            dt = dt.withYear(((p >>> 14) & 0xFFFF) + 1900);
            dt = dt.withMonthOfYear(((p >>> 10) & 0xF) + 1);
            dt = dt.withDayOfMonth(((p >>> 5) & 0x1F));
            dt = dt.withHourOfDay((p & 0x1F));
            dt = dt.withMinuteOfHour(((s >>> 26) & 0x3F));
            dt = dt.withSecondOfMinute(((s >>> 20) & 0x3F));
            // marsaling dumps usec, not msec
            dt = dt.withMillisOfSecond((s & 0xFFFFF) / 1000);
            dt = dt.withZone(getLocalTimeZone(runtime));
            time.setUSec((s & 0xFFFFF) % 1000);
        }
        time.setDateTime(dt);
        return time;
    }

From source file:org.jruby.RubyTime.java

License:LGPL

protected static RubyTime s_mload(IRubyObject recv, RubyTime time, IRubyObject from) {
    Ruby runtime = recv.getRuntime();/*from w w  w .java2s .com*/

    DateTime dt = new DateTime(DateTimeZone.UTC);

    byte[] fromAsBytes;
    fromAsBytes = from.convertToString().getBytes();
    if (fromAsBytes.length != 8) {
        throw runtime.newTypeError("marshaled time format differ");
    }
    int p = 0;
    int s = 0;
    for (int i = 0; i < 4; i++) {
        p |= ((int) fromAsBytes[i] & 0xFF) << (8 * i);
    }
    for (int i = 4; i < 8; i++) {
        s |= ((int) fromAsBytes[i] & 0xFF) << (8 * (i - 4));
    }
    boolean utc = false;
    if ((p & (1 << 31)) == 0) {
        dt = dt.withMillis(p * 1000L);
        time.setUSec((s & 0xFFFFF) % 1000);
    } else {
        p &= ~(1 << 31);
        utc = ((p >>> 30 & 0x1) == 0x1);
        dt = dt.withYear(((p >>> 14) & 0xFFFF) + 1900);
        dt = dt.withMonthOfYear(((p >>> 10) & 0xF) + 1);
        dt = dt.withDayOfMonth(((p >>> 5) & 0x1F));
        dt = dt.withHourOfDay((p & 0x1F));
        dt = dt.withMinuteOfHour(((s >>> 26) & 0x3F));
        dt = dt.withSecondOfMinute(((s >>> 20) & 0x3F));
        // marsaling dumps usec, not msec
        dt = dt.withMillisOfSecond((s & 0xFFFFF) / 1000);
        time.setUSec((s & 0xFFFFF) % 1000);
    }
    time.setDateTime(dt);
    if (!utc)
        time.localtime();

    from.getInstanceVariables().copyInstanceVariablesInto(time);

    // pull out nanos, offset, zone
    IRubyObject nano_num = (IRubyObject) from.getInternalVariables().getInternalVariable("nano_num");
    IRubyObject nano_den = (IRubyObject) from.getInternalVariables().getInternalVariable("nano_den");
    IRubyObject offsetVar = (IRubyObject) from.getInternalVariables().getInternalVariable("offset");
    IRubyObject zoneVar = (IRubyObject) from.getInternalVariables().getInternalVariable("zone");

    if (nano_num != null && nano_den != null) {
        long nanos = nano_num.convertToInteger().getLongValue() / nano_den.convertToInteger().getLongValue();
        time.nsec += nanos;
    }

    int offset = 0;
    if (offsetVar != null && offsetVar.respondsTo("to_int")) {
        IRubyObject oldExc = runtime.getGlobalVariables().get("$!"); // Save $!
        try {
            offset = offsetVar.convertToInteger().getIntValue() * 1000;
        } catch (RaiseException typeError) {
            runtime.getGlobalVariables().set("$!", oldExc); // Restore $!
        }
    }

    String zone = "";
    if (zoneVar != null && zoneVar.respondsTo("to_str")) {
        IRubyObject oldExc = runtime.getGlobalVariables().get("$!"); // Save $!
        try {
            zone = zoneVar.convertToString().toString();
        } catch (RaiseException typeError) {
            runtime.getGlobalVariables().set("$!", oldExc); // Restore $!
        }
    }

    time.dt = dt.withZone(getTimeZoneWithOffset(runtime, zone, offset));
    return time;
}

From source file:org.jtalks.jcommune.service.transactional.TransactionalComponentService.java

License:Open Source License

/**
 * {@inheritDoc}//from  ww w  . ja  v a 2  s. co  m
 */
@Override
@PreAuthorize("hasPermission(#componentInformation.id, 'COMPONENT', 'GeneralPermission.ADMIN')")
public void setComponentInformation(ComponentInformation componentInformation) {
    if (componentInformation.getId() != getComponentOfForum().getId()) {
        throw new IllegalArgumentException(
                "Service should work with the same component as the componentInformation argument.");
    }
    Component forumComponent = getDao().getComponent();
    forumComponent.setName(componentInformation.getName());
    forumComponent.setDescription(componentInformation.getDescription());
    forumComponent.setProperty(LOGO_TOOLTIP_PROPERTY, componentInformation.getLogoTooltip());
    forumComponent.setProperty(TITLE_PREFIX_PROPERTY, componentInformation.getTitlePrefix());
    forumComponent.setProperty(COPYRIGHT_PROPERTY, componentInformation.getCopyright());

    forumComponent.setProperty(COMPONENT_AVATAR_MAX_SIZE, componentInformation.getAvatarMaxSize());
    forumComponent.setProperty(COMPONENT_EMAIL_NOTIFICATION,
            String.valueOf(componentInformation.isEmailNotification()));
    forumComponent.setProperty(COMPONENT_SESSION_TIMEOUT, componentInformation.getSessionTimeout());

    if (!StringUtils.isEmpty(componentInformation.getLogo())) {
        forumComponent.setProperty(LOGO_PROPERTY, componentInformation.getLogo());
    }

    if (!StringUtils.isEmpty(componentInformation.getIcon())) {
        forumComponent.setProperty(COMPONENT_FAVICON_PNG_PARAM, componentInformation.getIcon());

        Base64Wrapper wrapper = new Base64Wrapper();
        byte[] favIcon = wrapper.decodeB64Bytes(componentInformation.getIcon());
        try {
            String iconInTheIcoFormat = icoFormatImageService.preProcessAndEncodeInString64(favIcon);
            forumComponent.setProperty(COMPONENT_FAVICON_ICO_PARAM, iconInTheIcoFormat);
        } catch (ImageProcessException e) {
            LOGGER.error("Can't convert fav icon to *.ico format", e);
        }
    }

    DateTime now = new DateTime();
    now = now.withMillisOfSecond(0);
    forumComponent.setProperty(COMPONENT_INFO_CHANGE_DATE_PROPERTY, String.valueOf(now.getMillis()));
}

From source file:org.jtalks.jcommune.web.controller.AdministrationImagesController.java

License:Open Source License

/**
 * Creates instance of the service// w  w  w  . j  a  v  a  2s.  c  o  m
 *
 * @param componentService          service to work with the forum component
 * @param logoControllerUtils       utility object for logo converting functions
 * @param favIconPngControllerUtils utility object for fav icon converting (to PNG format) functions
 * @param favIconIcoControllerUtils utility object for fav icon converting (to ICO format) functions
 * @param messageSource             to resolve locale-dependent messages
 */
@Autowired
public AdministrationImagesController(ComponentService componentService,
        @Qualifier("forumLogoControllerUtils") ImageControllerUtils logoControllerUtils,
        @Qualifier("favIconPngControllerUtils") ImageControllerUtils favIconPngControllerUtils,
        @Qualifier("favIconIcoControllerUtils") ImageControllerUtils favIconIcoControllerUtils,
        MessageSource messageSource) {
    super(messageSource);
    this.componentService = componentService;
    this.logoControllerUtils = logoControllerUtils;
    this.favIconIcoControllerUtils = favIconIcoControllerUtils;
    this.favIconPngControllerUtils = favIconPngControllerUtils;

    DateTime now = new DateTime();
    startTime = now.withMillisOfSecond(0).toDate();
}

From source file:org.jtalks.jcommune.web.controller.AvatarController.java

License:Open Source License

/**
 * Write user avatar in response for rendering it on html pages.
 *
 * @param request  servlet request/*from  w w  w  .  j  a v a2s.co m*/
 * @param response servlet response
 * @param id       user database identifier
 * @throws NotFoundException if user with given encodedUsername not found
 * @throws IOException       throws if an output exception occurred
 */
@RequestMapping(value = "/users/{id}/avatar", method = RequestMethod.GET)
public void renderAvatar(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id)
        throws NotFoundException, IOException {
    JCUser user = userService.get(id);

    Date ifModifiedDate = super.getIfModifiedSinceDate(request.getHeader(IF_MODIFIED_SINCE_HEADER));
    // using 0 unix time if avatar has never changed (the date is null). It's easier to work with something
    // non-null than to check for null all the time.
    DateTime avatarLastModificationTime = defaultIfNull(user.getAvatarLastModificationTime(), new DateTime(0));
    // if-modified-since header doesn't include milliseconds, so if it floors the value (millis = 0), then
    // actual modification date will always be after the if-modified-since and we'll always be returning avatar
    avatarLastModificationTime = avatarLastModificationTime.withMillisOfSecond(0);
    if (avatarLastModificationTime.isAfter(ifModifiedDate.getTime())) {
        byte[] avatar = user.getAvatar();
        response.setContentType("image/jpeg");
        response.setContentLength(avatar.length);
        response.getOutputStream().write(avatar);
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    }
    setupAvatarHeaders(response, new Date(avatarLastModificationTime.getMillis()));
}

From source file:org.jvyamlb.SafeConstructorImpl.java

public static Object constructYamlTimestamp(final Constructor ctor, final Node node) {
    Matcher match = YMD_REGEXP.matcher(node.getValue().toString());
    if (match.matches()) {
        final String year_s = match.group(1);
        final String month_s = match.group(2);
        final String day_s = match.group(3);
        DateTime dt = new DateTime(0, 1, 1, 0, 0, 0, 0);
        if (year_s != null) {
            dt = dt.withYear(Integer.parseInt(year_s));
        }//from w  w w . ja  v  a  2s. c  o  m
        if (month_s != null) {
            dt = dt.withMonthOfYear(Integer.parseInt(month_s));
        }
        if (day_s != null) {
            dt = dt.withDayOfMonth(Integer.parseInt(day_s));
        }
        return new Object[] { dt };
    }
    match = TIMESTAMP_REGEXP.matcher(node.getValue().toString());
    if (!match.matches()) {
        return new Object[] { ctor.constructPrivateType(node) };
    }
    final String year_s = match.group(1);
    final String month_s = match.group(2);
    final String day_s = match.group(3);
    final String hour_s = match.group(4);
    final String min_s = match.group(5);
    final String sec_s = match.group(6);
    final String fract_s = match.group(7);
    final String utc = match.group(8);
    final String timezoneh_s = match.group(9);
    final String timezonem_s = match.group(10);

    int usec = 0;
    if (fract_s != null) {
        usec = Integer.parseInt(fract_s);
        if (usec != 0) {
            while (10 * usec < 1000) {
                usec *= 10;
            }
        }
    }
    DateTime dt = new DateTime(0, 1, 1, 0, 0, 0, 0);
    if ("Z".equalsIgnoreCase(utc)) {
        dt = dt.withZone(DateTimeZone.forID("Etc/GMT"));
    } else {
        if (timezoneh_s != null || timezonem_s != null) {
            int zone = 0;
            int sign = +1;
            if (timezoneh_s != null) {
                if (timezoneh_s.startsWith("-")) {
                    sign = -1;
                }
                zone += Integer.parseInt(timezoneh_s.substring(1)) * 3600000;
            }
            if (timezonem_s != null) {
                zone += Integer.parseInt(timezonem_s) * 60000;
            }
            dt = dt.withZone(DateTimeZone.forOffsetMillis(sign * zone));
        }
    }
    if (year_s != null) {
        dt = dt.withYear(Integer.parseInt(year_s));
    }
    if (month_s != null) {
        dt = dt.withMonthOfYear(Integer.parseInt(month_s));
    }
    if (day_s != null) {
        dt = dt.withDayOfMonth(Integer.parseInt(day_s));
    }
    if (hour_s != null) {
        dt = dt.withHourOfDay(Integer.parseInt(hour_s));
    }
    if (min_s != null) {
        dt = dt.withMinuteOfHour(Integer.parseInt(min_s));
    }
    if (sec_s != null) {
        dt = dt.withSecondOfMinute(Integer.parseInt(sec_s));
    }
    dt = dt.withMillisOfSecond(usec / 1000);

    return new Object[] { dt, new Integer(usec % 1000) };
}