idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
142,500
public Entity newEntity ( String id , List < Span < Term > > references ) { idManager . updateCounter ( AnnotationType . ENTITY , id ) ; Entity newEntity = new Entity ( id , references ) ; annotationContainer . add ( newEntity , Layer . ENTITIES , AnnotationType . ENTITY ) ; return newEntity ; }
Creates an Entity object to load an existing entity . It receives the ID as an argument . The entity is added to the document object .
72
28
142,501
public Entity newEntity ( List < Span < Term > > references ) { String newId = idManager . getNextId ( AnnotationType . ENTITY ) ; Entity newEntity = new Entity ( newId , references ) ; annotationContainer . add ( newEntity , Layer . ENTITIES , AnnotationType . ENTITY ) ; return newEntity ; }
Creates a new Entity . It assigns an appropriate ID to it . The entity is added to the document object .
73
23
142,502
public Coref newCoref ( String id , List < Span < Term > > mentions ) { idManager . updateCounter ( AnnotationType . COREF , id ) ; Coref newCoref = new Coref ( id , mentions ) ; annotationContainer . add ( newCoref , Layer . COREFERENCES , AnnotationType . COREF ) ; return newCoref ; }
Creates a coreference object to load an existing Coref . It receives it s ID as an argument . The Coref is added to the document .
84
31
142,503
public Coref newCoref ( List < Span < Term > > mentions ) { String newId = idManager . getNextId ( AnnotationType . COREF ) ; Coref newCoref = new Coref ( newId , mentions ) ; annotationContainer . add ( newCoref , Layer . COREFERENCES , AnnotationType . COREF ) ; return newCoref ; }
Creates a new coreference . It assigns an appropriate ID to it . The Coref is added to the document .
85
24
142,504
public Timex3 newTimex3 ( String id , String type ) { idManager . updateCounter ( AnnotationType . TIMEX3 , id ) ; Timex3 newTimex3 = new Timex3 ( id , type ) ; annotationContainer . add ( newTimex3 , Layer . TIME_EXPRESSIONS , AnnotationType . TIMEX3 ) ; return newTimex3 ; }
Creates a timeExpressions object to load an existing Timex3 . It receives it s ID as an argument . The Timex3 is added to the document .
85
34
142,505
public Timex3 newTimex3 ( String type ) { String newId = idManager . getNextId ( AnnotationType . TIMEX3 ) ; Timex3 newTimex3 = new Timex3 ( newId , type ) ; annotationContainer . add ( newTimex3 , Layer . TIME_EXPRESSIONS , AnnotationType . TIMEX3 ) ; return newTimex3 ; }
Creates a new timeExpressions . It assigns an appropriate ID to it . The Coref is added to the document .
86
25
142,506
public Factvalue newFactvalue ( WF wf , String prediction ) { Factvalue factuality = new Factvalue ( wf , prediction ) ; annotationContainer . add ( factuality , Layer . FACTUALITY_LAYER , AnnotationType . FACTVALUE ) ; return factuality ; }
Creates a factualitylayer object and add it to the document
65
13
142,507
public Feature newProperty ( String id , String lemma , List < Span < Term > > references ) { idManager . updateCounter ( AnnotationType . PROPERTY , id ) ; Feature newProperty = new Feature ( id , lemma , references ) ; annotationContainer . add ( newProperty , Layer . PROPERTIES , AnnotationType . PROPERTY ) ; return newProperty ; }
Creates a new property . It receives it s ID as an argument . The property is added to the document .
83
23
142,508
public Feature newProperty ( String lemma , List < Span < Term > > references ) { String newId = idManager . getNextId ( AnnotationType . PROPERTY ) ; Feature newProperty = new Feature ( newId , lemma , references ) ; annotationContainer . add ( newProperty , Layer . PROPERTIES , AnnotationType . PROPERTY ) ; return newProperty ; }
Creates a new property . It assigns an appropriate ID to it . The property is added to the document .
84
22
142,509
public Feature newCategory ( String id , String lemma , List < Span < Term > > references ) { idManager . updateCounter ( AnnotationType . CATEGORY , id ) ; Feature newCategory = new Feature ( id , lemma , references ) ; annotationContainer . add ( newCategory , Layer . CATEGORIES , AnnotationType . CATEGORY ) ; return newCategory ; }
Creates a new category . It receives it s ID as an argument . The category is added to the document .
86
23
142,510
public Feature newCategory ( String lemma , List < Span < Term > > references ) { String newId = idManager . getNextId ( AnnotationType . CATEGORY ) ; Feature newCategory = new Feature ( newId , lemma , references ) ; annotationContainer . add ( newCategory , Layer . CATEGORIES , AnnotationType . CATEGORY ) ; return newCategory ; }
Creates a new category . It assigns an appropriate ID to it . The category is added to the document .
87
22
142,511
public Opinion newOpinion ( ) { String newId = idManager . getNextId ( AnnotationType . OPINION ) ; Opinion newOpinion = new Opinion ( newId ) ; annotationContainer . add ( newOpinion , Layer . OPINIONS , AnnotationType . OPINION ) ; return newOpinion ; }
Creates a new opinion object . It assigns an appropriate ID to it . The opinion is added to the document .
74
23
142,512
public Opinion newOpinion ( String id ) { idManager . updateCounter ( AnnotationType . OPINION , id ) ; Opinion newOpinion = new Opinion ( id ) ; annotationContainer . add ( newOpinion , Layer . OPINIONS , AnnotationType . OPINION ) ; return newOpinion ; }
Creates a new opinion object . It receives its ID as an argument . The opinion is added to the document .
72
23
142,513
public Predicate newPredicate ( String id , Span < Term > span ) { idManager . updateCounter ( AnnotationType . PREDICATE , id ) ; Predicate newPredicate = new Predicate ( id , span ) ; annotationContainer . add ( newPredicate , Layer . SRL , AnnotationType . PREDICATE ) ; return newPredicate ; }
Creates a new srl predicate . It receives its ID as an argument . The predicate is added to the document .
80
24
142,514
public Predicate newPredicate ( Span < Term > span ) { String newId = idManager . getNextId ( AnnotationType . PREDICATE ) ; Predicate newPredicate = new Predicate ( newId , span ) ; annotationContainer . add ( newPredicate , Layer . SRL , AnnotationType . PREDICATE ) ; return newPredicate ; }
Creates a new srl predicate . It assigns an appropriate ID to it . The predicate is added to the document .
81
24
142,515
public Predicate . Role newRole ( String id , Predicate predicate , String semRole , Span < Term > span ) { idManager . updateCounter ( AnnotationType . ROLE , id ) ; Predicate . Role newRole = new Predicate . Role ( id , semRole , span ) ; return newRole ; }
Creates a Role object to load an existing role . It receives the ID as an argument . It doesn t add the role to the predicate .
68
29
142,516
public Predicate . Role newRole ( Predicate predicate , String semRole , Span < Term > span ) { String newId = idManager . getNextId ( AnnotationType . ROLE ) ; Predicate . Role newRole = new Predicate . Role ( newId , semRole , span ) ; return newRole ; }
Creates a new Role object . It assigns an appropriate ID to it . It uses the ID of the predicate to create a new ID for the role . It doesn t add the role to the predicate .
69
41
142,517
public List < List < WF > > getSentences ( ) { return ( List < List < WF > > ) ( List < ? > ) annotationContainer . getSentences ( AnnotationType . WF ) ; }
Returns a list with all sentences . Each sentence is a list of WFs .
48
16
142,518
public List < Term > getTermsFromWFs ( List < String > wfIds ) { List < Term > terms = new ArrayList < Term > ( ) ; for ( String wfId : wfIds ) { terms . addAll ( this . wfId2Terms . get ( wfId ) ) ; } return terms ; }
Hau kendu behar da
77
8
142,519
public String createTimestamp ( ) { Date date = new Date ( ) ; //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd H:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ssZ" ) ; String formattedDate = sdf . format ( date ) ; return formattedDate ; }
Returns current timestamp .
87
4
142,520
static < T extends IdentifiableAnnotation > Span < T > list2Span ( List < T > list ) { Span < T > span = new Span < T > ( ) ; for ( T elem : list ) { span . addTarget ( elem ) ; } return span ; }
Converts a List into a Span
62
7
142,521
static Span < Term > targetList2Span ( List < Target > list ) { Span < Term > span = new Span < Term > ( ) ; for ( Target target : list ) { if ( target . isHead ( ) ) { span . addTarget ( target . getTerm ( ) , true ) ; } else { span . addTarget ( target . getTerm ( ) ) ; } } return span ; }
Converts a Target list into a Span of terms
87
10
142,522
static List < Target > span2TargetList ( Span < Term > span ) { List < Target > list = new ArrayList < Target > ( ) ; for ( Term t : span . getTargets ( ) ) { list . add ( KAFDocument . createTarget ( t , ( t == span . getHead ( ) ) ) ) ; } return list ; }
Converts a Span into a Target list
78
8
142,523
@ Nullable public static String findContentText ( final Node rootNode , final XPath xPath , final String expression ) { final Node node = findNode ( rootNode , xPath , expression ) ; if ( node == null ) { return null ; } return node . getTextContent ( ) ; }
Returns an string from a node s content .
63
9
142,524
@ Nullable public static Integer findContentInteger ( final Node rootNode , final XPath xPath , final String expression ) { final Node node = findNode ( rootNode , xPath , expression ) ; if ( node == null ) { return null ; } final String str = node . getTextContent ( ) ; return Integer . valueOf ( str ) ; }
Returns an integer value from a node s content .
75
10
142,525
@ Nullable public static Node findNode ( @ NotNull final Node rootNode , @ NotNull final XPath xPath , @ NotNull final String expression ) { Contract . requireArgNotNull ( "rootNode" , rootNode ) ; Contract . requireArgNotNull ( "xPath" , xPath ) ; Contract . requireArgNotNull ( "expression" , expression ) ; try { return ( Node ) xPath . compile ( expression ) . evaluate ( rootNode , XPathConstants . NODE ) ; } catch ( final XPathExpressionException ex ) { throw new RuntimeException ( "Failed to read node: " + expression , ex ) ; } }
Returns a single node from a given document using xpath .
141
12
142,526
@ Nullable public static NodeList findNodes ( @ NotNull final Node rootNode , @ NotNull final XPath xPath , @ NotNull final String expression ) { Contract . requireArgNotNull ( "doc" , rootNode ) ; Contract . requireArgNotNull ( "xPath" , xPath ) ; Contract . requireArgNotNull ( "expression" , expression ) ; try { return ( NodeList ) xPath . compile ( expression ) . evaluate ( rootNode , XPathConstants . NODESET ) ; } catch ( final XPathExpressionException ex ) { throw new RuntimeException ( "Failed to read node: " + expression , ex ) ; } }
Returns a list of nodes from a given document using xpath .
145
13
142,527
@ NotNull public static Document parseDocument ( @ NotNull final DocumentBuilder builder , @ NotNull final InputStream inputStream ) { Contract . requireArgNotNull ( "builder" , builder ) ; Contract . requireArgNotNull ( "inputStream" , inputStream ) ; try { return builder . parse ( inputStream ) ; } catch ( final SAXException | IOException ex ) { throw new RuntimeException ( "Failed to parse XML" , ex ) ; } }
Parse the document and wraps checked exceptions into runtime exceptions .
99
12
142,528
@ NotNull public static XPath createXPath ( @ Nullable final String ... values ) { final NamespaceContext context = new NamespaceContextMap ( values ) ; final XPath xPath = XPathFactory . newInstance ( ) . newXPath ( ) ; xPath . setNamespaceContext ( context ) ; return xPath ; }
Creates a new XPath with a configured namespace context .
72
12
142,529
@ NotNull public static DocumentBuilder createDocumentBuilder ( ) { try { final DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; return factory . newDocumentBuilder ( ) ; } catch ( final ParserConfigurationException ex ) { throw new RuntimeException ( "Couldn't create document builder" , ex ) ; } }
Creates a namespace aware document builder .
80
8
142,530
private void reduceResults ( final List < AnalysisResultFuture > results , final Map < ComponentJob , AnalyzerResult > resultMap , final List < AnalysisResultReductionException > reductionErrors ) { if ( _hasRun . get ( ) ) { // already reduced return ; } _hasRun . set ( true ) ; for ( AnalysisResultFuture result : results ) { if ( result . isErrornous ( ) ) { logger . error ( "Encountered errorneous slave result. Result reduction will stop. Result={}" , result ) ; final List < Throwable > errors = result . getErrors ( ) ; if ( ! errors . isEmpty ( ) ) { final Throwable firstError = errors . get ( 0 ) ; logger . error ( "Encountered error before reducing results (showing stack trace of invoking the reducer): " + firstError . getMessage ( ) , new Throwable ( ) ) ; _analysisListener . errorUknown ( _masterJob , firstError ) ; } // error occurred! return ; } } final Collection < AnalyzerJob > analyzerJobs = _masterJob . getAnalyzerJobs ( ) ; for ( AnalyzerJob masterAnalyzerJob : analyzerJobs ) { final Collection < AnalyzerResult > slaveResults = new ArrayList < AnalyzerResult > ( ) ; logger . info ( "Reducing {} slave results for component: {}" , results . size ( ) , masterAnalyzerJob ) ; for ( AnalysisResultFuture result : results ) { final Map < ComponentJob , AnalyzerResult > slaveResultMap = result . getResultMap ( ) ; final List < AnalyzerJob > slaveAnalyzerJobs = CollectionUtils2 . filterOnClass ( slaveResultMap . keySet ( ) , AnalyzerJob . class ) ; final AnalyzerJobHelper analyzerJobHelper = new AnalyzerJobHelper ( slaveAnalyzerJobs ) ; final AnalyzerJob slaveAnalyzerJob = analyzerJobHelper . getAnalyzerJob ( masterAnalyzerJob ) ; if ( slaveAnalyzerJob == null ) { throw new IllegalStateException ( "Could not resolve slave component matching [" + masterAnalyzerJob + "] in slave result: " + result ) ; } final AnalyzerResult analyzerResult = result . getResult ( slaveAnalyzerJob ) ; slaveResults . add ( analyzerResult ) ; } reduce ( masterAnalyzerJob , slaveResults , resultMap , reductionErrors ) ; } }
Reduces all the analyzer results of an analysis
520
10
142,531
@ SuppressWarnings ( "unchecked" ) private void reduce ( AnalyzerJob analyzerJob , Collection < AnalyzerResult > slaveResults , Map < ComponentJob , AnalyzerResult > resultMap , List < AnalysisResultReductionException > reductionErrors ) { if ( slaveResults . size ( ) == 1 ) { // special case where these was only 1 slave job final AnalyzerResult firstResult = slaveResults . iterator ( ) . next ( ) ; resultMap . put ( analyzerJob , firstResult ) ; _analysisListener . analyzerSuccess ( _masterJob , analyzerJob , firstResult ) ; return ; } final Class < ? extends AnalyzerResultReducer < ? > > reducerClass = analyzerJob . getDescriptor ( ) . getResultReducerClass ( ) ; final ComponentDescriptor < ? extends AnalyzerResultReducer < ? > > reducerDescriptor = Descriptors . ofComponent ( reducerClass ) ; AnalyzerResultReducer < AnalyzerResult > reducer = null ; boolean success = false ; try { reducer = ( AnalyzerResultReducer < AnalyzerResult > ) reducerDescriptor . newInstance ( ) ; _lifeCycleHelper . assignProvidedProperties ( reducerDescriptor , reducer ) ; _lifeCycleHelper . initialize ( reducerDescriptor , reducer ) ; final AnalyzerResult reducedResult = reducer . reduce ( slaveResults ) ; resultMap . put ( analyzerJob , reducedResult ) ; success = true ; _analysisListener . analyzerSuccess ( _masterJob , analyzerJob , reducedResult ) ; } catch ( Exception e ) { AnalysisResultReductionException reductionError = new AnalysisResultReductionException ( analyzerJob , slaveResults , e ) ; reductionErrors . add ( reductionError ) ; _analysisListener . errorInComponent ( _masterJob , analyzerJob , null , e ) ; } finally { if ( reducer != null ) { _lifeCycleHelper . close ( reducerDescriptor , reducer , success ) ; } } }
Reduces result for a single analyzer
443
8
142,532
public Configuration unmarshall ( InputStream inputStream ) { try { final Unmarshaller unmarshaller = _jaxbContext . createUnmarshaller ( ) ; unmarshaller . setEventHandler ( new JaxbValidationEventHandler ( ) ) ; final Configuration configuration = ( Configuration ) unmarshaller . unmarshal ( inputStream ) ; return configuration ; } catch ( JAXBException e ) { throw new IllegalStateException ( e ) ; } }
Convenience method to get the untouched JAXB configuration object from an inputstream .
105
18
142,533
public void marshall ( Configuration configuration , OutputStream outputStream ) { try { final Marshaller marshaller = _jaxbContext . createMarshaller ( ) ; marshaller . setProperty ( Marshaller . JAXB_FORMATTED_OUTPUT , Boolean . TRUE ) ; marshaller . setEventHandler ( new JaxbValidationEventHandler ( ) ) ; marshaller . marshal ( configuration , outputStream ) ; } catch ( JAXBException e ) { throw new IllegalStateException ( e ) ; } }
Convenience method to marshal a JAXB configuration object into an output stream .
117
18
142,534
public static synchronized void createSource ( Java . _ClassBody clazz ) throws IOException { if ( baseDir == null ) { throw new IOException ( "Base directory for output not set, use 'setBaseDirectory'" ) ; } String pkg = clazz . getPackage ( ) ; if ( pkg == null ) { pkg = "" ; // throw new IOException("Class package cannot be null"); } pkg = pkg . replace ( ' ' , ' ' ) ; File path = new File ( baseDir , pkg ) ; path . mkdirs ( ) ; try ( PrintWriter fp = new PrintWriter ( new FileWriter ( new File ( path , clazz . getName ( ) + ".java" ) ) ) ) { clazz . emit ( 0 , fp ) ; } }
Create the source file for a given class
172
8
142,535
private static void emitCommentIndentN ( PrintWriter fp , String text , int indent , boolean type ) { synchronized ( lock ) { String cc = type ? "/**" : "/*" ; fp . println ( cc ) ; String comment = emitCommentIndentNOnly ( fp , text , indent ) ; fp . println ( comment + "/" ) ; } }
Write a comment at some indentation level .
81
9
142,536
private static void emitFinishCommentIndentN ( PrintWriter fp , int indent ) { final String spaces = " " ; synchronized ( lock ) { String comment = spaces . substring ( 0 , indent ) + " */" ; fp . println ( comment ) ; } }
Finish a comment .
58
4
142,537
private static String emitCommentIndentNOnly ( PrintWriter fp , String text , int indent ) { synchronized ( lock ) { return ( emitCommentIndentNOnly ( fp , text , indent , true ) ) ; } }
Write a comment indent only .
49
6
142,538
public void create ( String outputdir , Program program ) { types . stream ( ) . forEach ( ( type ) - > type . createOutput ( outputdir , program ) ) ; }
Create the output .
39
4
142,539
protected boolean setConfiguredPropertyIfChanged ( final ConfiguredPropertyDescriptor configuredProperty , final Object value ) { if ( configuredProperty == null ) { throw new IllegalArgumentException ( "configuredProperty cannot be null" ) ; } final Object currentValue = configuredProperty . getValue ( _configurableBean ) ; if ( EqualsBuilder . equals ( currentValue , value ) ) { // no change return false ; } if ( value != null ) { boolean correctType = true ; if ( configuredProperty . isArray ( ) ) { if ( value . getClass ( ) . isArray ( ) ) { int length = Array . getLength ( value ) ; for ( int i = 0 ; i < length ; i ++ ) { Object valuePart = Array . get ( value , i ) ; if ( valuePart == null ) { logger . warn ( "Element no. {} in array (size {}) is null! Value passed to {}" , new Object [ ] { i , length , configuredProperty } ) ; } else { if ( ! ReflectionUtils . is ( valuePart . getClass ( ) , configuredProperty . getBaseType ( ) ) ) { correctType = false ; } } } } else { if ( ! ReflectionUtils . is ( value . getClass ( ) , configuredProperty . getBaseType ( ) ) ) { correctType = false ; } } } else { if ( ! ReflectionUtils . is ( value . getClass ( ) , configuredProperty . getBaseType ( ) ) ) { correctType = false ; } } if ( ! correctType ) { throw new IllegalArgumentException ( "Invalid value type: " + value . getClass ( ) . getName ( ) + ", expected: " + configuredProperty . getBaseType ( ) . getName ( ) ) ; } } configuredProperty . setValue ( _configurableBean , value ) ; return true ; }
Sets a configured property if it has changed .
404
10
142,540
@ NotNull public static < T > T deserialize ( @ NotNull final DeserializerRegistry registry , @ NotNull final SerializedData data ) { Contract . requireArgNotNull ( "registry" , registry ) ; Contract . requireArgNotNull ( "data" , data ) ; final Deserializer deserializer = registry . getDeserializer ( data . getType ( ) , data . getMimeType ( ) ) ; return deserializer . unmarshal ( data . getRaw ( ) , data . getType ( ) , data . getMimeType ( ) ) ; }
Tries to find a deserializer for the given data block .
129
14
142,541
public static EnhancedMimeType mimeType ( @ NotNull final SerializerRegistry registry , @ NotNull final List < CommonEvent > commonEvents ) { Contract . requireArgNotNull ( "registry" , registry ) ; Contract . requireArgNotNull ( "commonEvents" , commonEvents ) ; EnhancedMimeType mimeType = null ; for ( final CommonEvent commonEvent : commonEvents ) { final Serializer serializer = registry . getSerializer ( new SerializedDataType ( commonEvent . getDataType ( ) . asBaseType ( ) ) ) ; if ( mimeType == null ) { mimeType = serializer . getMimeType ( ) ; } else { if ( ! mimeType . equals ( serializer . getMimeType ( ) ) ) { return null ; } } } return mimeType ; }
Returns the mime types shared by all events in the list .
180
13
142,542
public static boolean eventsEqual ( @ Nullable final List < CommonEvent > eventsA , @ Nullable final List < CommonEvent > eventsB ) { if ( ( eventsA == null ) && ( eventsB == null ) ) { return true ; } if ( ( eventsA == null ) && ( eventsB != null ) ) { return false ; } if ( ( eventsA != null ) && ( eventsB == null ) ) { return false ; } if ( eventsA . size ( ) != eventsB . size ( ) ) { return false ; } int currentIdx = eventsA . size ( ) - 1 ; int appendIdx = eventsB . size ( ) - 1 ; while ( appendIdx >= 0 ) { final CommonEvent current = eventsA . get ( currentIdx ) ; final CommonEvent append = eventsB . get ( appendIdx ) ; if ( ! current . equals ( append ) ) { return false ; } currentIdx -- ; appendIdx -- ; } return true ; }
Tests if both lists contain the same events .
213
10
142,543
public static String nodeToString ( final Node node ) { try { final Transformer t = TransformerFactory . newInstance ( ) . newTransformer ( ) ; t . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "yes" ) ; final StringWriter sw = new StringWriter ( ) ; t . transform ( new DOMSource ( node ) , new StreamResult ( sw ) ) ; return sw . toString ( ) ; } catch ( final TransformerException ex ) { throw new RuntimeException ( "Failed to render node" , ex ) ; } }
Render a node as string .
125
6
142,544
public static JsonbDeserializer < ? > [ ] joinJsonbDeserializerArrays ( final JsonbDeserializer < ? > [ ] ... deserializerArrays ) { final List < JsonbDeserializer < ? > > all = joinArrays ( deserializerArrays ) ; return all . toArray ( new JsonbDeserializer < ? > [ all . size ( ) ] ) ; }
Creates all available JSON - B deserializers necessary for the ESC implementation .
95
16
142,545
@ Override public final CommonEvent convert ( final RecordedEvent eventData ) { final EnhancedMimeType escMetaMimeType = metaMimeType ( eventData . isJson ) ; final SerializedDataType escSerMetaType = new SerializedDataType ( EscMeta . TYPE . asBaseType ( ) ) ; final Deserializer escMetaDeserializer = deserRegistry . getDeserializer ( escSerMetaType , escMetaMimeType ) ; final EscMeta escMeta = escMetaDeserializer . unmarshal ( eventData . metadata , escSerMetaType , escMetaMimeType ) ; final EnhancedMimeType metaMimeType = escMeta . getMetaContentType ( ) ; final String metaTransferEncoding ; if ( escMeta . getMetaType ( ) == null ) { metaTransferEncoding = null ; } else { metaTransferEncoding = escMeta . getMetaContentType ( ) . getParameter ( "transfer-encoding" ) ; } final EnhancedMimeType dataMimeType = escMeta . getDataContentType ( ) ; final SerializedDataType serDataType = new SerializedDataType ( escMeta . getDataType ( ) ) ; final Deserializer dataDeserializer = deserRegistry . getDeserializer ( serDataType , dataMimeType ) ; final String dataTransferEncoding = escMeta . getDataContentType ( ) . getParameter ( "transfer-encoding" ) ; final Object data = unmarshal ( dataTransferEncoding , serDataType , dataDeserializer , dataMimeType , eventData . data , metaMimeType , escMetaMimeType ) ; final EventId eventId = new EventId ( eventData . eventId ) ; final TypeName dataType = new TypeName ( eventData . eventType ) ; if ( escMeta . getMetaType ( ) == null ) { return new SimpleCommonEvent ( eventId , dataType , data ) ; } final TypeName metaType = new TypeName ( escMeta . getMetaType ( ) ) ; final SerializedDataType serMetaType = new SerializedDataType ( escMeta . getMetaType ( ) ) ; final Deserializer metaDeserializer = deserRegistry . getDeserializer ( serMetaType , metaMimeType ) ; final Object meta = unmarshal ( metaTransferEncoding , serMetaType , metaDeserializer , metaMimeType , escMeta . getMeta ( ) , metaMimeType , escMetaMimeType ) ; return new SimpleCommonEvent ( eventId , dataType , data , metaType , meta ) ; }
Converts event data into a common event .
563
9
142,546
public SortedSet < TimeInterval > getOverlappingIntervals ( boolean includeSingleTimeInstanceIntervals ) { SortedSet < TimeInterval > result = new TreeSet < TimeInterval > ( ) ; for ( TimeInterval interval1 : intervals ) { for ( TimeInterval interval2 : intervals ) { if ( interval1 != interval2 ) { TimeInterval overlap = interval1 . getOverlap ( interval2 ) ; if ( overlap != null ) { result . add ( overlap ) ; } } } } result = getFlattenedIntervals ( result ) ; if ( ! includeSingleTimeInstanceIntervals ) { for ( Iterator < TimeInterval > it = result . iterator ( ) ; it . hasNext ( ) ; ) { TimeInterval timeInterval = it . next ( ) ; if ( timeInterval . isSingleTimeInstance ( ) ) { it . remove ( ) ; } } } return result ; }
Gets a set of intervals representing the times where there are more than one interval overlaps .
200
19
142,547
public SortedSet < TimeInterval > getTimeGapIntervals ( ) { SortedSet < TimeInterval > flattenedIntervals = getFlattenedIntervals ( ) ; SortedSet < TimeInterval > gaps = new TreeSet < TimeInterval > ( ) ; TimeInterval previous = null ; for ( TimeInterval timeInterval : flattenedIntervals ) { if ( previous != null ) { long from = previous . getTo ( ) ; long to = timeInterval . getFrom ( ) ; TimeInterval gap = new TimeInterval ( from , to ) ; gaps . add ( gap ) ; } previous = timeInterval ; } return gaps ; }
Gets a set of intervals representing the times that are NOT represented in this timeline .
144
17
142,548
public static byte [ ] decode ( char [ ] in , int iOff , int iLen ) { if ( iLen % 4 != 0 ) { throw new IllegalArgumentException ( "Length of Base64 encoded input string is not a multiple of 4." ) ; } while ( iLen > 0 && in [ iOff + iLen - 1 ] == ' ' ) { iLen -- ; } int oLen = ( iLen * 3 ) / 4 ; byte [ ] out = new byte [ oLen ] ; int ip = iOff ; int iEnd = iOff + iLen ; int op = 0 ; while ( ip < iEnd ) { int i0 = in [ ip ++ ] ; int i1 = in [ ip ++ ] ; int i2 = ip < iEnd ? in [ ip ++ ] : ' ' ; int i3 = ip < iEnd ? in [ ip ++ ] : ' ' ; if ( i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127 ) { throw new IllegalArgumentException ( "Illegal character in Base64 encoded data." ) ; } int b0 = map2 [ i0 ] ; int b1 = map2 [ i1 ] ; int b2 = map2 [ i2 ] ; int b3 = map2 [ i3 ] ; if ( b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0 ) { throw new IllegalArgumentException ( "Illegal character in Base64 encoded data." ) ; } int o0 = ( b0 << 2 ) | ( b1 >>> 4 ) ; int o1 = ( ( b1 & 0xf ) << 4 ) | ( b2 >>> 2 ) ; int o2 = ( ( b2 & 3 ) << 6 ) | b3 ; out [ op ++ ] = ( byte ) o0 ; if ( op < oLen ) { out [ op ++ ] = ( byte ) o1 ; } if ( op < oLen ) { out [ op ++ ] = ( byte ) o2 ; } } return out ; }
Decodes a byte array from Base64 format . No blanks or line breaks are allowed within the Base64 encoded input data .
441
26
142,549
private String getPropertyKey ( ) { if ( StringUtils . isNullOrEmpty ( captureStateIdentifier ) ) { if ( lastModifiedColumn . isPhysicalColumn ( ) ) { Table table = lastModifiedColumn . getPhysicalColumn ( ) . getTable ( ) ; if ( table != null && ! StringUtils . isNullOrEmpty ( table . getName ( ) ) ) { return table . getName ( ) + "." + lastModifiedColumn . getName ( ) + ".GreatestLastModifiedTimestamp" ; } } return lastModifiedColumn . getName ( ) + ".GreatestLastModifiedTimestamp" ; } return captureStateIdentifier . trim ( ) + ".GreatestLastModifiedTimestamp" ; }
Gets the key to use in the capture state file . If there is not a captureStateIdentifier available we want to avoid using a hardcoded key since the same file may be used for multiple purposes even multiple filters of the same type . Of course this is not desired configuration but may be more convenient for lazy users!
160
65
142,550
public static void addToScope ( Scriptable scope , Object object , String ... names ) { Object jsObject = Context . javaToJS ( object , scope ) ; for ( String name : names ) { name = name . replaceAll ( " " , "_" ) ; ScriptableObject . putProperty ( scope , name , jsObject ) ; } }
Adds an object to the JavaScript scope with a set of variable names
73
13
142,551
public static void addToScope ( Scriptable scope , InputRow inputRow , InputColumn < ? > [ ] columns , String arrayName ) { NativeArray values = new NativeArray ( columns . length * 2 ) ; for ( int i = 0 ; i < columns . length ; i ++ ) { InputColumn < ? > column = columns [ i ] ; Object value = inputRow . getValue ( column ) ; if ( value != null ) { Class < ? > dataType = column . getDataType ( ) ; if ( ReflectionUtils . isNumber ( dataType ) ) { value = Context . toNumber ( value ) ; } else if ( ReflectionUtils . isBoolean ( dataType ) ) { value = Context . toBoolean ( value ) ; } } values . put ( i , values , value ) ; values . put ( column . getName ( ) , values , value ) ; addToScope ( scope , value , column . getName ( ) , column . getName ( ) . toLowerCase ( ) , column . getName ( ) . toUpperCase ( ) ) ; } addToScope ( scope , values , arrayName ) ; }
Adds the values of a row to the JavaScript scope
248
10
142,552
@ Nullable public final Charset getEncoding ( ) { final String parameter = getParameter ( ENCODING ) ; if ( parameter == null ) { return null ; } return Charset . forName ( parameter ) ; }
Returns the encoding from the parameters .
50
7
142,553
public final boolean matchEncoding ( final EnhancedMimeType other ) { return match ( other ) && Objects . equals ( getEncoding ( ) , other . getEncoding ( ) ) ; }
Determine if the primary sub type and encoding of this object is the same as what is in the given type .
41
24
142,554
@ Nullable public static EnhancedMimeType create ( @ Nullable final String str ) { if ( str == null ) { return null ; } try { return new EnhancedMimeType ( str ) ; } catch ( final MimeTypeParseException ex ) { throw new RuntimeException ( "Failed to create versioned mime type: " + str , ex ) ; } }
Creates an instance with all data . Exceptions are wrapped to runtime exceptions .
80
16
142,555
@ NotNull public static EnhancedMimeType create ( @ NotNull final String primary , @ NotNull final String sub , final Charset encoding , final String version ) { return create ( primary , sub , encoding , version , new HashMap < String , String > ( ) ) ; }
Creates an instance with primary sub type encoding and version . Exceptions are wrapped to runtime exceptions .
60
20
142,556
@ NotNull public static EnhancedMimeType create ( @ NotNull final String primary , @ NotNull final String sub , final Charset encoding , final String version , final Map < String , String > parameters ) { try { return new EnhancedMimeType ( primary , sub , encoding , version , parameters ) ; } catch ( final MimeTypeParseException ex ) { throw new RuntimeException ( "Failed to create versioned mime type: " + primary + "/" + sub , ex ) ; } }
Creates an instance with all data and exceptions wrapped to runtime exceptions .
108
14
142,557
public void init ( final SerializedDataTypeRegistry typeRegistry , final DeserializerRegistry deserRegistry , final SerializerRegistry serRegistry ) { if ( initialized ) { throw new IllegalStateException ( "Instance already initialized - Don't call the init methods more than once" ) ; } this . typeRegistry = typeRegistry ; for ( final JsonbDeserializer < ? > deserializer : deserializers ) { if ( deserializer instanceof DeserializerRegistryRequired ) { if ( deserRegistry == null ) { throw new IllegalStateException ( "There is at least one deserializer that requires a 'DeserializerRegistry', but you didn't provide one (deserializer=" + deserializer . getClass ( ) . getName ( ) + ")" ) ; } final DeserializerRegistryRequired des = ( DeserializerRegistryRequired ) deserializer ; des . setRegistry ( deserRegistry ) ; } if ( deserializer instanceof SerializedDataTypeRegistryRequired ) { if ( typeRegistry == null ) { throw new IllegalStateException ( "There is at least one deserializer that requires a 'SerializedDataTypeRegistry', but you didn't provide one (deserializer=" + deserializer . getClass ( ) . getName ( ) + ")" ) ; } final SerializedDataTypeRegistryRequired des = ( SerializedDataTypeRegistryRequired ) deserializer ; des . setRegistry ( typeRegistry ) ; } } for ( final JsonbSerializer < ? > serializer : serializers ) { if ( serializer instanceof SerializerRegistryRequired ) { if ( serRegistry == null ) { throw new IllegalStateException ( "There is at least one serializer that requires a 'SerializerRegistry', but you didn't provide one (serializer=" + serializer . getClass ( ) . getName ( ) + ")" ) ; } final SerializerRegistryRequired ser = ( SerializerRegistryRequired ) serializer ; ser . setRegistry ( serRegistry ) ; } if ( serializer instanceof SerializedDataTypeRegistryRequired ) { if ( typeRegistry == null ) { throw new IllegalStateException ( "There is at least one serializer that requires a 'SerializedDataTypeRegistry', but you didn't provide one (serializer=" + serializer . getClass ( ) . getName ( ) + ")" ) ; } final SerializedDataTypeRegistryRequired ser = ( SerializedDataTypeRegistryRequired ) serializer ; ser . setRegistry ( typeRegistry ) ; } } initialized = true ; }
Initializes the instance with necessary registries .
569
9
142,558
public void initializeAll ( InjectionManager injectionManager ) { if ( injectionManager != null ) { for ( Converter < ? > converter : _converters ) { Field [ ] fields = ReflectionUtils . getFields ( converter . getClass ( ) , Inject . class ) ; for ( Field field : fields ) { final Object value ; if ( field . getType ( ) == Converter . class ) { // Injected converters are used as callbacks. They // should be assigned to the outer converter, which is // this. value = this ; } else { InjectionPoint < Object > injectionPoint = new MemberInjectionPoint < Object > ( field , converter ) ; value = injectionManager . getInstance ( injectionPoint ) ; } field . setAccessible ( true ) ; try { field . set ( converter , value ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Could not initialize converter: " + converter , e ) ; } } } } }
Initializes all converters contained with injections
209
8
142,559
public static Method [ ] getMethods ( Class < ? > clazz ) { final boolean legacyApproach = isGetMethodsLegacyApproach ( ) ; final List < Method > allMethods = new ArrayList <> ( ) ; addMethods ( allMethods , clazz , legacyApproach ) ; return allMethods . toArray ( new Method [ allMethods . size ( ) ] ) ; }
Gets all methods of a class excluding those from Object .
82
12
142,560
public static < T > String joinAnd ( final String delimiter , final String lastDelimiter , final Collection < T > objs ) { if ( objs == null || objs . isEmpty ( ) ) { return "" ; } final Iterator < T > iter = objs . iterator ( ) ; final StringBuffer buffer = new StringBuffer ( Strings . toString ( iter . next ( ) ) ) ; int i = 1 ; while ( iter . hasNext ( ) ) { final T obj = iter . next ( ) ; if ( notEmpty ( obj ) ) { buffer . append ( ++ i == objs . size ( ) ? lastDelimiter : delimiter ) . append ( Strings . toString ( obj ) ) ; } } return buffer . toString ( ) ; }
Like join but allows for a distinct final delimiter . For english sentences such as Alice Bob and Charlie use and and as the delimiters .
168
29
142,561
public final ProjectionJavaScriptBuilder type ( final String eventType ) { if ( count > 0 ) { sb . append ( "," ) ; } sb . append ( "'" + eventType + "': function(state, ev) { linkTo('" + projection + "', ev); }" ) ; count ++ ; return this ; }
Adds another type to select .
74
6
142,562
public List < CommonEvent > asCommonEvents ( final JAXBContext ctx ) { final List < CommonEvent > list = new ArrayList < CommonEvent > ( ) ; for ( final Event event : events ) { list . add ( event . asCommonEvent ( ctx ) ) ; } return list ; }
Returns this object as a list of common event objects .
67
11
142,563
public static boolean isValid ( String name ) { char [ ] nameChars = name . toCharArray ( ) ; for ( int i = 0 ; i < nameChars . length ; i ++ ) { boolean valid = i == 0 ? Character . isJavaIdentifierStart ( nameChars [ i ] ) : Character . isJavaIdentifierPart ( nameChars [ i ] ) ; if ( ! valid ) { return valid ; } } return true ; }
Test if an identifier is valid .
98
7
142,564
List < Integer > getParaSents ( Integer para ) { List < Integer > sentList = new ArrayList < Integer > ( this . paraSentIndex . get ( para ) ) ; Collections . sort ( sentList ) ; return sentList ; }
Returns all sentences in a paragraph .
53
7
142,565
List < List < Annotation > > getSentences ( AnnotationType type , String groupID ) { List < List < Annotation >> sentences = new ArrayList < List < Annotation > > ( ) ; for ( int sent : Helper . getIndexKeys ( type , groupID , this . sentIndex ) ) { sentences . add ( this . getSentAnnotations ( sent , type ) ) ; } return sentences ; }
Return all annotations of type type classified into sentences
90
9
142,566
List < List < Annotation > > getParagraphs ( AnnotationType type , String groupID ) { List < List < Annotation >> paragraphs = new ArrayList < List < Annotation > > ( ) ; for ( int para : Helper . getIndexKeys ( type , groupID , this . paraIndex ) ) { paragraphs . add ( this . getParaAnnotations ( para , type ) ) ; } return paragraphs ; }
Return all annotations of type type classified into paragraphs
92
9
142,567
public static String streamEntityName ( final StreamId streamId ) { // User defined ID if ( streamId instanceof JpaStreamId ) { final JpaStreamId jpaId = ( JpaStreamId ) streamId ; return jpaId . getEntityName ( ) ; } // Default ID if ( streamId . isProjection ( ) ) { return streamId . getName ( ) ; } if ( streamId . getParameters ( ) . size ( ) == 0 ) { return NoParamsStream . class . getSimpleName ( ) ; } return streamId . getName ( ) + "Stream" ; }
Returns the name of the stream entity for a given stream .
131
12
142,568
public static String nativeEventsTableName ( final StreamId streamId ) { // User defined ID if ( streamId instanceof JpaStreamId ) { final JpaStreamId jpaId = ( JpaStreamId ) streamId ; return jpaId . getNativeTableName ( ) ; } // Default ID if ( streamId . isProjection ( ) ) { return camel2Underscore ( streamId . getName ( ) ) ; } if ( streamId . getParameters ( ) . size ( ) == 0 ) { return NoParamsEvent . NO_PARAMS_EVENTS_TABLE ; } return camel2Underscore ( streamId . getName ( ) ) + "_events" ; }
Returns a native database events table name .
149
8
142,569
public static String camel2Underscore ( @ Nullable final String name ) { if ( name == null ) { return null ; } return name . replaceAll ( "(.)(\\p{Upper})" , "$1_$2" ) . toLowerCase ( ) ; }
Converts the given camel case name into a name with underscores .
60
13
142,570
public final CommonEvent asCommonEvent ( final JAXBContext ctx ) { final Object m ; if ( getMeta ( ) == null ) { m = null ; } else { m = getMeta ( ) . unmarshalContent ( ctx ) ; } final Object d = getData ( ) . unmarshalContent ( ctx ) ; if ( getMeta ( ) == null ) { return new SimpleCommonEvent ( getId ( ) , new TypeName ( getData ( ) . getType ( ) ) , d ) ; } return new SimpleCommonEvent ( getId ( ) , new TypeName ( getData ( ) . getType ( ) ) , d , new TypeName ( getMeta ( ) . getType ( ) ) , m ) ; }
Returns this object as a common event object .
161
9
142,571
public static Event valueOf ( final CommonEvent selEvent ) { final Data data = Data . valueOf ( selEvent . getDataType ( ) . asBaseType ( ) , selEvent . getData ( ) ) ; if ( selEvent . getMeta ( ) == null ) { return new Event ( selEvent . getId ( ) , data ) ; } final Data meta = Data . valueOf ( "meta" , selEvent . getMeta ( ) ) ; return new Event ( selEvent . getId ( ) , data , meta ) ; }
Creates an event using a common event .
122
9
142,572
public boolean isConfigured ( final boolean throwException ) throws IllegalStateException , UnconfiguredConfiguredPropertyException { if ( _datastoreConnection == null ) { if ( throwException ) { throw new IllegalStateException ( "No Datastore or DatastoreConnection set" ) ; } return false ; } if ( _sourceColumns . isEmpty ( ) ) { if ( throwException ) { throw new IllegalStateException ( "No source columns in job" ) ; } return false ; } if ( _analyzerJobBuilders . isEmpty ( ) ) { if ( throwException ) { throw new IllegalStateException ( "No Analyzers in job" ) ; } return false ; } for ( FilterJobBuilder < ? , ? > fjb : _filterJobBuilders ) { if ( ! fjb . isConfigured ( throwException ) ) { return false ; } } for ( TransformerJobBuilder < ? > tjb : _transformerJobBuilders ) { if ( ! tjb . isConfigured ( throwException ) ) { return false ; } } for ( AnalyzerJobBuilder < ? > ajb : _analyzerJobBuilders ) { if ( ! ajb . isConfigured ( throwException ) ) { return false ; } } return true ; }
Used to verify whether or not the builder s configuration is valid and all properties are satisfied .
276
18
142,573
private void delete ( File file ) { if ( file . isDirectory ( ) ) { File [ ] children = file . listFiles ( ) ; for ( File child : children ) { delete ( child ) ; } } if ( ! file . delete ( ) ) { if ( ! file . isDirectory ( ) ) { logger . warn ( "Unable to clean/delete file: {}" , file ) ; } else { logger . debug ( "Unable to clean/delete directory: {}" , file ) ; } } }
Recursively deletes a directory and all it s files
110
12
142,574
public static < E > List < E > refineCandidates ( final List < E > candidates , final Predicate < ? super E > predicate ) { if ( candidates . size ( ) == 1 ) { return candidates ; } List < E > newCandidates = CollectionUtils . filter ( candidates , predicate ) ; if ( newCandidates . isEmpty ( ) ) { return candidates ; } return newCandidates ; }
Refines a list of candidate objects based on a inclusion predicate . If no candidates are found the original list will be retained in the result . Therefore the result will always have 1 or more elements in it .
87
41
142,575
public static < K , V > Cache < K , V > createCache ( int maximumSize , long expiryDurationSeconds ) { Cache < K , V > cache = CacheBuilder . newBuilder ( ) . maximumSize ( maximumSize ) . expireAfterAccess ( expiryDurationSeconds , TimeUnit . SECONDS ) . build ( ) ; return cache ; }
Creates a typical Google Guava cache
77
8
142,576
@ Deprecated public void close ( ComponentDescriptor < ? > descriptor , Object component ) { close ( descriptor , component , true ) ; }
Closes a component after user .
30
7
142,577
public void closeReferenceData ( ) { if ( _referenceDataActivationManager == null ) { return ; } final Collection < Object > referenceData = _referenceDataActivationManager . getAllReferenceData ( ) ; for ( Object object : referenceData ) { ComponentDescriptor < ? extends Object > descriptor = Descriptors . ofComponent ( object . getClass ( ) ) ; close ( descriptor , object , true ) ; } }
Closes all reference data used in this life cycle helper
91
11
142,578
public void initializeReferenceData ( ) { if ( _referenceDataActivationManager == null ) { return ; } final Collection < Object > referenceDataCollection = _referenceDataActivationManager . getAllReferenceData ( ) ; for ( Object referenceData : referenceDataCollection ) { ComponentDescriptor < ? extends Object > descriptor = Descriptors . ofComponent ( referenceData . getClass ( ) ) ; assignProvidedProperties ( descriptor , referenceData ) ; initialize ( descriptor , referenceData ) ; } }
Initializes all reference data used in this life cycle helper
106
11
142,579
@ NotNull public final String toDebugString ( ) { return new ToStringBuilder ( this ) . append ( "fromEventNumber" , fromEventNumber ) . append ( "nextEventNumber" , nextEventNumber ) . append ( "endOfStream" , endOfStream ) . append ( "events" , events ) . toString ( ) ; }
Returns a debug string representation with all data .
75
9
142,580
public static String getString ( String key , String valueIfNull ) { String value = System . getProperty ( key ) ; if ( Strings . isNullOrEmpty ( value ) ) { return valueIfNull ; } return value ; }
Gets a system property string or a replacement value if the property is null or blank .
50
18
142,581
public static long getLong ( String key , long valueIfNullOrNotParseable ) { String value = System . getProperty ( key ) ; if ( Strings . isNullOrEmpty ( value ) ) { return valueIfNullOrNotParseable ; } try { return Long . parseLong ( value ) ; } catch ( NumberFormatException e ) { return valueIfNullOrNotParseable ; } }
Gets a system property long or a replacement value if the property is null or blank or not parseable
88
21
142,582
public static long getInt ( String key , int valueIfNullOrNotParseable ) { String value = System . getProperty ( key ) ; if ( Strings . isNullOrEmpty ( value ) ) { return valueIfNullOrNotParseable ; } try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException e ) { return valueIfNullOrNotParseable ; } }
Gets a system property int or a replacement value if the property is null or blank or not parseable
88
21
142,583
public static boolean getBoolean ( String key , boolean valueIfNull ) { String value = System . getProperty ( key ) ; if ( Strings . isNullOrEmpty ( value ) ) { return valueIfNull ; } value = value . trim ( ) . toLowerCase ( ) ; if ( "true" . equals ( value ) ) { return true ; } else if ( "false" . equals ( value ) ) { return false ; } return valueIfNull ; }
Gets a system property boolean or a replacement value if the property is null or blank or not parseable as a boolean .
100
25
142,584
private void restoreData ( ) { Map < String , ? > map = preferenceUtils . getAll ( ) ; Set < String > strings = map . keySet ( ) ; for ( String string : strings ) { if ( string . startsWith ( SharedPreferenceUtils . keyTestMode ) ) { preferenceUtils . restoreKey ( string ) ; } } refreshKeyValues ( ) ; }
Restore values of original keys stored .
83
8
142,585
private ArrayList < Pair < String , ? > > getKeyValues ( ) { ArrayList < Pair < String , ? > > keyValPair = new ArrayList <> ( ) ; Map < String , ? > map = preferenceUtils . getAll ( ) ; Set < String > strings = map . keySet ( ) ; Object value ; for ( String key : strings ) { if ( ! key . contains ( SharedPreferenceUtils . keyTestMode ) ) { value = map . get ( key ) ; keyValPair . add ( new Pair < String , Object > ( key , value ) ) ; } } return keyValPair ; }
Get Key value pair for given shared preference files
139
9
142,586
private void storeOriginal ( Pair < String , Object > keyValue ) { String key = SharedPreferenceUtils . keyTestMode + keyValue . first ; if ( ! preferenceUtils . isValueExistForKey ( key ) ) { preferenceUtils . put ( key , keyValue . second ) ; } }
Store original value before it s changed in test mode . It will take care not to over write if original value is already stored .
67
26
142,587
@ NotNull public final EnhancedMimeType getDataContentType ( ) { if ( dataContentType == null ) { dataContentType = EnhancedMimeType . create ( dataContentTypeStr ) ; } return dataContentType ; }
Returns the type of the data .
49
7
142,588
@ Nullable public final EnhancedMimeType getMetaContentType ( ) { if ( ( metaContentType == null ) && ( metaContentTypeStr != null ) ) { metaContentType = EnhancedMimeType . create ( metaContentTypeStr ) ; } return metaContentType ; }
Returns the type of the meta data if meta data is available .
60
13
142,589
public JsonObject toJson ( ) { final JsonObjectBuilder builder = Json . createObjectBuilder ( ) ; builder . add ( EL_DATA_TYPE , dataType ) ; builder . add ( EL_DATA_CONTENT_TYPE , dataContentTypeStr ) ; if ( meta == null ) { return builder . build ( ) ; } builder . add ( EL_META_TYPE , metaType ) ; builder . add ( EL_META_CONTENT_TYPE , metaContentTypeStr ) ; if ( meta instanceof JsonObject ) { final JsonObject jo = ( JsonObject ) meta ; return builder . add ( metaType , jo ) . build ( ) ; } if ( meta instanceof ToJsonCapable ) { final ToJsonCapable tjc = ( ToJsonCapable ) meta ; return builder . add ( metaType , tjc . toJson ( ) ) . build ( ) ; } if ( meta instanceof Base64Data ) { final Base64Data base64data = ( Base64Data ) meta ; return builder . add ( metaType , base64data . getEncoded ( ) ) . build ( ) ; } throw new IllegalStateException ( "Unknown meta object type: " + meta . getClass ( ) ) ; }
Converts the object into a JSON object .
273
9
142,590
public JsonElement callRC ( LsApiBody body ) throws LimesurveyRCException { try ( CloseableHttpClient client = HttpClientBuilder . create ( ) . build ( ) ) { HttpPost post = new HttpPost ( url ) ; post . setHeader ( "Content-type" , "application/json" ) ; String jsonBody = gson . toJson ( body ) ; LOGGER . debug ( "API CALL JSON => " + jsonBody ) ; post . setEntity ( new StringEntity ( jsonBody ) ) ; HttpResponse response = client . execute ( post ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == 200 ) { String jsonResult = EntityUtils . toString ( response . getEntity ( ) ) ; LOGGER . debug ( "API RESPONSE JSON => " + jsonResult ) ; JsonElement result = new JsonParser ( ) . parse ( jsonResult ) . getAsJsonObject ( ) . get ( "result" ) ; if ( result . isJsonObject ( ) && result . getAsJsonObject ( ) . has ( "status" ) ) { throw new LimesurveyRCException ( "Error from API : " + result . getAsJsonObject ( ) . get ( "status" ) . getAsString ( ) ) ; } return result ; } else { throw new LimesurveyRCException ( "Expecting status code 200, got " + response . getStatusLine ( ) . getStatusCode ( ) + " instead" ) ; } } catch ( IOException e ) { throw new LimesurveyRCException ( "Exception while calling API : " + e . getMessage ( ) , e ) ; } }
Call Limesurvey Remote Control .
372
8
142,591
public int createIncompleteResponse ( int surveyId , String token ) throws LimesurveyRCException { LsApiBody . LsApiParams params = getParamsWithKey ( surveyId ) ; HashMap < String , String > responseData = new HashMap <> ( ) ; responseData . put ( "submitdate" , "" ) ; String date = ZonedDateTime . now ( ) . format ( DateTimeFormatter . ISO_LOCAL_DATE ) + " " + ZonedDateTime . now ( ) . format ( DateTimeFormatter . ISO_LOCAL_TIME ) ; responseData . put ( "startdate" , date ) ; responseData . put ( "datestamp" , date ) ; if ( StringUtils . isNotEmpty ( token ) ) { responseData . put ( "token" , token ) ; } params . setResponseData ( responseData ) ; return callRC ( new LsApiBody ( "add_response" , params ) ) . getAsInt ( ) ; }
Create an incomplete response its field completed is set to N and the response doesn t have a submitdate .
223
21
142,592
public boolean completeResponse ( int surveyId , int responseId , LocalDateTime date ) throws LimesurveyRCException { Map < String , String > responseData = new HashMap <> ( ) ; responseData . put ( "submitdate" , date . format ( DateTimeFormatter . ISO_LOCAL_DATE ) + " " + date . format ( DateTimeFormatter . ISO_LOCAL_TIME ) ) ; JsonElement result = updateResponse ( surveyId , responseId , responseData ) ; if ( ! result . getAsBoolean ( ) ) { throw new LimesurveyRCException ( result . getAsString ( ) ) ; } return true ; }
Complete a response .
146
4
142,593
public JsonElement updateResponse ( int surveyId , int responseId , Map < String , String > responseData ) throws LimesurveyRCException { LsApiBody . LsApiParams params = getParamsWithKey ( surveyId ) ; responseData . put ( "id" , String . valueOf ( responseId ) ) ; params . setResponseData ( responseData ) ; return callRC ( new LsApiBody ( "update_response" , params ) ) ; }
Update a response .
107
4
142,594
public Stream < LsQuestion > getQuestions ( int surveyId ) throws LimesurveyRCException { return getGroups ( surveyId ) . flatMap ( group -> { try { return getQuestionsFromGroup ( surveyId , group . getId ( ) ) ; } catch ( LimesurveyRCException e ) { LOGGER . error ( "Unable to get questions from group " + group . getId ( ) , e ) ; } return Stream . empty ( ) ; } ) ; }
Gets questions from a survey . The questions are ordered using the group_order field from the groups and then the question_order field from the questions
105
30
142,595
public LsQuestion getQuestion ( int surveyId , int questionId ) throws LimesurveyRCException { return getQuestions ( surveyId ) . filter ( question -> question . getId ( ) == questionId ) . findFirst ( ) . orElseThrow ( ( ) -> new LimesurveyRCException ( "No question found for id " + questionId + " in survey " + surveyId ) ) ; }
Gets question from a survey .
88
7
142,596
public Map < String , LsQuestionAnswer > getQuestionAnswers ( int questionId ) throws LimesurveyRCException { LsApiBody . LsApiParams params = getParamsWithKey ( ) ; params . setQuestionId ( questionId ) ; List < String > questionSettings = new ArrayList <> ( ) ; questionSettings . add ( "answeroptions" ) ; params . setQuestionSettings ( questionSettings ) ; JsonElement result = callRC ( new LsApiBody ( "get_question_properties" , params ) ) . getAsJsonObject ( ) . get ( "answeroptions" ) ; return gson . fromJson ( result , new TypeToken < Map < String , LsQuestionAnswer > > ( ) { } . getType ( ) ) ; }
Gets possible answers from a question .
174
8
142,597
public Stream < LsQuestionGroup > getGroups ( int surveyId ) throws LimesurveyRCException { JsonElement result = callRC ( new LsApiBody ( "list_groups" , getParamsWithKey ( surveyId ) ) ) ; List < LsQuestionGroup > questionGroups = gson . fromJson ( result , new TypeToken < List < LsQuestionGroup > > ( ) { } . getType ( ) ) ; return questionGroups . stream ( ) . sorted ( Comparator . comparing ( LsQuestionGroup :: getOrder ) ) ; }
Gets groups from a survey . The groups are ordered using the group_order field .
127
18
142,598
public Stream < LsQuestion > getQuestionsFromGroup ( int surveyId , int groupId ) throws LimesurveyRCException { LsApiBody . LsApiParams params = getParamsWithKey ( surveyId ) ; params . setGroupId ( groupId ) ; JsonElement result = callRC ( new LsApiBody ( "list_questions" , params ) ) ; List < LsQuestion > questions = gson . fromJson ( result , new TypeToken < List < LsQuestion > > ( ) { } . getType ( ) ) ; return questions . stream ( ) . sorted ( Comparator . comparing ( LsQuestion :: getOrder ) ) ; }
Gets questions from a group . The questions are ordered using the question_order field .
151
18
142,599
public boolean isSurveyActive ( int surveyId ) throws LimesurveyRCException { LsApiBody . LsApiParams params = getParamsWithKey ( surveyId ) ; List < String > surveySettings = new ArrayList <> ( ) ; surveySettings . add ( "active" ) ; params . setSurveySettings ( surveySettings ) ; return "Y" . equals ( callRC ( new LsApiBody ( "get_survey_properties" , params ) ) . getAsJsonObject ( ) . get ( "active" ) . getAsString ( ) ) ; }
Check if a survey is active .
132
7