text
stringlengths 30
1.67M
|
|---|
<s> package org . apache . gora . query . impl ; import org . apache . gora . mock . persistency . MockPersistent ; import org . apache . gora . mock . query . MockQuery ; import org . apache . gora . mock . store . MockDataStore ; import org . apache . gora . query . impl . PartitionQueryImpl ; import org . apache . hadoop . io . TestWritable ; import org . junit . Test ; public class TestPartitionQueryImpl { private MockDataStore dataStore = MockDataStore . get ( ) ; @ Test public void testReadWrite ( ) throws Exception { MockQuery baseQuery = dataStore . newQuery ( ) ; baseQuery . setStartKey ( "<STR_LIT:start>" ) ; baseQuery . setLimit ( <NUM_LIT> ) ; PartitionQueryImpl < String , MockPersistent > query = new PartitionQueryImpl < String , MockPersistent > ( baseQuery ) ; TestWritable . testWritable ( query ) ; } } </s>
|
<s> package org . apache . gora . query . impl ; import junit . framework . Assert ; import org . apache . gora . mock . query . MockQuery ; import org . apache . gora . mock . store . MockDataStore ; import org . apache . gora . query . impl . QueryBase ; import org . apache . gora . util . TestIOUtils ; import org . junit . Before ; import org . junit . Test ; public class TestQueryBase { private MockDataStore dataStore = MockDataStore . get ( ) ; private MockQuery query ; private static final String [ ] FIELDS = { "<STR_LIT:foo>" , "<STR_LIT:baz>" , "<STR_LIT:bar>" } ; private static final String START_KEY = "<STR_LIT>" ; private static final String END_KEY = "<STR_LIT>" ; @ Before public void setUp ( ) { query = dataStore . newQuery ( ) ; } @ Test public void testReadWrite ( ) throws Exception { query . setFields ( FIELDS ) ; query . setKeyRange ( START_KEY , END_KEY ) ; TestIOUtils . testSerializeDeserialize ( query ) ; Assert . assertNotNull ( query . getDataStore ( ) ) ; } @ Test public void testReadWrite2 ( ) throws Exception { query . setLimit ( <NUM_LIT:1000> ) ; query . setTimeRange ( <NUM_LIT:0> , System . currentTimeMillis ( ) ) ; TestIOUtils . testSerializeDeserialize ( query ) ; } } </s>
|
<s> package org . apache . gora ; import java . io . IOException ; import java . util . HashSet ; import java . util . Properties ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . store . DataStore ; import org . apache . gora . store . DataStoreFactory ; import org . apache . gora . util . GoraException ; import org . apache . hadoop . conf . Configuration ; public class GoraTestDriver { protected static final Logger log = LoggerFactory . getLogger ( GoraTestDriver . class ) ; protected Class < ? extends DataStore > dataStoreClass ; protected Configuration conf = new Configuration ( ) ; @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) protected HashSet < DataStore > dataStores ; @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) protected GoraTestDriver ( Class < ? extends DataStore > dataStoreClass ) { this . dataStoreClass = dataStoreClass ; this . dataStores = new HashSet < DataStore > ( ) ; } public void setUpClass ( ) throws Exception { setProperties ( DataStoreFactory . createProps ( ) ) ; } public void tearDownClass ( ) throws Exception { } public void setUp ( ) throws Exception { log . info ( "<STR_LIT>" ) ; try { for ( DataStore store : dataStores ) { store . truncateSchema ( ) ; } } catch ( IOException ignore ) { } } @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) public void tearDown ( ) throws Exception { log . info ( "<STR_LIT>" ) ; for ( DataStore store : dataStores ) { try { store . deleteSchema ( ) ; store . close ( ) ; } catch ( Exception ignore ) { } } dataStores . clear ( ) ; } protected void setProperties ( Properties properties ) { } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public < K , T extends Persistent > DataStore < K , T > createDataStore ( Class < K > keyClass , Class < T > persistentClass ) throws GoraException { setProperties ( DataStoreFactory . createProps ( ) ) ; DataStore < K , T > dataStore = DataStoreFactory . createDataStore ( ( Class < ? extends DataStore < K , T > > ) dataStoreClass , keyClass , persistentClass , conf ) ; dataStores . add ( dataStore ) ; return dataStore ; } public Class < ? > getDataStoreClass ( ) { return dataStoreClass ; } } </s>
|
<s> package org . apache . gora . util ; import java . io . ByteArrayInputStream ; import java . io . DataInput ; import java . io . DataInputStream ; import java . io . DataOutput ; import java . io . DataOutputStream ; import java . io . EOFException ; import java . io . IOException ; import java . util . Arrays ; import junit . framework . Assert ; import org . apache . avro . ipc . ByteBufferInputStream ; import org . apache . avro . ipc . ByteBufferOutputStream ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . apache . gora . mapreduce . GoraMapReduceUtils ; import org . apache . gora . util . IOUtils ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . io . DataInputBuffer ; import org . apache . hadoop . io . DataOutputBuffer ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import org . junit . Test ; public class TestIOUtils { public static final Logger log = LoggerFactory . getLogger ( TestIOUtils . class ) ; public static Configuration conf = new Configuration ( ) ; private static final int BOOL_ARRAY_MAX_LENGTH = <NUM_LIT:30> ; private static final int STRING_ARRAY_MAX_LENGTH = <NUM_LIT:30> ; private static class BoolArrayWrapper implements Writable { boolean [ ] arr ; @ SuppressWarnings ( "<STR_LIT:unused>" ) public BoolArrayWrapper ( ) { } public BoolArrayWrapper ( boolean [ ] arr ) { this . arr = arr ; } @ Override public void readFields ( DataInput in ) throws IOException { this . arr = IOUtils . readBoolArray ( in ) ; } @ Override public void write ( DataOutput out ) throws IOException { IOUtils . writeBoolArray ( out , arr ) ; } @ Override public boolean equals ( Object obj ) { return Arrays . equals ( arr , ( ( BoolArrayWrapper ) obj ) . arr ) ; } } private static class StringArrayWrapper implements Writable { String [ ] arr ; @ SuppressWarnings ( "<STR_LIT:unused>" ) public StringArrayWrapper ( ) { } public StringArrayWrapper ( String [ ] arr ) { this . arr = arr ; } @ Override public void readFields ( DataInput in ) throws IOException { this . arr = IOUtils . readStringArray ( in ) ; } @ Override public void write ( DataOutput out ) throws IOException { IOUtils . writeStringArray ( out , arr ) ; } @ Override public boolean equals ( Object obj ) { return Arrays . equals ( arr , ( ( StringArrayWrapper ) obj ) . arr ) ; } } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public static < T > void testSerializeDeserialize ( T ... objects ) throws Exception { ByteBufferOutputStream os = new ByteBufferOutputStream ( ) ; DataOutputStream dos = new DataOutputStream ( os ) ; ByteBufferInputStream is = null ; DataInputStream dis = null ; GoraMapReduceUtils . setIOSerializations ( conf , true ) ; try { for ( T before : objects ) { IOUtils . serialize ( conf , dos , before , ( Class < T > ) before . getClass ( ) ) ; dos . flush ( ) ; } is = new ByteBufferInputStream ( os . getBufferList ( ) ) ; dis = new DataInputStream ( is ) ; for ( T before : objects ) { T after = IOUtils . deserialize ( conf , dis , null , ( Class < T > ) before . getClass ( ) ) ; log . info ( "<STR_LIT>" + before ) ; log . info ( "<STR_LIT>" + after ) ; Assert . assertEquals ( before , after ) ; } try { long skipped = dis . skip ( <NUM_LIT:1> ) ; Assert . assertEquals ( <NUM_LIT:0> , skipped ) ; } catch ( EOFException expected ) { } } finally { org . apache . hadoop . io . IOUtils . closeStream ( dos ) ; org . apache . hadoop . io . IOUtils . closeStream ( os ) ; org . apache . hadoop . io . IOUtils . closeStream ( dis ) ; org . apache . hadoop . io . IOUtils . closeStream ( is ) ; } } @ Test public void testWritableSerde ( ) throws Exception { Text text = new Text ( "<STR_LIT>" ) ; testSerializeDeserialize ( text ) ; } @ Test public void testJavaSerializableSerde ( ) throws Exception { Integer integer = Integer . valueOf ( <NUM_LIT> ) ; testSerializeDeserialize ( integer ) ; } @ Test public void testReadWriteBoolArray ( ) throws Exception { boolean [ ] [ ] patterns = { { true } , { false } , { true , false } , { false , true } , { true , false , true } , { false , true , false } , { false , true , false , false , true , true , true } , { false , true , false , false , true , true , true , true } , { false , true , false , false , true , true , true , true , false } , } ; for ( int i = <NUM_LIT:0> ; i < BOOL_ARRAY_MAX_LENGTH ; i ++ ) { for ( int j = <NUM_LIT:0> ; j < patterns . length ; j ++ ) { boolean [ ] arr = new boolean [ i ] ; for ( int k = <NUM_LIT:0> ; k < i ; k ++ ) { arr [ k ] = patterns [ j ] [ k % patterns [ j ] . length ] ; } testSerializeDeserialize ( new BoolArrayWrapper ( arr ) ) ; } } } @ Test public void testReadWriteNullFieldsInfo ( ) throws IOException { Integer n = null ; Integer nn = new Integer ( <NUM_LIT> ) ; testNullFieldsWith ( nn ) ; testNullFieldsWith ( n ) ; testNullFieldsWith ( n , nn ) ; testNullFieldsWith ( nn , n ) ; testNullFieldsWith ( nn , n , nn , n ) ; testNullFieldsWith ( nn , n , nn , n , n , n , nn , nn , nn , n , n ) ; } private void testNullFieldsWith ( Object ... values ) throws IOException { DataOutputBuffer out = new DataOutputBuffer ( ) ; DataInputBuffer in = new DataInputBuffer ( ) ; IOUtils . writeNullFieldsInfo ( out , values ) ; in . reset ( out . getData ( ) , out . getLength ( ) ) ; boolean [ ] ret = IOUtils . readNullFieldsInfo ( in ) ; Assert . assertEquals ( values . length , ret . length ) ; for ( int i = <NUM_LIT:0> ; i < values . length ; i ++ ) { Assert . assertEquals ( values [ i ] == null , ret [ i ] ) ; } } @ Test public void testReadWriteStringArray ( ) throws Exception { for ( int i = <NUM_LIT:0> ; i < STRING_ARRAY_MAX_LENGTH ; i ++ ) { String [ ] arr = new String [ i ] ; for ( int j = <NUM_LIT:0> ; j < i ; j ++ ) { arr [ j ] = String . valueOf ( j ) ; } testSerializeDeserialize ( new StringArrayWrapper ( arr ) ) ; } } @ Test public void testReadFullyBufferLimit ( ) throws IOException { for ( int i = - <NUM_LIT:2> ; i <= <NUM_LIT:2> ; i ++ ) { byte [ ] bytes = new byte [ IOUtils . BUFFER_SIZE + i ] ; for ( int j = <NUM_LIT:0> ; j < bytes . length ; j ++ ) { bytes [ j ] = ( byte ) j ; } ByteArrayInputStream is = new ByteArrayInputStream ( bytes ) ; byte [ ] readBytes = IOUtils . readFully ( is ) ; assertByteArrayEquals ( bytes , readBytes ) ; } } public void assertByteArrayEquals ( byte [ ] expected , byte [ ] actual ) { Assert . assertEquals ( "<STR_LIT>" , expected . length , actual . length ) ; for ( int j = <NUM_LIT:0> ; j < expected . length ; j ++ ) { Assert . assertEquals ( "<STR_LIT>" + j + "<STR_LIT>" , expected [ j ] , actual [ j ] ) ; } } } </s>
|
<s> package org . apache . gora . util ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . DataInput ; import java . io . DataInputStream ; import java . io . DataOutput ; import java . io . DataOutputStream ; import java . util . Properties ; import org . junit . Assert ; import org . junit . Test ; public class TestWritableUtils { @ Test public void testWritesReads ( ) throws Exception { Properties props = new Properties ( ) ; props . put ( "<STR_LIT>" , "<STR_LIT>" ) ; props . put ( "<STR_LIT>" , "<STR_LIT>" ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; DataOutput out = new DataOutputStream ( bos ) ; WritableUtils . writeProperties ( out , props ) ; DataInput in = new DataInputStream ( new ByteArrayInputStream ( bos . toByteArray ( ) ) ) ; Properties propsRead = WritableUtils . readProperties ( in ) ; Assert . assertEquals ( propsRead . get ( "<STR_LIT>" ) , props . get ( "<STR_LIT>" ) ) ; Assert . assertEquals ( propsRead . get ( "<STR_LIT>" ) , props . get ( "<STR_LIT>" ) ) ; } } </s>
|
<s> package org . apache . gora . mapreduce ; import java . io . IOException ; import java . util . HashMap ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . apache . gora . examples . WebPageDataCreator ; import org . apache . gora . examples . generated . TokenDatum ; import org . apache . gora . examples . generated . WebPage ; import org . apache . gora . examples . mapreduce . QueryCounter ; import org . apache . gora . examples . mapreduce . WordCount ; import org . apache . gora . query . Query ; import org . apache . gora . store . DataStore ; import org . apache . hadoop . conf . Configuration ; import org . junit . Assert ; public class MapReduceTestUtils { private static final Logger log = LoggerFactory . getLogger ( MapReduceTestUtils . class ) ; public static void testCountQuery ( DataStore < String , WebPage > dataStore , Configuration conf ) throws Exception { dataStore . setConf ( conf ) ; WebPageDataCreator . createWebPageData ( dataStore ) ; QueryCounter < String , WebPage > counter = new QueryCounter < String , WebPage > ( conf ) ; Query < String , WebPage > query = dataStore . newQuery ( ) ; query . setFields ( WebPage . _ALL_FIELDS ) ; dataStore . close ( ) ; log . info ( "<STR_LIT>" ) ; long result = counter . countQuery ( dataStore , query ) ; log . info ( "<STR_LIT>" ) ; Assert . assertEquals ( WebPageDataCreator . URLS . length , result ) ; } public static void testWordCount ( Configuration conf , DataStore < String , WebPage > inStore , DataStore < String , TokenDatum > outStore ) throws Exception { inStore . setConf ( conf ) ; outStore . setConf ( conf ) ; WebPageDataCreator . createWebPageData ( inStore ) ; WordCount wordCount = new WordCount ( conf ) ; wordCount . wordCount ( inStore , outStore ) ; HashMap < String , Integer > actualCounts = new HashMap < String , Integer > ( ) ; for ( String content : WebPageDataCreator . CONTENTS ) { for ( String token : content . split ( "<STR_LIT:U+0020>" ) ) { Integer count = actualCounts . get ( token ) ; if ( count == null ) count = <NUM_LIT:0> ; actualCounts . put ( token , ++ count ) ; } } for ( Map . Entry < String , Integer > entry : actualCounts . entrySet ( ) ) { assertTokenCount ( outStore , entry . getKey ( ) , entry . getValue ( ) ) ; } } private static void assertTokenCount ( DataStore < String , TokenDatum > outStore , String token , int count ) throws IOException { TokenDatum datum = outStore . get ( token , null ) ; Assert . assertNotNull ( "<STR_LIT>" + token + "<STR_LIT>" , datum ) ; Assert . assertEquals ( "<STR_LIT>" + token + "<STR_LIT>" , count , datum . getCount ( ) ) ; } } </s>
|
<s> package org . apache . gora . mapreduce ; import junit . framework . Assert ; import org . apache . avro . util . Utf8 ; import org . apache . gora . examples . WebPageDataCreator ; import org . apache . gora . examples . generated . Employee ; import org . apache . gora . examples . generated . WebPage ; import org . apache . gora . mapreduce . PersistentDeserializer ; import org . apache . gora . mapreduce . PersistentSerialization ; import org . apache . gora . mapreduce . PersistentSerializer ; import org . apache . gora . memory . store . MemStore ; import org . apache . gora . query . Result ; import org . apache . gora . store . DataStoreFactory ; import org . apache . gora . store . DataStoreTestUtil ; import org . apache . gora . util . TestIOUtils ; import org . apache . hadoop . conf . Configuration ; import org . junit . Test ; public class TestPersistentSerialization { @ SuppressWarnings ( "<STR_LIT:unchecked>" ) @ Test public void testSerdeEmployee ( ) throws Exception { MemStore < String , Employee > store = DataStoreFactory . getDataStore ( MemStore . class , String . class , Employee . class , new Configuration ( ) ) ; Employee employee = DataStoreTestUtil . createEmployee ( store ) ; TestIOUtils . testSerializeDeserialize ( employee ) ; } @ Test public void testSerdeEmployeeOneField ( ) throws Exception { Employee employee = new Employee ( ) ; employee . setSsn ( new Utf8 ( "<STR_LIT>" ) ) ; TestIOUtils . testSerializeDeserialize ( employee ) ; } @ Test public void testSerdeEmployeeTwoFields ( ) throws Exception { Employee employee = new Employee ( ) ; employee . setSsn ( new Utf8 ( "<STR_LIT>" ) ) ; employee . setSalary ( <NUM_LIT:100> ) ; TestIOUtils . testSerializeDeserialize ( employee ) ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) @ Test public void testSerdeWebPage ( ) throws Exception { MemStore < String , WebPage > store = DataStoreFactory . getDataStore ( MemStore . class , String . class , WebPage . class , new Configuration ( ) ) ; WebPageDataCreator . createWebPageData ( store ) ; Result < String , WebPage > result = store . newQuery ( ) . execute ( ) ; int i = <NUM_LIT:0> ; while ( result . next ( ) ) { WebPage page = result . get ( ) ; TestIOUtils . testSerializeDeserialize ( page ) ; i ++ ; } Assert . assertEquals ( WebPageDataCreator . URLS . length , i ) ; } @ Test public void testSerdeMultipleWebPages ( ) throws Exception { WebPage page1 = new WebPage ( ) ; WebPage page2 = new WebPage ( ) ; WebPage page3 = new WebPage ( ) ; page1 . setUrl ( new Utf8 ( "<STR_LIT:foo>" ) ) ; page2 . setUrl ( new Utf8 ( "<STR_LIT:baz>" ) ) ; page3 . setUrl ( new Utf8 ( "<STR_LIT:bar>" ) ) ; page1 . addToParsedContent ( new Utf8 ( "<STR_LIT>" ) ) ; page2 . putToOutlinks ( new Utf8 ( "<STR_LIT:a>" ) , new Utf8 ( "<STR_LIT:b>" ) ) ; TestIOUtils . testSerializeDeserialize ( page1 , page2 , page3 ) ; } } </s>
|
<s> package org . apache . gora . mapreduce ; import java . io . IOException ; import java . util . List ; import junit . framework . Assert ; import org . apache . gora . mapreduce . GoraInputSplit ; import org . apache . gora . mock . persistency . MockPersistent ; import org . apache . gora . mock . query . MockQuery ; import org . apache . gora . mock . store . MockDataStore ; import org . apache . gora . query . PartitionQuery ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . io . TestWritable ; import org . junit . Test ; public class TestGoraInputSplit { private Configuration conf = new Configuration ( ) ; private List < PartitionQuery < String , MockPersistent > > getPartitions ( ) throws IOException { MockDataStore store = MockDataStore . get ( ) ; MockQuery query = store . newQuery ( ) ; List < PartitionQuery < String , MockPersistent > > partitions = store . getPartitions ( query ) ; return partitions ; } @ Test public void testGetLocations ( ) throws IOException { List < PartitionQuery < String , MockPersistent > > partitions = getPartitions ( ) ; int i = <NUM_LIT:0> ; ; for ( PartitionQuery < String , MockPersistent > partition : partitions ) { GoraInputSplit split = new GoraInputSplit ( conf , partition ) ; Assert . assertEquals ( split . getLocations ( ) . length , <NUM_LIT:1> ) ; Assert . assertEquals ( split . getLocations ( ) [ <NUM_LIT:0> ] , MockDataStore . LOCATIONS [ i ++ ] ) ; } } @ Test public void testReadWrite ( ) throws Exception { List < PartitionQuery < String , MockPersistent > > partitions = getPartitions ( ) ; for ( PartitionQuery < String , MockPersistent > partition : partitions ) { GoraInputSplit split = new GoraInputSplit ( conf , partition ) ; TestWritable . testWritable ( split ) ; } } } </s>
|
<s> package org . apache . gora . mapreduce ; import java . io . IOException ; import org . apache . gora . examples . generated . WebPage ; import org . apache . gora . store . DataStore ; import org . apache . hadoop . mapred . HadoopTestCase ; import org . apache . hadoop . mapred . JobConf ; import org . junit . Before ; import org . junit . Test ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; @ SuppressWarnings ( "<STR_LIT:deprecation>" ) public abstract class DataStoreMapReduceTestBase extends HadoopTestCase { public static final Logger LOG = LoggerFactory . getLogger ( DataStoreMapReduceTestBase . class ) ; private DataStore < String , WebPage > webPageStore ; private JobConf job ; public DataStoreMapReduceTestBase ( int mrMode , int fsMode , int taskTrackers , int dataNodes ) throws IOException { super ( mrMode , fsMode , taskTrackers , dataNodes ) ; } public DataStoreMapReduceTestBase ( ) throws IOException { this ( HadoopTestCase . CLUSTER_MR , HadoopTestCase . DFS_FS , <NUM_LIT:2> , <NUM_LIT:2> ) ; } @ Override @ Before public void setUp ( ) throws Exception { LOG . info ( "<STR_LIT>" ) ; try { super . setUp ( ) ; webPageStore = createWebPageDataStore ( ) ; job = createJobConf ( ) ; } catch ( Exception e ) { LOG . error ( "<STR_LIT>" , e ) ; tearDown ( ) ; } } @ Override public void tearDown ( ) throws Exception { LOG . info ( "<STR_LIT>" ) ; super . tearDown ( ) ; webPageStore . close ( ) ; } protected abstract DataStore < String , WebPage > createWebPageDataStore ( ) throws IOException ; @ Test public void testCountQuery ( ) throws Exception { MapReduceTestUtils . testCountQuery ( webPageStore , job ) ; } } </s>
|
<s> package org . apache . gora . mapreduce ; import java . io . IOException ; import java . util . Arrays ; import java . util . List ; import junit . framework . Assert ; import org . apache . gora . examples . generated . Employee ; import org . apache . gora . mapreduce . GoraInputFormat ; import org . apache . gora . mapreduce . GoraInputSplit ; import org . apache . gora . mock . persistency . MockPersistent ; import org . apache . gora . mock . query . MockQuery ; import org . apache . gora . mock . store . MockDataStore ; import org . apache . gora . query . PartitionQuery ; import org . apache . hadoop . mapreduce . InputSplit ; import org . apache . hadoop . mapreduce . Job ; import org . junit . Test ; public class TestGoraInputFormat { public List < InputSplit > getInputSplits ( ) throws IOException , InterruptedException { Job job = new Job ( ) ; MockDataStore store = MockDataStore . get ( ) ; MockQuery query = store . newQuery ( ) ; query . setFields ( Employee . _ALL_FIELDS ) ; GoraInputFormat . setInput ( job , query , false ) ; GoraInputFormat < String , MockPersistent > inputFormat = new GoraInputFormat < String , MockPersistent > ( ) ; inputFormat . setConf ( job . getConfiguration ( ) ) ; return inputFormat . getSplits ( job ) ; } @ Test @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) public void testGetSplits ( ) throws IOException , InterruptedException { List < InputSplit > splits = getInputSplits ( ) ; Assert . assertTrue ( splits . size ( ) > <NUM_LIT:0> ) ; InputSplit split = splits . get ( <NUM_LIT:0> ) ; PartitionQuery query = ( ( GoraInputSplit ) split ) . getQuery ( ) ; Assert . assertTrue ( Arrays . equals ( Employee . _ALL_FIELDS , query . getFields ( ) ) ) ; } } </s>
|
<s> package org . apache . gora . store ; import java . io . IOException ; import java . nio . ByteBuffer ; import junit . framework . Assert ; import org . apache . avro . util . Utf8 ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . apache . gora . GoraTestDriver ; import org . apache . gora . examples . generated . Employee ; import org . apache . gora . examples . generated . Metadata ; import org . apache . gora . examples . generated . WebPage ; import org . apache . gora . store . DataStore ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; public abstract class DataStoreTestBase { public static final Logger log = LoggerFactory . getLogger ( DataStoreTestBase . class ) ; protected static GoraTestDriver testDriver ; protected DataStore < String , Employee > employeeStore ; protected DataStore < String , WebPage > webPageStore ; @ Deprecated protected abstract DataStore < String , Employee > createEmployeeDataStore ( ) throws IOException ; @ Deprecated protected abstract DataStore < String , WebPage > createWebPageDataStore ( ) throws IOException ; protected static void setTestDriver ( GoraTestDriver driver ) { testDriver = driver ; } private static boolean setUpClassCalled = false ; @ BeforeClass public static void setUpClass ( ) throws Exception { if ( testDriver != null && ! setUpClassCalled ) { log . info ( "<STR_LIT>" ) ; testDriver . setUpClass ( ) ; setUpClassCalled = true ; } } @ AfterClass public static void tearDownClass ( ) throws Exception { if ( testDriver != null ) { log . info ( "<STR_LIT>" ) ; testDriver . tearDownClass ( ) ; } } @ Before public void setUp ( ) throws Exception { if ( ! setUpClassCalled ) { setUpClass ( ) ; } log . info ( "<STR_LIT>" ) ; if ( testDriver != null ) { employeeStore = testDriver . createDataStore ( String . class , Employee . class ) ; webPageStore = testDriver . createDataStore ( String . class , WebPage . class ) ; testDriver . setUp ( ) ; } else { employeeStore = createEmployeeDataStore ( ) ; webPageStore = createWebPageDataStore ( ) ; employeeStore . truncateSchema ( ) ; webPageStore . truncateSchema ( ) ; } } @ After public void tearDown ( ) throws Exception { log . info ( "<STR_LIT>" ) ; if ( testDriver != null ) { testDriver . tearDown ( ) ; } } @ Test public void testNewInstance ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testNewPersistent ( employeeStore ) ; } @ Test public void testCreateSchema ( ) throws Exception { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testCreateEmployeeSchema ( employeeStore ) ; assertSchemaExists ( "<STR_LIT>" ) ; } public void assertSchemaExists ( String schemaName ) throws Exception { } @ Test public void testAutoCreateSchema ( ) throws Exception { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testAutoCreateSchema ( employeeStore ) ; assertAutoCreateSchema ( ) ; } public void assertAutoCreateSchema ( ) throws Exception { assertSchemaExists ( "<STR_LIT>" ) ; } @ Test public void testTruncateSchema ( ) throws Exception { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testTruncateSchema ( webPageStore ) ; assertSchemaExists ( "<STR_LIT>" ) ; } @ Test public void testDeleteSchema ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testDeleteSchema ( webPageStore ) ; } @ Test public void testSchemaExists ( ) throws Exception { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testSchemaExists ( webPageStore ) ; } @ Test public void testPut ( ) throws IOException { log . info ( "<STR_LIT>" ) ; Employee employee = DataStoreTestUtil . testPutEmployee ( employeeStore ) ; assertPut ( employee ) ; } public void assertPut ( Employee employee ) throws IOException { } @ Test public void testPutNested ( ) throws IOException { log . info ( "<STR_LIT>" ) ; String revUrl = "<STR_LIT>" ; String url = "<STR_LIT>" ; webPageStore . createSchema ( ) ; WebPage page = webPageStore . newPersistent ( ) ; Metadata metadata = new Metadata ( ) ; metadata . setVersion ( <NUM_LIT:1> ) ; metadata . putToData ( new Utf8 ( "<STR_LIT:foo>" ) , new Utf8 ( "<STR_LIT:baz>" ) ) ; page . setMetadata ( metadata ) ; page . setUrl ( new Utf8 ( url ) ) ; webPageStore . put ( revUrl , page ) ; webPageStore . flush ( ) ; page = webPageStore . get ( revUrl ) ; metadata = page . getMetadata ( ) ; Assert . assertNotNull ( metadata ) ; Assert . assertEquals ( <NUM_LIT:1> , metadata . getVersion ( ) ) ; Assert . assertEquals ( new Utf8 ( "<STR_LIT:baz>" ) , metadata . getData ( ) . get ( new Utf8 ( "<STR_LIT:foo>" ) ) ) ; } @ Test public void testPutArray ( ) throws IOException { log . info ( "<STR_LIT>" ) ; webPageStore . createSchema ( ) ; WebPage page = webPageStore . newPersistent ( ) ; String [ ] tokens = { "<STR_LIT>" , "<STR_LIT:content>" , "<STR_LIT>" , "<STR_LIT>" } ; for ( String token : tokens ) { page . addToParsedContent ( new Utf8 ( token ) ) ; } webPageStore . put ( "<STR_LIT>" , page ) ; webPageStore . close ( ) ; assertPutArray ( ) ; } public void assertPutArray ( ) throws IOException { } @ Test public void testPutBytes ( ) throws IOException { log . info ( "<STR_LIT>" ) ; webPageStore . createSchema ( ) ; WebPage page = webPageStore . newPersistent ( ) ; page . setUrl ( new Utf8 ( "<STR_LIT>" ) ) ; byte [ ] contentBytes = "<STR_LIT>" . getBytes ( ) ; ByteBuffer buff = ByteBuffer . wrap ( contentBytes ) ; page . setContent ( buff ) ; webPageStore . put ( "<STR_LIT>" , page ) ; webPageStore . close ( ) ; assertPutBytes ( contentBytes ) ; } public void assertPutBytes ( byte [ ] contentBytes ) throws IOException { } @ Test public void testPutMap ( ) throws IOException { log . info ( "<STR_LIT>" ) ; webPageStore . createSchema ( ) ; WebPage page = webPageStore . newPersistent ( ) ; page . setUrl ( new Utf8 ( "<STR_LIT>" ) ) ; page . putToOutlinks ( new Utf8 ( "<STR_LIT>" ) , new Utf8 ( "<STR_LIT>" ) ) ; page . putToOutlinks ( new Utf8 ( "<STR_LIT>" ) , new Utf8 ( "<STR_LIT>" ) ) ; page . putToOutlinks ( new Utf8 ( "<STR_LIT>" ) , new Utf8 ( "<STR_LIT>" ) ) ; webPageStore . put ( "<STR_LIT>" , page ) ; webPageStore . close ( ) ; assertPutMap ( ) ; } public void assertPutMap ( ) throws IOException { } @ Test public void testUpdate ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testUpdateEmployee ( employeeStore ) ; DataStoreTestUtil . testUpdateWebPage ( webPageStore ) ; } public void testEmptyUpdate ( ) throws IOException { DataStoreTestUtil . testEmptyUpdateEmployee ( employeeStore ) ; } @ Test public void testGet ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testGetEmployee ( employeeStore ) ; } @ Test public void testGetWithFields ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testGetEmployeeWithFields ( employeeStore ) ; } @ Test public void testGetWebPage ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testGetWebPage ( webPageStore ) ; } @ Test public void testGetWebPageDefaultFields ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testGetWebPageDefaultFields ( webPageStore ) ; } @ Test public void testGetNonExisting ( ) throws Exception { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testGetEmployeeNonExisting ( employeeStore ) ; } @ Test public void testQuery ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testQueryWebPages ( webPageStore ) ; } @ Test public void testQueryStartKey ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testQueryWebPageStartKey ( webPageStore ) ; } @ Test public void testQueryEndKey ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testQueryWebPageEndKey ( webPageStore ) ; } @ Test public void testQueryKeyRange ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testQueryWebPageKeyRange ( webPageStore ) ; } @ Test public void testQueryWebPageSingleKey ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testQueryWebPageSingleKey ( webPageStore ) ; } @ Test public void testQueryWebPageSingleKeyDefaultFields ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testQueryWebPageSingleKeyDefaultFields ( webPageStore ) ; } @ Test public void testQueryWebPageQueryEmptyResults ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testQueryWebPageEmptyResults ( webPageStore ) ; } @ Test public void testDelete ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testDelete ( webPageStore ) ; } @ Test public void testDeleteByQuery ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testDeleteByQuery ( webPageStore ) ; } @ Test public void testDeleteByQueryFields ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testDeleteByQueryFields ( webPageStore ) ; } @ Test public void testGetPartitions ( ) throws IOException { log . info ( "<STR_LIT>" ) ; DataStoreTestUtil . testGetPartitions ( webPageStore ) ; } } </s>
|
<s> package org . apache . gora . store ; import java . util . Properties ; import junit . framework . Assert ; import org . apache . gora . avro . store . DataFileAvroStore ; import org . apache . gora . mock . persistency . MockPersistent ; import org . apache . gora . mock . store . MockDataStore ; import org . apache . gora . util . GoraException ; import org . apache . hadoop . conf . Configuration ; import org . junit . Before ; import org . junit . Test ; public class TestDataStoreFactory { private Configuration conf ; @ Before public void setUp ( ) { conf = new Configuration ( ) ; } @ Test public void testGetDataStore ( ) throws GoraException { DataStore < ? , ? > dataStore = DataStoreFactory . getDataStore ( "<STR_LIT>" , String . class , MockPersistent . class , conf ) ; Assert . assertNotNull ( dataStore ) ; } @ Test public void testGetClasses ( ) throws GoraException { DataStore < ? , ? > dataStore = DataStoreFactory . getDataStore ( "<STR_LIT>" , String . class , MockPersistent . class , conf ) ; Assert . assertNotNull ( dataStore ) ; Assert . assertEquals ( String . class , dataStore . getKeyClass ( ) ) ; Assert . assertEquals ( MockPersistent . class , dataStore . getPersistentClass ( ) ) ; } @ Test public void testGetDataStore2 ( ) throws GoraException { DataStore < ? , ? > dataStore = DataStoreFactory . getDataStore ( MockDataStore . class , String . class , MockPersistent . class , conf ) ; Assert . assertNotNull ( dataStore ) ; } @ Test public void testGetDataStore3 ( ) throws GoraException { DataStore < ? , ? > dataStore1 = DataStoreFactory . getDataStore ( "<STR_LIT>" , Object . class , MockPersistent . class , conf ) ; DataStore < ? , ? > dataStore2 = DataStoreFactory . getDataStore ( "<STR_LIT>" , Object . class , MockPersistent . class , conf ) ; DataStore < ? , ? > dataStore3 = DataStoreFactory . getDataStore ( "<STR_LIT>" , String . class , MockPersistent . class , conf ) ; Assert . assertNotSame ( dataStore1 , dataStore2 ) ; Assert . assertNotSame ( dataStore1 , dataStore3 ) ; } @ Test public void testReadProperties ( ) throws GoraException { DataStore < ? , ? > dataStore = DataStoreFactory . getDataStore ( String . class , MockPersistent . class , conf ) ; Assert . assertNotNull ( dataStore ) ; Assert . assertEquals ( MockDataStore . class , dataStore . getClass ( ) ) ; } @ Test public void testFindProperty ( ) { Properties properties = DataStoreFactory . createProps ( ) ; DataStore < String , MockPersistent > store = new DataFileAvroStore < String , MockPersistent > ( ) ; String fooValue = DataStoreFactory . findProperty ( properties , store , "<STR_LIT>" , "<STR_LIT>" ) ; Assert . assertEquals ( "<STR_LIT>" , fooValue ) ; String bazValue = DataStoreFactory . findProperty ( properties , store , "<STR_LIT>" , "<STR_LIT>" ) ; Assert . assertEquals ( "<STR_LIT>" , bazValue ) ; String barValue = DataStoreFactory . findProperty ( properties , store , "<STR_LIT>" , "<STR_LIT>" ) ; Assert . assertEquals ( "<STR_LIT>" , barValue ) ; } } </s>
|
<s> package org . apache . gora . store ; import static org . apache . gora . examples . WebPageDataCreator . ANCHORS ; import static org . apache . gora . examples . WebPageDataCreator . CONTENTS ; import static org . apache . gora . examples . WebPageDataCreator . LINKS ; import static org . apache . gora . examples . WebPageDataCreator . SORTED_URLS ; import static org . apache . gora . examples . WebPageDataCreator . URLS ; import static org . apache . gora . examples . WebPageDataCreator . URL_INDEXES ; import static org . apache . gora . examples . WebPageDataCreator . createWebPageData ; import java . io . IOException ; import java . nio . ByteBuffer ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import junit . framework . Assert ; import org . apache . avro . generic . GenericArray ; import org . apache . avro . util . Utf8 ; import org . apache . gora . examples . WebPageDataCreator ; import org . apache . gora . examples . generated . Employee ; import org . apache . gora . examples . generated . WebPage ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . query . PartitionQuery ; import org . apache . gora . query . Query ; import org . apache . gora . query . Result ; import org . apache . gora . store . DataStore ; import org . apache . gora . util . ByteUtils ; import org . apache . gora . util . StringUtils ; public class DataStoreTestUtil { public static final long YEAR_IN_MS = <NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT> ; private static final int NUM_KEYS = <NUM_LIT:4> ; public static < K , T extends Persistent > void testNewPersistent ( DataStore < K , T > dataStore ) throws IOException { T obj1 = dataStore . newPersistent ( ) ; T obj2 = dataStore . newPersistent ( ) ; Assert . assertEquals ( dataStore . getPersistentClass ( ) , obj1 . getClass ( ) ) ; Assert . assertNotNull ( obj1 ) ; Assert . assertNotNull ( obj2 ) ; Assert . assertFalse ( obj1 == obj2 ) ; } public static < K > Employee createEmployee ( DataStore < K , Employee > dataStore ) throws IOException { Employee employee = dataStore . newPersistent ( ) ; employee . setName ( new Utf8 ( "<STR_LIT>" ) ) ; employee . setDateOfBirth ( System . currentTimeMillis ( ) - <NUM_LIT> * YEAR_IN_MS ) ; employee . setSalary ( <NUM_LIT> ) ; employee . setSsn ( new Utf8 ( "<STR_LIT>" ) ) ; return employee ; } public static void testAutoCreateSchema ( DataStore < String , Employee > dataStore ) throws IOException { dataStore . put ( "<STR_LIT:foo>" , createEmployee ( dataStore ) ) ; } public static void testCreateEmployeeSchema ( DataStore < String , Employee > dataStore ) throws IOException { dataStore . createSchema ( ) ; dataStore . createSchema ( ) ; } public static void testTruncateSchema ( DataStore < String , WebPage > dataStore ) throws IOException { dataStore . createSchema ( ) ; WebPageDataCreator . createWebPageData ( dataStore ) ; dataStore . truncateSchema ( ) ; assertEmptyResults ( dataStore . newQuery ( ) ) ; } public static void testDeleteSchema ( DataStore < String , WebPage > dataStore ) throws IOException { dataStore . createSchema ( ) ; WebPageDataCreator . createWebPageData ( dataStore ) ; dataStore . deleteSchema ( ) ; dataStore . createSchema ( ) ; assertEmptyResults ( dataStore . newQuery ( ) ) ; } public static < K , T extends Persistent > void testSchemaExists ( DataStore < K , T > dataStore ) throws IOException { dataStore . createSchema ( ) ; Assert . assertTrue ( dataStore . schemaExists ( ) ) ; dataStore . deleteSchema ( ) ; Assert . assertFalse ( dataStore . schemaExists ( ) ) ; } public static void testGetEmployee ( DataStore < String , Employee > dataStore ) throws IOException { dataStore . createSchema ( ) ; Employee employee = DataStoreTestUtil . createEmployee ( dataStore ) ; String ssn = employee . getSsn ( ) . toString ( ) ; dataStore . put ( ssn , employee ) ; dataStore . flush ( ) ; Employee after = dataStore . get ( ssn , Employee . _ALL_FIELDS ) ; Assert . assertEquals ( employee , after ) ; } public static void testGetEmployeeNonExisting ( DataStore < String , Employee > dataStore ) throws IOException { Employee employee = dataStore . get ( "<STR_LIT>" ) ; Assert . assertNull ( employee ) ; } public static void testGetEmployeeWithFields ( DataStore < String , Employee > dataStore ) throws IOException { Employee employee = DataStoreTestUtil . createEmployee ( dataStore ) ; String ssn = employee . getSsn ( ) . toString ( ) ; dataStore . put ( ssn , employee ) ; dataStore . flush ( ) ; String [ ] fields = employee . getFields ( ) ; for ( Set < String > subset : StringUtils . powerset ( fields ) ) { if ( subset . isEmpty ( ) ) continue ; Employee after = dataStore . get ( ssn , subset . toArray ( new String [ subset . size ( ) ] ) ) ; Employee expected = new Employee ( ) ; for ( String field : subset ) { int index = expected . getFieldIndex ( field ) ; expected . put ( index , employee . get ( index ) ) ; } Assert . assertEquals ( expected , after ) ; } } public static Employee testPutEmployee ( DataStore < String , Employee > dataStore ) throws IOException { dataStore . createSchema ( ) ; Employee employee = DataStoreTestUtil . createEmployee ( dataStore ) ; return employee ; } public static void testEmptyUpdateEmployee ( DataStore < String , Employee > dataStore ) throws IOException { dataStore . createSchema ( ) ; long ssn = <NUM_LIT> ; String ssnStr = Long . toString ( ssn ) ; long now = System . currentTimeMillis ( ) ; Employee employee = dataStore . newPersistent ( ) ; employee . setName ( new Utf8 ( "<STR_LIT>" ) ) ; employee . setDateOfBirth ( now - <NUM_LIT> * YEAR_IN_MS ) ; employee . setSalary ( <NUM_LIT> ) ; employee . setSsn ( new Utf8 ( ssnStr ) ) ; dataStore . put ( employee . getSsn ( ) . toString ( ) , employee ) ; dataStore . flush ( ) ; employee = dataStore . get ( ssnStr ) ; dataStore . put ( ssnStr , employee ) ; dataStore . flush ( ) ; employee = dataStore . newPersistent ( ) ; dataStore . put ( Long . toString ( ssn + <NUM_LIT:1> ) , employee ) ; dataStore . flush ( ) ; employee = dataStore . get ( Long . toString ( ssn + <NUM_LIT:1> ) ) ; Assert . assertNull ( employee ) ; } public static void testUpdateEmployee ( DataStore < String , Employee > dataStore ) throws IOException { dataStore . createSchema ( ) ; long ssn = <NUM_LIT> ; long now = System . currentTimeMillis ( ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:5> ; i ++ ) { Employee employee = dataStore . newPersistent ( ) ; employee . setName ( new Utf8 ( "<STR_LIT>" + i ) ) ; employee . setDateOfBirth ( now - <NUM_LIT> * YEAR_IN_MS ) ; employee . setSalary ( <NUM_LIT> ) ; employee . setSsn ( new Utf8 ( Long . toString ( ssn + i ) ) ) ; dataStore . put ( employee . getSsn ( ) . toString ( ) , employee ) ; } dataStore . flush ( ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:1> ; i ++ ) { Employee employee = dataStore . newPersistent ( ) ; employee . setName ( new Utf8 ( "<STR_LIT>" + ( i + <NUM_LIT:5> ) ) ) ; employee . setDateOfBirth ( now - <NUM_LIT> * YEAR_IN_MS ) ; employee . setSalary ( <NUM_LIT> ) ; employee . setSsn ( new Utf8 ( Long . toString ( ssn + i ) ) ) ; dataStore . put ( employee . getSsn ( ) . toString ( ) , employee ) ; } dataStore . flush ( ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:1> ; i ++ ) { String key = Long . toString ( ssn + i ) ; Employee employee = dataStore . get ( key ) ; Assert . assertEquals ( now - <NUM_LIT> * YEAR_IN_MS , employee . getDateOfBirth ( ) ) ; Assert . assertEquals ( "<STR_LIT>" + ( i + <NUM_LIT:5> ) , employee . getName ( ) . toString ( ) ) ; Assert . assertEquals ( <NUM_LIT> , employee . getSalary ( ) ) ; } } public static void testUpdateWebPage ( DataStore < String , WebPage > dataStore ) throws IOException { dataStore . createSchema ( ) ; String [ ] urls = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; String content = "<STR_LIT:content>" ; String parsedContent = "<STR_LIT>" ; String anchor = "<STR_LIT>" ; int parsedContentCount = <NUM_LIT:0> ; for ( int i = <NUM_LIT:0> ; i < urls . length ; i ++ ) { WebPage webPage = dataStore . newPersistent ( ) ; webPage . setUrl ( new Utf8 ( urls [ i ] ) ) ; for ( parsedContentCount = <NUM_LIT:0> ; parsedContentCount < <NUM_LIT:5> ; parsedContentCount ++ ) { webPage . addToParsedContent ( new Utf8 ( parsedContent + i + "<STR_LIT:U+002C>" + parsedContentCount ) ) ; } for ( int j = <NUM_LIT:0> ; j < urls . length ; j += <NUM_LIT:2> ) { webPage . putToOutlinks ( new Utf8 ( anchor + j ) , new Utf8 ( urls [ j ] ) ) ; } dataStore . put ( webPage . getUrl ( ) . toString ( ) , webPage ) ; } dataStore . flush ( ) ; for ( int i = <NUM_LIT:0> ; i < urls . length ; i ++ ) { WebPage webPage = dataStore . get ( urls [ i ] ) ; webPage . setContent ( ByteBuffer . wrap ( ByteUtils . toBytes ( content + i ) ) ) ; for ( parsedContentCount = <NUM_LIT:5> ; parsedContentCount < <NUM_LIT:10> ; parsedContentCount ++ ) { webPage . addToParsedContent ( new Utf8 ( parsedContent + i + "<STR_LIT:U+002C>" + parsedContentCount ) ) ; } webPage . getOutlinks ( ) . clear ( ) ; for ( int j = <NUM_LIT:1> ; j < urls . length ; j += <NUM_LIT:2> ) { webPage . putToOutlinks ( new Utf8 ( anchor + j ) , new Utf8 ( urls [ j ] ) ) ; } dataStore . put ( webPage . getUrl ( ) . toString ( ) , webPage ) ; } dataStore . flush ( ) ; for ( int i = <NUM_LIT:0> ; i < urls . length ; i ++ ) { WebPage webPage = dataStore . get ( urls [ i ] ) ; Assert . assertEquals ( content + i , ByteUtils . toString ( toByteArray ( webPage . getContent ( ) ) ) ) ; Assert . assertEquals ( <NUM_LIT:10> , webPage . getParsedContent ( ) . size ( ) ) ; int j = <NUM_LIT:0> ; for ( Utf8 pc : webPage . getParsedContent ( ) ) { Assert . assertEquals ( parsedContent + i + "<STR_LIT:U+002C>" + j , pc . toString ( ) ) ; j ++ ; } int count = <NUM_LIT:0> ; for ( j = <NUM_LIT:1> ; j < urls . length ; j += <NUM_LIT:2> ) { Utf8 link = webPage . getOutlinks ( ) . get ( new Utf8 ( anchor + j ) ) ; Assert . assertNotNull ( link ) ; Assert . assertEquals ( urls [ j ] , link . toString ( ) ) ; count ++ ; } Assert . assertEquals ( count , webPage . getOutlinks ( ) . size ( ) ) ; } for ( int i = <NUM_LIT:0> ; i < urls . length ; i ++ ) { WebPage webPage = dataStore . get ( urls [ i ] ) ; for ( int j = <NUM_LIT:0> ; j < urls . length ; j += <NUM_LIT:2> ) { webPage . putToOutlinks ( new Utf8 ( anchor + j ) , new Utf8 ( urls [ j ] ) ) ; } dataStore . put ( webPage . getUrl ( ) . toString ( ) , webPage ) ; } dataStore . flush ( ) ; for ( int i = <NUM_LIT:0> ; i < urls . length ; i ++ ) { WebPage webPage = dataStore . get ( urls [ i ] ) ; int count = <NUM_LIT:0> ; for ( int j = <NUM_LIT:0> ; j < urls . length ; j ++ ) { Utf8 link = webPage . getOutlinks ( ) . get ( new Utf8 ( anchor + j ) ) ; Assert . assertNotNull ( link ) ; Assert . assertEquals ( urls [ j ] , link . toString ( ) ) ; count ++ ; } } } public static void assertWebPage ( WebPage page , int i ) { Assert . assertNotNull ( page ) ; Assert . assertEquals ( URLS [ i ] , page . getUrl ( ) . toString ( ) ) ; Assert . assertTrue ( "<STR_LIT>" + new String ( toByteArray ( page . getContent ( ) ) ) + "<STR_LIT>" + CONTENTS [ i ] + "<STR_LIT>" + i , Arrays . equals ( toByteArray ( page . getContent ( ) ) , CONTENTS [ i ] . getBytes ( ) ) ) ; GenericArray < Utf8 > parsedContent = page . getParsedContent ( ) ; Assert . assertNotNull ( parsedContent ) ; Assert . assertTrue ( parsedContent . size ( ) > <NUM_LIT:0> ) ; int j = <NUM_LIT:0> ; String [ ] tokens = CONTENTS [ i ] . split ( "<STR_LIT:U+0020>" ) ; for ( Utf8 token : parsedContent ) { Assert . assertEquals ( tokens [ j ++ ] , token . toString ( ) ) ; } if ( LINKS [ i ] . length > <NUM_LIT:0> ) { Assert . assertNotNull ( page . getOutlinks ( ) ) ; Assert . assertTrue ( page . getOutlinks ( ) . size ( ) > <NUM_LIT:0> ) ; for ( j = <NUM_LIT:0> ; j < LINKS [ i ] . length ; j ++ ) { Assert . assertEquals ( ANCHORS [ i ] [ j ] , page . getFromOutlinks ( new Utf8 ( URLS [ LINKS [ i ] [ j ] ] ) ) . toString ( ) ) ; } } else { Assert . assertTrue ( page . getOutlinks ( ) == null || page . getOutlinks ( ) . isEmpty ( ) ) ; } } private static void testGetWebPage ( DataStore < String , WebPage > store , String [ ] fields ) throws IOException { createWebPageData ( store ) ; for ( int i = <NUM_LIT:0> ; i < URLS . length ; i ++ ) { WebPage page = store . get ( URLS [ i ] , fields ) ; assertWebPage ( page , i ) ; } } public static void testGetWebPage ( DataStore < String , WebPage > store ) throws IOException { testGetWebPage ( store , WebPage . _ALL_FIELDS ) ; } public static void testGetWebPageDefaultFields ( DataStore < String , WebPage > store ) throws IOException { testGetWebPage ( store , null ) ; } private static void testQueryWebPageSingleKey ( DataStore < String , WebPage > store , String [ ] fields ) throws IOException { createWebPageData ( store ) ; for ( int i = <NUM_LIT:0> ; i < URLS . length ; i ++ ) { Query < String , WebPage > query = store . newQuery ( ) ; query . setFields ( fields ) ; query . setKey ( URLS [ i ] ) ; Result < String , WebPage > result = query . execute ( ) ; Assert . assertTrue ( result . next ( ) ) ; WebPage page = result . get ( ) ; assertWebPage ( page , i ) ; Assert . assertFalse ( result . next ( ) ) ; } } public static void testQueryWebPageSingleKey ( DataStore < String , WebPage > store ) throws IOException { testQueryWebPageSingleKey ( store , WebPage . _ALL_FIELDS ) ; } public static void testQueryWebPageSingleKeyDefaultFields ( DataStore < String , WebPage > store ) throws IOException { testQueryWebPageSingleKey ( store , null ) ; } public static void testQueryWebPageKeyRange ( DataStore < String , WebPage > store , boolean setStartKeys , boolean setEndKeys ) throws IOException { createWebPageData ( store ) ; List < String > sortedUrls = new ArrayList < String > ( ) ; for ( String url : URLS ) { sortedUrls . add ( url ) ; } Collections . sort ( sortedUrls ) ; for ( int i = <NUM_LIT:0> ; i < sortedUrls . size ( ) ; i ++ ) { for ( int j = i ; j < sortedUrls . size ( ) ; j ++ ) { Query < String , WebPage > query = store . newQuery ( ) ; if ( setStartKeys ) query . setStartKey ( sortedUrls . get ( i ) ) ; if ( setEndKeys ) query . setEndKey ( sortedUrls . get ( j ) ) ; Result < String , WebPage > result = query . execute ( ) ; int r = <NUM_LIT:0> ; while ( result . next ( ) ) { WebPage page = result . get ( ) ; assertWebPage ( page , URL_INDEXES . get ( page . getUrl ( ) . toString ( ) ) ) ; r ++ ; } int expectedLength = ( setEndKeys ? j + <NUM_LIT:1> : sortedUrls . size ( ) ) - ( setStartKeys ? i : <NUM_LIT:0> ) ; Assert . assertEquals ( expectedLength , r ) ; if ( ! setEndKeys ) break ; } if ( ! setStartKeys ) break ; } } public static void testQueryWebPages ( DataStore < String , WebPage > store ) throws IOException { testQueryWebPageKeyRange ( store , false , false ) ; } public static void testQueryWebPageStartKey ( DataStore < String , WebPage > store ) throws IOException { testQueryWebPageKeyRange ( store , true , false ) ; } public static void testQueryWebPageEndKey ( DataStore < String , WebPage > store ) throws IOException { testQueryWebPageKeyRange ( store , false , true ) ; } public static void testQueryWebPageKeyRange ( DataStore < String , WebPage > store ) throws IOException { testQueryWebPageKeyRange ( store , true , true ) ; } public static void testQueryWebPageEmptyResults ( DataStore < String , WebPage > store ) throws IOException { createWebPageData ( store ) ; Query < String , WebPage > query = store . newQuery ( ) ; query . setStartKey ( "<STR_LIT>" ) ; query . setEndKey ( "<STR_LIT>" ) ; assertEmptyResults ( query ) ; query = store . newQuery ( ) ; query . setKey ( "<STR_LIT>" ) ; assertEmptyResults ( query ) ; } public static < K , T extends Persistent > void assertEmptyResults ( Query < K , T > query ) throws IOException { assertNumResults ( query , <NUM_LIT:0> ) ; } public static < K , T extends Persistent > void assertNumResults ( Query < K , T > query , long numResults ) throws IOException { Result < K , T > result = query . execute ( ) ; int actualNumResults = <NUM_LIT:0> ; while ( result . next ( ) ) { actualNumResults ++ ; } result . close ( ) ; Assert . assertEquals ( numResults , actualNumResults ) ; } public static void testGetPartitions ( DataStore < String , WebPage > store ) throws IOException { createWebPageData ( store ) ; testGetPartitions ( store , store . newQuery ( ) ) ; } public static void testGetPartitions ( DataStore < String , WebPage > store , Query < String , WebPage > query ) throws IOException { List < PartitionQuery < String , WebPage > > partitions = store . getPartitions ( query ) ; Assert . assertNotNull ( partitions ) ; Assert . assertTrue ( partitions . size ( ) > <NUM_LIT:0> ) ; for ( PartitionQuery < String , WebPage > partition : partitions ) { Assert . assertNotNull ( partition ) ; } assertPartitions ( store , query , partitions ) ; } public static void assertPartitions ( DataStore < String , WebPage > store , Query < String , WebPage > query , List < PartitionQuery < String , WebPage > > partitions ) throws IOException { int count = <NUM_LIT:0> , partitionsCount = <NUM_LIT:0> ; Map < String , Integer > results = new HashMap < String , Integer > ( ) ; Map < String , Integer > partitionResults = new HashMap < String , Integer > ( ) ; Result < String , WebPage > result = store . execute ( query ) ; Assert . assertNotNull ( result ) ; while ( result . next ( ) ) { Assert . assertNotNull ( result . getKey ( ) ) ; Assert . assertNotNull ( result . get ( ) ) ; results . put ( result . getKey ( ) , result . get ( ) . hashCode ( ) ) ; count ++ ; } result . close ( ) ; Assert . assertTrue ( count > <NUM_LIT:0> ) ; Assert . assertEquals ( count , results . size ( ) ) ; for ( PartitionQuery < String , WebPage > partition : partitions ) { Assert . assertNotNull ( partition ) ; result = store . execute ( partition ) ; Assert . assertNotNull ( result ) ; while ( result . next ( ) ) { Assert . assertNotNull ( result . getKey ( ) ) ; Assert . assertNotNull ( result . get ( ) ) ; partitionResults . put ( result . getKey ( ) , result . get ( ) . hashCode ( ) ) ; partitionsCount ++ ; } result . close ( ) ; Assert . assertEquals ( partitionsCount , partitionResults . size ( ) ) ; } Assert . assertTrue ( partitionsCount > <NUM_LIT:0> ) ; Assert . assertEquals ( count , partitionsCount ) ; for ( Map . Entry < String , Integer > r : results . entrySet ( ) ) { Integer p = partitionResults . get ( r . getKey ( ) ) ; Assert . assertNotNull ( p ) ; Assert . assertEquals ( r . getValue ( ) , p ) ; } } public static void testDelete ( DataStore < String , WebPage > store ) throws IOException { WebPageDataCreator . createWebPageData ( store ) ; int deletedSoFar = <NUM_LIT:0> ; for ( String url : URLS ) { Assert . assertTrue ( store . delete ( url ) ) ; store . flush ( ) ; Assert . assertNull ( store . get ( url ) ) ; assertNumResults ( store . newQuery ( ) , URLS . length - ++ deletedSoFar ) ; } } public static void testDeleteByQuery ( DataStore < String , WebPage > store ) throws IOException { Query < String , WebPage > query ; WebPageDataCreator . createWebPageData ( store ) ; query = store . newQuery ( ) ; assertNumResults ( store . newQuery ( ) , URLS . length ) ; store . deleteByQuery ( query ) ; store . flush ( ) ; assertEmptyResults ( store . newQuery ( ) ) ; WebPageDataCreator . createWebPageData ( store ) ; query = store . newQuery ( ) ; query . setFields ( WebPage . _ALL_FIELDS ) ; assertNumResults ( store . newQuery ( ) , URLS . length ) ; store . deleteByQuery ( query ) ; store . flush ( ) ; assertEmptyResults ( store . newQuery ( ) ) ; WebPageDataCreator . createWebPageData ( store ) ; query = store . newQuery ( ) ; query . setKeyRange ( "<STR_LIT:a>" , "<STR_LIT>" ) ; assertNumResults ( store . newQuery ( ) , URLS . length ) ; store . deleteByQuery ( query ) ; store . flush ( ) ; assertEmptyResults ( store . newQuery ( ) ) ; WebPageDataCreator . createWebPageData ( store ) ; query = store . newQuery ( ) ; query . setEndKey ( SORTED_URLS [ NUM_KEYS ] ) ; assertNumResults ( store . newQuery ( ) , URLS . length ) ; store . deleteByQuery ( query ) ; store . flush ( ) ; assertNumResults ( store . newQuery ( ) , URLS . length - ( NUM_KEYS + <NUM_LIT:1> ) ) ; store . truncateSchema ( ) ; } public static void testDeleteByQueryFields ( DataStore < String , WebPage > store ) throws IOException { Query < String , WebPage > query ; WebPageDataCreator . createWebPageData ( store ) ; query = store . newQuery ( ) ; query . setFields ( WebPage . Field . OUTLINKS . getName ( ) , WebPage . Field . PARSED_CONTENT . getName ( ) , WebPage . Field . CONTENT . getName ( ) ) ; assertNumResults ( store . newQuery ( ) , URLS . length ) ; store . deleteByQuery ( query ) ; store . deleteByQuery ( query ) ; store . deleteByQuery ( query ) ; store . flush ( ) ; assertNumResults ( store . newQuery ( ) , URLS . length ) ; for ( int i = <NUM_LIT:0> ; i < SORTED_URLS . length ; i ++ ) { WebPage page = store . get ( SORTED_URLS [ i ] ) ; Assert . assertNotNull ( page ) ; Assert . assertNotNull ( page . getUrl ( ) ) ; Assert . assertEquals ( page . getUrl ( ) . toString ( ) , SORTED_URLS [ i ] ) ; Assert . assertEquals ( <NUM_LIT:0> , page . getOutlinks ( ) . size ( ) ) ; Assert . assertEquals ( <NUM_LIT:0> , page . getParsedContent ( ) . size ( ) ) ; if ( page . getContent ( ) != null ) { System . out . println ( "<STR_LIT>" + page . getUrl ( ) . toString ( ) ) ; System . out . println ( "<STR_LIT>" + page . getContent ( ) . limit ( ) ) ; } else { Assert . assertNull ( page . getContent ( ) ) ; } } WebPageDataCreator . createWebPageData ( store ) ; query = store . newQuery ( ) ; query . setFields ( WebPage . Field . URL . getName ( ) ) ; String startKey = SORTED_URLS [ NUM_KEYS ] ; String endKey = SORTED_URLS [ SORTED_URLS . length - NUM_KEYS ] ; query . setStartKey ( startKey ) ; query . setEndKey ( endKey ) ; assertNumResults ( store . newQuery ( ) , URLS . length ) ; store . deleteByQuery ( query ) ; store . deleteByQuery ( query ) ; store . deleteByQuery ( query ) ; store . flush ( ) ; assertNumResults ( store . newQuery ( ) , URLS . length ) ; for ( int i = <NUM_LIT:0> ; i < URLS . length ; i ++ ) { WebPage page = store . get ( URLS [ i ] ) ; Assert . assertNotNull ( page ) ; if ( URLS [ i ] . compareTo ( startKey ) < <NUM_LIT:0> || URLS [ i ] . compareTo ( endKey ) >= <NUM_LIT:0> ) { assertWebPage ( page , i ) ; } else { Assert . assertNull ( page . getUrl ( ) ) ; Assert . assertNotNull ( page . getOutlinks ( ) ) ; Assert . assertNotNull ( page . getParsedContent ( ) ) ; Assert . assertNotNull ( page . getContent ( ) ) ; Assert . assertTrue ( page . getOutlinks ( ) . size ( ) > <NUM_LIT:0> ) ; Assert . assertTrue ( page . getParsedContent ( ) . size ( ) > <NUM_LIT:0> ) ; } } } private static byte [ ] toByteArray ( ByteBuffer buffer ) { int p = buffer . position ( ) ; int n = buffer . limit ( ) - p ; byte [ ] bytes = new byte [ n ] ; for ( int i = <NUM_LIT:0> ; i < n ; i ++ ) { bytes [ i ] = buffer . get ( p ++ ) ; } return bytes ; } } </s>
|
<s> package org . apache . gora . mock . query ; import org . apache . gora . mock . persistency . MockPersistent ; import org . apache . gora . query . impl . QueryBase ; import org . apache . gora . store . DataStore ; public class MockQuery extends QueryBase < String , MockPersistent > { public MockQuery ( ) { super ( null ) ; } public MockQuery ( DataStore < String , MockPersistent > dataStore ) { super ( dataStore ) ; } } </s>
|
<s> package org . apache . gora . mock . store ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import org . apache . gora . mock . persistency . MockPersistent ; import org . apache . gora . mock . query . MockQuery ; import org . apache . gora . query . PartitionQuery ; import org . apache . gora . query . Query ; import org . apache . gora . query . Result ; import org . apache . gora . query . impl . PartitionQueryImpl ; import org . apache . gora . store . DataStoreFactory ; import org . apache . gora . store . impl . DataStoreBase ; import org . apache . gora . util . GoraException ; import org . apache . hadoop . conf . Configuration ; public class MockDataStore extends DataStoreBase < String , MockPersistent > { public static final int NUM_PARTITIONS = <NUM_LIT:5> ; public static final String [ ] LOCATIONS = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; public static MockDataStore get ( ) { MockDataStore dataStore ; try { dataStore = DataStoreFactory . getDataStore ( MockDataStore . class , String . class , MockPersistent . class , new Configuration ( ) ) ; return dataStore ; } catch ( GoraException ex ) { throw new RuntimeException ( ex ) ; } } public MockDataStore ( ) { } @ Override public String getSchemaName ( ) { return null ; } @ Override public void close ( ) throws IOException { } @ Override public void createSchema ( ) throws IOException { } @ Override public void deleteSchema ( ) throws IOException { } @ Override public void truncateSchema ( ) throws IOException { } @ Override public boolean schemaExists ( ) throws IOException { return true ; } @ Override public boolean delete ( String key ) throws IOException { return false ; } @ Override public long deleteByQuery ( Query < String , MockPersistent > query ) throws IOException { return <NUM_LIT:0> ; } @ Override public Result < String , MockPersistent > execute ( Query < String , MockPersistent > query ) throws IOException { return null ; } @ Override public void flush ( ) throws IOException { } @ Override public MockPersistent get ( String key , String [ ] fields ) throws IOException { return null ; } @ Override public Class < String > getKeyClass ( ) { return String . class ; } @ Override public List < PartitionQuery < String , MockPersistent > > getPartitions ( Query < String , MockPersistent > query ) throws IOException { ArrayList < PartitionQuery < String , MockPersistent > > list = new ArrayList < PartitionQuery < String , MockPersistent > > ( ) ; for ( int i = <NUM_LIT:0> ; i < NUM_PARTITIONS ; i ++ ) { list . add ( new PartitionQueryImpl < String , MockPersistent > ( query , LOCATIONS [ i ] ) ) ; } return list ; } @ Override public Class < MockPersistent > getPersistentClass ( ) { return MockPersistent . class ; } @ Override public MockQuery newQuery ( ) { return new MockQuery ( this ) ; } @ Override public void put ( String key , MockPersistent obj ) throws IOException { } @ Override public void setKeyClass ( Class < String > keyClass ) { } @ Override public void setPersistentClass ( Class < MockPersistent > persistentClass ) { } } </s>
|
<s> package org . apache . gora . mock . persistency ; import org . apache . avro . Schema ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . persistency . StateManager ; import org . apache . gora . persistency . impl . PersistentBase ; public class MockPersistent extends PersistentBase { public static final String FOO = "<STR_LIT:foo>" ; public static final String BAZ = "<STR_LIT:baz>" ; public static final String [ ] _ALL_FIELDS = { FOO , BAZ } ; private int foo ; private int baz ; public MockPersistent ( ) { } public MockPersistent ( StateManager stateManager ) { super ( stateManager ) ; } @ Override public Object get ( int field ) { switch ( field ) { case <NUM_LIT:0> : return foo ; case <NUM_LIT:1> : return baz ; } return null ; } @ Override public void put ( int field , Object value ) { switch ( field ) { case <NUM_LIT:0> : foo = ( Integer ) value ; case <NUM_LIT:1> : baz = ( Integer ) value ; } } @ Override public Schema getSchema ( ) { return Schema . parse ( "<STR_LIT>" ) ; } public void setFoo ( int foo ) { this . foo = foo ; } public void setBaz ( int baz ) { this . baz = baz ; } public int getFoo ( ) { return foo ; } public int getBaz ( ) { return baz ; } @ Override public String getField ( int index ) { return null ; } @ Override public int getFieldIndex ( String field ) { return <NUM_LIT:0> ; } @ Override public String [ ] getFields ( ) { return null ; } @ Override public Persistent newInstance ( StateManager stateManager ) { return new MockPersistent ( stateManager ) ; } } </s>
|
<s> package org . apache . gora . persistency ; import org . apache . avro . Schema ; import org . apache . avro . generic . GenericData ; import org . apache . avro . util . Utf8 ; import org . apache . gora . persistency . ListGenericArray ; import org . junit . Assert ; import org . junit . Test ; public class TestListGenericArray { @ Test public void testHashCode ( ) { ListGenericArray array = new ListGenericArray ( Schema . create ( Schema . Type . STRING ) ) ; boolean stackOverflowError = false ; array . add ( new Utf8 ( "<STR_LIT>" ) ) ; try { int hashCode = array . hashCode ( ) ; } catch ( StackOverflowError e ) { stackOverflowError = true ; } Assert . assertFalse ( stackOverflowError ) ; } @ Test public void testCompareTo ( ) { ListGenericArray array = new ListGenericArray ( Schema . create ( Schema . Type . STRING ) ) ; boolean stackOverflowError = false ; array . add ( new Utf8 ( "<STR_LIT>" ) ) ; try { int compareTo = array . compareTo ( array ) ; } catch ( StackOverflowError e ) { stackOverflowError = true ; } Assert . assertFalse ( stackOverflowError ) ; } } </s>
|
<s> package org . apache . gora . persistency . impl ; import java . io . IOException ; import junit . framework . Assert ; import org . apache . avro . util . Utf8 ; import org . apache . gora . examples . generated . Employee ; import org . apache . gora . mock . persistency . MockPersistent ; import org . apache . gora . persistency . impl . StateManagerImpl ; import org . junit . Before ; import org . junit . Test ; public class TestStateManagerImpl { private StateManagerImpl stateManager ; private MockPersistent persistent ; @ Before public void setUp ( ) { this . stateManager = new StateManagerImpl ( ) ; this . persistent = new MockPersistent ( stateManager ) ; } @ Test public void testDirty ( ) { Assert . assertFalse ( stateManager . isDirty ( persistent ) ) ; stateManager . setDirty ( persistent ) ; Assert . assertTrue ( stateManager . isDirty ( persistent ) ) ; } @ Test public void testDirty2 ( ) { Assert . assertFalse ( stateManager . isDirty ( persistent , <NUM_LIT:0> ) ) ; Assert . assertFalse ( stateManager . isDirty ( persistent , <NUM_LIT:1> ) ) ; stateManager . setDirty ( persistent , <NUM_LIT:0> ) ; Assert . assertTrue ( stateManager . isDirty ( persistent , <NUM_LIT:0> ) ) ; Assert . assertFalse ( stateManager . isDirty ( persistent , <NUM_LIT:1> ) ) ; } @ Test public void testClearDirty ( ) { Assert . assertFalse ( stateManager . isDirty ( persistent ) ) ; stateManager . setDirty ( persistent , <NUM_LIT:0> ) ; stateManager . clearDirty ( persistent ) ; Assert . assertFalse ( this . stateManager . isDirty ( persistent ) ) ; } @ Test public void testReadable ( ) throws IOException { Assert . assertFalse ( stateManager . isReadable ( persistent , <NUM_LIT:0> ) ) ; Assert . assertFalse ( stateManager . isReadable ( persistent , <NUM_LIT:1> ) ) ; stateManager . setReadable ( persistent , <NUM_LIT:0> ) ; Assert . assertTrue ( stateManager . isReadable ( persistent , <NUM_LIT:0> ) ) ; Assert . assertFalse ( stateManager . isReadable ( persistent , <NUM_LIT:1> ) ) ; } @ Test public void testReadable2 ( ) { stateManager = new StateManagerImpl ( ) ; Employee employee = new Employee ( stateManager ) ; Assert . assertFalse ( stateManager . isReadable ( employee , <NUM_LIT:0> ) ) ; Assert . assertFalse ( stateManager . isReadable ( employee , <NUM_LIT:1> ) ) ; employee . setName ( new Utf8 ( "<STR_LIT:foo>" ) ) ; Assert . assertTrue ( stateManager . isReadable ( employee , <NUM_LIT:0> ) ) ; Assert . assertFalse ( stateManager . isReadable ( employee , <NUM_LIT:1> ) ) ; } @ Test public void testClearReadable ( ) { stateManager . setReadable ( persistent , <NUM_LIT:0> ) ; stateManager . clearReadable ( persistent ) ; Assert . assertFalse ( stateManager . isReadable ( persistent , <NUM_LIT:0> ) ) ; } @ Test public void testIsNew ( ) { Assert . assertTrue ( persistent . isNew ( ) ) ; } @ Test public void testNew ( ) { stateManager . setNew ( persistent ) ; Assert . assertTrue ( persistent . isNew ( ) ) ; } @ Test public void testClearNew ( ) { stateManager . clearNew ( persistent ) ; Assert . assertFalse ( persistent . isNew ( ) ) ; } } </s>
|
<s> package org . apache . gora . persistency . impl ; import java . io . IOException ; import java . nio . ByteBuffer ; import org . apache . avro . util . Utf8 ; import org . apache . gora . examples . generated . Employee ; import org . apache . gora . examples . generated . WebPage ; import org . apache . gora . memory . store . MemStore ; import org . apache . gora . store . DataStoreFactory ; import org . apache . gora . store . DataStoreTestUtil ; import org . apache . hadoop . conf . Configuration ; import org . junit . Assert ; import org . junit . Test ; public class TestPersistentBase { @ Test public void testGetFields ( ) { WebPage page = new WebPage ( ) ; String [ ] fields = page . getFields ( ) ; Assert . assertArrayEquals ( WebPage . _ALL_FIELDS , fields ) ; } @ Test public void testGetField ( ) { WebPage page = new WebPage ( ) ; for ( int i = <NUM_LIT:0> ; i < WebPage . _ALL_FIELDS . length ; i ++ ) { String field = page . getField ( i ) ; Assert . assertEquals ( WebPage . _ALL_FIELDS [ i ] , field ) ; } } @ Test public void testGetFieldIndex ( ) { WebPage page = new WebPage ( ) ; for ( int i = <NUM_LIT:0> ; i < WebPage . _ALL_FIELDS . length ; i ++ ) { int index = page . getFieldIndex ( WebPage . _ALL_FIELDS [ i ] ) ; Assert . assertEquals ( i , index ) ; } } @ Test public void testFieldsWithTwoClasses ( ) { WebPage page = new WebPage ( ) ; for ( int i = <NUM_LIT:0> ; i < WebPage . _ALL_FIELDS . length ; i ++ ) { int index = page . getFieldIndex ( WebPage . _ALL_FIELDS [ i ] ) ; Assert . assertEquals ( i , index ) ; } Employee employee = new Employee ( ) ; for ( int i = <NUM_LIT:0> ; i < Employee . _ALL_FIELDS . length ; i ++ ) { int index = employee . getFieldIndex ( Employee . _ALL_FIELDS [ i ] ) ; Assert . assertEquals ( i , index ) ; } } @ Test public void testClear ( ) { WebPage page = new WebPage ( ) ; page . setUrl ( new Utf8 ( "<STR_LIT>" ) ) ; page . addToParsedContent ( new Utf8 ( "<STR_LIT:foo>" ) ) ; page . putToOutlinks ( new Utf8 ( "<STR_LIT:foo>" ) , new Utf8 ( "<STR_LIT:bar>" ) ) ; page . setContent ( ByteBuffer . wrap ( "<STR_LIT>" . getBytes ( ) ) ) ; page . clear ( ) ; Assert . assertNull ( page . getUrl ( ) ) ; Assert . assertEquals ( <NUM_LIT:0> , page . getParsedContent ( ) . size ( ) ) ; Assert . assertEquals ( <NUM_LIT:0> , page . getOutlinks ( ) . size ( ) ) ; Assert . assertNull ( page . getContent ( ) ) ; page . setUrl ( new Utf8 ( "<STR_LIT>" ) ) ; page . addToParsedContent ( new Utf8 ( "<STR_LIT:bar>" ) ) ; page . putToOutlinks ( new Utf8 ( "<STR_LIT:bar>" ) , new Utf8 ( "<STR_LIT:baz>" ) ) ; page . setContent ( ByteBuffer . wrap ( "<STR_LIT>" . getBytes ( ) ) ) ; page = new WebPage ( ) ; page . clear ( ) ; Employee employee = new Employee ( ) ; employee . clear ( ) ; } @ Test public void testClone ( ) throws IOException { @ SuppressWarnings ( "<STR_LIT:unchecked>" ) MemStore < String , Employee > store = DataStoreFactory . getDataStore ( MemStore . class , String . class , Employee . class , new Configuration ( ) ) ; Employee employee = DataStoreTestUtil . createEmployee ( store ) ; Assert . assertEquals ( employee , employee . clone ( ) ) ; } } </s>
|
<s> package at . bartinger . toastplugin ; public final class R { public static final class attr { } public static final class drawable { public static final int icon = <NUM_LIT> ; } public static final class id { public static final int button_cancel = <NUM_LIT> ; public static final int button_ok = <NUM_LIT> ; public static final int edittext = <NUM_LIT> ; public static final int widget30 = <NUM_LIT> ; } public static final class layout { public static final int main = <NUM_LIT> ; } public static final class string { public static final int app_name = <NUM_LIT> ; public static final int hello = <NUM_LIT> ; } } </s>
|
<s> package at . bartinger . toastplugin . activity ; import android . app . Activity ; import android . os . Bundle ; import android . view . View ; import android . view . WindowManager . LayoutParams ; import android . widget . Button ; import android . widget . EditText ; import at . bartinger . toastplugin . SmartPhonePluginHelper ; import at . bartinger . toastplugin . R ; public class ConfigActivity extends Activity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . main ) ; getWindow ( ) . setLayout ( LayoutParams . FILL_PARENT , LayoutParams . WRAP_CONTENT ) ; final EditText text = ( EditText ) findViewById ( R . id . edittext ) ; Button ok = ( Button ) findViewById ( R . id . button_ok ) ; Button cancel = ( Button ) findViewById ( R . id . button_cancel ) ; String data = SmartPhonePluginHelper . getData ( this ) ; if ( ! data . equals ( "<STR_LIT>" ) ) text . setText ( data ) ; ok . setOnClickListener ( new View . OnClickListener ( ) { @ Override public void onClick ( View v ) { String data = text . getText ( ) . toString ( ) ; SmartPhonePluginHelper . setResultAndFinish ( ConfigActivity . this , "<STR_LIT>" , "<STR_LIT>" + data , data ) ; } } ) ; cancel . setOnClickListener ( new View . OnClickListener ( ) { @ Override public void onClick ( View v ) { ConfigActivity . this . finish ( ) ; } } ) ; } } </s>
|
<s> package at . bartinger . toastplugin ; import android . app . Activity ; import android . content . Intent ; public class SmartPhonePluginHelper { public static final int SMART_PHONE_PLUGIN_VERSION = <NUM_LIT:2> ; public static final int SMART_PHONE_PLUGIN_REQUEST_CODE = <NUM_LIT:7> ; public static final String SMART_PHONE_PLUGIN_TITLE = "<STR_LIT>" ; public static final String SMART_PHONE_PLUGIN_INFO = "<STR_LIT>" ; public static final String SMART_PHONE_PLUGIN_DATA = "<STR_LIT>" ; public static final String SMART_PHONE_PLUGIN_TOGGLE_BACK = "<STR_LIT>" ; public static void setResultAndFinish ( Activity activity , String title , String info , String data ) { final Intent intent = activity . getIntent ( ) ; intent . putExtra ( SMART_PHONE_PLUGIN_TITLE , title ) ; intent . putExtra ( SMART_PHONE_PLUGIN_INFO , info ) ; intent . putExtra ( SMART_PHONE_PLUGIN_DATA , data ) ; activity . setResult ( Activity . RESULT_OK , intent ) ; activity . finish ( ) ; } public static String getTitle ( Activity activity ) { String data = "<STR_LIT>" ; if ( activity . getIntent ( ) . hasExtra ( SMART_PHONE_PLUGIN_TITLE ) ) data = activity . getIntent ( ) . getStringExtra ( SMART_PHONE_PLUGIN_TITLE ) ; return data ; } public static String getInfo ( Activity activity ) { String data = "<STR_LIT>" ; if ( activity . getIntent ( ) . hasExtra ( SMART_PHONE_PLUGIN_INFO ) ) data = activity . getIntent ( ) . getStringExtra ( SMART_PHONE_PLUGIN_INFO ) ; return data ; } public static String getData ( Activity activity ) { String data = "<STR_LIT>" ; if ( activity . getIntent ( ) . hasExtra ( SMART_PHONE_PLUGIN_DATA ) ) data = activity . getIntent ( ) . getStringExtra ( SMART_PHONE_PLUGIN_DATA ) ; return data ; } public static boolean isToggleBack ( Activity activity ) { boolean data = false ; if ( activity . getIntent ( ) . hasExtra ( SMART_PHONE_PLUGIN_DATA ) ) data = activity . getIntent ( ) . getBooleanExtra ( SMART_PHONE_PLUGIN_TOGGLE_BACK , false ) ; return data ; } } </s>
|
<s> package at . bartinger . toastplugin ; import android . content . BroadcastReceiver ; import android . content . Context ; import android . content . Intent ; import android . os . Handler ; import android . os . Looper ; import android . widget . Toast ; public class PluginReceiver extends BroadcastReceiver { private Handler handler ; @ Override public void onReceive ( final Context context , Intent intent ) { if ( intent . hasExtra ( SmartPhonePluginHelper . SMART_PHONE_PLUGIN_DATA ) ) { final String data = intent . getStringExtra ( SmartPhonePluginHelper . SMART_PHONE_PLUGIN_DATA ) ; final boolean toggleBack = intent . getBooleanExtra ( SmartPhonePluginHelper . SMART_PHONE_PLUGIN_TOGGLE_BACK , false ) ; handler = new Handler ( Looper . getMainLooper ( ) ) ; handler . post ( new Runnable ( ) { public void run ( ) { Toast . makeText ( context , data , Toast . LENGTH_LONG ) . show ( ) ; } } ) ; } } } </s>
|
<s> package uk . org . openhealthcare ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . Arrays ; import java . util . HashMap ; import java . util . Map ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . SAXException ; import android . content . Context ; import android . os . Environment ; public class GuidelineData { final Map < String , GuidelineItem > map = new HashMap < String , GuidelineItem > ( ) ; public GuidelineData ( Context ctx ) throws IOException , ParserConfigurationException , SAXException { InputStream inp = new FileInputStream ( Environment . getExternalStorageDirectory ( ) . getAbsolutePath ( ) + File . separator + "<STR_LIT>" + File . separator + "<STR_LIT>" ) ; DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; Document doc = null ; try { doc = db . parse ( inp ) ; } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; } NodeList nodeList = doc . getElementsByTagName ( "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < nodeList . getLength ( ) ; i ++ ) { Node node = nodeList . item ( i ) ; Element elem = ( Element ) node ; GuidelineItem item = new GuidelineItem ( ) ; item . name = elem . getElementsByTagName ( "<STR_LIT:title>" ) . item ( <NUM_LIT:0> ) . getFirstChild ( ) . getNodeValue ( ) . trim ( ) ; item . url = elem . getElementsByTagName ( "<STR_LIT:url>" ) . item ( <NUM_LIT:0> ) . getFirstChild ( ) . getNodeValue ( ) . trim ( ) ; item . code = elem . getAttribute ( "<STR_LIT:code>" ) ; item . category = elem . getAttribute ( "<STR_LIT>" ) ; item . subcategory = elem . getAttribute ( "<STR_LIT>" ) ; item . cached = false ; map . put ( item . name , item ) ; } } ; GuidelineItem Get ( String k ) { return map . get ( k ) ; } GuidelineItem GetLoc ( int l ) { Object [ ] objs = map . keySet ( ) . toArray ( ) ; String [ ] items = new String [ objs . length ] ; for ( int i = <NUM_LIT:0> ; i < objs . length ; i ++ ) items [ i ] = objs [ i ] . toString ( ) ; Arrays . sort ( items ) ; return map . get ( items [ l ] ) ; } String [ ] GetKeys ( ) { Object [ ] objs = map . keySet ( ) . toArray ( ) ; String [ ] items = new String [ objs . length ] ; for ( int i = <NUM_LIT:0> ; i < objs . length ; i ++ ) items [ i ] = objs [ i ] . toString ( ) ; Arrays . sort ( items ) ; return items ; } ; } </s>
|
<s> package uk . org . openhealthcare ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . math . BigInteger ; import java . security . MessageDigest ; import java . security . NoSuchAlgorithmException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Calendar ; import java . util . Collections ; import java . util . HashMap ; import java . util . Timer ; import java . util . TimerTask ; import java . lang . Boolean ; import android . net . ConnectivityManager ; import android . net . NetworkInfo ; import android . net . Uri ; import android . os . Bundle ; import android . os . Environment ; import android . os . Handler ; import android . os . StatFs ; import android . util . Log ; import android . view . Gravity ; import android . view . LayoutInflater ; import android . view . MenuItem ; import android . view . View ; import android . view . ViewGroup ; import android . widget . ArrayAdapter ; import android . app . Activity ; import android . app . AlertDialog ; import android . app . ListActivity ; import android . content . ActivityNotFoundException ; import android . content . Context ; import android . content . DialogInterface ; import android . content . Intent ; import android . content . SharedPreferences ; import android . content . pm . PackageManager ; import android . content . res . AssetManager ; import android . graphics . Color ; import android . widget . AdapterView ; import android . widget . AdapterView . OnItemClickListener ; import android . widget . ImageView ; import android . widget . ListView ; import android . widget . SectionIndexer ; import android . widget . TextView ; import android . widget . Toast ; import android . view . Menu ; import android . view . inputmethod . InputMethodManager ; import android . os . AsyncTask ; public class NICEApp extends ListActivity { private static final int PREFERENCES_GROUP_ID = <NUM_LIT:0> ; private static final int SHARE_ID = <NUM_LIT:0> ; private static final int GETALL_ID = <NUM_LIT:1> ; private static final int FEEDBACK_ID = <NUM_LIT:2> ; private static final int SEARCH_ID = <NUM_LIT:3> ; private static final int RELOAD_ID = <NUM_LIT:4> ; private static final int HELP_ID = <NUM_LIT:5> ; private static final int ABOUT_ID = <NUM_LIT:6> ; private static boolean downloadLock = false ; GuidelineData guidelines ; boolean cached [ ] ; int numGuidelines ; int lastOpened ; int lastSuccessfulCheck ; boolean firstrun ; boolean haveConnectedWifi = false ; boolean haveConnectedMobile = false ; boolean section [ ] ; boolean keyboardup = false ; ArrayAdapter < String > arrad ; ArrayAdapter < String > adapter = null ; ListView lv ; @ Override public boolean onCreateOptionsMenu ( Menu menu ) { super . onCreateOptionsMenu ( menu ) ; menu . add ( PREFERENCES_GROUP_ID , SHARE_ID , <NUM_LIT:0> , "<STR_LIT>" ) . setIcon ( android . R . drawable . ic_menu_share ) ; menu . add ( PREFERENCES_GROUP_ID , GETALL_ID , <NUM_LIT:0> , "<STR_LIT>" ) . setIcon ( android . R . drawable . ic_menu_save ) ; menu . add ( PREFERENCES_GROUP_ID , FEEDBACK_ID , <NUM_LIT:0> , "<STR_LIT>" ) . setIcon ( android . R . drawable . ic_menu_send ) ; menu . add ( PREFERENCES_GROUP_ID , SEARCH_ID , <NUM_LIT:0> , "<STR_LIT>" ) . setIcon ( android . R . drawable . ic_menu_search ) ; menu . add ( PREFERENCES_GROUP_ID , RELOAD_ID , <NUM_LIT:0> , "<STR_LIT>" ) . setIcon ( android . R . drawable . ic_menu_rotate ) ; menu . add ( PREFERENCES_GROUP_ID , ABOUT_ID , <NUM_LIT:0> , "<STR_LIT>" ) . setIcon ( android . R . drawable . ic_menu_info_details ) ; return true ; } public boolean onOptionsItemSelected ( MenuItem item ) { switch ( item . getItemId ( ) ) { case SHARE_ID : LayoutInflater inflater = getLayoutInflater ( ) ; View layout = inflater . inflate ( R . layout . toast_layout , ( ViewGroup ) findViewById ( R . id . toast_layout_root ) ) ; ImageView image = ( ImageView ) layout . findViewById ( R . id . image ) ; image . setImageResource ( R . drawable . qrcode ) ; Toast toast = new Toast ( getApplicationContext ( ) ) ; toast . setGravity ( Gravity . CENTER_VERTICAL , <NUM_LIT:0> , <NUM_LIT:0> ) ; toast . setDuration ( Toast . LENGTH_LONG ) ; toast . setView ( layout ) ; toast . show ( ) ; return true ; case HELP_ID : Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; return true ; case FEEDBACK_ID : Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; try { InputStream in = new FileInputStream ( Environment . getExternalStorageDirectory ( ) . getAbsolutePath ( ) + File . separator + "<STR_LIT>" + File . separator + "<STR_LIT>" ) ; OutputStream out = new FileOutputStream ( Environment . getExternalStorageDirectory ( ) . getAbsolutePath ( ) + File . separator + "<STR_LIT>" + File . separator + "<STR_LIT>" ) ; byte [ ] buffer = new byte [ <NUM_LIT> ] ; int read ; while ( ( read = in . read ( buffer ) ) != - <NUM_LIT:1> ) { out . write ( buffer , <NUM_LIT:0> , read ) ; } in . close ( ) ; in = null ; out . flush ( ) ; out . close ( ) ; out = null ; } catch ( IOException e ) { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; } try { downloadXML ( ) ; File file = new File ( Environment . getExternalStorageDirectory ( ) . getAbsolutePath ( ) + File . separator + "<STR_LIT>" + File . separator + "<STR_LIT>" ) ; File cfile = new File ( Environment . getExternalStorageDirectory ( ) . getAbsolutePath ( ) + File . separator + "<STR_LIT>" + File . separator + "<STR_LIT>" ) ; if ( cfile . length ( ) == file . length ( ) ) { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; } else { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; this . finish ( ) ; } } catch ( Exception exc ) { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; } return true ; case ABOUT_ID : Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; return true ; case GETALL_ID : StatFs stat = new StatFs ( Environment . getExternalStorageDirectory ( ) . getPath ( ) ) ; double sdAvailSize = ( double ) stat . getAvailableBlocks ( ) * ( double ) stat . getBlockSize ( ) ; if ( sdAvailSize < <NUM_LIT> ) { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; } else { if ( isNetworkAvailable ( ) ) { if ( haveConnectedWifi ) { AlertDialog ad = new AlertDialog . Builder ( this ) . create ( ) ; ad . setTitle ( "<STR_LIT>" ) ; ad . setMessage ( "<STR_LIT>" ) ; ad . setButton ( "<STR_LIT>" , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { final Toast ShortToast = Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_SHORT ) ; Timer timer = new Timer ( ) ; TimerTask task = new TimerTask ( ) { @ Override public void run ( ) { runOnUiThread ( new Runnable ( ) { @ Override public void run ( ) { ShortToast . cancel ( ) ; } } ) ; } } ; ShortToast . show ( ) ; timer . schedule ( task , <NUM_LIT> ) ; new AsyncDownload ( ) . execute ( guidelines . GetKeys ( ) ) ; dialog . dismiss ( ) ; } } ) ; ad . show ( ) ; } else { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; } } else { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; } } return true ; case SEARCH_ID : closeOptionsMenu ( ) ; Handler handler = new Handler ( ) ; handler . postDelayed ( new Runnable ( ) { public void run ( ) { onSearchRequested ( ) ; } } , <NUM_LIT:1000> ) ; return true ; case RELOAD_ID : Object item1 = getListAdapter ( ) . getItem ( lastOpened ) ; String key = ( String ) item1 ; new AsyncDownload ( ) . execute ( key ) ; return true ; } return false ; } public boolean onSearchRequested ( ) { InputMethodManager imm = ( InputMethodManager ) getSystemService ( Context . INPUT_METHOD_SERVICE ) ; imm . toggleSoftInput ( InputMethodManager . SHOW_FORCED , <NUM_LIT:0> ) ; keyboardup = true ; return false ; } public void onWindowFocusChanged ( boolean hasFocus ) { if ( keyboardup ) { InputMethodManager imm = ( InputMethodManager ) getSystemService ( Context . INPUT_METHOD_SERVICE ) ; imm . toggleSoftInput ( InputMethodManager . HIDE_IMPLICIT_ONLY , <NUM_LIT:0> ) ; keyboardup = false ; } } public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; SharedPreferences settings = getPreferences ( <NUM_LIT:0> ) ; SharedPreferences . Editor editor = settings . edit ( ) ; firstrun = settings . getBoolean ( "<STR_LIT>" , true ) ; lastSuccessfulCheck = settings . getInt ( "<STR_LIT>" , <NUM_LIT:0> ) ; String folderString = pathToStorage ( null ) ; File folder = new File ( folderString ) ; if ( ! folder . exists ( ) ) { folder . mkdir ( ) ; } String targetFile = pathToStorage ( "<STR_LIT>" ) ; boolean exists = ( new File ( targetFile ) ) . exists ( ) ; if ( exists ) { } else { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; CopyAssets ( "<STR_LIT>" ) ; sendBroadcast ( new Intent ( Intent . ACTION_MEDIA_MOUNTED , Uri . parse ( "<STR_LIT>" + Environment . getExternalStorageDirectory ( ) ) ) ) ; firstrun = false ; } if ( isNetworkAvailable ( ) && ( lastSuccessfulCheck != Calendar . DATE ) ) { if ( haveConnectedWifi ) { try { InputStream in = new FileInputStream ( Environment . getExternalStorageDirectory ( ) . getAbsolutePath ( ) + File . separator + "<STR_LIT>" + File . separator + "<STR_LIT>" ) ; OutputStream out = new FileOutputStream ( Environment . getExternalStorageDirectory ( ) . getAbsolutePath ( ) + File . separator + "<STR_LIT>" + File . separator + "<STR_LIT>" ) ; byte [ ] buffer = new byte [ <NUM_LIT> ] ; int read ; while ( ( read = in . read ( buffer ) ) != - <NUM_LIT:1> ) { out . write ( buffer , <NUM_LIT:0> , read ) ; } in . close ( ) ; in = null ; out . flush ( ) ; out . close ( ) ; out = null ; } catch ( IOException e ) { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; } try { downloadXML ( ) ; File file = new File ( Environment . getExternalStorageDirectory ( ) . getAbsolutePath ( ) + File . separator + "<STR_LIT>" + File . separator + "<STR_LIT>" ) ; File cfile = new File ( Environment . getExternalStorageDirectory ( ) . getAbsolutePath ( ) + File . separator + "<STR_LIT>" + File . separator + "<STR_LIT>" ) ; if ( cfile . length ( ) == file . length ( ) ) { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; lastSuccessfulCheck = Calendar . DATE ; editor . putInt ( "<STR_LIT>" , lastSuccessfulCheck ) ; } else { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; lastSuccessfulCheck = Calendar . DATE ; editor . putInt ( "<STR_LIT>" , lastSuccessfulCheck ) ; this . finish ( ) ; } } catch ( Exception exc ) { } } } try { guidelines = new GuidelineData ( this ) ; } catch ( Exception elocal ) { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_LONG ) . show ( ) ; } Object [ ] c = guidelines . GetKeys ( ) ; Arrays . sort ( c ) ; numGuidelines = c . length ; cached = new boolean [ numGuidelines ] ; section = new boolean [ numGuidelines ] ; String lastLetter = "<STR_LIT>" ; int count = numGuidelines ; for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { cached [ i ] = settings . getBoolean ( Integer . toString ( i ) , false ) ; section [ i ] = true ; GuidelineItem item = guidelines . GetLoc ( i ) ; String s = item . name . substring ( <NUM_LIT:0> , <NUM_LIT:1> ) ; if ( lastLetter . equals ( s ) ) { section [ i ] = false ; } lastLetter = s ; } lastOpened = settings . getInt ( "<STR_LIT>" , - <NUM_LIT:1> ) ; new CheckExists ( ) . execute ( guidelines . GetKeys ( ) ) ; final ArrayAdapter < String > arrad = new ColourArray ( this , ( String [ ] ) c ) ; setListAdapter ( arrad ) ; lv = getListView ( ) ; lv . setFastScrollEnabled ( true ) ; lv . setTextFilterEnabled ( true ) ; lv . setOnItemClickListener ( new OnItemClickListener ( ) { @ Override public void onItemClick ( AdapterView < ? > parent , View view , int position , long id ) { Object item = getListAdapter ( ) . getItem ( position ) ; String key = ( String ) item ; new AsyncDownload ( ) . execute ( key ) ; if ( cached [ position ] ) { Toast . makeText ( getApplicationContext ( ) , "<STR_LIT>" , Toast . LENGTH_SHORT ) . show ( ) ; } ; if ( isNetworkAvailable ( ) ) { GuidelineItem item0 = guidelines . Get ( ( String ) item ) ; item0 . cached = true ; lastOpened = position ; lv . invalidateViews ( ) ; } } } ) ; } @ Override protected void onStop ( ) { super . onStop ( ) ; SharedPreferences settings = getPreferences ( <NUM_LIT:0> ) ; SharedPreferences . Editor editor = settings . edit ( ) ; int count = numGuidelines ; for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { editor . putBoolean ( Integer . toString ( i ) , cached [ i ] ) ; } editor . putInt ( "<STR_LIT>" , lastOpened ) ; editor . putInt ( "<STR_LIT>" , lastSuccessfulCheck ) ; editor . putBoolean ( "<STR_LIT>" , firstrun ) ; editor . commit ( ) ; } @ Override protected void onNewIntent ( Intent intent ) { setIntent ( intent ) ; } public String MD5_Hash ( String s ) { MessageDigest m = null ; try { m = MessageDigest . getInstance ( "<STR_LIT>" ) ; } catch ( NoSuchAlgorithmException e ) { e . printStackTrace ( ) ; } m . update ( s . getBytes ( ) , <NUM_LIT:0> , s . length ( ) ) ; String hash = new BigInteger ( <NUM_LIT:1> , m . digest ( ) ) . toString ( <NUM_LIT:16> ) ; return hash ; } public String pathToStorage ( String filename ) { File sdcard = Environment . getExternalStorageDirectory ( ) ; if ( filename != null ) return sdcard . getAbsolutePath ( ) + File . separator + "<STR_LIT>" + File . separator + filename ; return sdcard . getAbsolutePath ( ) + File . separator + "<STR_LIT>" + File . separator ; } public boolean download ( String guideline ) { AsyncTask myDownload = new AsyncDownload ( ) . execute ( guideline ) ; try { Boolean success = ( Boolean ) myDownload . get ( ) ; return success . booleanValue ( ) ; } catch ( InterruptedException e ) { return false ; } catch ( java . util . concurrent . ExecutionException f ) { return false ; } } private class AsyncDownload extends AsyncTask < String , String , Boolean > { protected Boolean doInBackground ( String ... guidelinelist ) { try { int count = guidelinelist . length ; Boolean singlesuccess = Boolean . FALSE ; for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { GuidelineItem item = guidelines . Get ( guidelinelist [ i ] ) ; String url = item . url ; String hash = MD5_Hash ( url ) ; String targetFile = pathToStorage ( hash + "<STR_LIT>" ) ; File file = new File ( targetFile ) ; if ( ! file . exists ( ) ) { if ( isNetworkAvailable ( ) ) { if ( downloadLock ) { publishProgress ( "<STR_LIT>" ) ; return Boolean . FALSE ; } downloadLock = true ; if ( count == <NUM_LIT:1> ) { publishProgress ( "<STR_LIT>" + guidelinelist [ i ] ) ; } else { publishProgress ( "<STR_LIT>" + guidelinelist [ i ] ) ; } Download p = new Download ( ) ; try { p . DownloadFrom ( url , targetFile ) ; singlesuccess = Boolean . TRUE ; if ( ! haveConnectedWifi ) publishProgress ( "<STR_LIT>" ) ; } catch ( Exception exc ) { publishProgress ( "<STR_LIT>" + exc . toString ( ) ) ; } downloadLock = false ; } else { publishProgress ( "<STR_LIT>" ) ; } } else { singlesuccess = Boolean . TRUE ; } } if ( count == <NUM_LIT:1> && singlesuccess && ! downloadLock ) { GuidelineItem item = guidelines . Get ( guidelinelist [ <NUM_LIT:0> ] ) ; String url = item . url ; String hash = MD5_Hash ( url ) ; String targetFile = pathToStorage ( hash + "<STR_LIT>" ) ; File file = new File ( targetFile ) ; Uri path = Uri . fromFile ( file ) ; Intent intent = new Intent ( Intent . ACTION_VIEW ) ; intent . setDataAndType ( path , "<STR_LIT>" ) ; intent . setFlags ( Intent . FLAG_ACTIVITY_CLEAR_TOP ) ; try { startActivity ( intent ) ; } catch ( ActivityNotFoundException e ) { publishProgress ( "<STR_LIT>" ) ; } } new CheckExists ( ) . execute ( guidelines . GetKeys ( ) ) ; if ( count == <NUM_LIT:1> ) return singlesuccess ; return Boolean . TRUE ; } catch ( Exception eee ) { return false ; } } protected void onProgressUpdate ( String ... progress ) { Toast . makeText ( getApplicationContext ( ) , progress [ <NUM_LIT:0> ] , Toast . LENGTH_SHORT ) . show ( ) ; } } private class CheckExists extends AsyncTask < String , String , Boolean > { protected Boolean doInBackground ( String ... guidelinelist ) { int count = guidelinelist . length ; for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { GuidelineItem item = guidelines . Get ( guidelinelist [ i ] ) ; String url = item . url ; String hash = MD5_Hash ( url ) ; String targetFile = pathToStorage ( hash + "<STR_LIT>" ) ; boolean exists = ( new File ( targetFile ) ) . exists ( ) ; if ( exists ) { cached [ i ] = true ; item . cached = true ; } else { cached [ i ] = false ; item . cached = false ; } } publishProgress ( "<STR_LIT>" ) ; return true ; } protected void onProgressUpdate ( String ... progress ) { lv . invalidateViews ( ) ; } } private static class FilesViewHolder { public TextView separator ; public ImageView imageView ; public ImageView imageView2 ; public TextView textView ; public TextView subtitleView ; } public class ColourArray extends ArrayAdapter < String > implements SectionIndexer { HashMap < String , Integer > alphaIndexer ; String [ ] sections ; private final Activity context ; public final String [ ] names ; public ColourArray ( Activity context , String [ ] names ) { super ( context , R . layout . list_item , names ) ; this . context = context ; this . names = names ; alphaIndexer = new HashMap < String , Integer > ( ) ; int size = names . length ; for ( int x = <NUM_LIT:0> ; x < size ; x ++ ) { alphaIndexer . put ( guidelines . GetLoc ( x ) . name . substring ( <NUM_LIT:0> , <NUM_LIT:1> ) , x ) ; } ArrayList < String > sectionList = new ArrayList < String > ( alphaIndexer . keySet ( ) ) ; Collections . sort ( sectionList ) ; sections = new String [ sectionList . size ( ) ] ; sectionList . toArray ( sections ) ; } @ Override public View getView ( int position , View convertView , ViewGroup parent ) { LayoutInflater inflater = context . getLayoutInflater ( ) ; View rowView = inflater . inflate ( R . layout . list_item , null , true ) ; FilesViewHolder holder = new FilesViewHolder ( ) ; holder . textView = ( TextView ) rowView . findViewById ( R . id . label ) ; holder . imageView2 = ( ImageView ) rowView . findViewById ( R . id . icon2 ) ; holder . separator = ( TextView ) rowView . findViewById ( R . id . separator ) ; holder . subtitleView = ( TextView ) rowView . findViewById ( R . id . subtitle ) ; Object itemO = getListAdapter ( ) . getItem ( position ) ; GuidelineItem item = guidelines . Get ( ( String ) itemO ) ; String code = item . code ; String category = item . category ; holder . separator . setText ( item . name . substring ( <NUM_LIT:0> , <NUM_LIT:1> ) ) ; holder . textView . setText ( item . name ) ; holder . subtitleView . setText ( "<STR_LIT>" + code + String . format ( "<STR_LIT>" + ( <NUM_LIT> - item . subcategory . length ( ) - item . code . length ( ) ) + "<STR_LIT:s>" , "<STR_LIT:U+0020>" ) + item . subcategory ) ; if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . cancer ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . cardio ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . neuro ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . gastro ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . ear ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . endocrine ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . eye ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . gynae ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . id ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . ed ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . mental ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . mouth ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . ms ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . endocrine ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . thermo ) ; } if ( category . equals ( "<STR_LIT>" ) ) { holder . imageView2 . setImageResource ( R . drawable . ug ) ; } if ( ! section [ position ] ) holder . separator . setVisibility ( View . GONE ) ; if ( item . cached ) { holder . textView . setTextColor ( Color . rgb ( <NUM_LIT:255> , <NUM_LIT:255> , <NUM_LIT:255> ) ) ; } else { holder . textView . setTextColor ( Color . rgb ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ) ; } if ( position == lastOpened ) { holder . textView . setBackgroundColor ( Color . rgb ( <NUM_LIT:15> , <NUM_LIT:15> , <NUM_LIT> ) ) ; } rowView . setTag ( holder ) ; return rowView ; } public int getPositionForSection ( int section ) { if ( section == <NUM_LIT:0> ) return <NUM_LIT:0> ; else return alphaIndexer . get ( sections [ section - <NUM_LIT:1> ] ) ; } public int getSectionForPosition ( int position ) { return <NUM_LIT:1> ; } public Object [ ] getSections ( ) { return sections ; } } private boolean isNetworkAvailable ( ) { haveConnectedWifi = false ; haveConnectedMobile = false ; ConnectivityManager cm = ( ConnectivityManager ) getSystemService ( Context . CONNECTIVITY_SERVICE ) ; NetworkInfo [ ] netInfo = cm . getAllNetworkInfo ( ) ; for ( NetworkInfo ni : netInfo ) { if ( ni . isConnected ( ) ) { if ( ni . getTypeName ( ) . equalsIgnoreCase ( "<STR_LIT>" ) ) haveConnectedWifi = true ; if ( ni . getTypeName ( ) . equalsIgnoreCase ( "<STR_LIT>" ) ) haveConnectedMobile = true ; } } return haveConnectedWifi || haveConnectedMobile ; } private void CopyAssets ( String path ) { AssetManager assetManager = this . getAssets ( ) ; String assets [ ] = null ; try { Log . i ( "<STR_LIT>" , "<STR_LIT>" + path ) ; assets = assetManager . list ( path ) ; if ( assets . length == <NUM_LIT:0> ) { copyFile ( path ) ; } else { String fullPath = pathToStorage ( path ) ; Log . i ( "<STR_LIT>" , "<STR_LIT>" + fullPath ) ; File dir = new File ( fullPath ) ; if ( ! dir . exists ( ) && ! path . startsWith ( "<STR_LIT>" ) && ! path . startsWith ( "<STR_LIT>" ) && ! path . startsWith ( "<STR_LIT>" ) ) if ( ! dir . mkdirs ( ) ) ; Log . i ( "<STR_LIT>" , "<STR_LIT>" + fullPath ) ; for ( int i = <NUM_LIT:0> ; i < assets . length ; ++ i ) { String p ; if ( path . equals ( "<STR_LIT>" ) ) p = "<STR_LIT>" ; else p = path + "<STR_LIT:/>" ; if ( ! path . startsWith ( "<STR_LIT>" ) && ! path . startsWith ( "<STR_LIT>" ) && ! path . startsWith ( "<STR_LIT>" ) ) CopyAssets ( p + assets [ i ] ) ; } } } catch ( IOException ex ) { Log . e ( "<STR_LIT>" , "<STR_LIT>" , ex ) ; } } private void copyFile ( String filename ) { AssetManager assetManager = this . getAssets ( ) ; InputStream in = null ; OutputStream out = null ; String newFileName = null ; try { Log . i ( "<STR_LIT>" , "<STR_LIT>" + filename ) ; in = assetManager . open ( filename ) ; newFileName = pathToStorage ( filename ) ; out = new FileOutputStream ( newFileName ) ; byte [ ] buffer = new byte [ <NUM_LIT> ] ; int read ; while ( ( read = in . read ( buffer ) ) != - <NUM_LIT:1> ) { out . write ( buffer , <NUM_LIT:0> , read ) ; } in . close ( ) ; in = null ; out . flush ( ) ; out . close ( ) ; out = null ; } catch ( Exception e ) { Log . e ( "<STR_LIT>" , "<STR_LIT>" + newFileName ) ; Log . e ( "<STR_LIT>" , "<STR_LIT>" + e . toString ( ) ) ; } } public boolean canDisplayPdf ( ) { PackageManager packageManager = this . getPackageManager ( ) ; Intent testIntent = new Intent ( Intent . ACTION_VIEW ) ; testIntent . setType ( "<STR_LIT>" ) ; if ( packageManager . queryIntentActivities ( testIntent , PackageManager . MATCH_DEFAULT_ONLY ) . size ( ) > <NUM_LIT:0> ) { return true ; } else { return false ; } } public boolean downloadXML ( ) { AsyncTask < String , String , Boolean > myDownload = new AsyncDownloadXML ( ) . execute ( ) ; try { Boolean success = ( Boolean ) myDownload . get ( ) ; return success . booleanValue ( ) ; } catch ( InterruptedException e ) { return false ; } catch ( java . util . concurrent . ExecutionException f ) { return false ; } } private class AsyncDownloadXML extends AsyncTask < String , String , Boolean > { protected Boolean doInBackground ( String ... guidelinelist ) { String url = "<STR_LIT>" ; String targetFile = Environment . getExternalStorageDirectory ( ) . getAbsolutePath ( ) + File . separator + "<STR_LIT>" + File . separator + "<STR_LIT>" ; Download p = new Download ( ) ; try { p . DownloadFrom ( url , targetFile ) ; } catch ( Exception exc ) { publishProgress ( "<STR_LIT>" ) ; } return false ; } } protected void onProgressUpdate ( String ... progress ) { Toast . makeText ( getApplicationContext ( ) , progress [ <NUM_LIT:0> ] , Toast . LENGTH_SHORT ) . show ( ) ; } } </s>
|
<s> package uk . org . openhealthcare ; public class GuidelineItem { public String name ; public String url ; public String code ; public String category ; public String subcategory ; public boolean cached ; } </s>
|
<s> package uk . org . openhealthcare ; import java . io . BufferedInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . net . URLConnection ; public class Download { private final int SOCKET_TIMEOUT = <NUM_LIT> ; public void DownloadFrom ( String url , String target ) throws IOException { URL murl = new URL ( url ) ; URLConnection connection = murl . openConnection ( ) ; byte [ ] buff = new byte [ <NUM_LIT:5> * <NUM_LIT> ] ; int len ; connection . setReadTimeout ( SOCKET_TIMEOUT ) ; connection . setConnectTimeout ( SOCKET_TIMEOUT ) ; InputStream is = connection . getInputStream ( ) ; BufferedInputStream inStream = new BufferedInputStream ( is , <NUM_LIT> * <NUM_LIT:5> ) ; FileOutputStream outStream = new FileOutputStream ( target ) ; while ( ( len = inStream . read ( buff ) ) != - <NUM_LIT:1> ) { outStream . write ( buff , <NUM_LIT:0> , len ) ; } outStream . flush ( ) ; outStream . close ( ) ; inStream . close ( ) ; } } </s>
|
<s> package org . dspace . googlestats ; import org . apache . log4j . Logger ; import org . dspace . content . Bitstream ; import org . dspace . content . Collection ; import org . dspace . content . Item ; import org . dspace . content . ItemIterator ; import org . dspace . core . Constants ; import java . io . UnsupportedEncodingException ; import java . sql . SQLException ; import java . util . Collections ; import java . util . LinkedList ; import java . util . List ; public class GoogleAnalyticsCollectionStats { private static final Logger log = Logger . getLogger ( GoogleAnalyticsCollectionStats . class ) ; private int totalViews ; private int totalDownloads ; private final List < FileFeed > topViews ; private final List < FileFeed > topDownloads ; public List < FileFeed > getTopDownloads ( ) { return topDownloads ; } public List < FileFeed > getTopViews ( ) { return topViews ; } public int getTotalDownloads ( ) { return totalDownloads ; } public int getTotalViews ( ) { return totalViews ; } public GoogleAnalyticsCollectionStats ( Collection collection ) throws SQLException { topViews = new LinkedList < FileFeed > ( ) ; topDownloads = new LinkedList < FileFeed > ( ) ; ItemIterator itemItr = collection . getAllItems ( ) ; while ( itemItr . hasNext ( ) ) { Item item = itemItr . next ( ) ; String path = "<STR_LIT>" + item . getHandle ( ) ; String count = ItemViewCounter . getPageCount ( path ) ; int views = <NUM_LIT:0> ; if ( count . length ( ) > <NUM_LIT:0> ) { views = Integer . parseInt ( count ) ; } totalViews = totalViews + views ; FileFeed ff = new FileFeed ( item , path , views ) ; topViews . add ( ff ) ; Collections . sort ( topViews ) ; String bitpath = "<STR_LIT>" + item . getHandle ( ) + "<STR_LIT:/>" ; Bitstream [ ] bitstreams = item . getNonInternalBitstreams ( ) ; for ( Bitstream bitstream : bitstreams ) { String encodedName = null ; try { encodedName = encodeBitstreamName ( bitstream . getName ( ) , Constants . DEFAULT_ENCODING ) ; } catch ( UnsupportedEncodingException e ) { log . error ( e ) ; } String bitstreamPath = bitpath + bitstream . getSequenceID ( ) + "<STR_LIT:/>" + encodedName ; String downloadCount = ItemDownloadCounter . getPageCount ( bitstreamPath ) ; int downloads = <NUM_LIT:0> ; if ( downloadCount . length ( ) > <NUM_LIT:0> ) { downloads = Integer . parseInt ( downloadCount ) ; } totalDownloads = totalDownloads + downloads ; FileFeed bf = new FileFeed ( bitstream , path , downloads ) ; { topDownloads . add ( bf ) ; } } Collections . sort ( topDownloads ) ; } } private static String encodeBitstreamName ( String stringIn , String encoding ) throws java . io . UnsupportedEncodingException { StringBuilder out = new StringBuilder ( ) ; final String [ ] pctEncoding = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; byte [ ] bytes = stringIn . getBytes ( encoding ) ; for ( byte aByte : bytes ) { if ( ( aByte >= '<CHAR_LIT:A>' && aByte <= '<CHAR_LIT:Z>' ) || ( aByte >= '<CHAR_LIT:a>' && aByte <= '<CHAR_LIT>' ) || ( aByte >= '<CHAR_LIT:0>' && aByte <= '<CHAR_LIT:9>' ) || aByte == '<CHAR_LIT:->' || aByte == '<CHAR_LIT:.>' || aByte == '<CHAR_LIT:_>' || aByte == '<CHAR_LIT>' || aByte == '<CHAR_LIT:/>' ) { out . append ( ( char ) aByte ) ; } else if ( aByte >= <NUM_LIT:0> ) { out . append ( pctEncoding [ aByte ] ) ; } else { out . append ( pctEncoding [ <NUM_LIT> + aByte ] ) ; } } log . debug ( "<STR_LIT>" + stringIn + "<STR_LIT>" + out . toString ( ) + "<STR_LIT:\">" ) ; return out . toString ( ) ; } } </s>
|
<s> package org . dspace . googlestats ; import com . google . gdata . client . analytics . AnalyticsService ; import com . google . gdata . data . analytics . DataEntry ; import com . google . gdata . data . analytics . DataFeed ; import com . google . gdata . data . analytics . Metric ; import com . google . gdata . util . AuthenticationException ; import com . google . gdata . util . ServiceException ; import org . apache . commons . cli . * ; import org . apache . log4j . Logger ; import org . dspace . core . ConfigurationManager ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . net . MalformedURLException ; import java . net . URL ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import java . util . Date ; import java . util . GregorianCalendar ; import java . util . Properties ; import java . util . regex . Pattern ; public class ItemDownloadCounter { private static final Logger log = Logger . getLogger ( ItemDownloadCounter . class ) ; private static Properties counts ; private static Date lastloaded ; private static String filename ; private static void init ( ) { Calendar yesterday = Calendar . getInstance ( ) ; yesterday . add ( Calendar . DATE , - <NUM_LIT:1> ) ; lastloaded = yesterday . getTime ( ) ; filename = ConfigurationManager . getProperty ( "<STR_LIT>" ) + System . getProperty ( "<STR_LIT>" ) + ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; counts = new Properties ( ) ; loadCounter ( ) ; } public static String getPageCount ( String page ) { if ( lastloaded == null ) { init ( ) ; } loadCounter ( ) ; if ( page == null ) { page = "<STR_LIT>" ; } String count = counts . getProperty ( page ) ; if ( count != null ) { return count ; } return "<STR_LIT>" ; } private static void loadCounter ( ) { Calendar hourago = Calendar . getInstance ( ) ; hourago . add ( Calendar . HOUR , - <NUM_LIT:1> ) ; if ( lastloaded . before ( hourago . getTime ( ) ) ) { try { counts . load ( new FileInputStream ( new File ( filename ) ) ) ; lastloaded = Calendar . getInstance ( ) . getTime ( ) ; } catch ( Exception e ) { log . warn ( "<STR_LIT>" + filename ) ; } } } public static void main ( String [ ] args ) { CommandLineParser parser = new PosixParser ( ) ; Options options = new Options ( ) ; options . addOption ( "<STR_LIT:m>" , "<STR_LIT>" , true , "<STR_LIT>" ) ; options . addOption ( "<STR_LIT:y>" , "<STR_LIT>" , true , "<STR_LIT>" ) ; options . addOption ( "<STR_LIT:b>" , "<STR_LIT>" , true , "<STR_LIT>" ) ; try { CommandLine line = parser . parse ( options , args ) ; if ( line . hasOption ( "<STR_LIT:m>" ) && line . hasOption ( "<STR_LIT:y>" ) ) { populateCounter ( line . getOptionValue ( "<STR_LIT:m>" ) , line . getOptionValue ( "<STR_LIT:y>" ) ) ; } else if ( line . hasOption ( "<STR_LIT:b>" ) ) { String startDate = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" + startDate ) ; String [ ] dateParts = startDate . split ( "<STR_LIT:->" ) ; if ( dateParts . length == <NUM_LIT:3> ) { int year = Integer . parseInt ( dateParts [ <NUM_LIT:0> ] ) ; int month = Integer . parseInt ( dateParts [ <NUM_LIT:1> ] ) - <NUM_LIT:1> ; int day = Integer . parseInt ( dateParts [ <NUM_LIT:2> ] ) ; Calendar today = new GregorianCalendar ( ) ; Calendar startCal = new GregorianCalendar ( year , month , day ) ; while ( startCal . before ( today ) ) { populateCounter ( "<STR_LIT>" + startCal . get ( Calendar . MONTH ) , "<STR_LIT>" + startCal . get ( Calendar . YEAR ) ) ; startCal . add ( Calendar . MONTH , <NUM_LIT:1> ) ; } } else { System . err . println ( "<STR_LIT>" ) ; } } else { populateCounter ( ) ; } } catch ( ParseException e ) { e . printStackTrace ( ) ; } } private static void populateCounter ( ) { try { String siteid = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; String handle = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; String filename = ConfigurationManager . getProperty ( "<STR_LIT>" ) + System . getProperty ( "<STR_LIT>" ) + ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; AnalyticsService as = GoogleAnalyticsConnector . getConnection ( ) ; System . out . println ( "<STR_LIT>" + siteid ) ; System . out . println ( "<STR_LIT>" + handle ) ; System . out . println ( "<STR_LIT>" + filename ) ; Properties counts = new Properties ( ) ; URL queryUrl ; int i = <NUM_LIT:1> ; boolean found = true ; int total = <NUM_LIT:0> ; String baseUrl = "<STR_LIT>" ; Calendar today = Calendar . getInstance ( ) ; SimpleDateFormat format = new SimpleDateFormat ( "<STR_LIT>" ) ; String endDate = format . format ( today . getTime ( ) ) ; today . roll ( Calendar . YEAR , - <NUM_LIT:1> ) ; String startDate = format . format ( today . getTime ( ) ) ; while ( found ) { found = false ; try { String q = baseUrl + "<STR_LIT>" + i + "<STR_LIT>" + siteid + "<STR_LIT>" + startDate + "<STR_LIT>" + endDate + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + handle ; queryUrl = new URL ( q ) ; } catch ( MalformedURLException e ) { System . err . println ( "<STR_LIT>" + baseUrl ) ; return ; } DataFeed dataFeed ; try { dataFeed = as . getFeed ( queryUrl , DataFeed . class ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; return ; } catch ( ServiceException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; return ; } for ( DataEntry entry : dataFeed . getEntries ( ) ) { String id = entry . getId ( ) . substring ( <NUM_LIT> ) ; id = id . substring ( <NUM_LIT:1> , id . indexOf ( '<CHAR_LIT>' ) ) ; for ( Metric metric : entry . getMetrics ( ) ) { counts . put ( id , metric . getValue ( ) ) ; total = total + Integer . parseInt ( metric . getValue ( ) ) ; } found = true ; } i = i + <NUM_LIT:1000> ; } counts . put ( "<STR_LIT>" , "<STR_LIT>" + total ) ; counts . store ( new FileOutputStream ( filename ) , null ) ; System . out . println ( "<STR_LIT>" + total + "<STR_LIT>" + filename ) ; } catch ( AuthenticationException e ) { System . err . println ( "<STR_LIT>" + e ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" + filename ) ; } } private static void populateCounter ( String endMonth , String endYear ) { try { System . out . println ( "<STR_LIT>" + endMonth + "<STR_LIT>" + endYear ) ; String siteid = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; String handle = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; String filename = ConfigurationManager . getProperty ( "<STR_LIT>" ) + System . getProperty ( "<STR_LIT>" ) + ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) + "<STR_LIT:_>" + endMonth + "<STR_LIT:_>" + endYear ; AnalyticsService as = GoogleAnalyticsConnector . getConnection ( ) ; System . out . println ( "<STR_LIT>" + siteid ) ; System . out . println ( "<STR_LIT>" + handle ) ; System . out . println ( "<STR_LIT>" + filename ) ; Properties counts = new Properties ( ) ; URL queryUrl ; int i = <NUM_LIT:1> ; boolean found = true ; int total = <NUM_LIT:0> ; String baseUrl = "<STR_LIT>" ; SimpleDateFormat format = new SimpleDateFormat ( "<STR_LIT>" ) ; Calendar endCal = Calendar . getInstance ( ) ; endCal . set ( Calendar . MONTH , Integer . valueOf ( endMonth ) ) ; endCal . set ( Calendar . YEAR , Integer . valueOf ( endYear ) ) ; endCal . set ( Calendar . DAY_OF_MONTH , <NUM_LIT:1> ) ; String endDate = format . format ( endCal . getTime ( ) ) ; endCal . roll ( Calendar . MONTH , - <NUM_LIT:1> ) ; String startDate = format . format ( endCal . getTime ( ) ) ; while ( found ) { found = false ; try { String q = baseUrl + "<STR_LIT>" + i + "<STR_LIT>" + siteid + "<STR_LIT>" + startDate + "<STR_LIT>" + endDate + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + handle ; queryUrl = new URL ( q ) ; } catch ( MalformedURLException e ) { System . err . println ( "<STR_LIT>" + baseUrl ) ; return ; } DataFeed dataFeed ; try { dataFeed = as . getFeed ( queryUrl , DataFeed . class ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; return ; } catch ( ServiceException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; return ; } for ( DataEntry entry : dataFeed . getEntries ( ) ) { String id = entry . getId ( ) . substring ( <NUM_LIT> ) ; id = id . substring ( <NUM_LIT:1> , id . indexOf ( '<CHAR_LIT>' ) ) ; for ( Metric metric : entry . getMetrics ( ) ) { counts . put ( id , metric . getValue ( ) ) ; total = total + Integer . parseInt ( metric . getValue ( ) ) ; } found = true ; } i = i + <NUM_LIT:1000> ; } counts . put ( "<STR_LIT>" , "<STR_LIT>" + total ) ; counts . store ( new FileOutputStream ( filename ) , null ) ; System . out . println ( "<STR_LIT>" + total + "<STR_LIT>" + filename ) ; } catch ( AuthenticationException e ) { System . err . println ( "<STR_LIT>" + e ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" + filename ) ; } } } </s>
|
<s> package org . dspace . googlestats ; import com . google . gdata . client . analytics . AnalyticsService ; import com . google . gdata . data . analytics . DataEntry ; import com . google . gdata . data . analytics . DataFeed ; import com . google . gdata . data . analytics . Dimension ; import com . google . gdata . util . ServiceException ; import org . apache . log4j . Logger ; import org . dspace . content . Collection ; import org . dspace . content . Community ; import org . dspace . content . DSpaceObject ; import org . dspace . core . ConfigurationManager ; import org . dspace . core . Context ; import java . io . IOException ; import java . net . MalformedURLException ; import java . net . URL ; import java . sql . SQLException ; import java . util . LinkedList ; import java . util . List ; public class GoogleQueryManager { private static Logger log = Logger . getLogger ( GoogleQueryManager . class ) ; private DataFeed feed ; public DataFeed queryViewDSpaceMonth ( String startDate , String endDate ) { URL queryUrl ; String baseUrl = GoogleAnalyticsAccount . getInstance ( ) . getDataUrl ( ) ; try { String q = baseUrl + "<STR_LIT>" + startDate + "<STR_LIT>" + endDate + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + GoogleAnalyticsAccount . getInstance ( ) . getSiteId ( ) ; queryUrl = new URL ( q ) ; log . info ( "<STR_LIT>" + q ) ; AnalyticsService as = GoogleAnalyticsConnector . getConnection ( ) ; feed = as . getFeed ( queryUrl , DataFeed . class ) ; } catch ( MalformedURLException e ) { log . error ( "<STR_LIT>" + baseUrl ) ; } catch ( IOException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( ServiceException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } return feed ; } public DataFeed queryBitstreamViewMonth ( String startDate , String endDate ) { URL queryUrl ; String baseUrl = GoogleAnalyticsAccount . getInstance ( ) . getDataUrl ( ) ; try { String q = baseUrl + "<STR_LIT>" + startDate + "<STR_LIT>" + endDate + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + GoogleAnalyticsAccount . getInstance ( ) . getSiteId ( ) ; queryUrl = new URL ( q ) ; log . info ( "<STR_LIT>" + q ) ; AnalyticsService as = GoogleAnalyticsConnector . getConnection ( ) ; feed = as . getFeed ( queryUrl , DataFeed . class ) ; } catch ( MalformedURLException e ) { log . error ( "<STR_LIT>" + baseUrl ) ; } catch ( IOException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( ServiceException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } return feed ; } public DataFeed queryViewDSpaceMonth ( DSpaceObject dso , String startDate , String endDate , AnalyticsService as ) { URL queryUrl ; String baseUrl = GoogleAnalyticsAccount . getInstance ( ) . getDataUrl ( ) ; try { String q = baseUrl + "<STR_LIT>" + startDate + "<STR_LIT>" + endDate + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + GoogleAnalyticsAccount . getInstance ( ) . getSiteId ( ) + "<STR_LIT>" + dso . getHandle ( ) + "<STR_LIT:$>" ; queryUrl = new URL ( q ) ; log . info ( "<STR_LIT>" + q ) ; as = GoogleAnalyticsConnector . getConnection ( ) ; feed = as . getFeed ( queryUrl , DataFeed . class ) ; } catch ( MalformedURLException e ) { log . error ( "<STR_LIT>" + baseUrl ) ; } catch ( IOException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( ServiceException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } return feed ; } public DataFeed queryBitstreamViewMonth ( DSpaceObject dso , String startDate , String endDate ) { URL queryUrl ; String baseUrl = GoogleAnalyticsAccount . getInstance ( ) . getDataUrl ( ) ; log . info ( "<STR_LIT>" + baseUrl ) ; try { String q = baseUrl + "<STR_LIT>" + startDate + "<STR_LIT>" + endDate + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + dso . getHandle ( ) + "<STR_LIT>" + GoogleAnalyticsAccount . getInstance ( ) . getSiteId ( ) ; queryUrl = new URL ( q ) ; log . info ( "<STR_LIT>" + q ) ; AnalyticsService as = GoogleAnalyticsConnector . getConnection ( ) ; feed = as . getFeed ( queryUrl , DataFeed . class ) ; } catch ( MalformedURLException e ) { log . error ( "<STR_LIT>" + baseUrl ) ; } catch ( IOException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( ServiceException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } return feed ; } public DataFeed queryTopPages ( String startDate , String endDate ) { URL queryUrl ; String baseUrl = GoogleAnalyticsAccount . getInstance ( ) . getDataUrl ( ) ; try { String q = baseUrl + "<STR_LIT>" + startDate + "<STR_LIT>" + endDate + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + GoogleAnalyticsAccount . getInstance ( ) . getSiteId ( ) ; queryUrl = new URL ( q ) ; log . info ( "<STR_LIT>" + q ) ; AnalyticsService as = GoogleAnalyticsConnector . getConnection ( ) ; feed = as . getFeed ( queryUrl , DataFeed . class ) ; } catch ( MalformedURLException e ) { log . error ( "<STR_LIT>" + baseUrl ) ; } catch ( IOException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( ServiceException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } return feed ; } public DataFeed queryTopItems ( String startDate , String endDate , Context context ) { URL queryUrl ; String baseUrl = GoogleAnalyticsAccount . getInstance ( ) . getDataUrl ( ) ; ; try { String handlePrefix = ConfigurationManager . getProperty ( "<STR_LIT>" ) ; log . info ( "<STR_LIT>" + handlePrefix ) ; Collection [ ] colls = Collection . findAll ( context ) ; Community [ ] comms = Community . findAll ( context ) ; LinkedList < String > collHandles = new LinkedList < String > ( ) ; LinkedList < String > commHandles = new LinkedList < String > ( ) ; for ( Collection coll : colls ) { String handle = coll . getHandle ( ) ; log . info ( "<STR_LIT>" + coll . getHandle ( ) ) ; collHandles . add ( handle ) ; } for ( Community comm : comms ) { String handle = comm . getHandle ( ) ; commHandles . add ( handle ) ; } String q = baseUrl + "<STR_LIT>" + startDate + "<STR_LIT>" + endDate + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + GoogleAnalyticsAccount . getInstance ( ) . getSiteId ( ) ; queryUrl = new URL ( q ) ; log . info ( "<STR_LIT>" + q ) ; AnalyticsService as = GoogleAnalyticsConnector . getConnection ( ) ; feed = as . getFeed ( queryUrl , DataFeed . class ) ; List < DataEntry > entries = feed . getEntries ( ) ; for ( DataEntry entry : entries ) { Dimension dimension = entry . getDimension ( "<STR_LIT>" ) ; String handle = dimension . getValue ( ) ; handle = handle . substring ( handle . indexOf ( "<STR_LIT>" ) + <NUM_LIT:8> , handle . length ( ) ) ; if ( collHandles . contains ( handle ) ) { Dimension di = new Dimension ( "<STR_LIT>" , "<STR_LIT>" ) ; entry . addDimension ( di ) ; } else if ( commHandles . contains ( handle ) ) { Dimension di = new Dimension ( "<STR_LIT>" , "<STR_LIT>" ) ; entry . addDimension ( di ) ; } else { Dimension di = new Dimension ( "<STR_LIT>" , "<STR_LIT>" ) ; entry . addDimension ( di ) ; } } } catch ( MalformedURLException e ) { log . error ( "<STR_LIT>" + baseUrl ) ; } catch ( IOException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( ServiceException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( SQLException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; e . printStackTrace ( ) ; } return feed ; } public DataFeed queryTopDownloads ( String startDate , String endDate ) { URL queryUrl ; String baseUrl = GoogleAnalyticsAccount . getInstance ( ) . getDataUrl ( ) ; try { String q = baseUrl + "<STR_LIT>" + startDate + "<STR_LIT>" + endDate + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + GoogleAnalyticsAccount . getInstance ( ) . getSiteId ( ) ; queryUrl = new URL ( q ) ; log . info ( "<STR_LIT>" + q ) ; AnalyticsService as = GoogleAnalyticsConnector . getConnection ( ) ; feed = as . getFeed ( queryUrl , DataFeed . class ) ; } catch ( MalformedURLException e ) { log . error ( "<STR_LIT>" + baseUrl ) ; } catch ( IOException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( ServiceException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } return feed ; } public DataFeed queryTopCountries ( String startDate , String endDate ) { URL queryUrl ; String baseUrl = GoogleAnalyticsAccount . getInstance ( ) . getDataUrl ( ) ; try { String q = baseUrl + "<STR_LIT>" + startDate + "<STR_LIT>" + endDate + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + GoogleAnalyticsAccount . getInstance ( ) . getSiteId ( ) ; queryUrl = new URL ( q ) ; log . info ( "<STR_LIT>" + q ) ; AnalyticsService as = GoogleAnalyticsConnector . getConnection ( ) ; feed = as . getFeed ( queryUrl , DataFeed . class ) ; } catch ( MalformedURLException e ) { log . error ( "<STR_LIT>" + baseUrl ) ; } catch ( IOException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( ServiceException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; } return feed ; } } </s>
|
<s> package org . dspace . googlestats ; import org . dspace . content . DSpaceObject ; public class FileFeed implements Comparable { private final DSpaceObject dso ; private final String path ; private final int views ; public FileFeed ( DSpaceObject dso , String path , int views ) { this . dso = dso ; this . path = path ; this . views = views ; } public DSpaceObject getObject ( ) { return dso ; } public int getViews ( ) { return views ; } public String getPath ( ) { return path ; } @ Override public int hashCode ( ) { int result = dso != null ? dso . hashCode ( ) : <NUM_LIT:0> ; result = <NUM_LIT:31> * result + ( path != null ? path . hashCode ( ) : <NUM_LIT:0> ) ; result = <NUM_LIT:31> * result + views ; return result ; } @ Override public String toString ( ) { return "<STR_LIT>" + "<STR_LIT>" + dso + "<STR_LIT>" + path + '<STR_LIT>' + "<STR_LIT>" + views + '<CHAR_LIT:}>' ; } public int compareTo ( Object o ) { final int BEFORE = - <NUM_LIT:1> ; final int EQUAL = <NUM_LIT:0> ; final int AFTER = <NUM_LIT:1> ; if ( ! ( o instanceof FileFeed ) ) { return AFTER ; } else { FileFeed aThat = ( FileFeed ) o ; if ( this . views < aThat . views ) { return AFTER ; } else if ( this . views > aThat . views ) { return BEFORE ; } else { return EQUAL ; } } } } </s>
|
<s> package org . dspace . googlestats ; import com . google . gdata . client . GoogleAuthTokenFactory ; import com . google . gdata . client . analytics . AnalyticsService ; import com . google . gdata . data . analytics . AccountFeed ; import com . google . gdata . util . AuthenticationException ; import com . google . gdata . util . ServiceException ; import org . apache . log4j . Logger ; import java . io . IOException ; import java . net . URL ; public class GoogleAnalyticsConnector { private static final Logger log = Logger . getLogger ( GoogleAnalyticsConnector . class ) ; protected static AccountFeed getAvailableAccounts ( AnalyticsService myService ) throws IOException , ServiceException { URL feedUrl = new URL ( GoogleAnalyticsAccount . getInstance ( ) . getDataUrl ( ) ) ; return myService . getFeed ( feedUrl , AccountFeed . class ) ; } public static AnalyticsService getConnection ( ) throws AuthenticationException { AnalyticsService as = new AnalyticsService ( "<STR_LIT>" ) ; try { as . setUserCredentials ( GoogleAnalyticsAccount . getInstance ( ) . getUsername ( ) , GoogleAnalyticsAccount . getInstance ( ) . getPassword ( ) ) ; GoogleAuthTokenFactory . UserToken auth_token = ( GoogleAuthTokenFactory . UserToken ) as . getAuthTokenFactory ( ) . getAuthToken ( ) ; String token = auth_token . getValue ( ) ; log . info ( "<STR_LIT>" + token ) ; return as ; } catch ( AuthenticationException e ) { log . error ( "<STR_LIT>" + e . getMessage ( ) ) ; throw e ; } } } </s>
|
<s> package org . dspace . googlestats ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . * ; public class GoogleAnalyticsUtils { public static List testDate ( String startDate , String endDate , String gaStartDate ) { List < String > dateErrors = new ArrayList < String > ( ) ; SimpleDateFormat sdf = new SimpleDateFormat ( "<STR_LIT>" ) ; try { Date end = sdf . parse ( endDate ) ; Date gaStart = sdf . parse ( gaStartDate ) ; if ( end . before ( gaStart ) ) { dateErrors . add ( "<STR_LIT>" ) ; } } catch ( ParseException e ) { dateErrors . add ( "<STR_LIT>" ) ; } if ( startDate . length ( ) == <NUM_LIT:0> || endDate . length ( ) == <NUM_LIT:0> ) { Calendar gregCal = new GregorianCalendar ( ) ; endDate = sdf . format ( gregCal . getTime ( ) ) ; gregCal . roll ( Calendar . YEAR , - <NUM_LIT:1> ) ; startDate = sdf . format ( gregCal . getTime ( ) ) ; } else { try { Date testDate = sdf . parse ( startDate ) ; if ( ! sdf . format ( testDate ) . equals ( startDate ) ) { dateErrors . add ( "<STR_LIT>" ) ; } } catch ( ParseException pe ) { dateErrors . add ( "<STR_LIT>" ) ; } try { Date testDate = sdf . parse ( endDate ) ; if ( ! sdf . format ( testDate ) . equals ( endDate ) ) { dateErrors . add ( "<STR_LIT>" ) ; } } catch ( ParseException pe ) { dateErrors . add ( "<STR_LIT>" ) ; } } return dateErrors ; } } </s>
|
<s> package org . dspace . googlestats ; import org . dspace . core . ConfigurationManager ; import java . net . MalformedURLException ; import java . net . URL ; import java . text . SimpleDateFormat ; import java . util . GregorianCalendar ; public class GoogleAnalyticsAccount { private static String siteUrl ; private static String siteId ; private static String startDate ; private static String endDate ; private static String handlePrefix ; private static String filename ; private static String dataUrl ; private static String gaHandle ; private static String username ; private static String password ; private static final GoogleAnalyticsAccount INSTANCE = new GoogleAnalyticsAccount ( ) ; public String getSiteUrl ( ) { return siteUrl ; } public String getGaHandle ( ) { return gaHandle ; } public String getDataUrl ( ) { return dataUrl ; } public String getFilename ( ) { return filename ; } public String getHandlePrefix ( ) { return handlePrefix ; } public String getEndDate ( ) { return endDate ; } public String getStartDate ( ) { return startDate ; } public String getSiteId ( ) { return siteId ; } public String getPassword ( ) { return password ; } public String getUsername ( ) { return username ; } private GoogleAnalyticsAccount ( ) { siteId = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; gaHandle = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; filename = ConfigurationManager . getProperty ( "<STR_LIT>" ) + System . getProperty ( "<STR_LIT>" ) + ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; startDate = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; String url = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; dataUrl = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; SimpleDateFormat dateFormat = new SimpleDateFormat ( "<STR_LIT>" ) ; endDate = dateFormat . format ( GregorianCalendar . getInstance ( ) . getTime ( ) ) ; username = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT:username>" ) ; password = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT:password>" ) ; try { URL localURL = new URL ( url ) ; url = localURL . getPath ( ) ; if ( url . endsWith ( "<STR_LIT:/>" ) ) { url = url . substring ( <NUM_LIT:0> , url . length ( ) - <NUM_LIT:1> ) ; } } catch ( MalformedURLException e ) { System . err . println ( "<STR_LIT>" + url + "<STR_LIT:)>" ) ; } siteUrl = url ; } public static GoogleAnalyticsAccount getInstance ( ) { return INSTANCE ; } } </s>
|
<s> package org . dspace . googlestats ; import com . google . gdata . client . analytics . AnalyticsService ; import com . google . gdata . data . analytics . DataEntry ; import com . google . gdata . data . analytics . DataFeed ; import com . google . gdata . data . analytics . Metric ; import com . google . gdata . util . AuthenticationException ; import com . google . gdata . util . ServiceException ; import org . apache . log4j . Logger ; import org . dspace . core . ConfigurationManager ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . net . MalformedURLException ; import java . net . URL ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import java . util . Date ; import java . util . Properties ; public class ItemViewCounter { private static final Logger log = Logger . getLogger ( ItemViewCounter . class ) ; private static Properties counts ; private static Date lastloaded ; private static String filename ; private static void init ( ) { Calendar yesterday = Calendar . getInstance ( ) ; yesterday . add ( Calendar . DATE , - <NUM_LIT:1> ) ; lastloaded = yesterday . getTime ( ) ; filename = ConfigurationManager . getProperty ( "<STR_LIT>" ) + System . getProperty ( "<STR_LIT>" ) + ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; counts = new Properties ( ) ; loadCounter ( ) ; } public static String getPageCount ( String page ) { if ( lastloaded == null ) { init ( ) ; } loadCounter ( ) ; if ( page == null ) { page = "<STR_LIT>" ; } String count = counts . getProperty ( page ) ; if ( count != null ) { return count ; } return "<STR_LIT>" ; } private static void loadCounter ( ) { Calendar hourago = Calendar . getInstance ( ) ; hourago . add ( Calendar . HOUR , - <NUM_LIT:1> ) ; if ( lastloaded . before ( hourago . getTime ( ) ) ) { try { counts . load ( new FileInputStream ( new File ( filename ) ) ) ; lastloaded = Calendar . getInstance ( ) . getTime ( ) ; } catch ( Exception e ) { log . warn ( "<STR_LIT>" + filename ) ; } } } public static void main ( String [ ] args ) { populateCounter ( ) ; } private static void populateCounter ( ) { try { String siteid = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; String handle = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; String filename = ConfigurationManager . getProperty ( "<STR_LIT>" ) + System . getProperty ( "<STR_LIT>" ) + ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; AnalyticsService as = GoogleAnalyticsConnector . getConnection ( ) ; Properties counts = new Properties ( ) ; URL queryUrl ; int i = <NUM_LIT:1> ; boolean found = true ; int total = <NUM_LIT:0> ; String baseUrl = "<STR_LIT>" ; Calendar today = Calendar . getInstance ( ) ; SimpleDateFormat format = new SimpleDateFormat ( "<STR_LIT>" ) ; String enddate = format . format ( today . getTime ( ) ) ; today . roll ( Calendar . YEAR , - <NUM_LIT:1> ) ; String startdate = format . format ( today . getTime ( ) ) ; while ( found ) { found = false ; try { String q = baseUrl + "<STR_LIT>" + i + "<STR_LIT>" + siteid + "<STR_LIT>" + startdate + "<STR_LIT>" + enddate + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + handle ; queryUrl = new URL ( q ) ; } catch ( MalformedURLException e ) { System . err . println ( "<STR_LIT>" + baseUrl ) ; return ; } DataFeed dataFeed ; try { dataFeed = as . getFeed ( queryUrl , DataFeed . class ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; return ; } catch ( ServiceException e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; return ; } for ( DataEntry entry : dataFeed . getEntries ( ) ) { String id = entry . stringValueOf ( "<STR_LIT>" ) ; for ( Metric metric : entry . getMetrics ( ) ) { counts . put ( id , metric . getValue ( ) ) ; System . out . println ( metric . getValue ( ) + "<STR_LIT>" + id + "<STR_LIT:'>" ) ; total = total + Integer . parseInt ( metric . getValue ( ) ) ; found = true ; } } i = i + <NUM_LIT:1000> ; } counts . put ( "<STR_LIT>" , "<STR_LIT>" + total ) ; counts . store ( new FileOutputStream ( filename ) , null ) ; System . out . println ( "<STR_LIT>" + total + "<STR_LIT>" + filename ) ; } catch ( AuthenticationException e ) { System . err . println ( "<STR_LIT>" + e ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" + filename ) ; } catch ( Exception e ) { System . err . println ( "<STR_LIT>" + e ) ; } } } </s>
|
<s> package org . dspace . googlestats ; public class GoogleAnalyticsException extends Exception { public GoogleAnalyticsException ( String message ) { super ( message ) ; } public GoogleAnalyticsException ( Throwable cause ) { super ( cause ) ; } public GoogleAnalyticsException ( String message , Throwable cause ) { super ( message , cause ) ; } } </s>
|
<s> package org . dspace . googlestats ; import com . google . gdata . data . analytics . * ; import org . apache . log4j . Logger ; import java . util . ArrayList ; import java . util . List ; public class PrintoutFeedData { private static Logger log = Logger . getLogger ( PrintoutFeedData . class ) ; private final DataFeed feed ; private GoogleAnalyticsAccount gaa ; public PrintoutFeedData ( DataFeed feed ) { this . feed = feed ; } public void printFeedData ( ) { System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" + feed . getTitle ( ) . getPlainText ( ) + "<STR_LIT>" + feed . getId ( ) + "<STR_LIT>" + feed . getTotalResults ( ) + "<STR_LIT>" + feed . getStartIndex ( ) + "<STR_LIT>" + feed . getItemsPerPage ( ) + "<STR_LIT>" + feed . getStartDate ( ) . getValue ( ) + "<STR_LIT>" + feed . getEndDate ( ) . getValue ( ) + "<STR_LIT>" + feed . getContainsSampledData ( ) . getValue ( ) . toString ( ) ) ; } public void printFeedDataSources ( ) { DataSource gaDataSource = feed . getDataSources ( ) . get ( <NUM_LIT:0> ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" + gaDataSource . getTableName ( ) . getValue ( ) + "<STR_LIT>" + gaDataSource . getTableId ( ) . getValue ( ) + "<STR_LIT>" + gaDataSource . getProperty ( "<STR_LIT>" ) + "<STR_LIT>" + gaDataSource . getProperty ( "<STR_LIT>" ) + "<STR_LIT>" + gaDataSource . getProperty ( "<STR_LIT>" ) ) ; } public void printFeedAggregates ( ) { System . out . println ( "<STR_LIT>" ) ; Aggregates aggregates = feed . getAggregates ( ) ; for ( Metric metric : aggregates . getMetrics ( ) ) { System . out . println ( "<STR_LIT>" + metric . getName ( ) + "<STR_LIT>" + metric . getValue ( ) + "<STR_LIT>" + metric . getType ( ) + "<STR_LIT>" + metric . getConfidenceInterval ( ) . toString ( ) ) ; } } public void printSegmentInfo ( ) { if ( feed . hasSegments ( ) ) { System . out . println ( "<STR_LIT>" ) ; for ( Segment segment : feed . getSegments ( ) ) { System . out . println ( "<STR_LIT>" + segment . getName ( ) + "<STR_LIT>" + segment . getId ( ) + "<STR_LIT>" + segment . getDefinition ( ) . getValue ( ) ) ; } } } public void printDataForOneEntry ( ) { System . out . println ( "<STR_LIT>" ) ; if ( feed . getEntries ( ) . isEmpty ( ) ) { System . out . println ( "<STR_LIT>" ) ; } else { DataEntry singleEntry = feed . getEntries ( ) . get ( <NUM_LIT:0> ) ; printEntryData ( singleEntry ) ; } } private void printEntryData ( DataEntry singleEntry ) { System . out . println ( "<STR_LIT>" + singleEntry . getId ( ) ) ; System . out . println ( "<STR_LIT>" + singleEntry . getTitle ( ) . getPlainText ( ) ) ; for ( Dimension dimension : singleEntry . getDimensions ( ) ) { System . out . println ( "<STR_LIT>" + dimension . getName ( ) ) ; System . out . println ( "<STR_LIT>" + dimension . getValue ( ) ) ; } for ( Metric metric : singleEntry . getMetrics ( ) ) { System . out . println ( "<STR_LIT>" + metric . getName ( ) ) ; System . out . println ( "<STR_LIT>" + metric . getValue ( ) ) ; System . out . println ( "<STR_LIT>" + metric . getType ( ) ) ; System . out . println ( "<STR_LIT>" + metric . getConfidenceInterval ( ) . toString ( ) ) ; } } public String getEntriesAsTable ( ) { if ( feed . getEntries ( ) . isEmpty ( ) ) { return "<STR_LIT>" ; } DataEntry singleEntry = feed . getEntries ( ) . get ( <NUM_LIT:0> ) ; List < String > feedDataNames = new ArrayList < String > ( ) ; StringBuilder feedDataValues = new StringBuilder ( "<STR_LIT>" ) ; for ( Dimension dimension : singleEntry . getDimensions ( ) ) { feedDataNames . add ( dimension . getName ( ) ) ; } for ( Metric metric : singleEntry . getMetrics ( ) ) { feedDataNames . add ( metric . getName ( ) ) ; } for ( DataEntry entry : feed . getEntries ( ) ) { for ( String dataName : feedDataNames ) { feedDataValues . append ( String . format ( "<STR_LIT>" , dataName , entry . stringValueOf ( dataName ) ) ) ; } feedDataValues . append ( "<STR_LIT:n>" ) ; } return feedDataValues . toString ( ) ; } } </s>
|
<s> package org . dspace . app . webui . servlet ; import com . google . gdata . data . ExtensionProfile ; import com . google . gdata . data . analytics . DataFeed ; import com . google . gdata . util . common . xml . XmlWriter ; import org . apache . log4j . Logger ; import org . apache . xml . serializer . Method ; import org . apache . xml . serializer . OutputPropertiesFactory ; import org . apache . xml . serializer . Serializer ; import org . apache . xml . serializer . SerializerFactory ; import org . dspace . authorize . AuthorizeException ; import org . dspace . core . ConfigurationManager ; import org . dspace . core . Context ; import org . dspace . eperson . Group ; import org . dspace . googlestats . GoogleAnalyticsAccount ; import org . dspace . googlestats . GoogleAnalyticsUtils ; import org . dspace . googlestats . GoogleQueryManager ; import javax . servlet . ServletException ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import java . io . IOException ; import java . io . Writer ; import java . sql . SQLException ; import java . util . List ; import java . util . Properties ; public class GoogleAnalyticsQueryServlet extends DSpaceServlet { private static Logger log = Logger . getLogger ( GoogleAnalyticsQueryServlet . class ) ; protected void doDSGet ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { boolean privatereport = ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ; boolean admin = Group . isMember ( context , <NUM_LIT:1> ) ; if ( ! privatereport || admin ) { process ( context , request , response ) ; } else { throw new AuthorizeException ( ) ; } } protected void doDSPost ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { boolean privatereport = ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ; boolean admin = Group . isMember ( context , <NUM_LIT:1> ) ; if ( ! privatereport || admin ) { process ( context , request , response ) ; } else { throw new AuthorizeException ( ) ; } } protected void process ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { String headMetadata = "<STR_LIT>" ; String startDate = request . getParameter ( "<STR_LIT>" ) ; String endDate = request . getParameter ( "<STR_LIT>" ) ; String action = request . getParameter ( "<STR_LIT>" ) ; log . debug ( "<STR_LIT>" + action ) ; String gaStart = GoogleAnalyticsAccount . getInstance ( ) . getStartDate ( ) ; request . setAttribute ( "<STR_LIT>" , gaStart ) ; request . setAttribute ( "<STR_LIT>" , headMetadata ) ; GoogleQueryManager query = new GoogleQueryManager ( ) ; List < String > dateErrors = GoogleAnalyticsUtils . testDate ( startDate , endDate , gaStart ) ; Writer writer = response . getWriter ( ) ; Properties props = OutputPropertiesFactory . getDefaultMethodProperties ( Method . XML ) ; Serializer ser = SerializerFactory . getSerializer ( props ) ; ser . setWriter ( writer ) ; response . setContentType ( "<STR_LIT>" ) ; if ( dateErrors . isEmpty ( ) ) { try { DataFeed feed ; if ( action . equals ( "<STR_LIT>" ) ) { feed = query . queryViewDSpaceMonth ( startDate , endDate ) ; XmlWriter xmlW = new XmlWriter ( writer ) ; writer . append ( "<STR_LIT>" ) ; feed . generateAtom ( xmlW , new ExtensionProfile ( ) ) ; } else if ( action . equals ( "<STR_LIT>" ) ) { feed = query . queryBitstreamViewMonth ( startDate , endDate ) ; XmlWriter xmlW = new XmlWriter ( writer ) ; writer . append ( "<STR_LIT>" ) ; feed . generateAtom ( xmlW , new ExtensionProfile ( ) ) ; } else if ( action . equals ( "<STR_LIT>" ) ) { feed = query . queryTopPages ( startDate , endDate ) ; XmlWriter xmlW = new XmlWriter ( writer ) ; writer . append ( "<STR_LIT>" ) ; feed . generateAtom ( xmlW , new ExtensionProfile ( ) ) ; } else if ( action . equals ( "<STR_LIT>" ) ) { feed = query . queryTopItems ( startDate , endDate , context ) ; XmlWriter xmlW = new XmlWriter ( writer ) ; writer . append ( "<STR_LIT>" ) ; feed . generateAtom ( xmlW , new ExtensionProfile ( ) ) ; } else if ( action . equals ( "<STR_LIT>" ) ) { feed = query . queryTopDownloads ( startDate , endDate ) ; writer . append ( "<STR_LIT>" ) ; XmlWriter xmlW = new XmlWriter ( writer ) ; feed . generateAtom ( xmlW , new ExtensionProfile ( ) ) ; } else if ( action . equals ( "<STR_LIT>" ) ) { feed = query . queryTopCountries ( startDate , endDate ) ; XmlWriter xmlW = new XmlWriter ( writer ) ; writer . append ( "<STR_LIT>" ) ; feed . generateAtom ( xmlW , new ExtensionProfile ( ) ) ; } else { writer . append ( "<STR_LIT>" ) ; } writer . flush ( ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e ) ; writer . append ( "<STR_LIT>" + e ) ; writer . flush ( ) ; } finally { ser . reset ( ) ; } } else { log . info ( "<STR_LIT>" + dateErrors ) ; writer . append ( "<STR_LIT>" ) ; for ( String error : dateErrors ) { writer . append ( "<STR_LIT>" + error + "<STR_LIT>" ) ; } writer . flush ( ) ; ser . reset ( ) ; } } } </s>
|
<s> package org . dspace . app . webui . servlet ; import org . apache . log4j . Logger ; import org . dspace . app . webui . util . JSPManager ; import org . dspace . authorize . AuthorizeException ; import org . dspace . content . DSpaceObject ; import org . dspace . core . ConfigurationManager ; import org . dspace . core . Context ; import org . dspace . eperson . Group ; import org . dspace . googlestats . GoogleAnalyticsAccount ; import org . dspace . handle . HandleManager ; import javax . servlet . ServletException ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import java . io . IOException ; import java . sql . SQLException ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import java . util . GregorianCalendar ; public class GoogleAnalyticsItemServlet extends DSpaceServlet { private static Logger log = Logger . getLogger ( GoogleAnalyticsItemServlet . class ) ; protected void doDSGet ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { boolean privatereport = ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ; boolean admin = Group . isMember ( context , <NUM_LIT:1> ) ; if ( ! privatereport || admin ) { displayStatistics ( context , request , response ) ; } else { throw new AuthorizeException ( ) ; } } protected void doDSPost ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { boolean privatereport = ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ; boolean admin = Group . isMember ( context , <NUM_LIT:1> ) ; if ( ! privatereport || admin ) { displayStatistics ( context , request , response ) ; } else { throw new AuthorizeException ( ) ; } } protected void displayStatistics ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { String headMetadata = "<STR_LIT>" ; String handle = request . getParameter ( "<STR_LIT>" ) ; DSpaceObject dso = HandleManager . resolveToObject ( context , handle ) ; try { Calendar gregCal = new GregorianCalendar ( ) ; SimpleDateFormat sdf = new SimpleDateFormat ( "<STR_LIT>" ) ; String endDate = sdf . format ( gregCal . getTime ( ) ) ; gregCal . roll ( Calendar . YEAR , - <NUM_LIT:1> ) ; String startDate = sdf . format ( gregCal . getTime ( ) ) ; request . setAttribute ( "<STR_LIT>" , dso ) ; request . setAttribute ( "<STR_LIT>" , headMetadata ) ; request . setAttribute ( "<STR_LIT>" , GoogleAnalyticsAccount . getInstance ( ) . getSiteId ( ) ) ; request . setAttribute ( "<STR_LIT>" , startDate ) ; request . setAttribute ( "<STR_LIT>" , endDate ) ; String gaStart = GoogleAnalyticsAccount . getInstance ( ) . getStartDate ( ) ; request . setAttribute ( "<STR_LIT>" , gaStart ) ; JSPManager . showJSP ( request , response , "<STR_LIT>" ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e ) ; e . printStackTrace ( ) ; throw new ServletException ( e ) ; } } } </s>
|
<s> package org . dspace . app . webui . servlet ; import org . apache . log4j . Logger ; import org . dspace . app . webui . util . JSPManager ; import org . dspace . authorize . AuthorizeException ; import org . dspace . core . ConfigurationManager ; import org . dspace . core . Context ; import org . dspace . eperson . Group ; import javax . servlet . ServletException ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import java . io . IOException ; import java . sql . SQLException ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import java . util . GregorianCalendar ; public class GoogleAnalyticsDSpaceServlet extends DSpaceServlet { private static Logger log = Logger . getLogger ( GoogleAnalyticsDSpaceServlet . class ) ; protected void doDSGet ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { boolean privatereport = ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ; boolean admin = Group . isMember ( context , <NUM_LIT:1> ) ; if ( ! privatereport || admin ) { displayStatistics ( context , request , response ) ; } else { throw new AuthorizeException ( ) ; } } protected void doDSPost ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { boolean privatereport = ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ; boolean admin = Group . isMember ( context , <NUM_LIT:1> ) ; if ( ! privatereport || admin ) { displayStatistics ( context , request , response ) ; } else { throw new AuthorizeException ( ) ; } } protected void displayStatistics ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { String headMetadata = "<STR_LIT>" ; try { Calendar gregCal = new GregorianCalendar ( ) ; SimpleDateFormat sdf = new SimpleDateFormat ( "<STR_LIT>" ) ; String endDate = sdf . format ( gregCal . getTime ( ) ) ; gregCal . roll ( Calendar . YEAR , - <NUM_LIT:1> ) ; String startDate = sdf . format ( gregCal . getTime ( ) ) ; request . setAttribute ( "<STR_LIT>" , headMetadata ) ; request . setAttribute ( "<STR_LIT>" , startDate ) ; request . setAttribute ( "<STR_LIT>" , endDate ) ; String gaStart = ConfigurationManager . getProperty ( "<STR_LIT>" ) ; request . setAttribute ( "<STR_LIT>" , gaStart ) ; JSPManager . showJSP ( request , response , "<STR_LIT>" ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e ) ; throw new ServletException ( e ) ; } } } </s>
|
<s> package org . dspace . app . webui . servlet ; import com . google . gdata . client . analytics . AnalyticsService ; import com . google . gdata . data . analytics . DataFeed ; import com . google . gdata . util . common . xml . XmlWriter ; import org . apache . log4j . Logger ; import org . apache . xml . serializer . Method ; import org . apache . xml . serializer . OutputPropertiesFactory ; import org . apache . xml . serializer . Serializer ; import org . apache . xml . serializer . SerializerFactory ; import org . dspace . authorize . AuthorizeException ; import org . dspace . content . DSpaceObject ; import org . dspace . core . ConfigurationManager ; import org . dspace . core . Context ; import org . dspace . eperson . Group ; import org . dspace . googlestats . GoogleAnalyticsAccount ; import org . dspace . googlestats . GoogleAnalyticsConnector ; import org . dspace . googlestats . GoogleAnalyticsUtils ; import org . dspace . googlestats . GoogleQueryManager ; import org . dspace . handle . HandleManager ; import javax . servlet . ServletException ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import java . io . IOException ; import java . io . PrintWriter ; import java . sql . SQLException ; import java . util . List ; import java . util . Properties ; public class GoogleAnalyticsItemQueryServlet extends DSpaceServlet { private static Logger log = Logger . getLogger ( GoogleAnalyticsItemQueryServlet . class ) ; protected void doDSGet ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { boolean privatereport = ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ; boolean admin = Group . isMember ( context , <NUM_LIT:1> ) ; if ( ! privatereport || admin ) { process ( context , request , response ) ; } else { throw new AuthorizeException ( ) ; } } protected void doDSPost ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { boolean privateReport = ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ; boolean admin = Group . isMember ( context , <NUM_LIT:1> ) ; if ( ! privateReport || admin ) { process ( context , request , response ) ; } else { throw new AuthorizeException ( ) ; } } protected void process ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { String headMetadata = "<STR_LIT>" ; String startDate = request . getParameter ( "<STR_LIT>" ) ; String endDate = request . getParameter ( "<STR_LIT>" ) ; String action = request . getParameter ( "<STR_LIT>" ) ; String handle = request . getParameter ( "<STR_LIT>" ) ; DSpaceObject dso = HandleManager . resolveToObject ( context , handle ) ; String gaStart = GoogleAnalyticsAccount . getInstance ( ) . getStartDate ( ) ; request . setAttribute ( "<STR_LIT>" , gaStart ) ; List < String > dateErrors = GoogleAnalyticsUtils . testDate ( startDate , endDate , gaStart ) ; request . setAttribute ( "<STR_LIT>" , headMetadata ) ; GoogleQueryManager query = new GoogleQueryManager ( ) ; response . setContentType ( "<STR_LIT>" ) ; Properties props = OutputPropertiesFactory . getDefaultMethodProperties ( Method . XML ) ; Serializer ser = SerializerFactory . getSerializer ( props ) ; PrintWriter writer = response . getWriter ( ) ; ser . setWriter ( writer ) ; if ( dateErrors . isEmpty ( ) ) { try { DataFeed feed ; AnalyticsService as = GoogleAnalyticsConnector . getConnection ( ) ; if ( action . equals ( "<STR_LIT>" ) ) { feed = query . queryViewDSpaceMonth ( dso , startDate , endDate , as ) ; XmlWriter xmlW = new XmlWriter ( writer ) ; writer . append ( "<STR_LIT>" ) ; feed . generateAtom ( xmlW , as . getExtensionProfile ( ) ) ; } else if ( action . equals ( "<STR_LIT>" ) ) { feed = query . queryBitstreamViewMonth ( dso , startDate , endDate ) ; XmlWriter xmlW = new XmlWriter ( writer ) ; writer . append ( "<STR_LIT>" ) ; feed . generateAtom ( xmlW , as . getExtensionProfile ( ) ) ; } else { writer . append ( "<STR_LIT>" ) ; } writer . flush ( ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e ) ; throw new ServletException ( e . toString ( ) ) ; } finally { ser . reset ( ) ; } } else { log . info ( "<STR_LIT>" + dateErrors ) ; writer . append ( "<STR_LIT>" ) ; for ( String error : dateErrors ) { writer . append ( "<STR_LIT>" + error + "<STR_LIT>" ) ; } writer . flush ( ) ; ser . reset ( ) ; } } } </s>
|
<s> package org . dspace . app . webui . servlet ; import org . apache . log4j . Logger ; import org . dspace . app . webui . util . JSPManager ; import org . dspace . authorize . AuthorizeException ; import org . dspace . content . Collection ; import org . dspace . content . DSpaceObject ; import org . dspace . core . ConfigurationManager ; import org . dspace . core . Context ; import org . dspace . eperson . Group ; import org . dspace . googlestats . GoogleAnalyticsCollectionStats ; import org . dspace . handle . HandleManager ; import javax . servlet . ServletException ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import java . io . IOException ; import java . sql . SQLException ; import java . util . List ; public class GoogleAnalyticsCollectionServlet extends DSpaceServlet { private static Logger log = Logger . getLogger ( GoogleAnalyticsCollectionServlet . class ) ; protected void doDSGet ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { boolean privatereport = ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ; boolean admin = Group . isMember ( context , <NUM_LIT:1> ) ; if ( ! privatereport || admin ) { displayStatistics ( context , request , response ) ; } else { throw new AuthorizeException ( ) ; } } protected void doDSPost ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { boolean privatereport = ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ; boolean admin = Group . isMember ( context , <NUM_LIT:1> ) ; if ( ! privatereport || admin ) { displayStatistics ( context , request , response ) ; } else { throw new AuthorizeException ( ) ; } } protected void displayStatistics ( Context context , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException , SQLException , AuthorizeException { String headMetadata = "<STR_LIT>" ; String handle = request . getParameter ( "<STR_LIT>" ) ; DSpaceObject dso = HandleManager . resolveToObject ( context , handle ) ; try { request . setAttribute ( "<STR_LIT>" , dso ) ; request . setAttribute ( "<STR_LIT>" , headMetadata ) ; Collection collection = ( Collection ) dso ; GoogleAnalyticsCollectionStats query = new GoogleAnalyticsCollectionStats ( collection ) ; request . setAttribute ( "<STR_LIT>" , query . getTotalViews ( ) ) ; request . setAttribute ( "<STR_LIT>" , query . getTotalDownloads ( ) ) ; List topviews = query . getTopViews ( ) ; List topdownloads = query . getTopDownloads ( ) ; if ( ! topviews . isEmpty ( ) && topviews . size ( ) > <NUM_LIT:10> ) { request . setAttribute ( "<STR_LIT>" , topviews . subList ( <NUM_LIT:0> , <NUM_LIT:10> ) ) ; } else { request . setAttribute ( "<STR_LIT>" , topviews ) ; } if ( ! topdownloads . isEmpty ( ) && topdownloads . size ( ) > <NUM_LIT:10> ) { request . setAttribute ( "<STR_LIT>" , topdownloads . subList ( <NUM_LIT:0> , <NUM_LIT:10> ) ) ; } else { request . setAttribute ( "<STR_LIT>" , topdownloads ) ; } String gaStart = ConfigurationManager . getProperty ( "<STR_LIT>" ) ; request . setAttribute ( "<STR_LIT>" , gaStart ) ; JSPManager . showJSP ( request , response , "<STR_LIT>" ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + e ) ; throw new ServletException ( e ) ; } } } </s>
|
<s> package org . dspace . app . webui . jsptag ; import org . apache . commons . lang . ArrayUtils ; import org . apache . log4j . Logger ; import org . dspace . app . util . MetadataExposure ; import org . dspace . app . webui . util . StyleSelection ; import org . dspace . app . webui . util . UIUtil ; import org . dspace . browse . BrowseException ; import org . dspace . content . * ; import org . dspace . content . authority . MetadataAuthorityManager ; import org . dspace . core . * ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . jsp . JspException ; import javax . servlet . jsp . JspWriter ; import javax . servlet . jsp . jstl . fmt . LocaleSupport ; import javax . servlet . jsp . tagext . TagSupport ; import java . io . IOException ; import java . net . URLEncoder ; import java . sql . SQLException ; import java . util . HashMap ; import java . util . Map ; import java . util . MissingResourceException ; import java . util . StringTokenizer ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; public class ItemTag extends TagSupport { private static final String HANDLE_DEFAULT_BASEURL = "<STR_LIT>" ; private static final String DOI_DEFAULT_BASEURL = "<STR_LIT>" ; private transient Item item ; private transient Collection [ ] collections ; private String style ; private boolean showThumbs ; private static String defaultFields = "<STR_LIT>" ; private static Logger log = Logger . getLogger ( ItemTag . class ) ; private StyleSelection styleSelection = ( StyleSelection ) PluginManager . getSinglePlugin ( StyleSelection . class ) ; private static Map < String , String > linkedMetadata ; private static Map < String , String > urn2baseurl ; private Pattern fieldStylePatter = Pattern . compile ( "<STR_LIT>" ) ; private static final long serialVersionUID = - <NUM_LIT> ; static { int i ; linkedMetadata = new HashMap < String , String > ( ) ; String linkMetadata ; i = <NUM_LIT:1> ; do { linkMetadata = ConfigurationManager . getProperty ( "<STR_LIT>" + i ) ; if ( linkMetadata != null ) { String [ ] linkedMetadataSplit = linkMetadata . split ( "<STR_LIT::>" ) ; String indexName = linkedMetadataSplit [ <NUM_LIT:0> ] . trim ( ) ; String metadataName = linkedMetadataSplit [ <NUM_LIT:1> ] . trim ( ) ; linkedMetadata . put ( indexName , metadataName ) ; } i ++ ; } while ( linkMetadata != null ) ; urn2baseurl = new HashMap < String , String > ( ) ; String urn ; i = <NUM_LIT:1> ; do { urn = ConfigurationManager . getProperty ( "<STR_LIT>" + i + "<STR_LIT>" ) ; if ( urn != null ) { String baseurl = ConfigurationManager . getProperty ( "<STR_LIT>" + i + "<STR_LIT>" ) ; if ( baseurl != null ) { urn2baseurl . put ( urn , baseurl ) ; } else { log . warn ( "<STR_LIT>" + i ) ; } } i ++ ; } while ( urn != null ) ; if ( ! urn2baseurl . containsKey ( "<STR_LIT>" ) ) { urn2baseurl . put ( "<STR_LIT>" , DOI_DEFAULT_BASEURL ) ; } if ( ! urn2baseurl . containsKey ( "<STR_LIT>" ) ) { urn2baseurl . put ( "<STR_LIT>" , HANDLE_DEFAULT_BASEURL ) ; } } public ItemTag ( ) { super ( ) ; getThumbSettings ( ) ; } public int doStartTag ( ) throws JspException { try { if ( style == null || style . equals ( "<STR_LIT>" ) ) { style = styleSelection . getStyleForItem ( item ) ; } if ( style . equals ( "<STR_LIT>" ) ) { renderFull ( ) ; } else { render ( ) ; } } catch ( SQLException sqle ) { throw new JspException ( sqle ) ; } catch ( IOException ie ) { throw new JspException ( ie ) ; } return SKIP_BODY ; } public Item getItem ( ) { return item ; } public void setItem ( Item itemIn ) { item = itemIn ; } public Collection [ ] getCollections ( ) { return ( Collection [ ] ) ArrayUtils . clone ( collections ) ; } public void setCollections ( Collection [ ] collectionsIn ) { collections = ( Collection [ ] ) ArrayUtils . clone ( collectionsIn ) ; } public String getStyle ( ) { return style ; } public void setStyle ( String styleIn ) { style = styleIn ; } public void release ( ) { style = "<STR_LIT:default>" ; item = null ; collections = null ; } private void render ( ) throws IOException , SQLException { JspWriter out = pageContext . getOut ( ) ; HttpServletRequest request = ( HttpServletRequest ) pageContext . getRequest ( ) ; Context context = UIUtil . obtainContext ( request ) ; String configLine = styleSelection . getConfigurationForStyle ( style ) ; if ( configLine == null ) { configLine = defaultFields ; } out . println ( "<STR_LIT>" ) ; StringTokenizer st = new StringTokenizer ( configLine , "<STR_LIT:U+002C>" ) ; while ( st . hasMoreTokens ( ) ) { String field = st . nextToken ( ) . trim ( ) ; boolean isDate = false ; boolean isLink = false ; boolean isResolver = false ; String style = null ; Matcher fieldStyleMatcher = fieldStylePatter . matcher ( field ) ; if ( fieldStyleMatcher . matches ( ) ) { style = fieldStyleMatcher . group ( <NUM_LIT:1> ) ; } String browseIndex ; try { browseIndex = getBrowseField ( field ) ; } catch ( BrowseException e ) { log . error ( e ) ; browseIndex = null ; } if ( style != null ) { isDate = style . equals ( "<STR_LIT:date>" ) ; isLink = style . equals ( "<STR_LIT>" ) ; isResolver = style . equals ( "<STR_LIT>" ) || urn2baseurl . keySet ( ) . contains ( style ) ; field = field . replaceAll ( "<STR_LIT>" + style + "<STR_LIT>" , "<STR_LIT>" ) ; } String [ ] eq = field . split ( "<STR_LIT:\\.>" ) ; String schema = eq [ <NUM_LIT:0> ] ; String element = eq [ <NUM_LIT:1> ] ; String qualifier = null ; if ( eq . length > <NUM_LIT:2> && eq [ <NUM_LIT:2> ] . equals ( "<STR_LIT:*>" ) ) { qualifier = Item . ANY ; } else if ( eq . length > <NUM_LIT:2> ) { qualifier = eq [ <NUM_LIT:2> ] ; } if ( MetadataExposure . isHidden ( context , schema , element , qualifier ) ) { continue ; } DCValue [ ] values = item . getMetadata ( schema , element , qualifier , Item . ANY ) ; if ( values . length > <NUM_LIT:0> ) { out . print ( "<STR_LIT>" ) ; String label = null ; try { label = I18nUtil . getMessage ( "<STR_LIT>" + ( style != null ? style + "<STR_LIT:.>" : "<STR_LIT>" ) + field , context ) ; } catch ( MissingResourceException e ) { label = LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" + field ) ; } out . print ( label ) ; out . print ( "<STR_LIT>" ) ; for ( int j = <NUM_LIT:0> ; j < values . length ; j ++ ) { if ( values [ j ] != null && values [ j ] . value != null ) { if ( j > <NUM_LIT:0> ) { out . print ( "<STR_LIT>" ) ; } if ( isLink ) { out . print ( "<STR_LIT>" + values [ j ] . value + "<STR_LIT>" + Utils . addEntities ( values [ j ] . value ) + "<STR_LIT>" ) ; } else if ( isDate ) { DCDate dd = new DCDate ( values [ j ] . value ) ; out . print ( UIUtil . displayDate ( dd , false , false , ( HttpServletRequest ) pageContext . getRequest ( ) ) ) ; } else if ( isResolver ) { String value = values [ j ] . value ; if ( value . startsWith ( "<STR_LIT:http://>" ) || value . startsWith ( "<STR_LIT>" ) || value . startsWith ( "<STR_LIT>" ) || value . startsWith ( "<STR_LIT>" ) ) { out . print ( "<STR_LIT>" + value + "<STR_LIT>" + Utils . addEntities ( value ) + "<STR_LIT>" ) ; } else { String foundUrn = null ; if ( ! style . equals ( "<STR_LIT>" ) ) { foundUrn = style ; } else { for ( String checkUrn : urn2baseurl . keySet ( ) ) { if ( value . startsWith ( checkUrn ) ) { foundUrn = checkUrn ; } } } if ( foundUrn != null ) { if ( value . startsWith ( foundUrn + "<STR_LIT::>" ) ) { value = value . substring ( foundUrn . length ( ) + <NUM_LIT:1> ) ; } String url = urn2baseurl . get ( foundUrn ) ; out . print ( "<STR_LIT>" + url + value + "<STR_LIT>" + Utils . addEntities ( values [ j ] . value ) + "<STR_LIT>" ) ; } else { out . print ( value ) ; } } } else if ( browseIndex != null ) { String argument , value ; if ( values [ j ] . authority != null && values [ j ] . confidence >= MetadataAuthorityManager . getManager ( ) . getMinConfidence ( values [ j ] . schema , values [ j ] . element , values [ j ] . qualifier ) ) { argument = "<STR_LIT>" ; value = values [ j ] . authority ; } else { argument = "<STR_LIT:value>" ; value = values [ j ] . value ; } out . print ( "<STR_LIT>" + ( "<STR_LIT>" . equals ( argument ) ? "<STR_LIT>" : "<STR_LIT>" ) + browseIndex + "<STR_LIT:\">" + "<STR_LIT>" + request . getContextPath ( ) + "<STR_LIT>" + browseIndex + "<STR_LIT>" + argument + "<STR_LIT:=>" + URLEncoder . encode ( value , "<STR_LIT:UTF-8>" ) + "<STR_LIT>" + Utils . addEntities ( values [ j ] . value ) + "<STR_LIT>" ) ; } else { out . print ( Utils . addEntities ( values [ j ] . value ) ) ; } } } out . println ( "<STR_LIT>" ) ; } } listCollections ( ) ; out . println ( "<STR_LIT>" ) ; listBitstreams ( ) ; if ( ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ) { out . println ( "<STR_LIT>" ) ; showLicence ( ) ; } } private void renderFull ( ) throws IOException , SQLException { JspWriter out = pageContext . getOut ( ) ; HttpServletRequest request = ( HttpServletRequest ) pageContext . getRequest ( ) ; Context context = UIUtil . obtainContext ( request ) ; DCValue [ ] values = item . getMetadata ( Item . ANY , Item . ANY , Item . ANY , Item . ANY ) ; out . println ( "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" ) ; out . println ( "<STR_LIT>" ) ; out . println ( "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < values . length ; i ++ ) { if ( ! MetadataExposure . isHidden ( context , values [ i ] . schema , values [ i ] . element , values [ i ] . qualifier ) ) { out . print ( "<STR_LIT>" ) ; out . print ( values [ i ] . schema ) ; out . print ( "<STR_LIT:.>" + values [ i ] . element ) ; if ( values [ i ] . qualifier != null ) { out . print ( "<STR_LIT:.>" + values [ i ] . qualifier ) ; } out . print ( "<STR_LIT>" ) ; out . print ( Utils . addEntities ( values [ i ] . value ) ) ; out . print ( "<STR_LIT>" ) ; if ( values [ i ] . language == null ) { out . print ( "<STR_LIT:->" ) ; } else { out . print ( values [ i ] . language ) ; } out . println ( "<STR_LIT>" ) ; } } listCollections ( ) ; out . println ( "<STR_LIT>" ) ; listBitstreams ( ) ; if ( ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ) { out . println ( "<STR_LIT>" ) ; showLicence ( ) ; } } private void listCollections ( ) throws IOException { JspWriter out = pageContext . getOut ( ) ; HttpServletRequest request = ( HttpServletRequest ) pageContext . getRequest ( ) ; if ( collections != null ) { out . print ( "<STR_LIT>" ) ; if ( item . getHandle ( ) == null ) { out . print ( LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) ) ; } else { out . print ( LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) ) ; } out . print ( "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < collections . length ; i ++ ) { out . print ( "<STR_LIT>" ) ; out . print ( request . getContextPath ( ) ) ; out . print ( "<STR_LIT>" ) ; out . print ( collections [ i ] . getHandle ( ) ) ; out . print ( "<STR_LIT>" ) ; out . print ( collections [ i ] . getMetadata ( "<STR_LIT:name>" ) ) ; out . print ( "<STR_LIT>" ) ; } out . println ( "<STR_LIT>" ) ; } } private void listBitstreams ( ) throws IOException { JspWriter out = pageContext . getOut ( ) ; HttpServletRequest request = ( HttpServletRequest ) pageContext . getRequest ( ) ; out . print ( "<STR_LIT>" ) ; out . println ( "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" ) ; try { Bundle [ ] bundles = item . getBundles ( "<STR_LIT>" ) ; boolean filesExist = false ; for ( Bundle bnd : bundles ) { filesExist = bnd . getBitstreams ( ) . length > <NUM_LIT:0> ; if ( filesExist ) { break ; } } if ( ! filesExist ) { out . println ( "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" ) ; } else { boolean html = false ; String handle = item . getHandle ( ) ; Bitstream primaryBitstream = null ; Bundle [ ] bunds = item . getBundles ( "<STR_LIT>" ) ; Bundle [ ] thumbs = item . getBundles ( "<STR_LIT>" ) ; boolean multiFile = false ; Bundle [ ] allBundles = item . getBundles ( ) ; for ( int i = <NUM_LIT:0> , filecount = <NUM_LIT:0> ; ( i < allBundles . length ) && ! multiFile ; i ++ ) { filecount += allBundles [ i ] . getBitstreams ( ) . length ; multiFile = ( filecount > <NUM_LIT:1> ) ; } if ( bunds [ <NUM_LIT:0> ] != null ) { Bitstream [ ] bits = bunds [ <NUM_LIT:0> ] . getBitstreams ( ) ; for ( int i = <NUM_LIT:0> ; ( i < bits . length ) && ! html ; i ++ ) { if ( bits [ i ] . getID ( ) == bunds [ <NUM_LIT:0> ] . getPrimaryBitstreamID ( ) ) { html = bits [ i ] . getFormat ( ) . getMIMEType ( ) . equals ( "<STR_LIT:text/html>" ) ; primaryBitstream = bits [ i ] ; } } } out . println ( "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" ) ; if ( multiFile ) { out . println ( "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" ) ; } out . println ( "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" ) ; if ( html ) { if ( handle == null ) { handle = "<STR_LIT>" + item . getID ( ) ; } String url = request . getContextPath ( ) + "<STR_LIT>" + handle + "<STR_LIT:/>" + UIUtil . encodeBitstreamName ( primaryBitstream . getName ( ) , Constants . DEFAULT_ENCODING ) ; out . print ( "<STR_LIT>" ) ; out . print ( "<STR_LIT>" ) ; out . print ( url + "<STR_LIT:\">" ) ; out . print ( "<STR_LIT>" + url + "<STR_LIT>" ) ; out . print ( "<STR_LIT>" ) ; out . print ( primaryBitstream . getName ( ) ) ; out . print ( "<STR_LIT>" ) ; if ( multiFile ) { out . print ( "<STR_LIT>" ) ; String desc = primaryBitstream . getDescription ( ) ; out . print ( ( desc != null ) ? desc : "<STR_LIT>" ) ; } out . print ( "<STR_LIT>" ) ; out . print ( UIUtil . formatFileSize ( primaryBitstream . getSize ( ) ) ) ; out . print ( "<STR_LIT>" ) ; out . print ( primaryBitstream . getFormatDescription ( ) ) ; out . print ( "<STR_LIT>" ) ; out . print ( request . getContextPath ( ) ) ; out . print ( "<STR_LIT>" ) ; out . print ( handle + "<STR_LIT:/>" ) ; out . print ( UIUtil . encodeBitstreamName ( primaryBitstream . getName ( ) , Constants . DEFAULT_ENCODING ) ) ; out . print ( "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" ) ; } else { for ( int i = <NUM_LIT:0> ; i < bundles . length ; i ++ ) { Bitstream [ ] bitstreams = bundles [ i ] . getBitstreams ( ) ; for ( Bitstream bitstream : bitstreams ) { if ( ! bitstream . getFormat ( ) . isInternal ( ) ) { String bsLink = "<STR_LIT>" ; String url = request . getContextPath ( ) ; if ( ( handle != null ) && ( bitstream . getSequenceID ( ) > <NUM_LIT:0> ) ) { url = url + "<STR_LIT>" + item . getHandle ( ) + "<STR_LIT:/>" + bitstream . getSequenceID ( ) + "<STR_LIT:/>" ; } else { url = url + "<STR_LIT>" + bitstream . getID ( ) + "<STR_LIT:/>" ; } url = url + UIUtil . encodeBitstreamName ( bitstream . getName ( ) , Constants . DEFAULT_ENCODING ) ; bsLink += url + "<STR_LIT:\">" ; bsLink += "<STR_LIT>" + url + "<STR_LIT>" ; bsLink += "<STR_LIT>" ; out . print ( "<STR_LIT>" ) ; out . print ( bsLink ) ; out . print ( bitstream . getName ( ) ) ; out . print ( "<STR_LIT>" ) ; if ( multiFile ) { out . print ( "<STR_LIT>" ) ; String desc = bitstream . getDescription ( ) ; out . print ( ( desc != null ) ? desc : "<STR_LIT>" ) ; } out . print ( "<STR_LIT>" ) ; out . print ( UIUtil . formatFileSize ( bitstream . getSize ( ) ) ) ; out . print ( "<STR_LIT>" ) ; out . print ( bitstream . getFormatDescription ( ) ) ; out . print ( "<STR_LIT>" ) ; if ( ( thumbs . length > <NUM_LIT:0> ) && showThumbs ) { String tName = bitstream . getName ( ) + "<STR_LIT>" ; String tAltText = LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) ; Bitstream tb = thumbs [ <NUM_LIT:0> ] . getBitstreamByName ( tName ) ; if ( tb != null ) { String myPath = request . getContextPath ( ) + "<STR_LIT>" + tb . getID ( ) + "<STR_LIT:/>" + UIUtil . encodeBitstreamName ( tb . getName ( ) , Constants . DEFAULT_ENCODING ) ; out . print ( bsLink ) ; out . print ( "<STR_LIT>" + myPath + "<STR_LIT>" ) ; out . print ( "<STR_LIT>" + tAltText + "<STR_LIT>" ) ; } } out . print ( bsLink + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" ) ; } } } } out . println ( "<STR_LIT>" ) ; } } catch ( SQLException sqle ) { throw new IOException ( sqle . getMessage ( ) , sqle ) ; } out . println ( "<STR_LIT>" ) ; } private void getThumbSettings ( ) { showThumbs = ConfigurationManager . getBooleanProperty ( "<STR_LIT>" ) ; } private void showLicence ( ) throws IOException { JspWriter out = pageContext . getOut ( ) ; HttpServletRequest request = ( HttpServletRequest ) pageContext . getRequest ( ) ; Bundle [ ] bundles = null ; try { bundles = item . getBundles ( "<STR_LIT>" ) ; } catch ( SQLException sqle ) { throw new IOException ( sqle . getMessage ( ) , sqle ) ; } out . println ( "<STR_LIT>" ) ; out . println ( "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < bundles . length ; i ++ ) { Bitstream [ ] bitstreams = bundles [ i ] . getBitstreams ( ) ; for ( int k = <NUM_LIT:0> ; k < bitstreams . length ; k ++ ) { out . print ( "<STR_LIT>" ) ; out . print ( "<STR_LIT>" ) ; out . print ( request . getContextPath ( ) ) ; out . print ( "<STR_LIT>" ) ; out . print ( bitstreams [ k ] . getID ( ) + "<STR_LIT:/>" ) ; out . print ( UIUtil . encodeBitstreamName ( bitstreams [ k ] . getName ( ) , Constants . DEFAULT_ENCODING ) ) ; out . print ( "<STR_LIT>" + LocaleSupport . getLocalizedMessage ( pageContext , "<STR_LIT>" ) + "<STR_LIT>" ) ; } } out . println ( "<STR_LIT>" ) ; } private String getBrowseField ( String field ) throws BrowseException { for ( String indexName : linkedMetadata . keySet ( ) ) { StringTokenizer bw_dcf = new StringTokenizer ( linkedMetadata . get ( indexName ) , "<STR_LIT:.>" ) ; String [ ] bw_tokens = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; int i = <NUM_LIT:0> ; while ( bw_dcf . hasMoreTokens ( ) ) { bw_tokens [ i ] = bw_dcf . nextToken ( ) . toLowerCase ( ) . trim ( ) ; i ++ ; } String bw_schema = bw_tokens [ <NUM_LIT:0> ] ; String bw_element = bw_tokens [ <NUM_LIT:1> ] ; String bw_qualifier = bw_tokens [ <NUM_LIT:2> ] ; StringTokenizer dcf = new StringTokenizer ( field , "<STR_LIT:.>" ) ; String [ ] tokens = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; int j = <NUM_LIT:0> ; while ( dcf . hasMoreTokens ( ) ) { tokens [ j ] = dcf . nextToken ( ) . toLowerCase ( ) . trim ( ) ; j ++ ; } String schema = tokens [ <NUM_LIT:0> ] ; String element = tokens [ <NUM_LIT:1> ] ; String qualifier = tokens [ <NUM_LIT:2> ] ; if ( schema . equals ( bw_schema ) && element . equals ( bw_element ) && ( ( bw_qualifier != null ) && ( ( qualifier != null && qualifier . equals ( bw_qualifier ) ) || bw_qualifier . equals ( "<STR_LIT:*>" ) ) || ( bw_qualifier == null && qualifier == null ) ) ) { return indexName ; } } return null ; } } </s>
|
<s> package org . dspace . statistics ; import com . Ostermiller . util . CSVParser ; import com . Ostermiller . util . CSVPrinter ; import com . maxmind . geoip . Location ; import com . maxmind . geoip . LookupService ; import org . apache . commons . httpclient . HttpClient ; import org . apache . commons . httpclient . methods . GetMethod ; import org . apache . commons . io . FileUtils ; import org . apache . commons . lang . time . DateFormatUtils ; import org . apache . log4j . Logger ; import org . apache . solr . client . solrj . SolrQuery ; import org . apache . solr . client . solrj . SolrServerException ; import org . apache . solr . client . solrj . impl . CommonsHttpSolrServer ; import org . apache . solr . client . solrj . request . AbstractUpdateRequest ; import org . apache . solr . client . solrj . request . ContentStreamUpdateRequest ; import org . apache . solr . client . solrj . response . FacetField ; import org . apache . solr . client . solrj . response . QueryResponse ; import org . apache . solr . client . solrj . util . ClientUtils ; import org . apache . solr . common . SolrDocument ; import org . apache . solr . common . SolrInputDocument ; import org . apache . solr . common . params . CommonParams ; import org . apache . solr . common . params . MapSolrParams ; import org . dspace . content . * ; import org . dspace . content . Collection ; import org . dspace . core . ConfigurationManager ; import org . dspace . core . Constants ; import org . dspace . core . Context ; import org . dspace . eperson . EPerson ; import org . dspace . statistics . util . DnsLookup ; import org . dspace . statistics . util . LocationUtils ; import org . dspace . statistics . util . SpiderDetector ; import javax . servlet . http . HttpServletRequest ; import java . io . * ; import java . net . URLEncoder ; import java . sql . SQLException ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . * ; public class SolrLogger { private static final Logger log = Logger . getLogger ( SolrLogger . class ) ; private static final CommonsHttpSolrServer solr ; public static final String DATE_FORMAT_8601 = "<STR_LIT>" ; public static final String DATE_FORMAT_DCDATE = "<STR_LIT>" ; private static final LookupService locationService ; private static final boolean useProxies ; private static Map < String , String > metadataStorageInfo ; static { CommonsHttpSolrServer server = null ; if ( ConfigurationManager . getBooleanProperty ( "<STR_LIT>" , "<STR_LIT>" , true ) ) { log . info ( "<STR_LIT>" + ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ) ; log . info ( "<STR_LIT>" + ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ) ; log . info ( "<STR_LIT>" + ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ) ; if ( ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) != null ) { try { server = new CommonsHttpSolrServer ( ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ) ; SolrQuery solrQuery = new SolrQuery ( ) . setQuery ( "<STR_LIT>" ) ; server . query ( solrQuery ) ; } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; } } solr = server ; LookupService service = null ; String dbfile = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; if ( dbfile != null ) { try { service = new LookupService ( dbfile , LookupService . GEOIP_STANDARD ) ; } catch ( FileNotFoundException fe ) { log . error ( "<STR_LIT>" + dbfile + "<STR_LIT>" , fe ) ; } catch ( IOException e ) { log . error ( "<STR_LIT>" + dbfile + "<STR_LIT>" , e ) ; } } else { log . error ( "<STR_LIT>" ) ; } locationService = service ; if ( "<STR_LIT:true>" . equals ( ConfigurationManager . getProperty ( "<STR_LIT>" ) ) ) { useProxies = true ; } else { useProxies = false ; } log . info ( "<STR_LIT>" + useProxies ) ; metadataStorageInfo = new HashMap < String , String > ( ) ; int count = <NUM_LIT:1> ; String metadataVal ; while ( ( metadataVal = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" + count ) ) != null ) { String storeVal = metadataVal . split ( "<STR_LIT::>" ) [ <NUM_LIT:0> ] ; String metadataField = metadataVal . split ( "<STR_LIT::>" ) [ <NUM_LIT:1> ] ; metadataStorageInfo . put ( storeVal , metadataField ) ; log . info ( "<STR_LIT>" + count + "<STR_LIT:=>" + metadataVal ) ; count ++ ; } } else { solr = null ; useProxies = false ; locationService = null ; } } public static void post ( DSpaceObject dspaceObject , HttpServletRequest request , EPerson currentUser ) { if ( solr == null || locationService == null ) { return ; } boolean isSpiderBot = SpiderDetector . isSpider ( request ) ; try { if ( isSpiderBot && ! ConfigurationManager . getBooleanProperty ( "<STR_LIT>" , "<STR_LIT>" , true ) ) { return ; } SolrInputDocument doc1 = new SolrInputDocument ( ) ; String ip = request . getRemoteAddr ( ) ; if ( isUseProxies ( ) && request . getHeader ( "<STR_LIT>" ) != null ) { for ( String xfip : request . getHeader ( "<STR_LIT>" ) . split ( "<STR_LIT:U+002C>" ) ) { if ( ! request . getHeader ( "<STR_LIT>" ) . contains ( ip ) ) { ip = xfip . trim ( ) ; } } } doc1 . addField ( "<STR_LIT>" , ip ) ; doc1 . addField ( "<STR_LIT:id>" , dspaceObject . getID ( ) ) ; doc1 . addField ( "<STR_LIT:type>" , dspaceObject . getType ( ) ) ; doc1 . addField ( "<STR_LIT>" , DateFormatUtils . format ( new Date ( ) , DATE_FORMAT_8601 ) ) ; if ( currentUser != null ) { doc1 . addField ( "<STR_LIT>" , currentUser . getID ( ) ) ; } try { String dns = DnsLookup . reverseDns ( ip ) ; doc1 . addField ( "<STR_LIT>" , dns . toLowerCase ( ) ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" + ip ) ; log . debug ( e . getMessage ( ) , e ) ; } Location location = locationService . getLocation ( ip ) ; if ( location != null && ! ( "<STR_LIT:-->" . equals ( location . countryCode ) && location . latitude == - <NUM_LIT> && location . longitude == - <NUM_LIT> ) ) { try { doc1 . addField ( "<STR_LIT>" , LocationUtils . getContinentCode ( location . countryCode ) ) ; } catch ( Exception e ) { System . out . println ( "<STR_LIT>" + location . countryCode ) ; } doc1 . addField ( "<STR_LIT>" , location . countryCode ) ; doc1 . addField ( "<STR_LIT>" , location . city ) ; doc1 . addField ( "<STR_LIT>" , location . latitude ) ; doc1 . addField ( "<STR_LIT>" , location . longitude ) ; doc1 . addField ( "<STR_LIT>" , isSpiderBot ) ; if ( request . getHeader ( "<STR_LIT>" ) != null ) { doc1 . addField ( "<STR_LIT>" , request . getHeader ( "<STR_LIT>" ) ) ; } } if ( dspaceObject instanceof Item ) { Item item = ( Item ) dspaceObject ; for ( Object storedField : metadataStorageInfo . keySet ( ) ) { String dcField = metadataStorageInfo . get ( storedField ) ; DCValue [ ] vals = item . getMetadata ( dcField . split ( "<STR_LIT:\\.>" ) [ <NUM_LIT:0> ] , dcField . split ( "<STR_LIT:\\.>" ) [ <NUM_LIT:1> ] , dcField . split ( "<STR_LIT:\\.>" ) [ <NUM_LIT:2> ] , Item . ANY ) ; for ( DCValue val1 : vals ) { String val = val1 . value ; doc1 . addField ( String . valueOf ( storedField ) , val ) ; doc1 . addField ( storedField + "<STR_LIT>" , val . toLowerCase ( ) ) ; } } } if ( dspaceObject instanceof Bitstream ) { Bitstream bit = ( Bitstream ) dspaceObject ; Bundle [ ] bundles = bit . getBundles ( ) ; for ( Bundle bundle : bundles ) { doc1 . addField ( "<STR_LIT>" , bundle . getName ( ) ) ; } } storeParents ( doc1 , dspaceObject ) ; solr . add ( doc1 ) ; } catch ( RuntimeException re ) { throw re ; } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; } } public static Map < String , String > getMetadataStorageInfo ( ) { return metadataStorageInfo ; } public static void storeParents ( SolrInputDocument doc1 , DSpaceObject dso ) throws SQLException { if ( dso instanceof Community ) { Community comm = ( Community ) dso ; while ( comm != null && comm . getParentCommunity ( ) != null ) { comm = comm . getParentCommunity ( ) ; doc1 . addField ( "<STR_LIT>" , comm . getID ( ) ) ; } } else if ( dso instanceof Collection ) { Collection coll = ( Collection ) dso ; for ( int i = <NUM_LIT:0> ; i < coll . getCommunities ( ) . length ; i ++ ) { Community community = coll . getCommunities ( ) [ i ] ; doc1 . addField ( "<STR_LIT>" , community . getID ( ) ) ; storeParents ( doc1 , community ) ; } } else if ( dso instanceof Item ) { Item item = ( Item ) dso ; for ( int i = <NUM_LIT:0> ; i < item . getCollections ( ) . length ; i ++ ) { Collection collection = item . getCollections ( ) [ i ] ; doc1 . addField ( "<STR_LIT>" , collection . getID ( ) ) ; storeParents ( doc1 , collection ) ; } } else if ( dso instanceof Bitstream ) { Bitstream bitstream = ( Bitstream ) dso ; for ( int i = <NUM_LIT:0> ; i < bitstream . getBundles ( ) . length ; i ++ ) { Bundle bundle = bitstream . getBundles ( ) [ i ] ; for ( int j = <NUM_LIT:0> ; j < bundle . getItems ( ) . length ; j ++ ) { Item item = bundle . getItems ( ) [ j ] ; doc1 . addField ( "<STR_LIT>" , item . getID ( ) ) ; storeParents ( doc1 , item ) ; } } } } public static boolean isUseProxies ( ) { return useProxies ; } public static void removeIndex ( String query ) throws IOException , SolrServerException { solr . deleteByQuery ( query ) ; solr . commit ( ) ; } public static Map < String , List < String > > queryField ( String query , List oldFieldVals , String field ) { Map < String , List < String > > currentValsStored = new HashMap < String , List < String > > ( ) ; try { Map < String , String > params = new HashMap < String , String > ( ) ; params . put ( "<STR_LIT:q>" , query ) ; params . put ( "<STR_LIT>" , "<STR_LIT:1>" ) ; MapSolrParams solrParams = new MapSolrParams ( params ) ; QueryResponse response = solr . query ( solrParams ) ; if ( response . getResults ( ) . getNumFound ( ) == <NUM_LIT:0> ) { return currentValsStored ; } SolrDocument document = response . getResults ( ) . get ( <NUM_LIT:0> ) ; for ( Object storedField : metadataStorageInfo . keySet ( ) ) { java . util . Collection collection = document . getFieldValues ( ( String ) storedField ) ; List < String > storedVals = new ArrayList < String > ( ) ; storedVals . addAll ( collection ) ; currentValsStored . put ( ( String ) storedField , storedVals ) ; } } catch ( SolrServerException e ) { e . printStackTrace ( ) ; } return currentValsStored ; } public static class ResultProcessor { public void execute ( String query ) throws SolrServerException , IOException { Map < String , String > params = new HashMap < String , String > ( ) ; params . put ( "<STR_LIT:q>" , query ) ; params . put ( "<STR_LIT>" , "<STR_LIT:10>" ) ; MapSolrParams solrParams = new MapSolrParams ( params ) ; QueryResponse response = solr . query ( solrParams ) ; long numbFound = response . getResults ( ) . getNumFound ( ) ; process ( response . getResults ( ) ) ; for ( int i = <NUM_LIT:10> ; i < numbFound ; i += <NUM_LIT:10> ) { params . put ( "<STR_LIT:start>" , String . valueOf ( i ) ) ; solrParams = new MapSolrParams ( params ) ; response = solr . query ( solrParams ) ; process ( response . getResults ( ) ) ; } } public void commit ( ) throws IOException , SolrServerException { solr . commit ( ) ; } public void process ( List < SolrDocument > docs ) throws IOException , SolrServerException { for ( SolrDocument doc : docs ) { process ( doc ) ; } } public void process ( SolrDocument doc ) throws IOException , SolrServerException { } } public static void markRobotsByIP ( ) { for ( String ip : SpiderDetector . getSpiderIpAddresses ( ) ) { try { ResultProcessor processor = new ResultProcessor ( ) { public void process ( SolrDocument doc ) throws IOException , SolrServerException { doc . removeFields ( "<STR_LIT>" ) ; doc . addField ( "<STR_LIT>" , true ) ; SolrInputDocument newInput = ClientUtils . toSolrInputDocument ( doc ) ; solr . add ( newInput ) ; log . info ( "<STR_LIT>" + doc . getFieldValue ( "<STR_LIT>" ) + "<STR_LIT>" ) ; } } ; processor . execute ( "<STR_LIT>" + ip + "<STR_LIT>" ) ; solr . commit ( ) ; } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; } } } public static void markRobotByUserAgent ( String agent ) { try { ResultProcessor processor = new ResultProcessor ( ) { public void process ( SolrDocument doc ) throws IOException , SolrServerException { doc . removeFields ( "<STR_LIT>" ) ; doc . addField ( "<STR_LIT>" , true ) ; SolrInputDocument newInput = ClientUtils . toSolrInputDocument ( doc ) ; solr . add ( newInput ) ; } } ; processor . execute ( "<STR_LIT>" + agent + "<STR_LIT>" ) ; solr . commit ( ) ; } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; } } public static void deleteRobotsByIsBotFlag ( ) { try { solr . deleteByQuery ( "<STR_LIT>" ) ; } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; } } public static void deleteIP ( String ip ) { try { solr . deleteByQuery ( "<STR_LIT>" + ip + "<STR_LIT:*>" ) ; } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; } } public static void deleteRobotsByIP ( ) { for ( String ip : SpiderDetector . getSpiderIpAddresses ( ) ) { deleteIP ( ip ) ; } } public static void update ( String query , String action , List < String > fieldNames , List < List < Object > > fieldValuesList ) throws SolrServerException , IOException { final List < SolrDocument > docsToUpdate = new ArrayList < SolrDocument > ( ) ; ResultProcessor processor = new ResultProcessor ( ) { public void process ( List < SolrDocument > docs ) throws IOException , SolrServerException { docsToUpdate . addAll ( docs ) ; } } ; processor . execute ( query ) ; solr . deleteByQuery ( query ) ; for ( int i = <NUM_LIT:0> ; i < docsToUpdate . size ( ) ; i ++ ) { SolrDocument solrDocument = docsToUpdate . get ( i ) ; for ( int j = <NUM_LIT:0> ; j < fieldNames . size ( ) ; j ++ ) { String fieldName = fieldNames . get ( j ) ; List < Object > fieldValues = fieldValuesList . get ( j ) ; if ( action . equals ( "<STR_LIT>" ) || action . equals ( "<STR_LIT>" ) ) { if ( action . equals ( "<STR_LIT>" ) ) { solrDocument . removeFields ( fieldName ) ; } for ( Object fieldValue : fieldValues ) { solrDocument . addField ( fieldName , fieldValue ) ; } } else if ( action . equals ( "<STR_LIT>" ) ) { java . util . Collection < Object > values = solrDocument . getFieldValues ( fieldName ) ; solrDocument . removeFields ( fieldName ) ; for ( Object value : values ) { if ( ! fieldValues . contains ( ( value ) ) ) { solrDocument . addField ( fieldName , value ) ; } } } } SolrInputDocument newInput = ClientUtils . toSolrInputDocument ( solrDocument ) ; solr . add ( newInput ) ; } solr . commit ( ) ; } public static void query ( String query , int max ) throws SolrServerException { query ( query , null , null , max , null , null , null , null ) ; } public static ObjectCount [ ] queryFacetField ( String query , String filterQuery , String facetField , int max , boolean showTotal , List < String > facetQueries ) throws SolrServerException { QueryResponse queryResponse = query ( query , filterQuery , facetField , max , null , null , null , facetQueries ) ; if ( queryResponse == null ) { return new ObjectCount [ <NUM_LIT:0> ] ; } FacetField field = queryResponse . getFacetField ( facetField ) ; if ( <NUM_LIT:0> < field . getValueCount ( ) ) { ObjectCount [ ] result = new ObjectCount [ field . getValueCount ( ) + ( showTotal ? <NUM_LIT:1> : <NUM_LIT:0> ) ] ; for ( int i = <NUM_LIT:0> ; i < field . getValues ( ) . size ( ) ; i ++ ) { FacetField . Count fieldCount = field . getValues ( ) . get ( i ) ; result [ i ] = new ObjectCount ( ) ; result [ i ] . setCount ( fieldCount . getCount ( ) ) ; result [ i ] . setValue ( fieldCount . getName ( ) ) ; } if ( showTotal ) { result [ result . length - <NUM_LIT:1> ] = new ObjectCount ( ) ; result [ result . length - <NUM_LIT:1> ] . setCount ( queryResponse . getResults ( ) . getNumFound ( ) ) ; result [ result . length - <NUM_LIT:1> ] . setValue ( "<STR_LIT>" ) ; } return result ; } else { return new ObjectCount [ <NUM_LIT:0> ] ; } } public static ObjectCount [ ] queryFacetDate ( String query , String filterQuery , int max , String dateType , String dateStart , String dateEnd , boolean showTotal ) throws SolrServerException { QueryResponse queryResponse = query ( query , filterQuery , null , max , dateType , dateStart , dateEnd , null ) ; if ( queryResponse == null ) { return new ObjectCount [ <NUM_LIT:0> ] ; } FacetField dateFacet = queryResponse . getFacetDate ( "<STR_LIT>" ) ; ObjectCount [ ] result = new ObjectCount [ dateFacet . getValueCount ( ) + ( showTotal ? <NUM_LIT:1> : <NUM_LIT:0> ) ] ; for ( int i = <NUM_LIT:0> ; i < dateFacet . getValues ( ) . size ( ) ; i ++ ) { FacetField . Count dateCount = dateFacet . getValues ( ) . get ( i ) ; result [ i ] = new ObjectCount ( ) ; result [ i ] . setCount ( dateCount . getCount ( ) ) ; result [ i ] . setValue ( getDateView ( dateCount . getName ( ) , dateType ) ) ; } if ( showTotal ) { result [ result . length - <NUM_LIT:1> ] = new ObjectCount ( ) ; result [ result . length - <NUM_LIT:1> ] . setCount ( queryResponse . getResults ( ) . getNumFound ( ) ) ; result [ result . length - <NUM_LIT:1> ] . setValue ( "<STR_LIT>" ) ; } return result ; } public static Map < String , Integer > queryFacetQuery ( String query , String filterQuery , List < String > facetQueries ) throws SolrServerException { QueryResponse response = query ( query , filterQuery , null , <NUM_LIT:1> , null , null , null , facetQueries ) ; return response . getFacetQuery ( ) ; } public static ObjectCount queryTotal ( String query , String filterQuery ) throws SolrServerException { QueryResponse queryResponse = query ( query , filterQuery , null , - <NUM_LIT:1> , null , null , null , null ) ; ObjectCount objCount = new ObjectCount ( ) ; objCount . setCount ( queryResponse . getResults ( ) . getNumFound ( ) ) ; return objCount ; } private static String getDateView ( String name , String type ) { if ( name != null && name . matches ( "<STR_LIT>" ) ) { Date date = null ; try { SimpleDateFormat format = new SimpleDateFormat ( DATE_FORMAT_8601 ) ; date = format . parse ( name ) ; } catch ( ParseException e ) { try { SimpleDateFormat format = new SimpleDateFormat ( DATE_FORMAT_DCDATE ) ; date = format . parse ( name ) ; } catch ( ParseException e1 ) { e1 . printStackTrace ( ) ; } } String dateformatString = "<STR_LIT>" ; if ( "<STR_LIT>" . equals ( type ) ) { dateformatString = "<STR_LIT>" ; } else if ( "<STR_LIT>" . equals ( type ) ) { dateformatString = "<STR_LIT>" ; } else if ( "<STR_LIT>" . equals ( type ) ) { dateformatString = "<STR_LIT>" ; } SimpleDateFormat simpleFormat = new SimpleDateFormat ( dateformatString ) ; if ( date != null ) { name = simpleFormat . format ( date ) ; } } return name ; } private static QueryResponse query ( String query , String filterQuery , String facetField , int max , String dateType , String dateStart , String dateEnd , List < String > facetQueries ) throws SolrServerException { if ( solr == null ) { return null ; } SolrQuery solrQuery = new SolrQuery ( ) . setRows ( <NUM_LIT:0> ) . setQuery ( query ) . setFacetMinCount ( <NUM_LIT:1> ) ; if ( dateType != null ) { solrQuery . setParam ( "<STR_LIT>" , "<STR_LIT>" ) . setParam ( "<STR_LIT>" , "<STR_LIT>" + dateType + dateEnd + dateType ) . setParam ( "<STR_LIT>" , "<STR_LIT>" + dateType ) . setParam ( "<STR_LIT>" , "<STR_LIT>" + dateType + dateStart + dateType + "<STR_LIT:S>" ) . setFacet ( true ) ; } if ( facetQueries != null ) { for ( int i = <NUM_LIT:0> ; i < facetQueries . size ( ) ; i ++ ) { String facetQuery = facetQueries . get ( i ) ; solrQuery . addFacetQuery ( facetQuery ) ; } if ( <NUM_LIT:0> < facetQueries . size ( ) ) { solrQuery . setFacet ( true ) ; } } if ( facetField != null ) { solrQuery . addFacetField ( facetField ) ; } if ( max != - <NUM_LIT:1> ) { solrQuery . setFacetLimit ( max ) ; } if ( ConfigurationManager . getBooleanProperty ( "<STR_LIT>" , "<STR_LIT>" , false ) ) { solrQuery . addFilterQuery ( getIgnoreSpiderIPs ( ) ) ; } if ( ConfigurationManager . getBooleanProperty ( "<STR_LIT>" , "<STR_LIT>" , true ) ) { solrQuery . addFilterQuery ( "<STR_LIT>" ) ; } String bundles ; if ( ( bundles = ConfigurationManager . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) ) != null && <NUM_LIT:0> < bundles . length ( ) ) { StringBuffer bundleQuery = new StringBuffer ( ) ; bundleQuery . append ( "<STR_LIT>" ) ; String [ ] split = bundles . split ( "<STR_LIT:U+002C>" ) ; for ( int i = <NUM_LIT:0> ; i < split . length ; i ++ ) { String bundle = split [ i ] . trim ( ) ; bundleQuery . append ( "<STR_LIT>" ) . append ( bundle ) ; if ( i != split . length - <NUM_LIT:1> ) { bundleQuery . append ( "<STR_LIT>" ) ; } } bundleQuery . append ( "<STR_LIT:)>" ) ; solrQuery . addFilterQuery ( bundleQuery . toString ( ) ) ; } if ( filterQuery != null ) { solrQuery . addFilterQuery ( filterQuery ) ; } QueryResponse response ; try { response = solr . query ( solrQuery ) ; } catch ( SolrServerException e ) { System . err . println ( "<STR_LIT>" + query ) ; throw e ; } return response ; } private static String filterQuery = null ; public static String getIgnoreSpiderIPs ( ) { if ( filterQuery == null ) { StringBuilder query = new StringBuilder ( ) ; boolean first = true ; for ( String ip : SpiderDetector . getSpiderIpAddresses ( ) ) { if ( first ) { query . append ( "<STR_LIT>" ) ; first = false ; } query . append ( "<STR_LIT>" ) . append ( ip ) . append ( "<STR_LIT:)>" ) ; } filterQuery = query . toString ( ) ; } return filterQuery ; } public static void optimizeSOLR ( ) { try { long start = System . currentTimeMillis ( ) ; System . out . println ( "<STR_LIT>" + start ) ; solr . optimize ( ) ; long finish = System . currentTimeMillis ( ) ; System . out . println ( "<STR_LIT>" + finish ) ; System . out . println ( "<STR_LIT>" + ( finish - start ) + "<STR_LIT>" ) ; } catch ( SolrServerException sse ) { System . err . println ( sse . getMessage ( ) ) ; } catch ( IOException ioe ) { System . err . println ( ioe . getMessage ( ) ) ; } } public static void reindexBitstreamHits ( boolean removeDeletedBitstreams ) throws Exception { Context context = new Context ( ) ; try { SolrQuery query = new SolrQuery ( ) ; query . setQuery ( "<STR_LIT>" ) ; query . addFilterQuery ( "<STR_LIT>" + Constants . BITSTREAM ) ; query . addFilterQuery ( "<STR_LIT>" ) ; query . setRows ( <NUM_LIT:0> ) ; long totalRecords = solr . query ( query ) . getResults ( ) . getNumFound ( ) ; File tempDirectory = new File ( ConfigurationManager . getProperty ( "<STR_LIT>" ) + File . separator + "<STR_LIT>" + File . separator ) ; tempDirectory . mkdirs ( ) ; List < File > tempCsvFiles = new ArrayList < File > ( ) ; for ( int i = <NUM_LIT:0> ; i < totalRecords ; i += <NUM_LIT> ) { Map < String , String > params = new HashMap < String , String > ( ) ; params . put ( CommonParams . Q , "<STR_LIT>" ) ; params . put ( CommonParams . FQ , "<STR_LIT>" + Constants . BITSTREAM ) ; params . put ( CommonParams . WT , "<STR_LIT>" ) ; params . put ( CommonParams . ROWS , String . valueOf ( <NUM_LIT> ) ) ; params . put ( CommonParams . START , String . valueOf ( i ) ) ; String solrRequestUrl = solr . getBaseURL ( ) + "<STR_LIT>" ; solrRequestUrl = generateURL ( solrRequestUrl , params ) ; GetMethod get = new GetMethod ( solrRequestUrl ) ; new HttpClient ( ) . executeMethod ( get ) ; InputStream csvOutput = get . getResponseBodyAsStream ( ) ; Reader csvReader = new InputStreamReader ( csvOutput ) ; String [ ] [ ] csvParsed = CSVParser . parse ( csvReader ) ; String [ ] header = csvParsed [ <NUM_LIT:0> ] ; int idIndex = <NUM_LIT:0> ; for ( int j = <NUM_LIT:0> ; j < header . length ; j ++ ) { if ( header [ j ] . equals ( "<STR_LIT:id>" ) ) { idIndex = j ; } } File tempCsv = new File ( tempDirectory . getPath ( ) + File . separatorChar + "<STR_LIT>" + i + "<STR_LIT>" ) ; tempCsvFiles . add ( tempCsv ) ; FileOutputStream outputStream = new FileOutputStream ( tempCsv ) ; CSVPrinter csvp = new CSVPrinter ( outputStream ) ; csvp . setAlwaysQuote ( false ) ; csvp . write ( header ) ; csvp . write ( "<STR_LIT>" ) ; csvp . writeln ( ) ; Map < Integer , String > bitBundleCache = new HashMap < Integer , String > ( ) ; for ( int j = <NUM_LIT:1> ; j < csvParsed . length ; j ++ ) { String [ ] csvLine = csvParsed [ j ] ; int bitstreamId = Integer . parseInt ( csvLine [ idIndex ] ) ; String bundleName = bitBundleCache . get ( bitstreamId ) ; if ( bundleName == null ) { Bitstream bitstream = Bitstream . find ( context , bitstreamId ) ; if ( bitstream != null ) { Bundle [ ] bundles = bitstream . getBundles ( ) ; if ( bundles != null && <NUM_LIT:0> < bundles . length ) { Bundle bundle = bundles [ <NUM_LIT:0> ] ; bundleName = bundle . getName ( ) ; context . removeCached ( bundle , bundle . getID ( ) ) ; } else { DSpaceObject parentObject = bitstream . getParentObject ( ) ; if ( parentObject instanceof Collection ) { bundleName = "<STR_LIT>" ; } else if ( parentObject instanceof Community ) { bundleName = "<STR_LIT>" ; } if ( parentObject != null ) { context . removeCached ( parentObject , parentObject . getID ( ) ) ; } } bitBundleCache . put ( bitstream . getID ( ) , bundleName ) ; context . removeCached ( bitstream , bitstreamId ) ; } if ( bundleName == null && ! removeDeletedBitstreams ) { bundleName = "<STR_LIT>" ; } } csvp . write ( csvLine ) ; csvp . write ( bundleName ) ; csvp . writeln ( ) ; } csvp . flush ( ) ; csvp . close ( ) ; } for ( File tempCsv : tempCsvFiles ) { ContentStreamUpdateRequest contentStreamUpdateRequest = new ContentStreamUpdateRequest ( "<STR_LIT>" ) ; contentStreamUpdateRequest . setParam ( "<STR_LIT>" , "<STR_LIT>" ) ; contentStreamUpdateRequest . setAction ( AbstractUpdateRequest . ACTION . COMMIT , true , true ) ; contentStreamUpdateRequest . addFile ( tempCsv ) ; solr . request ( contentStreamUpdateRequest ) ; } solr . deleteByQuery ( "<STR_LIT>" + Constants . BITSTREAM ) ; solr . commit ( true , true ) ; FileUtils . deleteDirectory ( tempDirectory ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" , e ) ; throw e ; } finally { context . abort ( ) ; } } private static String generateURL ( String baseURL , Map < String , String > parameters ) throws UnsupportedEncodingException { boolean first = true ; StringBuilder result = new StringBuilder ( baseURL ) ; for ( String key : parameters . keySet ( ) ) { if ( first ) { result . append ( "<STR_LIT:?>" ) ; first = false ; } else { result . append ( "<STR_LIT:&>" ) ; } result . append ( key ) . append ( "<STR_LIT:=>" ) . append ( URLEncoder . encode ( parameters . get ( key ) , "<STR_LIT:UTF-8>" ) ) ; } return result . toString ( ) ; } } </s>
|
<s> import static org . junit . Assert . * ; import java . util . Random ; import java . util . logging . Level ; import org . bukkit . ChatColor ; import org . junit . Test ; import com . tommytony . karma . KarmaGroup ; import com . tommytony . karma . KarmaPlayer ; public class KarmaSandbox { @ Test public void testDaysAgo ( ) { long now = System . currentTimeMillis ( ) ; long twelveHoursAgo = now - ( <NUM_LIT:12> * <NUM_LIT> * <NUM_LIT:1000> ) ; long oneDayAgo = now - ( <NUM_LIT:24> * <NUM_LIT> * <NUM_LIT:1000> ) ; long threeAndHalfDaysAgo = now - ( <NUM_LIT> * <NUM_LIT> * <NUM_LIT:1000> ) ; long gone = System . currentTimeMillis ( ) - now ; int howManyDays = ( int ) Math . floor ( gone / <NUM_LIT> ) ; assertEquals ( <NUM_LIT:0> , howManyDays ) ; gone = System . currentTimeMillis ( ) - twelveHoursAgo ; howManyDays = ( int ) Math . floor ( gone / <NUM_LIT> ) ; assertEquals ( <NUM_LIT:0> , howManyDays ) ; gone = System . currentTimeMillis ( ) - oneDayAgo ; howManyDays = ( int ) Math . floor ( gone / <NUM_LIT> ) ; assertEquals ( <NUM_LIT:1> , howManyDays ) ; gone = System . currentTimeMillis ( ) - threeAndHalfDaysAgo ; howManyDays = ( int ) Math . floor ( gone / <NUM_LIT> ) ; assertEquals ( <NUM_LIT:3> , howManyDays ) ; } @ Test public void testLastActive ( ) { long now = System . currentTimeMillis ( ) ; long twominutesago = now - <NUM_LIT> * <NUM_LIT:1000> ; long fifteenminutesago = now - <NUM_LIT:15> * <NUM_LIT> * <NUM_LIT:1000> ; long activeInterval = System . currentTimeMillis ( ) - fifteenminutesago ; int minutesAfk = ( int ) Math . floor ( activeInterval / ( <NUM_LIT:1000> * <NUM_LIT> ) ) ; assertEquals ( <NUM_LIT:15> , minutesAfk ) ; assertFalse ( minutesAfk < <NUM_LIT:15> ) ; } @ Test public void testStartBonus ( ) { KarmaGroup greybeard = new KarmaGroup ( "<STR_LIT>" , <NUM_LIT> , null , ChatColor . AQUA ) ; KarmaGroup moderator = new KarmaGroup ( "<STR_LIT>" , <NUM_LIT:1000> , greybeard , ChatColor . AQUA ) ; KarmaGroup minimod = new KarmaGroup ( "<STR_LIT>" , <NUM_LIT> , moderator , ChatColor . AQUA ) ; KarmaGroup zonemaker = new KarmaGroup ( "<STR_LIT>" , <NUM_LIT:100> , minimod , ChatColor . AQUA ) ; KarmaGroup builder = new KarmaGroup ( "<STR_LIT>" , <NUM_LIT:10> , zonemaker , ChatColor . AQUA ) ; KarmaGroup recruit = new KarmaGroup ( "<STR_LIT>" , <NUM_LIT:0> , builder , ChatColor . AQUA ) ; KarmaGroup group = recruit ; int initialKarma = <NUM_LIT:0> ; int karmaToNext = <NUM_LIT:0> ; while ( group != null ) { if ( hasPermission ( "<STR_LIT>" + group . getGroupName ( ) ) ) { initialKarma = group . getKarmaPoints ( ) ; if ( group . getNext ( ) != null ) { karmaToNext = group . getNext ( ) . getKarmaPoints ( ) - group . getKarmaPoints ( ) ; } else { karmaToNext = <NUM_LIT:100> ; } } else { break ; } group = group . getNext ( ) ; } initialKarma += ( int ) ( <NUM_LIT> * karmaToNext ) ; assertEquals ( <NUM_LIT> , initialKarma ) ; } private boolean hasPermission ( String string ) { string = string . replace ( "<STR_LIT>" , "<STR_LIT>" ) ; if ( string . equals ( "<STR_LIT>" ) ) { return true ; } else if ( string . equals ( "<STR_LIT>" ) ) { return true ; } else if ( string . equals ( "<STR_LIT>" ) ) { return true ; } else if ( string . equals ( "<STR_LIT>" ) ) { return true ; } else if ( string . equals ( "<STR_LIT>" ) ) { return true ; } else { return true ; } } } </s>
|
<s> package com . tommytony . karma ; import java . util . Random ; import java . util . logging . Level ; import org . bukkit . ChatColor ; import org . bukkit . entity . Player ; import com . tommytony . war . Team ; import com . tommytony . war . War ; import com . tommytony . war . Warzone ; public class KarmaParty implements Runnable { private final Karma karma ; private final Random random = new Random ( ) ; public KarmaParty ( Karma karma ) { this . karma = karma ; } public void run ( ) { for ( Player player : this . karma . getServer ( ) . getOnlinePlayers ( ) ) { this . karma . msg ( player , "<STR_LIT>" + ChatColor . GREEN + "<STR_LIT>" + ChatColor . GRAY + "<STR_LIT>" ) ; } String playerList = "<STR_LIT>" ; for ( String playerName : this . karma . getPlayers ( ) . keySet ( ) ) { KarmaPlayer player = this . karma . getPlayers ( ) . get ( playerName ) ; long activeInterval = System . currentTimeMillis ( ) - player . getLastActivityTime ( ) ; int minutesAfk = ( int ) Math . floor ( activeInterval / ( <NUM_LIT:1000> * <NUM_LIT> ) ) ; Player p = this . karma . findPlayer ( player . getName ( ) ) ; if ( minutesAfk < <NUM_LIT:10> ) { int warPlayBonus = getWarPlayingBonus ( player , p ) ; int warZonemakerBonus = getZonemakerBonus ( player , p ) ; int total = <NUM_LIT:1> + warPlayBonus + warZonemakerBonus ; if ( total > <NUM_LIT:1> ) { this . karma . msg ( p , "<STR_LIT>" + ChatColor . GREEN + total + ChatColor . GRAY + "<STR_LIT>" ) ; } else { this . karma . msg ( p , "<STR_LIT>" + ChatColor . GREEN + "<STR_LIT:1>" + ChatColor . GRAY + "<STR_LIT>" ) ; } player . addKarma ( total ) ; playerList += playerName + "<STR_LIT:U+002CU+0020>" ; } else { this . karma . msg ( p , "<STR_LIT>" + ChatColor . GREEN + "<STR_LIT:1>" + ChatColor . GRAY + "<STR_LIT>" ) ; } } if ( ! playerList . equals ( "<STR_LIT>" ) ) { this . karma . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" + playerList + "<STR_LIT>" ) ; } this . karma . getKarmaDatabase ( ) . putAll ( ) ; this . karma . getServer ( ) . getScheduler ( ) . scheduleSyncDelayedTask ( this . karma , new KarmaParty ( this . karma ) , this . karma . getNextRandomKarmaPartyDelay ( ) ) ; } private int getWarPlayingBonus ( KarmaPlayer karmaPlayer , Player player ) { if ( Warzone . getZoneByPlayerName ( karmaPlayer . getName ( ) ) != null ) { if ( random . nextInt ( <NUM_LIT:3> ) == <NUM_LIT:2> ) { karma . msg ( player , "<STR_LIT>" ) ; return <NUM_LIT:1> ; } } return <NUM_LIT:0> ; } private int getZonemakerBonus ( KarmaPlayer karmaPlayer , Player player ) { for ( Warzone zone : War . war . getWarzones ( ) ) { for ( String author : zone . getAuthors ( ) ) { if ( author . equals ( karmaPlayer . getName ( ) ) && ! zoneIsEmpty ( zone ) && zone . isEnoughPlayers ( ) ) { if ( random . nextInt ( <NUM_LIT:3> ) == <NUM_LIT:2> ) { karma . msg ( player , "<STR_LIT>" ) ; return <NUM_LIT:1> ; } } } } return <NUM_LIT:0> ; } private boolean zoneIsEmpty ( Warzone zone ) { for ( Team team : zone . getTeams ( ) ) { if ( team . getPlayers ( ) . size ( ) > <NUM_LIT:0> ) { return false ; } } return true ; } } </s>
|
<s> package com . tommytony . karma ; import org . bukkit . event . EventHandler ; import org . bukkit . event . Listener ; import org . bukkit . event . world . WorldSaveEvent ; public class KarmaWorldListener implements Listener { private final Karma karma ; public KarmaWorldListener ( Karma karma ) { this . karma = karma ; } @ EventHandler public void onWorldSave ( final WorldSaveEvent event ) { this . karma . getKarmaDatabase ( ) . putAll ( ) ; } } </s>
|
<s> package com . tommytony . karma ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import java . util . logging . Level ; public class Database { private final Karma karma ; public Database ( Karma karmaPlugin ) { this . karma = karmaPlugin ; } public boolean exists ( String playerName ) { boolean exists = false ; if ( this . sqlite ( ) ) { try { Connection conn = this . getConnection ( ) ; Statement stat = conn . createStatement ( ) ; ResultSet result = stat . executeQuery ( "<STR_LIT>" + playerName + "<STR_LIT:'>" ) ; exists = result . next ( ) ; result . close ( ) ; stat . close ( ) ; conn . close ( ) ; } catch ( SQLException e ) { this . karma . getServer ( ) . getLogger ( ) . log ( Level . WARNING , "<STR_LIT>" + playerName + "<STR_LIT>" + e . toString ( ) ) ; } } return exists ; } public KarmaPlayer get ( String playerName ) { KarmaPlayer karmaPlayer = null ; if ( this . sqlite ( ) ) { try { Connection conn = this . getConnection ( ) ; Statement stat = conn . createStatement ( ) ; ResultSet result = stat . executeQuery ( "<STR_LIT>" + playerName + "<STR_LIT:'>" ) ; if ( result . next ( ) ) { karmaPlayer = new KarmaPlayer ( this . karma , playerName , result . getInt ( "<STR_LIT>" ) , result . getLong ( "<STR_LIT>" ) , result . getLong ( "<STR_LIT>" ) ) ; } result . close ( ) ; stat . close ( ) ; conn . close ( ) ; } catch ( SQLException e ) { this . karma . getServer ( ) . getLogger ( ) . log ( Level . WARNING , "<STR_LIT>" + playerName + "<STR_LIT>" + e . toString ( ) ) ; } } return karmaPlayer ; } public void put ( KarmaPlayer karmaPlayer ) { if ( this . sqlite ( ) ) { boolean exists = this . exists ( karmaPlayer . getName ( ) ) ; try { Connection conn = this . getConnection ( ) ; Statement stat = conn . createStatement ( ) ; if ( exists ) { stat . executeUpdate ( "<STR_LIT>" + karmaPlayer . getKarmaPoints ( ) + "<STR_LIT>" + karmaPlayer . getLastActivityTime ( ) + "<STR_LIT>" + karmaPlayer . getLastGiftTime ( ) + "<STR_LIT>" + karmaPlayer . getName ( ) + "<STR_LIT:'>" ) ; } else { stat . executeUpdate ( "<STR_LIT>" + karmaPlayer . getName ( ) + "<STR_LIT>" + karmaPlayer . getKarmaPoints ( ) + "<STR_LIT:U+002CU+0020>" + karmaPlayer . getLastActivityTime ( ) + "<STR_LIT:U+002CU+0020>" + karmaPlayer . getLastGiftTime ( ) + "<STR_LIT>" ) ; } stat . close ( ) ; conn . close ( ) ; } catch ( SQLException e ) { if ( exists ) { this . karma . getServer ( ) . getLogger ( ) . log ( Level . WARNING , "<STR_LIT>" + karmaPlayer . getName ( ) + "<STR_LIT>" + e . toString ( ) ) ; } else { this . karma . getServer ( ) . getLogger ( ) . log ( Level . WARNING , "<STR_LIT>" + karmaPlayer . getName ( ) + "<STR_LIT>" + e . toString ( ) ) ; } } } } public void putAll ( ) { for ( String playerName : this . karma . getPlayers ( ) . keySet ( ) ) { KarmaPlayer player = this . karma . getPlayers ( ) . get ( playerName ) ; this . put ( player ) ; } } public void initialize ( ) { if ( this . karma . getDataFolder ( ) . mkdir ( ) ) { this . karma . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" ) ; } if ( this . sqlite ( ) ) { try { Connection connection = this . getConnection ( ) ; Statement statement = connection . createStatement ( ) ; statement . executeUpdate ( "<STR_LIT>" ) ; boolean updatedSchema = true ; try { Statement alterStatement = connection . createStatement ( ) ; alterStatement . executeUpdate ( "<STR_LIT>" ) ; } catch ( SQLException e ) { updatedSchema = false ; } this . addColumn ( connection , "<STR_LIT>" ) ; this . addColumn ( connection , "<STR_LIT>" ) ; statement . close ( ) ; connection . close ( ) ; } catch ( SQLException e ) { this . karma . getServer ( ) . getLogger ( ) . log ( Level . WARNING , "<STR_LIT>" + e . toString ( ) ) ; } } } private void addColumn ( Connection connection , String newColumn ) { boolean updatedSchema = true ; try { Statement alterStatement = connection . createStatement ( ) ; alterStatement . executeUpdate ( "<STR_LIT>" + newColumn ) ; } catch ( SQLException e ) { updatedSchema = false ; } if ( updatedSchema ) { this . karma . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" + newColumn + "<STR_LIT:.>" ) ; } } private boolean sqlite ( ) { try { Class . forName ( "<STR_LIT>" ) ; } catch ( ClassNotFoundException e ) { this . karma . getServer ( ) . getLogger ( ) . log ( Level . WARNING , "<STR_LIT>" ) ; return false ; } return true ; } private Connection getConnection ( ) throws SQLException { return DriverManager . getConnection ( "<STR_LIT>" ) ; } } </s>
|
<s> package com . tommytony . karma ; public class KarmaPlayer { private final Karma karma ; private final String name ; private int karmaPoints ; private long lastActivityTime ; private long lastGift ; private long lastPrize ; public KarmaPlayer ( Karma karma , String name , int karmaPoints , long lastActivityTime , long lastGift ) { this . karma = karma ; this . name = name ; this . karmaPoints = karmaPoints ; this . lastActivityTime = lastActivityTime ; this . lastGift = lastGift ; } public void addKarma ( int pointsToAdd ) { if ( pointsToAdd > <NUM_LIT:0> ) { int before = this . karmaPoints ; this . karmaPoints += pointsToAdd ; this . karma . checkForPromotion ( name , before , this . karmaPoints ) ; this . karma . getKarmaDatabase ( ) . put ( this ) ; } } public void removeKarma ( int pointsToRemove ) { this . removeKarma ( pointsToRemove , false ) ; } public void removeKarmaAutomatic ( int pointsToRemove ) { this . removeKarma ( pointsToRemove , true ) ; } private void removeKarma ( int pointsToRemove , boolean automatic ) { if ( pointsToRemove > this . karmaPoints ) { pointsToRemove = this . karmaPoints ; } if ( pointsToRemove > <NUM_LIT:0> ) { int before = this . karmaPoints ; this . karmaPoints -= pointsToRemove ; this . karma . checkForDemotion ( name , before , this . karmaPoints , automatic ) ; this . karma . getKarmaDatabase ( ) . put ( this ) ; } } public String getName ( ) { return name ; } public int getKarmaPoints ( ) { return karmaPoints ; } public long getLastActivityTime ( ) { return lastActivityTime ; } public void ping ( ) { this . lastActivityTime = System . currentTimeMillis ( ) ; } public void updateLastGiftTime ( ) { this . lastGift = System . currentTimeMillis ( ) ; } public long getLastGiftTime ( ) { return lastGift ; } public boolean canGift ( ) { long since = System . currentTimeMillis ( ) - getLastGiftTime ( ) ; return since > <NUM_LIT> * <NUM_LIT:1000> ; } } </s>
|
<s> package com . tommytony . karma ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Random ; import java . util . logging . Level ; import org . bukkit . ChatColor ; import org . bukkit . command . Command ; import org . bukkit . command . CommandSender ; import org . bukkit . entity . Player ; import org . bukkit . plugin . Plugin ; import org . bukkit . plugin . PluginManager ; import org . bukkit . plugin . java . JavaPlugin ; import com . nijiko . permissions . PermissionHandler ; import com . nijikokun . bukkit . Permissions . Permissions ; public class Karma extends JavaPlugin { public static PermissionHandler permissionHandler ; private Map < String , KarmaPlayer > players ; private Database db ; private KarmaGroup startGroup ; private Random random = new Random ( ) ; public void onDisable ( ) { this . getServer ( ) . getScheduler ( ) . cancelTasks ( this ) ; this . db . putAll ( ) ; players . clear ( ) ; this . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" ) ; } public void onEnable ( ) { this . players = new HashMap < String , KarmaPlayer > ( ) ; this . db = new Database ( this ) ; this . db . initialize ( ) ; this . setupPermissions ( ) ; KarmaGroup greybeard = new KarmaGroup ( "<STR_LIT>" , <NUM_LIT> , null , ChatColor . DARK_GREEN ) ; KarmaGroup moderator = new KarmaGroup ( "<STR_LIT>" , <NUM_LIT:1000> , greybeard , ChatColor . DARK_AQUA ) ; KarmaGroup minimod = new KarmaGroup ( "<STR_LIT>" , <NUM_LIT> , moderator , ChatColor . AQUA ) ; KarmaGroup zonemaker = new KarmaGroup ( "<STR_LIT>" , <NUM_LIT:100> , minimod , ChatColor . GOLD ) ; KarmaGroup builder = new KarmaGroup ( "<STR_LIT>" , <NUM_LIT:10> , zonemaker , ChatColor . GRAY ) ; KarmaGroup recruit = new KarmaGroup ( "<STR_LIT>" , <NUM_LIT:0> , builder , ChatColor . LIGHT_PURPLE ) ; this . startGroup = recruit ; PluginManager manager = this . getServer ( ) . getPluginManager ( ) ; KarmaWorldListener worldListener = new KarmaWorldListener ( this ) ; manager . registerEvents ( worldListener , this ) ; KarmaPlayerListener playerListener = new KarmaPlayerListener ( this ) ; manager . registerEvents ( playerListener , this ) ; this . getServer ( ) . getScheduler ( ) . scheduleSyncDelayedTask ( this , new LoadPlayers ( this ) ) ; this . getServer ( ) . getScheduler ( ) . scheduleSyncDelayedTask ( this , new KarmaParty ( this ) , this . getNextRandomKarmaPartyDelay ( ) ) ; this . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" ) ; } public void setupPermissions ( ) { Plugin permissionsPlugin = this . getServer ( ) . getPluginManager ( ) . getPlugin ( "<STR_LIT>" ) ; if ( Karma . permissionHandler == null ) { if ( permissionsPlugin != null ) { Karma . permissionHandler = ( ( Permissions ) permissionsPlugin ) . getHandler ( ) ; } else { this . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" , Level . INFO ) ; } } } @ Override public boolean onCommand ( CommandSender sender , Command command , String label , String [ ] args ) { try { if ( command . getName ( ) . equals ( "<STR_LIT>" ) || command . getName ( ) . equals ( "<STR_LIT>" ) ) { if ( args . length == <NUM_LIT:0> && sender instanceof Player ) { KarmaPlayer karmaPlayer = this . players . get ( ( ( Player ) sender ) . getName ( ) ) ; if ( karmaPlayer != null ) { this . msg ( sender , "<STR_LIT>" + ChatColor . GREEN + karmaPlayer . getKarmaPoints ( ) + ChatColor . GRAY + "<STR_LIT>" + this . getPlayerGroupString ( karmaPlayer ) + "<STR_LIT>" + this . getPlayerNextGroupString ( karmaPlayer ) + "<STR_LIT:.>" ) ; return true ; } } else if ( args . length == <NUM_LIT:1> && ( args [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) || args [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) || args [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) ) ) { String ranksString = "<STR_LIT>" ; KarmaGroup group = this . startGroup ; while ( group != null ) { ranksString += group . getGroupName ( ) + "<STR_LIT:(>" + ChatColor . GREEN + group . getKarmaPoints ( ) + ChatColor . GRAY + "<STR_LIT:)>" ; if ( group . getNext ( ) != null ) ranksString += ChatColor . WHITE + "<STR_LIT>" + ChatColor . GRAY ; group = group . getNext ( ) ; } this . msg ( sender , ranksString ) ; return true ; } else if ( args . length == <NUM_LIT:1> && ( args [ <NUM_LIT:0> ] . equals ( "<STR_LIT:?>" ) || args [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) ) ) { return false ; } else if ( args . length == <NUM_LIT:1> ) { List < Player > matches = this . getServer ( ) . matchPlayer ( args [ <NUM_LIT:0> ] ) ; if ( ! matches . isEmpty ( ) ) { Player playerTarget = matches . get ( <NUM_LIT:0> ) ; KarmaPlayer karmaTarget = this . players . get ( playerTarget . getName ( ) ) ; if ( karmaTarget != null ) { this . msg ( sender , ChatColor . WHITE + playerTarget . getName ( ) + ChatColor . GRAY + "<STR_LIT>" + ChatColor . GREEN + karmaTarget . getKarmaPoints ( ) + ChatColor . GRAY + "<STR_LIT>" ) ; return true ; } else { this . msg ( sender , "<STR_LIT>" ) ; return true ; } } else { this . msg ( sender , "<STR_LIT>" ) ; return true ; } } else if ( args . length == <NUM_LIT:2> && ( args [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) || args [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) ) && ( ! ( sender instanceof Player ) || Karma . permissionHandler . has ( ( Player ) sender , "<STR_LIT>" ) ) ) { List < Player > matches = this . getServer ( ) . matchPlayer ( args [ <NUM_LIT:1> ] ) ; KarmaGroup builder = this . startGroup . getNext ( ) ; if ( ! matches . isEmpty ( ) ) { Player playerTarget = matches . get ( <NUM_LIT:0> ) ; KarmaPlayer karmaTarget = this . players . get ( playerTarget . getName ( ) ) ; if ( karmaTarget != null && karmaTarget . getKarmaPoints ( ) < builder . getKarmaPoints ( ) ) { karmaTarget . addKarma ( builder . getKarmaPoints ( ) - karmaTarget . getKarmaPoints ( ) ) ; this . msg ( playerTarget , "<STR_LIT>" ) ; return true ; } else { this . msg ( sender , "<STR_LIT>" ) ; return true ; } } else { this . msg ( sender , "<STR_LIT>" ) ; return true ; } } else if ( args . length == <NUM_LIT:2> && ( args [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) || args [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) ) && ( ! ( sender instanceof Player ) || Karma . permissionHandler . has ( ( Player ) sender , "<STR_LIT>" ) ) ) { String target = args [ <NUM_LIT:1> ] ; List < Player > matches = this . getServer ( ) . matchPlayer ( target ) ; KarmaPlayer karmaGiver = null ; if ( sender instanceof Player ) { karmaGiver = this . players . get ( ( ( Player ) sender ) . getName ( ) ) ; } if ( karmaGiver == null || karmaGiver . getKarmaPoints ( ) > <NUM_LIT:0> ) { Player playerTarget = matches . get ( <NUM_LIT:0> ) ; KarmaPlayer karmaTarget = this . getPlayers ( ) . get ( playerTarget . getName ( ) ) ; if ( karmaTarget != null && ! sender . getName ( ) . equals ( playerTarget . getName ( ) ) ) { String gifterName = "<STR_LIT>" ; if ( karmaGiver != null ) { gifterName = ( ( Player ) sender ) . getName ( ) ; if ( karmaGiver . canGift ( ) ) { karmaGiver . updateLastGiftTime ( ) ; karmaGiver . removeKarma ( <NUM_LIT:1> ) ; this . msg ( sender , "<STR_LIT>" + ChatColor . WHITE + playerTarget . getName ( ) + ChatColor . GREEN + "<STR_LIT>" + ChatColor . GRAY + "<STR_LIT>" ) ; } else { long since = ( System . currentTimeMillis ( ) - karmaGiver . getLastGiftTime ( ) ) / <NUM_LIT:1000> ; this . msg ( sender , "<STR_LIT>" + ( ( <NUM_LIT> - since ) / <NUM_LIT> ) + "<STR_LIT>" ) ; return true ; } } karmaTarget . addKarma ( <NUM_LIT:1> ) ; this . msg ( playerTarget , "<STR_LIT>" + ChatColor . GREEN + "<STR_LIT:1>" + ChatColor . GRAY + "<STR_LIT>" + ChatColor . WHITE + gifterName + ChatColor . GRAY + "<STR_LIT>" ) ; this . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" + gifterName + "<STR_LIT>" + playerTarget . getName ( ) ) ; return true ; } else { this . getServer ( ) . getLogger ( ) . log ( Level . WARNING , "<STR_LIT>" ) ; } } } else if ( args . length == <NUM_LIT:3> ) { String action = args [ <NUM_LIT:0> ] ; String target = args [ <NUM_LIT:1> ] ; if ( action . equals ( "<STR_LIT>" ) || action . equals ( "<STR_LIT>" ) ) { this . msg ( sender , "<STR_LIT>" + action + "<STR_LIT>" + ChatColor . GREEN + "<STR_LIT:1>" + ChatColor . GRAY + "<STR_LIT>" ) ; return true ; } int amount = Integer . parseInt ( args [ <NUM_LIT:2> ] ) ; List < Player > matches = this . getServer ( ) . matchPlayer ( target ) ; if ( action . equals ( "<STR_LIT>" ) && ! matches . isEmpty ( ) && amount >= <NUM_LIT:0> && ( ! ( sender instanceof Player ) || ( Karma . permissionHandler . has ( ( Player ) sender , "<STR_LIT>" ) ) ) ) { return this . setAmount ( matches , amount ) ; } else { this . getServer ( ) . getLogger ( ) . log ( Level . WARNING , "<STR_LIT>" ) ; } } } else { this . getServer ( ) . getLogger ( ) . log ( Level . WARNING , "<STR_LIT>" ) ; } } catch ( Exception e ) { this . getServer ( ) . getLogger ( ) . log ( Level . WARNING , "<STR_LIT>" + e . toString ( ) ) ; e . printStackTrace ( ) ; return false ; } return false ; } private boolean setAmount ( List < Player > matches , int amount ) { Player playerTarget = matches . get ( <NUM_LIT:0> ) ; return this . setAmount ( playerTarget , amount ) ; } private boolean setAmount ( Player playerTarget , int amount ) { KarmaPlayer karmaTarget = this . getPlayers ( ) . get ( playerTarget . getName ( ) ) ; if ( karmaTarget != null && amount != karmaTarget . getKarmaPoints ( ) ) { int before = karmaTarget . getKarmaPoints ( ) ; if ( amount > karmaTarget . getKarmaPoints ( ) ) { karmaTarget . addKarma ( amount - karmaTarget . getKarmaPoints ( ) ) ; } else { karmaTarget . removeKarma ( karmaTarget . getKarmaPoints ( ) - amount ) ; } this . msg ( playerTarget , "<STR_LIT>" + ChatColor . GREEN + karmaTarget . getKarmaPoints ( ) + ChatColor . GRAY + "<STR_LIT:.>" ) ; this . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" + playerTarget . getName ( ) + "<STR_LIT>" + karmaTarget . getKarmaPoints ( ) + "<STR_LIT>" + before ) ; return true ; } return false ; } public void loadOrCreateKarmaPlayer ( Player player ) { String playerName = player . getName ( ) ; if ( this . db . exists ( playerName ) ) { KarmaPlayer karmaPlayer = this . db . get ( playerName ) ; if ( karmaPlayer != null ) { this . players . put ( playerName , karmaPlayer ) ; KarmaGroup currentGroup = this . startGroup ; while ( currentGroup != null ) { if ( karmaPlayer . getKarmaPoints ( ) >= currentGroup . getKarmaPoints ( ) && ! permissionHandler . has ( player , "<STR_LIT>" + currentGroup . getGroupName ( ) ) && ! ( currentGroup . getNext ( ) != null && karmaPlayer . getKarmaPoints ( ) >= currentGroup . getNext ( ) . getKarmaPoints ( ) ) ) { this . getServer ( ) . dispatchCommand ( this . getServer ( ) . getConsoleSender ( ) , "<STR_LIT>" + playerName + "<STR_LIT:U+0020>" + currentGroup . getGroupName ( ) ) ; this . getServer ( ) . dispatchCommand ( this . getServer ( ) . getConsoleSender ( ) , "<STR_LIT>" ) ; for ( Player playerOnline : this . getServer ( ) . getOnlinePlayers ( ) ) { this . msg ( playerOnline , "<STR_LIT>" + ChatColor . WHITE + playerName + ChatColor . GRAY + "<STR_LIT>" + currentGroup . getChatColor ( ) + currentGroup . getGroupName ( ) + ChatColor . GRAY + "<STR_LIT:.>" ) ; } } currentGroup = currentGroup . getNext ( ) ; } long gone = System . currentTimeMillis ( ) - karmaPlayer . getLastActivityTime ( ) ; int howManyDays = ( int ) Math . floor ( gone / <NUM_LIT> ) ; if ( howManyDays > <NUM_LIT:0> ) { int before = karmaPlayer . getKarmaPoints ( ) ; karmaPlayer . removeKarmaAutomatic ( howManyDays ) ; this . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" + player . getName ( ) + "<STR_LIT>" + ( before - karmaPlayer . getKarmaPoints ( ) ) + "<STR_LIT>" ) ; } karmaPlayer . ping ( ) ; this . db . put ( karmaPlayer ) ; } } else { int initialKarma = this . getInitialKarma ( player ) ; KarmaPlayer karmaPlayer = new KarmaPlayer ( this , player . getName ( ) , initialKarma , System . currentTimeMillis ( ) , <NUM_LIT:0> ) ; this . players . put ( player . getName ( ) , karmaPlayer ) ; this . db . put ( karmaPlayer ) ; this . msg ( player , "<STR_LIT>" + ChatColor . GREEN + initialKarma + ChatColor . GRAY + "<STR_LIT>" + ChatColor . GREEN + "<STR_LIT>" + ChatColor . GRAY + "<STR_LIT>" ) ; this . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" + player . getName ( ) + "<STR_LIT>" + initialKarma + "<STR_LIT>" ) ; } } private int getInitialKarma ( Player player ) { KarmaGroup group = this . startGroup ; int initialKarma = <NUM_LIT:0> ; int karmaToNext = <NUM_LIT:0> ; while ( group != null ) { String perm = "<STR_LIT>" + group . getGroupName ( ) ; if ( Karma . permissionHandler . has ( player , perm ) ) { initialKarma = group . getKarmaPoints ( ) ; if ( group . getNext ( ) != null ) { karmaToNext = group . getNext ( ) . getKarmaPoints ( ) - group . getKarmaPoints ( ) ; } else { karmaToNext = <NUM_LIT:100> ; } } else { this . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" + perm ) ; break ; } group = group . getNext ( ) ; } initialKarma += ( int ) ( <NUM_LIT> * karmaToNext ) ; return initialKarma ; } public void checkForPromotion ( String playerName , int before , int after ) { KarmaGroup group = this . startGroup ; Player playerForPromotion = this . findPlayer ( playerName ) ; while ( group != null && playerForPromotion != null ) { String perm = "<STR_LIT>" + group . getGroupName ( ) ; if ( before < group . getKarmaPoints ( ) && after >= group . getKarmaPoints ( ) && ! Karma . permissionHandler . has ( playerForPromotion , perm ) ) { this . getServer ( ) . dispatchCommand ( this . getServer ( ) . getConsoleSender ( ) , "<STR_LIT>" + playerName + "<STR_LIT:U+0020>" + group . getGroupName ( ) ) ; this . getServer ( ) . dispatchCommand ( this . getServer ( ) . getConsoleSender ( ) , "<STR_LIT>" ) ; for ( Player player : this . getServer ( ) . getOnlinePlayers ( ) ) { this . msg ( player , "<STR_LIT>" + ChatColor . WHITE + playerName + ChatColor . GRAY + "<STR_LIT>" + group . getGroupName ( ) + "<STR_LIT:.>" ) ; } this . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" + playerName + "<STR_LIT>" + group . getGroupName ( ) ) ; } group = group . getNext ( ) ; } } public void checkForDemotion ( String playerName , int before , int after , boolean automatic ) { KarmaGroup group = this . startGroup ; Player playerForDemotion = this . findPlayer ( playerName ) ; while ( group != null && playerForDemotion != null ) { if ( group . getNext ( ) != null && before >= group . getNext ( ) . getKarmaPoints ( ) && after < group . getNext ( ) . getKarmaPoints ( ) ) { String perm = "<STR_LIT>" + group . getNext ( ) . getGroupName ( ) ; if ( group . getGroupName ( ) . equals ( "<STR_LIT>" ) && automatic ) return ; if ( Karma . permissionHandler . has ( playerForDemotion , perm ) ) { this . getServer ( ) . dispatchCommand ( this . getServer ( ) . getConsoleSender ( ) , "<STR_LIT>" + playerName + "<STR_LIT:U+0020>" + group . getGroupName ( ) ) ; this . getServer ( ) . dispatchCommand ( this . getServer ( ) . getConsoleSender ( ) , "<STR_LIT>" ) ; for ( Player player : this . getServer ( ) . getOnlinePlayers ( ) ) { this . msg ( player , "<STR_LIT>" + ChatColor . WHITE + playerName + ChatColor . GRAY + "<STR_LIT>" + group . getGroupName ( ) + "<STR_LIT:.>" ) ; } this . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" + playerName + "<STR_LIT>" + group . getGroupName ( ) ) ; break ; } } group = group . getNext ( ) ; } } public void msg ( CommandSender destination , String message ) { destination . sendMessage ( ChatColor . DARK_PURPLE + "<STR_LIT>" + ChatColor . GRAY + replaceGroupNames ( message ) ) ; } private String replaceGroupNames ( String message ) { KarmaGroup group = this . startGroup ; while ( group != null ) { message = message . replace ( group . getGroupName ( ) , group . getChatColor ( ) + group . getGroupName ( ) + ChatColor . GRAY ) ; group = group . getNext ( ) ; } return message ; } private String getPlayerNextGroupString ( KarmaPlayer karmaPlayer ) { Player player = this . findPlayer ( karmaPlayer . getName ( ) ) ; KarmaGroup group = this . startGroup ; while ( group != null ) { String perm = "<STR_LIT>" + group . getGroupName ( ) ; if ( ! Karma . permissionHandler . has ( player , perm ) ) { return group . getGroupName ( ) + "<STR_LIT:U+0020(>" + ChatColor . GREEN + group . getKarmaPoints ( ) + ChatColor . GRAY + "<STR_LIT:)>" ; } group = group . getNext ( ) ; } return "<STR_LIT:none>" ; } private String getPlayerGroupString ( KarmaPlayer karmaPlayer ) { Player player = this . findPlayer ( karmaPlayer . getName ( ) ) ; KarmaGroup group = this . startGroup ; KarmaGroup lastGroup = null ; while ( group != null ) { String perm = "<STR_LIT>" + group . getGroupName ( ) ; if ( ! Karma . permissionHandler . has ( player , perm ) ) { return lastGroup . getGroupName ( ) + "<STR_LIT:U+0020(>" + ChatColor . GREEN + lastGroup . getKarmaPoints ( ) + ChatColor . GRAY + "<STR_LIT:)>" ; } lastGroup = group ; if ( group . getNext ( ) == null ) { return group . getGroupName ( ) ; } group = group . getNext ( ) ; } return "<STR_LIT:none>" ; } public Player findPlayer ( String playerName ) { for ( Player player : this . getServer ( ) . getOnlinePlayers ( ) ) { if ( player . getName ( ) . equals ( playerName ) ) { return player ; } } return null ; } public int getNextRandomKarmaPartyDelay ( ) { int minutes = <NUM_LIT:10> + this . random . nextInt ( <NUM_LIT:20> ) ; int ticks = minutes * <NUM_LIT:20> * <NUM_LIT> ; this . getServer ( ) . getLogger ( ) . log ( Level . INFO , "<STR_LIT>" + minutes + "<STR_LIT>" + ticks + "<STR_LIT>" ) ; return ticks ; } public Map < String , KarmaPlayer > getPlayers ( ) { return this . players ; } public Database getKarmaDatabase ( ) { return this . db ; } } </s>
|
<s> package com . tommytony . karma ; import org . bukkit . ChatColor ; public class KarmaGroup { private final String groupName ; private final int karmaPoints ; private final KarmaGroup next ; private final ChatColor chatColor ; public KarmaGroup ( String groupName , int karmaPoints , KarmaGroup next , ChatColor color ) { this . groupName = groupName ; this . karmaPoints = karmaPoints ; this . next = next ; this . chatColor = color ; } public int getKarmaPoints ( ) { return karmaPoints ; } public String getGroupName ( ) { return groupName ; } public KarmaGroup getNext ( ) { return next ; } public ChatColor getChatColor ( ) { return chatColor ; } } </s>
|
<s> package com . tommytony . karma ; import org . bukkit . entity . Player ; public class LoadPlayers implements Runnable { private final Karma karma ; public LoadPlayers ( Karma karma ) { this . karma = karma ; } public void run ( ) { for ( Player player : this . karma . getServer ( ) . getOnlinePlayers ( ) ) { this . karma . loadOrCreateKarmaPlayer ( player ) ; } } } </s>
|
<s> package com . tommytony . karma ; import org . bukkit . event . EventHandler ; import org . bukkit . event . Listener ; import org . bukkit . event . player . PlayerChatEvent ; import org . bukkit . event . player . PlayerJoinEvent ; import org . bukkit . event . player . PlayerMoveEvent ; import org . bukkit . event . player . PlayerQuitEvent ; public class KarmaPlayerListener implements Listener { private final Karma karma ; public KarmaPlayerListener ( Karma karma ) { this . karma = karma ; } @ EventHandler public void onPlayerJoin ( PlayerJoinEvent event ) { this . karma . loadOrCreateKarmaPlayer ( event . getPlayer ( ) ) ; } @ EventHandler public void onPlayerQuit ( PlayerQuitEvent event ) { String playerName = event . getPlayer ( ) . getName ( ) ; KarmaPlayer player = this . karma . getPlayers ( ) . get ( playerName ) ; if ( player != null ) { this . karma . getKarmaDatabase ( ) . put ( player ) ; this . karma . getPlayers ( ) . remove ( event . getPlayer ( ) . getName ( ) ) ; } } @ EventHandler public void onPlayerChat ( PlayerChatEvent event ) { String playerName = event . getPlayer ( ) . getName ( ) ; if ( this . karma . getPlayers ( ) . containsKey ( playerName ) ) { this . karma . getPlayers ( ) . get ( playerName ) . ping ( ) ; } } @ EventHandler public void onPlayerMove ( PlayerMoveEvent event ) { String playerName = event . getPlayer ( ) . getName ( ) ; if ( this . karma . getPlayers ( ) . containsKey ( playerName ) ) { this . karma . getPlayers ( ) . get ( playerName ) . ping ( ) ; } } } </s>
|
<s> package org . agetac ; public final class R { public static final class anim { public static final int slide_in_left = <NUM_LIT> ; public static final int slide_out_left = <NUM_LIT> ; } public static final class attr { } public static final class color { public static final int alpha_white = <NUM_LIT> ; } public static final class drawable { public static final int firetruck = <NUM_LIT> ; public static final int hide_show_menu = <NUM_LIT> ; public static final int ic_delete = <NUM_LIT> ; public static final int ic_edit = <NUM_LIT> ; public static final int ic_launcher = <NUM_LIT> ; public static final int ic_tab_crm = <NUM_LIT> ; public static final int ic_tab_messages = <NUM_LIT> ; public static final int ic_tab_moyens = <NUM_LIT> ; public static final int ic_tab_sitac = <NUM_LIT> ; public static final int ic_tab_soeic = <NUM_LIT> ; public static final int menu_sitac_row_selector = <NUM_LIT> ; public static final int menu_sitac_text_selector = <NUM_LIT> ; public static final int picto_blue_col = <NUM_LIT> ; public static final int picto_blue_down = <NUM_LIT> ; public static final int picto_blue_grp = <NUM_LIT> ; public static final int picto_blue_isole = <NUM_LIT> ; public static final int picto_blue_none = <NUM_LIT> ; public static final int picto_blue_up = <NUM_LIT> ; public static final int picto_green_col = <NUM_LIT> ; public static final int picto_green_down = <NUM_LIT> ; public static final int picto_green_grp = <NUM_LIT> ; public static final int picto_green_isole = <NUM_LIT> ; public static final int picto_green_none = <NUM_LIT> ; public static final int picto_green_up = <NUM_LIT> ; public static final int picto_line = <NUM_LIT> ; public static final int picto_orange_down = <NUM_LIT> ; public static final int picto_orange_up = <NUM_LIT> ; public static final int picto_point = <NUM_LIT> ; public static final int picto_red_col = <NUM_LIT> ; public static final int picto_red_dotted_isole = <NUM_LIT> ; public static final int picto_red_dotted_none = <NUM_LIT> ; public static final int picto_red_down = <NUM_LIT> ; public static final int picto_red_grp = <NUM_LIT> ; public static final int picto_red_isole = <NUM_LIT> ; public static final int picto_red_none = <NUM_LIT> ; public static final int picto_red_up = <NUM_LIT> ; public static final int picto_zone = <NUM_LIT> ; } public static final class id { public static final int CCGC = <NUM_LIT> ; public static final int FPT = <NUM_LIT> ; public static final int VSAV = <NUM_LIT> ; public static final int addEntity = <NUM_LIT> ; public static final int btn_demande_moyens = <NUM_LIT> ; public static final int btn_hide_menu = <NUM_LIT> ; public static final int btn_hide_show_menu = <NUM_LIT> ; public static final int btn_show_menu = <NUM_LIT> ; public static final int buttonAnnuler = <NUM_LIT> ; public static final int buttonConsMess = <NUM_LIT> ; public static final int buttonEnvoyer = <NUM_LIT> ; public static final int buttonRetMess = <NUM_LIT> ; public static final int caserne_vehicule = <NUM_LIT> ; public static final int connectBtn = <NUM_LIT> ; public static final int description = <NUM_LIT> ; public static final int edittext_je_demande = <NUM_LIT> ; public static final int edittext_je_prevois = <NUM_LIT> ; public static final int edittext_je_procede = <NUM_LIT> ; public static final int edittext_je_suis = <NUM_LIT> ; public static final int edittext_je_vois = <NUM_LIT> ; public static final int edittext_message_normal = <NUM_LIT> ; public static final int etat_vehicule = <NUM_LIT> ; public static final int field_titles = <NUM_LIT> ; public static final int fragment_menu_hidden = <NUM_LIT> ; public static final int fragment_menu_opened = <NUM_LIT> ; public static final int gh_arrivee = <NUM_LIT> ; public static final int gh_demande = <NUM_LIT> ; public static final int gh_retour = <NUM_LIT> ; public static final int img = <NUM_LIT> ; public static final int item2 = <NUM_LIT> ; public static final int listMess = <NUM_LIT> ; public static final int loginField = <NUM_LIT> ; public static final int mapview = <NUM_LIT> ; public static final int menu = <NUM_LIT> ; public static final int menu_alim = <NUM_LIT> ; public static final int menu_anchor = <NUM_LIT> ; public static final int menu_attaque = <NUM_LIT> ; public static final int menu_child_img = <NUM_LIT> ; public static final int menu_child_text = <NUM_LIT> ; public static final int menu_item_delete = <NUM_LIT> ; public static final int menu_item_edit = <NUM_LIT> ; public static final int menu_moyens = <NUM_LIT> ; public static final int menu_secours = <NUM_LIT> ; public static final int messAnnuler = <NUM_LIT> ; public static final int messEnvoyer = <NUM_LIT> ; public static final int moyens_listview = <NUM_LIT> ; public static final int name = <NUM_LIT> ; public static final int nbCurrentEntity = <NUM_LIT> ; public static final int nbFuturEntity = <NUM_LIT> ; public static final int passField = <NUM_LIT> ; public static final int retMessAmb = <NUM_LIT> ; public static final int sitac_actions_panel = <NUM_LIT> ; public static final int sitac_group = <NUM_LIT> ; public static final int submenu_0 = <NUM_LIT> ; public static final int submenu_1 = <NUM_LIT> ; public static final int submenu_3 = <NUM_LIT> ; public static final int titre = <NUM_LIT> ; public static final int type_vehicule = <NUM_LIT> ; public static final int vehicule_name = <NUM_LIT> ; public static final int vehicules_listview = <NUM_LIT> ; } public static final class layout { public static final int crm = <NUM_LIT> ; public static final int edit_item_dialog = <NUM_LIT> ; public static final int expandable_menu = <NUM_LIT> ; public static final int gridview_item = <NUM_LIT> ; public static final int liste_message = <NUM_LIT> ; public static final int main = <NUM_LIT> ; public static final int menu_hidden = <NUM_LIT> ; public static final int menu_opened = <NUM_LIT> ; public static final int menu_sitac_childs = <NUM_LIT> ; public static final int menu_sitac_groups = <NUM_LIT> ; public static final int mess = <NUM_LIT> ; public static final int messages = <NUM_LIT> ; public static final int moyens = <NUM_LIT> ; public static final int moyens_list_header = <NUM_LIT> ; public static final int moyens_list_item = <NUM_LIT> ; public static final int reception_mess = <NUM_LIT> ; public static final int sitac = <NUM_LIT> ; public static final int soeic = <NUM_LIT> ; public static final int tabs = <NUM_LIT> ; } public static final class menu { public static final int moyens_context_menu = <NUM_LIT> ; public static final int sitac_context_menu = <NUM_LIT> ; } public static final class string { public static final int CCGC = <NUM_LIT> ; public static final int FPT = <NUM_LIT> ; public static final int Message = <NUM_LIT> ; public static final int VSAV = <NUM_LIT> ; public static final int actions = <NUM_LIT> ; public static final int alim = <NUM_LIT> ; public static final int annuler = <NUM_LIT> ; public static final int app_name = <NUM_LIT> ; public static final int attaque = <NUM_LIT> ; public static final int cancel = <NUM_LIT> ; public static final int cibles = <NUM_LIT> ; public static final int connection = <NUM_LIT> ; public static final int contextRoot = <NUM_LIT> ; public static final int crm = <NUM_LIT> ; public static final int dangers = <NUM_LIT> ; public static final int delete = <NUM_LIT> ; public static final int demande_moyen = <NUM_LIT> ; public static final int dialog_confirmexit = <NUM_LIT> ; public static final int dialog_deletevehicule = <NUM_LIT> ; public static final int dialog_title_confirmexit = <NUM_LIT> ; public static final int dialog_title_deletevehicule = <NUM_LIT> ; public static final int dialog_title_edit_item = <NUM_LIT> ; public static final int dialog_title_vehicule = <NUM_LIT> ; public static final int dialog_update_gh_ou_supprimer_vehicule = <NUM_LIT> ; public static final int dialog_vehicule_gerer_gh = <NUM_LIT> ; public static final int dialog_vehicule_supprimer = <NUM_LIT> ; public static final int edit = <NUM_LIT> ; public static final int empty_text = <NUM_LIT> ; public static final int host = <NUM_LIT> ; public static final int imageContentDescription = <NUM_LIT> ; public static final int item2 = <NUM_LIT> ; public static final int je_demande = <NUM_LIT> ; public static final int je_prevois = <NUM_LIT> ; public static final int je_procede = <NUM_LIT> ; public static final int je_suis = <NUM_LIT> ; public static final int je_vois = <NUM_LIT> ; public static final int login = <NUM_LIT> ; public static final int menu_img_desc = <NUM_LIT> ; public static final int messages = <NUM_LIT> ; public static final int moyens = <NUM_LIT> ; public static final int no = <NUM_LIT> ; public static final int off_sitac = <NUM_LIT> ; public static final int password = <NUM_LIT> ; public static final int port = <NUM_LIT> ; public static final int progress_connection = <NUM_LIT> ; public static final int progress_loading = <NUM_LIT> ; public static final int progress_title_connection = <NUM_LIT> ; public static final int save = <NUM_LIT> ; public static final int secours = <NUM_LIT> ; public static final int sitac = <NUM_LIT> ; public static final int soeic = <NUM_LIT> ; public static final int unknown = <NUM_LIT> ; public static final int vehicule_caserne = <NUM_LIT> ; public static final int vehicule_etat = <NUM_LIT> ; public static final int vehicule_gh_arrivee = <NUM_LIT> ; public static final int vehicule_gh_demande = <NUM_LIT> ; public static final int vehicule_gh_retour = <NUM_LIT> ; public static final int vehicule_type = <NUM_LIT> ; public static final int yes = <NUM_LIT> ; } } </s>
|
<s> package org . agetac . fragment ; import org . agetac . listener . IOnMenuEventListener ; public interface IMenuFragment { public void setOnMenuEventListener ( IOnMenuEventListener listener ) ; public void removeOnMenuEventListener ( ) ; } </s>
|
<s> package org . agetac . fragment ; import java . util . ArrayList ; import org . agetac . R ; import org . agetac . entity . EntityHolder ; import org . agetac . entity . IEntity ; import org . agetac . listener . IOnMenuEventListener ; import org . agetac . view . Color ; import org . agetac . view . MenuExpandableListAdapter ; import org . agetac . view . MenuGroup ; import org . agetac . view . Shape ; import android . app . Fragment ; import android . os . Bundle ; import android . view . LayoutInflater ; import android . view . View ; import android . view . View . OnClickListener ; import android . view . ViewGroup ; import android . view . animation . Animation ; import android . view . animation . Animation . AnimationListener ; import android . view . animation . AnimationUtils ; import android . widget . ExpandableListView ; import android . widget . ExpandableListView . OnChildClickListener ; import android . widget . ExpandableListView . OnGroupClickListener ; import android . widget . ImageButton ; public class OpenedMenuFragment extends Fragment implements IMenuFragment , OnClickListener , OnChildClickListener , OnGroupClickListener { private static final String TAG = "<STR_LIT>" ; private Animation hideMenuAnim ; private Animation showMenuAnim ; private IOnMenuEventListener listener ; private ArrayList < MenuGroup > groups ; private ArrayList < IEntity > pictosDangers , pictosCibles , pictosActions , pictosMoyens , pictosOffSitac ; private MenuExpandableListAdapter menuAdapter ; private ExpandableListView listView ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; hideMenuAnim = AnimationUtils . loadAnimation ( getActivity ( ) , R . anim . slide_out_left ) ; hideMenuAnim . setAnimationListener ( new AnimationListener ( ) { @ Override public void onAnimationStart ( Animation animation ) { } @ Override public void onAnimationRepeat ( Animation animation ) { } @ Override public void onAnimationEnd ( Animation animation ) { if ( listener != null ) listener . onHideMenu ( ) ; } } ) ; showMenuAnim = AnimationUtils . loadAnimation ( getActivity ( ) , R . anim . slide_in_left ) ; EntityHolder pHolder = EntityHolder . getInstance ( getActivity ( ) ) ; pictosDangers = pHolder . getEntities ( Shape . TRIANGLE_UP ) ; pictosCibles = pHolder . getEntities ( Shape . TRIANGLE_DOWN ) ; pictosActions = pHolder . getEntities ( Color . BLACK ) ; pictosMoyens = pHolder . getEntities ( Shape . SQUARE ) ; pictosOffSitac = new ArrayList < IEntity > ( ) ; } @ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { return inflater . inflate ( R . layout . menu_opened , container , false ) ; } @ Override public void onActivityCreated ( Bundle savedInstanceState ) { super . onActivityCreated ( savedInstanceState ) ; ( ( ImageButton ) getActivity ( ) . findViewById ( R . id . btn_hide_menu ) ) . setOnClickListener ( this ) ; listView = ( ExpandableListView ) getActivity ( ) . findViewById ( R . id . menu ) ; groups = new ArrayList < MenuGroup > ( ) ; MenuGroup grpDangers = new MenuGroup ( getString ( R . string . dangers ) ) ; grpDangers . setEntities ( pictosDangers ) ; groups . add ( grpDangers ) ; MenuGroup grpCibles = new MenuGroup ( getString ( R . string . cibles ) ) ; grpCibles . setEntities ( pictosCibles ) ; groups . add ( grpCibles ) ; MenuGroup grpMoyens = new MenuGroup ( getString ( R . string . moyens ) ) ; grpMoyens . setEntities ( pictosMoyens ) ; groups . add ( grpMoyens ) ; MenuGroup grpMapItems = new MenuGroup ( getString ( R . string . actions ) ) ; grpMapItems . setEntities ( pictosActions ) ; groups . add ( grpMapItems ) ; menuAdapter = new MenuExpandableListAdapter ( getActivity ( ) , groups ) ; listView . setAdapter ( menuAdapter ) ; listView . setOnChildClickListener ( this ) ; listView . setOnGroupClickListener ( this ) ; getView ( ) . startAnimation ( showMenuAnim ) ; } @ Override public void onClick ( View v ) { switch ( v . getId ( ) ) { case R . id . btn_hide_menu : getView ( ) . startAnimation ( hideMenuAnim ) ; break ; default : android . util . Log . d ( "<STR_LIT>" , "<STR_LIT>" + v . toString ( ) ) ; break ; } } public void startShowMenuAnim ( ) { getView ( ) . startAnimation ( showMenuAnim ) ; } @ Override public void setOnMenuEventListener ( IOnMenuEventListener listener ) { this . listener = listener ; } @ Override public void removeOnMenuEventListener ( ) { this . listener = null ; } @ Override public boolean onChildClick ( ExpandableListView p , View v , int grpIndex , int childIndex , long id ) { menuAdapter . setChildSelected ( childIndex , grpIndex ) ; if ( listener != null ) { MenuGroup grp = groups . get ( grpIndex ) ; IEntity entity = grp . getEntities ( ) . get ( childIndex ) ; listener . onEntitySelected ( entity , grp ) ; } return true ; } @ Override public boolean onGroupClick ( ExpandableListView parent , View v , int groupPosition , long id ) { return false ; } public void addOffSitacEntities ( ArrayList < IEntity > entities ) { if ( entities == null || entities . isEmpty ( ) ) { if ( groups . get ( <NUM_LIT:0> ) . getGroupName ( ) . equals ( getString ( R . string . off_sitac ) ) ) { android . util . Log . d ( TAG , "<STR_LIT>" ) ; groups . remove ( <NUM_LIT:0> ) ; } } else { MenuGroup grpOffSitac = null ; if ( groups . get ( <NUM_LIT:0> ) . getGroupName ( ) . equals ( getString ( R . string . off_sitac ) ) ) { android . util . Log . d ( TAG , "<STR_LIT>" ) ; grpOffSitac = groups . get ( <NUM_LIT:0> ) ; } else { android . util . Log . d ( TAG , "<STR_LIT>" ) ; grpOffSitac = new MenuGroup ( getString ( R . string . off_sitac ) ) ; groups . add ( <NUM_LIT:0> , grpOffSitac ) ; } pictosOffSitac . clear ( ) ; pictosOffSitac . addAll ( entities ) ; grpOffSitac . setEntities ( pictosOffSitac ) ; } menuAdapter . notifyDataSetChanged ( ) ; } public void removeOnSitacEntity ( IEntity entity ) { MenuGroup grpOffSitac = null ; if ( groups . get ( <NUM_LIT:0> ) . getGroupName ( ) . equals ( getString ( R . string . off_sitac ) ) ) { grpOffSitac = groups . get ( <NUM_LIT:0> ) ; } else { grpOffSitac = new MenuGroup ( getString ( R . string . off_sitac ) ) ; groups . add ( <NUM_LIT:0> , grpOffSitac ) ; } pictosOffSitac . remove ( entity ) ; grpOffSitac . setEntities ( pictosOffSitac ) ; menuAdapter . notifyDataSetChanged ( ) ; } public void unselectItem ( View v ) { v . setSelected ( false ) ; } } </s>
|
<s> package org . agetac . fragment ; import org . agetac . R ; import org . agetac . listener . IOnMenuEventListener ; import android . app . Fragment ; import android . os . Bundle ; import android . view . LayoutInflater ; import android . view . View ; import android . view . View . OnClickListener ; import android . view . ViewGroup ; import android . widget . ImageButton ; public class HiddenMenuFragment extends Fragment implements IMenuFragment , OnClickListener { private IOnMenuEventListener listener ; @ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { return inflater . inflate ( R . layout . menu_hidden , container , false ) ; } @ Override public void onActivityCreated ( Bundle savedInstanceState ) { super . onActivityCreated ( savedInstanceState ) ; ( ( ImageButton ) getActivity ( ) . findViewById ( R . id . btn_show_menu ) ) . setOnClickListener ( this ) ; } @ Override public void onClick ( View v ) { switch ( v . getId ( ) ) { case R . id . btn_show_menu : if ( listener != null ) listener . onShowMenu ( ) ; break ; } } @ Override public void setOnMenuEventListener ( IOnMenuEventListener listener ) { this . listener = listener ; } @ Override public void removeOnMenuEventListener ( ) { this . listener = null ; } } </s>
|
<s> package org . agetac . controller ; import org . agetac . activity . ITabActivity ; public class CRMController implements ISubController { private Controller parent ; public CRMController ( Controller controller ) { parent = controller ; } @ Override public void processUpdate ( ITabActivity act ) { } } </s>
|
<s> package org . agetac . controller ; import java . util . ArrayList ; import java . util . Hashtable ; import java . util . Map ; import java . util . Observable ; import java . util . Observer ; import org . agetac . activity . CRMActivity ; import org . agetac . activity . ITabActivity ; import org . agetac . activity . MessagesActivity ; import org . agetac . activity . MoyensActivity ; import org . agetac . activity . SITACActivity ; import org . agetac . command . AddEntityCommand ; import org . agetac . command . EditEntityCommand ; import org . agetac . command . ICommand ; import org . agetac . command . RemoveEntityCommand ; import org . agetac . command . SendMessageCommand ; import org . agetac . common . dto . InterventionDTO ; import org . agetac . engine . IInterventionEngine ; import org . agetac . engine . InterventionEngine ; import org . agetac . entity . IEntity ; import android . content . Context ; public class Controller implements Observer { private static final String TAG = "<STR_LIT>" ; public enum ActionFlag { ADD , REMOVE , EDIT , SEND_MESSAGE , UPDATE_GH } private IEntity lastEntity ; private static Controller controller ; private Map < String , ICommand > commands ; private ISubController moyensCtrl , sitacCtrl , messagesCtrl , crmCtrl ; private ITabActivity currentActivity ; private IInterventionEngine interventionEngine ; private String message ; private Controller ( Context c ) { interventionEngine = new InterventionEngine ( c ) ; initCommands ( ) ; initControllers ( ) ; interventionEngine . addObserver ( this ) ; } private void initCommands ( ) { commands = new Hashtable < String , ICommand > ( ) ; commands . put ( AddEntityCommand . NAME , new AddEntityCommand ( this ) ) ; commands . put ( RemoveEntityCommand . NAME , new RemoveEntityCommand ( this ) ) ; commands . put ( SendMessageCommand . NAME , new SendMessageCommand ( this ) ) ; commands . put ( EditEntityCommand . NAME , new EditEntityCommand ( this ) ) ; } private void initControllers ( ) { sitacCtrl = new SITACController ( this ) ; moyensCtrl = new MoyensController ( this ) ; messagesCtrl = new MessagesController ( this ) ; } public static Controller getInstance ( Context c ) { if ( controller == null ) { controller = new Controller ( c ) ; } return controller ; } public void setCurrentActivity ( ITabActivity act ) { this . currentActivity = act ; act . update ( ) ; } public IEntity getLastEntity ( ) { return lastEntity ; } public void setLastEntity ( IEntity e ) { lastEntity = e ; } public Map < String , ICommand > getCommands ( ) { return commands ; } public ArrayList < IEntity > getEntities ( ) { return interventionEngine . getEntities ( ) ; } public IInterventionEngine getInterventionEngine ( ) { return interventionEngine ; } public void setMessage ( String m ) { message = m ; } public String getMessage ( ) { return message ; } @ Override public void update ( Observable observable , Object data ) { if ( data instanceof InterventionDTO ) { android . util . Log . d ( TAG , "<STR_LIT>" ) ; if ( currentActivity != null ) currentActivity . update ( ) ; } else if ( data instanceof ITabActivity ) { ITabActivity act = ( ITabActivity ) data ; if ( data instanceof SITACActivity ) { android . util . Log . d ( TAG , "<STR_LIT>" ) ; sitacCtrl . processUpdate ( act ) ; } else if ( data instanceof MoyensActivity ) { android . util . Log . d ( TAG , "<STR_LIT>" ) ; moyensCtrl . processUpdate ( act ) ; } else if ( data instanceof MessagesActivity ) { android . util . Log . d ( TAG , "<STR_LIT>" ) ; messagesCtrl . processUpdate ( act ) ; } else if ( data instanceof CRMActivity ) { android . util . Log . d ( TAG , "<STR_LIT>" ) ; crmCtrl . processUpdate ( act ) ; } else { android . util . Log . d ( TAG , "<STR_LIT>" ) ; } } else { android . util . Log . d ( TAG , "<STR_LIT>" ) ; } } public void quit ( ) { interventionEngine . stopUpdates ( ) ; } } </s>
|
<s> package org . agetac . controller ; import org . agetac . activity . ITabActivity ; import org . agetac . command . AddEntityCommand ; import org . agetac . command . RemoveEntityCommand ; public class MoyensController implements ISubController { private static final String TAG = "<STR_LIT>" ; private Controller parent ; public MoyensController ( Controller controller ) { parent = controller ; } @ Override public void processUpdate ( ITabActivity act ) { switch ( act . getActionFlag ( ) ) { case REMOVE : parent . setLastEntity ( act . getTouchedEntity ( ) ) ; parent . getCommands ( ) . get ( RemoveEntityCommand . NAME ) . execute ( ) ; break ; case ADD : parent . setLastEntity ( act . getTouchedEntity ( ) ) ; parent . getCommands ( ) . get ( AddEntityCommand . NAME ) . execute ( ) ; break ; default : android . util . Log . w ( TAG , "<STR_LIT>" ) ; break ; } } } </s>
|
<s> package org . agetac . controller ; import org . agetac . activity . ITabActivity ; import org . agetac . command . SendMessageCommand ; public class MessagesController implements ISubController { private Controller parent ; private static final String TAG = "<STR_LIT>" ; public MessagesController ( Controller controller ) { parent = controller ; } @ Override public void processUpdate ( ITabActivity act ) { switch ( act . getActionFlag ( ) ) { case SEND_MESSAGE : parent . setMessage ( act . getMessage ( ) ) ; parent . getCommands ( ) . get ( SendMessageCommand . NAME ) . execute ( ) ; break ; default : android . util . Log . w ( TAG , "<STR_LIT>" ) ; break ; } } } </s>
|
<s> package org . agetac . controller ; import org . agetac . activity . ITabActivity ; public interface ISubController { public void processUpdate ( ITabActivity act ) ; } </s>
|
<s> package org . agetac . controller ; import org . agetac . activity . ITabActivity ; import org . agetac . command . AddEntityCommand ; import org . agetac . command . RemoveEntityCommand ; public class SITACController implements ISubController { private static final String TAG = "<STR_LIT>" ; private Controller parent ; public SITACController ( Controller controller ) { parent = controller ; } @ Override public void processUpdate ( ITabActivity act ) { switch ( act . getActionFlag ( ) ) { case ADD : parent . setLastEntity ( act . getTouchedEntity ( ) ) ; parent . getCommands ( ) . get ( AddEntityCommand . NAME ) . execute ( ) ; break ; case REMOVE : parent . setLastEntity ( act . getTouchedEntity ( ) ) ; parent . getCommands ( ) . get ( RemoveEntityCommand . NAME ) . execute ( ) ; break ; default : android . util . Log . w ( TAG , "<STR_LIT>" ) ; break ; } } } </s>
|
<s> package org . agetac . memento ; public interface IMemento { } </s>
|
<s> package org . agetac . memento ; import org . agetac . entity . IEntity ; public class AddEntityMemento implements IMemento { public IEntity entity ; public void setEntity ( IEntity e ) { entity = e ; } public IEntity getEntity ( ) { return entity ; } } </s>
|
<s> package org . agetac . observer ; import java . util . Observable ; import java . util . Observer ; public class MyObservable extends Observable { public void setChanged ( ) { super . setChanged ( ) ; } } </s>
|
<s> package org . agetac . common . resources ; import org . agetac . common . dto . MessageDTO ; import org . restlet . resource . Post ; public interface MessageResource { @ Post public abstract MessageDTO add ( MessageDTO message ) ; } </s>
|
<s> package org . agetac . common . resources ; import org . agetac . common . dto . SourceDTO ; import org . restlet . resource . Delete ; import org . restlet . resource . Post ; import org . restlet . resource . Put ; public interface SourceResource { @ Post public abstract SourceDTO add ( SourceDTO source ) ; @ Put public abstract void update ( SourceDTO source ) ; @ Delete public abstract void remove ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import org . agetac . common . dto . VictimDTO ; import org . restlet . resource . Delete ; import org . restlet . resource . Post ; import org . restlet . resource . Put ; public interface VictimResource { @ Post public abstract VictimDTO add ( VictimDTO victim ) ; @ Put public abstract void update ( VictimDTO victim ) ; @ Delete public abstract void remove ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import org . agetac . common . dto . InterventionDTO ; import org . restlet . resource . Get ; import org . restlet . resource . Post ; public interface InterventionResource { @ Post void add ( InterventionDTO intervention ) ; @ Get InterventionDTO retrieve ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import java . util . Collection ; import org . agetac . common . dto . VictimDTO ; import org . restlet . resource . Get ; public interface VictimsResource { @ Get public abstract Collection < VictimDTO > retrieve ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import java . util . Collection ; import org . agetac . common . dto . ActionDTO ; import org . restlet . resource . Get ; public interface ActionsResource { @ Get public abstract Collection < ActionDTO > retrieve ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import java . util . Collection ; import org . agetac . common . dto . VehicleDTO ; import org . restlet . resource . Get ; public interface VehiclesResource { @ Get public abstract Collection < VehicleDTO > retrieve ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import java . util . Collection ; import org . agetac . common . dto . VehicleDemandDTO ; import org . restlet . resource . Get ; public interface VehicleDemandsResource { @ Get public abstract Collection < VehicleDemandDTO > retrieve ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import java . util . Collection ; import org . agetac . common . dto . SourceDTO ; import org . restlet . resource . Get ; public interface SourcesResource { @ Get public abstract Collection < SourceDTO > retrieve ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import java . util . Collection ; import org . agetac . common . dto . TargetDTO ; import org . restlet . resource . Get ; public interface TargetsResource { @ Get public abstract Collection < TargetDTO > retrieve ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import org . agetac . common . dto . TargetDTO ; import org . restlet . resource . Delete ; import org . restlet . resource . Post ; import org . restlet . resource . Put ; public interface TargetResource { @ Post public abstract TargetDTO add ( TargetDTO target ) ; @ Put public abstract void update ( TargetDTO target ) ; @ Delete public abstract void remove ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import java . util . Collection ; import org . agetac . common . dto . MessageDTO ; import org . restlet . resource . Get ; public interface MessagesResource { @ Get public abstract Collection < MessageDTO > retrieve ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import java . util . Collection ; import org . agetac . common . dto . InterventionDTO ; import org . restlet . resource . Get ; public interface InterventionsResource { @ Get public abstract Collection < InterventionDTO > retrieve ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import org . agetac . common . dto . VehicleDTO ; import org . restlet . resource . Delete ; import org . restlet . resource . Post ; import org . restlet . resource . Put ; public interface VehicleResource { @ Post public abstract VehicleDTO add ( VehicleDTO vehicle ) ; @ Put public abstract void update ( VehicleDTO vehicle ) ; @ Delete public abstract void remove ( ) ; } </s>
|
<s> package org . agetac . common . resources ; import org . agetac . common . dto . VehicleDemandDTO ; import org . restlet . resource . Post ; public interface VehicleDemandResource { @ Post public abstract VehicleDemandDTO add ( VehicleDemandDTO vehicleDemand ) ; } </s>
|
<s> package org . agetac . common . resources ; import org . agetac . common . dto . ActionDTO ; import org . restlet . resource . Delete ; import org . restlet . resource . Post ; import org . restlet . resource . Put ; public interface ActionResource { @ Post public abstract ActionDTO add ( ActionDTO action ) ; @ Put public abstract void update ( ActionDTO action ) ; @ Delete public abstract void remove ( ) ; } </s>
|
<s> package org . agetac . common . client ; public interface AgetacClientListener { } </s>
|
<s> package org . agetac . common . client ; import java . util . Collection ; import org . agetac . common . dto . ActionDTO ; import org . agetac . common . dto . InterventionDTO ; import org . agetac . common . dto . MessageDTO ; import org . agetac . common . dto . SourceDTO ; import org . agetac . common . dto . TargetDTO ; import org . agetac . common . dto . VehicleDTO ; import org . agetac . common . dto . VehicleDemandDTO ; import org . agetac . common . dto . VictimDTO ; import org . agetac . common . resources . ActionResource ; import org . agetac . common . resources . ActionsResource ; import org . agetac . common . resources . InterventionResource ; import org . agetac . common . resources . InterventionsResource ; import org . agetac . common . resources . MessageResource ; import org . agetac . common . resources . MessagesResource ; import org . agetac . common . resources . SourceResource ; import org . agetac . common . resources . SourcesResource ; import org . agetac . common . resources . TargetResource ; import org . agetac . common . resources . TargetsResource ; import org . agetac . common . resources . VehicleDemandResource ; import org . agetac . common . resources . VehicleDemandsResource ; import org . agetac . common . resources . VehicleResource ; import org . agetac . common . resources . VehiclesResource ; import org . agetac . common . resources . VictimResource ; import org . agetac . common . resources . VictimsResource ; import org . restlet . resource . ClientResource ; public class AgetacClient { private final String host ; private final int port ; public AgetacClient ( String host , int port ) { this . host = host ; this . port = port ; } public Collection < VehicleDemandDTO > getVehicleDemands ( long interId ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { VehicleDemandsResource vehicleDemandsResource = clientResource . wrap ( VehicleDemandsResource . class ) ; return vehicleDemandsResource . retrieve ( ) ; } finally { clientResource . release ( ) ; } } public VehicleDemandDTO addVehicleDemand ( long interId , VehicleDemandDTO vehicleDemand ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { VehicleDemandResource vehicleDemandResource = clientResource . wrap ( VehicleDemandResource . class ) ; return vehicleDemandResource . add ( vehicleDemand ) ; } finally { clientResource . release ( ) ; } } public Collection < InterventionDTO > getInterventions ( ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" ) ; try { InterventionsResource interventionsResource = clientResource . wrap ( InterventionsResource . class ) ; return interventionsResource . retrieve ( ) ; } finally { clientResource . release ( ) ; } } private static ClientResource makeClientResource ( String address ) { ClientResource clientResource = new ClientResource ( address ) ; clientResource . setEntityBuffering ( true ) ; return clientResource ; } public InterventionDTO createIntervention ( ) { InterventionDTO intervention = new InterventionDTO ( ) ; ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" ) ; try { InterventionResource interventionResource = clientResource . wrap ( InterventionResource . class ) ; interventionResource . add ( intervention ) ; return intervention ; } finally { clientResource . release ( ) ; } } public MessageDTO addMessage ( long interId , MessageDTO message ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { MessageResource messageResource = clientResource . wrap ( MessageResource . class ) ; return messageResource . add ( message ) ; } finally { clientResource . release ( ) ; } } public SourceDTO addSource ( long interId , SourceDTO source ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { SourceResource sourceResource = clientResource . wrap ( SourceResource . class ) ; return sourceResource . add ( source ) ; } finally { clientResource . release ( ) ; } } public TargetDTO addTarget ( long interId , TargetDTO target ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { TargetResource targetResource = clientResource . wrap ( TargetResource . class ) ; return targetResource . add ( target ) ; } finally { clientResource . release ( ) ; } } public VictimDTO addVictim ( long interId , VictimDTO victim ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { VictimResource resource = clientResource . wrap ( VictimResource . class ) ; return resource . add ( victim ) ; } finally { clientResource . release ( ) ; } } public ActionDTO addAction ( long interId , ActionDTO action ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { ActionResource resource = clientResource . wrap ( ActionResource . class ) ; return resource . add ( action ) ; } finally { clientResource . release ( ) ; } } public Collection < MessageDTO > getMessages ( long interId ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { MessagesResource resource = clientResource . wrap ( MessagesResource . class ) ; return resource . retrieve ( ) ; } finally { clientResource . release ( ) ; } } public Collection < VehicleDTO > getVehicles ( long interId ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { VehiclesResource resource = clientResource . wrap ( VehiclesResource . class ) ; return resource . retrieve ( ) ; } finally { clientResource . release ( ) ; } } public Collection < ActionDTO > getActions ( long interId ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { ActionsResource resource = clientResource . wrap ( ActionsResource . class ) ; return resource . retrieve ( ) ; } finally { clientResource . release ( ) ; } } public Collection < SourceDTO > getSources ( long interId ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { SourcesResource resource = clientResource . wrap ( SourcesResource . class ) ; return resource . retrieve ( ) ; } finally { clientResource . release ( ) ; } } public Collection < TargetDTO > getTargets ( long interId ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { TargetsResource resource = clientResource . wrap ( TargetsResource . class ) ; return resource . retrieve ( ) ; } finally { clientResource . release ( ) ; } } public Collection < VictimDTO > getVictims ( long interId ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + interId + "<STR_LIT>" ) ; try { VictimsResource resource = clientResource . wrap ( VictimsResource . class ) ; return resource . retrieve ( ) ; } finally { clientResource . release ( ) ; } } private String getBaseAddress ( ) { return "<STR_LIT:http://>" + host + "<STR_LIT::>" + port ; } public void updateVictim ( VictimDTO victim ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + victim . getId ( ) ) ; try { VictimResource resource = clientResource . wrap ( VictimResource . class ) ; resource . update ( victim ) ; } finally { clientResource . release ( ) ; } } public void updateVehicle ( VehicleDTO vehicle ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + vehicle . getId ( ) ) ; try { VehicleResource resource = clientResource . wrap ( VehicleResource . class ) ; resource . update ( vehicle ) ; } finally { clientResource . release ( ) ; } } public void updateTarget ( TargetDTO target ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + target . getId ( ) ) ; try { TargetResource resource = clientResource . wrap ( TargetResource . class ) ; resource . update ( target ) ; } finally { clientResource . release ( ) ; } } public void updateSource ( SourceDTO source ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + source . getId ( ) ) ; try { SourceResource resource = clientResource . wrap ( SourceResource . class ) ; resource . update ( source ) ; } finally { clientResource . release ( ) ; } } public void deleteTarget ( long id ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + id ) ; try { TargetResource resource = clientResource . wrap ( TargetResource . class ) ; resource . remove ( ) ; } finally { clientResource . release ( ) ; } } public void deleteVictim ( long id ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + id ) ; try { VictimResource resource = clientResource . wrap ( VictimResource . class ) ; resource . remove ( ) ; } finally { clientResource . release ( ) ; } } public void deleteSource ( long id ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + id ) ; try { SourceResource resource = clientResource . wrap ( SourceResource . class ) ; resource . remove ( ) ; } finally { clientResource . release ( ) ; } } public void deleteVehicle ( long id ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + id ) ; try { SourceResource resource = clientResource . wrap ( SourceResource . class ) ; resource . remove ( ) ; } finally { clientResource . release ( ) ; } } public void deleteAction ( long id ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + id ) ; try { SourceResource resource = clientResource . wrap ( SourceResource . class ) ; resource . remove ( ) ; } finally { clientResource . release ( ) ; } } public void deleteVehicleDemand ( long id ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + id ) ; try { SourceResource resource = clientResource . wrap ( SourceResource . class ) ; resource . remove ( ) ; } finally { clientResource . release ( ) ; } } public InterventionDTO getIntervention ( long id ) { ClientResource clientResource = makeClientResource ( getBaseAddress ( ) + "<STR_LIT>" + id ) ; try { InterventionResource resource = clientResource . wrap ( InterventionResource . class ) ; return resource . retrieve ( ) ; } finally { clientResource . release ( ) ; } } } </s>
|
<s> package org . agetac . common . dto ; public class GroupDTO implements IModel { private long id ; private PositionDTO position ; private String name = "<STR_LIT>" ; public GroupDTO ( ) { this . position = new PositionDTO ( ) ; } public GroupDTO ( String name , PositionDTO position ) { this . name = name ; this . position = position ; } @ Override public long getId ( ) { return id ; } @ Override public PositionDTO getPosition ( ) { return position ; } @ Override public void setPosition ( PositionDTO p ) { this . position = p ; } @ Override public String getName ( ) { return name ; } @ Override public void setName ( String name ) { this . name = name ; } } </s>
|
<s> package org . agetac . common . dto ; public class PositionDTO { private long id ; private double latitude = <NUM_LIT:0> ; private double longitude = <NUM_LIT:0> ; public PositionDTO ( ) { } public PositionDTO ( double latitude , double longitude ) { this . latitude = latitude ; this . longitude = longitude ; } public PositionDTO ( PositionDTO p ) { this . latitude = p . getLatitude ( ) ; this . longitude = p . getLongitude ( ) ; } public long getId ( ) { return id ; } public double getLatitude ( ) { return latitude ; } public void setLatitude ( double latitude ) { this . latitude = latitude ; } public double getLongitude ( ) { return longitude ; } public void setLongitude ( double longitude ) { this . longitude = longitude ; } } </s>
|
<s> package org . agetac . common . dto ; import java . util . ArrayList ; import java . util . Collection ; public class InterventionDTO implements IModel { private long id ; private Collection < VehicleDTO > vehicles = new ArrayList < VehicleDTO > ( ) ; private Collection < SourceDTO > sources = new ArrayList < SourceDTO > ( ) ; private Collection < MessageDTO > messages = new ArrayList < MessageDTO > ( ) ; private Collection < TargetDTO > targets = new ArrayList < TargetDTO > ( ) ; private Collection < ActionDTO > actions = new ArrayList < ActionDTO > ( ) ; private Collection < VictimDTO > victims = new ArrayList < VictimDTO > ( ) ; private Collection < VehicleDemandDTO > demands = new ArrayList < VehicleDemandDTO > ( ) ; private PositionDTO position ; private String name ; public InterventionDTO ( ) { this . position = new PositionDTO ( ) ; } public long getId ( ) { return id ; } public Collection < VehicleDTO > getVehicles ( ) { return vehicles ; } public Collection < SourceDTO > getSources ( ) { return sources ; } public Collection < MessageDTO > getMessages ( ) { return messages ; } public Collection < TargetDTO > getTargets ( ) { return targets ; } public Collection < VictimDTO > getVictims ( ) { return victims ; } public Collection < VehicleDemandDTO > getDemands ( ) { return demands ; } public Collection < ActionDTO > getActions ( ) { return actions ; } @ Override public PositionDTO getPosition ( ) { return position ; } @ Override public void setPosition ( PositionDTO p ) { this . position = p ; } @ Override public String getName ( ) { return name ; } @ Override public void setName ( String name ) { this . name = name ; } } </s>
|
<s> package org . agetac . common . dto ; public interface IModel { public long getId ( ) ; public PositionDTO getPosition ( ) ; public void setPosition ( PositionDTO p ) ; public String getName ( ) ; public void setName ( String name ) ; } </s>
|
<s> package org . agetac . common . dto ; public class ActionDTO implements IModel { public enum ActionType { WATER , FIRE , HUMAN } private long id ; private String name = "<STR_LIT>" ; private ActionType type ; private PositionDTO position ; private PositionDTO origin ; private PositionDTO aim ; public ActionDTO ( ) { this . type = ActionType . FIRE ; this . position = new PositionDTO ( ) ; this . aim = new PositionDTO ( ) ; } public ActionDTO ( String n , ActionType t , PositionDTO p , PositionDTO a ) { this . name = n ; this . type = t ; this . position = p ; this . aim = a ; } public ActionDTO ( PositionDTO p , ActionType t , PositionDTO origin , PositionDTO aim ) { this . position = p ; this . type = t ; this . origin = origin ; this . aim = aim ; } public long getId ( ) { return id ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public ActionType getType ( ) { return type ; } public void setType ( ActionType type ) { this . type = type ; } public PositionDTO getPosition ( ) { return position ; } public void setPosition ( PositionDTO position ) { this . position = position ; } public PositionDTO getAim ( ) { return aim ; } public void setAim ( PositionDTO aim ) { this . aim = aim ; } public PositionDTO getOrigin ( ) { return origin ; } public void setOrigin ( PositionDTO origin ) { this . origin = origin ; } } </s>
|
<s> package org . agetac . common . dto ; public class BarrackDTO implements IModel { private long id ; private String name ; public BarrackDTO ( ) { } public BarrackDTO ( String name ) { this . name = name ; } public long getId ( ) { return id ; } @ Override public PositionDTO getPosition ( ) { return null ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } @ Override public void setPosition ( PositionDTO p ) { } } </s>
|
<s> package org . agetac . common . dto ; public class MessageDTO { private long id ; private String text ; private String date ; public MessageDTO ( ) { } public MessageDTO ( String message , String date ) { this . text = message ; this . date = date ; } public long getId ( ) { return id ; } public String getText ( ) { return text ; } public void setText ( String text ) { this . text = text ; } public String getDate ( ) { return date ; } public void setDate ( String date ) { this . date = date ; } } </s>
|
<s> package org . agetac . common . dto ; public class VehicleDTO implements IModel { public enum VehicleState { DISPO_CASERNE , ALERTE , PARTIS , SUR_LES_LIEUX , TRANSPORT_HOPITAL , DISPO_RADIO , TEMPS_DEPASSE , DEMOBILISE } public enum VehicleType { BEA , BRS , BLS , EMB , BLSP , CAEM , CCFM , CCGC , CCGCLC , DA , EPS , ESPM , FMOGP , FPT , MPR , PCM , PEVSD , SAC_PS , UTP , VPRO , VRCB , VICB , VAR , VL , VLCC , VLDP , VLCGD , VLCS , VLCG , VLHR , VLSV , VLOS , VLS , VNRBC , VPL , VPHV , VRAD , VSAV , VSM , VSR , VTP , VTU , VCYNO } private long id ; private String name ; private VehicleState state ; private VehicleType type ; private PositionDTO position ; private BarrackDTO barrack ; private GroupDTO group ; public VehicleDTO ( ) { } public VehicleDTO ( String n , VehicleState s , VehicleType t , PositionDTO p , BarrackDTO b ) { this . name = n ; this . state = s ; this . type = t ; this . position = p ; this . barrack = b ; } public VehicleDTO ( PositionDTO p , VehicleType t , String barrack , VehicleState s , GroupDTO g , String string ) { this . position = p ; this . type = t ; this . state = s ; this . group = g ; } public long getId ( ) { return id ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public VehicleState getState ( ) { return state ; } public void setState ( VehicleState state ) { this . state = state ; } public VehicleType getType ( ) { return type ; } public void setType ( VehicleType type ) { this . type = type ; } public PositionDTO getPosition ( ) { return position ; } public void setPosition ( PositionDTO position ) { this . position = position ; } public BarrackDTO getBarrack ( ) { return barrack ; } public void setBarrack ( BarrackDTO barrack ) { this . barrack = barrack ; } public String getBarrackName ( ) { if ( barrack != null ) { return barrack . getName ( ) ; } return null ; } public GroupDTO getGroup ( ) { return group ; } public void setGroup ( GroupDTO group ) { this . group = group ; } } </s>
|
<s> package org . agetac . common . dto ; public class SourceDTO implements IModel { public enum SourceType { WATER , FIRE , CHEM } private SourceType type ; private PositionDTO position ; private String name = "<STR_LIT>" ; private long id ; public SourceDTO ( ) { this . position = new PositionDTO ( ) ; } public SourceDTO ( SourceType type ) { this . type = type ; this . position = new PositionDTO ( ) ; } public SourceDTO ( String name , SourceType type , PositionDTO p ) { this . name = name ; this . type = type ; this . position = p ; } public SourceDTO ( PositionDTO p , SourceType t ) { this . position = p ; this . type = t ; } public SourceType getType ( ) { return type ; } public void setType ( SourceType type ) { this . type = type ; } public PositionDTO getPosition ( ) { return position ; } public void setPosition ( PositionDTO position ) { this . position = position ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public long getId ( ) { return id ; } } </s>
|
<s> package org . agetac . common . dto ; public class VictimDTO implements IModel { private long id ; private PositionDTO position ; private String name = "<STR_LIT>" ; public VictimDTO ( ) { this . position = new PositionDTO ( ) ; } public VictimDTO ( String name ) { this . name = name ; this . position = new PositionDTO ( ) ; } public long getId ( ) { return id ; } public void setName ( String name ) { this . name = name ; } public String getName ( ) { return name ; } @ Override public PositionDTO getPosition ( ) { return position ; } @ Override public void setPosition ( PositionDTO p ) { this . position = p ; } } </s>
|
<s> package org . agetac . common . dto ; import java . util . Date ; import org . agetac . common . dto . VehicleDTO . VehicleType ; import org . agetac . common . dto . VehicleDemandDTO . DemandState ; public class VehicleDemandDTO implements IModel { public enum DemandState { ASKED , REFUSED , ACCEPTED } private long id ; private Date timestamp ; private DemandState state ; private PositionDTO position ; private VehicleType type ; private String name ; private GroupDTO group ; private int vehicleId = - <NUM_LIT:1> ; public VehicleDemandDTO ( ) { this . position = new PositionDTO ( ) ; } public VehicleDemandDTO ( DemandState s , VehicleType t , PositionDTO p , Date date ) { this . state = s ; this . type = t ; this . position = new PositionDTO ( ) ; this . timestamp = date ; } public VehicleDemandDTO ( String n , PositionDTO p , DemandState s , GroupDTO g ) { this . name = n ; this . position = p ; this . state = s ; this . group = g ; } public long getId ( ) { return id ; } public Date getTimestamp ( ) { return timestamp ; } public void setTimestamp ( Date timestamp ) { this . timestamp = timestamp ; } public DemandState getState ( ) { return state ; } public void setState ( DemandState state ) { this . state = state ; } public PositionDTO getPosition ( ) { return position ; } public void setPosition ( PositionDTO position ) { this . position = position ; } public VehicleType getType ( ) { return type ; } public void setType ( VehicleType type ) { this . type = type ; } public int getVehicleId ( ) { return vehicleId ; } public void setVehicleId ( int vehicleId ) { this . vehicleId = vehicleId ; } @ Override public String getName ( ) { return name ; } @ Override public void setName ( String name ) { this . name = name ; } public GroupDTO getGroup ( ) { return group ; } public void setGroup ( GroupDTO group ) { this . group = group ; } } </s>
|
<s> package org . agetac . common . dto ; public class TargetDTO implements IModel { private long id ; public enum TargetType { WATER , FIRE , CHEM , HUMAN } private TargetType type ; private PositionDTO position ; private String name = "<STR_LIT>" ; public TargetDTO ( ) { } public TargetDTO ( TargetType type ) { this . position = new PositionDTO ( ) ; } public long getId ( ) { return id ; } public TargetDTO ( String name , TargetType type , PositionDTO p ) { this . name = name ; this . type = type ; this . position = p ; } public TargetDTO ( PositionDTO p , TargetType t ) { this . position = p ; this . type = t ; } public TargetType getType ( ) { return type ; } public void setType ( TargetType type ) { this . type = type ; } public PositionDTO getPosition ( ) { return position ; } public void setPosition ( PositionDTO position ) { this . position = position ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } } </s>
|
<s> package org . agetac . common . dto ; public class AgentDTO implements IModel { private long id ; public long getId ( ) { return id ; } @ Override public PositionDTO getPosition ( ) { return null ; } @ Override public void setPosition ( PositionDTO p ) { } @ Override public String getName ( ) { return null ; } @ Override public void setName ( String name ) { } } </s>
|
<s> package org . agetac . handler ; import org . agetac . common . client . AgetacClient ; import org . agetac . common . dto . ActionDTO ; import org . agetac . common . dto . SourceDTO ; import org . agetac . common . dto . TargetDTO ; import org . agetac . common . dto . VehicleDTO ; import org . agetac . common . dto . VehicleDemandDTO ; import org . agetac . common . dto . VictimDTO ; import org . agetac . entity . EntityList ; import org . agetac . entity . IEntity ; public class DeleteHandler implements IHandler { private EntityList entities ; private AgetacClient client ; public DeleteHandler ( EntityList entList , AgetacClient client ) { this . entities = entList ; this . client = client ; } @ Override public void handle ( IEntity entity ) { if ( entity . getModel ( ) instanceof VehicleDTO ) { VehicleDTO v = ( VehicleDTO ) entity . getModel ( ) ; client . deleteVehicle ( v . getId ( ) ) ; entities . remove ( entity ) ; } else if ( entity . getModel ( ) instanceof ActionDTO ) { ActionDTO a = ( ActionDTO ) entity . getModel ( ) ; client . deleteAction ( a . getId ( ) ) ; entities . remove ( entity ) ; } else if ( entity . getModel ( ) instanceof SourceDTO ) { SourceDTO s = ( SourceDTO ) entity . getModel ( ) ; client . deleteSource ( s . getId ( ) ) ; entities . remove ( entity ) ; } else if ( entity . getModel ( ) instanceof TargetDTO ) { TargetDTO c = ( TargetDTO ) entity . getModel ( ) ; client . deleteTarget ( c . getId ( ) ) ; entities . remove ( entity ) ; } else if ( entity . getModel ( ) instanceof VictimDTO ) { VictimDTO i = ( VictimDTO ) entity . getModel ( ) ; client . deleteVictim ( i . getId ( ) ) ; entities . remove ( entity ) ; } else if ( entity . getModel ( ) instanceof VehicleDemandDTO ) { VehicleDemandDTO dm = ( VehicleDemandDTO ) entity . getModel ( ) ; client . deleteVehicleDemand ( dm . getId ( ) ) ; entities . remove ( entity ) ; } } } </s>
|
<s> package org . agetac . handler ; import org . agetac . common . client . AgetacClient ; import org . agetac . entity . EntityList ; import org . agetac . entity . IEntity ; public class UpdateHandler implements IHandler { private EntityList entities ; private AgetacClient client ; public UpdateHandler ( EntityList entList , AgetacClient client ) { this . entities = entList ; this . client = client ; } @ Override public void handle ( IEntity entity ) { System . out . println ( "<STR_LIT>" ) ; } } </s>
|
<s> package org . agetac . handler ; import javax . xml . transform . Source ; import org . agetac . common . client . AgetacClient ; import org . agetac . common . dto . ActionDTO ; import org . agetac . common . dto . SourceDTO ; import org . agetac . common . dto . TargetDTO ; import org . agetac . common . dto . VehicleDTO ; import org . agetac . common . dto . VehicleDemandDTO ; import org . agetac . common . dto . VictimDTO ; import org . agetac . entity . EntityList ; import org . agetac . entity . IEntity ; public class AddHandler implements IHandler { private EntityList entities ; private AgetacClient client ; private int interId ; public AddHandler ( EntityList entList , AgetacClient client , int interId ) { this . entities = entList ; this . client = client ; this . interId = interId ; } @ Override public void handle ( IEntity entity ) { if ( entity . getModel ( ) instanceof ActionDTO ) { ActionDTO a = ( ActionDTO ) entity . getModel ( ) ; entity . setModel ( client . addAction ( interId , a ) ) ; entities . add ( entity ) ; } else if ( entity . getModel ( ) instanceof VehicleDTO ) { VehicleDTO v = ( VehicleDTO ) entity . getModel ( ) ; } else if ( entity . getModel ( ) instanceof Source ) { SourceDTO s = ( SourceDTO ) entity . getModel ( ) ; entity . setModel ( client . addSource ( interId , s ) ) ; entities . add ( entity ) ; } else if ( entity . getModel ( ) instanceof TargetDTO ) { TargetDTO t = ( TargetDTO ) entity . getModel ( ) ; entity . setModel ( client . addTarget ( interId , t ) ) ; entities . add ( entity ) ; } else if ( entity . getModel ( ) instanceof VictimDTO ) { VictimDTO v = ( VictimDTO ) entity . getModel ( ) ; entity . setModel ( client . addVictim ( interId , v ) ) ; entities . add ( entity ) ; } else if ( entity . getModel ( ) instanceof VehicleDemandDTO ) { VehicleDemandDTO vd = ( VehicleDemandDTO ) entity . getModel ( ) ; entity . setModel ( client . addVehicleDemand ( interId , vd ) ) ; entities . add ( entity ) ; } } } </s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.