Skip to content

Commit c668bef

Browse files
author
Marcel Overdijk
committed
Added getUnit method (issue ocpsoft#23)
1 parent 2b58558 commit c668bef

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

‎core/src/main/java/org/ocpsoft/prettytime/PrettyTime.java‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,26 @@ public List<TimeUnit> getUnits()
399399
return Collections.unmodifiableList(result);
400400
}
401401

402+
/**
403+
* Get the registered {@link TimeUnit} for the given {@link TimeUnit} type or null if none exists.
404+
*
405+
* @return
406+
*/
407+
@SuppressWarnings("unchecked")
408+
public <UNIT extends TimeUnit> UNIT getUnit(final Class<UNIT> unitType)
409+
{
410+
if (unitType == null)
411+
throw new IllegalArgumentException("Unit type to get must not be null.");
412+
413+
for (TimeUnit unit : units.keySet()) {
414+
if (unitType.isAssignableFrom(unit.getClass()))
415+
{
416+
return (UNIT) unit;
417+
}
418+
}
419+
return null;
420+
}
421+
402422
/**
403423
* Register the given {@link TimeUnit} and corresponding {@link TimeFormat} instance to be used in calculations. If
404424
* an entry already exists for the given {@link TimeUnit}, its format will be overwritten with the given

‎core/src/test/java/org/ocpsoft/prettytime/PrettyTimeAPIManipulationTest.java‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,14 @@
1515
*/
1616
package org.ocpsoft.prettytime;
1717

18+
import static org.junit.Assert.assertEquals;
19+
import static org.junit.Assert.assertNotNull;
20+
1821
import java.util.Date;
1922
import java.util.List;
2023

2124
import org.junit.Test;
25+
import org.ocpsoft.prettytime.units.JustNow;
2226

2327
public class PrettyTimeAPIManipulationTest
2428
{
@@ -123,4 +127,29 @@ public void testApiMisuse17() throws Exception
123127
t.removeUnit((TimeUnit) null);
124128
}
125129

130+
@Test(expected = IllegalArgumentException.class)
131+
public void testApiMisuse18() throws Exception
132+
{
133+
t.getUnit(null);
134+
}
135+
136+
@Test(expected = IllegalArgumentException.class)
137+
public void testApiMisuse19() throws Exception
138+
{
139+
t.getUnit((Class<TimeUnit>) null);
140+
}
141+
142+
@Test
143+
public void testGetUnit() {
144+
JustNow unit = t.getUnit(JustNow.class);
145+
assertNotNull(unit);
146+
}
147+
148+
@Test
149+
public void testChangeUnit() {
150+
JustNow unit = t.getUnit(JustNow.class);
151+
assertEquals(1000L * 60L * 5L, unit.getMaxQuantity());
152+
unit.setMaxQuantity(1);
153+
assertEquals(1, t.getUnit(JustNow.class).getMaxQuantity());
154+
}
126155
}

0 commit comments

Comments
 (0)