code
stringlengths
3
1.18M
language
stringclasses
1 value
/** * BeanMapTests * * @author Chris Pratt * * 11/11/2011 */ package com.anodyzed.onyx.bean; import com.anodyzed.onyx.log.LogBuilder; import com.anodyzed.onyx.log.sysout.SysOutLogFactory; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.EnumMap; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; public class BeanMapTests { /** * Setup the Test Harness */ @BeforeClass public static void setup () { LogBuilder.setLogFactory(new SysOutLogFactory()); } //setup /** * Perform a jUnit Test on the BeanMap get capability */ @Test public void testGet () { Date dob = new GregorianCalendar(1955,Calendar.APRIL,1).getTime(); Name name = new Name("John","Xavior","Doe"); Person person = new Person(42,name,dob,"john.doe@anonymous.org",true); List<Integer> list = new ArrayList<Integer>(); list.add(7); list.add(13); list.add(31); person.setList(list); Map<Position,Name> map = new EnumMap<Position,Name>(Position.class); map.put(Position.First,name); map.put(Position.Second,new Name("Jane","Xaviera","Doe")); person.setMap(map); Map<String,String> strings = new HashMap<String,String>(); strings.put("one","One"); strings.put("two","Two"); strings.put("three","Three"); person.setStrings(strings); Map<String,Object> personMap = new BeanMap(person); assertEquals(42,personMap.get("id")); assertEquals("John",personMap.get("name.firstname")); assertEquals("Doe",personMap.get("name.lastname")); assertEquals(dob,personMap.get("birthdate")); assertEquals("john.doe@anonymous.org",personMap.get("email")); assertTrue((Boolean)personMap.get("admin")); assertEquals(13,personMap.get("list[1]")); assertEquals("Jane",personMap.get("map[Second].firstname")); assertEquals("Two",personMap.get("strings[two]")); } //testGet /** * Perform a jUnit Test on the BeanMap put capability */ @Test public void testPut () { Date dob = new GregorianCalendar(1955,Calendar.APRIL,1).getTime(); Person person = new Person(); Map<String,Object> personMap = new BeanMap(person); personMap.put("id",42); personMap.put("name.firstname","John"); personMap.put("name.middlename","Xavior"); personMap.put("name.lastname","Doe"); personMap.put("birthdate",dob); personMap.put("email","john.doe@anonymous.org"); personMap.put("admin",true); personMap.put("list[0]",7); personMap.put("list[1]",13); personMap.put("map[Second].firstname","Jane"); personMap.put("map[Second].middlename","Xaviera"); personMap.put("map[Second].lastname","Doe"); personMap.put("strings[one]","One"); personMap.put("strings[two]","Two"); personMap.put("strings[three]","Three"); assertEquals(42,person.getId()); Name name = person.getName(); assertNotNull("Name",name); assertEquals("John",name.getFirstname()); assertEquals("Doe",name.getLastname()); assertEquals(dob,person.getBirthdate()); assertEquals("john.doe@anonymous.org",person.getEmail()); assertTrue(person.isAdmin()); assertEquals(13,person.getList().get(1).intValue()); assertEquals("Jane",person.getMap().get(Position.Second).getFirstname()); assertEquals("Two",person.getStrings().get("two")); } //testPut /** * jUnit 3.x Test Suite * * @return Adapted Test Suite */ public static junit.framework.Test suite () { return new junit.framework.JUnit4TestAdapter(BeanMapTests.class); } //suite } //*BeanMapTests enum Position { First, Second, Third; } /** * Name */ @SuppressWarnings("serial") class Name implements Serializable { private String firstname; private String lastname; private String middlename; /** * No-arg Bean Constructor */ public Name () { } //Name /** * Constructor * * @param firstname Given Name * @param middlename Alternate Name * @param lastname Surname */ public Name (String firstname,String middlename,String lastname) { this.firstname = firstname; this.middlename = middlename; this.lastname = lastname; } //Name /** * Get the value of the firstname attribute. * * @return The firstname value as a String */ public String getFirstname () { return firstname; } //getFirstname /** * Set the value of the firstname attribute. * * @param firstname The new firstname value as a String */ public void setFirstname (String firstname) { this.firstname = firstname; } //setFirstname /** * Get the value of the lastname attribute. * * @return The lastname value as a String */ public String getLastname () { return lastname; } //getLastname /** * Set the value of the lastname attribute. * * @param lastname The new lastname value as a String */ public void setLastname (String lastname) { this.lastname = lastname; } //setLastname /** * Get the value of the middlename attribute. * * @return The middlename value as a String */ public String getMiddlename () { return middlename; } //getMiddlename /** * Set the value of the middlename attribute. * * @param middlename The new middlename value as a String */ public void setMiddlename (String middlename) { this.middlename = middlename; } //setMiddlename } //*Name /** * Person */ @SuppressWarnings("serial") class Person implements Serializable { private int id; private Name name; private Date birthdate; private String email; private boolean admin; private List<Integer> list; private Map<Position,Name> map; private Map<String,String> strings; /** * No-arg Bean Constructor */ public Person () { list = new ArrayList<Integer>(); map = new EnumMap<Position,Name>(Position.class); strings = new HashMap<String,String>(); } //Person /** * Constructor * * @param id The Person Identifier * @param name The Person's Name * @param birthdate The Date of Birth * @param email The Person's Electronic Mail Address * @param admin true if the Person is an Administrator */ public Person (int id,Name name,Date birthdate,String email,boolean admin) { this(); this.id = id; this.name = name; this.birthdate = birthdate; this.email = email; this.admin = admin; } //Person /** * Get the value of the id attribute. * * @return The id value as a int */ public int getId () { return id; } //getId /** * Set the value of the id attribute. * * @param id The new id value as a int */ public void setId (int id) { this.id = id; } //setId /** * Get the value of the list attribute. * * @return The list value as a List<Integer> */ public List<Integer> getList () { return list; } //getList /** * Set the value of the list attribute. * * @param list The new list value as a List<Integer> */ public void setList (List<Integer> list) { this.list = list; } //setList /** * Get the value of the map attribute. * * @return The map value as a Map<Position,Long> */ public Map<Position,Name> getMap () { return map; } //getMap /** * Set the value of the map attribute. * * @param map The new map value as a Map<Position,Long> */ public void setMap (Map<Position,Name> map) { this.map = map; } //setMap /** * Get the value of the name attribute. * * @return The name value as a Name */ public Name getName () { return name; } //getName /** * Set the value of the name attribute. * * @param name The new name value as a Name */ public void setName (Name name) { this.name = name; } //setName /** * Get the value of the birthdate attribute. * * @return The birthdate value as a Date */ public Date getBirthdate () { return birthdate; } //getBirthdate /** * Set the value of the birthdate attribute. * * @param birthdate The new birthdate value as a Date */ public void setBirthdate (Date birthdate) { this.birthdate = birthdate; } //setBirthdate /** * Get the value of the email attribute. * * @return The email value as a String */ public String getEmail () { return email; } //getEmail /** * Set the value of the email attribute. * * @param email The new email value as a String */ public void setEmail (String email) { this.email = email; } //setEmail /** * Get the value of the admin attribute. * * @return The admin value as a boolean */ public boolean isAdmin () { return admin; } //isAdmin /** * Set the value of the admin attribute. * * @param admin The new admin value as a boolean */ public void setAdmin (boolean admin) { this.admin = admin; } //setAdmin /** * Get the value of the strings attribute. * * @return The strings value as a Map<String,String> */ public Map<String,String> getStrings () { return strings; } //getStrings /** * Set the value of the strings attribute. * * @param strings The new strings value as a Map<String,String> */ public void setStrings (Map<String,String> strings) { this.strings = strings; } //setStrings } //*Person
Java
/** * TextFormatTests * * @author Chris Pratt * * 9/1/2006 */ package com.anodyzed.onyx.text; import com.anodyzed.onyx.log.LogBuilder; import com.anodyzed.onyx.log.sysout.SysOutLogFactory; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; public class TextFormatTests { public static class TestData { public class Inner { public String getText () { return "inner"; } //getText } //*Inner public String getText () { return "outer"; } //getText public Object getInner () { return new Inner(); } //getInner public Date getDate () { return new GregorianCalendar(1965,Calendar.JUNE,18).getTime(); } //getDate public int getNum () { return 42; } //getNum public String getStr () { return "Test"; } //getStr } //*TestData public TestData data = new TestData(); /** * Setup the Test Harness */ @BeforeClass public static void setup () { LogBuilder.setLogFactory(new SysOutLogFactory()); } //setup /** * Perform a jUnit Test on the TextFormat Bean introspection capability */ @Test public void testBean () { assertEquals("Test the Bean.traversal = outer - inner",TextFormat.format("Test the Bean.traversal = {0.text} - {0.inner.text}",data)); assertEquals("Test the Bean.traversal = outer - inner",TextFormat.format("Test the Bean.traversal = {text} - {inner.text}",data)); } //testBean /** * Perform a jUnit Test on the TextFormat List Formatting capability */ @Test public void testList () { List<String> list = new ArrayList<String>(); list.add("one"); list.add("two"); list.add("three"); assertEquals("Test the Bean.size = 3",TextFormat.format("Test the Bean.size = {0.size}",list)); assertEquals("Test List CSV = [one,two,three]",TextFormat.format("Test List CSV = [{0,list,csv}]",list)); assertEquals("Test List Fixed = \"on00twothree \"",TextFormat.format("Test List Fixed = \"{0,list,2,-5,7}\"",list)); } //testList /** * Perform a jUnit Test on the TextFormat Number formatting capablility */ @Test public void testNumber () { assertEquals("Test the Int = 602,214,179,000,000,000,000,000",TextFormat.format("Test the Int = {0,number}",6.02214179E23)); assertEquals("Test the Integer = 843,215,975",TextFormat.format("Test the Integer = {0,number,integer}",843215975)); assertEquals("Test the Currency = $785,141,658.00",TextFormat.format("Test the Currency = {0,number,currency}",785141658)); assertEquals("Test the Percent = 2,300%",TextFormat.format("Test the Percent = {0,number,percent}",23)); assertEquals("Test the Pattern = (1,024.42)",TextFormat.format("Test the Pattern = {0,number,#,##0.00;(#,##0.00)}",-1024.42)); } //testNumber /** * Perform a jUnit Test on the TextFormat Fraction formatting capability */ @Test public void testFraction () { assertEquals("Test the Pattern = 1/2",TextFormat.format("Test the Pattern = {0,number,fraction}",0.5)); assertEquals("Test the Pattern = 1/3",TextFormat.format("Test the Pattern = {0,number,fraction}",1.0 / 3.0)); assertEquals("Test the Pattern = 2/3",TextFormat.format("Test the Pattern = {0,number,fraction}","4/6")); assertEquals("Test the Pattern = 1 1/2",TextFormat.format("Test the Pattern = {0,number,fraction}","1.5")); } //testFraction /** * Perform a jUnit Test on the TextFormat Date formatting capability */ @Test public void testDate () { Date d = new GregorianCalendar(1965,Calendar.JUNE,18).getTime(); assertEquals("Test the Date = 6/18/1965",TextFormat.format("Test the Date = {0,date,M/d/yyyy}",d)); assertEquals("Test the Date = Friday, June 18, 1965",TextFormat.format("Test the Date = {0,date,full}",d)); assertEquals("Test the Date = June 18, 1965",TextFormat.format("Test the Date = {0,date,long}",d)); assertEquals("Test the Date = Jun 18, 1965",TextFormat.format("Test the Date = {0,date,medium}",d)); assertEquals("Test the Date = 6/18/65",TextFormat.format("Test the Date = {0,date,short}",d)); assertEquals("Test the Date = 6/18/65 12:00 AM",TextFormat.format("Test the Date = {0,date}",d)); } //testDate /** * Perform a jUnit Test on the TextFormat Time formatting capability */ @Test public void testTime () { Date d = new GregorianCalendar(1980,Calendar.NOVEMBER,7,20,31,23).getTime(); assertEquals("Test the Time = 8:31 PM",TextFormat.format("Test the Time = {0,time,h:mm a}",d)); assertEquals("Test the Time = 8:31:23 PM PST",TextFormat.format("Test the Time = {0,time,full}",d)); assertEquals("Test the Time = 8:31:23 PM PST",TextFormat.format("Test the Time = {0,time,long}",d)); assertEquals("Test the Time = 8:31:23 PM",TextFormat.format("Test the Time = {0,time,medium}",d)); assertEquals("Test the Time = 8:31 PM",TextFormat.format("Test the Time = {0,time,short}",d)); assertEquals("Test the Time = 8:31:23 PM",TextFormat.format("Test the Time = {0,time}",d)); } //testTime /** * Perform a jUnit Test on the TextFormat Boolean formatting capability */ @Test public void testBoolean () { assertEquals("I think the answer is yup",TextFormat.format("I think the answer is {0,boolean,yup|nope}",true)); assertEquals("I'm pretty sure it's nope",TextFormat.format("I''m pretty sure it''s {0,boolean,yup|nope}","false")); } //testBoolean /** * Perform a jUnit Test on the TextFormat Map Data Access capability */ @Test public void testMap () { Map<String,Object> map = new HashMap<String,Object>(); map.put("bean",data); assertEquals("Test the Mapped String = Test",TextFormat.format("Test the Mapped String = {bean.str}",map)); assertEquals("Test the Mapped Number = 42",TextFormat.format("Test the Mapped Number = {bean.num,number}",map)); assertEquals("Test the Mapped Date = 6/18/1965",TextFormat.format("Test the Mapped Date = {bean.date,date,M/d/yyyy}",map)); } //testMap /** * Perform a jUnit Test on the TextFormat Choice Format capability */ @Test(expected=IllegalArgumentException.class) public void testChoice () { TextFormat choice = new TextFormat("The disk \"{1}\" contains {0,choice,0#no files|1#one file|1<{0,number,integer} files}."); assertEquals("The disk \"none.test\" contains no files.",choice.format(0,"none.test")); assertEquals("The disk \"one.test\" contains one file.",choice.format(1,"one.test")); assertEquals("The disk \"big.test\" contains 1,273 files.",choice.format(1273,"big.test")); TextFormat.format("This test should throw an IllegalArgumentException, {0,choice}",1); } //testChoice /** * Perform a jUnit Test on the TextFormat Substring Format capability */ @Test public void testSubstring () { assertEquals("Test first five characters of \"abcdefghij\" = \"abcde\"",TextFormat.format("Test first five characters of \"abcdefghij\" = \"{0,substring,0-5}\"","abcdefghij")); assertEquals("Test last five characters of \"abcdefghij\" = \"fghij\"",TextFormat.format("Test last five characters of \"abcdefghij\" = \"{0,substring,5}\"","abcdefghij")); assertEquals("Test middle five characters of \"abcdefghij\" = \"defgh\"",TextFormat.format("Test middle five characters of \"abcdefghij\" = \"{0,substring,3-8}\"","abcdefghij")); assertEquals("Test first three characters of \"a\" = \"a\"",TextFormat.format("Test first three characters of \"a\" = \"{0,substring,0..3}\"","a")); assertEquals("Test character 15 thru 17 of \"abcdefghij\" = \"\"",TextFormat.format("Test character 15 thru 17 of \"abcdefghij\" = \"{0,substring,15-17}\"","abcdefghij")); assertEquals("Test first two characters of 12345 = 12",TextFormat.format("Test first two characters of 12345 = {0,substring,0,2}",12345)); assertEquals("Test first two characters of outer.inner.text = \"in\"",TextFormat.format("Test first two characters of outer.inner.text = \"{0.inner.text,substring,0..2}\"",data)); } //testSubstring /** * Perform a jUnit Test on the TextFormat ability to Override Text Formatters */ @Test public void testFormatOverride () { assertEquals("Test that a null integer parameter defaults to null",TextFormat.format("Test that a null integer parameter defaults to {0,number,integer}",(Object)null)); TextFormat fmt = new TextFormat("Test that an overridden integer parameter returns {0,number,integer}"); fmt.addFormatter("number",ZeroNullNumberFormatter.class); assertEquals("Test that an overridden integer parameter returns 0",fmt.format((Object)null)); } //testFormatOverride /** * Perform a jUnit Test on the TextFormat subformat capability */ // @Test public void testSubformat () { // } //testSubformat /** * jUnit 3.x Test Suite * * @return Adapted Test Suite */ public static junit.framework.Test suite () { return new junit.framework.JUnit4TestAdapter(TextFormatTests.class); } //suite } //*TextFormatTests
Java
/** * SplayTreeMapTests * * @author Chris Pratt * * 12/11/2011 */ package com.anodyzed.onyx.util; import com.anodyzed.onyx.log.LogBuilder; import com.anodyzed.onyx.log.sysout.SysOutLogFactory; import java.util.Map; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; public class SplayTreeMapTests { /** * Setup the Test Harness */ @BeforeClass public static void setup () { LogBuilder.setLogFactory(new SysOutLogFactory()); } //setup /** * Perform a jUnit Test on the Splay Tree */ @Test public void testTree () { SplayTreeMap<Integer,Integer> t = new SplayTreeMap<Integer,Integer>(); final int NUMS = 40000; final int GAP = 307; System.out.println("Checking... (no bad output means success)"); for(int i = GAP;i != 0;i = (i + GAP) % NUMS) { t.put(i,i); } System.out.println("Inserts complete"); for(int i = 1;i < NUMS;i += 2) { t.remove(i); } System.out.println("Removes complete"); if((t.firstKey() != 2) || (t.lastKey() != NUMS - 2)) { fail("FindMin or FindMax error!"); } for(int i = 2;i < NUMS;i += 2) { if(t.find(i).getValue() != i) { fail("Error: find fails for " + i); } } for(int i = 1;i < NUMS;i += 2) { if(t.find(i) != null) { fail("Error: Found deleted item " + i); } } } //testTree /** * Perform a Standard Map Test */ @Test public void testStandardMap () { Map<String,Integer> map = new SplayTreeMap<String,Integer>(); map.put("Test",1); map.put("Test",2); map.put("Test",1); assertEquals(1,map.get("Test").intValue()); for(int i = 0; i < 100; i++) { map.put(String.valueOf(i),i); } assertEquals(101,map.size()); assertEquals(51,map.get("51").intValue()); int n = 0; for(String k : map.keySet()) { if(n < 100) { assertEquals(n++,Integer.parseInt(k)); } else { assertEquals("Test",k); } } } //testStandardMap /** * jUnit 3.x Test Suite * * @return Adapted Test Suite */ public static junit.framework.Test suite () { return new junit.framework.JUnit4TestAdapter(SplayTreeMapTests.class); } //suite } //*SplayTreeMapTests
Java
/** * ChronoTests * * @author Chris Pratt * * 9/1/2006 */ package com.anodyzed.onyx.util; import java.util.Calendar; import java.util.GregorianCalendar; import static org.junit.Assert.*; import org.junit.Test; public class ChronoTests { /** * Perform a jUnit Test on the Misc test(Date) routine */ @Test public void testClearTo () { Calendar cal = new GregorianCalendar(1964,Calendar.OCTOBER,10,06,20,42); assertEquals("Clear To Second Failed",new GregorianCalendar(1964,Calendar.OCTOBER,10,06,20,42),Chrono.clearTo(cal,Calendar.SECOND)); assertEquals("Clear To Minute Failed",new GregorianCalendar(1964,Calendar.OCTOBER,10,06,20,0),Chrono.clearTo(cal,Calendar.MINUTE)); assertEquals("Clear To Hour Failed",new GregorianCalendar(1964,Calendar.OCTOBER,10,06,0,0),Chrono.clearTo(cal,Calendar.HOUR)); assertEquals("Clear To Day Failed",new GregorianCalendar(1964,Calendar.OCTOBER,10,0,0,0),Chrono.clearTo(cal,Calendar.DATE)); assertEquals("Clear To Month Failed",new GregorianCalendar(1964,Calendar.OCTOBER,1,0,0,0),Chrono.clearTo(cal,Calendar.MONTH)); assertEquals("Clear To Year Failed",new GregorianCalendar(1964,Calendar.JANUARY,1,0,0,0),Chrono.clearTo(cal,Calendar.YEAR)); assertEquals("Clear To Era Failed",new GregorianCalendar(0,Calendar.JANUARY,1,0,0,0),Chrono.clearTo(cal,Calendar.ERA)); } //testClearTo } //*ChronoTests
Java
/** * Base64Tests * * @author Chris Pratt * * 12/18/2008 */ package com.anodyzed.onyx.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import static org.junit.Assert.*; import org.junit.Test; public class Base64Tests { private static final String testee = "The quick brown fox jumps over the lazy dog."; private static final String testicle = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4="; /** * Test tye Byte Array methods */ @Test public void testBytes () { String encoded = Base64.encode(testee.getBytes()); assertEquals(testicle,encoded); assertArrayEquals(testee.getBytes(),Base64.decode(encoded)); } //testBytes /** * Test the Character Stream based methods */ @Test public void testReader () throws IOException { StringWriter encoded = new StringWriter(); Base64.encode(new ByteArrayInputStream(testee.getBytes()),encoded); assertEquals(testicle,encoded.toString()); ByteArrayOutputStream decoded = new ByteArrayOutputStream(); Base64.decode(new StringReader(encoded.toString()),decoded); assertArrayEquals(testee.getBytes(),decoded.toByteArray()); } //testReader /** * Test the Character Array methods */ @Test public void testChars () { char[] encoded = Base64.encode(testee.toCharArray()); assertArrayEquals(testicle.toCharArray(),encoded); assertArrayEquals(testee.toCharArray(),Base64.decode(encoded)); } //testChars /** * Test the Byte Stream based methods */ @Test public void testStream () throws IOException { ByteArrayOutputStream encoded = new ByteArrayOutputStream(); Base64.encode(new ByteArrayInputStream(testee.getBytes()),encoded); assertArrayEquals(testicle.getBytes(),encoded.toByteArray()); ByteArrayOutputStream decoded = new ByteArrayOutputStream(); Base64.decode(new ByteArrayInputStream(encoded.toByteArray()),decoded); assertArrayEquals(testee.getBytes(),decoded.toByteArray()); } //testStream } //*Base64Tests
Java
/** * MiscTests * * @author Chris Pratt * * 9/1/2006 */ package com.anodyzed.onyx.util; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import static org.junit.Assert.*; import org.junit.Test; public class MiscTests { /** * Test the isNumeric method */ @Test public void testIsNumeric () { assertTrue(Misc.isNumeric("0")); assertTrue(Misc.isNumeric("1")); assertTrue(Misc.isNumeric("65535")); assertFalse(Misc.isNumeric("1534x")); assertFalse(Misc.isNumeric("this")); } //testIsNumeric /** * Test the isEmpty(String) method */ @Test public void testIsStringEmpty () { assertTrue(Misc.isEmpty((String)null)); assertTrue(Misc.isEmpty("")); assertTrue(Misc.isEmpty(" ")); assertFalse(Misc.isEmpty("empty")); } //testIsStringEmpty /** * Test the isEmpty(T[]) method */ @Test public void testIsArrayEmpty () { Object[] array = null; assertTrue(Misc.isEmpty(array)); array = new Object[0]; assertTrue(Misc.isEmpty(array)); array = new Object[1]; assertFalse(Misc.isEmpty(array)); } //testIsArrayEmpty /** * Test the isEmpty(Collection<?>) method */ @Test public void testIsCollectionEmpty () { Collection<Object> collection = null; assertTrue(Misc.isEmpty(collection)); collection = new ArrayList<Object>(); assertTrue(Misc.isEmpty(collection)); collection.add(new Object()); assertFalse(Misc.isEmpty(collection)); collection = new HashSet<Object>(); assertTrue(Misc.isEmpty(collection)); collection.add(new Object()); assertFalse(Misc.isEmpty(collection)); } //testIsCollectionEmpty /** * Test the isEmpty(Map<?,?>) method */ @Test public void testIsMapEmpty () { Map<String,Object> map = null; assertTrue(Misc.isEmpty(map)); map = new HashMap<String,Object>(); assertTrue(Misc.isEmpty(map)); map.put("new",new Object()); assertFalse(Misc.isEmpty(map)); } //testIsMapEmpty } //*MiscTests
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.demo.notepad1; import android.app.ListActivity; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.SimpleCursorAdapter; public class Notepadv1 extends ListActivity { public static final int INSERT_ID = Menu.FIRST; private int mNoteNumber = 1; private NotesDbAdapter mDbHelper; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.notepad_list); mDbHelper = new NotesDbAdapter(this); mDbHelper.open(); fillData(); } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); menu.add(0, INSERT_ID, 0, R.string.menu_insert); return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case INSERT_ID: createNote(); return true; } return super.onOptionsItemSelected(item); } private void createNote() { String noteName = "Note " + mNoteNumber++; mDbHelper.createNote(noteName, ""); fillData(); } private void fillData() { // Get all of the notes from the database and create the item list Cursor c = mDbHelper.fetchAllNotes(); startManagingCursor(c); String[] from = new String[] { NotesDbAdapter.KEY_TITLE }; int[] to = new int[] { R.id.text1 }; // Now create an array adapter and set it to display using our row SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to); setListAdapter(notes); } }
Java
package com.example.android.sherlockdemo; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ScrollView; import android.widget.TextView; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.app.SherlockListFragment; public class FragmentLayoutSupport extends SherlockFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_layout_support); } /** * This is a secondary activity, to show what the user has selected * when the screen is not large enough to show it all in one activity. */ public static class DetailsActivity extends SherlockFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // If the screen is now in landscape mode, we can show the // dialog in-line with the list so we don't need this activity. finish(); return; } if (savedInstanceState == null) { // During initial setup, plug in the details fragment. DetailsFragment details = new DetailsFragment(); details.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction().add( android.R.id.content, details).commit(); } } } /** * This is the "top-level" fragment, showing a list of items that the * user can pick. Upon picking an item, it takes care of displaying the * data to the user as appropriate based on the currrent UI layout. */ public static class TitlesFragment extends SherlockListFragment { boolean mDualPane; int mCurCheckPosition = 0; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Populate list with our static array of titles. setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.simple_list_item_checkable_1, android.R.id.text1, Shakespeare.TITLES)); // Check to see if we have a frame in which to embed the details // fragment directly in the containing UI. View detailsFrame = getActivity().findViewById(R.id.details); mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE; if (savedInstanceState != null) { // Restore last state for checked position. mCurCheckPosition = savedInstanceState.getInt("curChoice", 0); } if (mDualPane) { // In dual-pane mode, the list view highlights the selected item. getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); // Make sure our UI is in the correct state. showDetails(mCurCheckPosition); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("curChoice", mCurCheckPosition); } @Override public void onListItemClick(ListView l, View v, int position, long id) { showDetails(position); } /** * Helper function to show the details of a selected item, either by * displaying a fragment in-place in the current UI, or starting a * whole new activity in which it is displayed. */ void showDetails(int index) { mCurCheckPosition = index; if (mDualPane) { // We can display everything in-place with fragments, so update // the list to highlight the selected item and show the data. getListView().setItemChecked(index, true); // Check what fragment is currently shown, replace if needed. DetailsFragment details = (DetailsFragment) getFragmentManager().findFragmentById(R.id.details); if (details == null || details.getShownIndex() != index) { // Make new fragment to show this selection. details = DetailsFragment.newInstance(index); // Execute a transaction, replacing any existing fragment // with this one inside the frame. FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.details, details); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } } else { // Otherwise we need to launch a new activity to display // the dialog fragment with selected text. Intent intent = new Intent(); intent.setClass(getActivity(), DetailsActivity.class); intent.putExtra("index", index); startActivity(intent); } } } /** * This is the secondary fragment, displaying the details of a particular * item. */ public static class DetailsFragment extends SherlockFragment { /** * Create a new instance of DetailsFragment, initialized to * show the text at 'index'. */ public static DetailsFragment newInstance(int index) { DetailsFragment f = new DetailsFragment(); // Supply index input as an argument. Bundle args = new Bundle(); args.putInt("index", index); f.setArguments(args); return f; } public int getShownIndex() { return getArguments().getInt("index", 0); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (container == null) { // We have different layouts, and in one of them this // fragment's containing frame doesn't exist. The fragment // may still be created from its saved state, but there is // no reason to try to create its view hierarchy because it // won't be displayed. Note this is not needed -- we could // just run the code below, where we would create and return // the view hierarchy; it would just never be used. return null; } ScrollView scroller = new ScrollView(getActivity()); TextView text = new TextView(getActivity()); int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getActivity().getResources().getDisplayMetrics()); text.setPadding(padding, padding, padding, padding); scroller.addView(text); text.setText(Shakespeare.DIALOGUE[getShownIndex()]); return scroller; } } }
Java
package com.example.android.sherlockdemo; import android.accounts.Account; import android.accounts.AccountManager; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.BaseColumns; import android.provider.Contacts.People; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.SearchViewCompat; import android.support.v4.widget.SearchViewCompat.OnQueryTextListenerCompat; import android.support.v4.widget.SimpleCursorAdapter; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; @SuppressWarnings("deprecation") public class AccountListActivity extends SherlockFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentManager fm = getSupportFragmentManager(); // Create the list fragment and add it as our sole content. if (fm.findFragmentById(android.R.id.content) == null) { AccountListFragment list = new AccountListFragment(); fm.beginTransaction().add(android.R.id.content, list).commit(); } } public static class AccountListFragment extends SherlockListFragment { // This is the Adapter being used to display the list's data. SimpleCursorAdapter mAdapter; String[] mAccts = null; // If non-null, this is the current filter the user has provided. String mCurFilter; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Give some text to display if there is no data. In a real // application this would come from a resource. setEmptyText("No accounts"); // We have a menu item to show in action bar. setHasOptionsMenu(false); // Build list of accounts AccountManager am = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE); Account[]acs = am.getAccounts(); mAccts = new String[acs.length]; for(int i=0; i<acs.length; i++){ mAccts[i] = acs[i].name; } // Create an empty adapter we will use to display the loaded data. // Populate list with our static array of titles. setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.simple_list_item_checkable_1, android.R.id.text1, mAccts)); /* // Start out with a progress indicator. setListShown(false); // Prepare the loader. Either re-connect with an existing one, // or start a new one. getLoaderManager().initLoader(0, null, this); */ } @Override public void onListItemClick(ListView l, View v, int position, long id) { // Insert desired behavior here. Log.i("FragmentComplexList", "Item clicked: " + id); } /* // These are the Contacts rows that we will retrieve. // TODO: Replace People.DISPLAY_NAME with Account static final String[] ACCOUNTS_SUMMARY_PROJECTION = new String[] { BaseColumns._ID, People.DISPLAY_NAME, }; */ /* // TODO: Replace People ContentProvider with Account @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // This is called when a new Loader needs to be created. This // sample only has one Loader, so we don't care about the ID. // First, pick the base URI to use depending on whether we are // currently filtering. Uri baseUri; if (mCurFilter != null) { baseUri = Uri.withAppendedPath(People.CONTENT_FILTER_URI, Uri.encode(mCurFilter)); } else { baseUri = People.CONTENT_URI; } // Now create and return a CursorLoader that will take care of // creating a Cursor for the data being displayed. String select = "((" + People.DISPLAY_NAME + " NOTNULL) AND (" + People.DISPLAY_NAME + " != '' ))"; return new CursorLoader(getActivity(), baseUri, ACCOUNTS_SUMMARY_PROJECTION, select, null, People.DISPLAY_NAME + " COLLATE LOCALIZED ASC"); } */ /* @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) mAdapter.swapCursor(data); // The list should now be shown. if (isResumed()) { setListShown(true); } else { setListShownNoAnimation(true); } } */ /* @Override public void onLoaderReset(Loader<Cursor> loader) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. mAdapter.swapCursor(null); } */ } }
Java
package com.example.android.sherlockdemo; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; public class FragmentStackSupport extends SherlockFragmentActivity { int mStackLevel = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_stack); // Watch for button clicks. Button button = (Button)findViewById(R.id.new_fragment); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addFragmentToStack(); } }); button = (Button)findViewById(R.id.home); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // If there is a back stack, pop it all. FragmentManager fm = getSupportFragmentManager(); if (fm.getBackStackEntryCount() > 0) { fm.popBackStack(fm.getBackStackEntryAt(0).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE); } } }); if (savedInstanceState == null) { // Do first time initialization -- add initial fragment. SherlockFragment newFragment = CountingFragment.newInstance(mStackLevel); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.simple_fragment, newFragment).commit(); } else { mStackLevel = savedInstanceState.getInt("level"); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("level", mStackLevel); } void addFragmentToStack() { mStackLevel++; // Instantiate a new fragment. SherlockFragment newFragment = CountingFragment.newInstance(mStackLevel); // Add the fragment to the activity, pushing this transaction // on to the back stack. FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.simple_fragment, newFragment); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.addToBackStack(null); ft.commit(); } public static class CountingFragment extends SherlockFragment { int mNum; /** * Create a new instance of CountingFragment, providing "num" * as an argument. */ static CountingFragment newInstance(int num) { CountingFragment f = new CountingFragment(); // Supply num input as an argument. Bundle args = new Bundle(); args.putInt("num", num); f.setArguments(args); return f; } /** * When creating, retrieve this instance's number from its arguments. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNum = getArguments() != null ? getArguments().getInt("num") : 1; } /** * The Fragment's UI is just a simple text view showing its * instance number. */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.hello_world, container, false); View tv = v.findViewById(R.id.text); ((TextView)tv).setText("Fragment #" + mNum); tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb)); return v; } } }
Java
package com.example.android.sherlockdemo; import java.util.HashMap; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.BaseColumns; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.database.DatabaseUtilsCompat; import android.support.v4.widget.SimpleCursorAdapter; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.ListView; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; public class LoaderThrottleSupport extends SherlockFragmentActivity { // Debugging. static final String TAG = "LoaderThrottle"; /** * The authority we use to get to our sample provider. */ public static final String AUTHORITY = "com.example.android.sherlockdemo.LoaderThrottle"; /** * Definition of the contract for the main table of our provider. */ public static final class MainTable implements BaseColumns { // This class cannot be instantiated private MainTable() {} /** * The table name offered by this provider */ public static final String TABLE_NAME = "main"; /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/main"); /** * The content URI base for a single row of data. Callers must * append a numeric row id to this Uri to retrieve a row */ public static final Uri CONTENT_ID_URI_BASE = Uri.parse("content://" + AUTHORITY + "/main/"); /** * The MIME type of {@link #CONTENT_URI}. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.example.api-demos-throttle"; /** * The MIME type of a {@link #CONTENT_URI} sub-directory of a single row. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.example.api-demos-throttle"; /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = "data COLLATE LOCALIZED ASC"; /** * Column name for the single column holding our data. * <P>Type: TEXT</P> */ public static final String COLUMN_NAME_DATA = "data"; } /** * This class helps open, create, and upgrade the database file. */ static class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "loader_throttle.db"; private static final int DATABASE_VERSION = 2; DatabaseHelper(Context context) { // calls the super constructor, requesting the default cursor factory. super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * * Creates the underlying database with table name and column names taken from the * NotePad class. */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + MainTable.TABLE_NAME + " (" + MainTable._ID + " INTEGER PRIMARY KEY," + MainTable.COLUMN_NAME_DATA + " TEXT" + ");"); } /** * * Demonstrates that the provider must consider what happens when the * underlying datastore is changed. In this sample, the database is upgraded the database * by destroying the existing data. * A real application should upgrade the database in place. */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Logs that the database is being upgraded Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); // Kills the table and existing data db.execSQL("DROP TABLE IF EXISTS notes"); // Recreates the database with a new version onCreate(db); } } /** * A very simple implementation of a content provider. */ public static class SimpleProvider extends ContentProvider { // A projection map used to select columns from the database private final HashMap<String, String> mNotesProjectionMap; // Uri matcher to decode incoming URIs. private final UriMatcher mUriMatcher; // The incoming URI matches the main table URI pattern private static final int MAIN = 1; // The incoming URI matches the main table row ID URI pattern private static final int MAIN_ID = 2; // Handle to a new DatabaseHelper. private DatabaseHelper mOpenHelper; /** * Global provider initialization. */ public SimpleProvider() { // Create and initialize URI matcher. mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); mUriMatcher.addURI(AUTHORITY, MainTable.TABLE_NAME, MAIN); mUriMatcher.addURI(AUTHORITY, MainTable.TABLE_NAME + "/#", MAIN_ID); // Create and initialize projection map for all columns. This is // simply an identity mapping. mNotesProjectionMap = new HashMap<String, String>(); mNotesProjectionMap.put(MainTable._ID, MainTable._ID); mNotesProjectionMap.put(MainTable.COLUMN_NAME_DATA, MainTable.COLUMN_NAME_DATA); } /** * Perform provider creation. */ @Override public boolean onCreate() { mOpenHelper = new DatabaseHelper(getContext()); // Assumes that any failures will be reported by a thrown exception. return true; } /** * Handle incoming queries. */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Constructs a new query builder and sets its table name SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(MainTable.TABLE_NAME); switch (mUriMatcher.match(uri)) { case MAIN: // If the incoming URI is for main table. qb.setProjectionMap(mNotesProjectionMap); break; case MAIN_ID: // The incoming URI is for a single row. qb.setProjectionMap(mNotesProjectionMap); qb.appendWhere(MainTable._ID + "=?"); selectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs, new String[] { uri.getLastPathSegment() }); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } if (TextUtils.isEmpty(sortOrder)) { sortOrder = MainTable.DEFAULT_SORT_ORDER; } SQLiteDatabase db = mOpenHelper.getReadableDatabase(); Cursor c = qb.query(db, projection, selection, selectionArgs, null /* no group */, null /* no filter */, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } /** * Return the MIME type for an known URI in the provider. */ @Override public String getType(Uri uri) { switch (mUriMatcher.match(uri)) { case MAIN: return MainTable.CONTENT_TYPE; case MAIN_ID: return MainTable.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException("Unknown URI " + uri); } } /** * Handler inserting new data. */ @Override public Uri insert(Uri uri, ContentValues initialValues) { if (mUriMatcher.match(uri) != MAIN) { // Can only insert into to main URI. throw new IllegalArgumentException("Unknown URI " + uri); } ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } if (values.containsKey(MainTable.COLUMN_NAME_DATA) == false) { values.put(MainTable.COLUMN_NAME_DATA, ""); } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long rowId = db.insert(MainTable.TABLE_NAME, null, values); // If the insert succeeded, the row ID exists. if (rowId > 0) { Uri noteUri = ContentUris.withAppendedId(MainTable.CONTENT_ID_URI_BASE, rowId); getContext().getContentResolver().notifyChange(noteUri, null); return noteUri; } throw new SQLException("Failed to insert row into " + uri); } /** * Handle deleting data. */ @Override public int delete(Uri uri, String where, String[] whereArgs) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); String finalWhere; int count; switch (mUriMatcher.match(uri)) { case MAIN: // If URI is main table, delete uses incoming where clause and args. count = db.delete(MainTable.TABLE_NAME, where, whereArgs); break; // If the incoming URI matches a single note ID, does the delete based on the // incoming data, but modifies the where clause to restrict it to the // particular note ID. case MAIN_ID: // If URI is for a particular row ID, delete is based on incoming // data but modified to restrict to the given ID. finalWhere = DatabaseUtilsCompat.concatenateWhere( MainTable._ID + " = " + ContentUris.parseId(uri), where); count = db.delete(MainTable.TABLE_NAME, finalWhere, whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } /** * Handle updating data. */ @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count; String finalWhere; switch (mUriMatcher.match(uri)) { case MAIN: // If URI is main table, update uses incoming where clause and args. count = db.update(MainTable.TABLE_NAME, values, where, whereArgs); break; case MAIN_ID: // If URI is for a particular row ID, update is based on incoming // data but modified to restrict to the given ID. finalWhere = DatabaseUtilsCompat.concatenateWhere( MainTable._ID + " = " + ContentUris.parseId(uri), where); count = db.update(MainTable.TABLE_NAME, values, finalWhere, whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentManager fm = getSupportFragmentManager(); // Create the list fragment and add it as our sole content. if (fm.findFragmentById(android.R.id.content) == null) { ThrottledLoaderListFragment list = new ThrottledLoaderListFragment(); fm.beginTransaction().add(android.R.id.content, list).commit(); } } public static class ThrottledLoaderListFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> { // Menu identifiers static final int POPULATE_ID = Menu.FIRST; static final int CLEAR_ID = Menu.FIRST+1; // This is the Adapter being used to display the list's data. SimpleCursorAdapter mAdapter; // If non-null, this is the current filter the user has provided. String mCurFilter; // Task we have running to populate the database. AsyncTask<Void, Void, Void> mPopulatingTask; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setEmptyText("No data. Select 'Populate' to fill with data from Z to A at a rate of 4 per second."); setHasOptionsMenu(true); // Create an empty adapter we will use to display the loaded data. mAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1, null, new String[] { MainTable.COLUMN_NAME_DATA }, new int[] { android.R.id.text1 }, 0); setListAdapter(mAdapter); // Start out with a progress indicator. setListShown(false); // Prepare the loader. Either re-connect with an existing one, // or start a new one. getLoaderManager().initLoader(0, null, this); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { MenuItem populateItem = menu.add(Menu.NONE, POPULATE_ID, 0, "Populate"); populateItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); MenuItem clearItem = menu.add(Menu.NONE, CLEAR_ID, 0, "Clear"); clearItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } @Override public boolean onOptionsItemSelected(MenuItem item) { final ContentResolver cr = getActivity().getContentResolver(); switch (item.getItemId()) { case POPULATE_ID: if (mPopulatingTask != null) { mPopulatingTask.cancel(false); } mPopulatingTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { for (char c='Z'; c>='A'; c--) { if (isCancelled()) { break; } StringBuilder builder = new StringBuilder("Data "); builder.append(c); ContentValues values = new ContentValues(); values.put(MainTable.COLUMN_NAME_DATA, builder.toString()); cr.insert(MainTable.CONTENT_URI, values); // Wait a bit between each insert. try { Thread.sleep(250); } catch (InterruptedException e) { } } return null; } }; mPopulatingTask.execute((Void[]) null); return true; case CLEAR_ID: if (mPopulatingTask != null) { mPopulatingTask.cancel(false); mPopulatingTask = null; } AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { cr.delete(MainTable.CONTENT_URI, null, null); return null; } }; task.execute((Void[])null); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { // Insert desired behavior here. Log.i(TAG, "Item clicked: " + id); } // These are the rows that we will retrieve. static final String[] PROJECTION = new String[] { MainTable._ID, MainTable.COLUMN_NAME_DATA, }; @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { CursorLoader cl = new CursorLoader(getActivity(), MainTable.CONTENT_URI, PROJECTION, null, null, null); cl.setUpdateThrottle(2000); // update at most every 2 seconds. return cl; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mAdapter.swapCursor(data); // The list should now be shown. if (isResumed()) { setListShown(true); } else { setListShownNoAnimation(true); } } @Override public void onLoaderReset(Loader<Cursor> loader) { mAdapter.swapCursor(null); } } }
Java
package com.example.android.sherlockdemo; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.IntentCompat; import android.support.v4.content.Loader; import android.support.v4.content.pm.ActivityInfoCompat; import android.support.v4.widget.SearchViewCompat; import android.support.v4.widget.SearchViewCompat.OnQueryTextListenerCompat; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import java.io.File; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class LoaderCustomSupport extends SherlockFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentManager fm = getSupportFragmentManager(); // Create the list fragment and add it as our sole content. if (fm.findFragmentById(android.R.id.content) == null) { AppListFragment list = new AppListFragment(); fm.beginTransaction().add(android.R.id.content, list).commit(); } } /** * This class holds the per-item data in our Loader. */ public static class AppEntry { public AppEntry(AppListLoader loader, ApplicationInfo info) { mLoader = loader; mInfo = info; mApkFile = new File(info.sourceDir); } public ApplicationInfo getApplicationInfo() { return mInfo; } public String getLabel() { return mLabel; } public Drawable getIcon() { if (mIcon == null) { if (mApkFile.exists()) { mIcon = mInfo.loadIcon(mLoader.mPm); return mIcon; } else { mMounted = false; } } else if (!mMounted) { // If the app wasn't mounted but is now mounted, reload // its icon. if (mApkFile.exists()) { mMounted = true; mIcon = mInfo.loadIcon(mLoader.mPm); return mIcon; } } else { return mIcon; } return mLoader.getContext().getResources().getDrawable( android.R.drawable.sym_def_app_icon); } @Override public String toString() { return mLabel; } void loadLabel(Context context) { if (mLabel == null || !mMounted) { if (!mApkFile.exists()) { mMounted = false; mLabel = mInfo.packageName; } else { mMounted = true; CharSequence label = mInfo.loadLabel(context.getPackageManager()); mLabel = label != null ? label.toString() : mInfo.packageName; } } } private final AppListLoader mLoader; private final ApplicationInfo mInfo; private final File mApkFile; private String mLabel; private Drawable mIcon; private boolean mMounted; } /** * Perform alphabetical comparison of application entry objects. */ public static final Comparator<AppEntry> ALPHA_COMPARATOR = new Comparator<AppEntry>() { private final Collator sCollator = Collator.getInstance(); @Override public int compare(AppEntry object1, AppEntry object2) { return sCollator.compare(object1.getLabel(), object2.getLabel()); } }; /** * Helper for determining if the configuration has changed in an interesting * way so we need to rebuild the app list. */ public static class InterestingConfigChanges { final Configuration mLastConfiguration = new Configuration(); int mLastDensity; boolean applyNewConfig(Resources res) { int configChanges = mLastConfiguration.updateFrom(res.getConfiguration()); boolean densityChanged = mLastDensity != res.getDisplayMetrics().densityDpi; if (densityChanged || (configChanges&(ActivityInfo.CONFIG_LOCALE |ActivityInfoCompat.CONFIG_UI_MODE|ActivityInfo.CONFIG_SCREEN_LAYOUT)) != 0) { mLastDensity = res.getDisplayMetrics().densityDpi; return true; } return false; } } /** * Helper class to look for interesting changes to the installed apps * so that the loader can be updated. */ public static class PackageIntentReceiver extends BroadcastReceiver { final AppListLoader mLoader; public PackageIntentReceiver(AppListLoader loader) { mLoader = loader; IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addAction(Intent.ACTION_PACKAGE_CHANGED); filter.addDataScheme("package"); mLoader.getContext().registerReceiver(this, filter); // Register for events related to sdcard installation. IntentFilter sdFilter = new IntentFilter(); sdFilter.addAction(IntentCompat.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE); sdFilter.addAction(IntentCompat.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE); mLoader.getContext().registerReceiver(this, sdFilter); } @Override public void onReceive(Context context, Intent intent) { // Tell the loader about the change. mLoader.onContentChanged(); } } /** * A custom Loader that loads all of the installed applications. */ public static class AppListLoader extends AsyncTaskLoader<List<AppEntry>> { final InterestingConfigChanges mLastConfig = new InterestingConfigChanges(); final PackageManager mPm; List<AppEntry> mApps; PackageIntentReceiver mPackageObserver; public AppListLoader(Context context) { super(context); // Retrieve the package manager for later use; note we don't // use 'context' directly but instead the save global application // context returned by getContext(). mPm = getContext().getPackageManager(); } /** * This is where the bulk of our work is done. This function is * called in a background thread and should generate a new set of * data to be published by the loader. */ @Override public List<AppEntry> loadInBackground() { // Retrieve all known applications. List<ApplicationInfo> apps = mPm.getInstalledApplications( PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS); if (apps == null) { apps = new ArrayList<ApplicationInfo>(); } final Context context = getContext(); // Create corresponding array of entries and load their labels. List<AppEntry> entries = new ArrayList<AppEntry>(apps.size()); for (int i=0; i<apps.size(); i++) { AppEntry entry = new AppEntry(this, apps.get(i)); entry.loadLabel(context); entries.add(entry); } // Sort the list. Collections.sort(entries, ALPHA_COMPARATOR); // Done! return entries; } /** * Called when there is new data to deliver to the client. The * super class will take care of delivering it; the implementation * here just adds a little more logic. */ @Override public void deliverResult(List<AppEntry> apps) { if (isReset()) { // An async query came in while the loader is stopped. We // don't need the result. if (apps != null) { onReleaseResources(apps); } } List<AppEntry> oldApps = apps; mApps = apps; if (isStarted()) { // If the Loader is currently started, we can immediately // deliver its results. super.deliverResult(apps); } // At this point we can release the resources associated with // 'oldApps' if needed; now that the new result is delivered we // know that it is no longer in use. if (oldApps != null) { onReleaseResources(oldApps); } } /** * Handles a request to start the Loader. */ @Override protected void onStartLoading() { if (mApps != null) { // If we currently have a result available, deliver it // immediately. deliverResult(mApps); } // Start watching for changes in the app data. if (mPackageObserver == null) { mPackageObserver = new PackageIntentReceiver(this); } // Has something interesting in the configuration changed since we // last built the app list? boolean configChange = mLastConfig.applyNewConfig(getContext().getResources()); if (takeContentChanged() || mApps == null || configChange) { // If the data has changed since the last time it was loaded // or is not currently available, start a load. forceLoad(); } } /** * Handles a request to stop the Loader. */ @Override protected void onStopLoading() { // Attempt to cancel the current load task if possible. cancelLoad(); } /** * Handles a request to cancel a load. */ @Override public void onCanceled(List<AppEntry> apps) { super.onCanceled(apps); // At this point we can release the resources associated with 'apps' // if needed. onReleaseResources(apps); } /** * Handles a request to completely reset the Loader. */ @Override protected void onReset() { super.onReset(); // Ensure the loader is stopped onStopLoading(); // At this point we can release the resources associated with 'apps' // if needed. if (mApps != null) { onReleaseResources(mApps); mApps = null; } // Stop monitoring for changes. if (mPackageObserver != null) { getContext().unregisterReceiver(mPackageObserver); mPackageObserver = null; } } /** * Helper function to take care of releasing resources associated * with an actively loaded data set. */ protected void onReleaseResources(List<AppEntry> apps) { // For a simple List<> there is nothing to do. For something // like a Cursor, we would close it here. } } public static class AppListAdapter extends ArrayAdapter<AppEntry> { private final LayoutInflater mInflater; public AppListAdapter(Context context) { super(context, android.R.layout.simple_list_item_2); mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void setData(List<AppEntry> data) { clear(); if (data != null) { for (AppEntry appEntry : data) { add(appEntry); } } } /** * Populate new items in the list. */ @Override public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mInflater.inflate(R.layout.list_item_icon_text, parent, false); } else { view = convertView; } AppEntry item = getItem(position); ((ImageView)view.findViewById(R.id.icon)).setImageDrawable(item.getIcon()); ((TextView)view.findViewById(R.id.text)).setText(item.getLabel()); return view; } } public static class AppListFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<List<AppEntry>> { // This is the Adapter being used to display the list's data. AppListAdapter mAdapter; // If non-null, this is the current filter the user has provided. String mCurFilter; OnQueryTextListenerCompat mOnQueryTextListenerCompat; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Give some text to display if there is no data. In a real // application this would come from a resource. setEmptyText("No applications"); // We have a menu item to show in action bar. setHasOptionsMenu(true); // Create an empty adapter we will use to display the loaded data. mAdapter = new AppListAdapter(getActivity()); setListAdapter(mAdapter); // Start out with a progress indicator. setListShown(false); // Prepare the loader. Either re-connect with an existing one, // or start a new one. getLoaderManager().initLoader(0, null, this); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Place an action bar item for searching. MenuItem item = menu.add("Search"); item.setIcon(android.R.drawable.ic_menu_search); item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); View searchView = SearchViewCompat.newSearchView(getActivity()); if (searchView != null) { SearchViewCompat.setOnQueryTextListener(searchView, new OnQueryTextListenerCompat() { @Override public boolean onQueryTextChange(String newText) { // Called when the action bar search text has changed. Since this // is a simple array adapter, we can just have it do the filtering. mCurFilter = !TextUtils.isEmpty(newText) ? newText : null; mAdapter.getFilter().filter(mCurFilter); return true; } }); item.setActionView(searchView); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { // Insert desired behavior here. Log.i("LoaderCustom", "Item clicked: " + id); } @Override public Loader<List<AppEntry>> onCreateLoader(int id, Bundle args) { // This is called when a new Loader needs to be created. This // sample only has one Loader with no arguments, so it is simple. return new AppListLoader(getActivity()); } @Override public void onLoadFinished(Loader<List<AppEntry>> loader, List<AppEntry> data) { // Set the new data in the adapter. mAdapter.setData(data); // The list should now be shown. if (isResumed()) { setListShown(true); } else { setListShownNoAnimation(true); } } @Override public void onLoaderReset(Loader<List<AppEntry>> loader) { // Clear the data in the adapter. mAdapter.setData(null); } } }
Java
package com.example.android.sherlockdemo; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.FrameLayout; public class CheckableFrameLayout extends FrameLayout implements Checkable { private boolean mChecked; public CheckableFrameLayout(Context context) { super(context); } public CheckableFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void setChecked(boolean checked) { mChecked = checked; setBackgroundDrawable(checked ? new ColorDrawable(0xff0000a0) : null); } @Override public boolean isChecked() { return mChecked; } @Override public void toggle() { setChecked(!mChecked); } }
Java
package com.example.android.sherlockdemo; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.Contacts.People; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.SearchViewCompat; import android.support.v4.widget.SearchViewCompat.OnQueryTextListenerCompat; import android.support.v4.widget.SimpleCursorAdapter; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.ListView; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; @SuppressWarnings("deprecation") public class LoaderCursorSupport extends SherlockFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentManager fm = getSupportFragmentManager(); // Create the list fragment and add it as our sole content. if (fm.findFragmentById(android.R.id.content) == null) { CursorLoaderListFragment list = new CursorLoaderListFragment(); fm.beginTransaction().add(android.R.id.content, list).commit(); } } public static class CursorLoaderListFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> { // This is the Adapter being used to display the list's data. SimpleCursorAdapter mAdapter; // If non-null, this is the current filter the user has provided. String mCurFilter; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Give some text to display if there is no data. In a real // application this would come from a resource. setEmptyText("No phone numbers"); // We have a menu item to show in action bar. setHasOptionsMenu(true); // Create an empty adapter we will use to display the loaded data. mAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1, null, new String[] { People.DISPLAY_NAME }, new int[] { android.R.id.text1}, 0); setListAdapter(mAdapter); // Start out with a progress indicator. setListShown(false); // Prepare the loader. Either re-connect with an existing one, // or start a new one. getLoaderManager().initLoader(0, null, this); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Place an action bar item for searching. MenuItem item = menu.add("Search"); item.setIcon(android.R.drawable.ic_menu_search); item.setShowAsAction( MenuItem.SHOW_AS_ACTION_ALWAYS); View searchView = SearchViewCompat.newSearchView(getActivity()); if (searchView != null) { SearchViewCompat.setOnQueryTextListener(searchView, new OnQueryTextListenerCompat() { @Override public boolean onQueryTextChange(String newText) { // Called when the action bar search text has changed. Update // the search filter, and restart the loader to do a new query // with this filter. mCurFilter = !TextUtils.isEmpty(newText) ? newText : null; getLoaderManager().restartLoader(0, null, CursorLoaderListFragment.this); return true; } }); item.setActionView(searchView); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { // Insert desired behavior here. Log.i("FragmentComplexList", "Item clicked: " + id); } // These are the Contacts rows that we will retrieve. static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] { People._ID, People.DISPLAY_NAME, }; @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // This is called when a new Loader needs to be created. This // sample only has one Loader, so we don't care about the ID. // First, pick the base URI to use depending on whether we are // currently filtering. Uri baseUri; if (mCurFilter != null) { baseUri = Uri.withAppendedPath(People.CONTENT_FILTER_URI, Uri.encode(mCurFilter)); } else { baseUri = People.CONTENT_URI; } // Now create and return a CursorLoader that will take care of // creating a Cursor for the data being displayed. String select = "((" + People.DISPLAY_NAME + " NOTNULL) AND (" + People.DISPLAY_NAME + " != '' ))"; return new CursorLoader(getActivity(), baseUri, CONTACTS_SUMMARY_PROJECTION, select, null, People.DISPLAY_NAME + " COLLATE LOCALIZED ASC"); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) mAdapter.swapCursor(data); // The list should now be shown. if (isResumed()) { setListShown(true); } else { setListShownNoAnimation(true); } } @Override public void onLoaderReset(Loader<Cursor> loader) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. mAdapter.swapCursor(null); } } }
Java
package com.example.android.sherlockdemo; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.TabHost; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.Tab; import com.actionbarsherlock.app.SherlockFragmentActivity; import java.util.ArrayList; public class FragmentTabsPager extends SherlockFragmentActivity { ViewPager mViewPager; TabsAdapter mTabsAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_tabs_pager); mViewPager = (ViewPager)findViewById(R.id.pager); // This block thanks to http://stackoverflow.com/q/9790279/517561 ActionBar bar = getSupportActionBar(); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); bar.setDisplayShowTitleEnabled(true); bar.setDisplayShowHomeEnabled(true); // mTabsAdapter = new TabsAdapter(this, mViewPager); mTabsAdapter.addTab("simple", "Simple", FragmentStackSupport.CountingFragment.class, null); mTabsAdapter.addTab("accounts", "Accounts", AccountListActivity.AccountListFragment.class, null); mTabsAdapter.addTab("contacts", "Contacts", LoaderCursorSupport.CursorLoaderListFragment.class, null); mTabsAdapter.addTab("custom", "Custom", LoaderCustomSupport.AppListFragment.class, null); mTabsAdapter.addTab("throttle", "Throttle", LoaderThrottleSupport.ThrottledLoaderListFragment.class, null); } /** * This is a helper class that implements the management of tabs and all * details of connecting a ViewPager with associated TabHost. It relies on a * trick. Normally a tab host has a simple API for supplying a View or * Intent that each tab will show. This is not sufficient for switching * between pages. So instead we make the content part of the tab host * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy * view to show as the tab content. It listens to changes in tabs, and takes * care of switch to the correct paged in the ViewPager whenever the selected * tab changes. */ public static class TabsAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, ActionBar.TabListener { private final SherlockFragmentActivity mContext; private final ViewPager mViewPager; private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>(); static final class TabInfo { @SuppressWarnings("unused") private final String tag; private final Class<?> clss; private final Bundle args; TabInfo(String _tag, Class<?> _class, Bundle _args) { tag = _tag; clss = _class; args = _args; } } static class DummyTabFactory implements TabHost.TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } @Override public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) { super(activity.getSupportFragmentManager()); mContext = activity; mViewPager = pager; mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); } public void addTab(String tag, CharSequence label, Class<?> clss, Bundle args) { ActionBar.Tab tab = mContext.getSupportActionBar().newTab(); tab.setText(label); tab.setTabListener(this); mContext.getSupportActionBar().addTab(tab); TabInfo info = new TabInfo(tag, clss, args); mTabs.add(info); notifyDataSetChanged(); } @Override public int getCount() { return mTabs.size(); } @Override public Fragment getItem(int position) { TabInfo info = mTabs.get(position); return Fragment.instantiate(mContext, info.clss.getName(), info.args); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mContext.getSupportActionBar().setSelectedNavigationItem(position); } @Override public void onPageScrollStateChanged(int state) { } /* (non-Javadoc) * @see com.actionbarsherlock.app.ActionBar.TabListener#onTabSelected(com.actionbarsherlock.app.ActionBar.Tab, android.support.v4.app.FragmentTransaction) */ @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { mViewPager.setCurrentItem(mContext.getSupportActionBar().getSelectedNavigationIndex()); } /* (non-Javadoc) * @see com.actionbarsherlock.app.ActionBar.TabListener#onTabUnselected(com.actionbarsherlock.app.ActionBar.Tab, android.support.v4.app.FragmentTransaction) */ @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { } /* (non-Javadoc) * @see com.actionbarsherlock.app.ActionBar.TabListener#onTabReselected(com.actionbarsherlock.app.ActionBar.Tab, android.support.v4.app.FragmentTransaction) */ @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { } } }
Java
package com.example.android.sherlockdemo; public final class Shakespeare { /** * Our data, part 1. */ public static final String[] TITLES = { "Henry IV (1)", "Henry V", "Henry VIII", "Richard II", "Richard III", "Merchant of Venice", "Othello", "King Lear" }; /** * Our data, part 2. */ public static final String[] DIALOGUE = { "So shaken as we are, so wan with care," + "Find we a time for frighted peace to pant," + "And breathe short-winded accents of new broils" + "To be commenced in strands afar remote." + "No more the thirsty entrance of this soil" + "Shall daub her lips with her own children's blood;" + "Nor more shall trenching war channel her fields," + "Nor bruise her flowerets with the armed hoofs" + "Of hostile paces: those opposed eyes," + "Which, like the meteors of a troubled heaven," + "All of one nature, of one substance bred," + "Did lately meet in the intestine shock" + "And furious close of civil butchery" + "Shall now, in mutual well-beseeming ranks," + "March all one way and be no more opposed" + "Against acquaintance, kindred and allies:" + "The edge of war, like an ill-sheathed knife," + "No more shall cut his master. Therefore, friends," + "As far as to the sepulchre of Christ," + "Whose soldier now, under whose blessed cross" + "We are impressed and engaged to fight," + "Forthwith a power of English shall we levy;" + "Whose arms were moulded in their mothers' womb" + "To chase these pagans in those holy fields" + "Over whose acres walk'd those blessed feet" + "Which fourteen hundred years ago were nail'd" + "For our advantage on the bitter cross." + "But this our purpose now is twelve month old," + "And bootless 'tis to tell you we will go:" + "Therefore we meet not now. Then let me hear" + "Of you, my gentle cousin Westmoreland," + "What yesternight our council did decree" + "In forwarding this dear expedience.", "Hear him but reason in divinity," + "And all-admiring with an inward wish" + "You would desire the king were made a prelate:" + "Hear him debate of commonwealth affairs," + "You would say it hath been all in all his study:" + "List his discourse of war, and you shall hear" + "A fearful battle render'd you in music:" + "Turn him to any cause of policy," + "The Gordian knot of it he will unloose," + "Familiar as his garter: that, when he speaks," + "The air, a charter'd libertine, is still," + "And the mute wonder lurketh in men's ears," + "To steal his sweet and honey'd sentences;" + "So that the art and practic part of life" + "Must be the mistress to this theoric:" + "Which is a wonder how his grace should glean it," + "Since his addiction was to courses vain," + "His companies unletter'd, rude and shallow," + "His hours fill'd up with riots, banquets, sports," + "And never noted in him any study," + "Any retirement, any sequestration" + "From open haunts and popularity.", "I come no more to make you laugh: things now," + "That bear a weighty and a serious brow," + "Sad, high, and working, full of state and woe," + "Such noble scenes as draw the eye to flow," + "We now present. Those that can pity, here" + "May, if they think it well, let fall a tear;" + "The subject will deserve it. Such as give" + "Their money out of hope they may believe," + "May here find truth too. Those that come to see" + "Only a show or two, and so agree" + "The play may pass, if they be still and willing," + "I'll undertake may see away their shilling" + "Richly in two short hours. Only they" + "That come to hear a merry bawdy play," + "A noise of targets, or to see a fellow" + "In a long motley coat guarded with yellow," + "Will be deceived; for, gentle hearers, know," + "To rank our chosen truth with such a show" + "As fool and fight is, beside forfeiting" + "Our own brains, and the opinion that we bring," + "To make that only true we now intend," + "Will leave us never an understanding friend." + "Therefore, for goodness' sake, and as you are known" + "The first and happiest hearers of the town," + "Be sad, as we would make ye: think ye see" + "The very persons of our noble story" + "As they were living; think you see them great," + "And follow'd with the general throng and sweat" + "Of thousand friends; then in a moment, see" + "How soon this mightiness meets misery:" + "And, if you can be merry then, I'll say" + "A man may weep upon his wedding-day.", "First, heaven be the record to my speech!" + "In the devotion of a subject's love," + "Tendering the precious safety of my prince," + "And free from other misbegotten hate," + "Come I appellant to this princely presence." + "Now, Thomas Mowbray, do I turn to thee," + "And mark my greeting well; for what I speak" + "My body shall make good upon this earth," + "Or my divine soul answer it in heaven." + "Thou art a traitor and a miscreant," + "Too good to be so and too bad to live," + "Since the more fair and crystal is the sky," + "The uglier seem the clouds that in it fly." + "Once more, the more to aggravate the note," + "With a foul traitor's name stuff I thy throat;" + "And wish, so please my sovereign, ere I move," + "What my tongue speaks my right drawn sword may prove.", "Now is the winter of our discontent" + "Made glorious summer by this sun of York;" + "And all the clouds that lour'd upon our house" + "In the deep bosom of the ocean buried." + "Now are our brows bound with victorious wreaths;" + "Our bruised arms hung up for monuments;" + "Our stern alarums changed to merry meetings," + "Our dreadful marches to delightful measures." + "Grim-visaged war hath smooth'd his wrinkled front;" + "And now, instead of mounting barded steeds" + "To fright the souls of fearful adversaries," + "He capers nimbly in a lady's chamber" + "To the lascivious pleasing of a lute." + "But I, that am not shaped for sportive tricks," + "Nor made to court an amorous looking-glass;" + "I, that am rudely stamp'd, and want love's majesty" + "To strut before a wanton ambling nymph;" + "I, that am curtail'd of this fair proportion," + "Cheated of feature by dissembling nature," + "Deformed, unfinish'd, sent before my time" + "Into this breathing world, scarce half made up," + "And that so lamely and unfashionable" + "That dogs bark at me as I halt by them;" + "Why, I, in this weak piping time of peace," + "Have no delight to pass away the time," + "Unless to spy my shadow in the sun" + "And descant on mine own deformity:" + "And therefore, since I cannot prove a lover," + "To entertain these fair well-spoken days," + "I am determined to prove a villain" + "And hate the idle pleasures of these days." + "Plots have I laid, inductions dangerous," + "By drunken prophecies, libels and dreams," + "To set my brother Clarence and the king" + "In deadly hate the one against the other:" + "And if King Edward be as true and just" + "As I am subtle, false and treacherous," + "This day should Clarence closely be mew'd up," + "About a prophecy, which says that 'G'" + "Of Edward's heirs the murderer shall be." + "Dive, thoughts, down to my soul: here" + "Clarence comes.", "To bait fish withal: if it will feed nothing else," + "it will feed my revenge. He hath disgraced me, and" + "hindered me half a million; laughed at my losses," + "mocked at my gains, scorned my nation, thwarted my" + "bargains, cooled my friends, heated mine" + "enemies; and what's his reason? I am a Jew. Hath" + "not a Jew eyes? hath not a Jew hands, organs," + "dimensions, senses, affections, passions? fed with" + "the same food, hurt with the same weapons, subject" + "to the same diseases, healed by the same means," + "warmed and cooled by the same winter and summer, as" + "a Christian is? If you prick us, do we not bleed?" + "if you tickle us, do we not laugh? if you poison" + "us, do we not die? and if you wrong us, shall we not" + "revenge? If we are like you in the rest, we will" + "resemble you in that. If a Jew wrong a Christian," + "what is his humility? Revenge. If a Christian" + "wrong a Jew, what should his sufferance be by" + "Christian example? Why, revenge. The villany you" + "teach me, I will execute, and it shall go hard but I" + "will better the instruction.", "Virtue! a fig! 'tis in ourselves that we are thus" + "or thus. Our bodies are our gardens, to the which" + "our wills are gardeners: so that if we will plant" + "nettles, or sow lettuce, set hyssop and weed up" + "thyme, supply it with one gender of herbs, or" + "distract it with many, either to have it sterile" + "with idleness, or manured with industry, why, the" + "power and corrigible authority of this lies in our" + "wills. If the balance of our lives had not one" + "scale of reason to poise another of sensuality, the" + "blood and baseness of our natures would conduct us" + "to most preposterous conclusions: but we have" + "reason to cool our raging motions, our carnal" + "stings, our unbitted lusts, whereof I take this that" + "you call love to be a sect or scion.", "Blow, winds, and crack your cheeks! rage! blow!" + "You cataracts and hurricanoes, spout" + "Till you have drench'd our steeples, drown'd the cocks!" + "You sulphurous and thought-executing fires," + "Vaunt-couriers to oak-cleaving thunderbolts," + "Singe my white head! And thou, all-shaking thunder," + "Smite flat the thick rotundity o' the world!" + "Crack nature's moulds, an germens spill at once," + "That make ingrateful man!" }; }
Java
package com.example.android.sherlockdemo; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.actionbarsherlock.app.SherlockActivity; public class MainActivity extends SherlockActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void onClickFragmentLayout(View v) { Intent intent = new Intent(this, FragmentLayoutSupport.class); startActivity(intent); } public void onClickFragmentTabsPager(View v) { Intent intent = new Intent(this, FragmentTabsPager.class); startActivity(intent); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.jcas.tcas.Annotation_Type; /** * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class Sentence_Type extends Annotation_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (Sentence_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = Sentence_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new Sentence(addr, Sentence_Type.this); Sentence_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new Sentence(addr, Sentence_Type.this); } }; /** @generated */ public final static int typeIndexID = Sentence.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.Sentence"); /** initialize variables to correspond with Cas Type and Features * @generated */ public Sentence_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:12:19 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class Stem_Type extends Annotation_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (Stem_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = Stem_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new Stem(addr, Stem_Type.this); Stem_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new Stem(addr, Stem_Type.this); } }; /** @generated */ public final static int typeIndexID = Stem.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.Stem"); /** @generated */ final Feature casFeat_value; /** @generated */ final int casFeatCode_value; /** @generated */ public String getValue(int addr) { if (featOkTst && casFeat_value == null) jcas.throwFeatMissing("value", "de.tudarmstadt.ukp.dkpro.core.type.Stem"); return ll_cas.ll_getStringValue(addr, casFeatCode_value); } /** @generated */ public void setValue(int addr, String v) { if (featOkTst && casFeat_value == null) jcas.throwFeatMissing("value", "de.tudarmstadt.ukp.dkpro.core.type.Stem"); ll_cas.ll_setStringValue(addr, casFeatCode_value, v);} /** initialize variables to correspond with Cas Type and Features * @generated */ public Stem_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_value = jcas.getRequiredFeatureDE(casType, "value", "uima.cas.String", featOkTst); casFeatCode_value = (null == casFeat_value) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_value).getCode(); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type.pos; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import de.tudarmstadt.ukp.dkpro.core.type.POS_Type; /** Verb and verb phrase * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class V_Type extends POS_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (V_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = V_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new V(addr, V_Type.this); V_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new V(addr, V_Type.this); } }; /** @generated */ public final static int typeIndexID = V.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.pos.V"); /** initialize variables to correspond with Cas Type and Features * @generated */ public V_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type.pos; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import de.tudarmstadt.ukp.dkpro.core.type.POS_Type; /** Adverb * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class ADV_Type extends POS_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (ADV_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = ADV_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new ADV(addr, ADV_Type.this); ADV_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new ADV(addr, ADV_Type.this); } }; /** @generated */ public final static int typeIndexID = ADV.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.pos.ADV"); /** initialize variables to correspond with Cas Type and Features * @generated */ public ADV_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type.pos; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import de.tudarmstadt.ukp.dkpro.core.type.POS_Type; /** Exclamation * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class O_Type extends POS_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (O_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = O_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new O(addr, O_Type.this); O_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new O(addr, O_Type.this); } }; /** @generated */ public final static int typeIndexID = O.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.pos.O"); /** initialize variables to correspond with Cas Type and Features * @generated */ public O_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type.pos; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import de.tudarmstadt.ukp.dkpro.core.type.POS_Type; /** Pronoun * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class PR_Type extends POS_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (PR_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = PR_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new PR(addr, PR_Type.this); PR_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new PR(addr, PR_Type.this); } }; /** @generated */ public final static int typeIndexID = PR.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.pos.PR"); /** initialize variables to correspond with Cas Type and Features * @generated */ public PR_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type.pos; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import de.tudarmstadt.ukp.dkpro.core.type.POS_Type; /** Conjunction * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class CONJ_Type extends POS_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (CONJ_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = CONJ_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new CONJ(addr, CONJ_Type.this); CONJ_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new CONJ(addr, CONJ_Type.this); } }; /** @generated */ public final static int typeIndexID = CONJ.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.pos.CONJ"); /** initialize variables to correspond with Cas Type and Features * @generated */ public CONJ_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type.pos; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import de.tudarmstadt.ukp.dkpro.core.type.POS_Type; /** Article * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class ART_Type extends POS_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (ART_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = ART_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new ART(addr, ART_Type.this); ART_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new ART(addr, ART_Type.this); } }; /** @generated */ public final static int typeIndexID = ART.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.pos.ART"); /** initialize variables to correspond with Cas Type and Features * @generated */ public ART_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type.pos; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import de.tudarmstadt.ukp.dkpro.core.type.POS_Type; /** Punctuation * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class PUNC_Type extends POS_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (PUNC_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = PUNC_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new PUNC(addr, PUNC_Type.this); PUNC_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new PUNC(addr, PUNC_Type.this); } }; /** @generated */ public final static int typeIndexID = PUNC.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.pos.PUNC"); /** initialize variables to correspond with Cas Type and Features * @generated */ public PUNC_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type.pos; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import de.tudarmstadt.ukp.dkpro.core.type.POS_Type; /** Preposition * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class PP_Type extends POS_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (PP_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = PP_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new PP(addr, PP_Type.this); PP_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new PP(addr, PP_Type.this); } }; /** @generated */ public final static int typeIndexID = PP.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.pos.PP"); /** initialize variables to correspond with Cas Type and Features * @generated */ public PP_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type.pos; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import de.tudarmstadt.ukp.dkpro.core.type.POS_Type; /** Cardinal number * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class CARD_Type extends POS_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (CARD_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = CARD_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new CARD(addr, CARD_Type.this); CARD_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new CARD(addr, CARD_Type.this); } }; /** @generated */ public final static int typeIndexID = CARD.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.pos.CARD"); /** initialize variables to correspond with Cas Type and Features * @generated */ public CARD_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type.pos; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import de.tudarmstadt.ukp.dkpro.core.type.POS_Type; /** Noun * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class N_Type extends POS_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (N_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = N_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new N(addr, N_Type.this); N_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new N(addr, N_Type.this); } }; /** @generated */ public final static int typeIndexID = N.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.pos.N"); /** initialize variables to correspond with Cas Type and Features * @generated */ public N_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type.pos; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import de.tudarmstadt.ukp.dkpro.core.type.POS_Type; /** Adjective * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class ADJ_Type extends POS_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (ADJ_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = ADJ_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new ADJ(addr, ADJ_Type.this); ADJ_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new ADJ(addr, ADJ_Type.this); } }; /** @generated */ public final static int typeIndexID = ADJ.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.pos.ADJ"); /** initialize variables to correspond with Cas Type and Features * @generated */ public ADJ_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:10:48 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** The part of speech of a word or a phrase. * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class POS_Type extends Annotation_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (POS_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = POS_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new POS(addr, POS_Type.this); POS_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new POS(addr, POS_Type.this); } }; /** @generated */ public final static int typeIndexID = POS.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.POS"); /** @generated */ final Feature casFeat_value; /** @generated */ final int casFeatCode_value; /** @generated */ public String getValue(int addr) { if (featOkTst && casFeat_value == null) jcas.throwFeatMissing("value", "de.tudarmstadt.ukp.dkpro.core.type.POS"); return ll_cas.ll_getStringValue(addr, casFeatCode_value); } /** @generated */ public void setValue(int addr, String v) { if (featOkTst && casFeat_value == null) jcas.throwFeatMissing("value", "de.tudarmstadt.ukp.dkpro.core.type.POS"); ll_cas.ll_setStringValue(addr, casFeatCode_value, v);} /** initialize variables to correspond with Cas Type and Features * @generated */ public POS_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_value = jcas.getRequiredFeatureDE(casType, "value", "uima.cas.String", featOkTst); casFeatCode_value = (null == casFeat_value) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_value).getCode(); } }
Java
/* First created by JCasGen Mon May 02 14:11:32 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.jcas.tcas.Annotation_Type; /** * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class Token_Type extends Annotation_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (Token_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = Token_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new Token(addr, Token_Type.this); Token_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new Token(addr, Token_Type.this); } }; /** @generated */ public final static int typeIndexID = Token.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.Token"); /** initialize variables to correspond with Cas Type and Features * @generated */ public Token_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
Java
/* First created by JCasGen Mon May 02 14:12:52 CEST 2011 */ package de.tudarmstadt.ukp.dkpro.core.type; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** * Updated by JCasGen Mon May 02 14:13:32 CEST 2011 * @generated */ public class Lemma_Type extends Annotation_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (Lemma_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = Lemma_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new Lemma(addr, Lemma_Type.this); Lemma_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new Lemma(addr, Lemma_Type.this); } }; /** @generated */ public final static int typeIndexID = Lemma.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.tudarmstadt.ukp.dkpro.core.type.Lemma"); /** @generated */ final Feature casFeat_value; /** @generated */ final int casFeatCode_value; /** @generated */ public String getValue(int addr) { if (featOkTst && casFeat_value == null) jcas.throwFeatMissing("value", "de.tudarmstadt.ukp.dkpro.core.type.Lemma"); return ll_cas.ll_getStringValue(addr, casFeatCode_value); } /** @generated */ public void setValue(int addr, String v) { if (featOkTst && casFeat_value == null) jcas.throwFeatMissing("value", "de.tudarmstadt.ukp.dkpro.core.type.Lemma"); ll_cas.ll_setStringValue(addr, casFeatCode_value, v);} /** initialize variables to correspond with Cas Type and Features * @generated */ public Lemma_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_value = jcas.getRequiredFeatureDE(casType, "value", "uima.cas.String", featOkTst); casFeatCode_value = (null == casFeat_value) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_value).getCode(); } }
Java
/* * TempEval2Reader.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * author: Jannik Strötgen * email: stroetgen@uni-hd.de * * The TempEval2 Reader reads TempEval-2 corpora. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.uima.reader.tempeval2reader; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.collection.CollectionException; import org.apache.uima.collection.CollectionReader_ImplBase; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.util.Level; import org.apache.uima.util.Logger; import org.apache.uima.util.Progress; import org.apache.uima.util.ProgressImpl; import de.unihd.dbs.uima.types.heideltime.Dct; import de.unihd.dbs.uima.types.heideltime.Sentence; import de.unihd.dbs.uima.types.heideltime.Token; /** * CollectionReader for TempEval Data */ public class Tempeval2Reader extends CollectionReader_ImplBase { /** * Logger for this class */ private static Logger logger = null; /** * ComponentId */ private static final String compontent_id = "de.unihd.dbs.uima.reader.tempeval2reader"; /** * Parameter for files in the input directory */ public static final String FILE_BASE_SEGMENTATION = "base-segmentation.tab"; public static final String FILE_DCT = "dct.tab"; /** * Needed information to create cas objects for all "documents" */ public Integer numberOfDocuments = 0; /** * HashMap for all tokens of a document */ public HashMap<String, Token> hmToken = new HashMap<String, Token>(); /** * HashMap for all document creation times */ public HashMap<String, Dct> hmDct = new HashMap<String, Dct>(); /** * Name of configuration parameter that must be set to the path of a directory * containing input files. */ public static final String PARAM_INPUTDIR = "InputDirectory"; public static final String PARAM_CHARSET = "Charset"; public static final String PARAM_USE_SPACES = "UseSpacesAsSeparators"; /** * List containing all filenames of "documents" */ private List<String> filenames = new ArrayList<String>(); /** * Current file number */ private int currentIndex; /** * Parentheses are given as "-LRB-" ... reset to "(" ... */ Boolean resettingParentheses = true; /** * Check the TempEval counting beginning if "0" or "1" */ int newTokSentNumber = 0; /** * Charset to use for reading in files */ Charset charset = null; /** * Charset to use for reading in files */ Boolean USE_SPACES = true; /** * */ public void initialize() throws ResourceInitializationException { String charsetText = (String) getConfigParameterValue(PARAM_CHARSET); if(charsetText == null || charsetText.equals("")) charsetText = "UTF-8"; try { charset = Charset.forName(charsetText); } catch(Exception e) { System.err.println("["+compontent_id+"] Charset " + charsetText + " was not available to be used."); throw new ResourceInitializationException(); } Boolean useSpaces = (Boolean) getConfigParameterValue(PARAM_USE_SPACES); if(useSpaces != false) { USE_SPACES = true; } else { USE_SPACES = false; } // save doc names to list List<File> inputFiles = getFilesFromInputDirectory(); // get total document number and put all doc names into list "filenames" numberOfDocuments = getNumberOfDocuments(inputFiles); System.err.println("["+compontent_id+"] number of documents: "+numberOfDocuments); } public void getNext(CAS cas) throws IOException, CollectionException { // create jcas JCas jcas; try { jcas = cas.getJCas(); } catch (CASException e) { throw new CollectionException(e); } // clear HashMaps for new document hmToken.clear(); hmDct.clear(); // get current doc name String docname = filenames.get(currentIndex++); // save doc names to list List<File> inputFiles = getFilesFromInputDirectory(); // set documentText, sentences, tokens from file setTextSentencesTokens(docname, inputFiles, jcas); // set document creation time (dct) setDocumentCreationTime(docname, inputFiles, jcas); } /** * @see org.apache.uima.collection.CollectionReader#hasNext() */ public boolean hasNext() throws IOException, CollectionException { return currentIndex < numberOfDocuments; } /** * @see org.apache.uima.collection.base_cpm.BaseCollectionReader#getProgress() */ public Progress[] getProgress() { return new Progress[] { new ProgressImpl(currentIndex, numberOfDocuments, Progress.ENTITIES) }; } /** * @see org.apache.uima.collection.base_cpm.BaseCollectionReader#close() */ public void close() throws IOException { } public void setDocumentCreationTime(String docname, List<File> inputFiles, JCas jcas) throws IOException{ String documentCreationTime = ""; String directory = (String) getConfigParameterValue(PARAM_INPUTDIR); String filename = directory+"/"+FILE_DCT; for (File file : inputFiles) { if (file.getAbsolutePath().equals(filename)){ try { String line; BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)); while ((line = bf.readLine()) != null){ String[] parts = line.split("(\t)+"); String fileId = parts[0]; if (fileId.equals(docname)){ documentCreationTime = parts[1]; Dct dct = new Dct(jcas); String text = jcas.getDocumentText(); dct.setBegin(0); dct.setEnd(text.length()); dct.setFilename(fileId); dct.setValue(documentCreationTime); dct.setTimexId("t0"); dct.addToIndexes(); // add dct to HashMap hmDct.put("t0", dct); } } bf.close(); } catch (IOException e){ throw new IOException(e); } } } } public void setTextSentencesTokens(String docname, List<File> inputFiles, JCas jcas) throws IOException{ String text = ""; String sentString = ""; Integer positionCounter = 0; Integer sentId = -1; Integer lastSentId = -1; String directory = (String) getConfigParameterValue(PARAM_INPUTDIR); String filename = directory+"/"+FILE_BASE_SEGMENTATION; for (File file : inputFiles) { if (file.getAbsolutePath().equals(filename)){ try { String line; BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)); Boolean lastSentProcessed = false; Boolean firstSentProcessed = false; String fileId = ""; Boolean veryFirstLine = true; while ((line = bf.readLine()) != null){ // Check if TempEval counting starts with "0" or "1" if (veryFirstLine){ String[] parts = line.split("\t"); newTokSentNumber = Integer.parseInt(parts[1]); } veryFirstLine = false; String[] parts = line.split("\t"); fileId = parts[0]; sentId = Integer.parseInt(parts[1]); Integer tokId = Integer.parseInt(parts[2]); // Check for "empty tokens" (Italian corpus) String tokenString = ""; if (!(parts.length < 4)){ tokenString = parts[3]; } if (resettingParentheses == true){ tokenString = resetParentheses(tokenString); } if (fileId.equals(docname)){ // First Sentence, first Token if ((sentId == newTokSentNumber) && (tokId == newTokSentNumber)){ firstSentProcessed = true; text = tokenString; sentString = tokenString; positionCounter = addTokenAnnotation(tokenString, fileId, sentId, tokId, positionCounter, jcas); } // new Sentence, first Token else if ((tokId == newTokSentNumber) || (lastSentId != sentId)){ positionCounter = addSentenceAnnotation(sentString, fileId, sentId-1, positionCounter, jcas); if(!USE_SPACES) // in chinese, there are no spaces text = text + tokenString; else text = text + " " + tokenString; sentString = tokenString; positionCounter = addTokenAnnotation(tokenString, fileId, sentId, tokId, positionCounter, jcas); } // within any sentence else{ if(!USE_SPACES) { // in chinese, there are no spaces text = text + tokenString; sentString = sentString + tokenString; } else { text = text + " " + tokenString; sentString = sentString + " " + tokenString; } positionCounter = addTokenAnnotation(tokenString, fileId, sentId, tokId, positionCounter, jcas); } } else{ if ((firstSentProcessed) && (!(lastSentProcessed))){ positionCounter = addSentenceAnnotation(sentString, docname, lastSentId, positionCounter, jcas); lastSentProcessed = true; } } lastSentId = sentId; } if (fileId.equals(docname)){ positionCounter = addSentenceAnnotation(sentString, docname, lastSentId, positionCounter, jcas); } bf.close(); }catch (IOException e){ throw new IOException(e); } } } jcas.setDocumentText(text); } public String resetParentheses(String tokenString){ if (tokenString.equals("-LRB-")){ tokenString = tokenString.replace("-LRB-", "("); } else if (tokenString.equals("-RRB-")){ tokenString = tokenString.replace("-RRB-", ")"); } else if (tokenString.equals("-LSB-")){ tokenString = tokenString.replace("-LSB-","["); } else if (tokenString.equals("-RSB-")){ tokenString = tokenString.replace("-RSB-","]"); } else if (tokenString.equals("-LCB-")){ tokenString = tokenString.replace("-LCB-","{"); } else if (tokenString.equals("-RCB-")){ tokenString = tokenString.replace("-RCB-","}"); } // ITALIAN TEMPEVAL CORPUS PROBLEMS else if (tokenString.endsWith("a'")){ tokenString = tokenString.replaceFirst("a'", "à"); } else if (tokenString.endsWith("i'")){ tokenString = tokenString.replaceFirst("i'", "ì"); } else if (tokenString.endsWith("e'")){ tokenString = tokenString.replaceFirst("e'", "è"); } else if (tokenString.endsWith("u'")){ tokenString = tokenString.replaceFirst("u'", "ù"); } else if (tokenString.endsWith("o'")){ tokenString = tokenString.replaceFirst("o'", "ò"); } return tokenString; } public Integer addSentenceAnnotation(String sentenceString, String fileId, Integer sentId, Integer positionCounter, JCas jcas){ Sentence sentence = new Sentence(jcas); Integer begin = positionCounter - sentenceString.length(); sentence.setFilename(fileId); sentence.setSentenceId(sentId); sentence.setBegin(begin); sentence.setEnd(positionCounter); sentence.addToIndexes(); return positionCounter; } /** * Add token annotation to jcas * @param tokenString * @param fileId * @param tokId * @param positionCounter * @param jcas * @return */ public Integer addTokenAnnotation(String tokenString, String fileId, Integer sentId, Integer tokId, Integer positionCounter, JCas jcas){ Token token = new Token(jcas); if (!((sentId == newTokSentNumber) && (tokId == newTokSentNumber))){ if(USE_SPACES) // in chinese, there are no spaces, so the +1 correction is unnecessary positionCounter = positionCounter + 1; } token.setBegin(positionCounter); positionCounter = positionCounter + tokenString.length(); token.setEnd(positionCounter); token.setTokenId(tokId); token.setSentId(sentId); token.setFilename(fileId); token.addToIndexes(); String id = fileId+"_"+sentId+"_"+tokId; hmToken.put(id, token); return positionCounter; } /** * count the number of different "documents" and save doc names in filenames * @param inputFiles * @return * @throws ResourceInitializationException */ private Integer getNumberOfDocuments(List<File> inputFiles) throws ResourceInitializationException{ String directory = (String) getConfigParameterValue(PARAM_INPUTDIR); String filename = directory+"/"+FILE_BASE_SEGMENTATION; for (File file : inputFiles) { if (file.getAbsolutePath().equals(filename)){ try { String line; BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)); while ((line = bf.readLine()) != null){ String docName = (line.split("\t"))[0]; if (!(filenames.contains(docName))){ filenames.add(docName); } } bf.close(); } catch (IOException e) { throw new ResourceInitializationException(e); } } } int docCounter = filenames.size(); return docCounter; } private List<File> getFilesFromInputDirectory() { // get directory and save File directory = new File(((String) getConfigParameterValue(PARAM_INPUTDIR)).trim()); List<File> documentFiles = new ArrayList<File>(); // if input directory does not exist or is not a directory, throw exception if (!directory.exists() || !directory.isDirectory()) { logger.log(Level.WARNING, "getFilesFromInputDirectory() " + directory + " does not exist. Client has to set configuration parameter '" + PARAM_INPUTDIR + "'."); return null; } // get list of files (not subdirectories) in the specified directory File[] dirFiles = directory.listFiles(); for (int i = 0; i < dirFiles.length; i++) { if (!dirFiles[i].isDirectory()) { documentFiles.add(dirFiles[i]); } } return documentFiles; } }
Java
/* * Eventi2014Reader.java * * Copyright (c) 2014, Database Research Group, Institute of Computer Science, Heidelberg University. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * author: Jannik Strötgen * email: stroetgen@uni-hd.de * * The Eventi2014 Reader reads Eventi corpora. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.uima.reader.eventi2014reader; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.regex.MatchResult; import java.util.regex.Pattern; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.collection.CollectionException; import org.apache.uima.collection.CollectionReader_ImplBase; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.util.FileUtils; import org.apache.uima.util.Progress; import org.apache.uima.util.ProgressImpl; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; import de.unihd.dbs.uima.annotator.heideltime.utilities.Toolbox; import de.unihd.dbs.uima.types.heideltime.Dct; import de.unihd.dbs.uima.types.heideltime.Sentence; import de.unihd.dbs.uima.types.heideltime.Token; /** * CollectionReader for TempEval Data */ public class Eventi2014Reader extends CollectionReader_ImplBase { private Class<?> component = this.getClass(); // uima descriptor parameter name private String PARAM_INPUTDIR = "InputDirectory"; private Integer numberOfDocuments = 0; // For improving the formatting of the documentText // -> to not have a space between all the tokens // HashSet containing tokens in front of which no white space is added private HashSet<String> hsNoSpaceBefore = new HashSet<String>(); private HashSet<String> hsNoSpaceBehind = new HashSet<String>(); private Queue<File> files = new LinkedList<File>(); public void initialize() throws ResourceInitializationException { String dirPath = (String) getConfigParameterValue(PARAM_INPUTDIR); dirPath = dirPath.trim(); hsNoSpaceBefore.add("."); hsNoSpaceBefore.add(","); hsNoSpaceBefore.add(":"); hsNoSpaceBefore.add(";"); hsNoSpaceBefore.add("?"); hsNoSpaceBefore.add("!"); hsNoSpaceBefore.add(")"); hsNoSpaceBehind.add("("); populateFileList(dirPath); } public void getNext(CAS aCAS) throws IOException, CollectionException { JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new CollectionException(e); } fillJCas(jcas); // give an indicator that a file has been processed System.err.print("."); /*TODO:DEBUGGING FSIterator fsi = jcas.getAnnotationIndex(Token.type).iterator(); while(fsi.hasNext()) System.err.println("token: " + ((Token)fsi.next()).getTokenId()); */ } private void fillJCas(JCas jcas) throws IOException, CollectionException { // grab a file to process File f = files.poll(); String text = ""; String xml = FileUtils.file2String(f); String[] lines = xml.split("\n"); String fullDctTag = ""; String dct = ""; String filename = ""; String lastTok = ""; int sentBegin = 0; int sentEnd = -1; for (String line : lines) { // get document name if (line.startsWith("<Document doc_name=")){ Pattern paConstraint = Pattern.compile("<Document doc_name=\"(.*?)\">"); for (MatchResult mr : Toolbox.findMatches(paConstraint,line)) { filename = mr.group(1); } } // handle the tokens if (line.startsWith("<token")){ // get token text, token ID, token number, sentence number Pattern paConstraint = Pattern.compile("<token t_id=\"(.*?)\" sentence=\"(.*?)\" number=\"(.*?)\">(.*?)</token>"); for (MatchResult mr : Toolbox.findMatches(paConstraint,line)) { String token = mr.group(4); // System.err.println("INPUT: -->" + token + "<--"); int tokID = Integer.parseInt(mr.group(1)); int sentNum = Integer.parseInt(mr.group(2)); int tokNum = Integer.parseInt(mr.group(3)); // prepare token annotation int tokBegin; int tokEnd; // first token in sentence if (text.equals("")){ tokBegin = 0; tokEnd = token.length(); text = token; lastTok = token; } else{ // tokens without space before the tokens if (hsNoSpaceBefore.contains(token)){ tokBegin = text.length(); tokEnd = tokBegin + token.length(); text = text + token; lastTok = token; } // // empty tokens // else if (token.equals("")){ // tokBegin = text.length(); // tokEnd = tokBegin + token.length(); // text = text + token; // lastTok = token; // } else{ // tokens without space behind the tokens if (!(hsNoSpaceBehind.contains(lastTok))){ tokBegin = text.length()+ 1; text = text + " " + token; } // all other tokens else{ tokBegin = text.length(); text = text + token; } tokEnd = tokBegin + token.length(); lastTok = token; } } // check for new sentences if (tokNum == 0){ if (sentEnd >= 0){ // add sentence annotation, once a new sentence starts addSentenceAnnotation(jcas, sentBegin, sentEnd, filename); } sentBegin = tokBegin; } // add the token annotation addTokenAnnotation(jcas, tokBegin, tokEnd, tokID, filename, sentNum, tokNum); sentEnd = tokEnd; } } // get the document creation time if (line.startsWith("<TIMEX3")){ Pattern paConstraint = Pattern.compile("(<TIMEX3 .*? TAG_DESCRIPTOR=\"D[CP]T\" .*? value=\"(.*?)\".*?/>)"); for (MatchResult mr : Toolbox.findMatches(paConstraint,line)) { fullDctTag = mr.group(1); dct = mr.group(2); System.err.println("DCT: " + dct); } } } // add the very last sentence annotation addSentenceAnnotation(jcas, sentBegin, sentEnd, filename); jcas.setDocumentText(text); // add DCT to jcas if (!(dct.equals(""))){ Dct dctAnnotation = new Dct(jcas); dctAnnotation.setBegin(0); dctAnnotation.setEnd(text.length()); dctAnnotation.setFilename(filename + "---" + fullDctTag); dctAnnotation.setValue(dct); dctAnnotation.addToIndexes(); } } public void addSentenceAnnotation(JCas jcas, int begin, int end, String filename){ Sentence sentAnnotation = new Sentence(jcas); sentAnnotation.setBegin(begin); sentAnnotation.setEnd(end); sentAnnotation.setFilename(filename); sentAnnotation.addToIndexes(); } public void addTokenAnnotation(JCas jcas, int begin, int end, int tokID, String filename, int sentNum, int tokNum){ Token tokenAnnotation = new Token(jcas); tokenAnnotation.setBegin(begin); tokenAnnotation.setEnd(end); tokenAnnotation.setTokenId(tokID); tokenAnnotation.setFilename(filename + "---" + sentNum + "---" + tokNum); tokenAnnotation.addToIndexes(); } public boolean hasNext() throws IOException, CollectionException { return files.size() > 0; } public Progress[] getProgress() { return new Progress[] { new ProgressImpl(numberOfDocuments-files.size(), numberOfDocuments , Progress.ENTITIES) }; } public void close() throws IOException { files.clear(); } private void populateFileList(String dirPath) throws ResourceInitializationException { ArrayList<File> myFiles = new ArrayList<File>(); File dir = new File(dirPath); // check if the given directory path is valid if(!dir.exists() || !dir.isDirectory()) throw new ResourceInitializationException(); else myFiles.addAll(Arrays.asList(dir.listFiles())); // check for existence and readability; add handle to the list for(File f : myFiles) { if(!f.exists() || !f.isFile() || !f.canRead()) { Logger.printDetail(component, "File \""+f.getAbsolutePath()+"\" was ignored because it either didn't exist, wasn't a file or wasn't readable."); } else { files.add(f); } } numberOfDocuments = files.size(); } }
Java
/** * */ package de.unihd.dbs.uima.reader.tempeval3reader; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.collection.CollectionException; import org.apache.uima.collection.CollectionReader_ImplBase; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.util.Progress; import org.apache.uima.util.ProgressImpl; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; import de.unihd.dbs.uima.types.heideltime.Dct; /** * @author Julian Zell * */ public class Tempeval3Reader extends CollectionReader_ImplBase { private Class<?> component = this.getClass(); // uima descriptor parameter name private String PARAM_INPUTDIR = "InputDirectory"; private Integer numberOfDocuments = 0; private Queue<File> files = new LinkedList<File>(); public void initialize() throws ResourceInitializationException { String dirPath = (String) getConfigParameterValue(PARAM_INPUTDIR); dirPath = dirPath.trim(); populateFileList(dirPath); } public void getNext(CAS aCAS) throws IOException, CollectionException { JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new CollectionException(e); } fillJCas(jcas); // give an indicator that a file has been processed System.err.print("."); } private void fillJCas(JCas jcas) { // grab a file to process File f = files.poll(); try { // create xml parsing facilities DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // parse input xml file Document doc = db.parse(f); doc.getDocumentElement().normalize(); // get the <text> tag's content to set the document text NodeList nList = doc.getElementsByTagName("TEXT"); Node textNode = nList.item(0); String text = textNode.getTextContent(); jcas.setDocumentText(text); // get the <dct> timex tag's value attribute for the dct Boolean gotDCT = false; String dctText = null; try { nList = doc.getDocumentElement().getElementsByTagName("DCT"); nList = ((Element) nList.item(0)).getElementsByTagName("TIMEX3"); // timex3 tag Node dctTimex = nList.item(0); NamedNodeMap dctTimexAttr = dctTimex.getAttributes(); Node dctValue = dctTimexAttr.getNamedItem("value"); dctText = dctValue.getTextContent(); gotDCT = true; } catch(Exception e) { gotDCT = false; } if(!gotDCT) try { // try a different location for the DCT timex element nList = doc.getDocumentElement().getElementsByTagName("TEXT"); nList = ((Element) nList.item(0)).getElementsByTagName("TIMEX3"); // timex3 tag Node dctTimex = nList.item(0); NamedNodeMap dctTimexAttr = dctTimex.getAttributes(); if(dctTimexAttr.getNamedItem("functionInDocument") != null && dctTimexAttr.getNamedItem("functionInDocument").getTextContent().equals("CREATION_TIME")) { Node dctValue = dctTimexAttr.getNamedItem("value"); dctText = dctValue.getTextContent(); } gotDCT = true; } catch(Exception e) { gotDCT = false; } // get the document id nList = doc.getElementsByTagName("DOCID"); String filename = null; if(nList != null && nList.getLength() > 0) filename = nList.item(0).getTextContent(); else filename = f.getName().replaceAll("\\.[^\\.]+$", ""); Dct dct = new Dct(jcas); dct.setBegin(0); dct.setEnd(text.length()); dct.setFilename(filename); dct.setValue(dctText); dct.setTimexId("t0"); dct.addToIndexes(); } catch(Exception e) { e.printStackTrace(); Logger.printError(component, "File "+f.getAbsolutePath()+" could not be properly parsed."); } } public boolean hasNext() throws IOException, CollectionException { return files.size() > 0; } public Progress[] getProgress() { return new Progress[] { new ProgressImpl(numberOfDocuments-files.size(), numberOfDocuments , Progress.ENTITIES) }; } public void close() throws IOException { files.clear(); } private void populateFileList(String dirPath) throws ResourceInitializationException { ArrayList<File> myFiles = new ArrayList<File>(); File dir = new File(dirPath); // check if the given directory path is valid if(!dir.exists() || !dir.isDirectory()) throw new ResourceInitializationException(); else myFiles.addAll(Arrays.asList(dir.listFiles())); // check for existence and readability; add handle to the list for(File f : myFiles) { if(!f.exists() || !f.isFile() || !f.canRead()) { Logger.printDetail(component, "File \""+f.getAbsolutePath()+"\" was ignored because it either didn't exist, wasn't a file or wasn't readable."); } else { files.add(f); } } numberOfDocuments = files.size(); } }
Java
/* * ACETernReader.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * author: Jannik Strötgen * email: stroetgen@uni-hd.de * * ACE Tern Reader reads temporal annotated corpora that are in the ACE Tern style. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.uima.reader.aceternreader; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.collection.CollectionException; import org.apache.uima.collection.CollectionReader_ImplBase; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceConfigurationException; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.util.FileUtils; import org.apache.uima.util.Level; import org.apache.uima.util.Logger; import org.apache.uima.util.Progress; import org.apache.uima.util.ProgressImpl; import de.unihd.dbs.uima.types.heideltime.Dct; import de.unihd.dbs.uima.types.heideltime.SourceDocInfo; /** * CollectionReader for ACE Tern Data */ public class ACETernReader extends CollectionReader_ImplBase { private static Logger logger = null; private static final String compontent_id = "de.unihd.dbs.uima.reader.aceternreader"; /** * Needed information to create cas objects for all "documents" */ public Integer numberOfDocuments = 0; /** * Parameter information */ public static final String PARAM_INPUTDIR = "InputDirectory"; public static final String PARAM_DCT = "AnnotateCreationTime"; public Boolean annotateDCT = false; /** * List containing all filenames of "documents" */ private ArrayList<File> mFiles; /** * Current file number */ private int currentIndex; /** * @see org.apache.uima.collection.CollectionReader_ImplBase#initialize() */ public void initialize() throws ResourceInitializationException { logger = getUimaContext().getLogger(); logger.log(Level.INFO, "initialize() - Initializing ACETern-Reader..."); annotateDCT = (Boolean) getConfigParameterValue(PARAM_DCT); File directory = new File(((String) getConfigParameterValue(PARAM_INPUTDIR)).trim()); currentIndex = 0; // if input directory does not exist or is not a directory, throw exception if (!directory.exists() || !directory.isDirectory()) { throw new ResourceInitializationException(ResourceConfigurationException.DIRECTORY_NOT_FOUND, new Object[] { PARAM_INPUTDIR, this.getMetaData().getName(), directory.getPath() }); } // get list of files (without subdirectories) in the specified directory mFiles = new ArrayList<File>(); File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { if (!files[i].isDirectory()) { mFiles.add(files[i]); } } } /** * @see org.apache.uima.collection.CollectionReader#hasNext() */ public boolean hasNext() { return currentIndex < mFiles.size(); } /** * @see org.apache.uima.collection.CollectionReader#getNext(org.apache.uima.cas.CAS) */ public void getNext(CAS aCAS) throws IOException, CollectionException { System.err.print("."); JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new CollectionException(e); } // open input stream to file File file = (File) mFiles.get(currentIndex++); logger.log(Level.INFO, "getNext(CAS) - Reading file " + file.getName()); String text = ""; String xml = FileUtils.file2String(file); text = xml; // put document into CAS text = text.replaceAll("(?s)<QUOTE PREVIOUSPOST=.*?/>", ""); jcas.setDocumentText(text); // Keep Source document information SourceDocInfo srcDocInfo = new SourceDocInfo(jcas); URL url = file.getAbsoluteFile().toURI().toURL(); srcDocInfo.setUri(url.toString()); srcDocInfo.addToIndexes(); // Get document creation time if necessary if (annotateDCT){ /* * if DCT shall be set, set it now */ setDCT(xml, jcas, url.toString()); } } @SuppressWarnings("unused") public void setDCT(String xml, JCas jcas, String filename){ // SET DOCUMENT CREATION TIME!!!! // possible tags for DCT: // DATETIME (all WikiWar documents) with the following format 2009-12-20T17:00:00 // DATE_TIME (Tern 2004) with the following format "10/17/2000 18:46:13.59" "10/17/2000 18:41:01.17" "11/04/2000 9:14:43.41" "2000-10-01 20:56:35" // DATE (Tern 2004) with the following format "07/15/2000" "1996-02-13" "1997-03-09 10:50:59" // WITHOUT DATE ARE THE ACE TERN 2004 training files: chtb_171.eng.sgm, 172, 174, 179, 183, // DATETIME (ACE 2005 training) with the following formats additionally: 20041221-20:24:00, 20030422 String datetimetag = null; // possible date formats String dateformat1 = "(.*?)(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)(T| )(\\d\\d):(\\d\\d):(\\d\\d)(.*?)"; // 2009-12-20T17:00:00 or 2000-10-01 20:56:35 String dateformat2 = "(.*?)(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)(T| )(\\d):(\\d\\d):(\\d\\d)(.*?)"; // 2009-12-20T7:00:00 or 2000-10-01 9:56:35 String dateformat3 = "(.*?)(\\d\\d)/(\\d\\d)/(\\d\\d\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d)\\.(\\d\\d)(.*?)"; // 10/17/2000 18:46:13.59 String dateformat4 = "(.*?)(\\d\\d)/(\\d\\d)/(\\d\\d\\d\\d) (\\d):(\\d\\d):(\\d\\d)\\.(\\d\\d)(.*?)"; // 10/17/2000 1:46:13.59 String dateformat5 = "(.*?)(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)(.*?)"; // 1996-02-13 String dateformat6 = "(.*?)(\\d\\d)/(\\d\\d)/(\\d\\d\\d\\d)(.*?)"; // 07/15/2000 String dateformat7 = "(.*?)(January|February|March|April|May|June|July|August|September|October|November|December) ([\\d]?[\\d]),? (\\d\\d\\d\\d)(.*?)"; String dateformat8 = "(.*?)(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)-(\\d\\d):(\\d\\d):(\\d\\d)(.*?)"; // 20041221-20:24:00 String dateformat9 = "(.*?)(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)(.*?)"; // 20030422 for (MatchResult m : findMatches(Pattern.compile("(<DATETIME>|<DATE_TIME>|<DATE>|<STORY_REF_TIME>)(("+dateformat1+ ")|("+dateformat2+ ")|("+dateformat3+ ")|("+dateformat4+ ")|("+dateformat5+ ")|("+dateformat6+ ")|("+dateformat7+ ")|("+dateformat8+ ")|("+dateformat9+")(</DATETIME>|</DATE_TIME>|</DATE>|</STORY_REF_TIME>))"), xml)){ datetimetag = m.group(2); } String time_value = null; String date_value = null; if (!(datetimetag == null)){ if (datetimetag.matches(dateformat1)){ for (MatchResult m : findMatches(Pattern.compile(dateformat1), datetimetag)){ date_value = m.group(2)+"-"+m.group(3)+"-"+m.group(4); time_value = m.group(2)+"-"+m.group(3)+"-"+m.group(4)+"T"+m.group(6)+":"+m.group(7)+":"+m.group(8); } } else if (datetimetag.matches(dateformat2)){ for (MatchResult m : findMatches(Pattern.compile(dateformat2), datetimetag)){ date_value = m.group(2)+"-"+m.group(3)+"-"+m.group(4); time_value = m.group(2)+"-"+m.group(3)+"-"+m.group(4)+"T0"+m.group(6)+":"+m.group(7)+":"+m.group(8); } } else if (datetimetag.matches(dateformat3)){ for (MatchResult m : findMatches(Pattern.compile(dateformat3), datetimetag)){ date_value = m.group(4)+"-"+m.group(2)+"-"+m.group(3); time_value = m.group(4)+"-"+m.group(2)+"-"+m.group(3)+"T"+m.group(5)+":"+m.group(6)+":"+m.group(7)+"."+m.group(8); } } else if (datetimetag.matches(dateformat4)){ for (MatchResult m : findMatches(Pattern.compile(dateformat4), datetimetag)){ date_value = m.group(4)+"-"+m.group(2)+"-"+m.group(3); time_value = m.group(4)+"-"+m.group(2)+"-"+m.group(3)+"T0"+m.group(5)+":"+m.group(6)+":"+m.group(7)+"."+m.group(8); } } else if (datetimetag.matches(dateformat5)){ for (MatchResult m : findMatches(Pattern.compile(dateformat5), datetimetag)){ date_value = m.group(2)+"-"+m.group(3)+"-"+m.group(4); } } else if (datetimetag.matches(dateformat6)){ for (MatchResult m : findMatches(Pattern.compile(dateformat6), datetimetag)){ date_value = m.group(4)+"-"+m.group(2)+"-"+m.group(3); } } else if (datetimetag.matches(dateformat7)){ for (MatchResult m : findMatches(Pattern.compile(dateformat7), datetimetag)){ String year = m.group(4); String month = normMonth(m.group(2)); String day = normDay(m.group(3)); date_value = year+"-"+month+"-"+day; } } else if (datetimetag.matches(dateformat8)){ for (MatchResult m : findMatches(Pattern.compile(dateformat8), datetimetag)){ date_value = m.group(2)+"-"+m.group(3)+"-"+m.group(4); time_value = m.group(2)+"-"+m.group(3)+"-"+m.group(4)+"T"+m.group(5)+":"+m.group(6)+":"+m.group(7); } } else if (datetimetag.matches(dateformat9)){ for (MatchResult m : findMatches(Pattern.compile(dateformat9), datetimetag)){ date_value = m.group(2)+"-"+m.group(3)+"-"+m.group(4); } } else{ System.err.println(); System.err.println("["+compontent_id+"] cannot set dct with datetimetag: "+datetimetag); } if (!(date_value == null)){ Dct dct = new Dct(jcas); dct.setBegin(0); dct.setEnd(1); dct.setFilename(filename); dct.setTimexId("dct"); if (!(time_value == null)){ dct.setValue(time_value); // System.err.println("["+compontent_id+"] set dct to: "+time_value); }else if (!(date_value == null)){ dct.setValue(date_value); // System.err.println("["+compontent_id+"] set dct to: "+date_value); } else{ System.err.println(); System.err.println("["+compontent_id+"] something wrong with setting DCT of : "+datetimetag); } dct.addToIndexes(); } } else{ if (date_value == null){ // System.err.println("Checking for further formats of DCT..."); String refYear = ""; String refMonth = ""; String refDay = ""; for (MatchResult m1 : findMatches(Pattern.compile("DATE:[\\s]+("+dateformat7+")"),xml)){ String referenceDate = m1.group(1); if (referenceDate.matches(dateformat7)){ for (MatchResult mr : findMatches(Pattern.compile(dateformat7), referenceDate)){ refYear = mr.group(4); refMonth = normMonth(mr.group(2)); refDay = normDay(mr.group(3)); } } } for (MatchResult m : findMatches(Pattern.compile("<STORY_REF_TIME>" +"(Jan\\.|Feb\\.|Mar\\.|Apr\\.|May\\.|Jun\\.|Jul\\.|Aug\\.|Sep\\.|Oct\\.|Nov\\.|Dec\\.|" + "JAN\\.|FEB\\.|MAR\\.|APR\\.|MAY\\.|JUN\\.|JUL\\.|AUG\\.|SEP\\.|OCT\\.|NOV\\.|DEC\\.)[\\s]+([\\d]?[\\d])" +"</STORY_REF_TIME>"), xml)){ String exactMonth = m.group(1); String exactDay = m.group(2); date_value = refYear+"-"+normMonth(exactMonth)+"-"+normDay(exactDay); } } if (date_value == null){ for (MatchResult m : findMatches(Pattern.compile("<STORY_REF_TIME>" +".*?(\\d\\d\\d\\d)(\\d\\d)(\\d\\d).*?" +"</STORY_REF_TIME>"), xml)){ String exactYear = m.group(1); String exactMonth = m.group(2); String exactDay = m.group(3); date_value = exactYear+"-"+exactMonth+"-"+exactDay; } } if (date_value == null){ String refYear = ""; String refMonth = ""; String refDay = ""; for (MatchResult m : findMatches(Pattern.compile("<DOCNO>.*?(\\d\\d\\d\\d)(\\d\\d)(\\d\\d).*?</DOCNO>"),xml)){ refYear = m.group(1); refMonth = normMonth(m.group(2)); refDay = normDay(m.group(3)); } if (!(refYear.matches(""))){ for (MatchResult m : findMatches(Pattern.compile("<STORY_REF_TIME>.*?" +"(January|February|March|April|May|June|July|August|September|October|November|December) ([\\d]?[\\d]).*?"+ "</STORY_REF_TIME>"), xml)){ String exactMonth = normMonth(m.group(1)); String exactDay = normDay(m.group(2)); date_value = refYear+"-"+exactMonth+"-"+exactDay; } } } if (date_value == null){ String refYear = ""; String refMonth = ""; String refDay = ""; for (MatchResult m : findMatches(Pattern.compile("Publish Date:[\\s]+(\\d\\d)/(\\d\\d)/(\\d\\d)"),xml)){ refYear = "19"+m.group(3); refMonth = normMonth(m.group(1)); refDay = normDay(m.group(2)); } if (!(refYear.matches(""))){ for (MatchResult m : findMatches(Pattern.compile("<STORY_REF_TIME>.*?" +"(Jan\\.|Feb\\.|Mar\\.|Apr\\.|May\\.|Jun\\.|Jul\\.|Aug\\.|Sep\\.|Oct\\.|Nov\\.|Dec\\.|" + "JAN\\.|FEB\\.|MAR\\.|APR\\.|MAY\\.|JUN\\.|JUL\\.|AUG\\.|SEP\\.|OCT\\.|NOV\\.|DEC\\.)[\\s]+([\\d]?[\\d]).*?"+ "</STORY_REF_TIME>"), xml)){ String exactMonth = normMonth(m.group(1)); String exactDay = normDay(m.group(2)); date_value = refYear+"-"+exactMonth+"-"+exactDay; } } } // Document Creation Time style of EVALITA I-CAB corpus (Italian corpus) // example: <DOC ID="adige20040907_id405581" DATE="20040907"> if (date_value == null){ try { for (MatchResult m : findMatches(Pattern.compile("(<DOC ID=\".*?\" DATE=\")("+dateformat9+")(\">)"), xml)){ datetimetag = m.group(2); } if (datetimetag.matches(dateformat9)){ for (MatchResult m : findMatches(Pattern.compile(dateformat9), datetimetag)){ date_value = m.group(2)+"-"+m.group(3)+"-"+m.group(4); } } else { System.err.println(); System.err.println("["+compontent_id+"] cannot set dct with datetimetag: "+datetimetag); } } catch(NullPointerException e) { } // nothing to see here, carry on } if (date_value == null){ System.err.println(); System.err.println("["+compontent_id+"] Cannot set Document Creation Time - no datetimetag found in "+filename+"!"); } else{ Dct dct = new Dct(jcas); dct.setBegin(0); dct.setEnd(1); dct.setFilename(filename); dct.setTimexId("dct"); dct.setValue(date_value); dct.addToIndexes(); } } } public String normDay(String day){ if (!(day.matches("\\d\\d"))){ if (day.equals("1")){ day = "01"; } else if (day.equals("2")){ day = "02"; } else if (day.equals("3")){ day = "03"; } else if (day.equals("4")){ day = "04"; } else if (day.equals("5")){ day = "05"; } else if (day.equals("6")){ day = "06"; } else if (day.equals("7")){ day = "07"; } else if (day.equals("8")){ day = "08"; } else if (day.equals("9")){ day = "09"; } } return day; } public String normMonth(String month){ if (month.toLowerCase().startsWith("jan")){ month = "01"; } else if (month.toLowerCase().startsWith("feb")){ month = "02"; } else if (month.toLowerCase().startsWith("mar")){ month = "03"; } else if (month.toLowerCase().startsWith("apr")){ month = "04"; } else if (month.toLowerCase().startsWith("may")){ month = "05"; } else if (month.toLowerCase().startsWith("jun")){ month = "06"; } else if (month.toLowerCase().startsWith("jul")){ month = "07"; } else if (month.toLowerCase().startsWith("aug")){ month = "08"; } else if (month.toLowerCase().startsWith("sep")){ month = "09"; } else if (month.toLowerCase().startsWith("oct")){ month = "10"; } else if (month.toLowerCase().startsWith("nov")){ month = "11"; } else if (month.toLowerCase().startsWith("dec")){ month = "12"; } return month; } /** * @see org.apache.uima.collection.base_cpm.BaseCollectionReader#close() */ public void close() throws IOException { } /** * @see org.apache.uima.collection.base_cpm.BaseCollectionReader#getProgress() */ public Progress[] getProgress() { return new Progress[] { new ProgressImpl(currentIndex, mFiles.size(), Progress.ENTITIES) }; } /** * Gets the total number of documents that will be returned by this collection reader. This is not * part of the general collection reader interface. * * @return the number of documents in the collection */ public int getNumberOfDocuments() { return mFiles.size(); } /** * Find all the matches of a pattern in a charSequence and return the * results as list. * * @param pattern * @param s * @return */ public static Iterable<MatchResult> findMatches(Pattern pattern, CharSequence s) { List<MatchResult> results = new ArrayList<MatchResult>(); for (Matcher m = pattern.matcher(s); m.find();) results.add(m.toMatchResult()); return results; } }
Java
/* * Eventi2014Writer.java * * Copyright (c) 2014, Database Research Group, Institute of Computer Science, Heidelberg University. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * author: Jannik Strötgen * email: stroetgen@uni-hd.de * * The Eventi2014 Writer writes Eventi-style output. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.uima.consumer.eventi2014writer; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.FSIterator; import org.apache.uima.collection.CasConsumer_ImplBase; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.ResourceProcessException; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; import de.unihd.dbs.uima.types.heideltime.Dct; import de.unihd.dbs.uima.types.heideltime.Timex3; import de.unihd.dbs.uima.types.heideltime.Timex3Interval; import de.unihd.dbs.uima.types.heideltime.Token; public class Eventi2014Writer extends CasConsumer_ImplBase { private Class<?> component = this.getClass(); private static final String PARAM_OUTPUTDIR = "OutputDir"; // counter for outputting documents. gets increased in case there is no DCT/filename info private static volatile Integer outCount = 0; private File mOutputDir; public void initialize() throws ResourceInitializationException { mOutputDir = new File((String) getConfigParameterValue(PARAM_OUTPUTDIR)); if (!mOutputDir.exists()) { if(!mOutputDir.mkdirs()) { Logger.printError(component, "Couldn't create non-existant folder "+mOutputDir.getAbsolutePath()); throw new ResourceInitializationException(); } } if(!mOutputDir.canWrite()) { Logger.printError(component, "Folder "+mOutputDir.getAbsolutePath()+" is not writable."); throw new ResourceInitializationException(); } } public void processCas(CAS aCAS) throws ResourceProcessException { JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new ResourceProcessException(e); } // prepare everything for document String fullDocument = ""; // get the DCT Dct dct = null; String filename = null; String dctTag = ""; try { dct = (Dct) jcas.getAnnotationIndex(Dct.type).iterator().next(); String[] parts = dct.getFilename().split("---"); filename = parts[0]; dctTag = parts[1]; } catch(Exception e) { e.printStackTrace(); filename = "doc_" + Eventi2014Writer.getOutCount(); } // create the document according to the formatting requirements of EVENTI 2014 // first line: <Document doc_name="FILENAME"> String firstLine = "<Document doc_name=\"FILENAME\">\n"; fullDocument = firstLine.replaceAll("FILENAME", filename); // get the tokens and add them to fullDocument FSIterator itToken = jcas.getAnnotationIndex(Token.type).iterator(); int oldTokNum = 0; int oldTokID = 0; while (itToken.hasNext()){ Token t = (Token) itToken.next(); String[] parts = t.getFilename().split("---"); String sentNum = parts[1]; String tokNum = parts[2]; while (oldTokID < (t.getTokenId() - 1)){ oldTokNum++; oldTokID++; String tokenLine = "<token t_id=\"TOKENID\" sentence=\"SENTENCEID\" number=\"TOKENNUMBER\">TOKENSTRING</token>\n"; tokenLine = tokenLine.replace("TOKENID", oldTokID+""); tokenLine = tokenLine.replace("SENTENCEID", sentNum); tokenLine = tokenLine.replace("TOKENNUMBER", oldTokNum+""); tokenLine = tokenLine.replace("TOKENSTRING", ""); fullDocument = fullDocument + tokenLine; } String tokenLine = "<token t_id=\"TOKENID\" sentence=\"SENTENCEID\" number=\"TOKENNUMBER\">TOKENSTRING</token>\n"; tokenLine = tokenLine.replace("TOKENID", t.getTokenId()+""); tokenLine = tokenLine.replace("SENTENCEID", sentNum); tokenLine = tokenLine.replace("TOKENNUMBER", tokNum); tokenLine = tokenLine.replace("TOKENSTRING", t.getCoveredText()); oldTokNum = Integer.parseInt(tokNum); oldTokID = t.getTokenId(); // System.err.println("TOKEN FOUND....-->" + t.getCoveredText() + "<--"); fullDocument = fullDocument + tokenLine; } // add opening markable tag fullDocument = fullDocument + "\n\n<Markables>\n"; // collection for timexes which have an emptyValue attribute HashMap<Timex3, Integer> emptyValueTimexes = new HashMap<Timex3, Integer>(); // association for HeidelTime-internal Timex3 IDs -> markable_ids HashMap<String, String> idTranslation = new HashMap<String, String>(); // get the timex3s and add them to fullDocument int markableCounter = 1; FSIterator itTimex = jcas.getAnnotationIndex(Timex3.type).iterator(); while (itTimex.hasNext()){ Timex3 t = (Timex3) itTimex.next(); if(t instanceof Timex3Interval) continue; if(t.getEmptyValue() != null && !t.getEmptyValue().equals("")) emptyValueTimexes.put(t, markableCounter); // full tag - probably not required // String open = "<TIMEX3 m_id=\"MARKABLEID\" temporalFunction=\"FALSE\" functionInDocument=\"\" endPoint=\"\" anchorTimeID=\"\" mod=\"\" beginPoint=\"\" quant=\"\" freq=\"\" value=\"1985\" type=\"DATE\" comment=\"\" >"; String open = "<TIMEX3 m_id=\"MARKABLEID\" mod=\"MODSTRING\" "+ "quant=\"QUANTSTRING\" freq=\"FREQSTRING\" "+ "value=\"VALUESTRING\" type=\"TYPESTRING\" >\n"; String tokenInfoSingle = "<token_anchor t_id=\"TOKENID\"/>\n"; String close = "</TIMEX3>\n"; // set the attributes of the TIMEX3 annotations open = open.replace("MARKABLEID", markableCounter+""); open = open.replace("MODSTRING", t.getTimexMod()); open = open.replace("QUANTSTRING", t.getTimexQuant()); open = open.replace("FREQSTRING", t.getTimexFreq()); open = open.replace("VALUESTRING", t.getTimexValue()); open = open.replace("TYPESTRING", t.getTimexType()); fullDocument = fullDocument + open; // get the ids of the tokens which are involved FSIterator tokenIt = jcas.getAnnotationIndex(Token.type).iterator(); while (tokenIt.hasNext()) { Token tok = (Token) tokenIt.next(); if ((tok.getBegin() >= t.getBegin()) && (tok.getEnd() <= t.getEnd())){ int tokID = tok.getTokenId(); String line = tokenInfoSingle; line = line.replace("TOKENID", tokID+""); fullDocument = fullDocument + line; } } fullDocument = fullDocument + close; idTranslation.put(t.getTimexId(), markableCounter+""); markableCounter++; } // add document creation time tag Pattern p = Pattern.compile("m_id=\"([^\"]*)\""); Matcher m = p.matcher(dctTag); if(m.find()) dctTag = dctTag.substring(0, m.start(1)) + (markableCounter++) + dctTag.substring(m.end(1), dctTag.length()); fullDocument = fullDocument + dctTag + "\n"; // add empty tags for(Entry<Timex3, Integer> entry : emptyValueTimexes.entrySet()) { String open = "<TIMEX3 m_id=\""+(markableCounter++)+"\" TAG_DESCRIPTOR=\"Empty_Mark\" anchorTimeID=\""+entry.getValue()+"\" value=\""+entry.getKey().getEmptyValue()+"\" type=\"DATE\" />\n"; fullDocument = fullDocument + open; } // add empty tags from timex3intervals FSIterator tx3intIt = jcas.getAnnotationIndex(Timex3Interval.type).iterator(); while(tx3intIt.hasNext()) { Timex3Interval tx3i = (Timex3Interval) tx3intIt.next(); if(tx3i.getEmptyValue() != null && !tx3i.getEmptyValue().equals("")) { String beginMarkable = idTranslation.get(tx3i.getBeginTimex()); String endMarkable = idTranslation.get(tx3i.getEndTimex()); fullDocument += "<TIMEX3 m_id=\""+(markableCounter++)+"\" TAG_DESCRIPTOR=\"Empty_Mark\" beginPoint=\""+beginMarkable+"\" endPoint=\""+endMarkable+"\" anchorTimeID=\""+beginMarkable+"\" value=\""+tx3i.getEmptyValue()+"\" type=\"DURATION\" />\n"; } } // add closing tag for markables fullDocument += "</Markables>\n<Relations>\n</Relations>\n</Document>"; writeDocument(fullDocument, filename); } /** * writes a populated DOM xml(timeml) document to a given directory/file * @param xmlDoc xml dom object * @param filename name of the file that gets appended to the set output path */ private void writeDocument(String fullDocument, String filename) { // create output file handle File outFile = new File(mOutputDir, filename+".xml"); BufferedWriter bw = null; try { // create a buffered writer for the output file bw = new BufferedWriter(new FileWriter(outFile)); bw.append(fullDocument); } catch (IOException e) { // something went wrong with the bufferedwriter e.printStackTrace(); Logger.printError(component, "File "+outFile.getAbsolutePath()+" could not be written."); } finally { // clean up for the bufferedwriter try { bw.close(); } catch(IOException e) { e.printStackTrace(); Logger.printError(component, "File "+outFile.getAbsolutePath()+" could not be closed."); } } } public static synchronized Integer getOutCount() { return outCount++; } }
Java
/* * ACETernWriter.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * author: Jannik Strötgen * email: stroetgen@uni-hd.de * * ACE Tern Writer creates files according to the ACE Tern style. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.uima.consumer.aceternwriter; import java.util.List; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.FSIndex; import org.apache.uima.cas.FSIterator; import org.apache.uima.collection.CasConsumer_ImplBase; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.ResourceProcessException; import de.unihd.dbs.uima.types.heideltime.Timex3; import de.unihd.dbs.uima.types.heideltime.SourceDocInfo; /** * * @author jstroetgen * */ public class ACETernWriter extends CasConsumer_ImplBase { public static final String PARAM_OUTPUTDIR = "OutputDir"; public static final String PARAM_CONVERTTIMEX3TO2 = "ConvertTimex3To2"; private File mOutputDir; private int mDocNum; private Boolean convertTimex3To2 = true; private boolean printDetails = false; /** * initialize */ public void initialize() throws ResourceInitializationException { mDocNum = 0; convertTimex3To2 = (Boolean) getConfigParameterValue(PARAM_CONVERTTIMEX3TO2); mOutputDir = new File((String) getConfigParameterValue(PARAM_OUTPUTDIR)); if (!mOutputDir.exists()) { mOutputDir.mkdirs(); } } /** * process */ public void processCas(CAS aCAS) throws ResourceProcessException { JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new ResourceProcessException(e); } printTimexAnnotationsInline(jcas); } public void printTimexAnnotationsInline(JCas jcas){ // retrieve the filename of the input file from the CAS FSIterator it = jcas.getAnnotationIndex(SourceDocInfo.type).iterator(); File outFile = null; File inFile = null; if (it.hasNext()) { SourceDocInfo fileLoc = (SourceDocInfo) it.next(); try { inFile = new File(new URL(fileLoc.getUri()).getPath()); String outFileName = inFile.getName(); if (fileLoc.getOffsetInSource() > 0) { outFileName += ("_" + fileLoc.getOffsetInSource()); } outFileName += ".xmi"; outFile = new File(mOutputDir, outFileName); } catch (MalformedURLException e1) { // invalid URL, use default processing below } } if (outFile == null) { outFile = new File(mOutputDir, "doc" + mDocNum++); } // what has to be printed? String toprint = ""; // document text String doctext = jcas.getDocumentText(); int startposition = 0; int endposition = doctext.length(); boolean anyTimex = false; // get timex index FSIndex indexTimex = jcas.getAnnotationIndex(Timex3.type); FSIterator iterTimex = indexTimex.iterator(); while (iterTimex.hasNext()){ anyTimex = true; Timex3 t = (Timex3) iterTimex.next(); endposition = t.getBegin(); if (endposition < startposition){ if (printDetails == true){ System.err.println("[Tern2004Writer] Overlapping expressions... ignoring: "+t.getCoveredText()); } }else{ // CHANGES DUE TO TIMEX2 not equal TIMEX3 String timexvalue = t.getTimexValue(); if(convertTimex3To2) { timexvalue = translatetimex3timex2(timexvalue); if (t.getTimexType().equals("SET")){ timexvalue = translatetimex3timex2set(timexvalue); } } toprint = toprint + doctext.substring(startposition, endposition); // text from begin or last timex to begin of new timex toprint = toprint + "<TIMEX2 val=\"" + timexvalue + "\">"; // timex opening tag toprint = toprint + t.getCoveredText(); // timex text toprint = toprint + "</TIMEX2>"; startposition = t.getEnd(); } } if (anyTimex == true){ // text from last timex to end toprint = toprint + doctext.substring(startposition); } if (anyTimex == false){ // whole document text toprint = toprint + doctext; } // print toprint text try { BufferedWriter bf = new BufferedWriter(new FileWriter(outFile)); bf.append(toprint); bf.close(); } catch (IOException e1) { e1.printStackTrace(); } } public String translatetimex3timex2(String timexvalue){ // change decades String decade = "(.*\\d\\d\\d)X"; if (timexvalue.matches(decade)){ for (MatchResult m : findMatches(Pattern.compile(decade), timexvalue)){ timexvalue = m.group(1); } } // change century String century = "(.*\\d\\d)XX"; if (timexvalue.matches(century)){ for (MatchResult m : findMatches(Pattern.compile(century), timexvalue)){ timexvalue = m.group(1); } } return timexvalue; } public String translatetimex3timex2set(String timexvalue){ // change year String year = "(P(\\d)+Y)"; if (timexvalue.matches(year)){ timexvalue = "XXXX"; } // change month String month = "(P(\\d)+M)"; if (timexvalue.matches(month)){ timexvalue = "XXXX-XX"; } // change day String day = "(P(\\d)+D)"; if (timexvalue.matches(day)){ timexvalue = "XXXX-XX-XX"; } // change hour String hour = "(PT(\\d)+H)"; if (timexvalue.matches(hour)){ timexvalue = "XXXX-XX-XXTXX"; } // change minute String minute = "(PT(\\d)+M)"; if (timexvalue.matches(minute)){ timexvalue = "XXXX-XX-XXTXX:XX"; } return timexvalue; } /** * Find all the matches of a pattern in a charSequence and return the * results as list. * * @param pattern * @param s * @return */ public static Iterable<MatchResult> findMatches(Pattern pattern, CharSequence s) { List<MatchResult> results = new ArrayList<MatchResult>(); for (Matcher m = pattern.matcher(s); m.find();) results.add(m.toMatchResult()); return results; } }
Java
package de.unihd.dbs.uima.consumer.tempeval3writer; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.FSIterator; import org.apache.uima.collection.CasConsumer_ImplBase; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.ResourceProcessException; import org.w3c.dom.Document; import org.w3c.dom.Element; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; import de.unihd.dbs.uima.types.heideltime.Dct; import de.unihd.dbs.uima.types.heideltime.Timex3; public class TempEval3Writer extends CasConsumer_ImplBase { private Class<?> component = this.getClass(); private static final String PARAM_OUTPUTDIR = "OutputDir"; // counter for outputting documents. gets increased in case there is no DCT/filename info private static volatile Integer outCount = 0; private File mOutputDir; public void initialize() throws ResourceInitializationException { mOutputDir = new File((String) getConfigParameterValue(PARAM_OUTPUTDIR)); if (!mOutputDir.exists()) { if(!mOutputDir.mkdirs()) { Logger.printError(component, "Couldn't create non-existant folder "+mOutputDir.getAbsolutePath()); throw new ResourceInitializationException(); } } if(!mOutputDir.canWrite()) { Logger.printError(component, "Folder "+mOutputDir.getAbsolutePath()+" is not writable."); throw new ResourceInitializationException(); } } public void processCas(CAS aCAS) throws ResourceProcessException { JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new ResourceProcessException(e); } // get the DCT Dct dct = null; String filename = null; try { dct = (Dct) jcas.getAnnotationIndex(Dct.type).iterator().next(); filename = dct.getFilename(); } catch(Exception e) { filename = "doc_" + TempEval3Writer.getOutCount() + ".tml"; } // assemble an XML document Document xmlDoc = buildTimeMLDocument(jcas, dct, filename); // write the document to file writeTimeMLDocument(xmlDoc, filename); } /** * Creates a DOM Document filled with all of the timex3s that are in the jcas. * @param jcas * @param dct the document's DCT * @return */ private Document buildTimeMLDocument(JCas jcas, Dct dct, String filename) { DocumentBuilderFactory dbf = null; DocumentBuilder db = null; Document doc = null; try { dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); db = dbf.newDocumentBuilder(); doc = db.newDocument(); } catch (ParserConfigurationException e) { e.printStackTrace(); Logger.printError(component, "XML Builder could not be instantiated"); } // create the TimeML root element Element rootEl = doc.createElement("TimeML"); rootEl.setAttributeNS("xmlns", "xsi", "http://www.w3.org/2001/XMLSchema-instance"); rootEl.setAttributeNS("xsi", "noNamespaceSchemaLocation", "http://timeml.org/timeMLdocs/TimeML_1.2.1.xsd"); doc.appendChild(rootEl); // create DOCID tag Element docidEl = doc.createElement("DOCID"); docidEl.appendChild(doc.createTextNode(filename)); rootEl.appendChild(docidEl); // create DCT tag if(dct != null) { Element dctEl = doc.createElement("DCT"); Element timexForDCT = doc.createElement("TIMEX3"); timexForDCT.setAttribute("tid", "t0"); timexForDCT.setAttribute("type", "DATE"); timexForDCT.setAttribute("value", dct.getValue()); timexForDCT.setAttribute("temporalFunction", "false"); timexForDCT.setAttribute("functionInDocument", "CREATION_TIME"); timexForDCT.appendChild(doc.createTextNode(dct.getValue())); dctEl.appendChild(timexForDCT); // NEW rootEl.appendChild(dctEl); } // create and fill the TEXT tag Integer offset = 0; Element textEl = doc.createElement("TEXT"); rootEl.appendChild(textEl); FSIterator it = jcas.getAnnotationIndex(Timex3.type).iterator(); // if there are no timexes, just add one text node as a child. otherwise, iterate through timexes String docText = jcas.getDocumentText(); if(!it.hasNext()) { textEl.appendChild(doc.createTextNode(docText)); } else { HashSet<Timex3> timexesToSkip = new HashSet<Timex3>(); Timex3 prevT = null; Timex3 thisT = null; // iterate over timexes to find overlaps while(it.hasNext()) { thisT = (Timex3) it.next(); // check for whether this and the previous timex overlap. ex: [early (friday] morning) if(prevT != null && prevT.getEnd() > thisT.getBegin()) { Timex3 removedT = null; // only for debug message // assuming longer value string means better granularity if(prevT.getTimexValue().length() > thisT.getTimexValue().length()) { timexesToSkip.add(thisT); removedT = thisT; /* prevT stays the same. */ } else { timexesToSkip.add(prevT); removedT = prevT; prevT = thisT; // this iteration's prevT was removed; setting for new iteration } Logger.printError(component, "Two overlapping Timexes have been discovered:" + System.getProperty("line.separator") + "Timex A: " + prevT.getCoveredText() + " [\"" + prevT.getTimexValue() + "\" / " + prevT.getBegin() + ":" + prevT.getEnd() + "]" + System.getProperty("line.separator") + "Timex B: " + removedT.getCoveredText() + " [\"" + removedT.getTimexValue() + "\" / " + removedT.getBegin() + ":" + removedT.getEnd() + "]" + " [removed]" + System.getProperty("line.separator") + "The writer chose, for granularity: " + prevT.getCoveredText() + System.getProperty("line.separator") + "This usually happens with an incomplete ruleset. Please consider adding " + "a new rule that covers the entire expression."); } else { // no overlap found? set current timex as next iteration's previous timex prevT = thisT; } } it.moveToFirst(); // reset iterator for another loop // iterate over timexes to write the DOM tree. while(it.hasNext()) { Timex3 t = (Timex3) it.next(); // if this timex was marked to be removed, skip it entirely and go to the next one. if(timexesToSkip.contains(t)) continue; if(t.getBegin() > offset) { // add a textnode that contains the text before the timex textEl.appendChild(doc.createTextNode(docText.substring(offset, t.getBegin()))); } // create the TIMEX3 element Element newTimex = doc.createElement("TIMEX3"); // set its required attributes newTimex.setAttribute("tid", t.getTimexId()); newTimex.setAttribute("type", t.getTimexType()); newTimex.setAttribute("value", t.getTimexValue()); // set its optional attributes if(!t.getTimexMod().equals("")) newTimex.setAttribute("mod", t.getTimexMod()); if(!t.getTimexQuant().equals("")) newTimex.setAttribute("quant", t.getTimexQuant()); if(!t.getTimexFreq().equals("")) newTimex.setAttribute("freq", t.getTimexFreq()); // set text newTimex.appendChild(doc.createTextNode(t.getCoveredText())); // add the timex tag to the text tag textEl.appendChild(newTimex); // set cursor to the end of the timex offset = t.getEnd(); } // append the rest of the document text if(offset < docText.length()) textEl.appendChild(doc.createTextNode(docText.substring(offset))); } return doc; } /** * writes a populated DOM xml(timeml) document to a given directory/file * @param xmlDoc xml dom object * @param filename name of the file that gets appended to the set output path */ private void writeTimeMLDocument(Document xmlDoc, String filename) { // create output file handle File outFile = new File(mOutputDir, filename+".tml"); BufferedWriter bw = null; try { // create a buffered writer for the output file bw = new BufferedWriter(new FileWriter(outFile)); // prepare the transformer to convert from the xml doc to output text Transformer transformer = TransformerFactory.newInstance().newTransformer(); // some pretty printing transformer.setOutputProperty(OutputKeys.INDENT, "no"); DOMSource source = new DOMSource(xmlDoc); StreamResult result = new StreamResult(bw); // transform transformer.transform(source, result); } catch (IOException e) { // something went wrong with the bufferedwriter e.printStackTrace(); Logger.printError(component, "File "+outFile.getAbsolutePath()+" could not be written."); } catch (TransformerException e) { // the transformer malfunctioned (call optimus prime) e.printStackTrace(); Logger.printError(component, "XML transformer could not be properly initialized."); } finally { // clean up for the bufferedwriter try { bw.close(); } catch(IOException e) { e.printStackTrace(); Logger.printError(component, "File "+outFile.getAbsolutePath()+" could not be closed."); } } } public static synchronized Integer getOutCount() { return outCount++; } }
Java
/* * Tempeval2Writer.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * author: Jannik Strötgen * email: stroetgen@uni-hd.de * * TempEval2 Writer create files according to the TempEval-2 style. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.uima.consumer.tempeval2writer; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.FSIndex; import org.apache.uima.cas.FSIterator; import org.apache.uima.collection.CasConsumer_ImplBase; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.ResourceProcessException; import de.unihd.dbs.uima.types.heideltime.Timex3; /** * * @author jstroetgen * */ public class Tempeval2Writer extends CasConsumer_ImplBase { public static final String PARAM_OUTPUTDIR = "OutputDir"; private File mOutputDir; /** * initialize */ public void initialize() throws ResourceInitializationException { mOutputDir = new File((String) getConfigParameterValue(PARAM_OUTPUTDIR)); if (!mOutputDir.exists()) { mOutputDir.mkdirs(); } } /** * process */ public void processCas(CAS aCAS) throws ResourceProcessException { JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new ResourceProcessException(e); } printTimexAnnotations(jcas); } public void printTimexAnnotations(JCas jcas) { File outExtents = new File(mOutputDir, "timex-extents.tab"); File outAttributes = new File(mOutputDir, "timex-attributes.tab"); // get timex index FSIndex indexTimex = jcas.getAnnotationIndex(Timex3.type); FSIterator iterTimex = indexTimex.iterator(); while (iterTimex.hasNext()){ Timex3 t = (Timex3) iterTimex.next(); if (!((t.getType().toString().equals("de.unihd.dbs.uima.heidopp.types.tempeval2.GoldTimex3")))){ // output extents String toPrintExtents = ""; String[] allTokList = t.getAllTokIds().split("<-->"); for (int i=1; i < allTokList.length; i++){ toPrintExtents = toPrintExtents+t.getFilename()+"\t"+t.getSentId()+"\t"+allTokList[i]+ "\ttimex3\t"+t.getTimexId()+"\t1\n"; } try { BufferedWriter bf = new BufferedWriter(new FileWriter(outExtents, true)); bf.write(toPrintExtents); bf.close(); } catch (IOException e) { e.printStackTrace(); } // output attributes String toPrintAttributes = t.getFilename()+"\t"+t.getSentId()+"\t"+t.getFirstTokId()+ "\ttimex3\t"+t.getTimexId()+"\t1\ttype\t"+t.getTimexType()+"\n"; toPrintAttributes += t.getFilename()+"\t"+t.getSentId()+"\t"+t.getFirstTokId()+ "\ttimex3\t"+t.getTimexId()+"\t1\tvalue\t"+t.getTimexValue()+"\n"; try { BufferedWriter bf = new BufferedWriter(new FileWriter(outAttributes, true)); bf.write(toPrintAttributes); bf.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } }
Java
package de.unihd.dbs.uima.annotator.heideltime; import java.util.EnumMap; import java.util.Iterator; import java.util.Map.Entry; import org.apache.uima.UimaContext; import org.apache.uima.jcas.JCas; import de.unihd.dbs.uima.annotator.heideltime.processors.GenericProcessor; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; /** * This class implements a singleton "Addon Manager". Any subroutine (Processor) that * may be added to HeidelTime's code to achieve a specific goal which is self-sufficient, * i.e. creates new Timexes by itself and without the use of HeidelTime's non-resource * related functionality should be registered in an instance of this class. HeidelTime's * annotator will then execute every registered "Processor"'s process() function. * Note that these Processes will be instantiated and processed after the resource * collection and before HeidelTime's cleanup methods. * @author julian zell * */ public class ProcessorManager { // singleton instance private static final ProcessorManager INSTANCE = new ProcessorManager(); // list of processes' package names private EnumMap<Priority, String> processorNames; // array of instantiated processors private EnumMap<Priority, GenericProcessor> processors; // self-identifying component for logging purposes private Class<?> component; // flag for whether the processors have been initialized private boolean initialized = false; /** * Private constructor, only to be called by the getInstance() method. */ private ProcessorManager() { this.processorNames = new EnumMap<Priority, String>(Priority.class); this.component = this.getClass(); this.processors = new EnumMap<Priority, GenericProcessor>(Priority.class); } /** * method to register a processor * @param processor processor to be registered in the processormanager's list * @param p priority for the process to take */ public void registerProcessor(String processor, Priority prio) { this.processorNames.put(prio, processor); } /** * method to register a processor without priority * @param processor processor to be registered in the processormanager's list */ public void registerProcessor(String processor) { registerProcessor(processor, Priority.POSTPROCESSING); } /** * Based on reflection, this method instantiates and initializes all of the * registered Processors. * @param jcas */ public void initializeAllProcessors(UimaContext aContext) { Iterator<Entry<Priority, String>> it = processorNames.entrySet().iterator(); Entry<Priority, String> e; while(it.hasNext()) { e = it.next(); try { Class<?> c = Class.forName(e.getValue()); GenericProcessor p = (GenericProcessor) c.newInstance(); p.initialize(aContext); processors.put(e.getKey(), p); } catch (Exception exception) { exception.printStackTrace(); Logger.printError(component, "Unable to initialize registered Processor "+e.getValue()+", got: "+exception.toString()); System.exit(-1); } } this.initialized = true; } /** * Based on reflection, this method instantiates and executes all of the * registered Processors. * @param jcas */ public void executeProcessors(JCas jcas, ProcessorManager.Priority prio) { if(!this.initialized) { Logger.printError(component, "Unable to execute Processors; initialization was not concluded successfully."); System.exit(-1); } Iterator<Entry<Priority, GenericProcessor>> it = processors.entrySet().iterator(); Entry<Priority, GenericProcessor> e; while(it.hasNext()) { e = it.next(); if(prio.equals(e.getKey())) { try { e.getValue().process(jcas); } catch (Exception exception) { exception.printStackTrace(); Logger.printError(component, "Unable to process registered Processor "+e.getValue().getClass().getName()+", got: "+exception.toString()); System.exit(-1); } } } } /** * getInstance method of the singleton pattern * @return ProcessorManager */ public static ProcessorManager getInstance() { return ProcessorManager.INSTANCE; } public enum Priority { PREPROCESSING, POSTPROCESSING, ARBITRARY } }
Java
/** * A dedicated Exception type for HeidelTime-based Exceptions. */ package de.unihd.dbs.uima.annotator.heideltime; /** * @author Julian Zell * */ public class HeidelTimeException extends Exception { /** * automatically generated uid */ private static final long serialVersionUID = 5934916764509083459L; private String message; public HeidelTimeException() {}; public HeidelTimeException(String message) { this.message = message; } public String getMessage() { return this.message; } }
Java
package de.unihd.dbs.uima.annotator.heideltime.utilities; /** * Logger class to facilitate a centralized logging effort. Upon initialization of * the HeidelTime annotator, the verbosity (printDetails) should be set; any kind of * output should be done using either the printDetail()-methods for DEBUG-Level, * conditional output or the printError()-methods for ERROR-Level, unconditional * output. * @author julian zell * */ public class Logger { private static Boolean printDetails = false; /** * Controls whether DEBUG-Level information is printed or not * @param printDetails to print or not to print */ public static void setPrintDetails(Boolean printDetails) { Logger.printDetails = printDetails; } /** * print DEBUG level information with package name * @param component Component from which the message originates * @param msg DEBUG-level message */ public static void printDetail(Class<?> c, String msg) { if(Logger.printDetails) { String preamble; if(c != null) preamble = "["+c.getName()+"]"; else preamble = ""; System.out.println(preamble+" "+msg); } } /** * no-package proxy method * @param msg DEBUG-Level message */ public static void printDetail(String msg) { printDetail(null, msg); } /** * print an ERROR-Level message with package name * @param component Component from which the message originates * @param msg ERROR-Level message */ public static void printError(Class<?> c, String msg) { String preamble; if(c != null) preamble = "["+c.getName()+"] "; else preamble = ""; System.err.println(preamble+msg); } /** * no-package proxy method * @param msg ERROR-Level message */ public static void printError(String msg) { printError(null, msg); } /** * Outputs whether DEBUG-Level information is printed or not */ public static Boolean getPrintDetails() { return printDetails; } }
Java
package de.unihd.dbs.uima.annotator.heideltime.utilities; import de.unihd.dbs.uima.annotator.heideltime.HeidelTimeException; public class LocaleException extends HeidelTimeException { /** * default generated uid */ private static final long serialVersionUID = -3573142250219483271L; }
Java
package de.unihd.dbs.uima.annotator.heideltime.utilities; import java.util.List; import java.util.TreeMap; import java.util.regex.MatchResult; import java.util.regex.Pattern; import org.apache.uima.cas.FSIterator; import org.apache.uima.jcas.JCas; import de.unihd.dbs.uima.annotator.heideltime.resources.Language; import de.unihd.dbs.uima.annotator.heideltime.resources.NormalizationManager; import de.unihd.dbs.uima.annotator.heideltime.resources.RePatternManager; import de.unihd.dbs.uima.types.heideltime.Sentence; import de.unihd.dbs.uima.types.heideltime.Timex3; import de.unihd.dbs.uima.types.heideltime.Token; /** * * This class contains methods that work with the dependence of a subject with its * surrounding data; namely via the jcas element or a subset list. * @author jannik stroetgen * */ public class ContextAnalyzer { /** * The value of the x of the last mentioned Timex is calculated. * @param linearDates list of previous linear dates * @param i index for the previous date entry * @param x type to search for * @return last mentioned entry */ public static String getLastMentionedX(List<Timex3> linearDates, int i, String x, Language language) { NormalizationManager nm = NormalizationManager.getInstance(language); // Timex for which to get the last mentioned x (i.e., Timex i) Timex3 t_i = linearDates.get(i); String xValue = ""; int j = i - 1; while (j >= 0) { Timex3 timex = linearDates.get(j); // check that the two timexes to compare do not have the same offset: if (!(t_i.getBegin() == timex.getBegin())) { String value = timex.getTimexValue(); if (!(value.contains("funcDate"))){ if (x.equals("century")) { if (value.matches("^[0-9][0-9].*")) { xValue = value.substring(0,2); break; } else if (value.matches("^BC[0-9][0-9].*")){ xValue = value.substring(0,4); break; } else { j--; } } else if (x.equals("decade")) { if (value.matches("^[0-9][0-9][0-9].*")) { xValue = value.substring(0,3); break; } else if (value.matches("^BC[0-9][0-9][0-9].*")){ xValue = value.substring(0,5); break; } else { j--; } } else if (x.equals("year")) { if (value.matches("^[0-9][0-9][0-9][0-9].*")) { xValue = value.substring(0,4); break; } else if (value.matches("^BC[0-9][0-9][0-9][0-9].*")){ xValue = value.substring(0,6); break; } else { j--; } } else if (x.equals("dateYear")) { if (value.matches("^[0-9][0-9][0-9][0-9].*")) { xValue = value; break; } else if (value.matches("^BC[0-9][0-9][0-9][0-9].*")){ xValue = value; break; } else { j--; } } else if (x.equals("month")) { if (value.matches("^[0-9][0-9][0-9][0-9]-[0-9][0-9].*")) { xValue = value.substring(0,7); break; } else if (value.matches("^BC[0-9][0-9][0-9][0-9]-[0-9][0-9].*")){ xValue = value.substring(0,9); break; } else { j--; } } else if (x.equals("month-with-details")) { if (value.matches("^[0-9][0-9][0-9][0-9]-[0-9][0-9].*")) { xValue = value; break; } // else if (value.matches("^BC[0-9][0-9][0-9][0-9]-[0-9][0-9].*")) { // xValue = value; // break; // } else { j--; } } else if (x.equals("day")) { if (value.matches("^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].*")) { xValue = value.substring(0,10); break; } // else if (value.matches("^BC[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].*")) { // xValue = value.substring(0,12); // break; // } else { j--; } } else if (x.equals("week")) { if (value.matches("^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].*")) { for (MatchResult r : Toolbox.findMatches(Pattern.compile("^(([0-9][0-9][0-9][0-9])-[0-9][0-9]-[0-9][0-9]).*"), value)) { xValue = r.group(2)+"-W"+DateCalculator.getWeekOfDate(r.group(1)); break; } break; } else if (value.matches("^[0-9][0-9][0-9][0-9]-W[0-9][0-9].*")) { for (MatchResult r : Toolbox.findMatches(Pattern.compile("^([0-9][0-9][0-9][0-9]-W[0-9][0-9]).*"), value)) { xValue = r.group(1); break; } break; } // TODO check what to do for BC times else { j--; } } else if (x.equals("quarter")) { if (value.matches("^[0-9][0-9][0-9][0-9]-[0-9][0-9].*")) { String month = value.substring(5,7); String quarter = nm.getFromNormMonthInQuarter(month); xValue = value.substring(0,4)+"-Q"+quarter; break; } else if (value.matches("^[0-9][0-9][0-9][0-9]-Q[1234].*")) { xValue = value.substring(0,7); break; } // TODO check what to do for BC times else { j--; } } else if (x.equals("dateQuarter")) { if (value.matches("^[0-9][0-9][0-9][0-9]-Q[1234].*")) { xValue = value.substring(0,7); break; } // TODO check what to do for BC times else { j--; } } else if (x.equals("season")) { if (value.matches("^[0-9][0-9][0-9][0-9]-[0-9][0-9].*")) { String month = value.substring(5,7); String season = nm.getFromNormMonthInSeason(month); xValue = value.substring(0,4)+"-"+season; break; } // else if (value.matches("^BC[0-9][0-9][0-9][0-9]-[0-9][0-9].*")) { // String month = value.substring(7,9); // String season = nm.getFromNormMonthInSeason(month); // xValue = value.substring(0,6)+"-"+season; // break; // } else if (value.matches("^[0-9][0-9][0-9][0-9]-(SP|SU|FA|WI).*")) { xValue = value.substring(0,7); break; } // else if (value.matches("^BC[0-9][0-9][0-9][0-9]-(SP|SU|FA|WI).*")) { // xValue = value.substring(0,9); // break; // } else { j--; } } } else { j--; } } else { j--; } } return xValue; } /** * Get the last tense used in the sentence * * @param timex timex construct to discover tense data for * @return string that contains the tense */ public static String getClosestTense(Timex3 timex, JCas jcas, Language language) { RePatternManager rpm = RePatternManager.getInstance(language); String lastTense = ""; String nextTense = ""; int tokenCounter = 0; int lastid = 0; int nextid = 0; int tid = 0; // Get the sentence FSIterator iterSentence = jcas.getAnnotationIndex(Sentence.type).iterator(); Sentence s = new Sentence(jcas); while (iterSentence.hasNext()) { s = (Sentence) iterSentence.next(); if ((s.getBegin() < timex.getBegin()) && (s.getEnd() > timex.getEnd())) { break; } } // Get the tokens TreeMap<Integer, Token> tmToken = new TreeMap<Integer, Token>(); FSIterator iterToken = jcas.getAnnotationIndex(Token.type).subiterator(s); while (iterToken.hasNext()) { Token token = (Token) iterToken.next(); tmToken.put(token.getEnd(), token); } // Get the last VERB token for (Integer tokEnd : tmToken.keySet()) { tokenCounter++; if (tokEnd < timex.getBegin()) { Token token = tmToken.get(tokEnd); Logger.printDetail("GET LAST TENSE: string:"+token.getCoveredText()+" pos:"+token.getPos()); Logger.printDetail("hmAllRePattern.containsKey(tensePos4PresentFuture):"+rpm.get("tensePos4PresentFuture")); Logger.printDetail("hmAllRePattern.containsKey(tensePos4Future):"+rpm.get("tensePos4Future")); Logger.printDetail("hmAllRePattern.containsKey(tensePos4Past):"+rpm.get("tensePos4Past")); Logger.printDetail("CHECK TOKEN:"+token.getPos()); if (token.getPos() == null) { } else if ((rpm.containsKey("tensePos4PresentFuture")) && (token.getPos().matches(rpm.get("tensePos4PresentFuture")))) { lastTense = "PRESENTFUTURE"; lastid = tokenCounter; } else if ((rpm.containsKey("tensePos4Past")) && (token.getPos().matches(rpm.get("tensePos4Past")))) { lastTense = "PAST"; lastid = tokenCounter; } else if ((rpm.containsKey("tensePos4Future")) && (token.getPos().matches(rpm.get("tensePos4Future")))) { if (token.getCoveredText().matches(rpm.get("tenseWord4Future"))) { lastTense = "FUTURE"; lastid = tokenCounter; } } } else { if (tid == 0) { tid = tokenCounter; } } } tokenCounter = 0; for (Integer tokEnd : tmToken.keySet()) { tokenCounter++; if (nextTense.equals("")) { if (tokEnd > timex.getEnd()) { Token token = tmToken.get(tokEnd); Logger.printDetail("GET NEXT TENSE: string:"+token.getCoveredText()+" pos:"+token.getPos()); Logger.printDetail("hmAllRePattern.containsKey(tensePos4PresentFuture):"+rpm.get("tensePos4PresentFuture")); Logger.printDetail("hmAllRePattern.containsKey(tensePos4Future):"+rpm.get("tensePos4Future")); Logger.printDetail("hmAllRePattern.containsKey(tensePos4Past):"+rpm.get("tensePos4Past")); Logger.printDetail("CHECK TOKEN:"+token.getPos()); if (token.getPos() == null) { } else if ((rpm.containsKey("tensePos4PresentFuture")) && (token.getPos().matches(rpm.get("tensePos4PresentFuture")))) { nextTense = "PRESENTFUTURE"; nextid = tokenCounter; } else if ((rpm.containsKey("tensePos4Past")) && (token.getPos().matches(rpm.get("tensePos4Past")))) { nextTense = "PAST"; nextid = tokenCounter; } else if ((rpm.containsKey("tensePos4Future")) && (token.getPos().matches(rpm.get("tensePos4Future")))) { if (token.getCoveredText().matches(rpm.get("tenseWord4Future"))) { nextTense = "FUTURE"; nextid = tokenCounter; } } } } } if (lastTense.equals("")) { Logger.printDetail("TENSE: "+nextTense); return nextTense; } else if (nextTense.equals("")) { Logger.printDetail("TENSE: "+lastTense); return lastTense; } else { // If there is tense before and after the timex token, // return the closer one: if ((tid - lastid) > (nextid - tid)) { Logger.printDetail("TENSE: "+nextTense); return nextTense; } else { Logger.printDetail("TENSE: "+lastTense); return lastTense; } } } /** * Get the last tense used in the sentence * * @param timex timex construct to discover tense data for * @return string that contains the tense */ public static String getLastTense(Timex3 timex, JCas jcas, Language language) { RePatternManager rpm = RePatternManager.getInstance(language); String lastTense = ""; // Get the sentence FSIterator iterSentence = jcas.getAnnotationIndex(Sentence.type).iterator(); Sentence s = new Sentence(jcas); while (iterSentence.hasNext()) { s = (Sentence) iterSentence.next(); if ((s.getBegin() < timex.getBegin()) && (s.getEnd() > timex.getEnd())) { break; } } // Get the tokens TreeMap<Integer, Token> tmToken = new TreeMap<Integer, Token>(); FSIterator iterToken = jcas.getAnnotationIndex(Token.type).subiterator(s); while (iterToken.hasNext()) { Token token = (Token) iterToken.next(); tmToken.put(token.getEnd(), token); } // Get the last VERB token for (Integer tokEnd : tmToken.keySet()) { if (tokEnd < timex.getBegin()) { Token token = tmToken.get(tokEnd); Logger.printDetail("GET LAST TENSE: string:"+token.getCoveredText()+" pos:"+token.getPos()); Logger.printDetail("hmAllRePattern.containsKey(tensePos4PresentFuture):"+rpm.get("tensePos4PresentFuture")); Logger.printDetail("hmAllRePattern.containsKey(tensePos4Future):"+rpm.get("tensePos4Future")); Logger.printDetail("hmAllRePattern.containsKey(tensePos4Past):"+rpm.get("tensePos4Past")); Logger.printDetail("CHECK TOKEN:"+token.getPos()); if (token.getPos() == null) { } else if ((rpm.containsKey("tensePos4PresentFuture")) && (token.getPos().matches(rpm.get("tensePos4PresentFuture")))) { lastTense = "PRESENTFUTURE"; Logger.printDetail("this tense:"+lastTense); } else if ((rpm.containsKey("tensePos4Past")) && (token.getPos().matches(rpm.get("tensePos4Past")))) { lastTense = "PAST"; Logger.printDetail("this tense:"+lastTense); } else if ((rpm.containsKey("tensePos4Future")) && (token.getPos().matches(rpm.get("tensePos4Future")))) { if (token.getCoveredText().matches(rpm.get("tenseWord4Future"))) { lastTense = "FUTURE"; Logger.printDetail("this tense:"+lastTense); } } if (token.getCoveredText().equals("since")) { lastTense = "PAST"; Logger.printDetail("this tense:"+lastTense); } if (token.getCoveredText().equals("depuis")) { // French lastTense = "PAST"; Logger.printDetail("this tense:"+lastTense); } } if (lastTense.equals("")) { if (tokEnd > timex.getEnd()) { Token token = tmToken.get(tokEnd); Logger.printDetail("GET NEXT TENSE: string:"+token.getCoveredText()+" pos:"+token.getPos()); Logger.printDetail("hmAllRePattern.containsKey(tensePos4PresentFuture):"+rpm.get("tensePos4PresentFuture")); Logger.printDetail("hmAllRePattern.containsKey(tensePos4Future):"+rpm.get("tensePos4Future")); Logger.printDetail("hmAllRePattern.containsKey(tensePos4Past):"+rpm.get("tensePos4Past")); Logger.printDetail("CHECK TOKEN:"+token.getPos()); if (token.getPos() == null) { } else if ((rpm.containsKey("tensePos4PresentFuture")) && (token.getPos().matches(rpm.get("tensePos4PresentFuture")))) { lastTense = "PRESENTFUTURE"; Logger.printDetail("this tense:"+lastTense); } else if ((rpm.containsKey("tensePos4Past")) && (token.getPos().matches(rpm.get("tensePos4Past")))) { lastTense = "PAST"; Logger.printDetail("this tense:"+lastTense); } else if ((rpm.containsKey("tensePos4Future")) && (token.getPos().matches(rpm.get("tensePos4Future")))) { if (token.getCoveredText().matches(rpm.get("tenseWord4Future"))) { lastTense = "FUTURE"; Logger.printDetail("this tense:"+lastTense); } } } } } // check for double POS Constraints (not included in the rule language, yet) TODO // VHZ VNN and VHZ VNN and VHP VNN and VBP VVN String prevPos = ""; String longTense = ""; if (lastTense.equals("PRESENTFUTURE")) { for (Integer tokEnd : tmToken.keySet()) { if (tokEnd < timex.getBegin()) { Token token = tmToken.get(tokEnd); if ((prevPos.equals("VHZ")) || (prevPos.equals("VBZ")) || (prevPos.equals("VHP")) || (prevPos.equals("VBP")) || (prevPos.equals("VER:pres"))) { if (token.getPos().equals("VVN") || token.getPos().equals("VER:pper")) { if ((!(token.getCoveredText().equals("expected"))) && (!(token.getCoveredText().equals("scheduled")))) { lastTense = "PAST"; longTense = "PAST"; Logger.printDetail("this tense:"+lastTense); } } } prevPos = token.getPos(); } if (longTense.equals("")) { if (tokEnd > timex.getEnd()) { Token token = tmToken.get(tokEnd); if ((prevPos.equals("VHZ")) || (prevPos.equals("VBZ")) || (prevPos.equals("VHP")) || (prevPos.equals("VBP")) || (prevPos.equals("VER:pres"))) { if (token.getPos().equals("VVN") || token.getPos().equals("VER:pper")) { if ((!(token.getCoveredText().equals("expected"))) && (!(token.getCoveredText().equals("scheduled")))) { lastTense = "PAST"; longTense = "PAST"; Logger.printDetail("this tense:"+lastTense); } } } prevPos = token.getPos(); } } } } // French: VER:pres VER:pper if (lastTense.equals("PAST")) { for (Integer tokEnd : tmToken.keySet()) { if (tokEnd < timex.getBegin()) { Token token = tmToken.get(tokEnd); if ((prevPos.equals("VER:pres")) && (token.getPos().equals("VER:pper"))) { if (((token.getCoveredText().matches("^prévue?s?$"))) || ((token.getCoveredText().equals("^envisagée?s?$")))) { lastTense = "FUTURE"; longTense = "FUTURE"; Logger.printDetail("this tense:"+lastTense); } } prevPos = token.getPos(); } if (longTense.equals("")) { if (tokEnd > timex.getEnd()) { Token token = tmToken.get(tokEnd); if ((prevPos.equals("VER:pres")) && (token.getPos().equals("VER:pper"))) { if (((token.getCoveredText().matches("^prévue?s?$"))) || ((token.getCoveredText().equals("^envisagée?s?$")))) { lastTense = "FUTURE"; longTense = "FUTURE"; Logger.printDetail("this tense:"+lastTense); } } prevPos = token.getPos(); } } } } Logger.printDetail("TENSE: "+lastTense); return lastTense; } /** * Check token boundaries of expressions. * @param r MatchResult * @param s Respective sentence * @return whether or not the MatchResult is a clean one */ public static Boolean checkInfrontBehind(MatchResult r, Sentence s) { Boolean ok = true; // get rid of expressions such as "1999" in 53453.1999 if (r.start() > 1) { if ((s.getCoveredText().substring(r.start() - 2, r.start()).matches("\\d\\."))){ ok = false; } } // get rid of expressions if there is a character or symbol ($+) directly in front of the expression if (r.start() > 0) { if (((s.getCoveredText().substring(r.start() - 1, r.start()).matches("[\\w\\$\\+]"))) && (!(s.getCoveredText().substring(r.start() - 1, r.start()).matches("\\(")))){ ok = false; } } if (r.end() < s.getCoveredText().length()) { if ((s.getCoveredText().substring(r.end(), r.end() + 1).matches("[°\\w]")) && (!(s.getCoveredText().substring(r.end(), r.end() + 1).matches("\\)")))){ ok = false; } if (r.end() + 1 < s.getCoveredText().length()) { if (s.getCoveredText().substring(r.end(), r.end() + 2).matches( "[\\.,]\\d")) { ok = false; } } } return ok; } /** * Check token boundaries using token information * @param r MatchResult * @param s respective Sentence * @param jcas current CAS object * @return whether or not the MatchResult is a clean one */ public static Boolean checkTokenBoundaries(MatchResult r, Sentence s, JCas jcas){ Boolean beginOK = false; Boolean endOK = false; // whole expression is marked as a sentence if ((r.end() - r.start()) == (s.getEnd() -s.getBegin())){ return true; } // Only check Token boundaries if no white-spaces in front of and behind the match-result if ((r.start() > 0) && ((s.getCoveredText().subSequence(r.start()-1, r.start()).equals(" "))) && ((r.end() < s.getCoveredText().length()) && ((s.getCoveredText().subSequence(r.end(), r.end()+1).equals(" "))))) { return true; } // other token boundaries than white-spaces else { FSIterator iterToken = jcas.getAnnotationIndex(Token.type).subiterator(s); while (iterToken.hasNext()) { Token t = (Token) iterToken.next(); // Check begin if ((r.start() + s.getBegin()) == t.getBegin()){ beginOK = true; } // Tokenizer does not split number from some symbols (".", "/", "-", "–"), // e.g., "...12 August-24 Augsut..." else if ((r.start() > 0) && ((s.getCoveredText().subSequence(r.start()-1, r.start()).equals(".")) || (s.getCoveredText().subSequence(r.start()-1, r.start()).equals("/")) || (s.getCoveredText().subSequence(r.start()-1, r.start()).equals("–")) || (s.getCoveredText().subSequence(r.start()-1, r.start()).equals("-")))) { beginOK = true; } // Check end if ((r.end() + s.getBegin()) == t.getEnd()) { endOK = true; } // Tokenizer does not split number from some symbols (".", "/", "-", "–"), // e.g., "... in 1990. New Sentence ..." else if ((r.end() < s.getCoveredText().length()) && ((s.getCoveredText().subSequence(r.end(), r.end()+1).equals(".")) || (s.getCoveredText().subSequence(r.end(), r.end()+1).equals("/")) || (s.getCoveredText().subSequence(r.end(), r.end()+1).equals("–")) || (s.getCoveredText().subSequence(r.end(), r.end()+1).equals("-")))) { endOK = true; } if (beginOK && endOK) return true; } } return false; } }
Java
package de.unihd.dbs.uima.annotator.heideltime.utilities; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import de.unihd.dbs.uima.annotator.heideltime.resources.Language; import de.unihd.dbs.uima.annotator.heideltime.resources.NormalizationManager; /** * * This class contains methods that rely on calendar functions to calculate data. * @author jannik stroetgen * */ public class DateCalculator { public static String getXNextYear(String date, Integer x){ // two formatters depending if BC or not SimpleDateFormat formatter = new SimpleDateFormat("yyyy"); SimpleDateFormat formatterBC = new SimpleDateFormat("GGyyyy"); String newDate = ""; Calendar c = Calendar.getInstance(); try { // read the original date if (date.matches("^\\d.*")){ c.setTime(formatter.parse(date)); } else{ c.setTime(formatterBC.parse(date)); } // make calucaltion c.add(Calendar.YEAR, x); c.getTime(); // check if new date is BC or AD for choosing formatter or formatterBC int newEra = c.get(Calendar.ERA); if (newEra > 0){ newDate = formatter.format(c.getTime()); } else{ newDate = formatterBC.format(c.getTime()); } } catch (ParseException e) { e.printStackTrace(); } return newDate; } public static String getXNextDecade(String date, Integer x) { date = date + "0"; // deal with years not with centuries // two formatters depending if BC or not SimpleDateFormat formatter = new SimpleDateFormat("yyyy"); SimpleDateFormat formatterBC = new SimpleDateFormat("GGyyyy"); String newDate = ""; Calendar c = Calendar.getInstance(); try { // read the original date if (date.matches("^\\d.*")){ c.setTime(formatter.parse(date)); } else{ c.setTime(formatterBC.parse(date)); } // make calucaltion c.add(Calendar.YEAR, x*10); c.getTime(); // check if new date is BC or AD for choosing formatter or formatterBC int newEra = c.get(Calendar.ERA); if (newEra > 0){ newDate = formatter.format(c.getTime()).substring(0, 3); } else{ newDate = formatterBC.format(c.getTime()).substring(0, 5); } } catch (ParseException e) { e.printStackTrace(); } return newDate; } public static String getXNextCentury(String date, Integer x) { date = date + "00"; // deal with years not with centuries int oldEra = 0; // 0 if BC date, 1 if AD date // two formatters depending if BC or not SimpleDateFormat formatter = new SimpleDateFormat("yyyy"); SimpleDateFormat formatterBC = new SimpleDateFormat("GGyyyy"); String newDate = ""; Calendar c = Calendar.getInstance(); try { // read the original date if (date.matches("^\\d.*")){ c.setTime(formatter.parse(date)); oldEra = 1; } else{ c.setTime(formatterBC.parse(date)); } // make calucaltion c.add(Calendar.YEAR, x*100); c.getTime(); // check if new date is BC or AD for choosing formatter or formatterBC int newEra = c.get(Calendar.ERA); if (newEra > 0){ if (oldEra == 0){ // -100 if from BC to AD c.add(Calendar.YEAR, -100); c.getTime(); } newDate = formatter.format(c.getTime()).substring(0, 2); } else{ if (oldEra > 0){ // +100 if from AD to BC c.add(Calendar.YEAR, 100); c.getTime(); } newDate = formatterBC.format(c.getTime()).substring(0, 4); } } catch (ParseException e) { e.printStackTrace(); } return newDate; } /** * get the x-next day of date. * * @param date given date to get new date from * @param x type of temporal event to search for * @return */ public static String getXNextDay(String date, Integer x) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String newDate = ""; Calendar c = Calendar.getInstance(); try { c.setTime(formatter.parse(date)); c.add(Calendar.DAY_OF_MONTH, x); c.getTime(); newDate = formatter.format(c.getTime()); } catch (ParseException e) { e.printStackTrace(); } return newDate; } /** * get the x-next month of date * * @param date current date * @param x amount of months to go forward * @return new month */ public static String getXNextMonth(String date, Integer x) { // two formatters depending if BC or not SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM"); SimpleDateFormat formatterBC = new SimpleDateFormat("GGyyyy-MM"); String newDate = ""; Calendar c = Calendar.getInstance(); try { // read the original date if (date.matches("^\\d.*")){ c.setTime(formatter.parse(date)); } else{ c.setTime(formatterBC.parse(date)); } // make calucaltion c.add(Calendar.MONTH, x); c.getTime(); // check if new date is BC or AD for choosing formatter or formatterBC int newEra = c.get(Calendar.ERA); if (newEra > 0){ newDate = formatter.format(c.getTime()); } else{ newDate = formatterBC.format(c.getTime()); } } catch (ParseException e) { e.printStackTrace(); } return newDate; } /** * get the x-next week of date * @param date current date * @param x amount of weeks to go forward * @return new week */ public static String getXNextWeek(String date, Integer x, Language language) { NormalizationManager nm = NormalizationManager.getInstance(language); String date_no_W = date.replace("W", ""); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-w"); String newDate = ""; Calendar c = Calendar.getInstance(); try { c.setTime(formatter.parse(date_no_W)); c.add(Calendar.WEEK_OF_YEAR, x); c.getTime(); newDate = formatter.format(c.getTime()); newDate = newDate.substring(0,4)+"-W"+nm.getFromNormNumber(newDate.substring(5)); } catch (ParseException e) { e.printStackTrace(); } return newDate; } /** * Get the weekday of date * * @param date current date * @return day of week */ public static int getWeekdayOfDate(String date) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); int weekday = 0; Calendar c = Calendar.getInstance(); try { c.setTime(formatter.parse(date)); weekday = c.get(Calendar.DAY_OF_WEEK); } catch (ParseException e) { e.printStackTrace(); } return weekday; } /** * Get the week of date * * @param date current date * @return week of year */ public static int getWeekOfDate(String date) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); int week = 0; ; Calendar c = Calendar.getInstance(); try { c.setTime(formatter.parse(date)); week = c.get(Calendar.WEEK_OF_YEAR); } catch (ParseException e) { e.printStackTrace(); } return week; } /** * takes a desired locale input string, iterates through available locales, returns a locale object * @param locale String to grab a locale for, i.e. en_US, en_GB, de_DE * @return Locale to represent the input String */ public static Locale getLocaleFromString(String locale) throws LocaleException { for(Locale l : Locale.getAvailableLocales()) { if(locale.toLowerCase().equals(l.toString().toLowerCase())) { return l; } } throw new LocaleException(); } }
Java
package de.unihd.dbs.uima.annotator.heideltime.utilities; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * The Toolbox class contains methods with functionality that you would also * find outside the context of HeidelTime's specific skillset; i.e. they do * not require the CAS context, but are 'useful code snippets'. * @author jannik stroetgen * */ public class Toolbox { /** * Find all the matches of a pattern in a charSequence and return the * results as list. * * @param pattern Pattern to be matched * @param s String to be matched against * @return Iterable List of MatchResults */ public static Iterable<MatchResult> findMatches(Pattern pattern, CharSequence s) { List<MatchResult> results = new ArrayList<MatchResult>(); for (Matcher m = pattern.matcher(s); m.find();) results.add(m.toMatchResult()); return results; } /** * Sorts a given HashMap using a custom function * @param m Map of items to sort * @return sorted List of items */ public static List<Pattern> sortByValue(final HashMap<Pattern,String> m) { List<Pattern> keys = new ArrayList<Pattern>(); keys.addAll(m.keySet()); Collections.sort(keys, new Comparator<Object>() { @SuppressWarnings({ "unchecked", "rawtypes" }) public int compare(Object o1, Object o2) { Object v1 = m.get(o1); Object v2 = m.get(o2); if (v1 == null) { return (v2 == null) ? 0 : 1; } else if (v1 instanceof Comparable) { return ((Comparable) v1).compareTo(v2); } else { return 0; } } }); return keys; } }
Java
/* * HeidelTime.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, Heidelberg University. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * author: Jannik Strötgen * email: stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.uima.annotator.heideltime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.regex.MatchResult; import java.util.regex.Pattern; import org.apache.uima.UimaContext; import org.apache.uima.analysis_component.JCasAnnotator_ImplBase; import org.apache.uima.cas.FSIterator; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import de.unihd.dbs.uima.annotator.heideltime.ProcessorManager.Priority; import de.unihd.dbs.uima.annotator.heideltime.resources.Language; import de.unihd.dbs.uima.annotator.heideltime.resources.NormalizationManager; import de.unihd.dbs.uima.annotator.heideltime.resources.RePatternManager; import de.unihd.dbs.uima.annotator.heideltime.resources.RegexHashMap; import de.unihd.dbs.uima.annotator.heideltime.resources.RuleManager; import de.unihd.dbs.uima.annotator.heideltime.utilities.DateCalculator; import de.unihd.dbs.uima.annotator.heideltime.utilities.ContextAnalyzer; import de.unihd.dbs.uima.annotator.heideltime.utilities.LocaleException; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; import de.unihd.dbs.uima.annotator.heideltime.utilities.Toolbox; import de.unihd.dbs.uima.types.heideltime.Dct; import de.unihd.dbs.uima.types.heideltime.Sentence; import de.unihd.dbs.uima.types.heideltime.Timex3; import de.unihd.dbs.uima.types.heideltime.Token; /** * HeidelTime finds temporal expressions and normalizes them according to the TIMEX3 * TimeML annotation standard. * * @author jannik stroetgen * */ public class HeidelTime extends JCasAnnotator_ImplBase { // TOOL NAME (may be used as componentId) private Class<?> component = this.getClass(); // PROCESSOR MANAGER ProcessorManager procMan = ProcessorManager.getInstance(); // COUNTER (how many timexes added to CAS? (finally) public int timex_counter = 0; public int timex_counter_global = 0; // FLAG (for historic expressions referring to BC) public Boolean flagHistoricDates = false; // COUNTER FOR TIMEX IDS private int timexID = 0; // INPUT PARAMETER HANDLING WITH UIMA private String PARAM_LANGUAGE = "Language"; // supported languages (2012-05-19): english, german, dutch, englishcoll, englishsci private String PARAM_TYPE_TO_PROCESS = "Type"; // chosen locale parameter name private String PARAM_LOCALE = "locale"; // supported types (2012-05-19): news (english, german, dutch), narrative (english, german, dutch), colloquial private Language language = Language.ENGLISH; private String typeToProcess = "news"; // INPUT PARAMETER HANDLING WITH UIMA (which types shall be extracted) private String PARAM_DATE = "Date"; private String PARAM_TIME = "Time"; private String PARAM_DURATION = "Duration"; private String PARAM_SET = "Set"; private String PARAM_DEBUG = "Debugging"; private String PARAM_GROUP = "ConvertDurations"; private Boolean find_dates = true; private Boolean find_times = true; private Boolean find_durations = true; private Boolean find_sets = true; private Boolean group_gran = true; // FOR DEBUGGING PURPOSES (IF FALSE) private Boolean deleteOverlapped = true; /** * @see AnalysisComponent#initialize(UimaContext) */ public void initialize(UimaContext aContext) throws ResourceInitializationException { super.initialize(aContext); ///////////////////////////////// // DEBUGGING PARAMETER SETTING // ///////////////////////////////// this.deleteOverlapped = true; Boolean doDebug = (Boolean) aContext.getConfigParameterValue(PARAM_DEBUG); Logger.setPrintDetails(doDebug == null ? false : doDebug); ///////////////////////////////// // HANDLE LOCALE // ///////////////////////////////// String requestedLocale = (String) aContext.getConfigParameterValue(PARAM_LOCALE); if(requestedLocale == null || requestedLocale.length() == 0) { // if the PARAM_LOCALE setting was left empty, Locale.setDefault(Locale.UK); // use a default, the ISO8601-adhering UK locale (equivalent to "en_GB") } else { // otherwise, check if the desired locale exists in the JVM's available locale repertoire try { Locale locale = DateCalculator.getLocaleFromString(requestedLocale); Locale.setDefault(locale); // sets it for the entire JVM session } catch (LocaleException e) { Logger.printError("Supplied locale parameter couldn't be resolved to a working locale. Try one of these:"); String localesString = new String(); for(Locale l : Locale.getAvailableLocales()) { // list all available locales localesString += l.toString()+" "; } Logger.printError(localesString); System.exit(-1); } } ////////////////////////////////// // GET CONFIGURATION PARAMETERS // ////////////////////////////////// language = Language.getLanguageFromString((String) aContext.getConfigParameterValue(PARAM_LANGUAGE)); typeToProcess = (String) aContext.getConfigParameterValue(PARAM_TYPE_TO_PROCESS); find_dates = (Boolean) aContext.getConfigParameterValue(PARAM_DATE); find_times = (Boolean) aContext.getConfigParameterValue(PARAM_TIME); find_durations = (Boolean) aContext.getConfigParameterValue(PARAM_DURATION); find_sets = (Boolean) aContext.getConfigParameterValue(PARAM_SET); group_gran = (Boolean) aContext.getConfigParameterValue(PARAM_GROUP); //////////////////////////////////////////////////////////// // READ NORMALIZATION RESOURCES FROM FILES AND STORE THEM // //////////////////////////////////////////////////////////// NormalizationManager.getInstance(language); ////////////////////////////////////////////////////// // READ PATTERN RESOURCES FROM FILES AND STORE THEM // ////////////////////////////////////////////////////// RePatternManager.getInstance(language); /////////////////////////////////////////////////// // READ RULE RESOURCES FROM FILES AND STORE THEM // /////////////////////////////////////////////////// RuleManager.getInstance(language); ///////////////////////////////////////////////////////////////////////////////// // SUBPROCESSOR CONFIGURATION. REGISTER YOUR OWN PROCESSORS HERE FOR EXECUTION // ///////////////////////////////////////////////////////////////////////////////// procMan.registerProcessor("de.unihd.dbs.uima.annotator.heideltime.processors.HolidayProcessor"); procMan.initializeAllProcessors(aContext); ///////////////////////////// // PRINT WHAT WILL BE DONE // ///////////////////////////// if (find_dates) Logger.printDetail("Getting Dates..."); if (find_times) Logger.printDetail("Getting Times..."); if (find_durations) Logger.printDetail("Getting Durations..."); if (find_sets) Logger.printDetail("Getting Sets..."); } /** * @see JCasAnnotator_ImplBase#process(JCas) */ public void process(JCas jcas) { // run preprocessing processors procMan.executeProcessors(jcas, Priority.PREPROCESSING); RuleManager rulem = RuleManager.getInstance(language); timexID = 1; // reset counter once per document processing timex_counter = 0; flagHistoricDates = false; //////////////////////////////////////////// // CHECK SENTENCE BY SENTENCE FOR TIMEXES // //////////////////////////////////////////// FSIterator sentIter = jcas.getAnnotationIndex(Sentence.type).iterator(); /* * check if the pipeline has annotated any sentences. if not, heideltime can't do any work, * will return from process() with a warning message. */ if(!sentIter.hasNext()) { Logger.printError(component, "HeidelTime has not found any sentence tokens in this document. " + "HeidelTime needs sentence tokens tagged by a preprocessing UIMA analysis engine to " + "do its work. Please check your UIMA workflow and add an analysis engine that creates " + "these sentence tokens."); } while (sentIter.hasNext()) { Sentence s = (Sentence) sentIter.next(); Boolean debugIteration = false; Boolean oldDebugState = Logger.getPrintDetails(); do { try { if (find_dates) { findTimexes("DATE", rulem.getHmDatePattern(), rulem.getHmDateOffset(), rulem.getHmDateNormalization(), rulem.getHmDateQuant(), s, jcas); } if (find_times) { findTimexes("TIME", rulem.getHmTimePattern(), rulem.getHmTimeOffset(), rulem.getHmTimeNormalization(), rulem.getHmTimeQuant(), s, jcas); } /* * check for historic dates/times starting with BC * to check if post-processing step is required */ if (typeToProcess.equals("narratives") || typeToProcess.equals("narratives")){ FSIterator iterDates = jcas.getAnnotationIndex(Timex3.type).iterator(); while (iterDates.hasNext()){ Timex3 t = (Timex3) iterDates.next(); if (t.getTimexValue().startsWith("BC")){ flagHistoricDates = true; break; } } } if (find_sets) { findTimexes("SET", rulem.getHmSetPattern(), rulem.getHmSetOffset(), rulem.getHmSetNormalization(), rulem.getHmSetQuant(), s, jcas); } if (find_durations) { findTimexes("DURATION", rulem.getHmDurationPattern(), rulem.getHmDurationOffset(), rulem.getHmDurationNormalization(), rulem.getHmDurationQuant(), s, jcas); } } catch(NullPointerException npe) { if(!debugIteration) { debugIteration = true; Logger.setPrintDetails(true); Logger.printError(component, "HeidelTime's execution has been interrupted by an exception that " + "is likely rooted in faulty normalization resource files. Please consider opening an issue " + "report containing the following information at our Google Code project issue tracker: " + "https://code.google.com/p/heideltime. Thanks!"); npe.printStackTrace(); Logger.printError(component, "Sentence [" + s.getBegin() + "-" + s.getEnd() + "]: " + s.getCoveredText()); Logger.printError(component, "Language: " + language); Logger.printError(component, "Re-running this sentence with DEBUGGING enabled..."); } else { debugIteration = false; Logger.setPrintDetails(oldDebugState); Logger.printError(component, "Execution will now resume."); } } } while(debugIteration); } /* * kick out some overlapping expressions */ if (deleteOverlapped == true) deleteOverlappedTimexesPreprocessing(jcas); /* * specify ambiguous values, e.g.: specific year for date values of * format UNDEF-year-01-01; specific month for values of format UNDEF-last-month */ specifyAmbiguousValues(jcas); // disambiguate historic dates // check dates without explicit hints to AD or BC if they might refer to BC dates if (flagHistoricDates) try { disambiguateHistoricDates(jcas); } catch(Exception e) { Logger.printError("Something went wrong disambiguating historic dates."); e.printStackTrace(); } /* * kick out the rest of the overlapping expressions */ if (deleteOverlapped == true) deleteOverlappedTimexesPostprocessing(jcas); // run arbitrary processors procMan.executeProcessors(jcas, Priority.ARBITRARY); // remove invalid timexes removeInvalids(jcas); // run postprocessing processors procMan.executeProcessors(jcas, Priority.POSTPROCESSING); timex_counter_global = timex_counter_global + timex_counter; Logger.printDetail(component, "Number of Timexes added to CAS: "+timex_counter + "(global: "+timex_counter_global+")"); } /** * Add timex annotation to CAS object. * * @param timexType * @param begin * @param end * @param timexValue * @param timexId * @param foundByRule * @param jcas */ public void addTimexAnnotation(String timexType, int begin, int end, Sentence sentence, String timexValue, String timexQuant, String timexFreq, String timexMod, String emptyValue, String timexId, String foundByRule, JCas jcas) { Timex3 annotation = new Timex3(jcas); annotation.setBegin(begin); annotation.setEnd(end); annotation.setFilename(sentence.getFilename()); annotation.setSentId(sentence.getSentenceId()); annotation.setEmptyValue(emptyValue); FSIterator iterToken = jcas.getAnnotationIndex(Token.type).subiterator(sentence); String allTokIds = ""; while (iterToken.hasNext()) { Token tok = (Token) iterToken.next(); if (tok.getBegin() <= begin && tok.getEnd() > begin) { annotation.setFirstTokId(tok.getTokenId()); allTokIds = "BEGIN<-->" + tok.getTokenId(); } if ((tok.getBegin() > begin) && (tok.getEnd() <= end)) { allTokIds = allTokIds + "<-->" + tok.getTokenId(); } } annotation.setAllTokIds(allTokIds); annotation.setTimexType(timexType); annotation.setTimexValue(timexValue); annotation.setTimexId(timexId); annotation.setFoundByRule(foundByRule); if ((timexType.equals("DATE")) || (timexType.equals("TIME"))) { if ((timexValue.startsWith("X")) || (timexValue.startsWith("UNDEF"))) { annotation.setFoundByRule(foundByRule+"-relative"); } else { annotation.setFoundByRule(foundByRule+"-explicit"); } } if (!(timexQuant == null)) { annotation.setTimexQuant(timexQuant); } if (!(timexFreq == null)) { annotation.setTimexFreq(timexFreq); } if (!(timexMod == null)) { annotation.setTimexMod(timexMod); } annotation.addToIndexes(); this.timex_counter++; Logger.printDetail(annotation.getTimexId()+"EXTRACTION PHASE: "+" found by:"+annotation.getFoundByRule()+" text:"+annotation.getCoveredText()); Logger.printDetail(annotation.getTimexId()+"NORMALIZATION PHASE:"+" found by:"+annotation.getFoundByRule()+" text:"+annotation.getCoveredText()+" value:"+annotation.getTimexValue()); } /** * Postprocessing: Check dates starting with "0" which were extracted without * explicit "AD" hints if it is likely that they refer to the respective date BC * * @param jcas */ public void disambiguateHistoricDates(JCas jcas){ // build up a list with all found TIMEX expressions List<Timex3> linearDates = new ArrayList<Timex3>(); FSIterator iterTimex = jcas.getAnnotationIndex(Timex3.type).iterator(); // Create List of all Timexes of types "date" and "time" while (iterTimex.hasNext()) { Timex3 timex = (Timex3) iterTimex.next(); if (timex.getTimexType().equals("DATE") || timex.getTimexType().equals("TIME")) { linearDates.add(timex); } } ////////////////////////////////////////////// // go through list of Date and Time timexes // ////////////////////////////////////////////// for (int i = 1; i < linearDates.size(); i++) { Timex3 t_i = (Timex3) linearDates.get(i); String value_i = t_i.getTimexValue(); String newValue = value_i; Boolean change = false; if (!(t_i.getFoundByRule().contains("-BCADhint"))){ if (value_i.startsWith("0")){ Integer offset = 1; do { if ((i == 1 || (i > 1 && !change)) && linearDates.get(i-offset).getTimexValue().startsWith("BC")){ if (value_i.length()>1){ if ((linearDates.get(i-offset).getTimexValue().startsWith("BC"+value_i.substring(0,2))) || (linearDates.get(i-offset).getTimexValue().startsWith("BC"+String.format("%02d",(Integer.parseInt(value_i.substring(0,2))+1))))){ if (((value_i.startsWith("00")) && (linearDates.get(i-offset).getTimexValue().startsWith("BC00"))) || ((value_i.startsWith("01")) && (linearDates.get(i-offset).getTimexValue().startsWith("BC01")))){ if ((value_i.length()>2) && (linearDates.get(i-offset).getTimexValue().length()>4)){ if (Integer.parseInt(value_i.substring(0,3)) <= Integer.parseInt(linearDates.get(i-offset).getTimexValue().substring(2,5))){ newValue = "BC" + value_i; change = true; Logger.printDetail("DisambiguateHistoricDates: "+value_i+" to "+newValue+". Expression "+t_i.getCoveredText()+" due to "+linearDates.get(i-offset).getCoveredText()); } } } else{ newValue = "BC" + value_i; change = true; Logger.printDetail("DisambiguateHistoricDates: "+value_i+" to "+newValue+". Expression "+t_i.getCoveredText()+" due to "+linearDates.get(i-offset).getCoveredText()); } } } } } while (offset++ < 5 && offset < i); } } if (!(newValue.equals(value_i))){ t_i.removeFromIndexes(); Logger.printDetail("DisambiguateHistoricDates: value changed to BC"); t_i.setTimexValue(newValue); t_i.addToIndexes(); linearDates.set(i, t_i); } } } /** * Postprocessing: Remove invalid timex expressions. These are already * marked as invalid: timexValue().equals("REMOVE") * * @param jcas */ public void removeInvalids(JCas jcas) { /* * Iterate over timexes and add invalids to HashSet * (invalids cannot be removed directly since iterator is used) */ FSIterator iterTimex = jcas.getAnnotationIndex(Timex3.type).iterator(); HashSet<Timex3> hsTimexToRemove = new HashSet<Timex3>(); while (iterTimex.hasNext()) { Timex3 timex = (Timex3) iterTimex.next(); if (timex.getTimexValue().equals("REMOVE")) { hsTimexToRemove.add(timex); } } // remove invalids, finally for (Timex3 timex3 : hsTimexToRemove) { timex3.removeFromIndexes(); this.timex_counter--; Logger.printDetail(timex3.getTimexId()+" REMOVING PHASE: "+"found by:"+timex3.getFoundByRule()+" text:"+timex3.getCoveredText()+" value:"+timex3.getTimexValue()); } } @SuppressWarnings("unused") public String specifyAmbiguousValuesString(String ambigString, Timex3 t_i, Integer i, List<Timex3> linearDates, JCas jcas) { NormalizationManager norm = NormalizationManager.getInstance(language); // ////////////////////////////////////// // IS THERE A DOCUMENT CREATION TIME? // // ////////////////////////////////////// boolean dctAvailable = false; // //////////////////////////// // DOCUMENT TYPE TO PROCESS // // ////////////////////////// boolean documentTypeNews = false; boolean documentTypeNarrative = false; boolean documentTypeColloquial = false; boolean documentTypeScientific = false; if (typeToProcess.equals("news")) { documentTypeNews = true; } if (typeToProcess.equals("narrative") || typeToProcess.equals("narratives")) { documentTypeNarrative = true; } if (typeToProcess.equals("colloquial")) { documentTypeColloquial = true; } if (typeToProcess.equals("scientific")) { documentTypeScientific = true; } // get the dct information String dctValue = ""; int dctCentury = 0; int dctYear = 0; int dctDecade = 0; int dctMonth = 0; int dctDay = 0; String dctSeason = ""; String dctQuarter = ""; String dctHalf = ""; int dctWeekday = 0; int dctWeek = 0; // //////////////////////////////////////////// // INFORMATION ABOUT DOCUMENT CREATION TIME // // //////////////////////////////////////////// FSIterator dctIter = jcas.getAnnotationIndex(Dct.type).iterator(); if (dctIter.hasNext()) { dctAvailable = true; Dct dct = (Dct) dctIter.next(); dctValue = dct.getValue(); // year, month, day as mentioned in the DCT if (dctValue.matches("\\d\\d\\d\\d\\d\\d\\d\\d")) { dctCentury = Integer.parseInt(dctValue.substring(0, 2)); dctYear = Integer.parseInt(dctValue.substring(0, 4)); dctDecade = Integer.parseInt(dctValue.substring(2, 3)); dctMonth = Integer.parseInt(dctValue.substring(4, 6)); dctDay = Integer.parseInt(dctValue.substring(6, 8)); Logger.printDetail("dctCentury:" + dctCentury); Logger.printDetail("dctYear:" + dctYear); Logger.printDetail("dctDecade:" + dctDecade); Logger.printDetail("dctMonth:" + dctMonth); Logger.printDetail("dctDay:" + dctDay); } else { dctCentury = Integer.parseInt(dctValue.substring(0, 2)); dctYear = Integer.parseInt(dctValue.substring(0, 4)); dctDecade = Integer.parseInt(dctValue.substring(2, 3)); dctMonth = Integer.parseInt(dctValue.substring(5, 7)); dctDay = Integer.parseInt(dctValue.substring(8, 10)); Logger.printDetail("dctCentury:" + dctCentury); Logger.printDetail("dctYear:" + dctYear); Logger.printDetail("dctDecade:" + dctDecade); Logger.printDetail("dctMonth:" + dctMonth); Logger.printDetail("dctDay:" + dctDay); } dctQuarter = "Q" + norm.getFromNormMonthInQuarter(norm .getFromNormNumber(dctMonth + "")); dctHalf = "H1"; if (dctMonth > 6) { dctHalf = "H2"; } // season, week, weekday, have to be calculated dctSeason = norm.getFromNormMonthInSeason(norm .getFromNormNumber(dctMonth + "") + ""); dctWeekday = DateCalculator.getWeekdayOfDate(dctYear + "-" + norm.getFromNormNumber(dctMonth + "") + "-" + norm.getFromNormNumber(dctDay + "")); dctWeek = DateCalculator.getWeekOfDate(dctYear + "-" + norm.getFromNormNumber(dctMonth + "") + "-" + norm.getFromNormNumber(dctDay + "")); Logger.printDetail("dctQuarter:" + dctQuarter); Logger.printDetail("dctSeason:" + dctSeason); Logger.printDetail("dctWeekday:" + dctWeekday); Logger.printDetail("dctWeek:" + dctWeek); } else { Logger.printDetail("No DCT available..."); } // check if value_i has month, day, season, week (otherwise no UNDEF-year is possible) Boolean viHasMonth = false; Boolean viHasDay = false; Boolean viHasSeason = false; Boolean viHasWeek = false; Boolean viHasQuarter = false; Boolean viHasHalf = false; int viThisMonth = 0; int viThisDay = 0; String viThisSeason = ""; String viThisQuarter = ""; String viThisHalf = ""; String[] valueParts = ambigString.split("-"); // check if UNDEF-year or UNDEF-century if ((ambigString.startsWith("UNDEF-year")) || (ambigString.startsWith("UNDEF-century"))) { if (valueParts.length > 2) { // get vi month if (valueParts[2].matches("\\d\\d")) { viHasMonth = true; viThisMonth = Integer.parseInt(valueParts[2]); } // get vi season else if ((valueParts[2].equals("SP")) || (valueParts[2].equals("SU")) || (valueParts[2].equals("FA")) || (valueParts[2].equals("WI"))) { viHasSeason = true; viThisSeason = valueParts[2]; } // get v1 quarter else if ((valueParts[2].equals("Q1")) || (valueParts[2].equals("Q2")) || (valueParts[2].equals("Q3")) || (valueParts[2].equals("Q4"))) { viHasQuarter = true; viThisQuarter = valueParts[2]; } // get v1 half else if ((valueParts[2].equals("H1")) || (valueParts[2].equals("H2"))) { viHasHalf = true; viThisHalf = valueParts[2]; } // get vi day if ((valueParts.length > 3) && (valueParts[3].matches("\\d\\d"))) { viHasDay = true; viThisDay = Integer.parseInt(valueParts[3]); } } } else { if (valueParts.length > 1) { // get vi month if (valueParts[1].matches("\\d\\d")) { viHasMonth = true; viThisMonth = Integer.parseInt(valueParts[1]); } // get vi season else if ((valueParts[1].equals("SP")) || (valueParts[1].equals("SU")) || (valueParts[1].equals("FA")) || (valueParts[1].equals("WI"))) { viHasSeason = true; viThisSeason = valueParts[1]; } // get v1 quarter else if ((valueParts[1].equals("Q1")) || (valueParts[1].equals("Q2")) || (valueParts[1].equals("Q3")) || (valueParts[1].equals("Q4"))) { viHasQuarter = true; viThisQuarter = valueParts[1]; } // get v1 half else if ((valueParts[1].equals("H1")) || (valueParts[1].equals("H2"))) { viHasHalf = true; viThisHalf = valueParts[1]; } // get vi day if ((valueParts.length > 2) && (valueParts[2].matches("\\d\\d"))) { viHasDay = true; viThisDay = Integer.parseInt(valueParts[2]); } } } // get the last tense (depending on the part of speech tags used in front or behind the expression) String last_used_tense = ContextAnalyzer.getLastTense(t_i, jcas, language); ////////////////////////// // DISAMBIGUATION PHASE // ////////////////////////// //////////////////////////////////////////////////// // IF YEAR IS COMPLETELY UNSPECIFIED (UNDEF-year) // //////////////////////////////////////////////////// String valueNew = ambigString; if (ambigString.startsWith("UNDEF-year")) { String newYearValue = dctYear+""; // vi has month (ignore day) if ((viHasMonth == true) && (viHasSeason == false)) { // WITH DOCUMENT CREATION TIME if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { // Tense is FUTURE if ((last_used_tense.equals("FUTURE")) || (last_used_tense.equals("PRESENTFUTURE"))) { // if dct-month is larger than vi-month, than add 1 to dct-year if (dctMonth > viThisMonth) { int intNewYear = dctYear + 1; newYearValue = intNewYear + ""; } } // Tense is PAST if ((last_used_tense.equals("PAST"))) { // if dct-month is smaller than vi month, than substrate 1 from dct-year if (dctMonth < viThisMonth) { int intNewYear = dctYear - 1; newYearValue = intNewYear + ""; } } } // WITHOUT DOCUMENT CREATION TIME else { newYearValue = ContextAnalyzer.getLastMentionedX(linearDates, i, "year", language); } } // vi has quaurter if (viHasQuarter == true) { // WITH DOCUMENT CREATION TIME if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { // Tense is FUTURE if ((last_used_tense.equals("FUTURE")) || (last_used_tense.equals("PRESENTFUTURE"))) { if (Integer.parseInt(dctQuarter.substring(1)) < Integer.parseInt(viThisQuarter.substring(1))) { int intNewYear = dctYear + 1; newYearValue = intNewYear + ""; } } // Tense is PAST if ((last_used_tense.equals("PAST"))) { if (Integer.parseInt(dctQuarter.substring(1)) < Integer.parseInt(viThisQuarter.substring(1))) { int intNewYear = dctYear - 1; newYearValue = intNewYear + ""; } } // IF NO TENSE IS FOUND if (last_used_tense.equals("")){ if (documentTypeColloquial){ // IN COLLOQUIAL: future temporal expressions if (Integer.parseInt(dctQuarter.substring(1)) < Integer.parseInt(viThisQuarter.substring(1))){ int intNewYear = dctYear + 1; newYearValue = intNewYear + ""; } } else{ // IN NEWS: past temporal expressions if (Integer.parseInt(dctQuarter.substring(1)) < Integer.parseInt(viThisQuarter.substring(1))){ int intNewYear = dctYear - 1; newYearValue = intNewYear + ""; } } } } // WITHOUT DOCUMENT CREATION TIME else { newYearValue = ContextAnalyzer.getLastMentionedX(linearDates, i, "year", language); } } // vi has half if (viHasHalf == true) { // WITH DOCUMENT CREATION TIME if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { // Tense is FUTURE if ((last_used_tense.equals("FUTURE")) || (last_used_tense.equals("PRESENTFUTURE"))) { if (Integer.parseInt(dctHalf.substring(1)) < Integer.parseInt(viThisHalf.substring(1))) { int intNewYear = dctYear + 1; newYearValue = intNewYear + ""; } } // Tense is PAST if ((last_used_tense.equals("PAST"))) { if (Integer.parseInt(dctHalf.substring(1)) < Integer.parseInt(viThisHalf.substring(1))) { int intNewYear = dctYear - 1; newYearValue = intNewYear + ""; } } // IF NO TENSE IS FOUND if (last_used_tense.equals("")){ if (documentTypeColloquial){ // IN COLLOQUIAL: future temporal expressions if (Integer.parseInt(dctHalf.substring(1)) < Integer.parseInt(viThisHalf.substring(1))){ int intNewYear = dctYear + 1; newYearValue = intNewYear + ""; } } else{ // IN NEWS: past temporal expressions if (Integer.parseInt(dctHalf.substring(1)) < Integer.parseInt(viThisHalf.substring(1))){ int intNewYear = dctYear - 1; newYearValue = intNewYear + ""; } } } } // WITHOUT DOCUMENT CREATION TIME else { newYearValue = ContextAnalyzer.getLastMentionedX(linearDates, i, "year", language); } } // vi has season if ((viHasMonth == false) && (viHasDay == false) && (viHasSeason == true)) { // TODO check tenses? // WITH DOCUMENT CREATION TIME if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { newYearValue = dctYear+""; } // WITHOUT DOCUMENT CREATION TIME else { newYearValue = ContextAnalyzer.getLastMentionedX(linearDates, i, "year", language); } } // vi has week if (viHasWeek) { // WITH DOCUMENT CREATION TIME if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { newYearValue = dctYear+""; } // WITHOUT DOCUMENT CREATION TIME else { newYearValue = ContextAnalyzer.getLastMentionedX(linearDates, i, "year", language); } } // REPLACE THE UNDEF-YEAR WITH THE NEWLY CALCULATED YEAR AND ADD TIMEX TO INDEXES if (newYearValue.equals("")) { valueNew = ambigString.replaceFirst("UNDEF-year", "XXXX"); } else { valueNew = ambigString.replaceFirst("UNDEF-year", newYearValue); } } /////////////////////////////////////////////////// // just century is unspecified (UNDEF-century86) // /////////////////////////////////////////////////// else if ((ambigString.startsWith("UNDEF-century"))) { String newCenturyValue = dctCentury+""; // NEWS and COLLOQUIAL DOCUMENTS if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable) && !ambigString.equals("UNDEF-century")) { int viThisDecade = Integer.parseInt(ambigString.substring(13, 14)); Logger.printDetail("dctCentury"+dctCentury); newCenturyValue = dctCentury+""; Logger.printDetail("dctCentury"+dctCentury); // Tense is FUTURE if ((last_used_tense.equals("FUTURE")) || (last_used_tense.equals("PRESENTFUTURE"))) { if (viThisDecade < dctDecade) { newCenturyValue = dctCentury + 1+""; } else { newCenturyValue = dctCentury+""; } } // Tense is PAST if ((last_used_tense.equals("PAST"))) { if (dctDecade < viThisDecade) { newCenturyValue = dctCentury - 1+""; } else { newCenturyValue = dctCentury+""; } } } // NARRATIVE DOCUMENTS else { newCenturyValue = ContextAnalyzer.getLastMentionedX(linearDates, i, "century", language); if (!(newCenturyValue.startsWith("BC"))){ if ((newCenturyValue.matches("^\\d\\d.*")) && (Integer.parseInt(newCenturyValue.substring(0, 2)) < 10)){ newCenturyValue = "00"; } }else{ newCenturyValue = "00"; } } if (newCenturyValue.equals("")){ if (!(documentTypeNarrative)) { // always assume that sixties, twenties, and so on are 19XX if no century found (LREC change) valueNew = ambigString.replaceFirst("UNDEF-century", "19"); } // LREC change: assume in narrative-style documents that if no other century was mentioned before, 1st century else { valueNew = ambigString.replaceFirst("UNDEF-century", "00"); } } else { valueNew = ambigString.replaceFirst("UNDEF-century", newCenturyValue); } // always assume that sixties, twenties, and so on are 19XX -- if not narrative document (LREC change) if ((valueNew.matches("\\d\\d\\d")) && (!(documentTypeNarrative))) { valueNew = "19" + valueNew.substring(2); } } //////////////////////////////////////////////////// // CHECK IMPLICIT EXPRESSIONS STARTING WITH UNDEF // //////////////////////////////////////////////////// else if (ambigString.startsWith("UNDEF")) { valueNew = ambigString; if (ambigString.matches("^UNDEF-REFDATE$")){ if (i > 0){ Timex3 anyDate = linearDates.get(i-1); String lmDate = anyDate.getTimexValue(); valueNew = lmDate; } else{ valueNew = "XXXX-XX-XX"; } ////////////////// // TO CALCULATE // ////////////////// // year to calculate } else if (ambigString.matches("^UNDEF-(this|REFUNIT|REF)-(.*?)-(MINUS|PLUS)-([0-9]+).*")) { for (MatchResult mr : Toolbox.findMatches(Pattern.compile("^(UNDEF-(this|REFUNIT|REF)-(.*?)-(MINUS|PLUS)-([0-9]+)).*"), ambigString)) { String checkUndef = mr.group(1); String ltn = mr.group(2); String unit = mr.group(3); String op = mr.group(4); int diff = Integer.parseInt(mr.group(5)); // do the processing for SCIENTIFIC documents (TPZ identification could be improved) if ((documentTypeScientific)){ String opSymbol = "-"; if (op.equals("PLUS")){ opSymbol = "+"; } if (unit.equals("year")){ String diffString = diff+""; if (diff < 10){ diffString = "000"+diff; } else if (diff < 100){ diffString = "00"+diff; } else if (diff < 1000){ diffString = "0"+diff; } valueNew = "TPZ"+opSymbol+diffString; } else if (unit.equals("month")){ String diffString = diff+""; if (diff < 10){ diffString = "0000-0"+diff; } else { diffString = "0000-"+diff; } valueNew = "TPZ"+opSymbol+diffString; } else if (unit.equals("week")){ String diffString = diff+""; if (diff < 10){ diffString = "0000-W0"+diff; } else { diffString = "0000-W"+diff; } valueNew = "TPZ"+opSymbol+diffString; } else if (unit.equals("day")){ String diffString = diff+""; if (diff < 10){ diffString = "0000-00-0"+diff; } else { diffString = "0000-00-"+diff; } valueNew = "TPZ"+opSymbol+diffString; } else if (unit.equals("hour")){ String diffString = diff+""; if (diff < 10){ diffString = "0000-00-00T0"+diff; } else { diffString = "0000-00-00T"+diff; } valueNew = "TPZ"+opSymbol+diffString; } else if (unit.equals("minute")){ String diffString = diff+""; if (diff < 10){ diffString = "0000-00-00T00:0"+diff; } else { diffString = "0000-00-00T00:"+diff; } valueNew = "TPZ"+opSymbol+diffString; } else if (unit.equals("second")){ String diffString = diff+""; if (diff < 10){ diffString = "0000-00-00T00:00:0"+diff; } else { diffString = "0000-00-00T00:00:"+diff; } valueNew = "TPZ"+opSymbol+diffString; } } else{ // check for REFUNIT (only allowed for "year") if ((ltn.equals("REFUNIT")) && (unit.equals("year"))) { String dateWithYear = ContextAnalyzer.getLastMentionedX(linearDates, i, "dateYear", language); String year = dateWithYear; if (dateWithYear.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX"); } else { if (dateWithYear.startsWith("BC")){ year = dateWithYear.substring(0,6); } else{ year = dateWithYear.substring(0,4); } if (op.equals("MINUS")) { diff = diff * (-1); } String yearNew = DateCalculator.getXNextYear(dateWithYear, diff); String rest = dateWithYear.substring(4); valueNew = valueNew.replace(checkUndef, yearNew+rest); } } // REF and this are handled here if (unit.equals("century")) { if ((documentTypeNews|documentTypeColloquial||documentTypeScientific) && (dctAvailable) && (ltn.equals("this"))) { int century = dctCentury; if (op.equals("MINUS")) { century = dctCentury - diff; } else if (op.equals("PLUS")) { century = dctCentury + diff; } valueNew = valueNew.replace(checkUndef, century+""); } else { String lmCentury = ContextAnalyzer.getLastMentionedX(linearDates, i, "century", language); if (lmCentury.equals("")) { valueNew = valueNew.replace(checkUndef, "XX"); } else { if (op.equals("MINUS")) { diff = (-1) * diff; } lmCentury = DateCalculator.getXNextCentury(lmCentury, diff); valueNew = valueNew.replace(checkUndef, lmCentury); } } } else if (unit.equals("decade")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable) && (ltn.equals("this"))) { int dctDecadeLong = Integer.parseInt(dctCentury + "" + dctDecade); int decade = dctDecadeLong; if (op.equals("MINUS")) { decade = dctDecadeLong - diff; } else if (op.equals("PLUS")) { decade = dctDecadeLong + diff; } valueNew = valueNew.replace(checkUndef, decade+"X"); } else { String lmDecade = ContextAnalyzer.getLastMentionedX(linearDates, i, "decade", language); if (lmDecade.equals("")) { valueNew = valueNew.replace(checkUndef, "XXX"); } else { if (op.equals("MINUS")) { diff = (-1) * diff; } lmDecade = DateCalculator.getXNextDecade(lmDecade, diff); valueNew = valueNew.replace(checkUndef, lmDecade); } } } else if (unit.equals("year")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable) && (ltn.equals("this"))) { int intValue = dctYear; if (op.equals("MINUS")) { intValue = dctYear - diff; } else if (op.equals("PLUS")) { intValue = dctYear + diff; } valueNew = valueNew.replace(checkUndef, intValue + ""); } else { String lmYear = ContextAnalyzer.getLastMentionedX(linearDates, i, "year", language); if (lmYear.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX"); } else { if (op.equals("MINUS")) { diff = (-1) * diff; } lmYear = DateCalculator.getXNextYear(lmYear, diff); valueNew = valueNew.replace(checkUndef, lmYear); } } // TODO BC years } else if (unit.equals("quarter")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable) && (ltn.equals("this"))) { int intYear = dctYear; int intQuarter = Integer.parseInt(dctQuarter.substring(1)); int diffQuarters = diff % 4; diff = diff - diffQuarters; int diffYears = diff / 4; if (op.equals("MINUS")) { diffQuarters = diffQuarters * (-1); diffYears = diffYears * (-1); } intYear = intYear + diffYears; intQuarter = intQuarter + diffQuarters; valueNew = valueNew.replace(checkUndef, intYear+"-Q"+intQuarter); } else { String lmQuarter = ContextAnalyzer.getLastMentionedX(linearDates, i, "quarter", language); if (lmQuarter.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX"); } else { int intYear = Integer.parseInt(lmQuarter.substring(0, 4)); int intQuarter = Integer.parseInt(lmQuarter.substring(6)); int diffQuarters = diff % 4; diff = diff - diffQuarters; int diffYears = diff / 4; if (op.equals("MINUS")) { diffQuarters = diffQuarters * (-1); diffYears = diffYears * (-1); } intYear = intYear + diffYears; intQuarter = intQuarter + diffQuarters; valueNew = valueNew.replace(checkUndef, intYear+"-Q"+intQuarter); } } } else if (unit.equals("month")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable) && (ltn.equals("this"))) { if (op.equals("MINUS")) { diff = diff * (-1); } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextMonth(dctYear + "-" + norm.getFromNormNumber(dctMonth+""), diff)); } else { String lmMonth = ContextAnalyzer.getLastMentionedX(linearDates, i, "month", language); if (lmMonth.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX"); } else { if (op.equals("MINUS")) { diff = diff * (-1); } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextMonth(lmMonth, diff)); } } } else if (unit.equals("week")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable) && (ltn.equals("this"))) { if (op.equals("MINUS")) { diff = diff * (-1); } else if (op.equals("PLUS")) { // diff = diff * 7; } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextWeek(dctYear+"-W"+norm.getFromNormNumber(dctWeek+""), diff, language)); } else { String lmDay = ContextAnalyzer.getLastMentionedX(linearDates, i, "day", language); if (lmDay.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX-XX"); } else { if (op.equals("MINUS")) { diff = diff * 7 * (-1); } else if (op.equals("PLUS")) { diff = diff * 7; } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(lmDay, diff)); } } } else if (unit.equals("day")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable) && (ltn.equals("this"))) { if (op.equals("MINUS")) { diff = diff * (-1); } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(dctYear + "-" + norm.getFromNormNumber(dctMonth+"") + "-" + dctDay, diff)); } else { String lmDay = ContextAnalyzer.getLastMentionedX(linearDates, i, "day", language); if (lmDay.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX-XX"); } else { if (op.equals("MINUS")) { diff = diff * (-1); } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(lmDay, diff)); } } } } } } // century else if (ambigString.startsWith("UNDEF-last-century")) { String checkUndef = "UNDEF-last-century"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, norm.getFromNormNumber(dctCentury - 1 +"")); } else { String lmCentury = ContextAnalyzer.getLastMentionedX(linearDates,i,"century", language); if (lmCentury.equals("")) { valueNew = valueNew.replace(checkUndef, "XX"); } else { lmCentury = DateCalculator.getXNextCentury(lmCentury, -1); valueNew = valueNew.replace(checkUndef, lmCentury); } } } else if (ambigString.startsWith("UNDEF-this-century")) { String checkUndef = "UNDEF-this-century"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, norm.getFromNormNumber(dctCentury+"")); } else { String lmCentury = ContextAnalyzer.getLastMentionedX(linearDates,i,"century", language); if (lmCentury.equals("")) { valueNew = valueNew.replace(checkUndef, "XX"); } else { valueNew = valueNew.replace(checkUndef, lmCentury); } } } else if (ambigString.startsWith("UNDEF-next-century")) { String checkUndef = "UNDEF-next-century"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, norm.getFromNormNumber(dctCentury + 1+"")); } else { String lmCentury = ContextAnalyzer.getLastMentionedX(linearDates,i,"century", language); if (lmCentury.equals("")) { valueNew = valueNew.replace(checkUndef, "XX"); } else { lmCentury = DateCalculator.getXNextCentury(lmCentury, +1); valueNew = valueNew.replace(checkUndef, lmCentury); } } } // decade else if (ambigString.startsWith("UNDEF-last-decade")) { String checkUndef = "UNDEF-last-decade"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, (dctYear - 10+"").substring(0,3)); } else { String lmDecade = ContextAnalyzer.getLastMentionedX(linearDates,i,"decade", language); if (lmDecade.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX"); } else { lmDecade = DateCalculator.getXNextDecade(lmDecade, -1); valueNew = valueNew.replace(checkUndef, lmDecade); } } } else if (ambigString.startsWith("UNDEF-this-decade")) { String checkUndef = "UNDEF-this-decade"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, (dctYear+"").substring(0,3)); } else { String lmDecade = ContextAnalyzer.getLastMentionedX(linearDates,i,"decade", language); if (lmDecade.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX"); } else { valueNew = valueNew.replace(checkUndef, lmDecade); } } } else if (ambigString.startsWith("UNDEF-next-decade")) { String checkUndef = "UNDEF-next-decade"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, (dctYear + 10+"").substring(0,3)); } else { String lmDecade = ContextAnalyzer.getLastMentionedX(linearDates,i,"decade", language); if (lmDecade.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX"); } else { lmDecade = DateCalculator.getXNextDecade(lmDecade, 1); valueNew = valueNew.replace(checkUndef, lmDecade); } } } // year else if (ambigString.startsWith("UNDEF-last-year")) { String checkUndef = "UNDEF-last-year"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, dctYear -1 +""); } else { String lmYear = ContextAnalyzer.getLastMentionedX(linearDates,i,"year", language); if (lmYear.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX"); } else { lmYear = DateCalculator.getXNextYear(lmYear, -1); valueNew = valueNew.replace(checkUndef, lmYear); } } if (valueNew.endsWith("-FY")){ valueNew = "FY" + valueNew.substring(0, Math.min(valueNew.length(), 4)); } } else if (ambigString.startsWith("UNDEF-this-year")) { String checkUndef = "UNDEF-this-year"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, dctYear +""); } else { String lmYear = ContextAnalyzer.getLastMentionedX(linearDates,i,"year", language); if (lmYear.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX"); } else { valueNew = valueNew.replace(checkUndef, lmYear); } } if (valueNew.endsWith("-FY")){ valueNew = "FY" + valueNew.substring(0, Math.min(valueNew.length(), 4)); } } else if (ambigString.startsWith("UNDEF-next-year")) { String checkUndef = "UNDEF-next-year"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, dctYear +1 +""); } else { String lmYear = ContextAnalyzer.getLastMentionedX(linearDates,i,"year", language); if (lmYear.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX"); } else { lmYear = DateCalculator.getXNextYear(lmYear, 1); valueNew = valueNew.replace(checkUndef, lmYear); } } if (valueNew.endsWith("-FY")){ valueNew = "FY" + valueNew.substring(0, Math.min(valueNew.length(), 4)); } } // month else if (ambigString.startsWith("UNDEF-last-month")) { String checkUndef = "UNDEF-last-month"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextMonth(dctYear + "-" + norm.getFromNormNumber(dctMonth+""), -1)); } else { String lmMonth = ContextAnalyzer.getLastMentionedX(linearDates,i,"month", language); if (lmMonth.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX"); } else { valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextMonth(lmMonth, -1)); } } } else if (ambigString.startsWith("UNDEF-this-month")) { String checkUndef = "UNDEF-this-month"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, dctYear + "-" + norm.getFromNormNumber(dctMonth+"")); } else { String lmMonth = ContextAnalyzer.getLastMentionedX(linearDates,i,"month", language); if (lmMonth.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX"); } else { valueNew = valueNew.replace(checkUndef, lmMonth); } } } else if (ambigString.startsWith("UNDEF-next-month")) { String checkUndef = "UNDEF-next-month"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextMonth(dctYear + "-" + norm.getFromNormNumber(dctMonth+""), 1)); } else { String lmMonth = ContextAnalyzer.getLastMentionedX(linearDates,i,"month", language); if (lmMonth.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX"); } else { valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextMonth(lmMonth, 1)); } } } // day else if (ambigString.startsWith("UNDEF-last-day")) { String checkUndef = "UNDEF-last-day"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(dctYear + "-" + norm.getFromNormNumber(dctMonth+"") + "-"+ dctDay, -1)); } else { String lmDay = ContextAnalyzer.getLastMentionedX(linearDates,i,"day", language); if (lmDay.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX-XX"); } else { valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(lmDay,-1)); } } } else if (ambigString.startsWith("UNDEF-this-day")) { String checkUndef = "UNDEF-this-day"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, dctYear + "-" + norm.getFromNormNumber(dctMonth+"") + "-"+ norm.getFromNormNumber(dctDay+"")); } else { String lmDay = ContextAnalyzer.getLastMentionedX(linearDates,i,"day", language); if (lmDay.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX-XX"); } else { valueNew = valueNew.replace(checkUndef, lmDay); } if (ambigString.equals("UNDEF-this-day")) { valueNew = "PRESENT_REF"; } } } else if (ambigString.startsWith("UNDEF-next-day")) { String checkUndef = "UNDEF-next-day"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(dctYear + "-" + norm.getFromNormNumber(dctMonth+"") + "-"+ dctDay, 1)); } else { String lmDay = ContextAnalyzer.getLastMentionedX(linearDates,i,"day", language); if (lmDay.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX-XX"); } else { valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(lmDay,1)); } } } // week else if (ambigString.startsWith("UNDEF-last-week")) { String checkUndef = "UNDEF-last-week"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextWeek(dctYear+"-W"+norm.getFromNormNumber(dctWeek+""),-1, language)); } else { String lmWeek = ContextAnalyzer.getLastMentionedX(linearDates,i,"week", language); if (lmWeek.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-WXX"); } else { valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextWeek(lmWeek,-1, language)); } } } else if (ambigString.startsWith("UNDEF-this-week")) { String checkUndef = "UNDEF-this-week"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef,dctYear+"-W"+norm.getFromNormNumber(dctWeek+"")); } else { String lmWeek = ContextAnalyzer.getLastMentionedX(linearDates,i,"week", language); if (lmWeek.equals("")) { valueNew = valueNew.replace(checkUndef,"XXXX-WXX"); } else { valueNew = valueNew.replace(checkUndef,lmWeek); } } } else if (ambigString.startsWith("UNDEF-next-week")) { String checkUndef = "UNDEF-next-week"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextWeek(dctYear+"-W"+norm.getFromNormNumber(dctWeek+""),1, language)); } else { String lmWeek = ContextAnalyzer.getLastMentionedX(linearDates,i,"week", language); if (lmWeek.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-WXX"); } else { valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextWeek(lmWeek,1, language)); } } } // quarter else if (ambigString.startsWith("UNDEF-last-quarter")) { String checkUndef = "UNDEF-last-quarter"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { if (dctQuarter.equals("Q1")) { valueNew = valueNew.replace(checkUndef, dctYear-1+"-Q4"); } else { int newQuarter = Integer.parseInt(dctQuarter.substring(1,2))-1; valueNew = valueNew.replace(checkUndef, dctYear+"-Q"+newQuarter); } } else { String lmQuarter = ContextAnalyzer.getLastMentionedX(linearDates, i, "quarter", language); if (lmQuarter.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-QX"); } else { int lmQuarterOnly = Integer.parseInt(lmQuarter.substring(6,7)); int lmYearOnly = Integer.parseInt(lmQuarter.substring(0,4)); if (lmQuarterOnly == 1) { valueNew = valueNew.replace(checkUndef, lmYearOnly-1+"-Q4"); } else { int newQuarter = lmQuarterOnly-1; valueNew = valueNew.replace(checkUndef, lmYearOnly+"-Q"+newQuarter); } } } } else if (ambigString.startsWith("UNDEF-this-quarter")) { String checkUndef = "UNDEF-this-quarter"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, dctYear+"-"+dctQuarter); } else { String lmQuarter = ContextAnalyzer.getLastMentionedX(linearDates, i, "quarter", language); if (lmQuarter.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-QX"); } else { valueNew = valueNew.replace(checkUndef, lmQuarter); } } } else if (ambigString.startsWith("UNDEF-next-quarter")) { String checkUndef = "UNDEF-next-quarter"; if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { if (dctQuarter.equals("Q4")) { valueNew = valueNew.replace(checkUndef, dctYear+1+"-Q1"); } else { int newQuarter = Integer.parseInt(dctQuarter.substring(1,2))+1; valueNew = valueNew.replace(checkUndef, dctYear+"-Q"+newQuarter); } } else { String lmQuarter = ContextAnalyzer.getLastMentionedX(linearDates, i, "quarter", language); if (lmQuarter.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-QX"); } else { int lmQuarterOnly = Integer.parseInt(lmQuarter.substring(6,7)); int lmYearOnly = Integer.parseInt(lmQuarter.substring(0,4)); if (lmQuarterOnly == 4) { valueNew = valueNew.replace(checkUndef, lmYearOnly+1+"-Q1"); } else { int newQuarter = lmQuarterOnly+1; valueNew = valueNew.replace(checkUndef, dctYear+"-Q"+newQuarter); } } } } // MONTH NAMES else if (ambigString.matches("UNDEF-(last|this|next)-(january|february|march|april|may|june|july|august|september|october|november|december).*")) { for (MatchResult mr : Toolbox.findMatches(Pattern.compile("(UNDEF-(last|this|next)-(january|february|march|april|may|june|july|august|september|october|november|december))(.*)"),ambigString)) { String rest = mr.group(4); int day = 0; for (MatchResult mr_rest : Toolbox.findMatches(Pattern.compile("-([0-9][0-9])"),rest)){ day = Integer.parseInt(mr_rest.group(1)); } String checkUndef = mr.group(1); String ltn = mr.group(2); String newMonth = norm.getFromNormMonthName((mr.group(3))); int newMonthInt = Integer.parseInt(newMonth); if (ltn.equals("last")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { // check day if dct-month and newMonth are equal if ((dctMonth == newMonthInt) && (!(day == 0))){ if (dctDay > day){ valueNew = valueNew.replace(checkUndef, dctYear+"-"+newMonth); } else{ valueNew = valueNew.replace(checkUndef, dctYear-1+"-"+newMonth); } } else if (dctMonth <= newMonthInt) { valueNew = valueNew.replace(checkUndef, dctYear-1+"-"+newMonth); } else { valueNew = valueNew.replace(checkUndef, dctYear+"-"+newMonth); } } else { String lmMonth = ContextAnalyzer.getLastMentionedX(linearDates, i, "month-with-details", language); if (lmMonth.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX"); } else { int lmMonthInt = Integer.parseInt(lmMonth.substring(5,7)); // int lmDayInt = 0; if ((lmMonth.length() > 9) && (lmMonth.subSequence(8,10).toString().matches("\\d\\d"))){ lmDayInt = Integer.parseInt(lmMonth.subSequence(8,10)+""); } if ((lmMonthInt == newMonthInt) && (!(lmDayInt == 0)) && (!(day == 0))){ if (lmDayInt > day){ valueNew = valueNew.replace(checkUndef, lmMonth.substring(0,4)+"-"+newMonth); } else{ valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmMonth.substring(0,4))-1+"-"+newMonth); } } if (lmMonthInt <= newMonthInt) { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmMonth.substring(0,4))-1+"-"+newMonth); } else { valueNew = valueNew.replace(checkUndef, lmMonth.substring(0,4)+"-"+newMonth); } } } } else if (ltn.equals("this")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { valueNew = valueNew.replace(checkUndef, dctYear+"-"+newMonth); } else { String lmMonth = ContextAnalyzer.getLastMentionedX(linearDates, i, "month-with-details", language); if (lmMonth.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX"); } else { valueNew = valueNew.replace(checkUndef, lmMonth.substring(0,4)+"-"+newMonth); } } } else if (ltn.equals("next")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { // check day if dct-month and newMonth are equal if ((dctMonth == newMonthInt) && (!(day == 0))){ if (dctDay < day){ valueNew = valueNew.replace(checkUndef, dctYear+"-"+newMonth); } else{ valueNew = valueNew.replace(checkUndef, dctYear+1+"-"+newMonth); } } else if (dctMonth >= newMonthInt) { valueNew = valueNew.replace(checkUndef, dctYear+1+"-"+newMonth); } else { valueNew = valueNew.replace(checkUndef, dctYear+"-"+newMonth); } } else { String lmMonth = ContextAnalyzer.getLastMentionedX(linearDates, i, "month-with-details", language); if (lmMonth.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX"); } else { int lmMonthInt = Integer.parseInt(lmMonth.substring(5,7)); if (lmMonthInt >= newMonthInt) { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmMonth.substring(0,4))+1+"-"+newMonth); } else { valueNew = valueNew.replace(checkUndef, lmMonth.substring(0,4)+"-"+newMonth); } } } } } } // SEASONS NAMES else if (ambigString.matches("^UNDEF-(last|this|next)-(SP|SU|FA|WI).*")) { for (MatchResult mr : Toolbox.findMatches(Pattern.compile("(UNDEF-(last|this|next)-(SP|SU|FA|WI)).*"),ambigString)) { String checkUndef = mr.group(1); String ltn = mr.group(2); String newSeason = mr.group(3); if (ltn.equals("last")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { if (dctSeason.equals("SP")) { valueNew = valueNew.replace(checkUndef, dctYear-1+"-"+newSeason); } else if (dctSeason.equals("SU")) { if (newSeason.equals("SP")) { valueNew = valueNew.replace(checkUndef, dctYear+"-"+newSeason); } else { valueNew = valueNew.replace(checkUndef, dctYear-1+"-"+newSeason); } } else if (dctSeason.equals("FA")) { if ((newSeason.equals("SP")) || (newSeason.equals("SU"))) { valueNew = valueNew.replace(checkUndef, dctYear+"-"+newSeason); } else { valueNew = valueNew.replace(checkUndef, dctYear-1+"-"+newSeason); } } else if (dctSeason.equals("WI")) { if (newSeason.equals("WI")) { valueNew = valueNew.replace(checkUndef, dctYear-1+"-"+newSeason); } else { if (dctMonth < 12){ valueNew = valueNew.replace(checkUndef, dctYear-1+"-"+newSeason); } else{ valueNew = valueNew.replace(checkUndef, dctYear+"-"+newSeason); } } } } else { // NARRATVIE DOCUMENT String lmSeason = ContextAnalyzer.getLastMentionedX(linearDates, i, "season", language); if (lmSeason.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX"); } else { if (lmSeason.substring(5,7).equals("SP")) { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))-1+"-"+newSeason); } else if (lmSeason.substring(5,7).equals("SU")) { if (lmSeason.substring(5,7).equals("SP")) { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))+"-"+newSeason); } else { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))-1+"-"+newSeason); } } else if (lmSeason.substring(5,7).equals("FA")) { if ((newSeason.equals("SP")) || (newSeason.equals("SU"))) { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))+"-"+newSeason); } else { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))-1+"-"+newSeason); } } else if (lmSeason.substring(5,7).equals("WI")) { if (newSeason.equals("WI")) { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))-1+"-"+newSeason); } else { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))+"-"+newSeason); } } } } } else if (ltn.equals("this")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { // TODO include tense of sentence? valueNew = valueNew.replace(checkUndef, dctYear+"-"+newSeason); } else { // TODO include tense of sentence? String lmSeason = ContextAnalyzer.getLastMentionedX(linearDates, i, "season", language); if (lmSeason.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX"); } else { valueNew = valueNew.replace(checkUndef, lmSeason.substring(0,4)+"-"+newSeason); } } } else if (ltn.equals("next")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { if (dctSeason.equals("SP")) { if (newSeason.equals("SP")) { valueNew = valueNew.replace(checkUndef, dctYear+1+"-"+newSeason); } else { valueNew = valueNew.replace(checkUndef, dctYear+"-"+newSeason); } } else if (dctSeason.equals("SU")) { if ((newSeason.equals("SP")) || (newSeason.equals("SU"))) { valueNew = valueNew.replace(checkUndef, dctYear+1+"-"+newSeason); } else { valueNew = valueNew.replace(checkUndef, dctYear+"-"+newSeason); } } else if (dctSeason.equals("FA")) { if (newSeason.equals("WI")) { valueNew = valueNew.replace(checkUndef, dctYear+"-"+newSeason); } else { valueNew = valueNew.replace(checkUndef, dctYear+1+"-"+newSeason); } } else if (dctSeason.equals("WI")) { valueNew = valueNew.replace(checkUndef, dctYear+1+"-"+newSeason); } } else { // NARRATIVE DOCUMENT String lmSeason = ContextAnalyzer.getLastMentionedX(linearDates, i, "season", language); if (lmSeason.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX"); } else { if (lmSeason.substring(5,7).equals("SP")) { if (newSeason.equals("SP")) { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))+1+"-"+newSeason); } else { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))+"-"+newSeason); } } else if (lmSeason.substring(5,7).equals("SU")) { if ((newSeason.equals("SP")) || (newSeason.equals("SU"))) { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))+1+"-"+newSeason); } else { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))+"-"+newSeason); } } else if (lmSeason.substring(5,7).equals("FA")) { if (newSeason.equals("WI")) { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))+"-"+newSeason); } else { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))+1+"-"+newSeason); } } else if (lmSeason.substring(5,7).equals("WI")) { valueNew = valueNew.replace(checkUndef, Integer.parseInt(lmSeason.substring(0,4))+1+"-"+newSeason); } } } } } } // WEEKDAY NAMES // TODO the calculation is strange, but works // TODO tense should be included?! else if (ambigString.matches("^UNDEF-(last|this|next|day)-(monday|tuesday|wednesday|thursday|friday|saturday|sunday).*")) { for (MatchResult mr : Toolbox.findMatches(Pattern.compile("(UNDEF-(last|this|next|day)-(monday|tuesday|wednesday|thursday|friday|saturday|sunday)).*"),ambigString)) { String checkUndef = mr.group(1); String ltnd = mr.group(2); String newWeekday = mr.group(3); int newWeekdayInt = Integer.parseInt(norm.getFromNormDayInWeek(newWeekday)); if (ltnd.equals("last")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { int diff = (-1) * (dctWeekday - newWeekdayInt); if (diff >= 0) { diff = diff - 7; } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(dctYear + "-" + dctMonth + "-" + dctDay, diff)); } else { String lmDay = ContextAnalyzer.getLastMentionedX(linearDates, i, "day", language); if (lmDay.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX-XX"); } else { int lmWeekdayInt = DateCalculator.getWeekdayOfDate(lmDay); int diff = (-1) * (lmWeekdayInt - newWeekdayInt); if (diff >= 0) { diff = diff - 7; } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(lmDay, diff)); } } } else if (ltnd.equals("this")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { // TODO tense should be included?! int diff = (-1) * (dctWeekday - newWeekdayInt); if (diff >= 0) { diff = diff - 7; } if (diff == -7) { diff = 0; } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(dctYear + "-" + dctMonth + "-"+ dctDay, diff)); } else { // TODO tense should be included?! String lmDay = ContextAnalyzer.getLastMentionedX(linearDates, i, "day", language); if (lmDay.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX-XX"); } else { int lmWeekdayInt = DateCalculator.getWeekdayOfDate(lmDay); int diff = (-1) * (lmWeekdayInt - newWeekdayInt); if (diff >= 0) { diff = diff - 7; } if (diff == -7) { diff = 0; } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(lmDay, diff)); } } } else if (ltnd.equals("next")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { int diff = newWeekdayInt - dctWeekday; if (diff <= 0) { diff = diff + 7; } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(dctYear + "-" + dctMonth + "-"+ dctDay, diff)); } else { String lmDay = ContextAnalyzer.getLastMentionedX(linearDates, i, "day", language); if (lmDay.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX-XX"); } else { int lmWeekdayInt = DateCalculator.getWeekdayOfDate(lmDay); int diff = newWeekdayInt - lmWeekdayInt; if (diff <= 0) { diff = diff + 7; } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(lmDay, diff)); } } } else if (ltnd.equals("day")) { if ((documentTypeNews||documentTypeColloquial||documentTypeScientific) && (dctAvailable)) { // TODO tense should be included?! int diff = (-1) * (dctWeekday - newWeekdayInt); if (diff >= 0) { diff = diff - 7; } if (diff == -7) { diff = 0; } // Tense is FUTURE if ((last_used_tense.equals("FUTURE")) && diff != 0) { diff = diff + 7; } // Tense is PAST if ((last_used_tense.equals("PAST"))) { } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(dctYear + "-" + dctMonth + "-"+ dctDay, diff)); } else { // TODO tense should be included?! String lmDay = ContextAnalyzer.getLastMentionedX(linearDates, i, "day", language); if (lmDay.equals("")) { valueNew = valueNew.replace(checkUndef, "XXXX-XX-XX"); } else { int lmWeekdayInt = DateCalculator.getWeekdayOfDate(lmDay); int diff = (-1) * (lmWeekdayInt - newWeekdayInt); if (diff >= 0) { diff = diff - 7; } if (diff == -7) { diff = 0; } valueNew = valueNew.replace(checkUndef, DateCalculator.getXNextDay(lmDay, diff)); } } } } } else { Logger.printDetail(component, "ATTENTION: UNDEF value for: " + valueNew+" is not handled in disambiguation phase!"); } } return valueNew; } /** * Under-specified values are disambiguated here. Only Timexes of types "date" and "time" can be under-specified. * @param jcas */ public void specifyAmbiguousValues(JCas jcas) { // build up a list with all found TIMEX expressions List<Timex3> linearDates = new ArrayList<Timex3>(); FSIterator iterTimex = jcas.getAnnotationIndex(Timex3.type).iterator(); // Create List of all Timexes of types "date" and "time" while (iterTimex.hasNext()) { Timex3 timex = (Timex3) iterTimex.next(); if (timex.getTimexType().equals("DATE") || timex.getTimexType().equals("TIME")) { linearDates.add(timex); } if(timex.getTimexType().equals("DURATION") && !timex.getEmptyValue().equals("")) { linearDates.add(timex); } } ////////////////////////////////////////////// // go through list of Date and Time timexes // ////////////////////////////////////////////// for (int i = 0; i < linearDates.size(); i++) { Timex3 t_i = (Timex3) linearDates.get(i); String value_i = t_i.getTimexValue(); String valueNew = value_i; // handle the value attribute only if we have a TIME or DATE if(t_i.getTimexType().equals("TIME") || t_i.getTimexType().equals("DATE")) valueNew = specifyAmbiguousValuesString(value_i, t_i, i, linearDates, jcas); // handle the emptyValue attribute for any type if(t_i.getEmptyValue() != null && t_i.getEmptyValue().length() > 0) { String emptyValueNew = specifyAmbiguousValuesString(t_i.getEmptyValue(), t_i, i, linearDates, jcas); t_i.setEmptyValue(emptyValueNew); } t_i.removeFromIndexes(); Logger.printDetail(t_i.getTimexId()+" DISAMBIGUATION PHASE: foundBy:"+t_i.getFoundByRule()+" text:"+t_i.getCoveredText()+" value:"+t_i.getTimexValue()+" NEW value:"+valueNew); t_i.setTimexValue(valueNew); t_i.addToIndexes(); linearDates.set(i, t_i); } } /** * @param jcas */ private void deleteOverlappedTimexesPreprocessing(JCas jcas) { FSIterator timexIter1 = jcas.getAnnotationIndex(Timex3.type).iterator(); HashSet<Timex3> hsTimexesToRemove = new HashSet<Timex3>(); while (timexIter1.hasNext()) { Timex3 t1 = (Timex3) timexIter1.next(); FSIterator timexIter2 = jcas.getAnnotationIndex(Timex3.type).iterator(); while (timexIter2.hasNext()) { Timex3 t2 = (Timex3) timexIter2.next(); if (((t1.getBegin() >= t2.getBegin()) && (t1.getEnd() < t2.getEnd())) || // t1 starts inside or with t2 and ends before t2 -> remove t1 ((t1.getBegin() > t2.getBegin()) && (t1.getEnd() <= t2.getEnd()))) { // t1 starts inside t2 and ends with or before t2 -> remove t1 hsTimexesToRemove.add(t1); } else if (((t2.getBegin() >= t1.getBegin()) && (t2.getEnd() < t1.getEnd())) || // t2 starts inside or with t1 and ends before t1 -> remove t2 ((t2.getBegin() > t1.getBegin()) && (t2.getEnd() <= t1.getEnd()))) { // t2 starts inside t1 and ends with or before t1 -> remove t2 hsTimexesToRemove.add(t2); } // identical length if ((t1.getBegin() == t2.getBegin()) && (t1.getEnd() == t2.getEnd())) { if ((t1.getTimexType().equals("SET")) || (t2.getTimexType().equals("SET"))) { // REMOVE REAL DUPLICATES (the one with the lower timexID) if ((Integer.parseInt(t1.getTimexId().substring(1)) < Integer.parseInt(t2.getTimexId().substring(1)))) { hsTimexesToRemove.add(t1); } } else { if (!(t1.equals(t2))) { if ((t1.getTimexValue().startsWith("UNDEF")) && (!(t2.getTimexValue().startsWith("UNDEF")))) { hsTimexesToRemove.add(t1); } else if ((!(t1.getTimexValue().startsWith("UNDEF"))) && (t2.getTimexValue().startsWith("UNDEF"))) { hsTimexesToRemove.add(t2); } // t1 is explicit, but t2 is not else if ((t1.getFoundByRule().endsWith("explicit")) && (!(t2.getFoundByRule().endsWith("explicit")))) { hsTimexesToRemove.add(t2); } // remove timexes that are identical, but one has an emptyvalue else if(t2.getEmptyValue().equals("") && !t1.getEmptyValue().equals("")) { hsTimexesToRemove.add(t2); } // REMOVE REAL DUPLICATES (the one with the lower timexID) else if ((Integer.parseInt(t1.getTimexId().substring(1)) < Integer.parseInt(t2.getTimexId().substring(1)))) { hsTimexesToRemove.add(t1); } } } } } } // remove, finally for (Timex3 t : hsTimexesToRemove) { Logger.printDetail("REMOVE DUPLICATE: " + t.getCoveredText()+"(id:"+t.getTimexId()+" value:"+t.getTimexValue()+" found by:"+t.getFoundByRule()+")"); t.removeFromIndexes(); timex_counter--; } } private void deleteOverlappedTimexesPostprocessing(JCas jcas) { FSIterator timexIter = jcas.getAnnotationIndex(Timex3.type).iterator(); FSIterator innerTimexIter = timexIter.copy(); HashSet<ArrayList<Timex3>> effectivelyToInspect = new HashSet<ArrayList<Timex3>>(); ArrayList<Timex3> allTimexesToInspect = new ArrayList<Timex3>(); while(timexIter.hasNext()) { Timex3 myTimex = (Timex3) timexIter.next(); ArrayList<Timex3> timexSet = new ArrayList<Timex3>(); timexSet.add(myTimex); // compare this timex to all other timexes and mark those that have an overlap while(innerTimexIter.hasNext()) { Timex3 myInnerTimex = (Timex3) innerTimexIter.next(); if((myTimex.getBegin() <= myInnerTimex.getBegin() && myTimex.getEnd() > myInnerTimex.getBegin()) || // timex1 starts, timex2 is partial overlap (myInnerTimex.getBegin() <= myTimex.getBegin() && myInnerTimex.getEnd() > myTimex.getBegin()) || // same as above, but in reverse (myInnerTimex.getBegin() <= myTimex.getBegin() && myTimex.getEnd() <= myInnerTimex.getEnd()) || // timex 1 is contained within or identical to timex2 (myTimex.getBegin() <= myInnerTimex.getBegin() && myInnerTimex.getEnd() <= myTimex.getEnd())) { // same as above, but in reverse timexSet.add(myInnerTimex); // increase the set allTimexesToInspect.add(myTimex); // note that these timexes are being looked at allTimexesToInspect.add(myInnerTimex); } } // if overlaps with myTimex were detected, memorize them if(timexSet.size() > 1) effectivelyToInspect.add(timexSet); // reset the inner iterator innerTimexIter.moveToFirst(); } /* prune those sets of overlapping timexes that are subsets of others * (i.e. leave only the largest union of overlapping timexes) */ HashSet<ArrayList<Timex3>> newEffectivelyToInspect = new HashSet<ArrayList<Timex3>>(); for(Timex3 t : allTimexesToInspect) { ArrayList<Timex3> setToKeep = new ArrayList<Timex3>(); // determine the largest set that contains this timex for(ArrayList<Timex3> tSet : effectivelyToInspect) { if(tSet.contains(t) && tSet.size() > setToKeep.size()) setToKeep = tSet; } newEffectivelyToInspect.add(setToKeep); } // overwrite previous list of sets effectivelyToInspect = newEffectivelyToInspect; // iterate over the selected sets and merge information, remove old timexes for(ArrayList<Timex3> tSet : effectivelyToInspect) { Timex3 newTimex = new Timex3(jcas); // if a timex has the timex value REMOVE, remove it from consideration @SuppressWarnings("unchecked") ArrayList<Timex3> newTSet = (ArrayList<Timex3>) tSet.clone(); for(Timex3 t : tSet) { if(t.getTimexValue().equals("REMOVE")) { // remove timexes with value "REMOVE" newTSet.remove(t); } } tSet = newTSet; // iteration is done if all the timexes have been removed, i.e. the set is empty if(tSet.size() == 0) continue; /* * check * - whether all timexes of this set have the same timex type attribute, * - which one in the set has the longest value attribute string length, * - what the combined extents are */ Boolean allSameTypes = true; String timexType = null; Timex3 longestTimex = null; Integer combinedBegin = Integer.MAX_VALUE, combinedEnd = Integer.MIN_VALUE; ArrayList<Integer> tokenIds = new ArrayList<Integer>(); for(Timex3 t : tSet) { // check whether the types are identical and either all DATE or TIME if(timexType == null) { timexType = t.getTimexType(); } else { if(allSameTypes && !timexType.equals(t.getTimexType()) || !(timexType.equals("DATE") || timexType.equals("TIME"))) { allSameTypes = false; } } Logger.printDetail("Are these overlapping timexes of same type? => " + allSameTypes); // check timex value attribute string length if(longestTimex == null) { longestTimex = t; } else if(allSameTypes && t.getFoundByRule().indexOf("-BCADhint") != -1) { longestTimex = t; } else if(allSameTypes && t.getFoundByRule().indexOf("relative") == -1 && longestTimex.getFoundByRule().indexOf("relative") != -1) { longestTimex = t; } else if(longestTimex.getTimexValue().length() == t.getTimexValue().length()) { if(t.getBegin() < longestTimex.getBegin()) longestTimex = t; } else if(longestTimex.getTimexValue().length() < t.getTimexValue().length()) { longestTimex = t; } Logger.printDetail("Selected " + longestTimex.getTimexId() + ": " + longestTimex.getCoveredText() + "[" + longestTimex.getTimexValue() + "] as the longest-valued timex."); // check combined beginning/end if(combinedBegin > t.getBegin()) combinedBegin = t.getBegin(); if(combinedEnd < t.getEnd()) combinedEnd = t.getEnd(); Logger.printDetail("Selected combined constraints: " + combinedBegin + ":" + combinedEnd); // disassemble and remember the token ids String[] tokenizedTokenIds = t.getAllTokIds().split("<-->"); for(Integer i = 1; i < tokenizedTokenIds.length; i++) { if(!tokenIds.contains(Integer.parseInt(tokenizedTokenIds[i]))) { tokenIds.add(Integer.parseInt(tokenizedTokenIds[i])); } } } /* types are equal => merge constraints, use the longer, "more granular" value. * if types are not equal, just take the longest value. */ Collections.sort(tokenIds); newTimex = longestTimex; if(allSameTypes) { newTimex.setBegin(combinedBegin); newTimex.setEnd(combinedEnd); if(tokenIds.size() > 0) newTimex.setFirstTokId(tokenIds.get(0)); String tokenIdText = "BEGIN"; for(Integer tokenId : tokenIds) { tokenIdText += "<-->" + tokenId; } newTimex.setAllTokIds(tokenIdText); } // remove old overlaps. for(Timex3 t : tSet) { t.removeFromIndexes(); } // add the single constructed/chosen timex to the indexes. newTimex.addToIndexes(); } } /** * Identify the part of speech (POS) of a MarchResult. * @param tokBegin * @param tokEnd * @param s * @param jcas * @return */ public String getPosFromMatchResult(int tokBegin, int tokEnd, Sentence s, JCas jcas) { // get all tokens in sentence HashMap<Integer, Token> hmTokens = new HashMap<Integer, Token>(); FSIterator iterTok = jcas.getAnnotationIndex(Token.type).subiterator(s); while (iterTok.hasNext()) { Token token = (Token) iterTok.next(); hmTokens.put(token.getBegin(), token); } // get correct token String pos = ""; if (hmTokens.containsKey(tokBegin)) { Token tokenToCheck = hmTokens.get(tokBegin); pos = tokenToCheck.getPos(); } return pos; } /** * Apply the extraction rules, normalization rules * @param timexType * @param hmPattern * @param hmOffset * @param hmNormalization * @param hmQuant * @param s * @param jcas */ public void findTimexes(String timexType, HashMap<Pattern, String> hmPattern, HashMap<String, String> hmOffset, HashMap<String, String> hmNormalization, HashMap<String, String> hmQuant, Sentence s, JCas jcas) { RuleManager rm = RuleManager.getInstance(language); HashMap<String, String> hmDatePosConstraint = rm.getHmDatePosConstraint(); HashMap<String, String> hmDurationPosConstraint = rm.getHmDurationPosConstraint(); HashMap<String, String> hmTimePosConstraint = rm.getHmTimePosConstraint(); HashMap<String, String> hmSetPosConstraint = rm.getHmSetPosConstraint(); // Iterator over the rules by sorted by the name of the rules // this is important since later, the timexId will be used to // decide which of two expressions shall be removed if both // have the same offset for (Iterator<Pattern> i = Toolbox.sortByValue(hmPattern).iterator(); i.hasNext(); ) { Pattern p = (Pattern) i.next(); for (MatchResult r : Toolbox.findMatches(p, s.getCoveredText())) { boolean infrontBehindOK = ContextAnalyzer.checkTokenBoundaries(r, s, jcas) // improved token boundary checking && ContextAnalyzer.checkInfrontBehind(r, s); boolean posConstraintOK = true; // CHECK POS CONSTRAINTS if (timexType.equals("DATE")) { if (hmDatePosConstraint.containsKey(hmPattern.get(p))) { posConstraintOK = checkPosConstraint(s , hmDatePosConstraint.get(hmPattern.get(p)), r, jcas); } } else if (timexType.equals("DURATION")) { if (hmDurationPosConstraint.containsKey(hmPattern.get(p))) { posConstraintOK = checkPosConstraint(s , hmDurationPosConstraint.get(hmPattern.get(p)), r, jcas); } } else if (timexType.equals("TIME")) { if (hmTimePosConstraint.containsKey(hmPattern.get(p))) { posConstraintOK = checkPosConstraint(s , hmTimePosConstraint.get(hmPattern.get(p)), r, jcas); } } else if (timexType.equals("SET")) { if (hmSetPosConstraint.containsKey(hmPattern.get(p))) { posConstraintOK = checkPosConstraint(s , hmSetPosConstraint.get(hmPattern.get(p)), r, jcas); } } if ((infrontBehindOK == true) && (posConstraintOK == true)) { // Offset of timex expression (in the checked sentence) int timexStart = r.start(); int timexEnd = r.end(); // Normalization from Files: // Any offset parameter? if (hmOffset.containsKey(hmPattern.get(p))) { String offset = hmOffset.get(hmPattern.get(p)); // pattern for offset information Pattern paOffset = Pattern.compile("group\\(([0-9]+)\\)-group\\(([0-9]+)\\)"); for (MatchResult mr : Toolbox.findMatches(paOffset,offset)) { int startOffset = Integer.parseInt(mr.group(1)); int endOffset = Integer.parseInt(mr.group(2)); timexStart = r.start(startOffset); timexEnd = r.end(endOffset); } } // Normalization Parameter if (hmNormalization.containsKey(hmPattern.get(p))) { String[] attributes = new String[5]; if (timexType.equals("DATE")) { attributes = getAttributesForTimexFromFile(hmPattern.get(p), rm.getHmDateNormalization(), rm.getHmDateQuant(), rm.getHmDateFreq(), rm.getHmDateMod(), rm.getHmDateEmptyValue(), r, jcas); } else if (timexType.equals("DURATION")) { attributes = getAttributesForTimexFromFile(hmPattern.get(p), rm.getHmDurationNormalization(), rm.getHmDurationQuant(), rm.getHmDurationFreq(), rm.getHmDurationMod(), rm.getHmDurationEmptyValue(), r, jcas); } else if (timexType.equals("TIME")) { attributes = getAttributesForTimexFromFile(hmPattern.get(p), rm.getHmTimeNormalization(), rm.getHmTimeQuant(), rm.getHmTimeFreq(), rm.getHmTimeMod(), rm.getHmTimeEmptyValue(), r, jcas); } else if (timexType.equals("SET")) { attributes = getAttributesForTimexFromFile(hmPattern.get(p), rm.getHmSetNormalization(), rm.getHmSetQuant(), rm.getHmSetFreq(), rm.getHmSetMod(), rm.getHmSetEmptyValue(), r, jcas); } addTimexAnnotation(timexType, timexStart + s.getBegin(), timexEnd + s.getBegin(), s, attributes[0], attributes[1], attributes[2], attributes[3], attributes[4], "t" + timexID++, hmPattern.get(p), jcas); } else { Logger.printError("SOMETHING REALLY WRONG HERE: "+hmPattern.get(p)); } } } } } /** * Check whether the part of speech constraint defined in a rule is satisfied. * @param s * @param posConstraint * @param m * @param jcas * @return */ public boolean checkPosConstraint(Sentence s, String posConstraint, MatchResult m, JCas jcas) { Pattern paConstraint = Pattern.compile("group\\(([0-9]+)\\):(.*?):"); for (MatchResult mr : Toolbox.findMatches(paConstraint,posConstraint)) { int groupNumber = Integer.parseInt(mr.group(1)); int tokenBegin = s.getBegin() + m.start(groupNumber); int tokenEnd = s.getBegin() + m.end(groupNumber); String pos = mr.group(2); String pos_as_is = getPosFromMatchResult(tokenBegin, tokenEnd ,s, jcas); if (pos.equals(pos_as_is)) { Logger.printDetail("POS CONSTRAINT IS VALID: pos should be "+pos+" and is "+pos_as_is); } else { return false; } } return true; } public String applyRuleFunctions(String tonormalize, MatchResult m) { NormalizationManager norm = NormalizationManager.getInstance(language); String normalized = ""; // pattern for normalization functions + group information // pattern for group information Pattern paNorm = Pattern.compile("%([A-Za-z0-9]+?)\\(group\\(([0-9]+)\\)\\)"); Pattern paGroup = Pattern.compile("group\\(([0-9]+)\\)"); while ((tonormalize.contains("%")) || (tonormalize.contains("group"))) { // replace normalization functions for (MatchResult mr : Toolbox.findMatches(paNorm,tonormalize)) { Logger.printDetail("-----------------------------------"); Logger.printDetail("DEBUGGING: tonormalize:"+tonormalize); Logger.printDetail("DEBUGGING: mr.group():"+mr.group()); Logger.printDetail("DEBUGGING: mr.group(1):"+mr.group(1)); Logger.printDetail("DEBUGGING: mr.group(2):"+mr.group(2)); Logger.printDetail("DEBUGGING: m.group():"+m.group()); Logger.printDetail("DEBUGGING: m.group("+Integer.parseInt(mr.group(2))+"):"+m.group(Integer.parseInt(mr.group(2)))); Logger.printDetail("DEBUGGING: hmR...:"+norm.getFromHmAllNormalization(mr.group(1)).get(m.group(Integer.parseInt(mr.group(2))))); Logger.printDetail("-----------------------------------"); if (! (m.group(Integer.parseInt(mr.group(2))) == null)) { String partToReplace = m.group(Integer.parseInt(mr.group(2))).replaceAll("[\n\\s]+", " "); if (!(norm.getFromHmAllNormalization(mr.group(1)).containsKey(partToReplace))) { Logger.printDetail("Maybe problem with normalization of the resource: "+mr.group(1)); Logger.printDetail("Maybe problem with part to replace? "+partToReplace); } tonormalize = tonormalize.replace(mr.group(), norm.getFromHmAllNormalization(mr.group(1)).get(partToReplace)); } else { Logger.printDetail("Empty part to normalize in "+mr.group(1)); tonormalize = tonormalize.replace(mr.group(), ""); } } // replace other groups for (MatchResult mr : Toolbox.findMatches(paGroup,tonormalize)) { Logger.printDetail("-----------------------------------"); Logger.printDetail("DEBUGGING: tonormalize:"+tonormalize); Logger.printDetail("DEBUGGING: mr.group():"+mr.group()); Logger.printDetail("DEBUGGING: mr.group(1):"+mr.group(1)); Logger.printDetail("DEBUGGING: m.group():"+m.group()); Logger.printDetail("DEBUGGING: m.group("+Integer.parseInt(mr.group(1))+"):"+m.group(Integer.parseInt(mr.group(1)))); Logger.printDetail("-----------------------------------"); tonormalize = tonormalize.replace(mr.group(), m.group(Integer.parseInt(mr.group(1)))); } // replace substrings Pattern paSubstring = Pattern.compile("%SUBSTRING%\\((.*?),([0-9]+),([0-9]+)\\)"); for (MatchResult mr : Toolbox.findMatches(paSubstring,tonormalize)) { String substring = mr.group(1).substring(Integer.parseInt(mr.group(2)), Integer.parseInt(mr.group(3))); tonormalize = tonormalize.replace(mr.group(),substring); } if(language.getName().compareTo("arabic") != 0) { // replace lowercase Pattern paLowercase = Pattern.compile("%LOWERCASE%\\((.*?)\\)"); for (MatchResult mr : Toolbox.findMatches(paLowercase,tonormalize)) { String substring = mr.group(1).toLowerCase(); tonormalize = tonormalize.replace(mr.group(),substring); } // replace uppercase Pattern paUppercase = Pattern.compile("%UPPERCASE%\\((.*?)\\)"); for (MatchResult mr : Toolbox.findMatches(paUppercase,tonormalize)) { String substring = mr.group(1).toUpperCase(); tonormalize = tonormalize.replace(mr.group(),substring); } } // replace sum, concatenation Pattern paSum = Pattern.compile("%SUM%\\((.*?),(.*?)\\)"); for (MatchResult mr : Toolbox.findMatches(paSum,tonormalize)) { int newValue = Integer.parseInt(mr.group(1)) + Integer.parseInt(mr.group(2)); tonormalize = tonormalize.replace(mr.group(), newValue+""); } // replace normalization function without group Pattern paNormNoGroup = Pattern.compile("%([A-Za-z0-9]+?)\\((.*?)\\)"); for (MatchResult mr : Toolbox.findMatches(paNormNoGroup, tonormalize)) { tonormalize = tonormalize.replace(mr.group(),norm.getFromHmAllNormalization(mr.group(1)).get(mr.group(2))); } // replace Chinese with Arabic numerals Pattern paChineseNorm = Pattern.compile("%CHINESENUMBERS%\\((.*?)\\)"); for (MatchResult mr : Toolbox.findMatches(paChineseNorm, tonormalize)) { RegexHashMap<String> chineseNumerals = new RegexHashMap<String>(); chineseNumerals.put("[零00]", "0"); chineseNumerals.put("[一11]", "1"); chineseNumerals.put("[二22]", "2"); chineseNumerals.put("[三33]", "3"); chineseNumerals.put("[四44]", "4"); chineseNumerals.put("[五55]", "5"); chineseNumerals.put("[六66]", "6"); chineseNumerals.put("[七77]", "7"); chineseNumerals.put("[八88]", "8"); chineseNumerals.put("[九99]", "9"); String outString = ""; for(Integer i = 0; i < mr.group(1).length(); i++) { String thisChar = mr.group(1).substring(i, i+1); if(chineseNumerals.containsKey(thisChar)){ outString += chineseNumerals.get(thisChar); } else { System.out.println(chineseNumerals.entrySet()); Logger.printError(component, "Found an error in the resources: " + mr.group(1) + " contains " + "a character that is not defined in the Chinese numerals map. Normalization may be mangled."); outString += thisChar; } } tonormalize = tonormalize.replace(mr.group(), outString); } } normalized = tonormalize; return normalized; } public String[] getAttributesForTimexFromFile(String rule, HashMap<String, String> hmNormalization, HashMap<String, String> hmQuant, HashMap<String, String> hmFreq, HashMap<String, String> hmMod, HashMap<String, String> hmEmptyValue, MatchResult m, JCas jcas) { String[] attributes = new String[5]; String value = ""; String quant = ""; String freq = ""; String mod = ""; String emptyValue = ""; // Normalize Value String value_normalization_pattern = hmNormalization.get(rule); value = applyRuleFunctions(value_normalization_pattern, m); // get quant if (hmQuant.containsKey(rule)) { String quant_normalization_pattern = hmQuant.get(rule); quant = applyRuleFunctions(quant_normalization_pattern, m); } // get freq if (hmFreq.containsKey(rule)) { String freq_normalization_pattern = hmFreq.get(rule); freq = applyRuleFunctions(freq_normalization_pattern, m); } // get mod if (hmMod.containsKey(rule)) { String mod_normalization_pattern = hmMod.get(rule); mod = applyRuleFunctions(mod_normalization_pattern, m); } // get emptyValue if (hmEmptyValue.containsKey(rule)) { String emptyValue_normalization_pattern = hmEmptyValue.get(rule); emptyValue = applyRuleFunctions(emptyValue_normalization_pattern, m); emptyValue = correctDurationValue(emptyValue); } // For example "PT24H" -> "P1D" if (group_gran) value = correctDurationValue(value); attributes[0] = value; attributes[1] = quant; attributes[2] = freq; attributes[3] = mod; attributes[4] = emptyValue; return attributes; } /** * Durations of a finer granularity are mapped to a coarser one if possible, e.g., "PT24H" -> "P1D". * One may add several further corrections. * @param value * @return */ public String correctDurationValue(String value) { if (value.matches("PT[0-9]+H")){ for (MatchResult mr : Toolbox.findMatches(Pattern.compile("PT([0-9]+)H"), value)){ try { int hours = Integer.parseInt(mr.group(1)); if ((hours % 24) == 0){ int days = hours / 24; value = "P"+days+"D"; } } catch(NumberFormatException e) { Logger.printDetail(component, "Couldn't do granularity conversion for " + value); } } } else if (value.matches("PT[0-9]+M")){ for (MatchResult mr : Toolbox.findMatches(Pattern.compile("PT([0-9]+)M"), value)){ try { int minutes = Integer.parseInt(mr.group(1)); if ((minutes % 60) == 0){ int hours = minutes / 60; value = "PT"+hours+"H"; } } catch(NumberFormatException e) { Logger.printDetail(component, "Couldn't do granularity conversion for " + value); } } } else if (value.matches("P[0-9]+M")){ for (MatchResult mr : Toolbox.findMatches(Pattern.compile("P([0-9]+)M"), value)){ try { int months = Integer.parseInt(mr.group(1)); if ((months % 12) == 0){ int years = months / 12; value = "P"+years+"Y"; } } catch(NumberFormatException e) { Logger.printDetail(component, "Couldn't do granularity conversion for " + value); } } } return value; } }
Java
package de.unihd.dbs.uima.annotator.heideltime.resources; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.TreeMap; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; /** * * This class fills the role of a manager of all the RePattern resources. * It reads the data from a file system and fills up a bunch of HashMaps * with their information. * @author jannik stroetgen * */ public class RePatternManager extends GenericResourceManager { protected static HashMap<Language, RePatternManager> instances = new HashMap<Language, RePatternManager>(); // STORE PATTERNS AND NORMALIZATIONS private TreeMap<String, String> hmAllRePattern; /** * Constructor calls the parent constructor that sets language/resource * parameters and collects resource repatterns. * @param language */ private RePatternManager(String language) { // calls the Generic constructor with repattern parameter super("repattern", language); // initialize the member map of all repatterns hmAllRePattern = new TreeMap<String, String>(); ////////////////////////////////////////////////////// // READ PATTERN RESOURCES FROM FILES AND STORE THEM // ////////////////////////////////////////////////////// HashMap<String, String> hmResourcesRePattern = readResourcesFromDirectory(); for (String which : hmResourcesRePattern.keySet()) { hmAllRePattern.put(which, ""); } readRePatternResources(hmResourcesRePattern); } /** * singleton producer. * @return singleton instance of RePatternManager */ public static RePatternManager getInstance(Language language) { if(!instances.containsKey(language)) { RePatternManager nm = new RePatternManager(language.getResourceFolder()); instances.put(language, nm); } return instances.get(language); } /** * READ THE REPATTERN FROM THE FILES. The files have to be defined in the HashMap hmResourcesRePattern. * @param hmResourcesRePattern RePattern resources to be interpreted */ private void readRePatternResources(HashMap<String, String> hmResourcesRePattern) { ////////////////////////////////////// // READ REGULAR EXPRESSION PATTERNS // ////////////////////////////////////// try { for (String resource : hmResourcesRePattern.keySet()) { Logger.printDetail(component, "Adding pattern resource: "+resource); // create a buffered reader for every repattern resource file BufferedReader in = new BufferedReader(new InputStreamReader (this.getClass().getClassLoader().getResourceAsStream(hmResourcesRePattern.get(resource)),"UTF-8")); for (String line; (line=in.readLine()) != null; ) { if (!line.startsWith("//")) { boolean correctLine = false; if (!(line.equals(""))) { correctLine = true; for (String which : hmAllRePattern.keySet()) { if (resource.equals(which)) { String devPattern = hmAllRePattern.get(which); devPattern = devPattern + "|" + line; hmAllRePattern.put(which, devPattern); } } } if ((correctLine == false) && (!(line.matches("")))) { Logger.printError(component, "Cannot read one of the lines of pattern resource "+resource); Logger.printError(component, "Line: "+line); } } } } //////////////////////////// // FINALIZE THE REPATTERN // //////////////////////////// for (String which : hmAllRePattern.keySet()) { finalizeRePattern(which, hmAllRePattern.get(which)); } } catch (IOException e) { e.printStackTrace(); } } /** * Pattern containing regular expression is finalized, i.e., created correctly and added to hmAllRePattern. * @param name key name * @param rePattern repattern value */ private void finalizeRePattern(String name, String rePattern) { // create correct regular expression rePattern = rePattern.replaceFirst("\\|", ""); /* this was added to reduce the danger of getting unusable groups from user-made repattern * files with group-producing parentheses (i.e. "(foo|bar)" while matching against the documents. */ rePattern = rePattern.replaceAll("\\(([^\\?])", "(?:$1"); rePattern = "(" + rePattern + ")"; rePattern = rePattern.replaceAll("\\\\", "\\\\\\\\"); // add rePattern to hmAllRePattern hmAllRePattern.put(name, rePattern); } /** * proxy method to access the hmAllRePattern member * @param key key to check for * @return whether the map contains the key */ public Boolean containsKey(String key) { return hmAllRePattern.containsKey(key); } /** * proxy method to access the hmAllRePattern member * @param key Key to retrieve data from * @return String from the map */ public String get(String key) { return hmAllRePattern.get(key); } }
Java
package de.unihd.dbs.uima.annotator.heideltime.resources; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.regex.MatchResult; import java.util.regex.Pattern; import de.unihd.dbs.uima.annotator.heideltime.utilities.*; /** * * This class fills the role of a manager of all the Normalization resources. * It reads the data from a file system and fills up a bunch of HashMaps * with their information. * @author jannik stroetgen * */ public class NormalizationManager extends GenericResourceManager { protected static HashMap<Language, NormalizationManager> instances = new HashMap<Language, NormalizationManager>(); // PATTERNS TO READ RESOURCES "RULES" AND "NORMALIZATION" private Pattern paReadNormalizations = Pattern.compile("\"(.*?)\",\"(.*?)\""); // STORE PATTERNS AND NORMALIZATIONS private HashMap<String, RegexHashMap<String>> hmAllNormalization; // ACCESS TO SOME NORMALIZATION MAPPINGS (set internally) private HashMap<String, String> normDayInWeek; private HashMap<String, String> normNumber; private HashMap<String, String> normMonthName; private HashMap<String, String> normMonthInSeason; private HashMap<String, String> normMonthInQuarter; /** * Constructor calls the parent constructor that sets language/resource parameters, * initializes basic and collects resource normalization patterns. * @param language */ private NormalizationManager(String language) { // calls the Generic constructor with normalization-parameter super("normalization", language); // initialize the data structures hmAllNormalization = new HashMap<String, RegexHashMap<String>>(); normNumber = new HashMap<String, String>(); normDayInWeek = new HashMap<String, String>(); normMonthName = new HashMap<String, String>(); normMonthInSeason = new HashMap<String, String>(); normMonthInQuarter = new HashMap<String, String>(); // GLOBAL NORMALIZATION INFORMATION readGlobalNormalizationInformation(); //////////////////////////////////////////////////////////// // READ NORMALIZATION RESOURCES FROM FILES AND STORE THEM // //////////////////////////////////////////////////////////// HashMap<String, String> hmResourcesNormalization = readResourcesFromDirectory(); for (String which : hmResourcesNormalization.keySet()) { hmAllNormalization.put(which, new RegexHashMap<String>()); } readNormalizationResources(hmResourcesNormalization); } /** * singleton producer. * @return singleton instance of NormalizationManager */ public static NormalizationManager getInstance(Language language) { if(!instances.containsKey(language)) { NormalizationManager nm = new NormalizationManager(language.getResourceFolder()); instances.put(language, nm); } return instances.get(language); } /** * Read the resources (of any language) from resource files and * fill the HashMaps used for normalization tasks. * @param hmResourcesNormalization normalization patterns to be interpreted */ public void readNormalizationResources(HashMap<String, String> hmResourcesNormalization) { try { for (String resource : hmResourcesNormalization.keySet()) { Logger.printDetail(component, "Adding normalization resource: "+resource); // create a buffered reader for every normalization resource file BufferedReader in = new BufferedReader(new InputStreamReader (this.getClass().getClassLoader().getResourceAsStream(hmResourcesNormalization.get(resource)),"UTF-8")); for ( String line; (line=in.readLine()) != null; ) { if (line.startsWith("//")) continue; // ignore comments // check each line for the normalization format (defined in paReadNormalizations) boolean correctLine = false; for (MatchResult r : Toolbox.findMatches(paReadNormalizations, line)) { correctLine = true; String resource_word = r.group(1); String normalized_word = r.group(2); for (String which : hmAllNormalization.keySet()) { if (resource.equals(which)) { hmAllNormalization.get(which).put(resource_word,normalized_word); } } if ((correctLine == false) && (!(line.matches("")))) { Logger.printError("["+component+"] Cannot read one of the lines of normalization resource "+resource); Logger.printError("["+component+"] Line: "+line); } } } } } catch (IOException e) { e.printStackTrace(); } } /** * sets a couple of rudimentary normalization parameters */ private void readGlobalNormalizationInformation() { // MONTH IN QUARTER normMonthInQuarter.put("01","1"); normMonthInQuarter.put("02","1"); normMonthInQuarter.put("03","1"); normMonthInQuarter.put("04","2"); normMonthInQuarter.put("05","2"); normMonthInQuarter.put("06","2"); normMonthInQuarter.put("07","3"); normMonthInQuarter.put("08","3"); normMonthInQuarter.put("09","3"); normMonthInQuarter.put("10","4"); normMonthInQuarter.put("11","4"); normMonthInQuarter.put("12","4"); // MONTH IN SEASON normMonthInSeason.put("", ""); normMonthInSeason.put("01","WI"); normMonthInSeason.put("02","WI"); normMonthInSeason.put("03","SP"); normMonthInSeason.put("04","SP"); normMonthInSeason.put("05","SP"); normMonthInSeason.put("06","SU"); normMonthInSeason.put("07","SU"); normMonthInSeason.put("08","SU"); normMonthInSeason.put("09","FA"); normMonthInSeason.put("10","FA"); normMonthInSeason.put("11","FA"); normMonthInSeason.put("12","WI"); // DAY IN WEEK normDayInWeek.put("sunday","1"); normDayInWeek.put("monday","2"); normDayInWeek.put("tuesday","3"); normDayInWeek.put("wednesday","4"); normDayInWeek.put("thursday","5"); normDayInWeek.put("friday","6"); normDayInWeek.put("saturday","7"); normDayInWeek.put("Sunday","1"); normDayInWeek.put("Monday","2"); normDayInWeek.put("Tuesday","3"); normDayInWeek.put("Wednesday","4"); normDayInWeek.put("Thursday","5"); normDayInWeek.put("Friday","6"); normDayInWeek.put("Saturday","7"); // normDayInWeek.put("sunday","7"); // normDayInWeek.put("monday","1"); // normDayInWeek.put("tuesday","2"); // normDayInWeek.put("wednesday","3"); // normDayInWeek.put("thursday","4"); // normDayInWeek.put("friday","5"); // normDayInWeek.put("saturday","6"); // normDayInWeek.put("Sunday","7"); // normDayInWeek.put("Monday","1"); // normDayInWeek.put("Tuesday","2"); // normDayInWeek.put("Wednesday","3"); // normDayInWeek.put("Thursday","4"); // normDayInWeek.put("Friday","5"); // normDayInWeek.put("Saturday","6"); // NORM MINUTE normNumber.put("0","00"); normNumber.put("00","00"); normNumber.put("1","01"); normNumber.put("01","01"); normNumber.put("2","02"); normNumber.put("02","02"); normNumber.put("3","03"); normNumber.put("03","03"); normNumber.put("4","04"); normNumber.put("04","04"); normNumber.put("5","05"); normNumber.put("05","05"); normNumber.put("6","06"); normNumber.put("06","06"); normNumber.put("7","07"); normNumber.put("07","07"); normNumber.put("8","08"); normNumber.put("08","08"); normNumber.put("9","09"); normNumber.put("09","09"); normNumber.put("10","10"); normNumber.put("11","11"); normNumber.put("12","12"); normNumber.put("13","13"); normNumber.put("14","14"); normNumber.put("15","15"); normNumber.put("16","16"); normNumber.put("17","17"); normNumber.put("18","18"); normNumber.put("19","19"); normNumber.put("20","20"); normNumber.put("21","21"); normNumber.put("22","22"); normNumber.put("23","23"); normNumber.put("24","24"); normNumber.put("25","25"); normNumber.put("26","26"); normNumber.put("27","27"); normNumber.put("28","28"); normNumber.put("29","29"); normNumber.put("30","30"); normNumber.put("31","31"); normNumber.put("32","32"); normNumber.put("33","33"); normNumber.put("34","34"); normNumber.put("35","35"); normNumber.put("36","36"); normNumber.put("37","37"); normNumber.put("38","38"); normNumber.put("39","39"); normNumber.put("40","40"); normNumber.put("41","41"); normNumber.put("42","42"); normNumber.put("43","43"); normNumber.put("44","44"); normNumber.put("45","45"); normNumber.put("46","46"); normNumber.put("47","47"); normNumber.put("48","48"); normNumber.put("49","49"); normNumber.put("50","50"); normNumber.put("51","51"); normNumber.put("52","52"); normNumber.put("53","53"); normNumber.put("54","54"); normNumber.put("55","55"); normNumber.put("56","56"); normNumber.put("57","57"); normNumber.put("58","58"); normNumber.put("59","59"); normNumber.put("60","60"); // NORM MONTH normMonthName.put("january","01"); normMonthName.put("february","02"); normMonthName.put("march","03"); normMonthName.put("april","04"); normMonthName.put("may","05"); normMonthName.put("june","06"); normMonthName.put("july","07"); normMonthName.put("august","08"); normMonthName.put("september","09"); normMonthName.put("october","10"); normMonthName.put("november","11"); normMonthName.put("december","12"); } /* * a bunch of getter methods to facilitate access to the data structures */ public final RegexHashMap<String> getFromHmAllNormalization(String key) { return hmAllNormalization.get(key); } public final String getFromNormNumber(String key) { return normNumber.get(key); } public final String getFromNormDayInWeek(String key) { return normDayInWeek.get(key); } public final String getFromNormMonthName(String key) { return normMonthName.get(key); } public final String getFromNormMonthInSeason(String key) { return normMonthInSeason.get(key); } public final String getFromNormMonthInQuarter(String key) { return normMonthInQuarter.get(key); } }
Java
package de.unihd.dbs.uima.annotator.heideltime.resources; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; /** * Hardcoded Language information for use with HeidelTime/Standalone. Contains * information on the resource folder name as well as the relevant treetagger * parameter file and command line switch. * * @author Julian Zell */ public enum Language { /* * set languages here. elements are: * (languageName [for output labelling], * resourceFolder [where the resources for this language reside], * treeTaggerLangName [partial of the name of the treetagger parameter file], * treeTaggerSwitch [if tree-tagger tokenization script needs a special switch for this language]) */ ENGLISH ("english", "english", "english", "-e"), GERMAN ("german", "german", "german", ""), DUTCH ("dutch", "dutch", "dutch", ""), ENGLISHCOLL ("englishcoll", "englishcoll", "english", "-e"), ENGLISHSCI ("englishsci", "englishsci", "english", "-e"), ITALIAN ("italian", "italian", "italian", "-i"), SPANISH ("spanish", "spanish", "spanish", ""), VIETNAMESE ("vietnamese", "vietnamese", "vietnamese", ""), ARABIC ("arabic", "arabic", "arabic", ""), FRENCH ("french", "french", "french", "-f"), CHINESE ("chinese", "chinese", "zh", ""), RUSSIAN ("russian", "russian", "russian", ""), WILDCARD ("", "", "", ""), // if no match was found, this gets filled with parameter ; // ends the enum element list private String languageName; private String treeTaggerSwitch; private String treeTaggerLangName; private String resourceFolder; /** * Constructor for the Language elements. * @param languageName formal name of the language * @param resourceFolder folder name in the classpath that contains the resources * @param treeTaggerLangName name of the treetagger parameter file (for treetaggerwrapper) * @param treeTaggerSwitch special switch for the treetagger */ Language(String languageName, String resourceFolder, String treeTaggerLangName, String treeTaggerSwitch) { this.languageName = languageName; this.resourceFolder = resourceFolder; this.treeTaggerLangName = treeTaggerLangName; this.treeTaggerSwitch = treeTaggerSwitch; } /** * Takes a string and checks whether we have hardcoded parameter support for the given language. * @param name name of the language, e.g. "english", "german" * @return Language enum element that represents the requested language */ public final static Language getLanguageFromString(String name) { if(name == null) { Logger.printError("Language parameter was specified as NULL."); throw new NullPointerException(); } // loop through languages that aren't the wildcard one to see if we have special info on that language for(Language l : Language.values()) { if(l != WILDCARD && name.toLowerCase().equals(l.getName().toLowerCase())) { return l; } } // if looping through present enums didn't yield a result, throw one that is customized with the name parameter Language.WILDCARD.languageName = name; Language.WILDCARD.treeTaggerLangName = name; Language.WILDCARD.resourceFolder = name; return WILDCARD; } /* * getters */ public final String getName() { return this.languageName; } public final String getTreeTaggerSwitch() { return this.treeTaggerSwitch; } public final String getTreeTaggerLangName() { return this.treeTaggerLangName; } public final String getResourceFolder() { return this.resourceFolder; } }
Java
package de.unihd.dbs.uima.annotator.heideltime.resources; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; /** * Implements a HashMap extended with regular expression keys and caching functionality. * * @author Julian Zell * */ public class RegexHashMap<T> implements Map<String, T> { private HashMap<String, T> container = new HashMap<String, T>(); private HashMap<String, T> cache = new HashMap<String, T>(); /** * clears both the container and the cache hashmaps */ public void clear() { container.clear(); cache.clear(); } /** * checks whether the cache or container contain a specific key, then evaluates the * container's keys as regexes and checks whether they match the specific key. */ public boolean containsKey(Object key) { // the key is a direct hit from our cache if(cache.containsKey(key)) return true; // the key is a direct hit from our hashmap if(container.containsKey(key)) return true; // check if the requested key is a matching string of a regex key from our container Iterator<String> regexKeys = container.keySet().iterator(); while(regexKeys.hasNext()) { if(Pattern.matches(regexKeys.next(), (String) key)) return true; } // if the three previous tests yield no result, the key does not exist return false; } /** * checks whether a specific value is container within either container or cache */ public boolean containsValue(Object value) { // the value is a direct hit from our cache if(cache.containsValue(value)) return true; // the value is a direct hit from our hashmap if(container.containsValue(value)) return true; // otherwise, the value isn't within this object return false; } /** * returns a merged entryset containing within both the container and cache entrysets */ public Set<Entry<String, T>> entrySet() { // prepare the container HashSet<Entry<String, T>> set = new HashSet<Entry<String, T>>(); // add the set from our container set.addAll(container.entrySet()); // add the set from our cache set.addAll(cache.entrySet()); return set; } /** * checks whether the requested key has a direct match in either cache or container, and if it * doesn't, also evaluates the container's keyset as regexes to match against the input key and * if any of those methods yield a value, returns that value * if a value is found doing regex evaluation, use that regex-key's match as a non-regex * key with the regex's value to form a new entry in the cache. */ public T get(Object key) { // output for requested key null is the value null; normal Map behavior if(key == null) return null; T result = null; if((result = cache.get(key)) != null) { // if the requested key maps to a value in the cache return result; } else if((result = container.get(key)) != null) { // if the requested key maps to a value in the container return result; } else { // check if the requested key is a matching string of a regex key from our container Iterator<Entry<String, T>> regexKeys = container.entrySet().iterator(); while(regexKeys.hasNext()) { // prepare current entry Entry<String, T> entry = regexKeys.next(); // check if the key is a regex matching the input key if(Pattern.matches(entry.getKey(), (String) key)) { putCache((String) key, entry.getValue()); return entry.getValue(); } } } // no value for the given key was found in any of container/cache/regexkey-container return null; } /** * checks whether both container and cache are empty */ public boolean isEmpty() { return container.isEmpty() && cache.isEmpty(); } /** * returns the keysets of both the container and cache hashmaps */ public Set<String> keySet() { // prepare container HashSet<String> set = new HashSet<String>(); // add container keys set.addAll(container.keySet()); // add cache keys set.addAll(cache.keySet()); return set; } /** * associates a key with a value in the container hashmap */ public T put(String key, T value) { return container.put(key, value); } /** * associates a key with a value in the cache hashmap. * @param key Key to map from * @param value Value to map to * @return previous value associated with the key, or null if unassociated before */ public T putCache(String key, T value) { return cache.put(key, value); } /** * adds a map to the container */ public void putAll(Map<? extends String, ? extends T> m) { container.putAll(m); } /** * removes a specific key's association from the container */ public T remove(Object key) { return container.remove(key); } /** * returns the combined size of container and cache */ public int size() { return container.size() + cache.size(); } /** * returns the combined collection of both the values of the container as well as * the cache. */ public Collection<T> values() { // prepare set HashSet<T> set = new HashSet<T>(); // add all container values set.addAll(container.values()); // add all cache values set.addAll(cache.values()); return set; } }
Java
package de.unihd.dbs.uima.annotator.heideltime.resources; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.regex.MatchResult; import java.util.regex.Pattern; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; import de.unihd.dbs.uima.annotator.heideltime.utilities.Toolbox; /** * * Abstract class for all Resource Managers to inherit from. Contains basic * functionality such as file system access and some private members. * */ public abstract class GenericResourceManager { // language for the utilized resources protected String LANGUAGE; // kind of resource -- e.g. repattern, normalization, rules protected String resourceType; // local package for logging output protected Class<?> component; /** * Instantiates the Resource Manager with a resource type * @param resourceType kind of resource to represent */ protected GenericResourceManager(String resourceType, String language) { this.resourceType = resourceType; this.LANGUAGE = language; this.component = this.getClass(); } /** * Reads resource files of the type resourceType from the "used_resources.txt" file and returns a HashMap * containing information to access these resources. * @return HashMap containing filename/path tuples */ protected HashMap<String, String> readResourcesFromDirectory() { HashMap<String, String> hmResources = new HashMap<String, String>(); InputStream is = this.getClass().getClassLoader().getResourceAsStream("used_resources.txt"); if(is == null) { Logger.printError(component, "Couldn't load used_resources.txt. Perhaps you forgot to execute " + "the printResourceInformation.sh/bat script from inside the heideltime-kit/resources folder?"); System.exit(-1); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); try { for (String line; (line=br.readLine()) != null; ) { Pattern paResource = Pattern.compile(".(?:\\\\|/)?(\\\\|/)"+LANGUAGE+"(?:\\\\|/)"+resourceType+"(?:\\\\|/)"+"resources_"+resourceType+"_"+"(.*?)\\.txt"); for (MatchResult ro : Toolbox.findMatches(paResource, line)){ String foundResource = ro.group(2); String pathToResource = LANGUAGE+"/"+resourceType+"/"+"resources_"+resourceType+"_"+foundResource+".txt"; hmResources.put(foundResource, pathToResource); } } } catch (IOException e) { e.printStackTrace(); Logger.printError(component, "Failed to read a resource from used_resources.txt."); System.exit(-1); } Logger.printDetail(component, "Read in " + hmResources.size() + " " + LANGUAGE + " " + resourceType + " resource files."); if(hmResources.size() == 0) { Logger.printError(component, "used_resources.txt contained no readable files. Consider rebuilding it " + "using the printResourceInformation.sh/bat script from the heideltime-kit/resources folder."); System.exit(-1); } return hmResources; } }
Java
package de.unihd.dbs.uima.annotator.heideltime.resources; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.regex.MatchResult; import java.util.regex.Pattern; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; import de.unihd.dbs.uima.annotator.heideltime.utilities.Toolbox; /** * * This class fills the role of a manager of all the rule resources. It reads * the data from a file system and fills up a bunch of HashMaps with their * information. * * @author jannik stroetgen * */ public class RuleManager extends GenericResourceManager { protected static HashMap<Language, RuleManager> instances = new HashMap<Language, RuleManager>(); // PATTERNS TO READ RESOURCES "RULES" AND "NORMALIZATION" Pattern paReadRules = Pattern .compile("RULENAME=\"(.*?)\",EXTRACTION=\"(.*?)\",NORM_VALUE=\"(.*?)\"(.*)"); // EXTRACTION PARTS OF RULES (patterns loaded from files) HashMap<Pattern, String> hmDatePattern = new HashMap<Pattern, String>(); HashMap<Pattern, String> hmDurationPattern = new HashMap<Pattern, String>(); HashMap<Pattern, String> hmTimePattern = new HashMap<Pattern, String>(); HashMap<Pattern, String> hmSetPattern = new HashMap<Pattern, String>(); // NORMALIZATION PARTS OF RULES (patterns loaded from files) HashMap<String, String> hmDateNormalization = new HashMap<String, String>(); HashMap<String, String> hmTimeNormalization = new HashMap<String, String>(); HashMap<String, String> hmDurationNormalization = new HashMap<String, String>(); HashMap<String, String> hmSetNormalization = new HashMap<String, String>(); // OFFSET PARTS OF RULES (patterns loaded from files) HashMap<String, String> hmDateOffset = new HashMap<String, String>(); HashMap<String, String> hmTimeOffset = new HashMap<String, String>(); HashMap<String, String> hmDurationOffset = new HashMap<String, String>(); HashMap<String, String> hmSetOffset = new HashMap<String, String>(); // QUANT PARTS OF RULES (patterns loaded from files) HashMap<String, String> hmDateQuant = new HashMap<String, String>(); HashMap<String, String> hmTimeQuant = new HashMap<String, String>(); HashMap<String, String> hmDurationQuant = new HashMap<String, String>(); HashMap<String, String> hmSetQuant = new HashMap<String, String>(); // FREQ PARTS OF RULES (patterns loaded from files) HashMap<String, String> hmDateFreq = new HashMap<String, String>(); HashMap<String, String> hmTimeFreq = new HashMap<String, String>(); HashMap<String, String> hmDurationFreq = new HashMap<String, String>(); HashMap<String, String> hmSetFreq = new HashMap<String, String>(); // MOD PARTS OF RULES (patterns loaded from files) HashMap<String, String> hmDateMod = new HashMap<String, String>(); HashMap<String, String> hmTimeMod = new HashMap<String, String>(); HashMap<String, String> hmDurationMod = new HashMap<String, String>(); HashMap<String, String> hmSetMod = new HashMap<String, String>(); // POS PARTS OF RULES (patterns loaded from files) HashMap<String, String> hmDatePosConstraint = new HashMap<String, String>(); HashMap<String, String> hmTimePosConstraint = new HashMap<String, String>(); HashMap<String, String> hmDurationPosConstraint = new HashMap<String, String>(); HashMap<String, String> hmSetPosConstraint = new HashMap<String, String>(); // EMPTYVALUE part of rules HashMap<String, String> hmDateEmptyValue = new HashMap<String, String>(); HashMap<String, String> hmTimeEmptyValue = new HashMap<String, String>(); HashMap<String, String> hmDurationEmptyValue = new HashMap<String, String>(); HashMap<String, String> hmSetEmptyValue = new HashMap<String, String>(); /** * Constructor calls the parent constructor that sets language/resource * parameters and collects rules resources. * * @param language * language of resources to be used */ private RuleManager(String language) { // Process Generic constructor with rules parameter super("rules", language); // ///////////////////////////////////////////////// // READ RULE RESOURCES FROM FILES AND STORE THEM // // ///////////////////////////////////////////////// HashMap<String, String> hmResourcesRules = readResourcesFromDirectory(); readRules(hmResourcesRules, language); } /** * singleton producer. * * @return singleton instance of RuleManager */ public static RuleManager getInstance(Language language) { if(!instances.containsKey(language)) { RuleManager nm = new RuleManager(language.getResourceFolder()); instances.put(language, nm); } return instances.get(language); } /** * READ THE RULES FROM THE FILES. The files have to be defined in the * HashMap hmResourcesRules. * * @param hmResourcesRules * rules to be interpreted */ public void readRules(HashMap<String, String> hmResourcesRules, String language) { try { for (String resource : hmResourcesRules.keySet()) { BufferedReader br = new BufferedReader(new InputStreamReader( this.getClass() .getClassLoader() .getResourceAsStream( hmResourcesRules.get(resource)))); Logger.printDetail(component, "Adding rule resource: " + resource); for (String line; (line = br.readLine()) != null;) { // skip comments or empty lines in resource files if (line.startsWith("//") || line.equals("")) continue; boolean correctLine = false; Logger.printDetail("DEBUGGING: reading rules..." + line); // check each line for the name, extraction, and // normalization part for (MatchResult r : Toolbox.findMatches(paReadRules, line)) { correctLine = true; String rule_name = r.group(1); String rule_extraction = r.group(2); String rule_normalization = r.group(3); String rule_offset = ""; String rule_quant = ""; String rule_freq = ""; String rule_mod = ""; String pos_constraint = ""; String rule_empty_value = ""; // ////////////////////////////////////////////////////////////////// // RULE EXTRACTION PARTS ARE TRANSLATED INTO REGULAR // EXPRESSSIONS // // ////////////////////////////////////////////////////////////////// // create pattern for rule extraction part Pattern paVariable = Pattern.compile("%(re[a-zA-Z0-9]*)"); RePatternManager rpm = RePatternManager.getInstance(Language.getLanguageFromString(language)); for (MatchResult mr : Toolbox.findMatches(paVariable, rule_extraction)) { Logger.printDetail("DEBUGGING: replacing patterns..." + mr.group()); if (!(rpm.containsKey(mr.group(1)))) { Logger.printError("Error creating rule:" + rule_name); Logger.printError("The following pattern used in this rule does not exist, does it? %" + mr.group(1)); System.exit(-1); } rule_extraction = rule_extraction.replaceAll("%" + mr.group(1), rpm.get(mr.group(1))); } rule_extraction = rule_extraction.replaceAll(" ", "[\\\\s]+"); Pattern pattern = null; try { pattern = Pattern.compile(rule_extraction); } catch (java.util.regex.PatternSyntaxException e) { Logger.printError("Compiling rules resulted in errors."); Logger.printError("Problematic rule is " + rule_name); Logger.printError("Cannot compile pattern: " + rule_extraction); e.printStackTrace(); System.exit(-1); } // Pattern pattern = Pattern.compile(rule_extraction); // /////////////////////////////////// // CHECK FOR ADDITIONAL CONSTRAINS // // /////////////////////////////////// if (!(r.group(4) == null)) { if (r.group(4).contains("OFFSET")) { Pattern paOffset = Pattern .compile("OFFSET=\"(.*?)\""); for (MatchResult ro : Toolbox.findMatches( paOffset, line)) { rule_offset = ro.group(1); } } if (r.group(4).contains("NORM_QUANT")) { Pattern paQuant = Pattern .compile("NORM_QUANT=\"(.*?)\""); for (MatchResult rq : Toolbox.findMatches( paQuant, line)) { rule_quant = rq.group(1); } } if (r.group(4).contains("NORM_FREQ")) { Pattern paFreq = Pattern .compile("NORM_FREQ=\"(.*?)\""); for (MatchResult rf : Toolbox.findMatches( paFreq, line)) { rule_freq = rf.group(1); } } if (r.group(4).contains("NORM_MOD")) { Pattern paMod = Pattern .compile("NORM_MOD=\"(.*?)\""); for (MatchResult rf : Toolbox.findMatches( paMod, line)) { rule_mod = rf.group(1); } } if (r.group(4).contains("POS_CONSTRAINT")) { Pattern paPos = Pattern .compile("POS_CONSTRAINT=\"(.*?)\""); for (MatchResult rp : Toolbox.findMatches( paPos, line)) { pos_constraint = rp.group(1); } } if (r.group(4).contains("EMPTY_VALUE")) { Pattern paEmpty = Pattern .compile("EMPTY_VALUE=\"(.*?)\""); for (MatchResult rp : Toolbox.findMatches( paEmpty, line)) { rule_empty_value = rp.group(1); } } } // /////////////////////////////////////////// // READ DATE RULES AND MAKE THEM AVAILABLE // // /////////////////////////////////////////// if (resource.equals("daterules")) { // get extraction part hmDatePattern.put(pattern, rule_name); // get normalization part hmDateNormalization.put(rule_name, rule_normalization); // get offset part if (!(rule_offset.equals(""))) { hmDateOffset.put(rule_name, rule_offset); } // get quant part if (!(rule_quant.equals(""))) { hmDateQuant.put(rule_name, rule_quant); } // get freq part if (!(rule_freq.equals(""))) { hmDateFreq.put(rule_name, rule_freq); } // get mod part if (!(rule_mod.equals(""))) { hmDateMod.put(rule_name, rule_mod); } // get pos constraint part if (!(pos_constraint.equals(""))) { hmDatePosConstraint.put(rule_name, pos_constraint); } // get empty value part if (!(rule_empty_value.equals(""))) { hmDateEmptyValue.put(rule_name, rule_empty_value); } } // /////////////////////////////////////////////// // READ DURATION RULES AND MAKE THEM AVAILABLE // // /////////////////////////////////////////////// else if (resource.equals("durationrules")) { // get extraction part hmDurationPattern.put(pattern, rule_name); // get normalization part hmDurationNormalization.put(rule_name, rule_normalization); // get offset part if (!(rule_offset.equals(""))) { hmDurationOffset.put(rule_name, rule_offset); } // get quant part if (!(rule_quant.equals(""))) { hmDurationQuant.put(rule_name, rule_quant); } // get freq part if (!(rule_freq.equals(""))) { hmDurationFreq.put(rule_name, rule_freq); } // get mod part if (!(rule_mod.equals(""))) { hmDurationMod.put(rule_name, rule_mod); } // get pos constraint part if (!(pos_constraint.equals(""))) { hmDurationPosConstraint.put(rule_name, pos_constraint); } // get empty value part if (!(rule_empty_value.equals(""))) { hmDurationEmptyValue.put(rule_name, rule_empty_value); } } // ////////////////////////////////////////// // READ SET RULES AND MAKE THEM AVAILABLE // // ////////////////////////////////////////// else if (resource.equals("setrules")) { // get extraction part hmSetPattern.put(pattern, rule_name); // get normalization part hmSetNormalization.put(rule_name, rule_normalization); // get offset part if (!rule_offset.equals("")) { hmSetOffset.put(rule_name, rule_offset); } // get quant part if (!rule_quant.equals("")) { hmSetQuant.put(rule_name, rule_quant); } // get freq part if (!rule_freq.equals("")) { hmSetFreq.put(rule_name, rule_freq); } // get mod part if (!rule_mod.equals("")) { hmSetMod.put(rule_name, rule_mod); } // get pos constraint part if (!pos_constraint.equals("")) { hmSetPosConstraint.put(rule_name, pos_constraint); } // get empty value part if (!(rule_empty_value.equals(""))) { hmSetEmptyValue.put(rule_name, rule_empty_value); } } // /////////////////////////////////////////// // READ TIME RULES AND MAKE THEM AVAILABLE // // /////////////////////////////////////////// else if (resource.equals("timerules")) { // get extraction part hmTimePattern.put(pattern, rule_name); // get normalization part hmTimeNormalization.put(rule_name, rule_normalization); // get offset part if (!rule_offset.equals("")) { hmTimeOffset.put(rule_name, rule_offset); } // get quant part if (!rule_quant.equals("")) { hmTimeQuant.put(rule_name, rule_quant); } // get freq part if (!rule_freq.equals("")) { hmTimeFreq.put(rule_name, rule_freq); } // get mod part if (!rule_mod.equals("")) { hmTimeMod.put(rule_name, rule_mod); } // get pos constraint part if (!pos_constraint.equals("")) { hmTimePosConstraint.put(rule_name, pos_constraint); } // get empty value part if (!(rule_empty_value.equals(""))) { hmTimeEmptyValue.put(rule_name, rule_empty_value); } } else { Logger.printDetail(component, "Resource not recognized by HeidelTime: " + resource); } } // ///////////////////////////////////////// // CHECK FOR PROBLEMS WHEN READING RULES // // ///////////////////////////////////////// if (!correctLine) { Logger.printError(component, "Cannot read the following line of rule resource " + resource); Logger.printError(component, "Line: " + line); } } } } catch (IOException e) { e.printStackTrace(); } } public final HashMap<Pattern, String> getHmDatePattern() { return hmDatePattern; } public final HashMap<Pattern, String> getHmDurationPattern() { return hmDurationPattern; } public final HashMap<Pattern, String> getHmTimePattern() { return hmTimePattern; } public final HashMap<Pattern, String> getHmSetPattern() { return hmSetPattern; } public final HashMap<String, String> getHmDateNormalization() { return hmDateNormalization; } public final HashMap<String, String> getHmTimeNormalization() { return hmTimeNormalization; } public final HashMap<String, String> getHmDurationNormalization() { return hmDurationNormalization; } public final HashMap<String, String> getHmSetNormalization() { return hmSetNormalization; } public final HashMap<String, String> getHmDateOffset() { return hmDateOffset; } public final HashMap<String, String> getHmTimeOffset() { return hmTimeOffset; } public final HashMap<String, String> getHmDurationOffset() { return hmDurationOffset; } public final HashMap<String, String> getHmSetOffset() { return hmSetOffset; } public final HashMap<String, String> getHmDateQuant() { return hmDateQuant; } public final HashMap<String, String> getHmTimeQuant() { return hmTimeQuant; } public final HashMap<String, String> getHmDurationQuant() { return hmDurationQuant; } public final HashMap<String, String> getHmSetQuant() { return hmSetQuant; } public final HashMap<String, String> getHmDateFreq() { return hmDateFreq; } public final HashMap<String, String> getHmTimeFreq() { return hmTimeFreq; } public final HashMap<String, String> getHmDurationFreq() { return hmDurationFreq; } public final HashMap<String, String> getHmSetFreq() { return hmSetFreq; } public final HashMap<String, String> getHmDateMod() { return hmDateMod; } public final HashMap<String, String> getHmTimeMod() { return hmTimeMod; } public final HashMap<String, String> getHmDurationMod() { return hmDurationMod; } public final HashMap<String, String> getHmSetMod() { return hmSetMod; } public final HashMap<String, String> getHmDatePosConstraint() { return hmDatePosConstraint; } public final HashMap<String, String> getHmTimePosConstraint() { return hmTimePosConstraint; } public final HashMap<String, String> getHmDurationPosConstraint() { return hmDurationPosConstraint; } public final HashMap<String, String> getHmSetPosConstraint() { return hmSetPosConstraint; } public final HashMap<String, String> getHmDateEmptyValue() { return hmDateEmptyValue; } public final HashMap<String, String> getHmTimeEmptyValue() { return hmTimeEmptyValue; } public final HashMap<String, String> getHmDurationEmptyValue() { return hmDurationEmptyValue; } public final HashMap<String, String> getHmSetEmptyValue() { return hmSetEmptyValue; } }
Java
package de.unihd.dbs.uima.annotator.heideltime.processors; import org.apache.uima.UimaContext; import org.apache.uima.jcas.JCas; /** * * Abstract class to for all Processors to inherit from. A processor is a * modular, self-sufficient piece of code that was added to HeidelTime to * fulfill a specific function. * @author julian zell * */ public abstract class GenericProcessor { protected Class<?> component; /** * Constructor that sets the component for logger use. * Any inheriting class should run this via super() */ public GenericProcessor() { this.component = this.getClass(); } /** * sets up for later work done in process(). This shouldn't change the jcas object. * @param jcas * @throws ProcessorInitializationException Exception */ public abstract void initialize(final UimaContext aContext) throws ProcessorInitializationException; /** * starts the processing of the processor during HeidelTime's process()ing method. * @param jcas */ public abstract void process(JCas jcas) throws ProcessorProcessingException; }
Java
package de.unihd.dbs.uima.annotator.heideltime.processors; import de.unihd.dbs.uima.annotator.heideltime.HeidelTimeException; public class ProcessorProcessingException extends HeidelTimeException { /** * */ private static final long serialVersionUID = 6123306006146166368L; }
Java
package de.unihd.dbs.uima.annotator.heideltime.processors; import de.unihd.dbs.uima.annotator.heideltime.HeidelTimeException; public class ProcessorInitializationException extends HeidelTimeException { /** * */ private static final long serialVersionUID = -4036889037291484936L; }
Java
package de.unihd.dbs.uima.annotator.heideltime.processors; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.uima.UimaContext; import org.apache.uima.cas.FSIterator; import org.apache.uima.jcas.JCas; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; import de.unihd.dbs.uima.types.heideltime.Timex3; /** * Addition to HeidelTime to recognize several (mostly, but not * entirely christian) holidays. * @author Hans-Peter Pfeiffer * */ public class HolidayProcessor extends GenericProcessor { /** * Constructor just calls the parent constructor here. */ public HolidayProcessor() { super(); } /** * not needed here */ public void initialize(UimaContext aContext) { return; } /** * all the functionality was put into evaluateCalculationFunctions(). */ public void process(JCas jcas) { evaluateCalculationFunctions(jcas); } /** * This function replaces function calls from the resource files with their TIMEX value. * * @author Hans-Peter Pfeiffer * @param jcas */ public void evaluateCalculationFunctions(JCas jcas) { // build up a list with all found TIMEX expressions List<Timex3> linearDates = new ArrayList<Timex3>(); FSIterator iterTimex = jcas.getAnnotationIndex(Timex3.type).iterator(); // Create List of all Timexes of types "date" and "time" while (iterTimex.hasNext()) { Timex3 timex = (Timex3) iterTimex.next(); if ((timex.getTimexType().equals("DATE")) || (timex.getTimexType().equals("TIME"))) { linearDates.add(timex); } } ////////////////////////////////////////////// // go through list of Date and Time timexes // ////////////////////////////////////////////// //compile regex pattern for validating commands/arguments Pattern cmd_p = Pattern.compile("((\\w\\w\\w\\w)-(\\w\\w)-(\\w\\w))\\s+funcDateCalc\\((\\w+)\\((.+)\\)\\)"); Pattern year_p = Pattern.compile("(\\d\\d\\d\\d)"); Pattern date_p = Pattern.compile("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"); Matcher cmd_m; Matcher year_m; Matcher date_m; String date; String year; String month; String day; String function; String args[]; String valueNew; for (int i = 0; i < linearDates.size(); i++) { Timex3 t_i = (Timex3) linearDates.get(i); String value_i = t_i.getTimexValue(); cmd_m = cmd_p.matcher(value_i); valueNew = value_i; if(cmd_m.matches()) { date = cmd_m.group(1); year = cmd_m.group(2); month = cmd_m.group(3); day = cmd_m.group(4); function = cmd_m.group(5); args = cmd_m.group(6).split("\\s*,\\s*"); //replace keywords in function with actual values for(int j=0; j<args.length; j++) { args[j] = args[j].replace("DATE", date); args[j] = args[j].replace("YEAR", year); args[j] = args[j].replace("MONTH", month); args[j] = args[j].replace("DAY", day); } if(function.equals("EasterSunday")) { year_m = year_p.matcher(args[0]); //check if args[0] is a valid YEAR value if(year_m.matches()) { //System.err.println("correct format"); valueNew = this.getEasterSunday(Integer.valueOf(args[0]), Integer.valueOf(args[1])); } else{ Logger.printError("wrong format"); valueNew = "XXXX-XX-XX"; } } else if(function.equals("WeekdayRelativeTo")) { date_m = date_p.matcher(args[0]); //check if args[0] is a valid DATE value if(date_m.matches()) { //System.err.println("correct format"); valueNew = this.getWeekdayRelativeTo(args[0], Integer.valueOf(args[1]), Integer.valueOf(args[2]), Boolean.parseBoolean(args[3])); } else{ Logger.printError("wrong format"); valueNew = "XXXX-XX-XX"; } } else if(function.equals("EasterSundayOrthodox")) { year_m = year_p.matcher(args[0]); //check if args[0] is a valid YEAR value if(year_m.matches()) { //System.err.println("correct format"); valueNew = this.getEasterSundayOrthodox(Integer.valueOf(args[0]), Integer.valueOf(args[1])); } else{ Logger.printError("wrong format"); valueNew = "XXXX-XX-XX"; } } else if(function.equals("ShroveTideOrthodox")) { year_m = year_p.matcher(args[0]); //check if args[0] is a valid YEAR value if(year_m.matches()) { //System.err.println("correct format"); valueNew = this.getShroveTideWeekOrthodox(Integer.valueOf(args[0])); } else{ Logger.printError("wrong format"); valueNew = "XXXX-XX-XX"; } } else{ // if function call doesn't match any supported function Logger.printError("command not found"); valueNew = "XXXX-XX-XX"; } } t_i.removeFromIndexes(); t_i.setTimexValue(valueNew); t_i.addToIndexes(); linearDates.set(i, t_i); } } /** * Get the date of a day relative to Easter Sunday in a given year. Algorithm used is from the "Physikalisch-Technische Bundesanstalt Braunschweig" PTB. * * @author Hans-Peter Pfeiffer * @param year * @param days * @return date */ public String getEasterSunday(int year, int days) { int K = year / 100; int M = 15 + ( ( 3 * K + 3 ) / 4 ) - ( ( 8 * K + 13 ) / 25 ); int S = 2 - ( (3 * K + 3) / 4 ); int A = year % 19; int D = ( 19 * A + M ) % 30; int R = ( D / 29) + ( ( D / 28 ) - ( D / 29 ) * ( A / 11 ) ); int OG = 21 + D - R; int SZ = 7 - ( year + ( year / 4 ) + S ) % 7; int OE = 7 - ( OG - SZ ) % 7; int OS = OG + OE; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Calendar c = Calendar.getInstance(); String date; if( OS <= 31 ) { date = String.format("%04d-03-%02d", year, OS); } else{ date = String.format("%04d-04-%02d", year, ( OS - 31 ) ); } try{ c.setTime(formatter.parse(date)); c.add(Calendar.DAY_OF_MONTH, days); date = formatter.format(c.getTime()); } catch (ParseException e) { e.printStackTrace(); } return date; } /** * Get the date of Eastersunday in a given year * * @author Hans-Peter Pfeiffer * @param year * @return date */ public String getEasterSunday(int year) { return getEasterSunday(year, 0); } /** * Get the date of a day relative to Easter Sunday in a given year. Algorithm used is from the http://en.wikipedia.org/wiki/Computus#cite_note-otheralgs-47. * * @author Elena Klyachko * @param year * @param days * @return date */ public String getEasterSundayOrthodox(int year, int days) { int A = year%4; int B = year%7; int C = year%19; int D = (19*C+15)%30; int E = ((2*A + 4*B -D + 34))%7; int Month = (int)(Math.floor ((D + E + 114) / 31)); int Day = ((D + E + 114)% 31) +1; /* int K = year / 100; int M = 15 + ( ( 3 * K + 3 ) / 4 ) - ( ( 8 * K + 13 ) / 25 ); int S = 2 - ( (3 * K + 3) / 4 ); int A = year % 19; int D = ( 19 * A + M ) % 30; int R = ( D / 29) + ( ( D / 28 ) - ( D / 29 ) * ( A / 11 ) ); int OG = 21 + D - R; int SZ = 7 - ( year + ( year / 4 ) + S ) % 7; int OE = 7 - ( OG - SZ ) % 7; int OS = OG + OE; */ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Calendar c = Calendar.getInstance(); String date; date = String.format("%04d-%02d-%02d", year, Month, Day ); try{ c.setTime(formatter.parse(date)); c.add(Calendar.DAY_OF_MONTH, days); c.add(Calendar.DAY_OF_MONTH, getJulianDifference(year)); date = formatter.format(c.getTime()); } catch (ParseException e) { e.printStackTrace(); } return date; } /** * Get the date of Eastersunday in a given year * * @author Elena Klyachko * @param year * @return date */ public String getEasterSundayOrthodox(int year) { return getEasterSundayOrthodox(year, 0); } /** * Get the date of the Shrove-Tide week in a given year * * @author Elena Klyachko * @param year * @return date */ public String getShroveTideWeekOrthodox(int year){ String easterOrthodox = getEasterSundayOrthodox(year); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); try{ Calendar calendar = Calendar.getInstance(); Date date = formatter.parse(easterOrthodox); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH, -49); int shroveTideWeek = calendar.get(Calendar.WEEK_OF_YEAR); if(shroveTideWeek<10){ return year+"-W0"+shroveTideWeek; } return year+"-W"+shroveTideWeek; } catch (ParseException pe){ Logger.printError("ParseException:"+pe.getMessage()); return "unknown"; } } /** * Get the date of a weekday relative to a date, e.g. first Wednesday before 11-23 * * @author Hans-Peter Pfeiffer * @param date * @param weekday * @param number * @param count_itself * @return */ public String getWeekdayRelativeTo(String date, int weekday, int number, boolean count_itself) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Calendar c = Calendar.getInstance(); int day; int add; if(number == 0) { try{ c.setTime(formatter.parse(date)); date = formatter.format(c.getTime()); } catch (ParseException e) { e.printStackTrace(); } return date; } else{ if(number<0) { number+=1; } try{ c.setTime(formatter.parse(date)); day = c.get(Calendar.DAY_OF_WEEK); if((count_itself && number>0) || (!count_itself && number <= 0)) { if(day<=weekday) { add = weekday - day; } else{ add = weekday - day + 7; } } else{ if(day<weekday) { add = weekday - day; } else{ add = weekday - day + 7; } } add += (( number - 1) * 7); c.add(Calendar.DAY_OF_MONTH, add); date = formatter.format(c.getTime()); } catch (ParseException e) { e.printStackTrace(); } return date; } } /** * Get the date of a the first, second, third etc. weekday in a month * * @author Hans-Peter Pfeiffer * @param number * @param weekday * @param month * @param year * @return date */ public String getWeekdayOfMonth(int number, int weekday, int month, int year) { return getWeekdayRelativeTo(String.format("%04d-%02d-01", year, month), weekday, number, true); } private int getJulianDifference(int year){ //TODO: this is not entirely correct! int century = year/100 + 1; if(century<18){ return 10; } if(century==18){ return 11; } if(century==19){ return 12; } if(century==20||century == 21){ return 13; } if(century==22){ return 14; } return 15; } }
Java
/* * AnnotationTranslator.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * author: Jannik Strötgen * email: stroetgen@uni-hd.de * * Annotation Translator translates annotations of one type system into another. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.uima.annotator.annotationtranslator; import java.util.HashMap; import java.util.HashSet; import org.apache.uima.UimaContext; import org.apache.uima.analysis_component.JCasAnnotator_ImplBase; import org.apache.uima.cas.FSIndex; import org.apache.uima.cas.FSIterator; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; /** * Add an additional annotation type for an existing annotation * @author jannik * */ public class AnnotationTranslator extends JCasAnnotator_ImplBase { @SuppressWarnings("unused") private String toolname = "de.unihd.dbs.uima.annotator.annotationtranslator"; public static final String PARAM_DKPRO_TO_HEIDELTIME = "DkproToHeideltime"; public static final String PARAM_HEIDELTIME_TO_DKPRO = "HeideltimeToDkpro"; public static final String PARAM_IMPROVE_SENTENCE_DE = "ImproveGermanSentences"; public Boolean dkproToHeidel = true; public Boolean heidelToDpkro = true; public Boolean improveSentDe = true; public HashSet<String> hsSentenceBeginnings; /** * @see AnalysisComponent#initialize(UimaContext) */ public void initialize(UimaContext aContext) throws ResourceInitializationException { super.initialize(aContext); heidelToDpkro = (Boolean) aContext.getConfigParameterValue(PARAM_HEIDELTIME_TO_DKPRO); dkproToHeidel = (Boolean) aContext.getConfigParameterValue(PARAM_DKPRO_TO_HEIDELTIME); improveSentDe = (Boolean) aContext.getConfigParameterValue(PARAM_IMPROVE_SENTENCE_DE); hsSentenceBeginnings = new HashSet<String>(); hsSentenceBeginnings.add("Januar"); hsSentenceBeginnings.add("Februar"); hsSentenceBeginnings.add("März"); hsSentenceBeginnings.add("April"); hsSentenceBeginnings.add("Mai"); hsSentenceBeginnings.add("Juni"); hsSentenceBeginnings.add("Juli"); hsSentenceBeginnings.add("August"); hsSentenceBeginnings.add("September"); hsSentenceBeginnings.add("Oktober"); hsSentenceBeginnings.add("November"); hsSentenceBeginnings.add("Dezember"); hsSentenceBeginnings.add("Jahrhundert"); hsSentenceBeginnings.add("Jahr"); hsSentenceBeginnings.add("Monat"); hsSentenceBeginnings.add("Woche"); } /** * @see JCasAnnotator_ImplBase#process(JCas) */ public void process(JCas jcas) { if (heidelToDpkro){ // translate the HeidelTime sentences and tokens to DKPro Tagset FSIndex annoSentHeidel = jcas.getAnnotationIndex(de.unihd.dbs.uima.types.heideltime.Sentence.type); FSIterator iterSentHeidel = annoSentHeidel.iterator(); FSIndex annoTokHeidel = jcas.getAnnotationIndex(de.unihd.dbs.uima.types.heideltime.Token.type); FSIterator iterTokHeidel = annoTokHeidel.iterator(); // create DKPro sentences from HeidelTime sentences HashSet<de.unihd.dbs.uima.types.heideltime.Sentence> hsRemoveHeidelSent = new HashSet<de.unihd.dbs.uima.types.heideltime.Sentence>(); while (iterSentHeidel.hasNext()){ de.unihd.dbs.uima.types.heideltime.Sentence s1 = (de.unihd.dbs.uima.types.heideltime.Sentence) iterSentHeidel.next(); de.tudarmstadt.ukp.dkpro.core.type.Sentence s2 = new de.tudarmstadt.ukp.dkpro.core.type.Sentence(jcas); s2.setBegin(s1.getBegin()); s2.setEnd(s1.getEnd()); s2.addToIndexes(); hsRemoveHeidelSent.add(s1); } // create DKPro tokens from HeidelTime tokens HashSet<de.unihd.dbs.uima.types.heideltime.Token> hsRemoveHeidelTok = new HashSet<de.unihd.dbs.uima.types.heideltime.Token>(); while (iterTokHeidel.hasNext()){ de.unihd.dbs.uima.types.heideltime.Token t1 = (de.unihd.dbs.uima.types.heideltime.Token) iterTokHeidel.next(); de.tudarmstadt.ukp.dkpro.core.type.Token t2 = new de.tudarmstadt.ukp.dkpro.core.type.Token(jcas); t2.setBegin(t1.getBegin()); t2.setEnd(t1.getEnd()); t2.addToIndexes(); hsRemoveHeidelTok.add(t1); } } if (dkproToHeidel){ // translate the DKPro sentences, tokens, and pos (with all kind of names) to HeidelTime FSIndex annoSentDkpro = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.Sentence.type); FSIterator iterSentDkpro = annoSentDkpro.iterator(); // get all the HeidelTime sentences, token if they are already available FSIndex annoSentHeidel = jcas.getAnnotationIndex(de.unihd.dbs.uima.types.heideltime.Sentence.type); FSIndex annoTokHeidel = jcas.getAnnotationIndex(de.unihd.dbs.uima.types.heideltime.Token.type); FSIterator iterSentHeidel = annoSentHeidel.iterator(); FSIterator iterTokHeidel = annoTokHeidel.iterator(); HashMap<String, de.unihd.dbs.uima.types.heideltime.Sentence> hmOldSent = new HashMap<String, de.unihd.dbs.uima.types.heideltime.Sentence>(); HashMap<String, de.unihd.dbs.uima.types.heideltime.Token> hmOldTok = new HashMap<String, de.unihd.dbs.uima.types.heideltime.Token>(); while (iterSentHeidel.hasNext()){ de.unihd.dbs.uima.types.heideltime.Sentence s = (de.unihd.dbs.uima.types.heideltime.Sentence) iterSentHeidel.next(); hmOldSent.put(s.getBegin()+"-"+s.getEnd(), s); } while (iterTokHeidel.hasNext()){ de.unihd.dbs.uima.types.heideltime.Token t = (de.unihd.dbs.uima.types.heideltime.Token) iterTokHeidel.next(); hmOldTok.put(t.getBegin()+"-"+t.getEnd(), t); } // create HeidelTime sentences from DKPro sentences HashSet<de.tudarmstadt.ukp.dkpro.core.type.Sentence> hsRemoveDkproSent = new HashSet<de.tudarmstadt.ukp.dkpro.core.type.Sentence>(); HashSet<de.tudarmstadt.ukp.dkpro.core.type.Token> hsRemoveDkproTok = new HashSet<de.tudarmstadt.ukp.dkpro.core.type.Token>(); while (iterSentDkpro.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.Sentence s1 = (de.tudarmstadt.ukp.dkpro.core.type.Sentence) iterSentDkpro.next(); de.unihd.dbs.uima.types.heideltime.Sentence s2 = new de.unihd.dbs.uima.types.heideltime.Sentence(jcas); if (hmOldSent.containsKey(s1.getBegin()+"-"+s1.getEnd())){ s2 = hmOldSent.get(s1.getBegin()+"-"+s1.getEnd()); s2.removeFromIndexes(); } s2.setBegin(s1.getBegin()); s2.setEnd(s1.getEnd()); s2.addToIndexes(); hsRemoveDkproSent.add(s1); FSIterator iterTokDkpro = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.Token.type).subiterator(s1); // create HeidelTime tokens (with POS information) from DKPro tokens and DKPro Pos information while (iterTokDkpro.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.Token t1 = (de.tudarmstadt.ukp.dkpro.core.type.Token) iterTokDkpro.next(); de.unihd.dbs.uima.types.heideltime.Token t2 = new de.unihd.dbs.uima.types.heideltime.Token(jcas); if (hmOldTok.containsKey(t1.getBegin()+"-"+t1.getEnd())){ t2 = hmOldTok.get(t1.getBegin()+"-"+t1.getEnd()); t2.removeFromIndexes(); } t2.setBegin(t1.getBegin()); t2.setEnd(t1.getEnd()); // ADD POS TAGS! FSIterator iterPosAdj = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.pos.ADJ.type).subiterator(s1); FSIterator iterPosAdv = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.pos.ADV.type).subiterator(s1); FSIterator iterPosArt = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.pos.ART.type).subiterator(s1); FSIterator iterPosCard = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.pos.CARD.type).subiterator(s1); FSIterator iterPosConj = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.pos.CONJ.type).subiterator(s1); FSIterator iterPosNn = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.pos.NN.type).subiterator(s1); FSIterator iterPosNp = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.pos.NP.type).subiterator(s1); FSIterator iterPosO = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.pos.O.type).subiterator(s1); FSIterator iterPosPp = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.pos.PP.type).subiterator(s1); FSIterator iterPosPr = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.pos.PR.type).subiterator(s1); FSIterator iterPosPunc = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.pos.PUNC.type).subiterator(s1); FSIterator iterPosV = jcas.getAnnotationIndex(de.tudarmstadt.ukp.dkpro.core.type.pos.V.type).subiterator(s1); while (iterPosAdj.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.pos.ADJ adj = (de.tudarmstadt.ukp.dkpro.core.type.pos.ADJ) iterPosAdj.next(); if ((adj.getBegin() == t2.getBegin()) && (adj.getEnd() == t2.getEnd())){ t2.setPos(adj.getValue()); } } while (iterPosAdv.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.pos.ADV adv = (de.tudarmstadt.ukp.dkpro.core.type.pos.ADV) iterPosAdv.next(); if ((adv.getBegin() == t2.getBegin()) && (adv.getEnd() == t2.getEnd())){ t2.setPos(adv.getValue()); } } while (iterPosArt.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.pos.ART art = (de.tudarmstadt.ukp.dkpro.core.type.pos.ART) iterPosArt.next(); if ((art.getBegin() == t2.getBegin()) && (art.getEnd() == t2.getEnd())){ t2.setPos(art.getValue()); } } while (iterPosCard.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.pos.CARD card = (de.tudarmstadt.ukp.dkpro.core.type.pos.CARD) iterPosCard.next(); if ((card.getBegin() == t2.getBegin()) && (card.getEnd() == t2.getEnd())){ t2.setPos(card.getValue()); } } while (iterPosConj.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.pos.CONJ conj = (de.tudarmstadt.ukp.dkpro.core.type.pos.CONJ) iterPosConj.next(); if ((conj.getBegin() == t2.getBegin()) && (conj.getEnd() == t2.getEnd())){ t2.setPos(conj.getValue()); } } while (iterPosNn.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.pos.NN nn = (de.tudarmstadt.ukp.dkpro.core.type.pos.NN) iterPosNn.next(); if ((nn.getBegin() == t2.getBegin()) && (nn.getEnd() == t2.getEnd())){ t2.setPos(nn.getValue()); } } while (iterPosNp.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.pos.NP np = (de.tudarmstadt.ukp.dkpro.core.type.pos.NP) iterPosNp.next(); if ((np.getBegin() == t2.getBegin()) && (np.getEnd() == t2.getEnd())){ t2.setPos(np.getValue()); } } while (iterPosO.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.pos.O o = (de.tudarmstadt.ukp.dkpro.core.type.pos.O) iterPosO.next(); if ((o.getBegin() == t2.getBegin()) && (o.getEnd() == t2.getEnd())){ t2.setPos(o.getValue()); } } while (iterPosPp.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.pos.PP pp = (de.tudarmstadt.ukp.dkpro.core.type.pos.PP) iterPosPp.next(); if ((pp.getBegin() == t2.getBegin()) && (pp.getEnd() == t2.getEnd())){ t2.setPos(pp.getValue()); } } while (iterPosPr.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.pos.PR pr = (de.tudarmstadt.ukp.dkpro.core.type.pos.PR) iterPosPr.next(); if ((pr.getBegin() == t2.getBegin()) && (pr.getEnd() == t2.getEnd())){ t2.setPos(pr.getValue()); } } while (iterPosPunc.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.pos.PUNC punc = (de.tudarmstadt.ukp.dkpro.core.type.pos.PUNC) iterPosPunc.next(); if ((punc.getBegin() == t2.getBegin()) && (punc.getEnd() == t2.getEnd())){ t2.setPos(punc.getValue()); } } while (iterPosV.hasNext()){ de.tudarmstadt.ukp.dkpro.core.type.pos.V v = (de.tudarmstadt.ukp.dkpro.core.type.pos.V) iterPosV.next(); if ((v.getBegin() == t2.getBegin()) && (v.getEnd() == t2.getEnd())){ t2.setPos(v.getValue()); } } t2.addToIndexes(); hsRemoveDkproTok.add(t1); } } // remove DKPro sentences finally for (de.tudarmstadt.ukp.dkpro.core.type.Sentence s : hsRemoveDkproSent) { s.removeFromIndexes(); } // remove DKPro tokens, finally for (de.tudarmstadt.ukp.dkpro.core.type.Token t1 : hsRemoveDkproTok) { t1.removeFromIndexes(); } } // IMPROVE SENTENCE BOUNDARIES (GERMAN SENTENCE SPLITTER) HashSet<de.unihd.dbs.uima.types.heideltime.Sentence> hsRemoveAnnotations = new HashSet<de.unihd.dbs.uima.types.heideltime.Sentence>(); HashSet<de.unihd.dbs.uima.types.heideltime.Sentence> hsAddAnnotations = new HashSet<de.unihd.dbs.uima.types.heideltime.Sentence>(); if (improveSentDe){ Boolean changes = true; while (changes){ changes = false; FSIndex annoHeidelSentences = jcas.getAnnotationIndex(de.unihd.dbs.uima.types.heideltime.Sentence.type); FSIterator iterHeidelSent = annoHeidelSentences.iterator(); while (iterHeidelSent.hasNext()){ de.unihd.dbs.uima.types.heideltime.Sentence s1 = (de.unihd.dbs.uima.types.heideltime.Sentence) iterHeidelSent.next(); int substringOffset = java.lang.Math.max(s1.getCoveredText().length()-4,1); if (s1.getCoveredText().substring(substringOffset).matches(".*[\\d]+\\.[\\s\\n]*$")){ // System.err.println("Checking sentence 1: successful: "+s1.getCoveredText()); if (iterHeidelSent.hasNext()){ de.unihd.dbs.uima.types.heideltime.Sentence s2 = (de.unihd.dbs.uima.types.heideltime.Sentence) iterHeidelSent.next(); iterHeidelSent.moveToPrevious(); // System.err.println("Checking sentence 2: "+s2.getCoveredText()); for (String beg : hsSentenceBeginnings){ if (s2.getCoveredText().startsWith(beg)){ // System.err.println("Checking sentence 2: successful"); de.unihd.dbs.uima.types.heideltime.Sentence s3 = new de.unihd.dbs.uima.types.heideltime.Sentence(jcas); s3.setBegin(s1.getBegin()); s3.setEnd(s2.getEnd()); hsAddAnnotations.add(s3); hsRemoveAnnotations.add(s1); hsRemoveAnnotations.add(s2); changes = true; break; } } } } } for (de.unihd.dbs.uima.types.heideltime.Sentence s : hsRemoveAnnotations){ s.removeFromIndexes(jcas); } hsRemoveAnnotations.clear(); for (de.unihd.dbs.uima.types.heideltime.Sentence s : hsAddAnnotations){ s.addToIndexes(jcas); } hsAddAnnotations.clear(); } } } }
Java
/** * This is a preprocessing engine for use in a UIMA pipeline. It will invoke * the JVnTextPro api that is supposed to be available in the classpath. */ package de.unihd.dbs.uima.annotator.jvntextprowrapper; import java.io.File; import java.util.LinkedList; import java.util.List; import jmaxent.Classification; import jvnpostag.POSContextGenerator; import jvnpostag.POSDataReader; import jvnsegmenter.CRFSegmenter; import jvnsensegmenter.JVnSenSegmenter; import jvntextpro.JVnTextPro; import jvntextpro.conversion.CompositeUnicode2Unicode; import jvntextpro.data.DataReader; import jvntextpro.data.TWord; import jvntextpro.data.TaggingData; import jvntextpro.util.StringUtils; import jvntokenizer.PennTokenizer; import org.apache.uima.UimaContext; import org.apache.uima.analysis_component.JCasAnnotator_ImplBase; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.jcas.JCas; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; import de.unihd.dbs.uima.types.heideltime.Sentence; import de.unihd.dbs.uima.types.heideltime.Token; /** * @author Julian Zell * */ public class JVnTextProWrapper extends JCasAnnotator_ImplBase { private Class<?> component = this.getClass(); // definitions of what names these parameters have in the wrapper's descriptor file public static final String PARAM_SENTSEGMODEL_PATH = "sent_model_path"; public static final String PARAM_WORDSEGMODEL_PATH = "word_model_path"; public static final String PARAM_POSMODEL_PATH = "pos_model_path"; public static final String PARAM_ANNOTATE_TOKENS = "annotate_tokens"; public static final String PARAM_ANNOTATE_SENTENCES = "annotate_sentences"; public static final String PARAM_ANNOTATE_PARTOFSPEECH = "annotate_partofspeech"; // switches for annotation parameters private Boolean annotate_tokens = false; private Boolean annotate_sentences = false; private Boolean annotate_partofspeech = false; private String sentModelPath = null; private String wordModelPath = null; private String posModelPath = null; // private jvntextpro objects JVnSenSegmenter vnSenSegmenter = new JVnSenSegmenter(); CRFSegmenter vnSegmenter = new CRFSegmenter(); DataReader reader = new POSDataReader(); TaggingData dataTagger = new TaggingData(); Classification classifier = null; /** * initialization method where we fill configuration values and check some prerequisites */ public void initialize(UimaContext aContext) { // get configuration from the descriptor annotate_tokens = (Boolean) aContext.getConfigParameterValue(PARAM_ANNOTATE_TOKENS); annotate_sentences = (Boolean) aContext.getConfigParameterValue(PARAM_ANNOTATE_SENTENCES); annotate_partofspeech = (Boolean) aContext.getConfigParameterValue(PARAM_ANNOTATE_PARTOFSPEECH); sentModelPath = (String) aContext.getConfigParameterValue(PARAM_SENTSEGMODEL_PATH); wordModelPath = (String) aContext.getConfigParameterValue(PARAM_WORDSEGMODEL_PATH); posModelPath = (String) aContext.getConfigParameterValue(PARAM_POSMODEL_PATH); if(sentModelPath != null) if(!vnSenSegmenter.init(sentModelPath)) { Logger.printError(component, "Error initializing the sentence segmenter model: " + sentModelPath); System.exit(-1); } if(wordModelPath != null) try { vnSegmenter.init(wordModelPath); } catch(Exception e) { Logger.printError(component, "Error initializing the word segmenter model: " + wordModelPath); System.exit(-1); } if(posModelPath != null) try { dataTagger.addContextGenerator(new POSContextGenerator(posModelPath + File.separator + "featuretemplate.xml")); classifier = new Classification(posModelPath); } catch(Exception e) { Logger.printError(component, "Error initializing the POS tagging model: " + posModelPath); System.exit(-1); } } /** * Method that gets called to process the documents' cas objects */ public void process(JCas jcas) throws AnalysisEngineProcessException { CompositeUnicode2Unicode convertor = new CompositeUnicode2Unicode(); String origText = jcas.getDocumentText(); final String convertedText = convertor.convert(origText); final String senSegmentedText = vnSenSegmenter.senSegment(convertedText).trim(); final String tokenizedText = PennTokenizer.tokenize(senSegmentedText).trim(); final String segmentedText = vnSegmenter.segmenting(tokenizedText); final String postProcessedString = (new JVnTextPro()).postProcessing(segmentedText).trim(); List<jvntextpro.data.Sentence> posSentences = jvnTagging(postProcessedString); LinkedList<TWord> posWords = new LinkedList<TWord>(); for(jvntextpro.data.Sentence sent : posSentences) for(Integer i = 0; i < sent.size(); ++i) posWords.add(sent.getTWordAt(i)); /* * annotate sentences */ if(annotate_sentences) { Integer offset = 0; String[] sentences = senSegmentedText.split("\n"); for(String sentence : sentences) { Sentence s = new Sentence(jcas); sentence = sentence.trim(); Integer sentOffset = origText.indexOf(sentence, offset); if(sentOffset >= 0) { s.setBegin(sentOffset); offset = sentOffset + sentence.length(); s.setEnd(offset); s.addToIndexes(); } else { sentence = sentence.substring(0, sentence.length() - 1).trim(); sentOffset = origText.indexOf(sentence, offset); if(sentOffset >= 0) { s.setBegin(sentOffset); offset = sentOffset + sentence.length(); s.setEnd(offset); s.addToIndexes(); } else { System.err.println("Sentence \"" + sentence + "\" was not found in the original text."); } } } } /* * annotate tokens */ if(annotate_tokens) { Integer offset = 0; String[] tokens = postProcessedString.split("\\s+"); for(Integer i = 0; i < tokens.length; ++i) { final String token = tokens[i].trim(); String thisPosTag = null; if(posWords.size() >= i + 1) { if(!token.equals(posWords.get(i).getWord())) { System.err.println("Couldn't match token: " + token + " to expected word/tag combination " + posWords.get(i).getWord()); } else { thisPosTag = posWords.get(i).getTag(); } } Integer tokenOffset = origText.indexOf(token, offset); Token t = new Token(jcas); if(tokenOffset >= 0 ) { /* * first, try to find the string in the form the tokenizer returned it */ t.setBegin(tokenOffset); offset = tokenOffset + token.length(); t.setEnd(offset); sanitizeToken(t, jcas); if(annotate_tokens) t.setPos(thisPosTag); t.addToIndexes(); } else { /* * straight up token not found. * assume that it is a compound word (e.g. some_thing) * and try to find it in the original text again; first using * a "_" -> " " replacement, then try just removing the underscore. */ String underscoreToSpaceToken = token.replaceAll("_", " "); Integer spaceOffset = origText.indexOf(underscoreToSpaceToken, offset); String underscoreRemovedToken = token.replaceAll("_", ""); Integer removedOffset = origText.indexOf(underscoreRemovedToken, offset); /* * offsets are the same. can't think of a good example where this could * possibly happen, but maybe there is one. */ if(removedOffset >= 0 && spaceOffset >= 0) { if(removedOffset >= spaceOffset) { t.setBegin(spaceOffset); offset = spaceOffset + underscoreToSpaceToken.length(); t.setEnd(offset); sanitizeToken(t, jcas); if(annotate_tokens) t.setPos(thisPosTag); t.addToIndexes(); } else { t.setBegin(removedOffset); offset = removedOffset + underscoreRemovedToken.length(); t.setEnd(offset); sanitizeToken(t, jcas); t.addToIndexes(); } } /* * underscore removed was found, underscore replaced to space was not */ else if(removedOffset >= 0 && spaceOffset == -1) { t.setBegin(removedOffset); offset = removedOffset + underscoreRemovedToken.length(); t.setEnd(offset); sanitizeToken(t, jcas); if(annotate_tokens) t.setPos(thisPosTag); t.addToIndexes(); } /* * underscore removed was not found, underscore replaced was found */ else if(removedOffset == -1 && spaceOffset >= 0) { t.setBegin(spaceOffset); offset = spaceOffset + underscoreToSpaceToken.length(); t.setEnd(offset); sanitizeToken(t, jcas); if(annotate_tokens) t.setPos(thisPosTag); t.addToIndexes(); } /* * there is no hope of finding this token */ else { System.err.println("Token \"" + token + "\" was not found in the original text."); } } } } } private Boolean sanitizeToken(Token t, JCas jcas) { Boolean workDone = false; // check the beginning of the token for punctuation and split off into a new token if(t.getCoveredText().matches("^\\p{Punct}.*") && t.getCoveredText().length() > 1) { Character thisChar = t.getCoveredText().charAt(0); t.setBegin(t.getBegin() + 1); // set corrected token boundary for the word Token puncToken = new Token(jcas); // create a new token for the punctuation character puncToken.setBegin(t.getBegin() - 1); puncToken.setEnd(t.getBegin()); // check if we want to annotate pos or the token itself if(annotate_partofspeech) puncToken.setPos(""+thisChar); if(annotate_tokens) puncToken.addToIndexes(); workDone = true; } // check the end of the token for punctuation and split off into a new token if(t.getCoveredText().matches(".*\\p{Punct}$") && t.getCoveredText().length() > 1) { Character thisChar = t.getCoveredText().charAt(t.getEnd() - t.getBegin() - 1); t.setEnd(t.getEnd() - 1); // set corrected token boundary for the word Token puncToken = new Token(jcas); // create a new token for the punctuation character puncToken.setBegin(t.getEnd()); puncToken.setEnd(t.getEnd() + 1); // check if we want to annotate pos or the token itself if(annotate_partofspeech) puncToken.setPos(""+thisChar); if(annotate_tokens) puncToken.addToIndexes(); workDone = true; } // get into a recursion to sanitize tokens as long as there are stray ones if(workDone) { workDone = sanitizeToken(t, jcas); } return workDone; } /** * Taken from the JVnTextPro package and adapted to not output a string * @param instr input string to be tagged * @return tagged text */ public List<jvntextpro.data.Sentence> jvnTagging(String instr) { List<jvntextpro.data.Sentence> data = reader.readString(instr); for (int i = 0; i < data.size(); ++i) { jvntextpro.data.Sentence sent = data.get(i); for (int j = 0; j < sent.size(); ++j) { String [] cps = dataTagger.getContext(sent, j); String label = classifier.classify(cps); if (label.equalsIgnoreCase("Mrk")) { if (StringUtils.isPunc(sent.getWordAt(j))) label = sent.getWordAt(j); else label = "X"; } sent.getTWordAt(j).setTag(label); } } return data; } }
Java
/** * This is a preprocessing engine for use in a UIMA pipeline. It will invoke * functions from the Stanford POS Tagger to tokenize words and sentences * and add part of speech tags to the pipeline. */ package de.unihd.dbs.uima.annotator.stanfordtagger; import java.io.File; import java.io.FileInputStream; import java.io.StringReader; import java.util.List; import java.util.ListIterator; import java.util.Properties; import org.apache.uima.UimaContext; import org.apache.uima.analysis_component.JCasAnnotator_ImplBase; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.FSIterator; import org.apache.uima.jcas.JCas; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; import de.unihd.dbs.uima.types.heideltime.Sentence; import de.unihd.dbs.uima.types.heideltime.Token; import edu.stanford.nlp.ling.HasWord; import edu.stanford.nlp.ling.TaggedWord; import edu.stanford.nlp.ling.Word; import edu.stanford.nlp.process.TokenizerFactory; import edu.stanford.nlp.tagger.maxent.MaxentTagger; import edu.stanford.nlp.tagger.maxent.TaggerConfig; import edu.stanford.nlp.process.PTBTokenizer.PTBTokenizerFactory; /** * @author Julian Zell * */ public class StanfordPOSTaggerWrapper extends JCasAnnotator_ImplBase { private Class<?> component = this.getClass(); // definitions of what names these parameters have in the wrapper's descriptor file public static final String PARAM_MODEL_PATH = "model_path"; public static final String PARAM_CONFIG_PATH = "config_path"; public static final String PARAM_ANNOTATE_TOKENS = "annotate_tokens"; public static final String PARAM_ANNOTATE_SENTENCES = "annotate_sentences"; public static final String PARAM_ANNOTATE_PARTOFSPEECH = "annotate_partofspeech"; // switches for annotation parameters private String model_path; private String config_path; private Boolean annotate_tokens = false; private Boolean annotate_sentences = false; private Boolean annotate_partofspeech = false; // Maximum Entropy Tagger from the Stanford POS Tagger private MaxentTagger mt; /** * initialization method where we fill configuration values and check some prerequisites */ public void initialize(UimaContext aContext) { // get configuration from the descriptor annotate_tokens = (Boolean) aContext.getConfigParameterValue(PARAM_ANNOTATE_TOKENS); annotate_sentences = (Boolean) aContext.getConfigParameterValue(PARAM_ANNOTATE_SENTENCES); annotate_partofspeech = (Boolean) aContext.getConfigParameterValue(PARAM_ANNOTATE_PARTOFSPEECH); model_path = (String) aContext.getConfigParameterValue(PARAM_MODEL_PATH); config_path = (String) aContext.getConfigParameterValue(PARAM_CONFIG_PATH); // check if the model file exists if(model_path == null || (new File(model_path)).exists() == false) { Logger.printError(component, "The supplied model file for the Stanford Tagger could not be found."); System.exit(-1); } // try instantiating the MaxEnt Tagger try { if(config_path != null) { // configuration exists FileInputStream isr = new FileInputStream(config_path); Properties props = new Properties(); props.load(isr); mt = new MaxentTagger(model_path, new TaggerConfig(props), false); } else { // instantiate without configuration file mt = new MaxentTagger(model_path, new TaggerConfig("-model", model_path), false); } } catch(Exception e) { e.printStackTrace(); Logger.printError(component, "MaxentTagger could not be instantiated with the supplied model("+model_path+") and config("+config_path+") file."); System.exit(-1); } } /** * Method that gets called to process the documents' cas objects */ public void process(JCas jcas) throws AnalysisEngineProcessException { Integer offset = 0; // a cursor of sorts to keep up with the position in the document text // grab the document text String docText = jcas.getDocumentText(); // get [sentence-tokens[word-tokens]] from the MaxentTagger TokenizerFactory<Word> fac = PTBTokenizerFactory.newTokenizerFactory(); fac.setOptions("ptb3Escaping=false,untokenizable=noneKeep"); List<List<HasWord>> tokenArray = MaxentTagger.tokenizeText(new StringReader(docText), fac); // iterate over sentences in this document for(List<HasWord> sentenceToken : tokenArray) { List<TaggedWord> taggedSentence = mt.tagSentence(sentenceToken); ListIterator<TaggedWord> twit = taggedSentence.listIterator(); // create a sentence object. gets added to index or discarded depending on configuration Sentence sentence = new Sentence(jcas); sentence.setBegin(offset); Integer wordCount = 0; // iterate over words in this sentence for(HasWord wordToken : sentenceToken) { Token t = new Token(jcas); TaggedWord tw = twit.next(); // if pos is supposed to be added, iterate through the tagged tokens and set pos if(annotate_partofspeech) { t.setPos(tw.tag()); } String thisWord = wordToken.word(); if(docText.indexOf(thisWord, offset) < 0) { Logger.printDetail(component, "A previously tagged token wasn't found in the document text: \"" + thisWord + "\". " + "This may be due to unpredictable punctuation tokenization; hence this token isn't tagged."); continue; // jump to next token: discards token } else { offset = docText.indexOf(thisWord, offset); // set cursor to the starting position of token in docText t.setBegin(offset); ++wordCount; } offset += thisWord.length(); // move cursor behind the word t.setEnd(offset); // add tokens to indexes. if(annotate_tokens) { t.addToIndexes(); } } // if flag is set, also tag sentences if(annotate_sentences) { if(wordCount == 0) sentence.setEnd(offset); else sentence.setEnd(offset-1); sentence.addToIndexes(); } } // TODO: DEBUG FSIterator fsi = jcas.getAnnotationIndex(Sentence.type).iterator(); while(fsi.hasNext()) { Sentence s = (Sentence) fsi.next(); if(s.getBegin() < 0 || s.getEnd() < 0) { System.err.println("Sentence: " + s.getBegin() + ":" + s.getEnd() + " = " + s.getCoveredText()); System.err.println("wrong index in text: " + jcas.getDocumentText()); System.exit(-1); } } FSIterator fsi2 = jcas.getAnnotationIndex(Token.type).iterator(); while(fsi2.hasNext()) { Token t = (Token) fsi2.next(); if(t.getBegin() < 0 || t.getEnd() < 0) { System.err.println("In text: " + jcas.getDocumentText()); System.err.println("Token: " + t.getBegin() + ":" + t.getEnd()); System.exit(-1); } } } }
Java
package de.unihd.dbs.uima.annotator.intervaltagger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.uima.UimaContext; import org.apache.uima.analysis_component.JCasAnnotator_ImplBase; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.FSIterator; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import de.unihd.dbs.uima.annotator.heideltime.resources.Language; import de.unihd.dbs.uima.annotator.heideltime.resources.RePatternManager; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; import de.unihd.dbs.uima.annotator.heideltime.utilities.Toolbox; import de.unihd.dbs.uima.types.heideltime.IntervalCandidateSentence; import de.unihd.dbs.uima.types.heideltime.Sentence; import de.unihd.dbs.uima.types.heideltime.Timex3; import de.unihd.dbs.uima.types.heideltime.Timex3Interval; /** * IntervalTagger is a UIMA annotator that discovers and tags intervals in documents. * @author Manuel Dewald, Julian Zell * */ public class IntervalTagger extends JCasAnnotator_ImplBase { // TOOL NAME (may be used as componentId) private Class<?> component = this.getClass(); // descriptor parameter names public static String PARAM_LANGUAGE = "language"; public static String PARAM_INTERVALS = "annotate_intervals"; public static String PARAM_INTERVAL_CANDIDATES = "annotate_interval_candidates"; // descriptor configuration private Language language = null; private Boolean find_intervals = true; private Boolean find_interval_candidates = true; private HashMap<Pattern, String> hmIntervalPattern = new HashMap<Pattern, String>(); private HashMap<String, String> hmIntervalNormalization = new HashMap<String, String>(); /** * initialization: read configuration parameters and resources */ public void initialize(UimaContext aContext) throws ResourceInitializationException { super.initialize(aContext); language = Language.getLanguageFromString((String) aContext.getConfigParameterValue(PARAM_LANGUAGE)); find_intervals = (Boolean) aContext.getConfigParameterValue(PARAM_INTERVALS); find_interval_candidates = (Boolean) aContext.getConfigParameterValue(PARAM_INTERVAL_CANDIDATES); readResources(readResourcesFromDirectory("rules")); } /** * called by the pipeline to process the document */ public void process(JCas jcas) throws AnalysisEngineProcessException { if(find_intervals) { findIntervals(jcas); findSentenceIntervals(jcas); } } /** * reads in heideltime's resource files. * @throws ResourceInitializationException */ private void readResources(HashMap<String, String> hmResourcesRules) throws ResourceInitializationException { Pattern paReadRules = Pattern.compile("RULENAME=\"(.*?)\",EXTRACTION=\"(.*?)\",NORM_VALUE=\"(.*?)\"(.*)"); // read normalization data try { for (String resource : hmResourcesRules.keySet()) { BufferedReader br = new BufferedReader(new InputStreamReader (this.getClass().getClassLoader().getResourceAsStream(hmResourcesRules.get(resource)))); Logger.printDetail(component, "Adding rule resource: "+resource); for ( String line; (line=br.readLine()) != null; ) { if (!(line.startsWith("//"))) { boolean correctLine = false; if (!(line.equals(""))) { Logger.printDetail("DEBUGGING: reading rules..."+ line); // check each line for the name, extraction, and normalization part for (MatchResult r : Toolbox.findMatches(paReadRules, line)) { correctLine = true; String rule_name = r.group(1); String rule_extraction = r.group(2); String rule_normalization = r.group(3); //////////////////////////////////////////////////////////////////// // RULE EXTRACTION PARTS ARE TRANSLATED INTO REGULAR EXPRESSSIONS // //////////////////////////////////////////////////////////////////// // create pattern for rule extraction part Pattern paVariable = Pattern.compile("%(re[a-zA-Z0-9]*)"); RePatternManager rpm = RePatternManager.getInstance(language); for (MatchResult mr : Toolbox.findMatches(paVariable,rule_extraction)) { Logger.printDetail("DEBUGGING: replacing patterns..."+ mr.group()); if (!(rpm.containsKey(mr.group(1)))) { Logger.printError("Error creating rule:"+rule_name); Logger.printError("The following pattern used in this rule does not exist, does it? %"+mr.group(1)); System.exit(-1); } rule_extraction = rule_extraction.replaceAll("%"+mr.group(1), rpm.get(mr.group(1))); } rule_extraction = rule_extraction.replaceAll(" ", "[\\\\s]+"); Pattern pattern = null; try{ pattern = Pattern.compile(rule_extraction); } catch (java.util.regex.PatternSyntaxException e) { Logger.printError("Compiling rules resulted in errors."); Logger.printError("Problematic rule is "+rule_name); Logger.printError("Cannot compile pattern: "+rule_extraction); e.printStackTrace(); System.exit(-1); } ///////////////////////////////////////////////// // READ INTERVAL RULES AND MAKE THEM AVAILABLE // ///////////////////////////////////////////////// if(resource.equals("intervalrules")){ hmIntervalPattern.put(pattern,rule_name); hmIntervalNormalization.put(rule_name, rule_normalization); } } } /////////////////////////////////////////// // CHECK FOR PROBLEMS WHEN READING RULES // /////////////////////////////////////////// if ((correctLine == false) && (!(line.matches("")))) { Logger.printError(component, "Cannot read the following line of rule resource "+resource); Logger.printError(component, "Line: "+line); } } } } } catch (IOException e) { e.printStackTrace(); throw new ResourceInitializationException(); } } /** * Reads resource files of the type resourceType from the "used_resources.txt" file and returns a HashMap * containing information to access these resources. * @return HashMap containing filename/path tuples */ protected HashMap<String, String> readResourcesFromDirectory(String resourceType) { HashMap<String, String> hmResources = new HashMap<String, String>(); BufferedReader br = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("used_resources.txt"))); try { for (String line; (line=br.readLine()) != null; ) { String pathDelim = System.getProperty("file.separator"); Pattern paResource = Pattern.compile(".(?:\\"+pathDelim+"|/)?(\\"+pathDelim+"|/)"+language.getResourceFolder()+"(?:\\"+pathDelim+"|/)"+resourceType+"(?:\\"+pathDelim+"|/)"+"resources_"+resourceType+"_"+"(.*?)\\.txt"); for (MatchResult ro : Toolbox.findMatches(paResource, line)){ pathDelim = ro.group(1); String foundResource = ro.group(2); String pathToResource = language.getResourceFolder()+ro.group(1)+resourceType+ro.group(1)+"resources_"+resourceType+"_"+foundResource+".txt"; hmResources.put(foundResource, pathToResource); } } } catch (IOException e) { e.printStackTrace(); Logger.printError(component, "Failed to read a resource from used_resources.txt."); System.exit(-1); } return hmResources; } /** * Extract Timex3Intervals, delimited by two Timex3Intervals in a sentence. * finsInterval needs to be run with jcas before. * @param jcas * @author Manuel Dewald */ private void findSentenceIntervals(JCas jcas){ HashSet<Timex3Interval> timexesToRemove = new HashSet<Timex3Interval>(); FSIterator iterSentence = jcas.getAnnotationIndex(Sentence.type).iterator(); while (iterSentence.hasNext()) { Sentence s=(Sentence)iterSentence.next(); String sString=s.getCoveredText(); FSIterator iterInter = jcas.getAnnotationIndex(Timex3Interval.type).subiterator(s); int count=0; List<Timex3Interval> txes=new ArrayList<Timex3Interval>(); List<Timex3Interval> sentenceTxes=new ArrayList<Timex3Interval>(); while(iterInter.hasNext()){ Timex3Interval t=(Timex3Interval)iterInter.next(); sString=sString.replace(t.getCoveredText(), "<TX3_"+count+">"); count++; txes.add(t); } if(count>0){ if (find_interval_candidates){ IntervalCandidateSentence sI=new IntervalCandidateSentence(jcas); sI.setBegin(s.getBegin()); sI.setEnd(s.getEnd()); sI.addToIndexes(); } for(Pattern p: hmIntervalPattern.keySet()){ String name=hmIntervalPattern.get(p); List<MatchResult>results=(List<MatchResult>)Toolbox.findMatches(p,sString); if(results.size()>0){ //Interval in Sentence s found by Pattern p! for(MatchResult r: results){ Pattern pNorm=Pattern.compile("group\\(([1-9]+)\\)-group\\(([1-9]+)\\)"); String norm=hmIntervalNormalization.get(name); Matcher mNorm=pNorm.matcher(norm); if(!mNorm.matches()){ System.err.println("Problem with the Norm in rule "+name); } Timex3Interval startTx=null,endTx=null; try{ int startId=Integer.parseInt(mNorm.group(1)); int endId=Integer.parseInt(mNorm.group(2)); startTx=txes.get(Integer.parseInt(r.group(startId))); endTx=txes.get(Integer.parseInt(r.group(endId))); }catch(Exception e){ e.printStackTrace(); return; } Timex3Interval annotation=new Timex3Interval(jcas); annotation.setBegin(startTx.getBegin()>endTx.getBegin()?endTx.getBegin():startTx.getBegin()); annotation.setEnd(startTx.getEnd()>endTx.getEnd()?startTx.getEnd():endTx.getEnd()); //Does the interval already exist, //found by another pattern? boolean duplicate=false; for(Timex3Interval tx:sentenceTxes){ if(tx.getBegin()==annotation.getBegin() && tx.getEnd()==annotation.getEnd()){ duplicate=true; break; } } if(!duplicate){ annotation.setTimexValueEB(startTx.getTimexValueEB()); annotation.setTimexValueLB(startTx.getTimexValueEE()); annotation.setTimexValueEE(endTx.getTimexValueEB()); annotation.setTimexValueLE(endTx.getTimexValueEE()); annotation.setTimexType(startTx.getTimexType()); annotation.setFoundByRule(name); // create emptyvalue value String emptyValue = createEmptyValue(startTx, endTx, jcas); annotation.setEmptyValue(emptyValue); annotation.setBeginTimex(startTx.getBeginTimex()); annotation.setEndTimex(endTx.getEndTimex()); try { sentenceTxes.add(annotation); } catch(NumberFormatException e) { Logger.printError(component, "Couldn't do emptyValue calculation on accont of a faulty normalization in " + annotation.getTimexValueEB() + " or " + annotation.getTimexValueEE()); } // prepare tx3intervals to remove timexesToRemove.add(startTx); timexesToRemove.add(endTx); annotation.addToIndexes(); // System.out.println(emptyValue); } } } } } } for(Timex3Interval txi : timexesToRemove) { txi.removeFromIndexes(); } } private String createEmptyValue(Timex3Interval startTx, Timex3Interval endTx, JCas jcas) throws NumberFormatException { String dateStr = "", timeStr = ""; // find granularity for start/end timex values Pattern p = Pattern.compile("(\\d{1,4})?-?(\\d{2})?-?(\\d{2})?(T)?(\\d{2})?:?(\\d{2})?:?(\\d{2})?"); // 1 2 3 4 5 6 7 Matcher mStart = p.matcher(startTx.getTimexValue()); Matcher mEnd = p.matcher(endTx.getTimexValue()); Integer granularityStart = -1; Integer granularityEnd = -2; Integer granularity = -1; // find the highest granularity in each timex if(mStart.find() && mEnd.find()) { for(Integer i = 1; i <= mStart.groupCount(); i++) { if(mStart.group(i) != null) granularityStart = i; if(mEnd.group(i) != null) granularityEnd = i; } } // if granularities aren't the same, we can't do anything here. if(granularityEnd != granularityStart) { return ""; } else { // otherwise, set maximum granularity granularity = granularityStart; } // check all the different granularities, starting with seconds, calculate differences, add carries Integer myYears = 0, myMonths = 0, myDays = 0, myHours = 0, myMinutes = 0, mySeconds = 0; if(granularity >= 7 && mStart.group(7) != null && mEnd.group(7) != null) { mySeconds = Integer.parseInt(mEnd.group(7)) - Integer.parseInt(mStart.group(7)); if(mySeconds < 0) { mySeconds += 60; myMinutes -= 1; } } if(granularity >= 6 && mStart.group(6) != null && mEnd.group(6) != null) { myMinutes += Integer.parseInt(mEnd.group(6)) - Integer.parseInt(mStart.group(6)); if(myMinutes < 0) { myMinutes += 60; myHours -= 1; } } if(granularity >= 5 && mStart.group(5) != null && mEnd.group(5) != null) { myHours += Integer.parseInt(mEnd.group(5)) - Integer.parseInt(mStart.group(5)); if(myHours < 0) { myMinutes += 24; myDays -= 1; } } if(granularity >= 3 && mStart.group(3) != null && mEnd.group(3) != null) { myDays += Integer.parseInt(mEnd.group(3)) - Integer.parseInt(mStart.group(3)); if(myDays < 0) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, Integer.parseInt(mStart.group(1))); cal.set(Calendar.MONTH, Integer.parseInt(mStart.group(2))); myMonths = myMonths - 1; myDays += cal.getActualMaximum(Calendar.DAY_OF_MONTH); } } if(granularity >= 2 && mStart.group(2) != null && mEnd.group(2) != null) { myMonths += Integer.parseInt(mEnd.group(2)) - Integer.parseInt(mStart.group(2)); if(myMonths < 0) { myMonths += Integer.parseInt(mStart.group(2)); myYears -= 1; } } String myYearUnit = ""; if(granularity >= 1 && mStart.group(1) != null && mEnd.group(1) != null) { String year1str = mStart.group(1), year2str = mEnd.group(1); // trim year strings to same length (NNNN year, NNN decade, NN century) while(year2str.length() > year1str.length()) year2str = year2str.substring(0, year2str.length()-1); while(year1str.length() > year2str.length()) year1str = year1str.substring(0, year1str.length()-1); // check for year unit switch(year1str.length()) { case 2: myYearUnit = "CE"; myYears = Integer.parseInt(year2str) - Integer.parseInt(year1str); break; case 3: myYearUnit = "DE"; myYears = Integer.parseInt(year2str) - Integer.parseInt(year1str); break; case 4: myYearUnit = "Y"; myYears += Integer.parseInt(year2str) - Integer.parseInt(year1str); break; default: break; } } // assemble strings dateStr += (myYears > 0 ? myYears + myYearUnit : ""); dateStr += (myMonths > 0 ? myMonths + "M" : ""); dateStr += (myDays > 0 ? myDays + "D" : ""); timeStr += (myHours > 0 ? myHours + "H" : ""); timeStr += (myMinutes > 0 ? myMinutes + "M" : ""); timeStr += (mySeconds > 0 ? mySeconds + "S" : ""); // output return "P" + dateStr + (timeStr.length() > 0 ? "T" + timeStr : ""); } /** * Build Timex3Interval-Annotations out of Timex3Annotations in jcas. * @author Manuel Dewald * @param jcas */ private void findIntervals(JCas jcas) { ArrayList<Timex3Interval> newAnnotations = new ArrayList<Timex3Interval>(); FSIterator iterTimex3 = jcas.getAnnotationIndex(Timex3.type).iterator(); while (iterTimex3.hasNext()) { Timex3Interval annotation=new Timex3Interval(jcas); Timex3 timex3 = (Timex3) iterTimex3.next(); //DATE Pattern Pattern pDate = Pattern.compile("(\\d+)(-(\\d+))?(-(\\d+))?(T(\\d+))?(:(\\d+))?(:(\\d+))?"); Pattern pCentury = Pattern.compile("(\\d\\d)"); Pattern pDecate = Pattern.compile("(\\d\\d\\d)"); Pattern pQuarter = Pattern.compile("(\\d+)-Q([1-4])"); Pattern pHalf = Pattern.compile("(\\d+)-H([1-2])"); Pattern pSeason = Pattern.compile("(\\d+)-(SP|SU|FA|WI)"); Pattern pWeek = Pattern.compile("(\\d+)-W(\\d+)"); Pattern pWeekend = Pattern.compile("(\\d+)-W(\\d+)-WE"); Pattern pTimeOfDay = Pattern.compile("(\\d+)-(\\d+)-(\\d+)T(AF|DT|MI|MO|EV|NI)"); Matcher mDate = pDate.matcher(timex3.getTimexValue()); Matcher mCentury= pCentury.matcher(timex3.getTimexValue()); Matcher mDecade = pDecate.matcher(timex3.getTimexValue()); Matcher mQuarter= pQuarter.matcher(timex3.getTimexValue()); Matcher mHalf = pHalf.matcher(timex3.getTimexValue()); Matcher mSeason = pSeason.matcher(timex3.getTimexValue()); Matcher mWeek = pWeek.matcher(timex3.getTimexValue()); Matcher mWeekend= pWeekend.matcher(timex3.getTimexValue()); Matcher mTimeOfDay= pTimeOfDay.matcher(timex3.getTimexValue()); boolean matchesDate=mDate.matches(); boolean matchesCentury=mCentury.matches(); boolean matchesDecade=mDecade.matches(); boolean matchesQuarter=mQuarter.matches(); boolean matchesHalf=mHalf.matches(); boolean matchesSeason=mSeason.matches(); boolean matchesWeek=mWeek.matches(); boolean matchesWeekend=mWeekend.matches(); boolean matchesTimeOfDay=mTimeOfDay.matches(); String beginYear, endYear; String beginMonth, endMonth; String beginDay, endDay; String beginHour, endHour; String beginMinute, endMinute; String beginSecond, endSecond; beginYear=endYear="UNDEF"; beginMonth="01"; endMonth="12"; beginDay="01"; endDay="31"; beginHour="00"; endHour="23"; beginMinute="00"; endMinute="59"; beginSecond="00"; endSecond="59"; if(matchesDate){ //Get Year(1) beginYear=endYear=mDate.group(1); //Get Month(3) if(mDate.group(3)!=null){ beginMonth=endMonth=mDate.group(3); //Get Day(5) if(mDate.group(5)==null){ Calendar c=Calendar.getInstance(); c.set(Integer.parseInt(beginYear), Integer.parseInt(beginMonth)-1, 1); endDay=""+c.getActualMaximum(Calendar.DAY_OF_MONTH); beginDay="01"; }else{ beginDay=endDay=mDate.group(5); //Get Hour(7) if(mDate.group(7)!=null){ beginHour=endHour=mDate.group(7); //Get Minute(9) if(mDate.group(9)!=null){ beginMinute=endMinute=mDate.group(9); //Get Second(11) if(mDate.group(11)!=null){ beginSecond=endSecond=mDate.group(11); } } } } } }else if(matchesCentury){ beginYear=mCentury.group(1)+"00"; endYear=mCentury.group(1)+"99"; }else if(matchesDecade){ beginYear=mDecade.group(1)+"0"; endYear=mDecade.group(1)+"9"; }else if(matchesQuarter){ beginYear=endYear=mQuarter.group(1); int beginMonthI=3*(Integer.parseInt(mQuarter.group(2))-1)+1; beginMonth=""+beginMonthI; endMonth=""+(beginMonthI+2); Calendar c=Calendar.getInstance(); c.set(Integer.parseInt(beginYear), Integer.parseInt(endMonth)-1, 1); endDay=""+c.getActualMaximum(Calendar.DAY_OF_MONTH); }else if(matchesHalf){ beginYear=endYear=mHalf.group(1); int beginMonthI=6*(Integer.parseInt(mHalf.group(2))-1)+1; beginMonth=""+beginMonthI; endMonth=""+(beginMonthI+5); Calendar c=Calendar.getInstance(); c.set(Integer.parseInt(beginYear), Integer.parseInt(endMonth)-1, 1); endDay=""+c.getActualMaximum(Calendar.DAY_OF_MONTH); }else if(matchesSeason){ beginYear=mSeason.group(1); endYear=beginYear; if(mSeason.group(2).equals("SP")){ beginMonth="03"; beginDay="21"; endMonth="06"; endDay="20"; }else if(mSeason.group(2).equals("SU")){ beginMonth="06"; beginDay="21"; endMonth="09"; endDay="22"; }else if(mSeason.group(2).equals("FA")){ beginMonth="09"; beginDay="23"; endMonth="12"; endDay="21"; }else if(mSeason.group(2).equals("WI")){ endYear=""+(Integer.parseInt(beginYear)+1); beginMonth="12"; beginDay="22"; endMonth="03"; endDay="20"; } }else if(matchesWeek){ beginYear=endYear=mWeek.group(1); Calendar c=Calendar.getInstance(); c.setFirstDayOfWeek(Calendar.MONDAY); c.set(Calendar.YEAR,Integer.parseInt(beginYear)); c.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(mWeek.group(2))); c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); beginDay=""+c.get(Calendar.DAY_OF_MONTH); beginMonth=""+(c.get(Calendar.MONTH)+1); c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); endDay=""+(c.get(Calendar.DAY_OF_MONTH)); endMonth=""+(c.get(Calendar.MONTH)+1); }else if(matchesWeekend){ beginYear=endYear=mWeekend.group(1); Calendar c=Calendar.getInstance(); c.setFirstDayOfWeek(Calendar.MONDAY); c.set(Calendar.YEAR,Integer.parseInt(beginYear)); c.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(mWeekend.group(2))); c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY); beginDay=""+c.get(Calendar.DAY_OF_MONTH); beginMonth=""+(c.get(Calendar.MONTH)+1); c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); endDay=""+(c.get(Calendar.DAY_OF_MONTH)); endMonth=""+(c.get(Calendar.MONTH)+1); }else if(matchesTimeOfDay){ beginYear=endYear=mTimeOfDay.group(1); beginMonth=endMonth=mTimeOfDay.group(2); beginDay=endDay=mTimeOfDay.group(3); } if(!beginYear.equals("UNDEF") && !endYear.equals("UNDEF")){ annotation.setTimexValueEB(beginYear+"-"+beginMonth+"-"+beginDay+"T"+beginHour+":"+beginMinute+":"+beginSecond); annotation.setTimexValueEE(endYear+"-"+endMonth+"-"+endDay+"T"+endHour+":"+endMinute+":"+endSecond); annotation.setTimexValueLB(beginYear+"-"+beginMonth+"-"+beginDay+"T"+beginHour+":"+beginMinute+":"+beginSecond); annotation.setTimexValueLE(endYear+"-"+endMonth+"-"+endDay+"T"+endHour+":"+endMinute+":"+endSecond); //Copy Values from the Timex3 Annotation annotation.setTimexFreq(timex3.getTimexFreq()); annotation.setTimexId(timex3.getTimexId()); annotation.setTimexInstance(timex3.getTimexInstance()); annotation.setTimexMod(timex3.getTimexMod()); annotation.setTimexQuant(timex3.getTimexMod()); annotation.setTimexType(timex3.getTimexType()); annotation.setTimexValue(timex3.getTimexValue()); annotation.setSentId(timex3.getSentId()); annotation.setBegin(timex3.getBegin()); annotation.setFoundByRule(timex3.getFoundByRule()); annotation.setEnd(timex3.getEnd()); annotation.setAllTokIds(timex3.getAllTokIds()); annotation.setFilename(timex3.getFilename()); annotation.setBeginTimex(timex3.getTimexId()); annotation.setEndTimex(timex3.getTimexId()); // remember this one for addition to indexes later newAnnotations.add(annotation); } } // add to indexes for(Timex3Interval t3i : newAnnotations) t3i.addToIndexes(); } }
Java
/** * This is a preprocessing engine for use in a UIMA pipeline. It will invoke * the tree-tagger binary that is supposed to be available on the system * through Java process access. */ package de.unihd.dbs.uima.annotator.treetagger; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashSet; import org.apache.uima.UimaContext; import org.apache.uima.analysis_component.JCasAnnotator_ImplBase; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.FSIndex; import org.apache.uima.cas.FSIterator; import org.apache.uima.impl.RootUimaContext_impl; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ConfigurationManager; import org.apache.uima.resource.impl.ConfigurationManager_impl; import org.apache.uima.resource.impl.ResourceManager_impl; import de.unihd.dbs.uima.annotator.heideltime.resources.Language; import de.unihd.dbs.uima.annotator.heideltime.utilities.Logger; import de.unihd.dbs.uima.types.heideltime.Sentence; import de.unihd.dbs.uima.types.heideltime.Token; /** * @author Andreas Fay, Julian Zell * */ public class TreeTaggerWrapper extends JCasAnnotator_ImplBase { private Class<?> component = this.getClass(); // definitions of what names these parameters have in the wrapper's descriptor file public static final String PARAM_LANGUAGE = "language"; public static final String PARAM_ANNOTATE_TOKENS = "annotate_tokens"; public static final String PARAM_ANNOTATE_SENTENCES = "annotate_sentences"; public static final String PARAM_ANNOTATE_PARTOFSPEECH = "annotate_partofspeech"; public static final String PARAM_IMPROVE_GERMAN_SENTENCES = "improvegermansentences"; public static final String PARAM_CHINESE_TOKENIZER_PATH = "ChineseTokenizerPath"; // language for this instance of the treetaggerwrapper private Language language; // switches for annotation parameters private Boolean annotate_tokens = false; private Boolean annotate_sentences = false; private Boolean annotate_partofspeech = false; private Boolean improve_german_sentences = false; // local treetagger properties container, see below private TreeTaggerProperties ttprops = new TreeTaggerProperties(); /** * uimacontext to make secondary initialize() method possible. * -> programmatic, non-uima pipeline usage. * @author julian * */ private class TreeTaggerContext extends RootUimaContext_impl { // shorthand for when we don't want to supply a cnTokPath @SuppressWarnings("unused") public TreeTaggerContext(Language language, Boolean annotateTokens, Boolean annotateSentences, Boolean annotatePartOfSpeech, Boolean improveGermanSentences) { this(language, annotateTokens, annotateSentences, annotatePartOfSpeech, improveGermanSentences, null); } public TreeTaggerContext(Language language, Boolean annotateTokens, Boolean annotateSentences, Boolean annotatePartOfSpeech, Boolean improveGermanSentences, String cnTokPath) { super(); // Initialize config ConfigurationManager configManager = new ConfigurationManager_impl(); // Initialize context this.initializeRoot(null, new ResourceManager_impl(), configManager); // Set session configManager.setSession(this.getSession()); // Set necessary variables configManager.setConfigParameterValue(makeQualifiedName(PARAM_LANGUAGE), language.getName()); configManager.setConfigParameterValue(makeQualifiedName(PARAM_ANNOTATE_TOKENS), annotateTokens); configManager.setConfigParameterValue(makeQualifiedName(PARAM_ANNOTATE_PARTOFSPEECH), annotatePartOfSpeech); configManager.setConfigParameterValue(makeQualifiedName(PARAM_ANNOTATE_SENTENCES), annotateSentences); configManager.setConfigParameterValue(makeQualifiedName(PARAM_IMPROVE_GERMAN_SENTENCES), improveGermanSentences); configManager.setConfigParameterValue(makeQualifiedName(PARAM_CHINESE_TOKENIZER_PATH), cnTokPath); } } /** * secondary initialize() to use wrapper outside of a uima pipeline * shorthand for when we don't want to specify a cnTokPath */ public void initialize(Language language, String treeTaggerHome, Boolean annotateTokens, Boolean annotateSentences, Boolean annotatePartOfSpeech, Boolean improveGermanSentences) { this.initialize(language, treeTaggerHome, annotateTokens, annotateSentences, annotatePartOfSpeech, improveGermanSentences, null); } /** * secondary initialize() to use wrapper outside of a uima pipeline * * @param language Language/parameter file to use for the TreeTagger * @param treeTaggerHome Path to the TreeTagger folder * @param annotateTokens Whether to annotate tokens * @param annotateSentences Whether to annotate sentences * @param annotatePartOfSpeech Whether to annotate POS tags * @param improveGermanSentences Whether to do improvements for german sentences */ public void initialize(Language language, String treeTaggerHome, Boolean annotateTokens, Boolean annotateSentences, Boolean annotatePartOfSpeech, Boolean improveGermanSentences, String cnTokPath) { this.setHome(treeTaggerHome); TreeTaggerContext ttContext = new TreeTaggerContext(language, annotateTokens, annotateSentences, annotatePartOfSpeech, improveGermanSentences, cnTokPath); this.initialize(ttContext); } /** * initialization method where we fill configuration values and check some prerequisites */ public void initialize(UimaContext aContext) { // check if the supplied language is one that we can currently handle this.language = Language.getLanguageFromString((String) aContext.getConfigParameterValue(PARAM_LANGUAGE)); // get configuration from the descriptor annotate_tokens = (Boolean) aContext.getConfigParameterValue(PARAM_ANNOTATE_TOKENS); annotate_sentences = (Boolean) aContext.getConfigParameterValue(PARAM_ANNOTATE_SENTENCES); annotate_partofspeech = (Boolean) aContext.getConfigParameterValue(PARAM_ANNOTATE_PARTOFSPEECH); improve_german_sentences = (Boolean) aContext.getConfigParameterValue(PARAM_IMPROVE_GERMAN_SENTENCES); String cnTokPath = (String) aContext.getConfigParameterValue(PARAM_CHINESE_TOKENIZER_PATH); // set some configuration based upon these values ttprops.languageName = language.getTreeTaggerLangName(); if(ttprops.rootPath == null) ttprops.rootPath = System.getenv("TREETAGGER_HOME"); ttprops.tokScriptName = "utf8-tokenize.perl"; // parameter file if(!(new File(ttprops.rootPath+ttprops.fileSeparator+"lib", ttprops.languageName + "-utf8.par").exists())) // get UTF8 version if it exists ttprops.parFileName = ttprops.languageName + ".par"; else ttprops.parFileName = ttprops.languageName + "-utf8.par"; // abbreviation file if(!(new File(ttprops.rootPath+ttprops.fileSeparator+"lib", ttprops.languageName + "-abbreviations-utf8").exists())) // get UTF8 version if it exists ttprops.abbFileName = ttprops.languageName + "-abbreviations"; else ttprops.abbFileName = ttprops.languageName + "-abbreviations-utf8"; ttprops.languageSwitch = language.getTreeTaggerSwitch(); if(cnTokPath != null && !cnTokPath.equals("")) ttprops.chineseTokenizerPath = new File(cnTokPath); else ttprops.chineseTokenizerPath = new File(ttprops.rootPath, "cmd"); // handle the treetagger path from the environment variables if(ttprops.rootPath == null) { Logger.printError("TreeTagger environment variable is not present, aborting."); System.exit(-1); } // Check for whether the required treetagger parameter files are present Boolean abbFileFlag = true; Boolean parFileFlag = true; Boolean tokScriptFlag = true; File abbFile = new File(ttprops.rootPath+ttprops.fileSeparator+"lib", ttprops.abbFileName); File parFile = new File(ttprops.rootPath+ttprops.fileSeparator+"lib", ttprops.parFileName); File tokFile = new File(ttprops.rootPath+ttprops.fileSeparator+"cmd", ttprops.tokScriptName); if (!(abbFileFlag = abbFile.exists())) { if(language.equals(Language.CHINESE) || language.equals(Language.RUSSIAN)) abbFileFlag = true; else Logger.printError(component, "File missing to use TreeTagger tokenizer: " + ttprops.abbFileName); } if (!(parFileFlag = parFile.exists())) { Logger.printError(component, "File missing to use TreeTagger tokenizer: " + ttprops.parFileName); } if (!(tokScriptFlag = tokFile.exists())) { if(language.equals(Language.CHINESE)) tokScriptFlag = true; else Logger.printError(component, "File missing to use TreeTagger tokenizer: " + ttprops.tokScriptName); } if (!abbFileFlag || !parFileFlag || !tokScriptFlag) { Logger.printError(component, "Cannot find tree tagger (" + ttprops.rootPath + ttprops.fileSeparator + "cmd" + ttprops.fileSeparator + ttprops.tokScriptName + ")." + " Make sure that path to tree tagger is set correctly in config.props!"); Logger.printError(component, "If path is set correctly:"); Logger.printError(component, "Maybe you need to download the TreeTagger tagger-scripts.tar.gz"); Logger.printError(component, "from http://www.cis.uni-muenchen.de/~schmid/tools/TreeTagger/data/tagger-scripts.tar.gz"); Logger.printError(component, "Extract this file and copy the missing file into the corresponding TreeTagger directories."); Logger.printError(component, "If missing, copy " + ttprops.abbFileName + " into " + ttprops.rootPath+ttprops.fileSeparator+"lib"); Logger.printError(component, "If missing, copy " + ttprops.parFileName + " into " + ttprops.rootPath+ttprops.fileSeparator+"lib"); Logger.printError(component, "If missing, copy " + ttprops.tokScriptName + " into " + ttprops.rootPath+ttprops.fileSeparator+"cmd"); System.exit(-1); } } /** * Method that gets called to process the documents' cas objects */ public void process(JCas jcas) throws AnalysisEngineProcessException { // if the annotate_tokens flag is set, annotate the tokens and add them to the jcas if(annotate_tokens) if(language.equals(Language.CHINESE)) tokenizeChinese(jcas); // chinese needs different tokenization else tokenize(jcas); /* if the annotate_partofspeech flag is set, annotate partofspeech and, * if specified, also tag sentences based upon the partofspeech tags. */ if(annotate_partofspeech) doTreeTag(jcas); // if the improve_german_sentences flag is set, improve the sentence tokens made by the treetagger if(improve_german_sentences) improveGermanSentences(jcas); // if French, improve the sentence tokens made by the TreeTagger with settings for French if (this.language.getTreeTaggerLangName().equals("french")) improveFrenchSentences(jcas); } /** * tokenizes a given JCas object's document text using the treetagger program * and adds the recognized tokens to the JCas object. * @param jcas JCas object supplied by the pipeline */ private void tokenize(JCas jcas) { File tmpDocument = null; BufferedWriter tmpFileWriter = null; BufferedReader in = null; try { // Create temp file containing the document text tmpDocument = File.createTempFile("pos", null); tmpFileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpDocument), "UTF-8")); // tmpFileWriter.write(jcas.getDocumentText()); tmpFileWriter.write(jcas.getDocumentText().replaceAll("\n\n", "\nEMPTYLINE\n")); tmpFileWriter.close(); // read tokenized text to add tokens to the jcas Process proc = ttprops.getTokenizationProcess(tmpDocument); Logger.printDetail(component, "TreeTagger (tokenization) with: " + ttprops.tokScriptName + " and " + ttprops.abbFileName); in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "UTF-8")); String s; int tokenOffset = 0; // loop through all the lines in the treetagger output while ((s = in.readLine()) != null) { // charset missmatch fallback: signal (invalid) s if ((!(s.equals("EMPTYLINE"))) && (jcas.getDocumentText().indexOf(s, tokenOffset) < 0)) // if (jcas.getDocumentText().indexOf(s, tokenOffset) < 0) throw new RuntimeException("Opps! Could not find token "+s+ " in JCas after tokenizing with TreeTagger." + " Hmm, there may exist a charset missmatch!" + " Default encoding is " + Charset.defaultCharset().name() + " and should always be UTF-8 (use -Dfile.encoding=UTF-8)." + " If input document is not UTF-8 use -e option to set it according to the input, additionally."); // create tokens and add them to the jcas's indexes. Token newToken = new Token(jcas); if (s.equals("EMPTYLINE")){ newToken.setBegin(tokenOffset); newToken.setEnd(tokenOffset); newToken.setPos("EMPTYLINE"); if (annotate_partofspeech){ newToken.addToIndexes(); } } else{ newToken.setBegin(jcas.getDocumentText().indexOf(s, tokenOffset)); newToken.setEnd(newToken.getBegin() + s.length()); newToken.addToIndexes(); tokenOffset = newToken.getEnd(); } } // clean up in.close(); proc.destroy(); tmpDocument.delete(); } catch (Exception e) { e.printStackTrace(); } finally { // I/O Housekeeping if (tmpFileWriter != null) { try { tmpFileWriter.close(); } catch (IOException e) { e.printStackTrace(); } // Delete temp files tmpDocument.delete(); } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * tokenizes a given JCas object's document text using the chinese tokenization * script and adds the recognized tokens to the JCas object. * @param jcas JCas object supplied by the pipeline */ private void tokenizeChinese(JCas jcas) { try { // read tokenized text to add tokens to the jcas Process proc = ttprops.getChineseTokenizationProcess(); Logger.printDetail(component, "Chinese tokenization: " + ttprops.chineseTokenizerPath); BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "UTF-8")); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream(), "UTF-8")); Integer tokenOffset = 0; // loop through all the lines in the stdout output String[] inSplits = jcas.getDocumentText().split("[\\r\\n]+"); for(String inSplit : inSplits) { out.write(inSplit); out.newLine(); out.flush(); // do one initial read String s = in.readLine(); do { // break out of the loop if we've read a null if(s == null) break; String[] outSplits = s.split("\\s+"); for(String tok : outSplits) { if(jcas.getDocumentText().indexOf(tok, tokenOffset) < 0) throw new RuntimeException("Could not find token " + tok + " in JCas after tokenizing with Chinese tokenization script."); // create tokens and add them to the jcas's indexes. Token newToken = new Token(jcas); newToken.setBegin(jcas.getDocumentText().indexOf(tok, tokenOffset)); newToken.setEnd(newToken.getBegin() + tok.length()); newToken.addToIndexes(); tokenOffset = newToken.getEnd(); } // break out of the loop if the next read will block if(!in.ready()) break; s = in.readLine(); } while(true); } // clean up in.close(); proc.destroy(); } catch (Exception e) { e.printStackTrace(); } } /** * based on tokens from the jcas object, adds part of speech (POS) and sentence * tags to the jcas object using the treetagger program. * @param jcas JCas object supplied by the pipeline */ private void doTreeTag(JCas jcas) { File tmpDocument = null; BufferedWriter tmpFileWriter; ArrayList<Token> tokens = new ArrayList<Token>(); try { // create a temporary file and write our pre-existing tokens to it. tmpDocument = File.createTempFile("postokens", null); tmpFileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpDocument), "UTF-8")); // iterate over existing tokens FSIterator ai = jcas.getAnnotationIndex(Token.type).iterator(); while(ai.hasNext()) { Token t = (Token) ai.next(); tokens.add(t); if (!(t.getBegin() == t.getEnd())){ tmpFileWriter.write(t.getCoveredText() + ttprops.newLineSeparator); } } tmpFileWriter.close(); } catch(IOException e) { Logger.printError("Something went wrong creating a temporary file for the treetagger to process."); System.exit(-1); } // Possible End-of-Sentence Tags HashSet<String> hsEndOfSentenceTag = new HashSet<String>(); hsEndOfSentenceTag.add("SENT"); // ENGLISH, FRENCH, GREEK, hsEndOfSentenceTag.add("$."); // GERMAN, DUTCH hsEndOfSentenceTag.add("FS"); // SPANISH hsEndOfSentenceTag.add("_Z_Fst"); // ESTONIAN hsEndOfSentenceTag.add("_Z_Int"); // ESTONIAN hsEndOfSentenceTag.add("_Z_Exc"); // ESTONIAN hsEndOfSentenceTag.add("ew"); // CHINESE try { Process p = ttprops.getTreeTaggingProcess(tmpDocument); Logger.printDetail(component, "TreeTagger (pos tagging) with: " + ttprops.parFileName); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8")); Sentence sentence = null; // iterate over all the output lines and tokens array (which have the same source and are hence symmetric) int i = 0; String s = null; while ((s = in.readLine()) != null) { // grab a token Token token = tokens.get(i++); // modified (Aug 29, 2011): Handle empty tokens (such as empty lines) in input file while (token.getCoveredText().equals("")){ // if part of the configuration, also add sentences to the jcas document if ((annotate_sentences) && (token.getPos() != null && token.getPos().equals("EMPTYLINE"))) { // Establish sentence structure if (sentence == null) { sentence = new Sentence(jcas); sentence.setBegin(token.getBegin()); } // Finish current sentence if end-of-sentence pos was found or document ended sentence.setEnd(token.getEnd()); if (sentence.getBegin() < sentence.getEnd()){ sentence.addToIndexes(); } // Make sure current sentence is not active anymore so that a new one might be created sentence = null; // sentence = new Sentence(jcas); } token.removeFromIndexes(); token = tokens.get(i++); } // remove tokens, otherwise they are in the index twice token.removeFromIndexes(); // set part of speech tag and add to indexes again if (!(token.getCoveredText().equals(""))){ token.setPos(s); token.addToIndexes(); } // if part of the configuration, also add sentences to the jcas document if(annotate_sentences) { // Establish sentence structure if (sentence == null) { sentence = new Sentence(jcas); sentence.setBegin(token.getBegin()); } // Finish current sentence if end-of-sentence pos was found or document ended if (hsEndOfSentenceTag.contains(s) || i == tokens.size()) { sentence.setEnd(token.getEnd()); sentence.addToIndexes(); // Make sure current sentence is not active anymore so that a new one might be created sentence = null; // sentence = new Sentence(jcas); } } } while (i < tokens.size()){ if (!(sentence == null)){ sentence.setEnd(tokens.get(tokens.size()-1).getEnd()); sentence.addToIndexes(); } Token token = tokens.get(i++); if (token.getPos() != null && token.getPos().equals("EMPTYLINE")){ token.removeFromIndexes(); } } in.close(); p.destroy(); } catch (Exception e) { e.printStackTrace(); } finally { // Delete temporary files tmpDocument.delete(); } } public void setHome(String home) { this.ttprops.rootPath = home; } private void improveFrenchSentences(JCas jcas) { HashSet<de.unihd.dbs.uima.types.heideltime.Sentence> hsRemoveAnnotations = new HashSet<de.unihd.dbs.uima.types.heideltime.Sentence>(); HashSet<de.unihd.dbs.uima.types.heideltime.Sentence> hsAddAnnotations = new HashSet<de.unihd.dbs.uima.types.heideltime.Sentence>(); HashSet<String> hsSentenceBeginnings = new HashSet<String>(); hsSentenceBeginnings.add("J.-C."); hsSentenceBeginnings.add("J-C."); hsSentenceBeginnings.add("NSJC"); Boolean changes = true; while (changes) { changes = false; FSIndex annoHeidelSentences = jcas.getAnnotationIndex(de.unihd.dbs.uima.types.heideltime.Sentence.type); FSIterator iterHeidelSent = annoHeidelSentences.iterator(); while (iterHeidelSent.hasNext()){ de.unihd.dbs.uima.types.heideltime.Sentence s1 = (de.unihd.dbs.uima.types.heideltime.Sentence) iterHeidelSent.next(); if ((s1.getCoveredText().endsWith("av.")) || (s1.getCoveredText().endsWith("Av.")) || (s1.getCoveredText().endsWith("apr.")) || (s1.getCoveredText().endsWith("Apr.")) || (s1.getCoveredText().endsWith("avant.")) || (s1.getCoveredText().endsWith("Avant."))){ if (iterHeidelSent.hasNext()){ de.unihd.dbs.uima.types.heideltime.Sentence s2 = (de.unihd.dbs.uima.types.heideltime.Sentence) iterHeidelSent.next(); iterHeidelSent.moveToPrevious(); for (String beg : hsSentenceBeginnings){ if (s2.getCoveredText().startsWith(beg)){ de.unihd.dbs.uima.types.heideltime.Sentence s3 = new de.unihd.dbs.uima.types.heideltime.Sentence(jcas); s3.setBegin(s1.getBegin()); s3.setEnd(s2.getEnd()); hsAddAnnotations.add(s3); hsRemoveAnnotations.add(s1); hsRemoveAnnotations.add(s2); changes = true; break; } } } } } for (de.unihd.dbs.uima.types.heideltime.Sentence s : hsRemoveAnnotations){ s.removeFromIndexes(jcas); } hsRemoveAnnotations.clear(); for (de.unihd.dbs.uima.types.heideltime.Sentence s : hsAddAnnotations){ s.addToIndexes(jcas); } hsAddAnnotations.clear(); } } /** * improve german sentences; the treetagger splits german sentences incorrectly on some occasions * @param jcas JCas object supplied by the pipeline */ private void improveGermanSentences(JCas jcas) { HashSet<String> hsSentenceBeginnings = new HashSet<String>(); hsSentenceBeginnings.add("Januar"); hsSentenceBeginnings.add("Februar"); hsSentenceBeginnings.add("März"); hsSentenceBeginnings.add("April"); hsSentenceBeginnings.add("Mai"); hsSentenceBeginnings.add("Juni"); hsSentenceBeginnings.add("Juli"); hsSentenceBeginnings.add("August"); hsSentenceBeginnings.add("September"); hsSentenceBeginnings.add("Oktober"); hsSentenceBeginnings.add("November"); hsSentenceBeginnings.add("Dezember"); hsSentenceBeginnings.add("Jahrhundert"); hsSentenceBeginnings.add("Jh"); hsSentenceBeginnings.add("Jahr"); hsSentenceBeginnings.add("Monat"); hsSentenceBeginnings.add("Woche"); HashSet<de.unihd.dbs.uima.types.heideltime.Sentence> hsRemoveAnnotations = new HashSet<de.unihd.dbs.uima.types.heideltime.Sentence>(); HashSet<de.unihd.dbs.uima.types.heideltime.Sentence> hsAddAnnotations = new HashSet<de.unihd.dbs.uima.types.heideltime.Sentence>(); Boolean changes = true; while (changes) { changes = false; FSIndex annoHeidelSentences = jcas.getAnnotationIndex(de.unihd.dbs.uima.types.heideltime.Sentence.type); FSIterator iterHeidelSent = annoHeidelSentences.iterator(); while (iterHeidelSent.hasNext()){ de.unihd.dbs.uima.types.heideltime.Sentence s1 = (de.unihd.dbs.uima.types.heideltime.Sentence) iterHeidelSent.next(); int substringOffset = java.lang.Math.max(s1.getCoveredText().length()-4,1); if (s1.getCoveredText().substring(substringOffset).matches(".*[\\d]+\\.[\\s\\n]*$")){ if (iterHeidelSent.hasNext()){ de.unihd.dbs.uima.types.heideltime.Sentence s2 = (de.unihd.dbs.uima.types.heideltime.Sentence) iterHeidelSent.next(); iterHeidelSent.moveToPrevious(); boolean newBoundary = false; for (String beg : hsSentenceBeginnings){ if (s2.getCoveredText().startsWith(beg)){ de.unihd.dbs.uima.types.heideltime.Sentence s3 = new de.unihd.dbs.uima.types.heideltime.Sentence(jcas); s3.setBegin(s1.getBegin()); s3.setEnd(s2.getEnd()); hsAddAnnotations.add(s3); hsRemoveAnnotations.add(s1); hsRemoveAnnotations.add(s2); newBoundary = true; changes = true; break; } } if (newBoundary == false){ if (s2.getCoveredText().matches("^([a-z]).*")){ de.unihd.dbs.uima.types.heideltime.Sentence s3 = new de.unihd.dbs.uima.types.heideltime.Sentence(jcas); s3.setBegin(s1.getBegin()); s3.setEnd(s2.getEnd()); hsAddAnnotations.add(s3); hsRemoveAnnotations.add(s1); hsRemoveAnnotations.add(s2); newBoundary = true; changes = true; } } if (newBoundary == false){ if (s2.getCoveredText().matches("^[/].*")){ de.unihd.dbs.uima.types.heideltime.Sentence s3 = new de.unihd.dbs.uima.types.heideltime.Sentence(jcas); s3.setBegin(s1.getBegin()); s3.setEnd(s2.getEnd()); hsAddAnnotations.add(s3); hsRemoveAnnotations.add(s1); hsRemoveAnnotations.add(s2); changes = true; } } } } } for (de.unihd.dbs.uima.types.heideltime.Sentence s : hsRemoveAnnotations){ s.removeFromIndexes(jcas); } hsRemoveAnnotations.clear(); for (de.unihd.dbs.uima.types.heideltime.Sentence s : hsAddAnnotations){ s.addToIndexes(jcas); } hsAddAnnotations.clear(); } } }
Java
/** * Settings class with variables and helper methods to use with TreeTaggerWrapper */ package de.unihd.dbs.uima.annotator.treetagger; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; /** * * @author Julian Zell * */ public class TreeTaggerProperties { // treetagger language name for par files public String languageName = null; // absolute path of the treetagger public String rootPath = null; // Files for tokenizer and part of speech tagger (standard values) public String tokScriptName = null; public String parFileName = null; public String abbFileName = null; // english, italian, and french tagger models require additional splits (see tagger readme) public String languageSwitch = null; // perl requires(?) special hint for utf-8-encoded input/output (see http://perldoc.perl.org/perlrun.html#Command-Switches -C) // The input text is read in HeidelTimeStandalone.java and always translated into UTF-8, // i.e., switch always "-CSD" public String utf8Switch = "-CSD"; // save System-specific separators for string generation public String newLineSeparator = System.getProperty("line.separator"); public String fileSeparator = System.getProperty("file.separator"); // chinese tokenizer path public File chineseTokenizerPath = null; public Process getTokenizationProcess(File inputFile) throws IOException { // assemble a command line for the tokenization script and execute it ArrayList<String> command = new ArrayList<String>(); command.add("perl"); if(this.utf8Switch != "") command.add(this.utf8Switch); command.add(this.rootPath + this.fileSeparator + "cmd" + this.fileSeparator + this.tokScriptName); if(this.languageSwitch != "") command.add(this.languageSwitch); if(new File(this.rootPath + this.fileSeparator + "lib" + this.fileSeparator, this.abbFileName).exists()) { command.add("-a"); command.add(this.rootPath + this.fileSeparator + "lib" + this.fileSeparator + this.abbFileName); } command.add(inputFile.getAbsolutePath()); String[] commandStr = new String[command.size()]; command.toArray(commandStr); Process p = Runtime.getRuntime().exec(commandStr); return p; } public Process getChineseTokenizationProcess() throws IOException { // assemble a command line for the tokenization script and execute it ArrayList<String> command = new ArrayList<String>(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(this.chineseTokenizerPath, "segment-zh.pl")))); String segmenterScript = ""; String buf = null; Boolean firstLine = true; // this dirty hack is to force the script to autoflush its buffers. thanks, PERL while((buf = br.readLine()) != null) { // set the lexicon files if(buf.startsWith("$lexicon=")) buf = "$lexicon=\"" + new File(this.chineseTokenizerPath, "lcmc-uni2.dat").getAbsolutePath() + "\";"; if(buf.startsWith("$lexicon2=")) buf = "$lexicon2=\"" + new File(this.chineseTokenizerPath, "lcmc-bigrams2.dat").getAbsolutePath() + "\";"; // add the autoflush variable if(firstLine) { segmenterScript += "$| = 1;"; firstLine = false; } // we omit comments if(!buf.startsWith("#")) segmenterScript += buf; } br.close(); command.add("perl"); command.add("-X"); command.add("-e"); command.add(segmenterScript); String[] commandStr = new String[command.size()]; command.toArray(commandStr); ProcessBuilder builder = new ProcessBuilder(commandStr); builder.directory(this.chineseTokenizerPath); return builder.start(); } public Process getTreeTaggingProcess(File inputFile) throws IOException { // assemble a command line based on configuration and execute the POS tagging. ArrayList<String> command = new ArrayList<String>(); command.add(this.rootPath + this.fileSeparator + "bin" + this.fileSeparator + "tree-tagger"); command.add(this.rootPath + this.fileSeparator + "lib" + this.fileSeparator + this.parFileName); command.add(inputFile.getAbsolutePath()); command.add("-no-unknown"); String[] commandStr = new String[command.size()]; command.toArray(commandStr); return Runtime.getRuntime().exec(commandStr); } }
Java
/* First created by JCasGen Sat Apr 30 11:35:10 CEST 2011 */ package de.unihd.dbs.uima.types.heideltime; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** * Updated by JCasGen Mon Aug 18 14:39:53 CEST 2014 * @generated */ public class Sentence_Type extends Annotation_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (Sentence_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = Sentence_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new Sentence(addr, Sentence_Type.this); Sentence_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new Sentence(addr, Sentence_Type.this); } }; /** @generated */ public final static int typeIndexID = Sentence.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.unihd.dbs.uima.types.heideltime.Sentence"); /** @generated */ final Feature casFeat_filename; /** @generated */ final int casFeatCode_filename; /** @generated */ public String getFilename(int addr) { if (featOkTst && casFeat_filename == null) jcas.throwFeatMissing("filename", "de.unihd.dbs.uima.types.heideltime.Sentence"); return ll_cas.ll_getStringValue(addr, casFeatCode_filename); } /** @generated */ public void setFilename(int addr, String v) { if (featOkTst && casFeat_filename == null) jcas.throwFeatMissing("filename", "de.unihd.dbs.uima.types.heideltime.Sentence"); ll_cas.ll_setStringValue(addr, casFeatCode_filename, v);} /** @generated */ final Feature casFeat_sentenceId; /** @generated */ final int casFeatCode_sentenceId; /** @generated */ public int getSentenceId(int addr) { if (featOkTst && casFeat_sentenceId == null) jcas.throwFeatMissing("sentenceId", "de.unihd.dbs.uima.types.heideltime.Sentence"); return ll_cas.ll_getIntValue(addr, casFeatCode_sentenceId); } /** @generated */ public void setSentenceId(int addr, int v) { if (featOkTst && casFeat_sentenceId == null) jcas.throwFeatMissing("sentenceId", "de.unihd.dbs.uima.types.heideltime.Sentence"); ll_cas.ll_setIntValue(addr, casFeatCode_sentenceId, v);} /** initialize variables to correspond with Cas Type and Features * @generated */ public Sentence_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_filename = jcas.getRequiredFeatureDE(casType, "filename", "uima.cas.String", featOkTst); casFeatCode_filename = (null == casFeat_filename) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_filename).getCode(); casFeat_sentenceId = jcas.getRequiredFeatureDE(casType, "sentenceId", "uima.cas.Integer", featOkTst); casFeatCode_sentenceId = (null == casFeat_sentenceId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_sentenceId).getCode(); } }
Java
/* First created by JCasGen Sat Apr 30 11:35:10 CEST 2011 */ package de.unihd.dbs.uima.types.heideltime; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** * Updated by JCasGen Mon Aug 18 14:39:53 CEST 2014 * @generated */ public class Timex3_Type extends Annotation_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (Timex3_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = Timex3_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new Timex3(addr, Timex3_Type.this); Timex3_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new Timex3(addr, Timex3_Type.this); } }; /** @generated */ public final static int typeIndexID = Timex3.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.unihd.dbs.uima.types.heideltime.Timex3"); /** @generated */ final Feature casFeat_filename; /** @generated */ final int casFeatCode_filename; /** @generated */ public String getFilename(int addr) { if (featOkTst && casFeat_filename == null) jcas.throwFeatMissing("filename", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getStringValue(addr, casFeatCode_filename); } /** @generated */ public void setFilename(int addr, String v) { if (featOkTst && casFeat_filename == null) jcas.throwFeatMissing("filename", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setStringValue(addr, casFeatCode_filename, v);} /** @generated */ final Feature casFeat_sentId; /** @generated */ final int casFeatCode_sentId; /** @generated */ public int getSentId(int addr) { if (featOkTst && casFeat_sentId == null) jcas.throwFeatMissing("sentId", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getIntValue(addr, casFeatCode_sentId); } /** @generated */ public void setSentId(int addr, int v) { if (featOkTst && casFeat_sentId == null) jcas.throwFeatMissing("sentId", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setIntValue(addr, casFeatCode_sentId, v);} /** @generated */ final Feature casFeat_firstTokId; /** @generated */ final int casFeatCode_firstTokId; /** @generated */ public int getFirstTokId(int addr) { if (featOkTst && casFeat_firstTokId == null) jcas.throwFeatMissing("firstTokId", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getIntValue(addr, casFeatCode_firstTokId); } /** @generated */ public void setFirstTokId(int addr, int v) { if (featOkTst && casFeat_firstTokId == null) jcas.throwFeatMissing("firstTokId", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setIntValue(addr, casFeatCode_firstTokId, v);} /** @generated */ final Feature casFeat_allTokIds; /** @generated */ final int casFeatCode_allTokIds; /** @generated */ public String getAllTokIds(int addr) { if (featOkTst && casFeat_allTokIds == null) jcas.throwFeatMissing("allTokIds", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getStringValue(addr, casFeatCode_allTokIds); } /** @generated */ public void setAllTokIds(int addr, String v) { if (featOkTst && casFeat_allTokIds == null) jcas.throwFeatMissing("allTokIds", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setStringValue(addr, casFeatCode_allTokIds, v);} /** @generated */ final Feature casFeat_timexId; /** @generated */ final int casFeatCode_timexId; /** @generated */ public String getTimexId(int addr) { if (featOkTst && casFeat_timexId == null) jcas.throwFeatMissing("timexId", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getStringValue(addr, casFeatCode_timexId); } /** @generated */ public void setTimexId(int addr, String v) { if (featOkTst && casFeat_timexId == null) jcas.throwFeatMissing("timexId", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setStringValue(addr, casFeatCode_timexId, v);} /** @generated */ final Feature casFeat_timexInstance; /** @generated */ final int casFeatCode_timexInstance; /** @generated */ public int getTimexInstance(int addr) { if (featOkTst && casFeat_timexInstance == null) jcas.throwFeatMissing("timexInstance", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getIntValue(addr, casFeatCode_timexInstance); } /** @generated */ public void setTimexInstance(int addr, int v) { if (featOkTst && casFeat_timexInstance == null) jcas.throwFeatMissing("timexInstance", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setIntValue(addr, casFeatCode_timexInstance, v);} /** @generated */ final Feature casFeat_timexType; /** @generated */ final int casFeatCode_timexType; /** @generated */ public String getTimexType(int addr) { if (featOkTst && casFeat_timexType == null) jcas.throwFeatMissing("timexType", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getStringValue(addr, casFeatCode_timexType); } /** @generated */ public void setTimexType(int addr, String v) { if (featOkTst && casFeat_timexType == null) jcas.throwFeatMissing("timexType", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setStringValue(addr, casFeatCode_timexType, v);} /** @generated */ final Feature casFeat_timexValue; /** @generated */ final int casFeatCode_timexValue; /** @generated */ public String getTimexValue(int addr) { if (featOkTst && casFeat_timexValue == null) jcas.throwFeatMissing("timexValue", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getStringValue(addr, casFeatCode_timexValue); } /** @generated */ public void setTimexValue(int addr, String v) { if (featOkTst && casFeat_timexValue == null) jcas.throwFeatMissing("timexValue", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setStringValue(addr, casFeatCode_timexValue, v);} /** @generated */ final Feature casFeat_foundByRule; /** @generated */ final int casFeatCode_foundByRule; /** @generated */ public String getFoundByRule(int addr) { if (featOkTst && casFeat_foundByRule == null) jcas.throwFeatMissing("foundByRule", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getStringValue(addr, casFeatCode_foundByRule); } /** @generated */ public void setFoundByRule(int addr, String v) { if (featOkTst && casFeat_foundByRule == null) jcas.throwFeatMissing("foundByRule", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setStringValue(addr, casFeatCode_foundByRule, v);} /** @generated */ final Feature casFeat_timexQuant; /** @generated */ final int casFeatCode_timexQuant; /** @generated */ public String getTimexQuant(int addr) { if (featOkTst && casFeat_timexQuant == null) jcas.throwFeatMissing("timexQuant", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getStringValue(addr, casFeatCode_timexQuant); } /** @generated */ public void setTimexQuant(int addr, String v) { if (featOkTst && casFeat_timexQuant == null) jcas.throwFeatMissing("timexQuant", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setStringValue(addr, casFeatCode_timexQuant, v);} /** @generated */ final Feature casFeat_timexFreq; /** @generated */ final int casFeatCode_timexFreq; /** @generated */ public String getTimexFreq(int addr) { if (featOkTst && casFeat_timexFreq == null) jcas.throwFeatMissing("timexFreq", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getStringValue(addr, casFeatCode_timexFreq); } /** @generated */ public void setTimexFreq(int addr, String v) { if (featOkTst && casFeat_timexFreq == null) jcas.throwFeatMissing("timexFreq", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setStringValue(addr, casFeatCode_timexFreq, v);} /** @generated */ final Feature casFeat_timexMod; /** @generated */ final int casFeatCode_timexMod; /** @generated */ public String getTimexMod(int addr) { if (featOkTst && casFeat_timexMod == null) jcas.throwFeatMissing("timexMod", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getStringValue(addr, casFeatCode_timexMod); } /** @generated */ public void setTimexMod(int addr, String v) { if (featOkTst && casFeat_timexMod == null) jcas.throwFeatMissing("timexMod", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setStringValue(addr, casFeatCode_timexMod, v);} /** @generated */ final Feature casFeat_emptyValue; /** @generated */ final int casFeatCode_emptyValue; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public String getEmptyValue(int addr) { if (featOkTst && casFeat_emptyValue == null) jcas.throwFeatMissing("emptyValue", "de.unihd.dbs.uima.types.heideltime.Timex3"); return ll_cas.ll_getStringValue(addr, casFeatCode_emptyValue); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setEmptyValue(int addr, String v) { if (featOkTst && casFeat_emptyValue == null) jcas.throwFeatMissing("emptyValue", "de.unihd.dbs.uima.types.heideltime.Timex3"); ll_cas.ll_setStringValue(addr, casFeatCode_emptyValue, v);} /** initialize variables to correspond with Cas Type and Features * @generated */ public Timex3_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_filename = jcas.getRequiredFeatureDE(casType, "filename", "uima.cas.String", featOkTst); casFeatCode_filename = (null == casFeat_filename) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_filename).getCode(); casFeat_sentId = jcas.getRequiredFeatureDE(casType, "sentId", "uima.cas.Integer", featOkTst); casFeatCode_sentId = (null == casFeat_sentId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_sentId).getCode(); casFeat_firstTokId = jcas.getRequiredFeatureDE(casType, "firstTokId", "uima.cas.Integer", featOkTst); casFeatCode_firstTokId = (null == casFeat_firstTokId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_firstTokId).getCode(); casFeat_allTokIds = jcas.getRequiredFeatureDE(casType, "allTokIds", "uima.cas.String", featOkTst); casFeatCode_allTokIds = (null == casFeat_allTokIds) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_allTokIds).getCode(); casFeat_timexId = jcas.getRequiredFeatureDE(casType, "timexId", "uima.cas.String", featOkTst); casFeatCode_timexId = (null == casFeat_timexId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexId).getCode(); casFeat_timexInstance = jcas.getRequiredFeatureDE(casType, "timexInstance", "uima.cas.Integer", featOkTst); casFeatCode_timexInstance = (null == casFeat_timexInstance) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexInstance).getCode(); casFeat_timexType = jcas.getRequiredFeatureDE(casType, "timexType", "uima.cas.String", featOkTst); casFeatCode_timexType = (null == casFeat_timexType) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexType).getCode(); casFeat_timexValue = jcas.getRequiredFeatureDE(casType, "timexValue", "uima.cas.String", featOkTst); casFeatCode_timexValue = (null == casFeat_timexValue) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexValue).getCode(); casFeat_foundByRule = jcas.getRequiredFeatureDE(casType, "foundByRule", "uima.cas.String", featOkTst); casFeatCode_foundByRule = (null == casFeat_foundByRule) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_foundByRule).getCode(); casFeat_timexQuant = jcas.getRequiredFeatureDE(casType, "timexQuant", "uima.cas.String", featOkTst); casFeatCode_timexQuant = (null == casFeat_timexQuant) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexQuant).getCode(); casFeat_timexFreq = jcas.getRequiredFeatureDE(casType, "timexFreq", "uima.cas.String", featOkTst); casFeatCode_timexFreq = (null == casFeat_timexFreq) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexFreq).getCode(); casFeat_timexMod = jcas.getRequiredFeatureDE(casType, "timexMod", "uima.cas.String", featOkTst); casFeatCode_timexMod = (null == casFeat_timexMod) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexMod).getCode(); casFeat_emptyValue = jcas.getRequiredFeatureDE(casType, "emptyValue", "uima.cas.String", featOkTst); casFeatCode_emptyValue = (null == casFeat_emptyValue) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_emptyValue).getCode(); } }
Java
/* First created by JCasGen Sat Apr 30 11:35:10 CEST 2011 */ package de.unihd.dbs.uima.types.heideltime; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** * Updated by JCasGen Mon Aug 18 14:39:53 CEST 2014 * @generated */ public class Dct_Type extends Annotation_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (Dct_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = Dct_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new Dct(addr, Dct_Type.this); Dct_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new Dct(addr, Dct_Type.this); } }; /** @generated */ public final static int typeIndexID = Dct.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.unihd.dbs.uima.types.heideltime.Dct"); /** @generated */ final Feature casFeat_filename; /** @generated */ final int casFeatCode_filename; /** @generated */ public String getFilename(int addr) { if (featOkTst && casFeat_filename == null) jcas.throwFeatMissing("filename", "de.unihd.dbs.uima.types.heideltime.Dct"); return ll_cas.ll_getStringValue(addr, casFeatCode_filename); } /** @generated */ public void setFilename(int addr, String v) { if (featOkTst && casFeat_filename == null) jcas.throwFeatMissing("filename", "de.unihd.dbs.uima.types.heideltime.Dct"); ll_cas.ll_setStringValue(addr, casFeatCode_filename, v);} /** @generated */ final Feature casFeat_value; /** @generated */ final int casFeatCode_value; /** @generated */ public String getValue(int addr) { if (featOkTst && casFeat_value == null) jcas.throwFeatMissing("value", "de.unihd.dbs.uima.types.heideltime.Dct"); return ll_cas.ll_getStringValue(addr, casFeatCode_value); } /** @generated */ public void setValue(int addr, String v) { if (featOkTst && casFeat_value == null) jcas.throwFeatMissing("value", "de.unihd.dbs.uima.types.heideltime.Dct"); ll_cas.ll_setStringValue(addr, casFeatCode_value, v);} /** @generated */ final Feature casFeat_timexId; /** @generated */ final int casFeatCode_timexId; /** @generated */ public String getTimexId(int addr) { if (featOkTst && casFeat_timexId == null) jcas.throwFeatMissing("timexId", "de.unihd.dbs.uima.types.heideltime.Dct"); return ll_cas.ll_getStringValue(addr, casFeatCode_timexId); } /** @generated */ public void setTimexId(int addr, String v) { if (featOkTst && casFeat_timexId == null) jcas.throwFeatMissing("timexId", "de.unihd.dbs.uima.types.heideltime.Dct"); ll_cas.ll_setStringValue(addr, casFeatCode_timexId, v);} /** initialize variables to correspond with Cas Type and Features * @generated */ public Dct_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_filename = jcas.getRequiredFeatureDE(casType, "filename", "uima.cas.String", featOkTst); casFeatCode_filename = (null == casFeat_filename) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_filename).getCode(); casFeat_value = jcas.getRequiredFeatureDE(casType, "value", "uima.cas.String", featOkTst); casFeatCode_value = (null == casFeat_value) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_value).getCode(); casFeat_timexId = jcas.getRequiredFeatureDE(casType, "timexId", "uima.cas.String", featOkTst); casFeatCode_timexId = (null == casFeat_timexId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexId).getCode(); } }
Java
/* First created by JCasGen Wed May 04 15:59:23 CEST 2011 */ package de.unihd.dbs.uima.types.heideltime; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** * Updated by JCasGen Mon Aug 18 14:39:53 CEST 2014 * @generated */ public class SourceDocInfo_Type extends Annotation_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (SourceDocInfo_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = SourceDocInfo_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new SourceDocInfo(addr, SourceDocInfo_Type.this); SourceDocInfo_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new SourceDocInfo(addr, SourceDocInfo_Type.this); } }; /** @generated */ public final static int typeIndexID = SourceDocInfo.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.unihd.dbs.uima.types.heideltime.SourceDocInfo"); /** @generated */ final Feature casFeat_uri; /** @generated */ final int casFeatCode_uri; /** @generated */ public String getUri(int addr) { if (featOkTst && casFeat_uri == null) jcas.throwFeatMissing("uri", "de.unihd.dbs.uima.types.heideltime.SourceDocInfo"); return ll_cas.ll_getStringValue(addr, casFeatCode_uri); } /** @generated */ public void setUri(int addr, String v) { if (featOkTst && casFeat_uri == null) jcas.throwFeatMissing("uri", "de.unihd.dbs.uima.types.heideltime.SourceDocInfo"); ll_cas.ll_setStringValue(addr, casFeatCode_uri, v);} /** @generated */ final Feature casFeat_offsetInSource; /** @generated */ final int casFeatCode_offsetInSource; /** @generated */ public int getOffsetInSource(int addr) { if (featOkTst && casFeat_offsetInSource == null) jcas.throwFeatMissing("offsetInSource", "de.unihd.dbs.uima.types.heideltime.SourceDocInfo"); return ll_cas.ll_getIntValue(addr, casFeatCode_offsetInSource); } /** @generated */ public void setOffsetInSource(int addr, int v) { if (featOkTst && casFeat_offsetInSource == null) jcas.throwFeatMissing("offsetInSource", "de.unihd.dbs.uima.types.heideltime.SourceDocInfo"); ll_cas.ll_setIntValue(addr, casFeatCode_offsetInSource, v);} /** initialize variables to correspond with Cas Type and Features * @generated */ public SourceDocInfo_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_uri = jcas.getRequiredFeatureDE(casType, "uri", "uima.cas.String", featOkTst); casFeatCode_uri = (null == casFeat_uri) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_uri).getCode(); casFeat_offsetInSource = jcas.getRequiredFeatureDE(casType, "offsetInSource", "uima.cas.Integer", featOkTst); casFeatCode_offsetInSource = (null == casFeat_offsetInSource) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_offsetInSource).getCode(); } }
Java
/* First created by JCasGen Sat Apr 30 11:35:10 CEST 2011 */ package de.unihd.dbs.uima.types.heideltime; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** * Updated by JCasGen Mon Aug 18 14:39:54 CEST 2014 * @generated */ public class Token_Type extends Annotation_Type { /** @generated */ protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (Token_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = Token_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new Token(addr, Token_Type.this); Token_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new Token(addr, Token_Type.this); } }; /** @generated */ public final static int typeIndexID = Token.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.unihd.dbs.uima.types.heideltime.Token"); /** @generated */ final Feature casFeat_filename; /** @generated */ final int casFeatCode_filename; /** @generated */ public String getFilename(int addr) { if (featOkTst && casFeat_filename == null) jcas.throwFeatMissing("filename", "de.unihd.dbs.uima.types.heideltime.Token"); return ll_cas.ll_getStringValue(addr, casFeatCode_filename); } /** @generated */ public void setFilename(int addr, String v) { if (featOkTst && casFeat_filename == null) jcas.throwFeatMissing("filename", "de.unihd.dbs.uima.types.heideltime.Token"); ll_cas.ll_setStringValue(addr, casFeatCode_filename, v);} /** @generated */ final Feature casFeat_tokenId; /** @generated */ final int casFeatCode_tokenId; /** @generated */ public int getTokenId(int addr) { if (featOkTst && casFeat_tokenId == null) jcas.throwFeatMissing("tokenId", "de.unihd.dbs.uima.types.heideltime.Token"); return ll_cas.ll_getIntValue(addr, casFeatCode_tokenId); } /** @generated */ public void setTokenId(int addr, int v) { if (featOkTst && casFeat_tokenId == null) jcas.throwFeatMissing("tokenId", "de.unihd.dbs.uima.types.heideltime.Token"); ll_cas.ll_setIntValue(addr, casFeatCode_tokenId, v);} /** @generated */ final Feature casFeat_sentId; /** @generated */ final int casFeatCode_sentId; /** @generated */ public int getSentId(int addr) { if (featOkTst && casFeat_sentId == null) jcas.throwFeatMissing("sentId", "de.unihd.dbs.uima.types.heideltime.Token"); return ll_cas.ll_getIntValue(addr, casFeatCode_sentId); } /** @generated */ public void setSentId(int addr, int v) { if (featOkTst && casFeat_sentId == null) jcas.throwFeatMissing("sentId", "de.unihd.dbs.uima.types.heideltime.Token"); ll_cas.ll_setIntValue(addr, casFeatCode_sentId, v);} /** @generated */ final Feature casFeat_pos; /** @generated */ final int casFeatCode_pos; /** @generated */ public String getPos(int addr) { if (featOkTst && casFeat_pos == null) jcas.throwFeatMissing("pos", "de.unihd.dbs.uima.types.heideltime.Token"); return ll_cas.ll_getStringValue(addr, casFeatCode_pos); } /** @generated */ public void setPos(int addr, String v) { if (featOkTst && casFeat_pos == null) jcas.throwFeatMissing("pos", "de.unihd.dbs.uima.types.heideltime.Token"); ll_cas.ll_setStringValue(addr, casFeatCode_pos, v);} /** initialize variables to correspond with Cas Type and Features * @generated */ public Token_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_filename = jcas.getRequiredFeatureDE(casType, "filename", "uima.cas.String", featOkTst); casFeatCode_filename = (null == casFeat_filename) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_filename).getCode(); casFeat_tokenId = jcas.getRequiredFeatureDE(casType, "tokenId", "uima.cas.Integer", featOkTst); casFeatCode_tokenId = (null == casFeat_tokenId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_tokenId).getCode(); casFeat_sentId = jcas.getRequiredFeatureDE(casType, "sentId", "uima.cas.Integer", featOkTst); casFeatCode_sentId = (null == casFeat_sentId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_sentId).getCode(); casFeat_pos = jcas.getRequiredFeatureDE(casType, "pos", "uima.cas.String", featOkTst); casFeatCode_pos = (null == casFeat_pos) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_pos).getCode(); } }
Java
/* First created by JCasGen Thu Sep 20 15:38:14 CEST 2012 */ package de.unihd.dbs.uima.types.heideltime; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; /** * Updated by JCasGen Mon Aug 18 14:39:53 CEST 2014 * @generated */ public class Timex3Interval_Type extends Timex3_Type { /** @generated */ @Override protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (Timex3Interval_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = Timex3Interval_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new Timex3Interval(addr, Timex3Interval_Type.this); Timex3Interval_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new Timex3Interval(addr, Timex3Interval_Type.this); } }; /** @generated */ public final static int typeIndexID = Timex3Interval.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.unihd.dbs.uima.types.heideltime.Timex3Interval"); /** @generated */ final Feature casFeat_TimexValueEB; /** @generated */ final int casFeatCode_TimexValueEB; /** @generated */ public String getTimexValueEB(int addr) { if (featOkTst && casFeat_TimexValueEB == null) jcas.throwFeatMissing("TimexValueEB", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); return ll_cas.ll_getStringValue(addr, casFeatCode_TimexValueEB); } /** @generated */ public void setTimexValueEB(int addr, String v) { if (featOkTst && casFeat_TimexValueEB == null) jcas.throwFeatMissing("TimexValueEB", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); ll_cas.ll_setStringValue(addr, casFeatCode_TimexValueEB, v);} /** @generated */ final Feature casFeat_TimexValueLE; /** @generated */ final int casFeatCode_TimexValueLE; /** @generated */ public String getTimexValueLE(int addr) { if (featOkTst && casFeat_TimexValueLE == null) jcas.throwFeatMissing("TimexValueLE", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); return ll_cas.ll_getStringValue(addr, casFeatCode_TimexValueLE); } /** @generated */ public void setTimexValueLE(int addr, String v) { if (featOkTst && casFeat_TimexValueLE == null) jcas.throwFeatMissing("TimexValueLE", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); ll_cas.ll_setStringValue(addr, casFeatCode_TimexValueLE, v);} /** @generated */ final Feature casFeat_TimexValueEE; /** @generated */ final int casFeatCode_TimexValueEE; /** @generated */ public String getTimexValueEE(int addr) { if (featOkTst && casFeat_TimexValueEE == null) jcas.throwFeatMissing("TimexValueEE", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); return ll_cas.ll_getStringValue(addr, casFeatCode_TimexValueEE); } /** @generated */ public void setTimexValueEE(int addr, String v) { if (featOkTst && casFeat_TimexValueEE == null) jcas.throwFeatMissing("TimexValueEE", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); ll_cas.ll_setStringValue(addr, casFeatCode_TimexValueEE, v);} /** @generated */ final Feature casFeat_TimexValueLB; /** @generated */ final int casFeatCode_TimexValueLB; /** @generated */ public String getTimexValueLB(int addr) { if (featOkTst && casFeat_TimexValueLB == null) jcas.throwFeatMissing("TimexValueLB", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); return ll_cas.ll_getStringValue(addr, casFeatCode_TimexValueLB); } /** @generated */ public void setTimexValueLB(int addr, String v) { if (featOkTst && casFeat_TimexValueLB == null) jcas.throwFeatMissing("TimexValueLB", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); ll_cas.ll_setStringValue(addr, casFeatCode_TimexValueLB, v);} /** @generated */ final Feature casFeat_emptyValue; /** @generated */ final int casFeatCode_emptyValue; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public String getEmptyValue(int addr) { if (featOkTst && casFeat_emptyValue == null) jcas.throwFeatMissing("emptyValue", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); return ll_cas.ll_getStringValue(addr, casFeatCode_emptyValue); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setEmptyValue(int addr, String v) { if (featOkTst && casFeat_emptyValue == null) jcas.throwFeatMissing("emptyValue", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); ll_cas.ll_setStringValue(addr, casFeatCode_emptyValue, v);} /** @generated */ final Feature casFeat_beginTimex; /** @generated */ final int casFeatCode_beginTimex; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public String getBeginTimex(int addr) { if (featOkTst && casFeat_beginTimex == null) jcas.throwFeatMissing("beginTimex", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); return ll_cas.ll_getStringValue(addr, casFeatCode_beginTimex); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setBeginTimex(int addr, String v) { if (featOkTst && casFeat_beginTimex == null) jcas.throwFeatMissing("beginTimex", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); ll_cas.ll_setStringValue(addr, casFeatCode_beginTimex, v);} /** @generated */ final Feature casFeat_endTimex; /** @generated */ final int casFeatCode_endTimex; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public String getEndTimex(int addr) { if (featOkTst && casFeat_endTimex == null) jcas.throwFeatMissing("endTimex", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); return ll_cas.ll_getStringValue(addr, casFeatCode_endTimex); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setEndTimex(int addr, String v) { if (featOkTst && casFeat_endTimex == null) jcas.throwFeatMissing("endTimex", "de.unihd.dbs.uima.types.heideltime.Timex3Interval"); ll_cas.ll_setStringValue(addr, casFeatCode_endTimex, v);} /** initialize variables to correspond with Cas Type and Features * @generated */ public Timex3Interval_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_TimexValueEB = jcas.getRequiredFeatureDE(casType, "TimexValueEB", "uima.cas.String", featOkTst); casFeatCode_TimexValueEB = (null == casFeat_TimexValueEB) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_TimexValueEB).getCode(); casFeat_TimexValueLE = jcas.getRequiredFeatureDE(casType, "TimexValueLE", "uima.cas.String", featOkTst); casFeatCode_TimexValueLE = (null == casFeat_TimexValueLE) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_TimexValueLE).getCode(); casFeat_TimexValueEE = jcas.getRequiredFeatureDE(casType, "TimexValueEE", "uima.cas.String", featOkTst); casFeatCode_TimexValueEE = (null == casFeat_TimexValueEE) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_TimexValueEE).getCode(); casFeat_TimexValueLB = jcas.getRequiredFeatureDE(casType, "TimexValueLB", "uima.cas.String", featOkTst); casFeatCode_TimexValueLB = (null == casFeat_TimexValueLB) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_TimexValueLB).getCode(); casFeat_emptyValue = jcas.getRequiredFeatureDE(casType, "emptyValue", "uima.cas.String", featOkTst); casFeatCode_emptyValue = (null == casFeat_emptyValue) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_emptyValue).getCode(); casFeat_beginTimex = jcas.getRequiredFeatureDE(casType, "beginTimex", "uima.cas.String", featOkTst); casFeatCode_beginTimex = (null == casFeat_beginTimex) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_beginTimex).getCode(); casFeat_endTimex = jcas.getRequiredFeatureDE(casType, "endTimex", "uima.cas.String", featOkTst); casFeatCode_endTimex = (null == casFeat_endTimex) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_endTimex).getCode(); } }
Java
/* First created by JCasGen Thu Sep 20 15:38:13 CEST 2012 */ package de.unihd.dbs.uima.types.heideltime; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** * Updated by JCasGen Mon Aug 18 14:39:53 CEST 2014 * @generated */ public class Event_Type extends Annotation_Type { /** @generated */ @Override protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (Event_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = Event_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new Event(addr, Event_Type.this); Event_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new Event(addr, Event_Type.this); } }; /** @generated */ public final static int typeIndexID = Event.typeIndexID; /** @generated @modifiable */ public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.unihd.dbs.uima.types.heideltime.Event"); /** @generated */ final Feature casFeat_filename; /** @generated */ final int casFeatCode_filename; /** @generated */ public String getFilename(int addr) { if (featOkTst && casFeat_filename == null) jcas.throwFeatMissing("filename", "de.unihd.dbs.uima.types.heideltime.Event"); return ll_cas.ll_getStringValue(addr, casFeatCode_filename); } /** @generated */ public void setFilename(int addr, String v) { if (featOkTst && casFeat_filename == null) jcas.throwFeatMissing("filename", "de.unihd.dbs.uima.types.heideltime.Event"); ll_cas.ll_setStringValue(addr, casFeatCode_filename, v);} /** @generated */ final Feature casFeat_sentId; /** @generated */ final int casFeatCode_sentId; /** @generated */ public int getSentId(int addr) { if (featOkTst && casFeat_sentId == null) jcas.throwFeatMissing("sentId", "de.unihd.dbs.uima.types.heideltime.Event"); return ll_cas.ll_getIntValue(addr, casFeatCode_sentId); } /** @generated */ public void setSentId(int addr, int v) { if (featOkTst && casFeat_sentId == null) jcas.throwFeatMissing("sentId", "de.unihd.dbs.uima.types.heideltime.Event"); ll_cas.ll_setIntValue(addr, casFeatCode_sentId, v);} /** @generated */ final Feature casFeat_tokId; /** @generated */ final int casFeatCode_tokId; /** @generated */ public int getTokId(int addr) { if (featOkTst && casFeat_tokId == null) jcas.throwFeatMissing("tokId", "de.unihd.dbs.uima.types.heideltime.Event"); return ll_cas.ll_getIntValue(addr, casFeatCode_tokId); } /** @generated */ public void setTokId(int addr, int v) { if (featOkTst && casFeat_tokId == null) jcas.throwFeatMissing("tokId", "de.unihd.dbs.uima.types.heideltime.Event"); ll_cas.ll_setIntValue(addr, casFeatCode_tokId, v);} /** @generated */ final Feature casFeat_eventId; /** @generated */ final int casFeatCode_eventId; /** @generated */ public String getEventId(int addr) { if (featOkTst && casFeat_eventId == null) jcas.throwFeatMissing("eventId", "de.unihd.dbs.uima.types.heideltime.Event"); return ll_cas.ll_getStringValue(addr, casFeatCode_eventId); } /** @generated */ public void setEventId(int addr, String v) { if (featOkTst && casFeat_eventId == null) jcas.throwFeatMissing("eventId", "de.unihd.dbs.uima.types.heideltime.Event"); ll_cas.ll_setStringValue(addr, casFeatCode_eventId, v);} /** @generated */ final Feature casFeat_eventInstanceId; /** @generated */ final int casFeatCode_eventInstanceId; /** @generated */ public int getEventInstanceId(int addr) { if (featOkTst && casFeat_eventInstanceId == null) jcas.throwFeatMissing("eventInstanceId", "de.unihd.dbs.uima.types.heideltime.Event"); return ll_cas.ll_getIntValue(addr, casFeatCode_eventInstanceId); } /** @generated */ public void setEventInstanceId(int addr, int v) { if (featOkTst && casFeat_eventInstanceId == null) jcas.throwFeatMissing("eventInstanceId", "de.unihd.dbs.uima.types.heideltime.Event"); ll_cas.ll_setIntValue(addr, casFeatCode_eventInstanceId, v);} /** @generated */ final Feature casFeat_aspect; /** @generated */ final int casFeatCode_aspect; /** @generated */ public String getAspect(int addr) { if (featOkTst && casFeat_aspect == null) jcas.throwFeatMissing("aspect", "de.unihd.dbs.uima.types.heideltime.Event"); return ll_cas.ll_getStringValue(addr, casFeatCode_aspect); } /** @generated */ public void setAspect(int addr, String v) { if (featOkTst && casFeat_aspect == null) jcas.throwFeatMissing("aspect", "de.unihd.dbs.uima.types.heideltime.Event"); ll_cas.ll_setStringValue(addr, casFeatCode_aspect, v);} /** @generated */ final Feature casFeat_modality; /** @generated */ final int casFeatCode_modality; /** @generated */ public String getModality(int addr) { if (featOkTst && casFeat_modality == null) jcas.throwFeatMissing("modality", "de.unihd.dbs.uima.types.heideltime.Event"); return ll_cas.ll_getStringValue(addr, casFeatCode_modality); } /** @generated */ public void setModality(int addr, String v) { if (featOkTst && casFeat_modality == null) jcas.throwFeatMissing("modality", "de.unihd.dbs.uima.types.heideltime.Event"); ll_cas.ll_setStringValue(addr, casFeatCode_modality, v);} /** @generated */ final Feature casFeat_polarity; /** @generated */ final int casFeatCode_polarity; /** @generated */ public String getPolarity(int addr) { if (featOkTst && casFeat_polarity == null) jcas.throwFeatMissing("polarity", "de.unihd.dbs.uima.types.heideltime.Event"); return ll_cas.ll_getStringValue(addr, casFeatCode_polarity); } /** @generated */ public void setPolarity(int addr, String v) { if (featOkTst && casFeat_polarity == null) jcas.throwFeatMissing("polarity", "de.unihd.dbs.uima.types.heideltime.Event"); ll_cas.ll_setStringValue(addr, casFeatCode_polarity, v);} /** @generated */ final Feature casFeat_tense; /** @generated */ final int casFeatCode_tense; /** @generated */ public String getTense(int addr) { if (featOkTst && casFeat_tense == null) jcas.throwFeatMissing("tense", "de.unihd.dbs.uima.types.heideltime.Event"); return ll_cas.ll_getStringValue(addr, casFeatCode_tense); } /** @generated */ public void setTense(int addr, String v) { if (featOkTst && casFeat_tense == null) jcas.throwFeatMissing("tense", "de.unihd.dbs.uima.types.heideltime.Event"); ll_cas.ll_setStringValue(addr, casFeatCode_tense, v);} /** @generated */ final Feature casFeat_token; /** @generated */ final int casFeatCode_token; /** @generated */ public int getToken(int addr) { if (featOkTst && casFeat_token == null) jcas.throwFeatMissing("token", "de.unihd.dbs.uima.types.heideltime.Event"); return ll_cas.ll_getRefValue(addr, casFeatCode_token); } /** @generated */ public void setToken(int addr, int v) { if (featOkTst && casFeat_token == null) jcas.throwFeatMissing("token", "de.unihd.dbs.uima.types.heideltime.Event"); ll_cas.ll_setRefValue(addr, casFeatCode_token, v);} /** initialize variables to correspond with Cas Type and Features * @generated */ public Event_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_filename = jcas.getRequiredFeatureDE(casType, "filename", "uima.cas.String", featOkTst); casFeatCode_filename = (null == casFeat_filename) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_filename).getCode(); casFeat_sentId = jcas.getRequiredFeatureDE(casType, "sentId", "uima.cas.Integer", featOkTst); casFeatCode_sentId = (null == casFeat_sentId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_sentId).getCode(); casFeat_tokId = jcas.getRequiredFeatureDE(casType, "tokId", "uima.cas.Integer", featOkTst); casFeatCode_tokId = (null == casFeat_tokId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_tokId).getCode(); casFeat_eventId = jcas.getRequiredFeatureDE(casType, "eventId", "uima.cas.String", featOkTst); casFeatCode_eventId = (null == casFeat_eventId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_eventId).getCode(); casFeat_eventInstanceId = jcas.getRequiredFeatureDE(casType, "eventInstanceId", "uima.cas.Integer", featOkTst); casFeatCode_eventInstanceId = (null == casFeat_eventInstanceId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_eventInstanceId).getCode(); casFeat_aspect = jcas.getRequiredFeatureDE(casType, "aspect", "uima.cas.String", featOkTst); casFeatCode_aspect = (null == casFeat_aspect) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_aspect).getCode(); casFeat_modality = jcas.getRequiredFeatureDE(casType, "modality", "uima.cas.String", featOkTst); casFeatCode_modality = (null == casFeat_modality) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_modality).getCode(); casFeat_polarity = jcas.getRequiredFeatureDE(casType, "polarity", "uima.cas.String", featOkTst); casFeatCode_polarity = (null == casFeat_polarity) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_polarity).getCode(); casFeat_tense = jcas.getRequiredFeatureDE(casType, "tense", "uima.cas.String", featOkTst); casFeatCode_tense = (null == casFeat_tense) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_tense).getCode(); casFeat_token = jcas.getRequiredFeatureDE(casType, "token", "de.unihd.dbs.uima.types.heideltime.Token", featOkTst); casFeatCode_token = (null == casFeat_token) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_token).getCode(); } }
Java
/* * Config.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone; import java.util.Properties; /** * Static class * * @author Andreas Fay, University of Heidelberg * @version 1.0 */ public abstract class Config { /** * */ private static Properties properties; /* * Constants to organize consistent access to config parameters */ public static final String CONSIDER_DATE = "considerDate"; public static final String CONSIDER_DURATION = "considerDuration"; public static final String CONSIDER_SET = "considerSet"; public static final String CONSIDER_TIME = "considerTime"; public static final String TREETAGGERHOME = "treeTaggerHome"; public static final String CHINESE_TOKENIZER_PATH = "chineseTokenizerPath"; public static final String JVNTEXTPRO_WORD_MODEL_PATH = "word_model_path"; public static final String JVNTEXTPRO_SENT_MODEL_PATH = "sent_model_path"; public static final String JVNTEXTPRO_POS_MODEL_PATH = "pos_model_path"; public static final String STANFORDPOSTAGGER_MODEL_PATH = "model_path"; public static final String STANFORDPOSTAGGER_CONFIG_PATH = "config_path"; public static final String TYPESYSTEMHOME = "typeSystemHome"; public static final String TYPESYSTEMHOME_DKPRO = "typeSystemHome_DKPro"; public static final String UIMAVAR_DATE = "uimaVarDate"; public static final String UIMAVAR_DURATION = "uimaVarDuration"; public static final String UIMAVAR_LANGUAGE = "uimaVarLanguage"; public static final String UIMAVAR_SET = "uimaVarSet"; public static final String UIMAVAR_TIME = "uimaVarTime"; public static final String UIMAVAR_TYPETOPROCESS = "uimaVarTypeToProcess"; public static final String UIMAVAR_CONVERTDURATIONS = "ConvertDurations"; /** * */ private Config() { } /** * Gets config parameter identified by <code>key</code> * * @param key * Identifier of config parameter * @return Config paramter */ public static String get(String key) { if (properties == null) { return null; } return properties.getProperty(key); } /** * Checks whether config was already initialized * * @return */ public static boolean isInitialized() { return properties != null; } /** * Sets properties once * * @param prop * Properties */ public static void setProps(Properties prop) { properties = prop; } }
Java
/* * DocumentCreationTimeMissingException.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone.exceptions; import de.unihd.dbs.heideltime.standalone.DocumentType; /** * Exception thrown if document creation time is missing while processing a document of type {@link DocumentType#NEWS} * * @author Andreas Fay, University of Heidelberg * @version 1.0 */ public class DocumentCreationTimeMissingException extends Exception { /** * */ private static final long serialVersionUID = -157033697488394828L; }
Java
/* * OutputType.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone; /** * Type of document to be processed by HeidelTime * * @author Andreas Fay, University of Heidelberg * @version 1.0 */ public enum OutputType { TIMEML { public String toString() { return "timeml"; } }, XMI { public String toString() { return "xmi"; } } }
Java
/** * A class that contains the detailed information on all of the command line interface * switches entertained by HeidelTimeStandalone. */ package de.unihd.dbs.heideltime.standalone; import java.util.Date; import de.unihd.dbs.uima.annotator.heideltime.resources.Language; /** * @author Julian Zell * */ public enum CLISwitch { VERBOSITY ("Verbosity level set to INFO and above", "-v"), VERBOSITY2 ("Verbosity level set to ALL", "-vv"), ENCODING ("Encoding to use", "-e", "UTF-8"), OUTPUTTYPE ("Output Type output type to use", "-o", OutputType.TIMEML), LANGUAGE ("Language to use", "-l", Language.ENGLISH.toString()), DOCTYPE ("Document Type/Domain to use", "-t", DocumentType.NARRATIVES), DCT ("Document Creation Time. Format: YYYY-mm-dd.", "-dct", new Date()), CONFIGFILE ("Configuration file path", "-c", "config.props"), LOCALE ("Locale", "-locale", null), POSTAGGER ("Part of Speech tagger", "-pos", POSTagger.TREETAGGER), INTERVALS ("Interval Tagger", "-it"), HELP ("This screen", "-h"), ; private boolean hasFollowingValue = false; private boolean isActive = false; private String name; private String switchString; private Object value = null; private Object defaultValue; /** * Constructor for switches that have a default value * @param name * @param switchString * @param defaultValue */ CLISwitch(String name, String switchString, Object defaultValue) { this.hasFollowingValue = true; this.name = name; this.switchString = switchString; this.defaultValue = defaultValue; } /** * Constructor for switches that don't have a default value * @param name * @param switchString */ CLISwitch(String name, String switchString) { this.hasFollowingValue = false; this.name = name; this.switchString = switchString; } public static CLISwitch getEnumFromSwitch(String cliSwitch) { for(CLISwitch s : CLISwitch.values()) { if(s.getSwitchString().equals(cliSwitch)) { return s; } } return null; } /* * getters/setters of private attributes */ public void setValue(String val) { value = val; isActive = true; } /** * if this switch is supposed to have a value after it, spit out the saved value * or the default value if the value is unset. if it's not supposed to have a value, * return null * @return String containing a value for the switch */ public Object getValue() { if(hasFollowingValue) { if(value != null) return value; else return defaultValue; } else { return null; } } public String getName() { return name; } public Object getDefaultValue() { return defaultValue; } public String getSwitchString() { return switchString; } public boolean getHasFollowingValue() { return hasFollowingValue; } public boolean getIsActive() { return isActive; } }
Java
/** * An enum that contains the POS preprocessing taggers that the HeidelTime * Standalone supports. */ package de.unihd.dbs.heideltime.standalone; /** * @author Julian Zell * */ public enum POSTagger { STANFORDPOSTAGGER, TREETAGGER }
Java
/* * HeidelTimeStandalone.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Locale; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.uima.UIMAFramework; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.metadata.TypeSystemDescription; import org.apache.uima.util.XMLInputSource; import de.unihd.dbs.heideltime.standalone.components.JCasFactory; import de.unihd.dbs.heideltime.standalone.components.ResultFormatter; import de.unihd.dbs.heideltime.standalone.components.PartOfSpeechTagger; import de.unihd.dbs.heideltime.standalone.components.impl.IntervalTaggerWrapper; import de.unihd.dbs.heideltime.standalone.components.impl.JCasFactoryImpl; import de.unihd.dbs.heideltime.standalone.components.impl.JVnTextProWrapper; import de.unihd.dbs.heideltime.standalone.components.impl.StanfordPOSTaggerWrapper; import de.unihd.dbs.heideltime.standalone.components.impl.TimeMLResultFormatter; import de.unihd.dbs.heideltime.standalone.components.impl.TreeTaggerWrapper; import de.unihd.dbs.heideltime.standalone.components.impl.UimaContextImpl; import de.unihd.dbs.heideltime.standalone.components.impl.XMIResultFormatter; import de.unihd.dbs.heideltime.standalone.exceptions.DocumentCreationTimeMissingException; import de.unihd.dbs.uima.annotator.heideltime.HeidelTime; import de.unihd.dbs.uima.annotator.heideltime.resources.Language; import de.unihd.dbs.uima.annotator.intervaltagger.IntervalTagger; import de.unihd.dbs.uima.types.heideltime.Dct; /** * Execution class for UIMA-Component HeidelTime. Singleton-Pattern * * @author Andreas Fay, Jannik Strötgen, Heidelberg Universtiy * @version 1.01 */ public class HeidelTimeStandalone { /** * Used document type */ private DocumentType documentType; /** * HeidelTime instance */ private HeidelTime heidelTime; /** * Type system description of HeidelTime */ private JCasFactory jcasFactory; /** * Used language */ private Language language; /** * output format */ private OutputType outputType; /** * POS tagger */ private POSTagger posTagger; /** * Whether or not to do Interval Tagging */ private Boolean doIntervalTagging; /** * Logging engine */ private static Logger logger = Logger.getLogger("HeidelTimeStandalone"); /** * empty constructor. * * call initialize() after using this! * * @param language * @param typeToProcess * @param outputType */ public HeidelTimeStandalone() { } /** * constructor * @param language * @param typeToProcess * @param outputType */ public HeidelTimeStandalone(Language language, DocumentType typeToProcess, OutputType outputType) { this(language, typeToProcess, outputType, null); } /** * Constructor with configPath. Used primarily for WebUI * * @param language * @param typeToProcess * @param outputType * @param configPath */ public HeidelTimeStandalone(Language language, DocumentType typeToProcess, OutputType outputType, String configPath) { this.language = language; this.documentType = typeToProcess; this.outputType = outputType; this.initialize(language, typeToProcess, outputType, configPath); } /** * Constructor with configPath * * @param language * @param typeToProcess * @param outputType * @param configPath * @param posTagger */ public HeidelTimeStandalone(Language language, DocumentType typeToProcess, OutputType outputType, String configPath, POSTagger posTagger) { this.language = language; this.documentType = typeToProcess; this.outputType = outputType; this.initialize(language, typeToProcess, outputType, configPath, posTagger); } /** * Constructor with configPath * * @param language * @param typeToProcess * @param outputType * @param configPath * @param posTagger */ public HeidelTimeStandalone(Language language, DocumentType typeToProcess, OutputType outputType, String configPath, POSTagger posTagger, Boolean doIntervalTagging) { this.language = language; this.documentType = typeToProcess; this.outputType = outputType; this.doIntervalTagging = doIntervalTagging; this.initialize(language, typeToProcess, outputType, configPath, posTagger, doIntervalTagging); } /** * Method that initializes all vital prerequisites * * @param language Language to be processed with this copy of HeidelTime * @param typeToProcess Domain type to be processed * @param outputType Output type * @param configPath Path to the configuration file for HeidelTimeStandalone */ public void initialize(Language language, DocumentType typeToProcess, OutputType outputType, String configPath) { initialize(language, typeToProcess, outputType, configPath, POSTagger.TREETAGGER); } /** * Method that initializes all vital prerequisites, including POS Tagger * * @param language Language to be processed with this copy of HeidelTime * @param typeToProcess Domain type to be processed * @param outputType Output type * @param configPath Path to the configuration file for HeidelTimeStandalone * @param posTagger POS Tagger to use for preprocessing */ public void initialize(Language language, DocumentType typeToProcess, OutputType outputType, String configPath, POSTagger posTagger) { initialize(language, typeToProcess, outputType, configPath, posTagger, false); } /** * Method that initializes all vital prerequisites, including POS Tagger * * @param language Language to be processed with this copy of HeidelTime * @param typeToProcess Domain type to be processed * @param outputType Output type * @param configPath Path to the configuration file for HeidelTimeStandalone * @param posTagger POS Tagger to use for preprocessing * @param doIntervalTagging Whether or not to invoke the IntervalTagger */ public void initialize(Language language, DocumentType typeToProcess, OutputType outputType, String configPath, POSTagger posTagger, Boolean doIntervalTagging) { logger.log(Level.INFO, "HeidelTimeStandalone initialized with language " + this.language.getName()); // set the POS tagger this.posTagger = posTagger; // set doIntervalTagging flag this.doIntervalTagging = doIntervalTagging; // read in configuration in case it's not yet initialized if(!Config.isInitialized()) { if(configPath == null) readConfigFile(CLISwitch.CONFIGFILE.getValue().toString()); else readConfigFile(configPath); } try { heidelTime = new HeidelTime(); heidelTime.initialize(new UimaContextImpl(language, typeToProcess)); logger.log(Level.INFO, "HeidelTime initialized"); } catch (Exception e) { e.printStackTrace(); logger.log(Level.WARNING, "HeidelTime could not be initialized"); } // Initialize JCas factory ------------- logger.log(Level.FINE, "Initializing JCas factory..."); try { TypeSystemDescription[] descriptions = new TypeSystemDescription[] { UIMAFramework .getXMLParser() .parseTypeSystemDescription( new XMLInputSource( this.getClass() .getClassLoader() .getResource( Config.get(Config.TYPESYSTEMHOME)))), UIMAFramework .getXMLParser() .parseTypeSystemDescription( new XMLInputSource( this.getClass() .getClassLoader() .getResource( Config.get(Config.TYPESYSTEMHOME_DKPRO)))) }; jcasFactory = new JCasFactoryImpl(descriptions); logger.log(Level.INFO, "JCas factory initialized"); } catch (Exception e) { e.printStackTrace(); logger.log(Level.WARNING, "JCas factory could not be initialized"); } } /** * Runs the IntervalTagger on the JCAS object. * @param jcas jcas object */ private void runIntervalTagger(JCas jcas) { logger.log(Level.FINEST, "Running Interval Tagger..."); Integer beforeAnnotations = jcas.getAnnotationIndex().size(); // Prepare the options for IntervalTagger's execution Properties settings = new Properties(); settings.put(IntervalTagger.PARAM_LANGUAGE, language.getResourceFolder()); settings.put(IntervalTagger.PARAM_INTERVALS, true); settings.put(IntervalTagger.PARAM_INTERVAL_CANDIDATES, false); // Instantiate and process with IntervalTagger IntervalTaggerWrapper iTagger = new IntervalTaggerWrapper(); iTagger.initialize(settings); iTagger.process(jcas); // debug output Integer afterAnnotations = jcas.getAnnotationIndex().size(); logger.log(Level.FINEST, "Annotation delta: " + (afterAnnotations - beforeAnnotations)); } /** * Provides jcas object with document creation time if * <code>documentCreationTime</code> is not null. * * @param jcas * @param documentCreationTime * @throws DocumentCreationTimeMissingException * If document creation time is missing when processing a * document of type {@link DocumentType#NEWS}. */ private void provideDocumentCreationTime(JCas jcas, Date documentCreationTime) throws DocumentCreationTimeMissingException { if (documentCreationTime == null) { // Document creation time is missing if (documentType == DocumentType.NEWS) { // But should be provided in case of news-document throw new DocumentCreationTimeMissingException(); } if (documentType == DocumentType.COLLOQUIAL) { // But should be provided in case of colloquial-document throw new DocumentCreationTimeMissingException(); } } else { // Document creation time provided // Translate it to expected string format SimpleDateFormat dateFormatter = new SimpleDateFormat( "yyyy.MM.dd'T'HH:mm"); String formattedDCT = dateFormatter.format(documentCreationTime); // Create dct object for jcas Dct dct = new Dct(jcas); dct.setValue(formattedDCT); dct.addToIndexes(); } } /** * Establishes preconditions for jcas to be processed by HeidelTime * * @param jcas */ private void establishHeidelTimePreconditions(JCas jcas) { // Token information & sentence structure establishPartOfSpeechInformation(jcas); } /** * Establishes part of speech information for cas object. * * @param jcas */ private void establishPartOfSpeechInformation(JCas jcas) { logger.log(Level.FINEST, "Establishing part of speech information..."); PartOfSpeechTagger partOfSpeechTagger = null; Properties settings = new Properties(); switch (language) { case ARABIC: partOfSpeechTagger = new StanfordPOSTaggerWrapper(); settings.put(PartOfSpeechTagger.STANFORDPOSTAGGER_ANNOTATE_TOKENS, true); settings.put(PartOfSpeechTagger.STANFORDPOSTAGGER_ANNOTATE_SENTENCES, true); settings.put(PartOfSpeechTagger.STANFORDPOSTAGGER_ANNOTATE_POS, true); settings.put(PartOfSpeechTagger.STANFORDPOSTAGGER_MODEL_PATH, Config.get(Config.STANFORDPOSTAGGER_MODEL_PATH)); settings.put(PartOfSpeechTagger.STANFORDPOSTAGGER_CONFIG_PATH, Config.get(Config.STANFORDPOSTAGGER_CONFIG_PATH)); break; case VIETNAMESE: partOfSpeechTagger = new JVnTextProWrapper(); settings.put(PartOfSpeechTagger.JVNTEXTPRO_ANNOTATE_TOKENS, true); settings.put(PartOfSpeechTagger.JVNTEXTPRO_ANNOTATE_SENTENCES, true); settings.put(PartOfSpeechTagger.JVNTEXTPRO_ANNOTATE_POS, true); settings.put(PartOfSpeechTagger.JVNTEXTPRO_WORD_MODEL_PATH, Config.get(Config.JVNTEXTPRO_WORD_MODEL_PATH)); settings.put(PartOfSpeechTagger.JVNTEXTPRO_SENT_MODEL_PATH, Config.get(Config.JVNTEXTPRO_SENT_MODEL_PATH)); settings.put(PartOfSpeechTagger.JVNTEXTPRO_POS_MODEL_PATH, Config.get(Config.JVNTEXTPRO_POS_MODEL_PATH)); break; default: if(POSTagger.STANFORDPOSTAGGER.equals(posTagger)) { partOfSpeechTagger = new StanfordPOSTaggerWrapper(); settings.put(PartOfSpeechTagger.STANFORDPOSTAGGER_ANNOTATE_TOKENS, true); settings.put(PartOfSpeechTagger.STANFORDPOSTAGGER_ANNOTATE_SENTENCES, true); settings.put(PartOfSpeechTagger.STANFORDPOSTAGGER_ANNOTATE_POS, true); settings.put(PartOfSpeechTagger.STANFORDPOSTAGGER_MODEL_PATH, Config.get(Config.STANFORDPOSTAGGER_MODEL_PATH)); settings.put(PartOfSpeechTagger.STANFORDPOSTAGGER_CONFIG_PATH, Config.get(Config.STANFORDPOSTAGGER_CONFIG_PATH)); } else if(POSTagger.TREETAGGER.equals(posTagger)) { partOfSpeechTagger = new TreeTaggerWrapper(); settings.put(PartOfSpeechTagger.TREETAGGER_LANGUAGE, language); settings.put(PartOfSpeechTagger.TREETAGGER_ANNOTATE_TOKENS, true); settings.put(PartOfSpeechTagger.TREETAGGER_ANNOTATE_SENTENCES, true); settings.put(PartOfSpeechTagger.TREETAGGER_ANNOTATE_POS, true); settings.put(PartOfSpeechTagger.TREETAGGER_IMPROVE_GERMAN_SENTENCES, (language == Language.GERMAN)); settings.put(PartOfSpeechTagger.TREETAGGER_CHINESE_TOKENIZER_PATH, Config.get(Config.CHINESE_TOKENIZER_PATH)); } else { logger.log(Level.FINEST, "Sorry, but you can't use that tagger."); } } partOfSpeechTagger.initialize(settings); partOfSpeechTagger.process(jcas); logger.log(Level.FINEST, "Part of speech information established"); } private ResultFormatter getFormatter() { if (outputType.toString().equals("xmi")){ return new XMIResultFormatter(); } else { return new TimeMLResultFormatter(); } } /** * Processes document with HeidelTime * * @param document * @return Annotated document * @throws DocumentCreationTimeMissingException * If document creation time is missing when processing a * document of type {@link DocumentType#NEWS}. Use * {@link #process(String, Date)} instead to provide document * creation time! */ public String process(String document) throws DocumentCreationTimeMissingException { return process(document, null, getFormatter()); } /** * Processes document with HeidelTime * * @param document * @return Annotated document * @throws DocumentCreationTimeMissingException * If document creation time is missing when processing a * document of type {@link DocumentType#NEWS}. Use * {@link #process(String, Date)} instead to provide document * creation time! */ public String process(String document, Date documentCreationTime) throws DocumentCreationTimeMissingException { return process(document, documentCreationTime, getFormatter()); } /** * Processes document with HeidelTime * * @param document * @return Annotated document * @throws DocumentCreationTimeMissingException * If document creation time is missing when processing a * document of type {@link DocumentType#NEWS}. Use * {@link #process(String, Date)} instead to provide document * creation time! */ public String process(String document, ResultFormatter resultFormatter) throws DocumentCreationTimeMissingException { return process(document, null, resultFormatter); } /** * Processes document with HeidelTime * * @param document * @param documentCreationTime * Date when document was created - especially important if * document is of type {@link DocumentType#NEWS} * @return Annotated document * @throws DocumentCreationTimeMissingException * If document creation time is missing when processing a * document of type {@link DocumentType#NEWS} */ public String process(String document, Date documentCreationTime, ResultFormatter resultFormatter) throws DocumentCreationTimeMissingException { logger.log(Level.INFO, "Processing started"); // Generate jcas object ---------- logger.log(Level.FINE, "Generate CAS object"); JCas jcas = null; try { jcas = jcasFactory.createJCas(); jcas.setDocumentText(document); logger.log(Level.FINE, "CAS object generated"); } catch (Exception e) { e.printStackTrace(); logger.log(Level.WARNING, "Cas object could not be generated"); } // Process jcas object ----------- try { logger.log(Level.FINER, "Establishing preconditions..."); provideDocumentCreationTime(jcas, documentCreationTime); establishHeidelTimePreconditions(jcas); logger.log(Level.FINER, "Preconditions established"); heidelTime.process(jcas); logger.log(Level.INFO, "Processing finished"); } catch (Exception e) { e.printStackTrace(); logger.log(Level.WARNING, "Processing aborted due to errors"); } // process interval tagging --- if(doIntervalTagging) runIntervalTagger(jcas); // Process results --------------- logger.log(Level.FINE, "Formatting result..."); // PrintAnnotations.printAnnotations(jcas.getCas(), System.out); String result = null; try { result = resultFormatter.format(jcas); logger.log(Level.INFO, "Result formatted"); } catch (Exception e) { e.printStackTrace(); logger.log(Level.WARNING, "Result could not be formatted"); } return result; } /** * @param args */ public static void main(String[] args) { String docPath = null; for(int i = 0; i < args.length; i++) { // iterate over cli parameter tokens if(args[i].startsWith("-")) { // assume we found a switch // get the relevant enum CLISwitch sw = CLISwitch.getEnumFromSwitch(args[i]); if(sw == null) { // unsupported CLI switch logger.log(Level.WARNING, "Unsupported switch: "+args[i]+". Quitting."); System.exit(-1); } if(sw.getHasFollowingValue()) { // handle values for switches if(args.length > i+1 && !args[i+1].startsWith("-")) { // we still have an array index after this one and it's not a switch sw.setValue(args[++i]); } else { // value is missing or malformed logger.log(Level.WARNING, "Invalid or missing parameter after "+args[i]+". Quitting."); System.exit(-1); } } else { // activate the value-less switches sw.setValue(null); } } else { // assume we found the document's path/name docPath = args[i]; } } // display help dialog if HELP-switch is given if(CLISwitch.HELP.getIsActive()) { printHelp(); System.exit(0); } // start off with the verbosity recognition -- lots of the other // stuff can be skipped if this is set too high if(CLISwitch.VERBOSITY2.getIsActive()) { logger.setLevel(Level.ALL); logger.log(Level.INFO, "Verbosity: '-vv'; Logging level set to ALL."); } else if(CLISwitch.VERBOSITY.getIsActive()) { logger.setLevel(Level.INFO); logger.log(Level.INFO, "Verbosity: '-v'; Logging level set to INFO and above."); } else { logger.setLevel(Level.WARNING); logger.log(Level.INFO, "Verbosity -v/-vv NOT FOUND OR RECOGNIZED; Logging level set to WARNING and above."); } // Check input encoding String encodingType = null; if(CLISwitch.ENCODING.getIsActive()) { encodingType = CLISwitch.ENCODING.getValue().toString(); logger.log(Level.INFO, "Encoding '-e': "+encodingType); } else { // Encoding type not found encodingType = CLISwitch.ENCODING.getValue().toString(); logger.log(Level.INFO, "Encoding '-e': NOT FOUND OR RECOGNIZED; set to 'UTF-8'"); } // Check output format OutputType outputType = null; if(CLISwitch.OUTPUTTYPE.getIsActive()) { outputType = OutputType.valueOf(CLISwitch.OUTPUTTYPE.getValue().toString().toUpperCase()); logger.log(Level.INFO, "Output '-o': "+outputType.toString().toUpperCase()); } else { // Output type not found outputType = (OutputType) CLISwitch.OUTPUTTYPE.getValue(); logger.log(Level.INFO, "Output '-o': NOT FOUND OR RECOGNIZED; set to "+outputType.toString().toUpperCase()); } // Check language Language language = null; if(CLISwitch.LANGUAGE.getIsActive()) { language = Language.getLanguageFromString((String) CLISwitch.LANGUAGE.getValue()); if(language == Language.WILDCARD) { logger.log(Level.SEVERE, "Language '-l': "+CLISwitch.LANGUAGE.getValue()+" NOT RECOGNIZED; aborting."); printHelp(); System.exit(-1); } else { logger.log(Level.INFO, "Language '-l': "+language.toString().toUpperCase()); } } else { // Language not found language = Language.getLanguageFromString((String) CLISwitch.LANGUAGE.getValue()); logger.log(Level.INFO, "Language '-l': NOT FOUND; set to "+language.toString().toUpperCase()); } // Check type DocumentType type = null; if(CLISwitch.DOCTYPE.getIsActive()) { type = DocumentType.valueOf(CLISwitch.DOCTYPE.getValue().toString().toUpperCase()); logger.log(Level.INFO, "Type '-t': "+type.toString().toUpperCase()); } else { // Type not found type = (DocumentType) CLISwitch.DOCTYPE.getValue(); logger.log(Level.INFO, "Type '-t': NOT FOUND OR RECOGNIZED; set to "+type.toString().toUpperCase()); } // Check document creation time Date dct = null; if(CLISwitch.DCT.getIsActive()) { try { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); dct = formatter.parse(CLISwitch.DCT.getValue().toString()); logger.log(Level.INFO, "Document Creation Time '-dct': "+dct.toString()); } catch (Exception e) { // DCT was not parseable logger.log(Level.WARNING, "Document Creation Time '-dct': NOT RECOGNIZED. Quitting."); printHelp(); System.exit(-1); } } else { if ((type == DocumentType.NEWS) || (type == DocumentType.COLLOQUIAL)) { // Dct needed dct = (Date) CLISwitch.DCT.getValue(); logger.log(Level.INFO, "Document Creation Time '-dct': NOT FOUND; set to local date (" + dct.toString() + ")."); } else { logger.log(Level.INFO, "Document Creation Time '-dct': NOT FOUND; skipping."); } } // Handle locale switch String locale = (String) CLISwitch.LOCALE.getValue(); Locale myLocale = null; if(CLISwitch.LOCALE.getIsActive()) { // check if the requested locale is available for(Locale l : Locale.getAvailableLocales()) { if(l.toString().toLowerCase().equals(locale.toLowerCase())) myLocale = l; } try { Locale.setDefault(myLocale); // try to set the locale logger.log(Level.INFO, "Locale '-locale': "+myLocale.toString()); } catch(Exception e) { // if the above fails, spit out error message and available locales logger.log(Level.WARNING, "Supplied locale parameter couldn't be resolved to a working locale. Try one of these:"); logger.log(Level.WARNING, Arrays.asList(Locale.getAvailableLocales()).toString()); // list available locales printHelp(); System.exit(-1); } } else { // no -locale parameter supplied: just show default locale logger.log(Level.INFO, "Locale '-locale': NOT FOUND, set to environment locale: "+Locale.getDefault().toString()); } // Read configuration from file String configPath = CLISwitch.CONFIGFILE.getValue().toString(); try { logger.log(Level.INFO, "Configuration path '-c': "+configPath); readConfigFile(configPath); logger.log(Level.FINE, "Config initialized"); } catch (Exception e) { e.printStackTrace(); logger.log(Level.WARNING, "Config could not be initialized! Please supply the -c switch or " + "put a config.props into this directory."); printHelp(); System.exit(-1); } // Set the preprocessing POS tagger POSTagger posTagger = null; if(CLISwitch.POSTAGGER.getIsActive()) { try { posTagger = POSTagger.valueOf(CLISwitch.POSTAGGER.getValue().toString().toUpperCase()); } catch(IllegalArgumentException e) { logger.log(Level.WARNING, "Given POS Tagger doesn't exist. Please specify a valid one as listed in the help."); printHelp(); System.exit(-1); } logger.log(Level.INFO, "POS Tagger '-pos': "+posTagger.toString().toUpperCase()); } else { // Type not found posTagger = (POSTagger) CLISwitch.POSTAGGER.getValue(); logger.log(Level.INFO, "POS Tagger '-pos': NOT FOUND OR RECOGNIZED; set to "+posTagger.toString().toUpperCase()); } // Set whether or not to use the Interval Tagger Boolean doIntervalTagging = false; if(CLISwitch.INTERVALS.getIsActive()) { doIntervalTagging = CLISwitch.INTERVALS.getIsActive(); logger.log(Level.INFO, "Interval Tagger '-it': " + doIntervalTagging.toString()); } else { logger.log(Level.INFO, "Interval Tagger '-it': NOT FOUND OR RECOGNIZED; set to " + doIntervalTagging.toString()); } // make sure we have a document path if (docPath == null) { logger.log(Level.WARNING, "No input file given; aborting."); printHelp(); System.exit(-1); } // Run HeidelTime RandomAccessFile aFile = null; MappedByteBuffer buffer = null; FileChannel inChannel = null; PrintWriter pwOut = null; try { logger.log(Level.INFO, "Reading document using charset: " + encodingType); aFile = new RandomAccessFile(docPath, "r"); inChannel = aFile.getChannel(); buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size()); buffer.load(); byte[] inArr = new byte[(int) inChannel.size()]; for(int i = 0; i < buffer.limit(); i++) { inArr[i] = buffer.get(); } // double-newstring should not be necessary, but without this, it's not running on Windows (?) String input = new String(new String(inArr, encodingType).getBytes("UTF-8"), "UTF-8"); HeidelTimeStandalone standalone = new HeidelTimeStandalone(language, type, outputType, null, posTagger, doIntervalTagging); String out = standalone.process(input, dct); // Print output always as UTF-8 pwOut = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")); pwOut.println(out); } catch (Exception e) { e.printStackTrace(); } finally { if(pwOut != null) { pwOut.close(); } if(buffer != null) { buffer.clear(); } if(inChannel != null) { try { inChannel.close(); } catch (IOException e) { } } if(aFile != null) { try { aFile.close(); } catch (IOException e) { } } } } public static void readConfigFile(String configPath) { InputStream configStream = null; try { logger.log(Level.INFO, "trying to read in file "+configPath); configStream = new FileInputStream(configPath); Properties props = new Properties(); props.load(configStream); Config.setProps(props); configStream.close(); } catch (FileNotFoundException e) { logger.log(Level.WARNING, "couldn't open configuration file \""+configPath+"\". quitting."); System.exit(-1); } catch (IOException e) { logger.log(Level.WARNING, "couldn't close config file handle"); e.printStackTrace(); } } private static void printHelp() { String path = HeidelTimeStandalone.class.getProtectionDomain().getCodeSource().getLocation().getFile(); String filename = path.substring(path.lastIndexOf(System.getProperty("file.separator")) + 1); System.out.println("Usage:"); System.out.println(" java -jar " + filename + " <input-document> [-param1 <value1> ...]"); System.out.println(); System.out.println("Parameters and expected values:"); for(CLISwitch c : CLISwitch.values()) { System.out.println(" " + c.getSwitchString() + "\t" + ((c.getSwitchString().length() > 4)? "" : "\t") + c.getName() ); if(c == CLISwitch.LANGUAGE) { System.out.print("\t\t" + "Available languages: [ "); for(Language l : Language.values()) if(l != Language.WILDCARD) System.out.print(l.getName().toLowerCase()+" "); System.out.println("]"); } if(c == CLISwitch.POSTAGGER) { System.out.print("\t\t" + "Available taggers: [ "); for(POSTagger p : POSTagger.values()) System.out.print(p.toString().toLowerCase()+" "); System.out.println("]"); } if(c == CLISwitch.DOCTYPE) { System.out.print("\t\t" + "Available types: [ "); for(DocumentType t : DocumentType.values()) System.out.print(t.toString().toLowerCase()+" "); System.out.println("]"); } } System.out.println(); } public DocumentType getDocumentType() { return documentType; } public void setDocumentType(DocumentType documentType) { this.documentType = documentType; } public Language getLanguage() { return language; } public void setLanguage(Language language) { this.language = language; } public OutputType getOutputType() { return outputType; } public void setOutputType(OutputType outputType) { this.outputType = outputType; } public final POSTagger getPosTagger() { return posTagger; } public final void setPosTagger(POSTagger posTagger) { this.posTagger = posTagger; } }
Java
/* * ResultFormatter.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone.components; import org.apache.uima.jcas.JCas; /** * Formatter pattern for results of HeidelTime execution. Similar to CasConsumer in UIMA. * * @author Andreas Fay, University of Heidelberg * @version 1.0 */ public interface ResultFormatter { /** * Formats result * * @param jcas JCas object containing annotations - result * @return Formatted result */ public String format(JCas jcas) throws Exception; }
Java
/* * PartOfSpeechTagger.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone.components; /** * Part of speech tagger * * @author Andreas Fay, University of Heidelberg * @version 1.0 */ public interface PartOfSpeechTagger extends UIMAAnnotator { public static final String TREETAGGER_ANNOTATE_TOKENS = "annotateTokens"; public static final String TREETAGGER_ANNOTATE_SENTENCES = "annotateSentences"; public static final String TREETAGGER_ANNOTATE_POS = "annotatePartOfSpeech"; public static final String TREETAGGER_IMPROVE_GERMAN_SENTENCES = "improveGermanSentences"; public static final String TREETAGGER_LANGUAGE = "language"; public static final String TREETAGGER_CHINESE_TOKENIZER_PATH = "ChineseTokenizerPath"; public static final String JVNTEXTPRO_WORD_MODEL_PATH = "word_model_path"; public static final String JVNTEXTPRO_SENT_MODEL_PATH = "sent_model_path"; public static final String JVNTEXTPRO_POS_MODEL_PATH = "pos_model_path"; public static final String JVNTEXTPRO_ANNOTATE_TOKENS = "annotate_tokens"; public static final String JVNTEXTPRO_ANNOTATE_SENTENCES = "annotate_sentences"; public static final String JVNTEXTPRO_ANNOTATE_POS = "annotate_partofspeech"; public static final String STANFORDPOSTAGGER_ANNOTATE_TOKENS = "annotate_tokens"; public static final String STANFORDPOSTAGGER_ANNOTATE_SENTENCES = "annotate_sentences"; public static final String STANFORDPOSTAGGER_ANNOTATE_POS = "annotate_partofspeech"; public static final String STANFORDPOSTAGGER_MODEL_PATH = "model_path"; public static final String STANFORDPOSTAGGER_CONFIG_PATH = "config_path"; }
Java
package de.unihd.dbs.heideltime.standalone.components.impl; import java.util.Properties; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.jcas.JCas; import de.unihd.dbs.heideltime.standalone.components.PartOfSpeechTagger; public class JVnTextProWrapper implements PartOfSpeechTagger { // uima wrapper instance private de.unihd.dbs.uima.annotator.jvntextprowrapper.JVnTextProWrapper jvntextpro = new de.unihd.dbs.uima.annotator.jvntextprowrapper.JVnTextProWrapper(); @Override public void process(JCas jcas) { try { jvntextpro.process(jcas); } catch(AnalysisEngineProcessException e) { e.printStackTrace(); } } @Override public void initialize(Properties settings) { StandaloneConfigContext aContext = new StandaloneConfigContext(); // construct a context for the uima engine aContext.setConfigParameterValue(de.unihd.dbs.uima.annotator.jvntextprowrapper.JVnTextProWrapper.PARAM_ANNOTATE_TOKENS, (Boolean) settings.get(JVNTEXTPRO_ANNOTATE_TOKENS)); aContext.setConfigParameterValue(de.unihd.dbs.uima.annotator.jvntextprowrapper.JVnTextProWrapper.PARAM_ANNOTATE_SENTENCES, (Boolean) settings.get(JVNTEXTPRO_ANNOTATE_SENTENCES)); aContext.setConfigParameterValue(de.unihd.dbs.uima.annotator.jvntextprowrapper.JVnTextProWrapper.PARAM_ANNOTATE_PARTOFSPEECH, (Boolean) settings.get(JVNTEXTPRO_ANNOTATE_POS)); aContext.setConfigParameterValue(de.unihd.dbs.uima.annotator.jvntextprowrapper.JVnTextProWrapper.PARAM_WORDSEGMODEL_PATH, (String) settings.get(JVNTEXTPRO_WORD_MODEL_PATH)); aContext.setConfigParameterValue(de.unihd.dbs.uima.annotator.jvntextprowrapper.JVnTextProWrapper.PARAM_SENTSEGMODEL_PATH, (String) settings.get(JVNTEXTPRO_SENT_MODEL_PATH)); aContext.setConfigParameterValue(de.unihd.dbs.uima.annotator.jvntextprowrapper.JVnTextProWrapper.PARAM_POSMODEL_PATH, (String) settings.get(JVNTEXTPRO_POS_MODEL_PATH)); jvntextpro.initialize(aContext); } }
Java
/* * TreeTaggerWrapper.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone.components.impl; import java.util.Properties; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.jcas.JCas; import de.unihd.dbs.heideltime.standalone.Config; import de.unihd.dbs.heideltime.standalone.components.PartOfSpeechTagger; import de.unihd.dbs.uima.annotator.heideltime.resources.Language; /** * Proxy class for UIMA-TreeTaggerWrapper * * @author Andreas Fay, Jannik Strötgen, Julian Zell, Heidelberg University * @version 1.01 */ public class TreeTaggerWrapper implements PartOfSpeechTagger { // uima wrapper instance private de.unihd.dbs.uima.annotator.treetagger.TreeTaggerWrapper ttw = new de.unihd.dbs.uima.annotator.treetagger.TreeTaggerWrapper(); public void initialize(Language language, Boolean annotateTokens, Boolean annotateSentences, Boolean annotatePartOfSpeech, Boolean improveGermanSentences) { } public void process(JCas jcas) { try { ttw.process(jcas); } catch(AnalysisEngineProcessException e) { e.printStackTrace(); } } @Override public void initialize(Properties settings) { Language language = (Language) settings.get(TREETAGGER_LANGUAGE); String treeTaggerHome = Config.get(Config.TREETAGGERHOME); Boolean annotateTokens = (Boolean) settings.get(TREETAGGER_ANNOTATE_TOKENS); Boolean annotateSentences = (Boolean) settings.get(TREETAGGER_ANNOTATE_SENTENCES); Boolean annotatePartOfSpeech = (Boolean) settings.get(TREETAGGER_ANNOTATE_POS); Boolean improveGermanSentences = (Boolean) settings.get(TREETAGGER_IMPROVE_GERMAN_SENTENCES); String cnTokenizerPath = (String) settings.get(TREETAGGER_CHINESE_TOKENIZER_PATH); ttw.initialize(language, treeTaggerHome, annotateTokens, annotateSentences, annotatePartOfSpeech, improveGermanSentences, cnTokenizerPath); } }
Java
/* * TimeMLResultFormatter.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone.components.impl; import java.util.HashSet; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.uima.cas.FSIterator; import org.apache.uima.jcas.JCas; import de.unihd.dbs.heideltime.standalone.components.ResultFormatter; import de.unihd.dbs.uima.types.heideltime.Timex3; import de.unihd.dbs.uima.types.heideltime.Timex3Interval; /** * Result formatter based on TimeML. * * @see {@link org.apache.uima.examples.xmi.XmiWriterCasConsumer} * * @author Andreas Fay, Jannik Strötgen Heidelberg University * @version 1.01 */ public class TimeMLResultFormatter implements ResultFormatter { public String format(JCas jcas) throws Exception { final String documentText = jcas.getDocumentText(); String outText = new String(); // get the timex3 intervals, do some pre-selection on them FSIterator iterIntervals = jcas.getAnnotationIndex(Timex3Interval.type).iterator(); TreeMap<Integer, Timex3Interval> intervals = new TreeMap<Integer, Timex3Interval>(); while(iterIntervals.hasNext()) { Timex3Interval t = (Timex3Interval) iterIntervals.next(); // disregard intervals that likely aren't a real interval, but just a timex-translation if(t.getTimexValueEB().equals(t.getTimexValueLB()) && t.getTimexValueEE().equals(t.getTimexValueLE())) continue; if(intervals.containsKey(t.getBegin())) { Timex3Interval tInt = intervals.get(t.getBegin()); // always get the "larger" intervals if(t.getEnd() - t.getBegin() > tInt.getEnd() - tInt.getBegin()) { intervals.put(t.getBegin(), t); } } else { intervals.put(t.getBegin(), t); } } /* * loop through the timexes to create two treemaps: * - one containing startingposition=>timex tuples for eradication of overlapping timexes * - one containing endposition=>timex tuples for assembly of the XML file */ FSIterator iterTimex = jcas.getAnnotationIndex(Timex3.type).iterator(); TreeMap<Integer, Timex3> forwardTimexes = new TreeMap<Integer, Timex3>(), backwardTimexes = new TreeMap<Integer, Timex3>(); while(iterTimex.hasNext()) { Timex3 t = (Timex3) iterTimex.next(); forwardTimexes.put(t.getBegin(), t); backwardTimexes.put(t.getEnd(), t); } HashSet<Timex3> timexesToSkip = new HashSet<Timex3>(); Timex3 prevT = null; Timex3 thisT = null; // iterate over timexes to find overlaps for(Integer begin : forwardTimexes.navigableKeySet()) { thisT = (Timex3) forwardTimexes.get(begin); // check for whether this and the previous timex overlap. ex: [early (friday] morning) if(prevT != null && prevT.getEnd() > thisT.getBegin()) { Timex3 removedT = null; // only for debug message // assuming longer value string means better granularity if(prevT.getTimexValue().length() > thisT.getTimexValue().length()) { timexesToSkip.add(thisT); removedT = thisT; /* prevT stays the same. */ } else { timexesToSkip.add(prevT); removedT = prevT; prevT = thisT; // this iteration's prevT was removed; setting for new iteration } // ask user to let us know about possibly incomplete rules Logger l = Logger.getLogger("TimeMLResultFormatter"); l.log(Level.WARNING, "Two overlapping Timexes have been discovered:" + System.getProperty("line.separator") + "Timex A: " + prevT.getCoveredText() + " [\"" + prevT.getTimexValue() + "\" / " + prevT.getBegin() + ":" + prevT.getEnd() + "]" + System.getProperty("line.separator") + "Timex B: " + removedT.getCoveredText() + " [\"" + removedT.getTimexValue() + "\" / " + removedT.getBegin() + ":" + removedT.getEnd() + "]" + " [removed]" + System.getProperty("line.separator") + "The writer chose, for granularity: " + prevT.getCoveredText() + System.getProperty("line.separator") + "This usually happens with an incomplete ruleset. Please consider adding " + "a new rule that covers the entire expression."); } else { // no overlap found? set current timex as next iteration's previous timex prevT = thisT; } } // alternative xml creation method Timex3Interval interval = null; Timex3 timex = null; for(Integer docOffset = 0; docOffset <= documentText.length(); docOffset++) { /** * see if we have to finish off old timexes/intervals */ if(timex != null && timex.getEnd() == docOffset) { outText += "</TIMEX3>"; timex = null; } if(interval != null && interval.getEnd() == docOffset) { outText += "</TIMEX3INTERVAL>"; interval = null; } /** * grab a new interval/timex if this offset marks the beginning of one */ if(interval == null && intervals.containsKey(docOffset)) interval = intervals.get(docOffset); if(timex == null && forwardTimexes.containsKey(docOffset) && !timexesToSkip.contains(forwardTimexes.get(docOffset))) timex = forwardTimexes.get(docOffset); /** * if an interval/timex begin here, append the opening tag. interval first, timex afterwards */ // handle interval openings first if(interval != null && interval.getBegin() == docOffset) { String intervalTag = "<TIMEX3INTERVAL"; if (!interval.getTimexValueEB().equals("")) intervalTag += " earliestBegin=\"" + interval.getTimexValueEB() + "\""; if (!interval.getTimexValueLB().equals("")) intervalTag += " latestBegin=\"" + interval.getTimexValueLB() + "\""; if (!interval.getTimexValueEE().equals("")) intervalTag += " earliestEnd=\"" + interval.getTimexValueEE() + "\""; if (!interval.getTimexValueLE().equals("")) intervalTag += " latestEnd=\"" + interval.getTimexValueLE() + "\""; intervalTag += ">"; outText += intervalTag; } // handle timex openings after that if(timex != null && timex.getBegin() == docOffset) { String timexTag = "<TIMEX3"; if (!timex.getTimexId().equals("")) timexTag += " tid=\"" + timex.getTimexId() + "\""; if (!timex.getTimexType().equals("")) timexTag += " type=\"" + timex.getTimexType() + "\""; if (!timex.getTimexValue().equals("")) timexTag += " value=\"" + timex.getTimexValue() + "\""; if (!timex.getTimexQuant().equals("")) timexTag += " quant=\"" + timex.getTimexQuant() + "\""; if (!timex.getTimexFreq().equals("")) timexTag += " freq=\"" + timex.getTimexFreq() + "\""; if (!timex.getTimexMod().equals("")) timexTag += " mod=\"" + timex.getTimexMod() + "\""; timexTag += ">"; outText += timexTag; } /** * append the current character */ if(docOffset + 1 <= documentText.length()) outText += documentText.substring(docOffset, docOffset + 1); } // Add TimeML start and end tags outText = "<?xml version=\"1.0\"?>\n<!DOCTYPE TimeML SYSTEM \"TimeML.dtd\">\n<TimeML>\n" + outText + "\n</TimeML>\n"; return outText; } }
Java
/* * JCasFactoryImpl.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone.components.impl; import org.apache.uima.cas.CASException; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.CasManager; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.ResourceManager; import org.apache.uima.resource.impl.ResourceManager_impl; import org.apache.uima.resource.metadata.ProcessingResourceMetaData; import org.apache.uima.resource.metadata.TypeSystemDescription; import org.apache.uima.resource.metadata.impl.ProcessingResourceMetaData_impl; import org.apache.uima.util.CasCreationUtils; import de.unihd.dbs.heideltime.standalone.components.JCasFactory; /** * @see JCasFactory */ public class JCasFactoryImpl implements JCasFactory { /** * Cas Manager */ private CasManager casManager; /** * Constructor * * @param typeSystemDescriptions */ public JCasFactoryImpl(TypeSystemDescription[] typeSystemDescriptions) { // Initialize cas manager ResourceManager resManager = new ResourceManager_impl(); casManager = resManager.getCasManager(); for (TypeSystemDescription desc : typeSystemDescriptions) { ProcessingResourceMetaData metaData = new ProcessingResourceMetaData_impl(); metaData.setTypeSystem(desc); casManager.addMetaData(metaData); } } @Override public JCas createJCas() throws CASException, ResourceInitializationException { return CasCreationUtils.createCas(casManager.getCasDefinition(), null).getJCas(); } }
Java
package de.unihd.dbs.heideltime.standalone.components.impl; import java.util.Properties; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.jcas.JCas; import de.unihd.dbs.heideltime.standalone.components.PartOfSpeechTagger; public class StanfordPOSTaggerWrapper implements PartOfSpeechTagger { // uima wrapper instance private de.unihd.dbs.uima.annotator.stanfordtagger.StanfordPOSTaggerWrapper stanford = new de.unihd.dbs.uima.annotator.stanfordtagger.StanfordPOSTaggerWrapper(); @Override public void process(JCas jcas) { try { stanford.process(jcas); } catch(AnalysisEngineProcessException e) { e.printStackTrace(); } } @Override public void initialize(Properties settings) { StandaloneConfigContext aContext = new StandaloneConfigContext(); // construct a context for the uima engine aContext.setConfigParameterValue(de.unihd.dbs.uima.annotator.stanfordtagger.StanfordPOSTaggerWrapper.PARAM_ANNOTATE_TOKENS, (Boolean) settings.get(STANFORDPOSTAGGER_ANNOTATE_TOKENS)); aContext.setConfigParameterValue(de.unihd.dbs.uima.annotator.stanfordtagger.StanfordPOSTaggerWrapper.PARAM_ANNOTATE_SENTENCES, (Boolean) settings.get(STANFORDPOSTAGGER_ANNOTATE_SENTENCES)); aContext.setConfigParameterValue(de.unihd.dbs.uima.annotator.stanfordtagger.StanfordPOSTaggerWrapper.PARAM_ANNOTATE_PARTOFSPEECH, (Boolean) settings.get(STANFORDPOSTAGGER_ANNOTATE_POS)); aContext.setConfigParameterValue(de.unihd.dbs.uima.annotator.stanfordtagger.StanfordPOSTaggerWrapper.PARAM_CONFIG_PATH, ((String) settings.get(STANFORDPOSTAGGER_CONFIG_PATH)).length() == 0 ? null : (String) settings.get(STANFORDPOSTAGGER_CONFIG_PATH)); aContext.setConfigParameterValue(de.unihd.dbs.uima.annotator.stanfordtagger.StanfordPOSTaggerWrapper.PARAM_MODEL_PATH, (String) settings.get(STANFORDPOSTAGGER_MODEL_PATH)); stanford.initialize(aContext); } }
Java
/* * UimaContextImpl.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone.components.impl; import org.apache.uima.impl.RootUimaContext_impl; import org.apache.uima.resource.ConfigurationManager; import org.apache.uima.resource.impl.ConfigurationManager_impl; import org.apache.uima.resource.impl.ResourceManager_impl; import de.unihd.dbs.heideltime.standalone.Config; import de.unihd.dbs.heideltime.standalone.DocumentType; import de.unihd.dbs.uima.annotator.heideltime.resources.Language; /** * Implementation of UimaContext * * @author Andreas Fay, University of Heidelberg * @version 1.0 */ public class UimaContextImpl extends RootUimaContext_impl { /** * Constructor * * @param language * Language to process * @param typeToProcess * Document type to process */ public UimaContextImpl(Language language, DocumentType typeToProcess) { super(); // Initialize config ConfigurationManager configManager = new ConfigurationManager_impl(); // Initialize context this.initializeRoot(null, new ResourceManager_impl(), configManager); // Set session configManager.setSession(this.getSession()); // Set necessary variables configManager.setConfigParameterValue( makeQualifiedName(Config.get(Config.UIMAVAR_DATE)), Boolean.parseBoolean(Config.get(Config.CONSIDER_DATE))); configManager.setConfigParameterValue( makeQualifiedName(Config.get(Config.UIMAVAR_DURATION)), Boolean.parseBoolean(Config.get(Config.CONSIDER_DURATION))); configManager.setConfigParameterValue( makeQualifiedName(Config.get(Config.UIMAVAR_LANGUAGE)), language.getName()); configManager.setConfigParameterValue( makeQualifiedName(Config.get(Config.UIMAVAR_SET)), Boolean.parseBoolean(Config.get(Config.CONSIDER_SET))); configManager.setConfigParameterValue( makeQualifiedName(Config.get(Config.UIMAVAR_TIME)), Boolean.parseBoolean(Config.get(Config.CONSIDER_TIME))); configManager.setConfigParameterValue( makeQualifiedName(Config.get(Config.UIMAVAR_TYPETOPROCESS)), typeToProcess.toString()); configManager.setConfigParameterValue( makeQualifiedName(Config.UIMAVAR_CONVERTDURATIONS), new Boolean(true)); } }
Java
package de.unihd.dbs.heideltime.standalone.components.impl; import java.util.Properties; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import de.unihd.dbs.heideltime.standalone.components.UIMAAnnotator; import de.unihd.dbs.uima.annotator.intervaltagger.IntervalTagger; public class IntervalTaggerWrapper implements UIMAAnnotator { // uima wrapper instance private IntervalTagger tagger = new IntervalTagger(); public void initialize(Properties settings) { StandaloneConfigContext aContext = new StandaloneConfigContext(); // construct a context for the uima engine aContext.setConfigParameterValue(IntervalTagger.PARAM_LANGUAGE, (String) settings.get(IntervalTagger.PARAM_LANGUAGE)); aContext.setConfigParameterValue(IntervalTagger.PARAM_INTERVALS, (Boolean) settings.get(IntervalTagger.PARAM_INTERVALS)); aContext.setConfigParameterValue(IntervalTagger.PARAM_INTERVAL_CANDIDATES, (Boolean) settings.get(IntervalTagger.PARAM_INTERVAL_CANDIDATES)); try { tagger.initialize(aContext); } catch (ResourceInitializationException e) { e.printStackTrace(); } } /** * invokes the IntervalTagger's process method. */ public void process(JCas jcas) { try { tagger.process(jcas); } catch(AnalysisEngineProcessException e) { e.printStackTrace(); } } }
Java
/* * XMIResultFormatter.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone.components.impl; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.uima.cas.impl.XmiCasSerializer; import org.apache.uima.jcas.JCas; import org.apache.uima.util.XMLSerializer; import de.unihd.dbs.heideltime.standalone.components.ResultFormatter; /** * Result formatter based on XMI. * * @see {@link org.apache.uima.examples.xmi.XmiWriterCasConsumer} * * @author Andreas Fay, University of Heidelberg * @version 1.0 */ public class XMIResultFormatter implements ResultFormatter { @Override public String format(JCas jcas) throws Exception { ByteArrayOutputStream outStream = null; try { // Write XMI outStream = new ByteArrayOutputStream(); XmiCasSerializer ser = new XmiCasSerializer(jcas.getTypeSystem()); XMLSerializer xmlSer = new XMLSerializer(outStream, false); ser.serialize(jcas.getCas(), xmlSer.getContentHandler()); // Convert output stream to string // String newOut = outStream.toString("UTF-8"); String newOut = outStream.toString(); // System.err.println("NEWOUT:"+newOut); // // if (newOut.matches("^<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>.*$")){ // newOut = newOut.replaceFirst("<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>", // "<\\?xml version=\"1.0\" encoding=\""+Charset.defaultCharset().name()+"\"\\?>"); // } // if (newOut.matches("^.*?sofaString=\"(.*?)\".*$")){ // for (MatchResult r : findMatches(Pattern.compile("^(.*?sofaString=\")(.*?)(\".*)$"), newOut)){ // String stringBegin = r.group(1); // String sofaString = r.group(2); // System.err.println("SOFASTRING:"+sofaString); // String stringEnd = r.group(3); // // The sofaString is encoded as UTF-8. // // However, at this point it has to be translated back into the defaultCharset. // byte[] defaultDocText = new String(sofaString.getBytes(), "UTF-8").getBytes(Charset.defaultCharset().name()); // String docText = new String(defaultDocText); // System.err.println("DOCTEXT:"+docText); // newOut = stringBegin + docText + stringEnd; //// newOut = newOut.replaceFirst("sofaString=\".*?\"", "sofaString=\"" + docText + "\""); // } // } // System.err.println("NEWOUT:"+newOut); return newOut; } finally { if (outStream != null) { outStream.close(); } } } /** * Find all the matches of a pattern in a charSequence and return the * results as list. * * @param pattern * @param s * @return */ public static Iterable<MatchResult> findMatches(Pattern pattern, CharSequence s) { List<MatchResult> results = new ArrayList<MatchResult>(); for (Matcher m = pattern.matcher(s); m.find();) results.add(m.toMatchResult()); return results; } }
Java
package de.unihd.dbs.heideltime.standalone.components.impl; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.util.HashMap; import org.apache.uima.UimaContext; import org.apache.uima.cas.AbstractCas; import org.apache.uima.cas.SofaID; import org.apache.uima.resource.ResourceAccessException; import org.apache.uima.resource.Session; import org.apache.uima.util.InstrumentationFacility; import org.apache.uima.util.Logger; @SuppressWarnings("deprecation") public class StandaloneConfigContext implements UimaContext { private HashMap<String, Object> settings = new HashMap<String, Object>(); @Override public Object getConfigParameterValue(String aParamName) { return settings.get(aParamName); } public void setConfigParameterValue(String aParamName, Object aParamValue) { settings.put(aParamName, aParamValue); } /* * leave these defunct because we don't use them for now */ @Override public Object getConfigParameterValue(String aGroupName, String aParamName) { // TODO Auto-generated method stub return null; } @Override public String[] getConfigurationGroupNames() { // TODO Auto-generated method stub return null; } @Override public String[] getConfigParameterNames(String aGroup) { // TODO Auto-generated method stub return null; } @Override public String[] getConfigParameterNames() { // TODO Auto-generated method stub return null; } @Override public Logger getLogger() { // TODO Auto-generated method stub return null; } @Override public InstrumentationFacility getInstrumentationFacility() { // TODO Auto-generated method stub return null; } @Override public URL getResourceURL(String aKey) throws ResourceAccessException { // TODO Auto-generated method stub return null; } @Override public URI getResourceURI(String aKey) throws ResourceAccessException { // TODO Auto-generated method stub return null; } @Override public String getResourceFilePath(String aKey) throws ResourceAccessException { // TODO Auto-generated method stub return null; } @Override public InputStream getResourceAsStream(String aKey) throws ResourceAccessException { // TODO Auto-generated method stub return null; } @Override public Object getResourceObject(String aKey) throws ResourceAccessException { // TODO Auto-generated method stub return null; } @Override public URL getResourceURL(String aKey, String[] aParams) throws ResourceAccessException { // TODO Auto-generated method stub return null; } @Override public URI getResourceURI(String aKey, String[] aParams) throws ResourceAccessException { // TODO Auto-generated method stub return null; } @Override public String getResourceFilePath(String aKey, String[] aParams) throws ResourceAccessException { // TODO Auto-generated method stub return null; } @Override public InputStream getResourceAsStream(String aKey, String[] aParams) throws ResourceAccessException { // TODO Auto-generated method stub return null; } @Override public Object getResourceObject(String aKey, String[] aParams) throws ResourceAccessException { // TODO Auto-generated method stub return null; } @Override public String getDataPath() { // TODO Auto-generated method stub return null; } @Override public Session getSession() { // TODO Auto-generated method stub return null; } @Override public SofaID mapToSofaID(String aSofaName) { // TODO Auto-generated method stub return null; } @Override public String mapSofaIDToComponentSofaName(String aSofaID) { // TODO Auto-generated method stub return null; } @Override public SofaID[] getSofaMappings() { // TODO Auto-generated method stub return null; } @Override @SuppressWarnings("rawtypes") public AbstractCas getEmptyCas(Class aCasInterface) { // TODO Auto-generated method stub return null; } }
Java
package de.unihd.dbs.heideltime.standalone.components; import java.util.Properties; import org.apache.uima.jcas.JCas; /** * Interface for a common UIMA annotator. * * @author Julian Zell, University of Heidelberg */ public interface UIMAAnnotator { /** * Initializes the jcas object. * * @param jcas * @param language Language of document */ public abstract void initialize(Properties settings); /** * Processes jcas object. * * @param jcas * @param language Language of document */ public abstract void process(JCas jcas); }
Java
/* * JCasFactory.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone.components; import org.apache.uima.cas.CASException; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; /** * Factory for JCas objects to be used by HeidelTime * * @author Andreas Fay, University of Heidelberg * @version 1.0 */ public interface JCasFactory { /** * Creates new JCas object based on the type system description * * @return * @throws CASException * @throws ResourceInitializationException */ public JCas createJCas() throws CASException, ResourceInitializationException; }
Java
/* * DocumentType.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone; /** * Type of document to be processed by HeidelTime * * @author Andreas Fay, University of Heidelberg * @version 1.0 */ public enum DocumentType { NARRATIVES { public String toString() { return "narratives"; } }, NEWS { public String toString() { return "news"; } }, COLLOQUIAL { public String toString() { return "colloquial"; } }, SCIENTIFIC { public String toString() { return "scientific"; } } }
Java
/* * Copyright (C) 2009 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.odk.collect.android.activities; import java.util.ArrayList; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.listeners.DeleteInstancesListener; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import org.odk.collect.android.tasks.DeleteInstancesTask; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Toast; /** * Responsible for displaying and deleting all the valid forms in the forms * directory. * * @author Carl Hartung (carlhartung@gmail.com) * @author Yaw Anokwa (yanokwa@gmail.com) */ public class DataManagerList extends ListActivity implements DeleteInstancesListener { private static final String t = "DataManagerList"; private AlertDialog mAlertDialog; private Button mDeleteButton; private Button mToggleButton; private SimpleCursorAdapter mInstances; private ArrayList<Long> mSelected = new ArrayList<Long>(); DeleteInstancesTask mDeleteInstancesTask = null; private static final String SELECTED = "selected"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.data_manage_list); mDeleteButton = (Button) findViewById(R.id.delete_button); mDeleteButton.setText(getString(R.string.delete_file)); mDeleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logAction(this, "deleteButton", Integer.toString(mSelected.size())); if (mSelected.size() > 0) { createDeleteInstancesDialog(); } else { Toast.makeText(getApplicationContext(), R.string.noselect_error, Toast.LENGTH_SHORT).show(); } } }); mToggleButton = (Button) findViewById(R.id.toggle_button); mToggleButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { boolean checkAll = false; // if everything is checked, uncheck if (mSelected.size() == mInstances.getCount()) { checkAll = false; mSelected.clear(); mDeleteButton.setEnabled(false); } else { // otherwise check everything checkAll = true; for (int pos = 0; pos < DataManagerList.this.getListView().getCount(); pos++) { Long id = getListAdapter().getItemId(pos); if (!mSelected.contains(id)) { mSelected.add(id); } } mDeleteButton.setEnabled(true); } for (int pos = 0; pos < DataManagerList.this.getListView().getCount(); pos++) { DataManagerList.this.getListView().setItemChecked(pos, checkAll); } } }); Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, null, null, InstanceColumns.DISPLAY_NAME + " ASC"); String[] data = new String[] { InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_SUBTEXT }; int[] view = new int[] { R.id.text1, R.id.text2 }; mInstances = new SimpleCursorAdapter(this, R.layout.two_item_multiple_choice, c, data, view); setListAdapter(mInstances); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); getListView().setItemsCanFocus(false); mDeleteButton.setEnabled(false); mDeleteInstancesTask = (DeleteInstancesTask) getLastNonConfigurationInstance(); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } @Override public Object onRetainNonConfigurationInstance() { // pass the tasks on orientation-change restart return mDeleteInstancesTask; } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); long[] selectedArray = savedInstanceState.getLongArray(SELECTED); for (int i = 0; i < selectedArray.length; i++) { mSelected.add(selectedArray[i]); } mDeleteButton.setEnabled(selectedArray.length > 0); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); long[] selectedArray = new long[mSelected.size()]; for (int i = 0; i < mSelected.size(); i++) { selectedArray[i] = mSelected.get(i); } outState.putLongArray(SELECTED, selectedArray); } @Override protected void onResume() { // hook up to receive completion events if (mDeleteInstancesTask != null) { mDeleteInstancesTask.setDeleteListener(this); } super.onResume(); // async task may have completed while we were reorienting... if (mDeleteInstancesTask != null && mDeleteInstancesTask.getStatus() == AsyncTask.Status.FINISHED) { deleteComplete(mDeleteInstancesTask.getDeleteCount()); } } @Override protected void onPause() { if (mDeleteInstancesTask != null ) { mDeleteInstancesTask.setDeleteListener(null); } if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } super.onPause(); } /** * Create the instance delete dialog */ private void createDeleteInstancesDialog() { Collect.getInstance().getActivityLogger().logAction(this, "createDeleteInstancesDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setTitle(getString(R.string.delete_file)); mAlertDialog.setMessage(getString(R.string.delete_confirm, mSelected.size())); DialogInterface.OnClickListener dialogYesNoListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON1: // delete Collect.getInstance().getActivityLogger().logAction(this, "createDeleteInstancesDialog", "delete"); deleteSelectedInstances(); break; case DialogInterface.BUTTON2: // do nothing Collect.getInstance().getActivityLogger().logAction(this, "createDeleteInstancesDialog", "cancel"); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.delete_yes), dialogYesNoListener); mAlertDialog.setButton2(getString(R.string.delete_no), dialogYesNoListener); mAlertDialog.show(); } /** * Deletes the selected files. Content provider handles removing the files * from the filesystem. */ private void deleteSelectedInstances() { if (mDeleteInstancesTask == null) { mDeleteInstancesTask = new DeleteInstancesTask(); mDeleteInstancesTask.setContentResolver(getContentResolver()); mDeleteInstancesTask.setDeleteListener(this); mDeleteInstancesTask.execute(mSelected.toArray(new Long[mSelected .size()])); } else { Toast.makeText(this, getString(R.string.file_delete_in_progress), Toast.LENGTH_LONG).show(); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // get row id from db Cursor c = (Cursor) getListAdapter().getItem(position); long k = c.getLong(c.getColumnIndex(InstanceColumns._ID)); // add/remove from selected list if (mSelected.contains(k)) mSelected.remove(k); else mSelected.add(k); Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", Long.toString(k)); mDeleteButton.setEnabled(!(mSelected.size() == 0)); } @Override public void deleteComplete(int deletedInstances) { Log.i(t, "Delete instances complete"); Collect.getInstance().getActivityLogger().logAction(this, "deleteComplete", Integer.toString(deletedInstances)); if (deletedInstances == mSelected.size()) { // all deletes were successful Toast.makeText(this, getString(R.string.file_deleted_ok, deletedInstances), Toast.LENGTH_SHORT).show(); } else { // had some failures Log.e(t, "Failed to delete " + (mSelected.size() - deletedInstances) + " instances"); Toast.makeText( this, getString(R.string.file_deleted_error, mSelected.size() - deletedInstances, mSelected.size()), Toast.LENGTH_LONG).show(); } mDeleteInstancesTask = null; mSelected.clear(); getListView().clearChoices(); // doesn't unset the checkboxes for ( int i = 0 ; i < getListView().getCount() ; ++i ) { getListView().setItemChecked(i, false); } mDeleteButton.setEnabled(false); } }
Java
/* * Copyright (C) 2009 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.odk.collect.android.activities; import java.util.ArrayList; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.listeners.DeleteFormsListener; import org.odk.collect.android.listeners.DiskSyncListener; import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns; import org.odk.collect.android.tasks.DeleteFormsTask; import org.odk.collect.android.tasks.DiskSyncTask; import org.odk.collect.android.utilities.VersionHidingCursorAdapter; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; /** * Responsible for displaying and deleting all the valid forms in the forms * directory. * * @author Carl Hartung (carlhartung@gmail.com) * @author Yaw Anokwa (yanokwa@gmail.com) */ public class FormManagerList extends ListActivity implements DiskSyncListener, DeleteFormsListener { private static String t = "FormManagerList"; private static final String SELECTED = "selected"; private static final String syncMsgKey = "syncmsgkey"; private AlertDialog mAlertDialog; private Button mDeleteButton; private Button mToggleButton; private SimpleCursorAdapter mInstances; private ArrayList<Long> mSelected = new ArrayList<Long>(); static class BackgroundTasks { DiskSyncTask mDiskSyncTask = null; DeleteFormsTask mDeleteFormsTask = null; BackgroundTasks() { }; } BackgroundTasks mBackgroundTasks; // handed across orientation changes @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.form_manage_list); mDeleteButton = (Button) findViewById(R.id.delete_button); mDeleteButton.setText(getString(R.string.delete_file)); mDeleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logAction(this, "deleteButton", Integer.toString(mSelected.size())); if (mSelected.size() > 0) { createDeleteFormsDialog(); } else { Toast.makeText(getApplicationContext(), R.string.noselect_error, Toast.LENGTH_SHORT).show(); } } }); mToggleButton = (Button) findViewById(R.id.toggle_button); mToggleButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { boolean checkAll = false; // if everything is checked, uncheck if (mSelected.size() == mInstances.getCount()) { checkAll = false; mSelected.clear(); mDeleteButton.setEnabled(false); } else { // otherwise check everything checkAll = true; for (int pos = 0; pos < FormManagerList.this.getListView().getCount(); pos++) { Long id = getListAdapter().getItemId(pos); if (!mSelected.contains(id)) { mSelected.add(id); } } mDeleteButton.setEnabled(true); } for (int pos = 0; pos < FormManagerList.this.getListView().getCount(); pos++) { FormManagerList.this.getListView().setItemChecked(pos, checkAll); } } }); String sortOrder = FormsColumns.DISPLAY_NAME + " ASC, " + FormsColumns.JR_VERSION + " DESC"; Cursor c = managedQuery(FormsColumns.CONTENT_URI, null, null, null, sortOrder); String[] data = new String[] { FormsColumns.DISPLAY_NAME, FormsColumns.DISPLAY_SUBTEXT, FormsColumns.JR_VERSION }; int[] view = new int[] { R.id.text1, R.id.text2, R.id.text3 }; // render total instance view mInstances = new VersionHidingCursorAdapter(FormsColumns.JR_VERSION, this, R.layout.two_item_multiple_choice, c, data, view); setListAdapter(mInstances); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); getListView().setItemsCanFocus(false); mDeleteButton.setEnabled(!(mSelected.size() == 0)); if (savedInstanceState != null && savedInstanceState.containsKey(syncMsgKey)) { TextView tv = (TextView) findViewById(R.id.status_text); tv.setText(savedInstanceState.getString(syncMsgKey)); } mBackgroundTasks = (BackgroundTasks) getLastNonConfigurationInstance(); if (mBackgroundTasks == null) { mBackgroundTasks = new BackgroundTasks(); mBackgroundTasks.mDiskSyncTask = new DiskSyncTask(); mBackgroundTasks.mDiskSyncTask.setDiskSyncListener(this); mBackgroundTasks.mDiskSyncTask.execute((Void[]) null); } } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } @Override public Object onRetainNonConfigurationInstance() { // pass the tasks on restart return mBackgroundTasks; } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); long[] selectedArray = savedInstanceState.getLongArray(SELECTED); for (int i = 0; i < selectedArray.length; i++) { mSelected.add(selectedArray[i]); } mDeleteButton.setEnabled(selectedArray.length > 0); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); long[] selectedArray = new long[mSelected.size()]; for (int i = 0; i < mSelected.size(); i++) { selectedArray[i] = mSelected.get(i); } outState.putLongArray(SELECTED, selectedArray); TextView tv = (TextView) findViewById(R.id.status_text); outState.putString(syncMsgKey, tv.getText().toString()); } @Override protected void onResume() { // hook up to receive completion events mBackgroundTasks.mDiskSyncTask.setDiskSyncListener(this); if (mBackgroundTasks.mDeleteFormsTask != null) { mBackgroundTasks.mDeleteFormsTask.setDeleteListener(this); } super.onResume(); // async task may have completed while we were reorienting... if (mBackgroundTasks.mDiskSyncTask.getStatus() == AsyncTask.Status.FINISHED) { SyncComplete(mBackgroundTasks.mDiskSyncTask.getStatusMessage()); } if (mBackgroundTasks.mDeleteFormsTask != null && mBackgroundTasks.mDeleteFormsTask.getStatus() == AsyncTask.Status.FINISHED) { deleteComplete(mBackgroundTasks.mDeleteFormsTask.getDeleteCount()); } } @Override protected void onPause() { mBackgroundTasks.mDiskSyncTask.setDiskSyncListener(null); if (mBackgroundTasks.mDeleteFormsTask != null ) { mBackgroundTasks.mDeleteFormsTask.setDeleteListener(null); } if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } super.onPause(); } /** * Create the form delete dialog */ private void createDeleteFormsDialog() { Collect.getInstance().getActivityLogger().logAction(this, "createDeleteFormsDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setTitle(getString(R.string.delete_file)); mAlertDialog.setMessage(getString(R.string.delete_confirm, mSelected.size())); DialogInterface.OnClickListener dialogYesNoListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON1: // delete Collect.getInstance().getActivityLogger().logAction(this, "createDeleteFormsDialog", "delete"); deleteSelectedForms(); break; case DialogInterface.BUTTON2: // do nothing Collect.getInstance().getActivityLogger().logAction(this, "createDeleteFormsDialog", "cancel"); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.delete_yes), dialogYesNoListener); mAlertDialog.setButton2(getString(R.string.delete_no), dialogYesNoListener); mAlertDialog.show(); } /** * Deletes the selected files.First from the database then from the file * system */ private void deleteSelectedForms() { // only start if no other task is running if (mBackgroundTasks.mDeleteFormsTask == null) { mBackgroundTasks.mDeleteFormsTask = new DeleteFormsTask(); mBackgroundTasks.mDeleteFormsTask .setContentResolver(getContentResolver()); mBackgroundTasks.mDeleteFormsTask.setDeleteListener(this); mBackgroundTasks.mDeleteFormsTask.execute(mSelected .toArray(new Long[mSelected.size()])); } else { Toast.makeText(this, getString(R.string.file_delete_in_progress), Toast.LENGTH_LONG).show(); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // get row id from db Cursor c = (Cursor) getListAdapter().getItem(position); long k = c.getLong(c.getColumnIndex(FormsColumns._ID)); // add/remove from selected list if (mSelected.contains(k)) mSelected.remove(k); else mSelected.add(k); Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", Long.toString(k)); mDeleteButton.setEnabled(!(mSelected.size() == 0)); } @Override public void SyncComplete(String result) { Log.i(t, "Disk scan complete"); TextView tv = (TextView) findViewById(R.id.status_text); tv.setText(result); } @Override public void deleteComplete(int deletedForms) { Log.i(t, "Delete forms complete"); Collect.getInstance().getActivityLogger().logAction(this, "deleteComplete", Integer.toString(deletedForms)); if (deletedForms == mSelected.size()) { // all deletes were successful Toast.makeText(getApplicationContext(), getString(R.string.file_deleted_ok, deletedForms), Toast.LENGTH_SHORT).show(); } else { // had some failures Log.e(t, "Failed to delete " + (mSelected.size() - deletedForms) + " forms"); Toast.makeText( getApplicationContext(), getString(R.string.file_deleted_error, mSelected.size() - deletedForms, mSelected.size()), Toast.LENGTH_LONG).show(); } mBackgroundTasks.mDeleteFormsTask = null; mSelected.clear(); getListView().clearChoices(); // doesn't unset the checkboxes for ( int i = 0 ; i < getListView().getCount() ; ++i ) { getListView().setItemChecked(i, false); } mDeleteButton.setEnabled(false); } }
Java
/* * Copyright (C) 2009 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.odk.collect.android.activities; import java.io.File; import java.io.FileFilter; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.Locale; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.form.api.FormEntryCaption; import org.javarosa.form.api.FormEntryController; import org.javarosa.form.api.FormEntryPrompt; import org.javarosa.model.xform.XFormsModule; import org.javarosa.xpath.XPathTypeMismatchException; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.listeners.AdvanceToNextListener; import org.odk.collect.android.listeners.FormLoaderListener; import org.odk.collect.android.listeners.FormSavedListener; import org.odk.collect.android.logic.FormController; import org.odk.collect.android.logic.FormController.FailedConstraint; import org.odk.collect.android.logic.PropertyManager; import org.odk.collect.android.preferences.AdminPreferencesActivity; import org.odk.collect.android.preferences.PreferencesActivity; import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns; import org.odk.collect.android.provider.InstanceProviderAPI; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import org.odk.collect.android.tasks.FormLoaderTask; import org.odk.collect.android.tasks.SaveToDiskTask; import org.odk.collect.android.utilities.FileUtils; import org.odk.collect.android.utilities.MediaUtils; import org.odk.collect.android.views.ODKView; import org.odk.collect.android.widgets.QuestionWidget; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.MediaStore.Images; import android.text.InputFilter; import android.text.Spanned; import android.util.DisplayMetrics; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; /** * FormEntryActivity is responsible for displaying questions, animating * transitions between questions, and allowing the user to enter data. * * @author Carl Hartung (carlhartung@gmail.com) */ public class FormEntryActivity extends Activity implements AnimationListener, FormLoaderListener, FormSavedListener, AdvanceToNextListener, OnGestureListener { private static final String t = "FormEntryActivity"; // save with every swipe forward or back. Timings indicate this takes .25 // seconds. // if it ever becomes an issue, this value can be changed to save every n'th // screen. private static final int SAVEPOINT_INTERVAL = 1; // Defines for FormEntryActivity private static final boolean EXIT = true; private static final boolean DO_NOT_EXIT = false; private static final boolean EVALUATE_CONSTRAINTS = true; private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false; // Request codes for returning data from specified intent. public static final int IMAGE_CAPTURE = 1; public static final int BARCODE_CAPTURE = 2; public static final int AUDIO_CAPTURE = 3; public static final int VIDEO_CAPTURE = 4; public static final int LOCATION_CAPTURE = 5; public static final int HIERARCHY_ACTIVITY = 6; public static final int IMAGE_CHOOSER = 7; public static final int AUDIO_CHOOSER = 8; public static final int VIDEO_CHOOSER = 9; public static final int EX_STRING_CAPTURE = 10; public static final int EX_INT_CAPTURE = 11; public static final int EX_DECIMAL_CAPTURE = 12; public static final int DRAW_IMAGE = 13; public static final int SIGNATURE_CAPTURE = 14; public static final int ANNOTATE_IMAGE = 15; public static final int ALIGNED_IMAGE = 16; // Extra returned from gp activity public static final String LOCATION_RESULT = "LOCATION_RESULT"; public static final String KEY_INSTANCES = "instances"; public static final String KEY_SUCCESS = "success"; public static final String KEY_ERROR = "error"; // Identifies the gp of the form used to launch form entry public static final String KEY_FORMPATH = "formpath"; // Identifies whether this is a new form, or reloading a form after a screen // rotation (or similar) private static final String NEWFORM = "newform"; // these are only processed if we shut down and are restoring after an // external intent fires public static final String KEY_INSTANCEPATH = "instancepath"; public static final String KEY_XPATH = "xpath"; public static final String KEY_XPATH_WAITING_FOR_DATA = "xpathwaiting"; private static final int MENU_LANGUAGES = Menu.FIRST; private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 1; private static final int MENU_SAVE = Menu.FIRST + 2; private static final int MENU_PREFERENCES = Menu.FIRST + 3; private static final int PROGRESS_DIALOG = 1; private static final int SAVING_DIALOG = 2; // Random ID private static final int DELETE_REPEAT = 654321; private String mFormPath; private GestureDetector mGestureDetector; private Animation mInAnimation; private Animation mOutAnimation; private View mStaleView = null; private LinearLayout mQuestionHolder; private View mCurrentView; private AlertDialog mAlertDialog; private ProgressDialog mProgressDialog; private String mErrorMessage; // used to limit forward/backward swipes to one per question private boolean mBeenSwiped = false; private int viewCount = 0; private FormLoaderTask mFormLoaderTask; private SaveToDiskTask mSaveToDiskTask; private ImageButton mNextButton; private ImageButton mBackButton; enum AnimationType { LEFT, RIGHT, FADE } private SharedPreferences mAdminPreferences; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must be at the beginning of any activity that can be called from an // external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } setContentView(R.layout.form_entry); setTitle(getString(R.string.app_name) + " > " + getString(R.string.loading_form)); mBeenSwiped = false; mAlertDialog = null; mCurrentView = null; mInAnimation = null; mOutAnimation = null; mGestureDetector = new GestureDetector(this); mQuestionHolder = (LinearLayout) findViewById(R.id.questionholder); // get admin preference settings mAdminPreferences = getSharedPreferences( AdminPreferencesActivity.ADMIN_PREFERENCES, 0); mNextButton = (ImageButton) findViewById(R.id.form_forward_button); mNextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mBeenSwiped = true; showNextView(); } }); mBackButton = (ImageButton) findViewById(R.id.form_back_button); mBackButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mBeenSwiped = true; showPreviousView(); } }); // Load JavaRosa modules. needed to restore forms. new XFormsModule().registerModule(); // needed to override rms property manager org.javarosa.core.services.PropertyManager .setPropertyManager(new PropertyManager(getApplicationContext())); String startingXPath = null; String waitingXPath = null; String instancePath = null; Boolean newForm = true; if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_FORMPATH)) { mFormPath = savedInstanceState.getString(KEY_FORMPATH); } if (savedInstanceState.containsKey(KEY_INSTANCEPATH)) { instancePath = savedInstanceState.getString(KEY_INSTANCEPATH); } if (savedInstanceState.containsKey(KEY_XPATH)) { startingXPath = savedInstanceState.getString(KEY_XPATH); Log.i(t, "startingXPath is: " + startingXPath); } if (savedInstanceState.containsKey(KEY_XPATH_WAITING_FOR_DATA)) { waitingXPath = savedInstanceState .getString(KEY_XPATH_WAITING_FOR_DATA); Log.i(t, "waitingXPath is: " + waitingXPath); } if (savedInstanceState.containsKey(NEWFORM)) { newForm = savedInstanceState.getBoolean(NEWFORM, true); } if (savedInstanceState.containsKey(KEY_ERROR)) { mErrorMessage = savedInstanceState.getString(KEY_ERROR); } } // If a parse error message is showing then nothing else is loaded // Dialogs mid form just disappear on rotation. if (mErrorMessage != null) { createErrorDialog(mErrorMessage, EXIT); return; } // Check to see if this is a screen flip or a new form load. Object data = getLastNonConfigurationInstance(); if (data instanceof FormLoaderTask) { mFormLoaderTask = (FormLoaderTask) data; } else if (data instanceof SaveToDiskTask) { mSaveToDiskTask = (SaveToDiskTask) data; } else if (data == null) { if (!newForm) { if (Collect.getInstance().getFormController() != null) { refreshCurrentView(); } else { Log.w(t, "Reloading form and restoring state."); // we need to launch the form loader to load the form // controller... mFormLoaderTask = new FormLoaderTask(instancePath, startingXPath, waitingXPath); Collect.getInstance().getActivityLogger() .logAction(this, "formReloaded", mFormPath); // TODO: this doesn' work (dialog does not get removed): // showDialog(PROGRESS_DIALOG); // show dialog before we execute... mFormLoaderTask.execute(mFormPath); } return; } // Not a restart from a screen orientation change (or other). Collect.getInstance().setFormController(null); Intent intent = getIntent(); if (intent != null) { Uri uri = intent.getData(); if (getContentResolver().getType(uri) == InstanceColumns.CONTENT_ITEM_TYPE) { // get the formId and version for this instance... String jrFormId = null; String jrVersion = null; { Cursor instanceCursor = null; try { instanceCursor = getContentResolver().query(uri, null, null, null, null); if (instanceCursor.getCount() != 1) { this.createErrorDialog("Bad URI: " + uri, EXIT); return; } else { instanceCursor.moveToFirst(); instancePath = instanceCursor .getString(instanceCursor .getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); Collect.getInstance() .getActivityLogger() .logAction(this, "instanceLoaded", instancePath); jrFormId = instanceCursor .getString(instanceCursor .getColumnIndex(InstanceColumns.JR_FORM_ID)); int idxJrVersion = instanceCursor .getColumnIndex(InstanceColumns.JR_VERSION); jrVersion = instanceCursor.isNull(idxJrVersion) ? null : instanceCursor .getString(idxJrVersion); } } finally { if (instanceCursor != null) { instanceCursor.close(); } } } String[] selectionArgs; String selection; if (jrVersion == null) { selectionArgs = new String[] { jrFormId }; selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + " IS NULL"; } else { selectionArgs = new String[] { jrFormId, jrVersion }; selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + "=?"; } { Cursor formCursor = null; try { formCursor = getContentResolver().query( FormsColumns.CONTENT_URI, null, selection, selectionArgs, null); if (formCursor.getCount() == 1) { formCursor.moveToFirst(); mFormPath = formCursor .getString(formCursor .getColumnIndex(FormsColumns.FORM_FILE_PATH)); } else if (formCursor.getCount() < 1) { this.createErrorDialog( getString( R.string.parent_form_not_present, jrFormId) + ((jrVersion == null) ? "" : "\n" + getString(R.string.version) + " " + jrVersion), EXIT); return; } else if (formCursor.getCount() > 1) { // still take the first entry, but warn that // there are multiple rows. // user will need to hand-edit the SQLite // database to fix it. formCursor.moveToFirst(); mFormPath = formCursor .getString(formCursor .getColumnIndex(FormsColumns.FORM_FILE_PATH)); this.createErrorDialog( "Multiple matching form definitions exist", DO_NOT_EXIT); } } finally { if (formCursor != null) { formCursor.close(); } } } } else if (getContentResolver().getType(uri) == FormsColumns.CONTENT_ITEM_TYPE) { Cursor c = null; try { c = getContentResolver().query(uri, null, null, null, null); if (c.getCount() != 1) { this.createErrorDialog("Bad URI: " + uri, EXIT); return; } else { c.moveToFirst(); mFormPath = c .getString(c .getColumnIndex(FormsColumns.FORM_FILE_PATH)); // This is the fill-blank-form code path. // See if there is a savepoint for this form that // has never been // explicitly saved // by the user. If there is, open this savepoint // (resume this filled-in // form). // Savepoints for forms that were explicitly saved // will be recovered // when that // explicitly saved instance is edited via // edit-saved-form. final String filePrefix = mFormPath.substring( mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.')) + "_"; final String fileSuffix = ".xml.save"; File cacheDir = new File(Collect.CACHE_PATH); File[] files = cacheDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { String name = pathname.getName(); return name.startsWith(filePrefix) && name.endsWith(fileSuffix); } }); // see if any of these savepoints are for a // filled-in form that has never been // explicitly saved by the user... for (int i = 0; i < files.length; ++i) { File candidate = files[i]; String instanceDirName = candidate.getName() .substring( 0, candidate.getName().length() - fileSuffix.length()); File instanceDir = new File( Collect.INSTANCES_PATH + File.separator + instanceDirName); File instanceFile = new File(instanceDir, instanceDirName + ".xml"); if (instanceDir.exists() && instanceDir.isDirectory() && !instanceFile.exists()) { // yes! -- use this savepoint file instancePath = instanceFile .getAbsolutePath(); break; } } } } finally { if (c != null) { c.close(); } } } else { Log.e(t, "unrecognized URI"); this.createErrorDialog("unrecognized URI: " + uri, EXIT); return; } mFormLoaderTask = new FormLoaderTask(instancePath, null, null); Collect.getInstance().getActivityLogger() .logAction(this, "formLoaded", mFormPath); showDialog(PROGRESS_DIALOG); // show dialog before we execute... mFormLoaderTask.execute(mFormPath); } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_FORMPATH, mFormPath); FormController formController = Collect.getInstance() .getFormController(); if (formController != null) { outState.putString(KEY_INSTANCEPATH, formController .getInstancePath().getAbsolutePath()); outState.putString(KEY_XPATH, formController.getXPath(formController.getFormIndex())); FormIndex waiting = formController.getIndexWaitingForData(); if (waiting != null) { outState.putString(KEY_XPATH_WAITING_FOR_DATA, formController.getXPath(waiting)); } // save the instance to a temp path... SaveToDiskTask.blockingExportTempData(); } outState.putBoolean(NEWFORM, false); outState.putString(KEY_ERROR, mErrorMessage); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); FormController formController = Collect.getInstance() .getFormController(); if (formController == null) { // we must be in the midst of a reload of the FormController. // try to save this callback data to the FormLoaderTask if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) { mFormLoaderTask.setActivityResult(requestCode, resultCode, intent); } else { Log.e(t, "Got an activityResult without any pending form loader"); } return; } if (resultCode == RESULT_CANCELED) { // request was canceled... if (requestCode != HIERARCHY_ACTIVITY) { ((ODKView) mCurrentView).cancelWaitingForBinaryData(); } return; } switch (requestCode) { case BARCODE_CAPTURE: String sb = intent.getStringExtra("SCAN_RESULT"); ((ODKView) mCurrentView).setBinaryData(sb); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case EX_STRING_CAPTURE: String sv = intent.getStringExtra("value"); ((ODKView) mCurrentView).setBinaryData(sv); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case EX_INT_CAPTURE: Integer iv = intent.getIntExtra("value", 0); ((ODKView) mCurrentView).setBinaryData(iv); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case EX_DECIMAL_CAPTURE: Double dv = intent.getDoubleExtra("value", 0.0); ((ODKView) mCurrentView).setBinaryData(dv); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case DRAW_IMAGE: case ANNOTATE_IMAGE: case SIGNATURE_CAPTURE: case IMAGE_CAPTURE: /* * We saved the image to the tempfile_path, but we really want it to * be in: /sdcard/odk/instances/[current instnace]/something.jpg so * we move it there before inserting it into the content provider. * Once the android image capture bug gets fixed, (read, we move on * from Android 1.6) we want to handle images the audio and video */ // The intent is empty, but we know we saved the image to the temp // file File fi = new File(Collect.TMPFILE_PATH); String mInstanceFolder = formController.getInstancePath() .getParent(); String s = mInstanceFolder + File.separator + System.currentTimeMillis() + ".jpg"; File nf = new File(s); if (!fi.renameTo(nf)) { Log.e(t, "Failed to rename " + fi.getAbsolutePath()); } else { Log.i(t, "renamed " + fi.getAbsolutePath() + " to " + nf.getAbsolutePath()); } ((ODKView) mCurrentView).setBinaryData(nf); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case ALIGNED_IMAGE: /* * We saved the image to the tempfile_path; the app returns the * full path to the saved file in the EXTRA_OUTPUT extra. Take * that file and move it into the instance folder. */ String path = intent.getStringExtra(android.provider.MediaStore.EXTRA_OUTPUT); fi = new File(path); mInstanceFolder = formController.getInstancePath() .getParent(); s = mInstanceFolder + File.separator + System.currentTimeMillis() + ".jpg"; nf = new File(s); if (!fi.renameTo(nf)) { Log.e(t, "Failed to rename " + fi.getAbsolutePath()); } else { Log.i(t, "renamed " + fi.getAbsolutePath() + " to " + nf.getAbsolutePath()); } ((ODKView) mCurrentView).setBinaryData(nf); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case IMAGE_CHOOSER: /* * We have a saved image somewhere, but we really want it to be in: * /sdcard/odk/instances/[current instnace]/something.jpg so we move * it there before inserting it into the content provider. Once the * android image capture bug gets fixed, (read, we move on from * Android 1.6) we want to handle images the audio and video */ // get gp of chosen file String sourceImagePath = null; Uri selectedImage = intent.getData(); if (selectedImage.toString().startsWith("file")) { sourceImagePath = selectedImage.toString().substring(6); } else { String[] projection = { Images.Media.DATA }; Cursor cursor = null; try { cursor = getContentResolver().query(selectedImage, projection, null, null, null); int column_index = cursor .getColumnIndexOrThrow(Images.Media.DATA); cursor.moveToFirst(); sourceImagePath = cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } // Copy file to sdcard String mInstanceFolder1 = formController.getInstancePath() .getParent(); String destImagePath = mInstanceFolder1 + File.separator + System.currentTimeMillis() + ".jpg"; File source = new File(sourceImagePath); File newImage = new File(destImagePath); FileUtils.copyFile(source, newImage); ((ODKView) mCurrentView).setBinaryData(newImage); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case AUDIO_CAPTURE: case VIDEO_CAPTURE: case AUDIO_CHOOSER: case VIDEO_CHOOSER: // For audio/video capture/chooser, we get the URI from the content // provider // then the widget copies the file and makes a new entry in the // content provider. Uri media = intent.getData(); ((ODKView) mCurrentView).setBinaryData(media); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case LOCATION_CAPTURE: String sl = intent.getStringExtra(LOCATION_RESULT); ((ODKView) mCurrentView).setBinaryData(sl); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case HIERARCHY_ACTIVITY: // We may have jumped to a new index in hierarchy activity, so // refresh break; } refreshCurrentView(); } /** * Refreshes the current view. the controller and the displayed view can get * out of sync due to dialogs and restarts caused by screen orientation * changes, so they're resynchronized here. */ public void refreshCurrentView() { FormController formController = Collect.getInstance() .getFormController(); int event = formController.getEvent(); // When we refresh, repeat dialog state isn't maintained, so step back // to the previous // question. // Also, if we're within a group labeled 'field list', step back to the // beginning of that // group. // That is, skip backwards over repeat prompts, groups that are not // field-lists, // repeat events, and indexes in field-lists that is not the containing // group. if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) { createRepeatDialog(); } else { View current = createView(event, false); showView(current, AnimationType.FADE); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onPrepareOptionsMenu", "show"); FormController formController = Collect.getInstance() .getFormController(); menu.removeItem(MENU_LANGUAGES); menu.removeItem(MENU_HIERARCHY_VIEW); menu.removeItem(MENU_SAVE); menu.removeItem(MENU_PREFERENCES); if (mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_SAVE_MID, true)) { menu.add(0, MENU_SAVE, 0, R.string.save_all_answers).setIcon( android.R.drawable.ic_menu_save); } if (mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_JUMP_TO, true)) { menu.add(0, MENU_HIERARCHY_VIEW, 0, getString(R.string.view_hierarchy)).setIcon( R.drawable.ic_menu_goto); } if (mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_CHANGE_LANGUAGE, true)) { menu.add(0, MENU_LANGUAGES, 0, getString(R.string.change_language)) .setIcon(R.drawable.ic_menu_start_conversation) .setEnabled( (formController.getLanguages() == null || formController .getLanguages().length == 1) ? false : true); } if (mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_ACCESS_SETTINGS, true)) { menu.add(0, MENU_PREFERENCES, 0, getString(R.string.general_preferences)).setIcon( android.R.drawable.ic_menu_preferences); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { FormController formController = Collect.getInstance() .getFormController(); switch (item.getItemId()) { case MENU_LANGUAGES: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "MENU_LANGUAGES"); createLanguageDialog(); return true; case MENU_SAVE: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "MENU_SAVE"); // don't exit saveDataToDisk(DO_NOT_EXIT, isInstanceComplete(false), null); return true; case MENU_HIERARCHY_VIEW: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "MENU_HIERARCHY_VIEW"); if (formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } Intent i = new Intent(this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY); return true; case MENU_PREFERENCES: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "MENU_PREFERENCES"); Intent pref = new Intent(this, PreferencesActivity.class); startActivity(pref); return true; } return super.onOptionsItemSelected(item); } /** * Attempt to save the answer(s) in the current screen to into the data * model. * * @param evaluateConstraints * @return false if any error occurs while saving (constraint violated, * etc...), true otherwise. */ private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) { FormController formController = Collect.getInstance() .getFormController(); // only try to save if the current event is a question or a field-list // group if (formController.currentPromptIsQuestion()) { LinkedHashMap<FormIndex, IAnswerData> answers = ((ODKView) mCurrentView) .getAnswers(); FailedConstraint constraint = formController.saveAllScreenAnswers( answers, evaluateConstraints); if (constraint != null) { createConstraintToast(constraint.index, constraint.status); return false; } } return true; } /** * Clears the answer on the screen. */ private void clearAnswer(QuestionWidget qw) { if ( qw.getAnswer() != null) { qw.clearAnswer(); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onCreateContextMenu", "show"); FormController formController = Collect.getInstance() .getFormController(); menu.add(0, v.getId(), 0, getString(R.string.clear_answer)); if (formController.indexContainsRepeatableGroup()) { menu.add(0, DELETE_REPEAT, 0, getString(R.string.delete_repeat)); } menu.setHeaderTitle(getString(R.string.edit_prompt)); } @Override public boolean onContextItemSelected(MenuItem item) { /* * We don't have the right view here, so we store the View's ID as the * item ID and loop through the possible views to find the one the user * clicked on. */ for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) { if (item.getItemId() == qw.getId()) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onContextItemSelected", "createClearDialog", qw.getPrompt().getIndex()); createClearDialog(qw); } } if (item.getItemId() == DELETE_REPEAT) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onContextItemSelected", "createDeleteRepeatConfirmDialog"); createDeleteRepeatConfirmDialog(); } return super.onContextItemSelected(item); } /** * If we're loading, then we pass the loading thread to our next instance. */ @Override public Object onRetainNonConfigurationInstance() { FormController formController = Collect.getInstance() .getFormController(); // if a form is loading, pass the loader task if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) return mFormLoaderTask; // if a form is writing to disk, pass the save to disk task if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED) return mSaveToDiskTask; // mFormEntryController is static so we don't need to pass it. if (formController != null && formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } return null; } /** * Creates a view given the View type and an event * * @param event * @param advancingPage * -- true if this results from advancing through the form * @return newly created View */ private View createView(int event, boolean advancingPage) { FormController formController = Collect.getInstance() .getFormController(); setTitle(getString(R.string.app_name) + " > " + formController.getFormTitle()); switch (event) { case FormEntryController.EVENT_BEGINNING_OF_FORM: View startView = View .inflate(this, R.layout.form_entry_start, null); setTitle(getString(R.string.app_name) + " > " + formController.getFormTitle()); Drawable image = null; File mediaFolder = formController.getMediaFolder(); String mediaDir = mediaFolder.getAbsolutePath(); BitmapDrawable bitImage = null; // attempt to load the form-specific logo... // this is arbitrarily silly bitImage = new BitmapDrawable(mediaDir + File.separator + "form_logo.png"); if (bitImage != null && bitImage.getBitmap() != null && bitImage.getIntrinsicHeight() > 0 && bitImage.getIntrinsicWidth() > 0) { image = bitImage; } if (image == null) { // show the opendatakit zig... // image = // getResources().getDrawable(R.drawable.opendatakit_zig); ((ImageView) startView.findViewById(R.id.form_start_bling)) .setVisibility(View.GONE); } else { ImageView v = ((ImageView) startView .findViewById(R.id.form_start_bling)); v.setImageDrawable(image); v.setContentDescription(formController.getFormTitle()); } // change start screen based on navigation prefs String navigationChoice = PreferenceManager.getDefaultSharedPreferences(this).getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.KEY_NAVIGATION); Boolean useSwipe = false; Boolean useButtons = false; ImageView ia = ((ImageView) startView.findViewById(R.id.image_advance)); ImageView ib = ((ImageView) startView.findViewById(R.id.image_backup)); TextView ta = ((TextView) startView.findViewById(R.id.text_advance)); TextView tb = ((TextView) startView.findViewById(R.id.text_backup)); TextView d = ((TextView) startView.findViewById(R.id.description)); if (navigationChoice != null) { if (navigationChoice.contains(PreferencesActivity.NAVIGATION_SWIPE)) { useSwipe = true; } if (navigationChoice.contains(PreferencesActivity.NAVIGATION_BUTTONS)) { useButtons = true; } } if (useSwipe && !useButtons) { d.setText(getString(R.string.swipe_instructions, formController.getFormTitle())); } else if (useButtons && !useSwipe) { ia.setVisibility(View.GONE); ib.setVisibility(View.GONE); ta.setVisibility(View.GONE); tb.setVisibility(View.GONE); d.setText(getString(R.string.buttons_instructions, formController.getFormTitle())); } else { d.setText(getString(R.string.swipe_buttons_instructions, formController.getFormTitle())); } if (mBackButton.isShown()) { mBackButton.setEnabled(false); } if (mNextButton.isShown()) { mNextButton.setEnabled(true); } return startView; case FormEntryController.EVENT_END_OF_FORM: View endView = View.inflate(this, R.layout.form_entry_end, null); ((TextView) endView.findViewById(R.id.description)) .setText(getString(R.string.save_enter_data_description, formController.getFormTitle())); // checkbox for if finished or ready to send final CheckBox instanceComplete = ((CheckBox) endView .findViewById(R.id.mark_finished)); instanceComplete.setChecked(isInstanceComplete(true)); if (!mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_MARK_AS_FINALIZED, true)) { instanceComplete.setVisibility(View.GONE); } // edittext to change the displayed name of the instance final EditText saveAs = (EditText) endView .findViewById(R.id.save_name); // disallow carriage returns in the name InputFilter returnFilter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (Character.getType((source.charAt(i))) == Character.CONTROL) { return ""; } } return null; } }; saveAs.setFilters(new InputFilter[] { returnFilter }); String saveName = formController.getSubmissionMetadata().instanceName; if (saveName == null) { // no meta/instanceName field in the form -- see if we have a // name for this instance from a previous save attempt... if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) { Uri instanceUri = getIntent().getData(); Cursor instance = null; try { instance = getContentResolver().query(instanceUri, null, null, null, null); if (instance.getCount() == 1) { instance.moveToFirst(); saveName = instance .getString(instance .getColumnIndex(InstanceColumns.DISPLAY_NAME)); } } finally { if (instance != null) { instance.close(); } } } if (saveName == null) { // last resort, default to the form title saveName = formController.getFormTitle(); } // present the prompt to allow user to name the form TextView sa = (TextView) endView .findViewById(R.id.save_form_as); sa.setVisibility(View.VISIBLE); saveAs.setText(saveName); saveAs.setEnabled(true); saveAs.setVisibility(View.VISIBLE); } else { // if instanceName is defined in form, this is the name -- no // revisions // display only the name, not the prompt, and disable edits TextView sa = (TextView) endView .findViewById(R.id.save_form_as); sa.setVisibility(View.GONE); saveAs.setText(saveName); saveAs.setEnabled(false); saveAs.setBackgroundColor(Color.WHITE); saveAs.setVisibility(View.VISIBLE); } // override the visibility settings based upon admin preferences if (!mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_SAVE_AS, true)) { saveAs.setVisibility(View.GONE); TextView sa = (TextView) endView .findViewById(R.id.save_form_as); sa.setVisibility(View.GONE); } // Create 'save' button ((Button) endView.findViewById(R.id.save_exit_button)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance() .getActivityLogger() .logInstanceAction( this, "createView.saveAndExit", instanceComplete.isChecked() ? "saveAsComplete" : "saveIncomplete"); // Form is marked as 'saved' here. if (saveAs.getText().length() < 1) { Toast.makeText(FormEntryActivity.this, R.string.save_as_error, Toast.LENGTH_SHORT).show(); } else { saveDataToDisk(EXIT, instanceComplete .isChecked(), saveAs.getText() .toString()); } } }); if (mBackButton.isShown()) { mBackButton.setEnabled(true); } if (mNextButton.isShown()) { mNextButton.setEnabled(false); } return endView; case FormEntryController.EVENT_QUESTION: case FormEntryController.EVENT_GROUP: case FormEntryController.EVENT_REPEAT: ODKView odkv = null; // should only be a group here if the event_group is a field-list try { FormEntryPrompt[] prompts = formController.getQuestionPrompts(); FormEntryCaption[] groups = formController .getGroupsForCurrentIndex(); odkv = new ODKView(this, formController.getQuestionPrompts(), groups, advancingPage); Log.i(t, "created view for group " + (groups.length > 0 ? groups[groups.length - 1] .getLongText() : "[top]") + " " + (prompts.length > 0 ? prompts[0] .getQuestionText() : "[no question]")); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); e.printStackTrace(); // this is badness to avoid a crash. event = formController.stepToNextScreenEvent(); return createView(event, advancingPage); } // Makes a "clear answer" menu pop up on long-click for (QuestionWidget qw : odkv.getWidgets()) { if (!qw.getPrompt().isReadOnly()) { registerForContextMenu(qw); } } if (mBackButton.isShown() && mNextButton.isShown()) { mBackButton.setEnabled(true); mNextButton.setEnabled(true); } return odkv; default: createErrorDialog("Internal error: step to prompt failed", EXIT); Log.e(t, "Attempted to create a view that does not exist."); // this is badness to avoid a crash. event = formController.stepToNextScreenEvent(); return createView(event, advancingPage); } } @Override public boolean dispatchTouchEvent(MotionEvent mv) { boolean handled = mGestureDetector.onTouchEvent(mv); if (!handled) { return super.dispatchTouchEvent(mv); } return handled; // this is always true } /** * Determines what should be displayed on the screen. Possible options are: * a question, an ask repeat dialog, or the submit screen. Also saves * answers to the data model after checking constraints. */ private void showNextView() { FormController formController = Collect.getInstance() .getFormController(); if (formController.currentPromptIsQuestion()) { if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) { // A constraint was violated so a dialog should be showing. mBeenSwiped = false; return; } } View next; int event = formController.stepToNextScreenEvent(); switch (event) { case FormEntryController.EVENT_QUESTION: case FormEntryController.EVENT_GROUP: // create a savepoint if ((++viewCount) % SAVEPOINT_INTERVAL == 0) { SaveToDiskTask.blockingExportTempData(); } next = createView(event, true); showView(next, AnimationType.RIGHT); break; case FormEntryController.EVENT_END_OF_FORM: case FormEntryController.EVENT_REPEAT: next = createView(event, true); showView(next, AnimationType.RIGHT); break; case FormEntryController.EVENT_PROMPT_NEW_REPEAT: createRepeatDialog(); break; case FormEntryController.EVENT_REPEAT_JUNCTURE: Log.i(t, "repeat juncture: " + formController.getFormIndex().getReference()); // skip repeat junctures until we implement them break; default: Log.w(t, "JavaRosa added a new EVENT type and didn't tell us... shame on them."); break; } } /** * Determines what should be displayed between a question, or the start * screen and displays the appropriate view. Also saves answers to the data * model without checking constraints. */ private void showPreviousView() { FormController formController = Collect.getInstance() .getFormController(); // The answer is saved on a back swipe, but question constraints are // ignored. if (formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } if (formController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) { int event = formController.stepToPreviousScreenEvent(); if (event == FormEntryController.EVENT_BEGINNING_OF_FORM || event == FormEntryController.EVENT_GROUP || event == FormEntryController.EVENT_QUESTION) { // create savepoint if ((++viewCount) % SAVEPOINT_INTERVAL == 0) { SaveToDiskTask.blockingExportTempData(); } } View next = createView(event, false); showView(next, AnimationType.LEFT); } else { mBeenSwiped = false; } } /** * Displays the View specified by the parameter 'next', animating both the * current view and next appropriately given the AnimationType. Also updates * the progress bar. */ public void showView(View next, AnimationType from) { // disable notifications... if (mInAnimation != null) { mInAnimation.setAnimationListener(null); } if (mOutAnimation != null) { mOutAnimation.setAnimationListener(null); } // logging of the view being shown is already done, as this was handled // by createView() switch (from) { case RIGHT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out); break; case LEFT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out); break; case FADE: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out); break; } // complete setup for animations... mInAnimation.setAnimationListener(this); mOutAnimation.setAnimationListener(this); // drop keyboard before transition... if (mCurrentView != null) { InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(), 0); } RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); // adjust which view is in the layout container... mStaleView = mCurrentView; mCurrentView = next; mQuestionHolder.addView(mCurrentView, lp); mAnimationCompletionSet = 0; if (mStaleView != null) { // start OutAnimation for transition... mStaleView.startAnimation(mOutAnimation); // and remove the old view (MUST occur after start of animation!!!) mQuestionHolder.removeView(mStaleView); } else { mAnimationCompletionSet = 2; } // start InAnimation for transition... mCurrentView.startAnimation(mInAnimation); String logString = ""; switch (from) { case RIGHT: logString = "next"; break; case LEFT: logString = "previous"; break; case FADE: logString = "refresh"; break; } Collect.getInstance().getActivityLogger() .logInstanceAction(this, "showView", logString); } // Hopefully someday we can use managed dialogs when the bugs are fixed /* * Ideally, we'd like to use Android to manage dialogs with onCreateDialog() * and onPrepareDialog(), but dialogs with dynamic content are broken in 1.5 * (cupcake). We do use managed dialogs for our static loading * ProgressDialog. The main issue we noticed and are waiting to see fixed * is: onPrepareDialog() is not called after a screen orientation change. * http://code.google.com/p/android/issues/detail?id=1639 */ // /** * Creates and displays a dialog displaying the violated constraint. */ private void createConstraintToast(FormIndex index, int saveStatus) { FormController formController = Collect.getInstance() .getFormController(); String constraintText = formController.getQuestionPrompt(index) .getConstraintText(); switch (saveStatus) { case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createConstraintToast.ANSWER_CONSTRAINT_VIOLATED", "show", index); if (constraintText == null) { constraintText = formController.getQuestionPrompt(index) .getSpecialFormQuestionText("constraintMsg"); if (constraintText == null) { constraintText = getString(R.string.invalid_answer_error); } } break; case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createConstraintToast.ANSWER_REQUIRED_BUT_EMPTY", "show", index); constraintText = formController.getQuestionPrompt(index) .getSpecialFormQuestionText("requiredMsg"); if (constraintText == null) { constraintText = getString(R.string.required_answer_error); } break; } showCustomToast(constraintText, Toast.LENGTH_SHORT); } /** * Creates a toast with the specified message. * * @param message */ private void showCustomToast(String message, int duration) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.toast_view, null); // set the text in the view TextView tv = (TextView) view.findViewById(R.id.message); tv.setText(message); Toast t = new Toast(this); t.setView(view); t.setDuration(duration); t.setGravity(Gravity.CENTER, 0, 0); t.show(); } /** * Creates and displays a dialog asking the user if they'd like to create a * repeat of the current group. */ private void createRepeatDialog() { FormController formController = Collect.getInstance() .getFormController(); Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createRepeatDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); DialogInterface.OnClickListener repeatListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { FormController formController = Collect.getInstance() .getFormController(); switch (i) { case DialogInterface.BUTTON1: // yes, repeat Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createRepeatDialog", "addRepeat"); try { formController.newRepeat(); } catch (XPathTypeMismatchException e) { FormEntryActivity.this.createErrorDialog( e.getMessage(), EXIT); return; } if (!formController.indexIsInFieldList()) { // we are at a REPEAT event that does not have a // field-list appearance // step to the next visible field... // which could be the start of a new repeat group... showNextView(); } else { // we are at a REPEAT event that has a field-list // appearance // just display this REPEAT event's group. refreshCurrentView(); } break; case DialogInterface.BUTTON2: // no, no repeat Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createRepeatDialog", "showNext"); showNextView(); break; } } }; if (formController.getLastRepeatCount() > 0) { mAlertDialog.setTitle(getString(R.string.leaving_repeat_ask)); mAlertDialog.setMessage(getString(R.string.add_another_repeat, formController.getLastGroupText())); mAlertDialog.setButton(getString(R.string.add_another), repeatListener); mAlertDialog.setButton2(getString(R.string.leave_repeat_yes), repeatListener); } else { mAlertDialog.setTitle(getString(R.string.entering_repeat_ask)); mAlertDialog.setMessage(getString(R.string.add_repeat, formController.getLastGroupText())); mAlertDialog.setButton(getString(R.string.entering_repeat), repeatListener); mAlertDialog.setButton2(getString(R.string.add_repeat_no), repeatListener); } mAlertDialog.setCancelable(false); mBeenSwiped = false; mAlertDialog.show(); } /** * Creates and displays dialog with the given errorMsg. */ private void createErrorDialog(String errorMsg, final boolean shouldExit) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createErrorDialog", "show." + Boolean.toString(shouldExit)); mErrorMessage = errorMsg; mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setTitle(getString(R.string.error_occured)); mAlertDialog.setMessage(errorMsg); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON1: Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createErrorDialog", "OK"); if (shouldExit) { finish(); } break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), errorListener); mBeenSwiped = false; mAlertDialog.show(); } /** * Creates a confirm/cancel dialog for deleting repeats. */ private void createDeleteRepeatConfirmDialog() { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createDeleteRepeatConfirmDialog", "show"); FormController formController = Collect.getInstance() .getFormController(); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); String name = formController.getLastRepeatedGroupName(); int repeatcount = formController.getLastRepeatedGroupRepeatCount(); if (repeatcount != -1) { name += " (" + (repeatcount + 1) + ")"; } mAlertDialog.setTitle(getString(R.string.delete_repeat_ask)); mAlertDialog .setMessage(getString(R.string.delete_repeat_confirm, name)); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { FormController formController = Collect.getInstance() .getFormController(); switch (i) { case DialogInterface.BUTTON1: // yes Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createDeleteRepeatConfirmDialog", "OK"); formController.deleteRepeat(); showPreviousView(); break; case DialogInterface.BUTTON2: // no Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createDeleteRepeatConfirmDialog", "cancel"); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.discard_group), quitListener); mAlertDialog.setButton2(getString(R.string.delete_repeat_no), quitListener); mAlertDialog.show(); } /** * Saves data and writes it to disk. If exit is set, program will exit after * save completes. Complete indicates whether the user has marked the * isntancs as complete. If updatedSaveName is non-null, the instances * content provider is updated with the new name */ private boolean saveDataToDisk(boolean exit, boolean complete, String updatedSaveName) { // save current answer if (!saveAnswersForCurrentScreen(complete)) { Toast.makeText(this, getString(R.string.data_saved_error), Toast.LENGTH_SHORT).show(); return false; } mSaveToDiskTask = new SaveToDiskTask(getIntent().getData(), exit, complete, updatedSaveName); mSaveToDiskTask.setFormSavedListener(this); showDialog(SAVING_DIALOG); // show dialog before we execute... mSaveToDiskTask.execute(); return true; } /** * Create a dialog with options to save and exit, save, or quit without * saving */ private void createQuitDialog() { FormController formController = Collect.getInstance() .getFormController(); String[] items; if (mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_SAVE_MID, true)) { String[] two = { getString(R.string.keep_changes), getString(R.string.do_not_save) }; items = two; } else { String[] one = { getString(R.string.do_not_save) }; items = one; } Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createQuitDialog", "show"); mAlertDialog = new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle( getString(R.string.quit_application, formController.getFormTitle())) .setNeutralButton(getString(R.string.do_not_exit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "cancel"); dialog.cancel(); } }) .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: // save and exit // this is slightly complicated because if the // option is disabled in // the admin menu, then case 0 actually becomes // 'discard and exit' // whereas if it's enabled it's 'save and exit' if (mAdminPreferences .getBoolean( AdminPreferencesActivity.KEY_SAVE_MID, true)) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "saveAndExit"); saveDataToDisk(EXIT, isInstanceComplete(false), null); } else { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "discardAndExit"); removeTempInstance(); finishReturnInstance(); } break; case 1: // discard changes and exit Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "discardAndExit"); removeTempInstance(); finishReturnInstance(); break; case 2:// do nothing Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "cancel"); break; } } }).create(); mAlertDialog.show(); } /** * this method cleans up unneeded files when the user selects 'discard and * exit' */ private void removeTempInstance() { FormController formController = Collect.getInstance() .getFormController(); // attempt to remove any scratch file File temp = SaveToDiskTask.savepointFile(formController .getInstancePath()); if (temp.exists()) { temp.delete(); } String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { formController.getInstancePath() .getAbsolutePath() }; boolean erase = false; { Cursor c = null; try { c = getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); erase = (c.getCount() < 1); } finally { if (c != null) { c.close(); } } } // if it's not already saved, erase everything if (erase) { // delete media first String instanceFolder = formController.getInstancePath() .getParent(); Log.i(t, "attempting to delete: " + instanceFolder); int images = MediaUtils .deleteImagesInFolderFromMediaProvider(formController .getInstancePath().getParentFile()); int audio = MediaUtils .deleteAudioInFolderFromMediaProvider(formController .getInstancePath().getParentFile()); int video = MediaUtils .deleteVideoInFolderFromMediaProvider(formController .getInstancePath().getParentFile()); Log.i(t, "removed from content providers: " + images + " image files, " + audio + " audio files," + " and " + video + " video files."); File f = new File(instanceFolder); if (f.exists() && f.isDirectory()) { for (File del : f.listFiles()) { Log.i(t, "deleting file: " + del.getAbsolutePath()); del.delete(); } f.delete(); } } } /** * Confirm clear answer dialog */ private void createClearDialog(final QuestionWidget qw) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createClearDialog", "show", qw.getPrompt().getIndex()); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setTitle(getString(R.string.clear_answer_ask)); String question = qw.getPrompt().getLongText(); if (question == null) { question = ""; } if (question.length() > 50) { question = question.substring(0, 50) + "..."; } mAlertDialog.setMessage(getString(R.string.clearanswer_confirm, question)); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON1: // yes Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createClearDialog", "clearAnswer", qw.getPrompt().getIndex()); clearAnswer(qw); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case DialogInterface.BUTTON2: // no Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createClearDialog", "cancel", qw.getPrompt().getIndex()); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog .setButton(getString(R.string.discard_answer), quitListener); mAlertDialog.setButton2(getString(R.string.clear_answer_no), quitListener); mAlertDialog.show(); } /** * Creates and displays a dialog allowing the user to set the language for * the form. */ private void createLanguageDialog() { Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createLanguageDialog", "show"); FormController formController = Collect.getInstance() .getFormController(); final String[] languages = formController.getLanguages(); int selected = -1; if (languages != null) { String language = formController.getLanguage(); for (int i = 0; i < languages.length; i++) { if (language.equals(languages[i])) { selected = i; } } } mAlertDialog = new AlertDialog.Builder(this) .setSingleChoiceItems(languages, selected, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { FormController formController = Collect .getInstance().getFormController(); // Update the language in the content provider // when selecting a new // language ContentValues values = new ContentValues(); values.put(FormsColumns.LANGUAGE, languages[whichButton]); String selection = FormsColumns.FORM_FILE_PATH + "=?"; String selectArgs[] = { mFormPath }; int updated = getContentResolver().update( FormsColumns.CONTENT_URI, values, selection, selectArgs); Log.i(t, "Updated language to: " + languages[whichButton] + " in " + updated + " rows"); Collect.getInstance() .getActivityLogger() .logInstanceAction( this, "createLanguageDialog", "changeLanguage." + languages[whichButton]); formController .setLanguage(languages[whichButton]); dialog.dismiss(); if (formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } refreshCurrentView(); } }) .setTitle(getString(R.string.change_language)) .setNegativeButton(getString(R.string.do_not_change), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createLanguageDialog", "cancel"); } }).create(); mAlertDialog.show(); } /** * We use Android's dialog management for loading/saving progress dialogs */ @Override protected Dialog onCreateDialog(int id) { switch (id) { case PROGRESS_DIALOG: Log.e(t, "Creating PROGRESS_DIALOG"); Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.PROGRESS_DIALOG", "show"); mProgressDialog = new ProgressDialog(this); DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.PROGRESS_DIALOG", "cancel"); dialog.dismiss(); mFormLoaderTask.setFormLoaderListener(null); FormLoaderTask t = mFormLoaderTask; mFormLoaderTask = null; t.cancel(true); t.destroy(); finish(); } }; mProgressDialog.setIcon(android.R.drawable.ic_dialog_info); mProgressDialog.setTitle(getString(R.string.loading_form)); mProgressDialog.setMessage(getString(R.string.please_wait)); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.setButton(getString(R.string.cancel_loading_form), loadingButtonListener); return mProgressDialog; case SAVING_DIALOG: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.SAVING_DIALOG", "show"); mProgressDialog = new ProgressDialog(this); DialogInterface.OnClickListener savingButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.SAVING_DIALOG", "cancel"); dialog.dismiss(); mSaveToDiskTask.setFormSavedListener(null); SaveToDiskTask t = mSaveToDiskTask; mSaveToDiskTask = null; t.cancel(true); } }; mProgressDialog.setIcon(android.R.drawable.ic_dialog_info); mProgressDialog.setTitle(getString(R.string.saving_form)); mProgressDialog.setMessage(getString(R.string.please_wait)); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.setButton(getString(R.string.cancel), savingButtonListener); mProgressDialog.setButton(getString(R.string.cancel_saving_form), savingButtonListener); return mProgressDialog; } return null; } /** * Dismiss any showing dialogs that we manually manage. */ private void dismissDialogs() { Log.e(t, "Dismiss dialogs"); if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } } @Override protected void onPause() { FormController formController = Collect.getInstance() .getFormController(); dismissDialogs(); // make sure we're not already saving to disk. if we are, currentPrompt // is getting constantly updated if (mSaveToDiskTask == null || mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { if (mCurrentView != null && formController != null && formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } } super.onPause(); } @Override protected void onResume() { super.onResume(); FormController formController = Collect.getInstance() .getFormController(); Collect.getInstance().getActivityLogger().open(); if (mFormLoaderTask != null) { mFormLoaderTask.setFormLoaderListener(this); if (formController == null && mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { FormController fec = mFormLoaderTask.getFormController(); if (fec != null) { loadingComplete(mFormLoaderTask); } else { dismissDialog(PROGRESS_DIALOG); FormLoaderTask t = mFormLoaderTask; mFormLoaderTask = null; t.cancel(true); t.destroy(); // there is no formController -- fire MainMenu activity? startActivity(new Intent(this, MainMenuActivity.class)); } } } else { refreshCurrentView(); } if (mSaveToDiskTask != null) { mSaveToDiskTask.setFormSavedListener(this); } if (mErrorMessage != null && (mAlertDialog != null && !mAlertDialog.isShowing())) { createErrorDialog(mErrorMessage, EXIT); return; } // only check the buttons if it's enabled in preferences SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); String navigation = sharedPreferences.getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.KEY_NAVIGATION); Boolean showButtons = false; if (navigation.contains(PreferencesActivity.NAVIGATION_BUTTONS)) { showButtons = true; } if (showButtons) { mBackButton.setVisibility(View.VISIBLE); mNextButton.setVisibility(View.VISIBLE); } else { mBackButton.setVisibility(View.GONE); mNextButton.setVisibility(View.GONE); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_BACK", "quit"); createQuitDialog(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (event.isAltPressed() && !mBeenSwiped) { mBeenSwiped = true; Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_RIGHT", "showNext"); showNextView(); return true; } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (event.isAltPressed() && !mBeenSwiped) { mBeenSwiped = true; Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_LEFT", "showPrevious"); showPreviousView(); return true; } break; } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { if (mFormLoaderTask != null) { mFormLoaderTask.setFormLoaderListener(null); // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. // but only if it's done, otherwise the thread never returns if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { FormLoaderTask t = mFormLoaderTask; mFormLoaderTask = null; t.cancel(true); t.destroy(); } } if (mSaveToDiskTask != null) { mSaveToDiskTask.setFormSavedListener(null); // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { mSaveToDiskTask.cancel(true); mSaveToDiskTask = null; } } super.onDestroy(); } private int mAnimationCompletionSet = 0; private void afterAllAnimations() { Log.i(t, "afterAllAnimations"); if (mStaleView != null) { if (mStaleView instanceof ODKView) { // http://code.google.com/p/android/issues/detail?id=8488 ((ODKView) mStaleView).recycleDrawables(); } mStaleView = null; } if (mCurrentView instanceof ODKView) { ((ODKView) mCurrentView).setFocus(this); } mBeenSwiped = false; } @Override public void onAnimationEnd(Animation animation) { Log.i(t, "onAnimationEnd " + ((animation == mInAnimation) ? "in" : ((animation == mOutAnimation) ? "out" : "other"))); if (mInAnimation == animation) { mAnimationCompletionSet |= 1; } else if (mOutAnimation == animation) { mAnimationCompletionSet |= 2; } else { Log.e(t, "Unexpected animation"); } if (mAnimationCompletionSet == 3) { this.afterAllAnimations(); } } @Override public void onAnimationRepeat(Animation animation) { // Added by AnimationListener interface. Log.i(t, "onAnimationRepeat " + ((animation == mInAnimation) ? "in" : ((animation == mOutAnimation) ? "out" : "other"))); } @Override public void onAnimationStart(Animation animation) { // Added by AnimationListener interface. Log.i(t, "onAnimationStart " + ((animation == mInAnimation) ? "in" : ((animation == mOutAnimation) ? "out" : "other"))); } /** * loadingComplete() is called by FormLoaderTask once it has finished * loading a form. */ @Override public void loadingComplete(FormLoaderTask task) { dismissDialog(PROGRESS_DIALOG); FormController formController = task.getFormController(); boolean pendingActivityResult = task.hasPendingActivityResult(); boolean hasUsedSavepoint = task.hasUsedSavepoint(); int requestCode = task.getRequestCode(); // these are bogus if // pendingActivityResult is // false int resultCode = task.getResultCode(); Intent intent = task.getIntent(); mFormLoaderTask.setFormLoaderListener(null); FormLoaderTask t = mFormLoaderTask; mFormLoaderTask = null; t.cancel(true); t.destroy(); Collect.getInstance().setFormController(formController); // Set the language if one has already been set in the past String[] languageTest = formController.getLanguages(); if (languageTest != null) { String defaultLanguage = formController.getLanguage(); String newLanguage = ""; String selection = FormsColumns.FORM_FILE_PATH + "=?"; String selectArgs[] = { mFormPath }; Cursor c = null; try { c = getContentResolver().query(FormsColumns.CONTENT_URI, null, selection, selectArgs, null); if (c.getCount() == 1) { c.moveToFirst(); newLanguage = c.getString(c .getColumnIndex(FormsColumns.LANGUAGE)); } } finally { if (c != null) { c.close(); } } // if somehow we end up with a bad language, set it to the default try { formController.setLanguage(newLanguage); } catch (Exception e) { formController.setLanguage(defaultLanguage); } } if (pendingActivityResult) { // set the current view to whatever group we were at... refreshCurrentView(); // process the pending activity request... onActivityResult(requestCode, resultCode, intent); return; } // it can be a normal flow for a pending activity result to restore from // a savepoint // (the call flow handled by the above if statement). For all other use // cases, the // user should be notified, as it means they wandered off doing other // things then // returned to ODK Collect and chose Edit Saved Form, but that the // savepoint for that // form is newer than the last saved version of their form data. if (hasUsedSavepoint) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(FormEntryActivity.this, getString(R.string.savepoint_used), Toast.LENGTH_LONG).show(); } }); } // Set saved answer path if (formController.getInstancePath() == null) { // Create new answer folder. String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.ENGLISH).format(Calendar.getInstance().getTime()); String file = mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.')); String path = Collect.INSTANCES_PATH + File.separator + file + "_" + time; if (FileUtils.createFolder(path)) { formController.setInstancePath(new File(path + File.separator + file + "_" + time + ".xml")); } } else { Intent reqIntent = getIntent(); boolean showFirst = reqIntent.getBooleanExtra("start", false); if (!showFirst) { // we've just loaded a saved form, so start in the hierarchy // view Intent i = new Intent(this, FormHierarchyActivity.class); startActivity(i); return; // so we don't show the intro screen before jumping to // the hierarchy } } refreshCurrentView(); } /** * called by the FormLoaderTask if something goes wrong. */ @Override public void loadingError(String errorMsg) { dismissDialog(PROGRESS_DIALOG); if (errorMsg != null) { createErrorDialog(errorMsg, EXIT); } else { createErrorDialog(getString(R.string.parse_error), EXIT); } } /** * Called by SavetoDiskTask if everything saves correctly. */ @Override public void savingComplete(int saveStatus) { dismissDialog(SAVING_DIALOG); switch (saveStatus) { case SaveToDiskTask.SAVED: Toast.makeText(this, getString(R.string.data_saved_ok), Toast.LENGTH_SHORT).show(); sendSavedBroadcast(); break; case SaveToDiskTask.SAVED_AND_EXIT: Toast.makeText(this, getString(R.string.data_saved_ok), Toast.LENGTH_SHORT).show(); sendSavedBroadcast(); finishReturnInstance(); break; case SaveToDiskTask.SAVE_ERROR: Toast.makeText(this, getString(R.string.data_saved_error), Toast.LENGTH_LONG).show(); break; case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: refreshCurrentView(); // an answer constraint was violated, so do a 'swipe' to the next // question to display the proper toast(s) next(); break; } } /** * Attempts to save an answer to the specified index. * * @param answer * @param index * @param evaluateConstraints * @return status as determined in FormEntryController */ public int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) { FormController formController = Collect.getInstance() .getFormController(); if (evaluateConstraints) { return formController.answerQuestion(index, answer); } else { formController.saveAnswer(index, answer); return FormEntryController.ANSWER_OK; } } /** * Checks the database to determine if the current instance being edited has * already been 'marked completed'. A form can be 'unmarked' complete and * then resaved. * * @return true if form has been marked completed, false otherwise. */ private boolean isInstanceComplete(boolean end) { FormController formController = Collect.getInstance() .getFormController(); // default to false if we're mid form boolean complete = false; // if we're at the end of the form, then check the preferences if (end) { // First get the value from the preferences SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); complete = sharedPreferences.getBoolean( PreferencesActivity.KEY_COMPLETED_DEFAULT, true); } // Then see if we've already marked this form as complete before String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { formController.getInstancePath() .getAbsolutePath() }; Cursor c = null; try { c = getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c != null && c.getCount() > 0) { c.moveToFirst(); String status = c.getString(c .getColumnIndex(InstanceColumns.STATUS)); if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) { complete = true; } } } finally { if (c != null) { c.close(); } } return complete; } public void next() { if (!mBeenSwiped) { mBeenSwiped = true; showNextView(); } } /** * Returns the instance that was just filled out to the calling activity, if * requested. */ private void finishReturnInstance() { FormController formController = Collect.getInstance() .getFormController(); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) { // caller is waiting on a picked form String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { formController.getInstancePath() .getAbsolutePath() }; Cursor c = null; try { c = getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c.getCount() > 0) { // should only be one... c.moveToFirst(); String id = c.getString(c .getColumnIndex(InstanceColumns._ID)); Uri instance = Uri.withAppendedPath( InstanceColumns.CONTENT_URI, id); setResult(RESULT_OK, new Intent().setData(instance)); } } finally { if (c != null) { c.close(); } } } finish(); } @Override public boolean onDown(MotionEvent e) { return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // only check the swipe if it's enabled in preferences SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); String navigation = sharedPreferences.getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.NAVIGATION_SWIPE); Boolean doSwipe = false; if (navigation.contains(PreferencesActivity.NAVIGATION_SWIPE)) { doSwipe = true; } if (doSwipe) { // Looks for user swipes. If the user has swiped, move to the // appropriate screen. // for all screens a swipe is left/right of at least // .25" and up/down of less than .25" // OR left/right of > .5" DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int xPixelLimit = (int) (dm.xdpi * .25); int yPixelLimit = (int) (dm.ydpi * .25); if (mCurrentView instanceof ODKView) { if (((ODKView) mCurrentView).suppressFlingGesture(e1, e2, velocityX, velocityY)) { return false; } } if (mBeenSwiped) { return false; } if ((Math.abs(e1.getX() - e2.getX()) > xPixelLimit && Math.abs(e1 .getY() - e2.getY()) < yPixelLimit) || Math.abs(e1.getX() - e2.getX()) > xPixelLimit * 2) { mBeenSwiped = true; if (velocityX > 0) { if (e1.getX() > e2.getX()) { Log.e(t, "showNextView VelocityX is bogus! " + e1.getX() + " > " + e2.getX()); Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onFling", "showNext"); showNextView(); } else { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onFling", "showPrevious"); showPreviousView(); } } else { if (e1.getX() < e2.getX()) { Log.e(t, "showPreviousView VelocityX is bogus! " + e1.getX() + " < " + e2.getX()); Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onFling", "showPrevious"); showPreviousView(); } else { Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onFling", "showNext"); showNextView(); } } return true; } } return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // The onFling() captures the 'up' event so our view thinks it gets long // pressed. // We don't wnat that, so cancel it. mCurrentView.cancelLongPress(); return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public void advance() { next(); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private void sendSavedBroadcast() { Intent i = new Intent(); i.setAction("org.odk.collect.android.FormSaved"); this.sendBroadcast(i); } }
Java
/* * Copyright (C) 2009 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.odk.collect.android.activities; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import android.app.TabActivity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; /** * A host activity for {@link InstanceChooserList}. * * @author Yaw Anokwa (yanokwa@gmail.com) */ public class InstanceChooserTabs extends TabActivity { private static final String SAVED_TAB = "saved_tab"; private static final String COMPLETED_TAB = "completed_tab"; // count for tab menu bar private int mSavedCount; private int mCompletedCount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getString(R.string.app_name) + " > " + getString(R.string.review_data)); // create tab host and tweak color final TabHost tabHost = getTabHost(); tabHost.setBackgroundColor(Color.WHITE); tabHost.getTabWidget().setBackgroundColor(Color.BLACK); // create intent for saved tab Intent saved = new Intent(this, InstanceChooserList.class); tabHost.addTab(tabHost.newTabSpec(SAVED_TAB) .setIndicator(getString(R.string.saved_data, mSavedCount)).setContent(saved)); // create intent for completed tab Intent completed = new Intent(this, InstanceChooserList.class); tabHost.addTab(tabHost.newTabSpec(COMPLETED_TAB) .setIndicator(getString(R.string.completed_data, mCompletedCount)) .setContent(completed)); // hack to set font size and padding in tab headers // arrived at these paths by using hierarchy viewer LinearLayout ll = (LinearLayout) tabHost.getChildAt(0); TabWidget tw = (TabWidget) ll.getChildAt(0); int fontsize = Collect.getQuestionFontsize(); RelativeLayout rls = (RelativeLayout) tw.getChildAt(0); TextView tvs = (TextView) rls.getChildAt(1); tvs.setTextSize(fontsize); tvs.setPadding(0, 0, 0, 6); RelativeLayout rlc = (RelativeLayout) tw.getChildAt(1); TextView tvc = (TextView) rlc.getChildAt(1); tvc.setTextSize(fontsize); tvc.setPadding(0, 0, 0, 6); if (mSavedCount >= mCompletedCount) { getTabHost().setCurrentTabByTag(SAVED_TAB); } else { getTabHost().setCurrentTabByTag(COMPLETED_TAB); } } }
Java
/* * Copyright (C) 2009 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.odk.collect.android.activities; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import android.app.TabActivity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; /** * An example of tab content that launches an activity via * {@link android.widget.TabHost.TabSpec#setContent(android.content.Intent)} */ public class FileManagerTabs extends TabActivity { private TextView mTVFF; private TextView mTVDF; private static final String FORMS_TAB = "forms_tab"; private static final String DATA_TAB = "data_tab"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getString(R.string.app_name) + " > " + getString(R.string.manage_files)); final TabHost tabHost = getTabHost(); tabHost.setBackgroundColor(Color.WHITE); tabHost.getTabWidget().setBackgroundColor(Color.BLACK); Intent remote = new Intent(this, DataManagerList.class); tabHost.addTab(tabHost.newTabSpec(DATA_TAB).setIndicator(getString(R.string.data)) .setContent(remote)); Intent local = new Intent(this, FormManagerList.class); tabHost.addTab(tabHost.newTabSpec(FORMS_TAB).setIndicator(getString(R.string.forms)) .setContent(local)); // hack to set font size LinearLayout ll = (LinearLayout) tabHost.getChildAt(0); TabWidget tw = (TabWidget) ll.getChildAt(0); int fontsize = Collect.getQuestionFontsize(); RelativeLayout rllf = (RelativeLayout) tw.getChildAt(0); mTVFF = (TextView) rllf.getChildAt(1); mTVFF.setTextSize(fontsize); mTVFF.setPadding(0, 0, 0, 6); RelativeLayout rlrf = (RelativeLayout) tw.getChildAt(1); mTVDF = (TextView) rlrf.getChildAt(1); mTVDF.setTextSize(fontsize); mTVDF.setPadding(0, 0, 0, 6); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } }
Java
/* * Copyright (C) 2009 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.odk.collect.android.activities; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.provider.InstanceProviderAPI; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import android.app.AlertDialog; import android.app.ListActivity; import android.content.ContentUris; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; /** * Responsible for displaying all the valid instances in the instance directory. * * @author Yaw Anokwa (yanokwa@gmail.com) * @author Carl Hartung (carlhartung@gmail.com) */ public class InstanceChooserList extends ListActivity { private static final boolean EXIT = true; private static final boolean DO_NOT_EXIT = false; private AlertDialog mAlertDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must be at the beginning of any activity that can be called from an external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } setContentView(R.layout.chooser_list_layout); setTitle(getString(R.string.app_name) + " > " + getString(R.string.review_data)); TextView tv = (TextView) findViewById(R.id.status_text); tv.setVisibility(View.GONE); String selection = InstanceColumns.STATUS + " != ?"; String[] selectionArgs = {InstanceProviderAPI.STATUS_SUBMITTED}; String sortOrder = InstanceColumns.STATUS + " DESC, " + InstanceColumns.DISPLAY_NAME + " ASC"; Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, sortOrder); String[] data = new String[] { InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_SUBTEXT }; int[] view = new int[] { R.id.text1, R.id.text2 }; // render total instance view SimpleCursorAdapter instances = new SimpleCursorAdapter(this, R.layout.two_item, c, data, view); setListAdapter(instances); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); } /** * Stores the path of selected instance in the parent class and finishes. */ @Override protected void onListItemClick(ListView listView, View view, int position, long id) { Cursor c = (Cursor) getListAdapter().getItem(position); startManagingCursor(c); Uri instanceUri = ContentUris.withAppendedId(InstanceColumns.CONTENT_URI, c.getLong(c.getColumnIndex(InstanceColumns._ID))); Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", instanceUri.toString()); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action)) { // caller is waiting on a picked form setResult(RESULT_OK, new Intent().setData(instanceUri)); } else { // the form can be edited if it is incomplete or if, when it was // marked as complete, it was determined that it could be edited // later. String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS)); String strCanEditWhenComplete = c.getString(c.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE)); boolean canEdit = status.equals(InstanceProviderAPI.STATUS_INCOMPLETE) || Boolean.parseBoolean(strCanEditWhenComplete); if (!canEdit) { createErrorDialog(getString(R.string.cannot_edit_completed_form), DO_NOT_EXIT); return; } // caller wants to view/edit a form, so launch formentryactivity startActivity(new Intent(Intent.ACTION_EDIT, instanceUri)); } finish(); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private void createErrorDialog(String errorMsg, final boolean shouldExit) { Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setMessage(errorMsg); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON1: Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", shouldExit ? "exitApplication" : "OK"); if (shouldExit) { finish(); } break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), errorListener); mAlertDialog.show(); } }
Java
/* * Copyright (C) 2009 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.odk.collect.android.activities; import org.javarosa.core.model.FormIndex; import org.javarosa.form.api.FormEntryCaption; import org.javarosa.form.api.FormEntryController; import org.javarosa.form.api.FormEntryPrompt; import org.odk.collect.android.R; import org.odk.collect.android.adapters.HierarchyListAdapter; import org.odk.collect.android.application.Collect; import org.odk.collect.android.logic.FormController; import org.odk.collect.android.logic.HierarchyElement; import android.app.ListActivity; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class FormHierarchyActivity extends ListActivity { private static final String t = "FormHierarchyActivity"; private static final int CHILD = 1; private static final int EXPANDED = 2; private static final int COLLAPSED = 3; private static final int QUESTION = 4; private static final String mIndent = " "; private Button jumpPreviousButton; List<HierarchyElement> formList; TextView mPath; FormIndex mStartIndex; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.hierarchy_layout); FormController formController = Collect.getInstance().getFormController(); // We use a static FormEntryController to make jumping faster. mStartIndex = formController.getFormIndex(); setTitle(getString(R.string.app_name) + " > " + formController.getFormTitle()); mPath = (TextView) findViewById(R.id.pathtext); jumpPreviousButton = (Button) findViewById(R.id.jumpPreviousButton); jumpPreviousButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "goUpLevelButton", "click"); goUpLevel(); } }); Button jumpBeginningButton = (Button) findViewById(R.id.jumpBeginningButton); jumpBeginningButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "jumpToBeginning", "click"); Collect.getInstance().getFormController().jumpToIndex(FormIndex .createBeginningOfFormIndex()); setResult(RESULT_OK); finish(); } }); Button jumpEndButton = (Button) findViewById(R.id.jumpEndButton); jumpEndButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "jumpToEnd", "click"); Collect.getInstance().getFormController().jumpToIndex(FormIndex.createEndOfFormIndex()); setResult(RESULT_OK); finish(); } }); // kinda slow, but works. // this scrolls to the last question the user was looking at getListView().post(new Runnable() { @Override public void run() { int position = 0; for (int i = 0; i < getListAdapter().getCount(); i++) { HierarchyElement he = (HierarchyElement) getListAdapter().getItem(i); if (mStartIndex.equals(he.getFormIndex())) { position = i; break; } } getListView().setSelection(position); } }); refreshView(); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private void goUpLevel() { Collect.getInstance().getFormController().stepToOuterScreenEvent(); refreshView(); } private String getCurrentPath() { FormController formController = Collect.getInstance().getFormController(); FormIndex index = formController.getFormIndex(); // move to enclosing group... index = formController.stepIndexOut(index); String path = ""; while (index != null) { path = formController.getCaptionPrompt(index).getLongText() + " (" + (formController.getCaptionPrompt(index) .getMultiplicity() + 1) + ") > " + path; index = formController.stepIndexOut(index); } // return path? return path.substring(0, path.length() - 2); } public void refreshView() { FormController formController = Collect.getInstance().getFormController(); // Record the current index so we can return to the same place if the user hits 'back'. FormIndex currentIndex = formController.getFormIndex(); // If we're not at the first level, we're inside a repeated group so we want to only display // everything enclosed within that group. String enclosingGroupRef = ""; formList = new ArrayList<HierarchyElement>(); // If we're currently at a repeat node, record the name of the node and step to the next // node to display. if (formController.getEvent() == FormEntryController.EVENT_REPEAT) { enclosingGroupRef = formController.getFormIndex().getReference().toString(false); formController.stepToNextEvent(FormController.STEP_INTO_GROUP); } else { FormIndex startTest = formController.stepIndexOut(currentIndex); // If we have a 'group' tag, we want to step back until we hit a repeat or the // beginning. while (startTest != null && formController.getEvent(startTest) == FormEntryController.EVENT_GROUP) { startTest = formController.stepIndexOut(startTest); } if (startTest == null) { // check to see if the question is at the first level of the hierarchy. If it is, // display the root level from the beginning. formController.jumpToIndex(FormIndex .createBeginningOfFormIndex()); } else { // otherwise we're at a repeated group formController.jumpToIndex(startTest); } // now test again for repeat. This should be true at this point or we're at the // beginning if (formController.getEvent() == FormEntryController.EVENT_REPEAT) { enclosingGroupRef = formController.getFormIndex().getReference().toString(false); formController.stepToNextEvent(FormController.STEP_INTO_GROUP); } } int event = formController.getEvent(); if (event == FormEntryController.EVENT_BEGINNING_OF_FORM) { // The beginning of form has no valid prompt to display. formController.stepToNextEvent(FormController.STEP_INTO_GROUP); mPath.setVisibility(View.GONE); jumpPreviousButton.setEnabled(false); } else { mPath.setVisibility(View.VISIBLE); mPath.setText(getCurrentPath()); jumpPreviousButton.setEnabled(true); } // Refresh the current event in case we did step forward. event = formController.getEvent(); // There may be repeating Groups at this level of the hierarchy, we use this variable to // keep track of them. String repeatedGroupRef = ""; event_search: while (event != FormEntryController.EVENT_END_OF_FORM) { switch (event) { case FormEntryController.EVENT_QUESTION: if (!repeatedGroupRef.equalsIgnoreCase("")) { // We're in a repeating group, so skip this question and move to the next // index. event = formController.stepToNextEvent(FormController.STEP_INTO_GROUP); continue; } FormEntryPrompt fp = formController.getQuestionPrompt(); String label = fp.getLongText(); if ( !fp.isReadOnly() || (label != null && label.length() > 0) ) { // show the question if it is an editable field. // or if it is read-only and the label is not blank. formList.add(new HierarchyElement(fp.getLongText(), fp.getAnswerText(), null, Color.WHITE, QUESTION, fp.getIndex())); } break; case FormEntryController.EVENT_GROUP: // ignore group events break; case FormEntryController.EVENT_PROMPT_NEW_REPEAT: if (enclosingGroupRef.compareTo(formController .getFormIndex().getReference().toString(false)) == 0) { // We were displaying a set of questions inside of a repeated group. This is // the end of that group. break event_search; } if (repeatedGroupRef.compareTo(formController.getFormIndex() .getReference().toString(false)) != 0) { // We're in a repeating group, so skip this repeat prompt and move to the // next event. event = formController.stepToNextEvent(FormController.STEP_INTO_GROUP); continue; } if (repeatedGroupRef.compareTo(formController.getFormIndex() .getReference().toString(false)) == 0) { // This is the end of the current repeating group, so we reset the // repeatedGroupName variable repeatedGroupRef = ""; } break; case FormEntryController.EVENT_REPEAT: FormEntryCaption fc = formController.getCaptionPrompt(); if (enclosingGroupRef.compareTo(formController .getFormIndex().getReference().toString(false)) == 0) { // We were displaying a set of questions inside a repeated group. This is // the end of that group. break event_search; } if (repeatedGroupRef.equalsIgnoreCase("") && fc.getMultiplicity() == 0) { // This is the start of a repeating group. We only want to display // "Group #", so we mark this as the beginning and skip all of its children HierarchyElement group = new HierarchyElement(fc.getLongText(), null, getResources() .getDrawable(R.drawable.expander_ic_minimized), Color.WHITE, COLLAPSED, fc.getIndex()); repeatedGroupRef = formController.getFormIndex().getReference() .toString(false); formList.add(group); } if (repeatedGroupRef.compareTo(formController.getFormIndex() .getReference().toString(false)) == 0) { // Add this group name to the drop down list for this repeating group. HierarchyElement h = formList.get(formList.size() - 1); h.addChild(new HierarchyElement(mIndent + fc.getLongText() + " " + (fc.getMultiplicity() + 1), null, null, Color.WHITE, CHILD, fc .getIndex())); } break; } event = formController.stepToNextEvent(FormController.STEP_INTO_GROUP); } HierarchyListAdapter itla = new HierarchyListAdapter(this); itla.setListItems(formList); setListAdapter(itla); // set the controller back to the current index in case the user hits 'back' formController.jumpToIndex(currentIndex); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { HierarchyElement h = (HierarchyElement) l.getItemAtPosition(position); FormIndex index = h.getFormIndex(); if (index == null) { goUpLevel(); return; } switch (h.getType()) { case EXPANDED: Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "COLLAPSED", h.getFormIndex()); h.setType(COLLAPSED); ArrayList<HierarchyElement> children = h.getChildren(); for (int i = 0; i < children.size(); i++) { formList.remove(position + 1); } h.setIcon(getResources().getDrawable(R.drawable.expander_ic_minimized)); h.setColor(Color.WHITE); break; case COLLAPSED: Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "EXPANDED", h.getFormIndex()); h.setType(EXPANDED); ArrayList<HierarchyElement> children1 = h.getChildren(); for (int i = 0; i < children1.size(); i++) { Log.i(t, "adding child: " + children1.get(i).getFormIndex()); formList.add(position + 1 + i, children1.get(i)); } h.setIcon(getResources().getDrawable(R.drawable.expander_ic_maximized)); h.setColor(Color.WHITE); break; case QUESTION: Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "QUESTION-JUMP", index); Collect.getInstance().getFormController().jumpToIndex(index); if ( Collect.getInstance().getFormController().indexIsInFieldList() ) { Collect.getInstance().getFormController().stepToPreviousScreenEvent(); } setResult(RESULT_OK); finish(); return; case CHILD: Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "REPEAT-JUMP", h.getFormIndex()); Collect.getInstance().getFormController().jumpToIndex(h.getFormIndex()); setResult(RESULT_OK); refreshView(); return; } // Should only get here if we've expanded or collapsed a group HierarchyListAdapter itla = new HierarchyListAdapter(this); itla.setListItems(formList); setListAdapter(itla); getListView().setSelection(position); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: Collect.getInstance().getActivityLogger().logInstanceAction(this, "onKeyDown", "KEYCODE_BACK.JUMP", mStartIndex); Collect.getInstance().getFormController().jumpToIndex(mStartIndex); } return super.onKeyDown(keyCode, event); } }
Java
/* * Copyright (C) 2011 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.odk.collect.android.activities; import java.text.DecimalFormat; import java.util.List; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.utilities.InfoLogger; import org.odk.collect.android.widgets.GeoPointWidget; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Point; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.FrameLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Overlay; public class GeoPointMapActivity extends MapActivity implements LocationListener { private static final String LOCATION_COUNT = "locationCount"; private MapView mMapView; private TextView mLocationStatus; private MapController mMapController; private LocationManager mLocationManager; private Overlay mLocationOverlay; private Overlay mGeoPointOverlay; private GeoPoint mGeoPoint; private Location mLocation; private Button mAcceptLocation; private Button mCancelLocation; private boolean mCaptureLocation = true; private Button mShowLocation; private boolean mGPSOn = false; private boolean mNetworkOn = false; private double mLocationAccuracy; private int mLocationCount = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if ( savedInstanceState != null ) { mLocationCount = savedInstanceState.getInt(LOCATION_COUNT); } requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.geopoint_layout); Intent intent = getIntent(); mLocationAccuracy = GeoPointWidget.DEFAULT_LOCATION_ACCURACY; if (intent != null && intent.getExtras() != null) { if ( intent.hasExtra(GeoPointWidget.LOCATION) ) { double[] location = intent.getDoubleArrayExtra(GeoPointWidget.LOCATION); mGeoPoint = new GeoPoint((int) (location[0] * 1E6), (int) (location[1] * 1E6)); mCaptureLocation = false; } if ( intent.hasExtra(GeoPointWidget.ACCURACY_THRESHOLD) ) { mLocationAccuracy = intent.getDoubleExtra(GeoPointWidget.ACCURACY_THRESHOLD, GeoPointWidget.DEFAULT_LOCATION_ACCURACY); } } /** * Add the MapView dynamically to the placeholding frame so as to not * incur the wrath of Android Lint... */ FrameLayout frame = (FrameLayout) findViewById(R.id.mapview_placeholder); String apiKey = "017Xo9E6R7WmcCITvo-lU2V0ERblKPqCcguwxSQ"; // String apiKey = "0wsgFhRvVBLVpgaFzmwaYuqfU898z_2YtlKSlkg"; mMapView = new MapView(this, apiKey); mMapView.setClickable(true); mMapView.setId(R.id.mapview); LayoutParams p = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); frame.addView(mMapView, p); mCancelLocation = (Button) findViewById(R.id.cancel_location); mCancelLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "cancelLocation", "cancel"); finish(); } }); mMapController = mMapView.getController(); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mMapView.setBuiltInZoomControls(true); mMapView.setSatellite(false); mMapController.setZoom(16); // make sure we have a good location provider before continuing List<String> providers = mLocationManager.getProviders(true); for (String provider : providers) { if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) { mGPSOn = true; } if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) { mNetworkOn = true; } } if (!mGPSOn && !mNetworkOn) { Toast.makeText(getBaseContext(), getString(R.string.provider_disabled_error), Toast.LENGTH_SHORT).show(); finish(); } if ( mGPSOn ) { Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if ( loc != null ) { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(GPS) lat: " + loc.getLatitude() + " long: " + loc.getLongitude() + " acc: " + loc.getAccuracy() ); } else { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(GPS) null location"); } } if ( mNetworkOn ) { Location loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if ( loc != null ) { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(Network) lat: " + loc.getLatitude() + " long: " + loc.getLongitude() + " acc: " + loc.getAccuracy() ); } else { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(Network) null location"); } } mLocationOverlay = new MyLocationOverlay(this, mMapView); mMapView.getOverlays().add(mLocationOverlay); if (mCaptureLocation) { mLocationStatus = (TextView) findViewById(R.id.location_status); mAcceptLocation = (Button) findViewById(R.id.accept_location); mAcceptLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "acceptLocation", "OK"); returnLocation(); } }); } else { mGeoPointOverlay = new Marker(mGeoPoint); mMapView.getOverlays().add(mGeoPointOverlay); ((Button) findViewById(R.id.accept_location)).setVisibility(View.GONE); ((TextView) findViewById(R.id.location_status)).setVisibility(View.GONE); mShowLocation = ((Button) findViewById(R.id.show_location)); mShowLocation.setVisibility(View.VISIBLE); mShowLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "showLocation", "onClick"); mMapController.animateTo(mGeoPoint); } }); } } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private void returnLocation() { if (mLocation != null) { Intent i = new Intent(); i.putExtra( FormEntryActivity.LOCATION_RESULT, mLocation.getLatitude() + " " + mLocation.getLongitude() + " " + mLocation.getAltitude() + " " + mLocation.getAccuracy()); setResult(RESULT_OK, i); } finish(); } private String truncateFloat(float f) { return new DecimalFormat("#.##").format(f); } @Override protected void onPause() { super.onPause(); mLocationManager.removeUpdates(this); ((MyLocationOverlay) mLocationOverlay).disableMyLocation(); } @Override protected void onResume() { super.onResume(); ((MyLocationOverlay) mLocationOverlay).enableMyLocation(); if (mGPSOn) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); } if (mNetworkOn) { mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); } } @Override protected boolean isRouteDisplayed() { return false; } @Override public void onLocationChanged(Location location) { if (mCaptureLocation) { mLocation = location; if (mLocation != null) { // Bug report: cached GeoPoint is being returned as the first value. // Wait for the 2nd value to be returned, which is hopefully not cached? ++mLocationCount; InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " onLocationChanged(" + mLocationCount + ") lat: " + mLocation.getLatitude() + " long: " + mLocation.getLongitude() + " acc: " + mLocation.getAccuracy() ); if (mLocationCount > 1) { mLocationStatus.setText(getString(R.string.location_provider_accuracy, mLocation.getProvider(), truncateFloat(mLocation.getAccuracy()))); mGeoPoint = new GeoPoint((int) (mLocation.getLatitude() * 1E6), (int) (mLocation.getLongitude() * 1E6)); mMapController.animateTo(mGeoPoint); if (mLocation.getAccuracy() <= mLocationAccuracy) { returnLocation(); } } } else { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " onLocationChanged(" + mLocationCount + ") null location"); } } } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } class Marker extends Overlay { GeoPoint gp = null; public Marker(GeoPoint gp) { super(); this.gp = gp; } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, shadow); Point screenPoint = new Point(); mMapView.getProjection().toPixels(gp, screenPoint); canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_maps_indicator_current_position), screenPoint.x, screenPoint.y - 8, null); // -8 as image is 16px high } } }
Java