Skip to content
This repository has been archived by the owner on Nov 9, 2017. It is now read-only.

Commit

Permalink
refactor: replace Joda-Time/PrettyTime with java.time and ICU4J
Browse files Browse the repository at this point in the history
  • Loading branch information
seanf committed Oct 26, 2015
1 parent c6b42e8 commit 7aa9fe7
Show file tree
Hide file tree
Showing 22 changed files with 335 additions and 279 deletions.
5 changes: 0 additions & 5 deletions functional-test/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -322,11 +322,6 @@
<artifactId>annotations</artifactId>
</dependency>

<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>

<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@
package org.zanata.feature.testharness;

import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
Expand All @@ -35,6 +31,9 @@
import org.zanata.util.EnsureLogoutRule;
import org.zanata.util.SampleProjectRule;

import java.time.Duration;
import java.time.Instant;

/**
* Global application of rules to Zanata functional tests
*
Expand Down Expand Up @@ -62,7 +61,7 @@ public class ZanataTestCase {
* public Timeout timeout = new Timeout(MAX_TEST_DURATION);
*/

public DateTime testFunctionStart;
public Instant testFunctionStart;

private String getTestDescription() {
return this.getClass().getCanonicalName()
Expand All @@ -73,24 +72,17 @@ private String getTestDescription() {
@Before
public void testEntry() {
log.info("Starting ".concat(getTestDescription()));
testFunctionStart = new DateTime();
testFunctionStart = Instant.now();
}

@After
public void testExit() {
Duration duration = new Duration(testFunctionStart, new DateTime());
PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
.appendLiteral("Finished "
.concat(getTestDescription()).concat(" in "))
.printZeroAlways()
.appendMinutes()
.appendSuffix(" minutes, ")
.appendSeconds()
.appendSuffix(" seconds, ")
.appendMillis()
.appendSuffix("ms")
.toFormatter();
log.info(periodFormatter.print(duration.toPeriod()));
Duration d = Duration.between(testFunctionStart, Instant.now());
String msg =
String.format("Finished %s in %d minutes, %d seconds, %dms",
getTestDescription(), d.toMinutes(), d.getSeconds(),
d.getNano() / 1000_000);
log.info(msg);
WebDriverFactory.INSTANCE.logLogs();
}

Expand Down
7 changes: 1 addition & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
<weld.se.version>${weld.version}</weld.se.version>
<guava.version>18.0</guava.version>
<gwt.version>2.6.1</gwt.version>
<icu4j.version>50.1.1</icu4j.version>
<icu4j.version>55.1</icu4j.version>
<lombok.source.dir>${project.build.sourceDirectory}/org/zanata</lombok.source.dir>
<lucene.version>3.6.2</lucene.version>
<org.mock-server.version>3.9.17</org.mock-server.version>
Expand Down Expand Up @@ -1228,11 +1228,6 @@
<version>1.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.fedorahosted.tennera</groupId>
<artifactId>jgettext</artifactId>
Expand Down
5 changes: 0 additions & 5 deletions zanata-model/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -293,11 +293,6 @@
<artifactId>validation-api</artifactId>
</dependency>

<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>

<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>annotations</artifactId>
Expand Down
17 changes: 17 additions & 0 deletions zanata-model/src/main/java/org/zanata/model/ModelEntityBase.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Date;

import javax.persistence.Column;
Expand All @@ -36,6 +38,7 @@
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.Version;

import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -94,6 +97,10 @@ public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}

@Transient
public Instant getCreationInstant() {
return creationDate.toInstant();
}

// TODO extract lastChanged from ModelEntityBase and use with @Embedded
// NB: also used in HSimpleComment
Expand All @@ -109,6 +116,16 @@ public void setLastChanged(Date lastChanged) {
this.lastChanged = lastChanged;
}

@Transient
public Instant getLastChangedInstant() {
return lastChanged.toInstant();
}

@Transient
public void setLastChangedInstant(Instant lastChanged) {
this.lastChanged = Date.from(lastChanged);
}

@Override
public int hashCode() {
final int prime = 31;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@

package org.zanata.model.tm;

import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Collections;
import java.util.Date;
import java.util.List;
Expand All @@ -36,8 +40,6 @@
import nu.xom.Elements;

import org.codehaus.jackson.map.ObjectMapper;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.zanata.util.TMXConstants;
import org.zanata.util.TMXParseException;

Expand All @@ -61,8 +63,8 @@ public class TMXMetadataHelper {
private static final String TMX_ELEMENT_CHILDREN =
"__TMX_ELEMENT_CHILDREN__";

private static final DateTimeFormatter ISO8601Z = DateTimeFormat
.forPattern("yyyyMMdd'T'HHmmss'Z").withZoneUTC();
private static final DateTimeFormatter ISO_FORMATTER = DateTimeFormatter
.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
private static final ObjectMapper jsonMapper = new ObjectMapper();

// TMX attributes which we store as fields (*not* in the generic metadata
Expand Down Expand Up @@ -295,13 +297,14 @@ private static void setGenericMetadata(HasTMMetadata toEntity,
@SuppressWarnings("null")
public static @Nonnull
Date toDate(String dateString) {
return ISO8601Z.parseDateTime(dateString).toDate();
TemporalAccessor temporalAccessor = ISO_FORMATTER.parse(dateString);
return Date.from(Instant.from(temporalAccessor));
}

@SuppressWarnings("null")
public static @Nonnull
String toString(Date date) {
return ISO8601Z.print(date.getTime());
return ISO_FORMATTER.format(date.toInstant());
}

private static Map<String, Object> buildMetadata(Element fromElem) {
Expand Down
10 changes: 0 additions & 10 deletions zanata-war/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2316,12 +2316,6 @@
<artifactId>deltaspike-jpa-module-impl</artifactId>
</dependency>

<dependency>
<groupId>org.ocpsoft.prettytime</groupId>
<artifactId>prettytime</artifactId>
<version>3.0.2.Final</version>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
Expand Down Expand Up @@ -2411,10 +2405,6 @@
<groupId>org.fedorahosted.tennera</groupId>
<artifactId>jgettext</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>com.beust</groupId>
<artifactId>jcommander</artifactId>
Expand Down
32 changes: 5 additions & 27 deletions zanata-war/src/main/java/org/zanata/action/ReindexAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
Expand All @@ -13,17 +14,13 @@
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.zanata.security.annotations.CheckLoggedIn;
import org.zanata.security.annotations.CheckPermission;
import org.zanata.security.annotations.CheckRole;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
import org.zanata.async.AsyncTaskHandle;
import org.zanata.security.annotations.ZanataSecured;
import org.zanata.service.SearchIndexManager;

import com.google.common.base.Optional;
import org.zanata.util.DateUtil;

@AutoCreate
@Name("reindexAction")
Expand Down Expand Up @@ -188,40 +185,21 @@ public boolean isCanceled() {
&& searchIndexManager.getProcessHandle().isCancelled();
}

// TODO move to common location with ViewAllStatusAction
private static final PeriodFormatter PERIOD_FORMATTER =
new PeriodFormatterBuilder().appendDays()
.appendSuffix(" day", " days").appendSeparator(", ")
.appendHours().appendSuffix(" hour", " hours")
.appendSeparator(", ").appendMinutes()
.appendSuffix(" min", " mins")
.toFormatter();

private String formatTimePeriod(long durationInMillis) {
Period period = new Period(durationInMillis);

if (period.toStandardMinutes().getMinutes() <= 0) {
return "less than a minute"; // TODO Localize
} else {
return PERIOD_FORMATTER.print(period.normalizedStandard());
}
}

public String getElapsedTime() {
AsyncTaskHandle<Void> processHandle = searchIndexManager.getProcessHandle();
if (processHandle == null) {
log.error("processHandle is null when looking up elapsed time");
return "";
} else {
long elapsedTime = processHandle.getExecutingTime();
return formatTimePeriod(elapsedTime);
Date start = new Date(processHandle.getStartTime());
return DateUtil.getHowLongAgoDescription(start);
}
}

public String getEstimatedTimeRemaining() {
Optional<Long> estimate = searchIndexManager.getProcessHandle().getEstimatedTimeRemaining();
if (estimate.isPresent()) {
return formatTimePeriod(estimate.get());
return DateUtil.getTimeRemainingDescription(estimate.get());
}
// TODO localize (not expecting to display estimate when it is unavailable anyway).
return "unknown";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
package org.zanata.dao;

import java.math.BigInteger;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
Expand All @@ -32,8 +34,6 @@
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.zanata.common.ContentState;
import org.zanata.model.HPerson;
import org.zanata.model.HTextFlowTarget;
Expand Down Expand Up @@ -71,8 +71,8 @@ public TextFlowTargetHistoryDAO(Session session) {
*
* @param versionId HProjectIteration identifier
* @param personId HPerson identifier
* @param from start of date range
* @param to end of date range
* @param fromDate start of date range
* @param toDate end of date range
*
* @return list of Object[wordCount][contentState][localeId]
*/
Expand Down Expand Up @@ -205,8 +205,8 @@ public boolean findConflictInHistory(HTextFlowTarget target,
*/
@NativeQuery(value = "need to use union", specificTo = "mysql due to usage of date() and convert_tz() functions.")
public <T> List<T> getUserTranslationMatrix(
HPerson user, DateTime fromDate, DateTime toDate,
Optional<DateTimeZone> userZoneOpt, DateTimeZone systemZone,
HPerson user, Instant fromDate, Instant toDate,
Optional<ZoneId> userZoneOpt, ZoneId systemZone,
ResultTransformer resultTransformer) {
// @formatter:off
String queryHistory = "select history.id, iter.id as iteration, tft.locale as locale, tf.wordCount as wordCount, history.state as state, history.lastChanged as lastChanged " +
Expand All @@ -228,8 +228,9 @@ public <T> List<T> getUserTranslationMatrix(
" and tft.last_modified_by_id = :user and (tft.translated_by_id is not null or tft.reviewed_by_id is not null)" +
" and tft.state <> :untranslated and tft.state <> :rejected and tft.automatedEntry =:automatedEntry";

// NB: we use the same timezones for the entire period
String convertedLastChanged = convertTimeZoneFunction("lastChanged",
userZoneOpt, systemZone);
userZoneOpt, systemZone, toDate);
// @formatter:on
String dateOfLastChanged = stripTimeFromDateTimeFunction(convertedLastChanged);
String queryString =
Expand All @@ -244,18 +245,19 @@ public <T> List<T> getUserTranslationMatrix(
.setInteger("untranslated", ContentState.New.ordinal())
.setInteger("rejected", ContentState.Rejected.ordinal())
.setBoolean("automatedEntry", false)
.setTimestamp("fromDate", fromDate.toDate())
.setTimestamp("toDate", toDate.toDate())
.setTimestamp("fromDate", Date.from(fromDate))
.setTimestamp("toDate", Date.from(toDate))
.setResultTransformer(resultTransformer);
return query.list();
}

@VisibleForTesting
protected String convertTimeZoneFunction(String columnName,
Optional<DateTimeZone> userZoneOpt, DateTimeZone systemZone) {
Optional<ZoneId> userZoneOpt,
ZoneId systemZone, Instant asAtTime) {
if (userZoneOpt.isPresent()) {
String userOffset = getOffsetAsString(userZoneOpt.get());
String systemOffset = getOffsetAsString(systemZone);
String userOffset = getOffsetAsString(userZoneOpt.get(), asAtTime);
String systemOffset = getOffsetAsString(systemZone, asAtTime);
return String.format("CONVERT_TZ(%s, '%s', '%s')", columnName, systemOffset, userOffset);
}
// no need to convert timezone
Expand All @@ -274,15 +276,16 @@ private <T> T loadById(Object object, Class<T> entityClass) {
((BigInteger) object).longValue());
}

private static String getOffsetAsString(DateTimeZone zone) {
int standardOffset = zone.getStandardOffset(0);
private static String getOffsetAsString(ZoneId zone, Instant asAtTime) {
int offsetSec = zone.getRules().getOffset(asAtTime).getTotalSeconds();
String prefix = "";
if (standardOffset < 0) {
if (offsetSec < 0) {
prefix = "-";
standardOffset = -standardOffset;
offsetSec = -offsetSec;
}
return String.format("%s%02d:00", prefix,
TimeUnit.MILLISECONDS.toHours(standardOffset));
int hours = (int) TimeUnit.SECONDS.toHours(offsetSec);
int min = (int) TimeUnit.SECONDS.toMinutes(offsetSec) % 60;
return String.format("%s%02d:%02d", prefix, hours, min);
}

}

0 comments on commit 7aa9fe7

Please sign in to comment.