idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
39,600
public Map < SNode , Long > getMarkedAndCovered ( ) { if ( cachedMarkedAndCoveredNodes == null ) { if ( document != null ) { cachedMarkedAndCoveredNodes = CommonHelper . createSNodeMapFromIDs ( markedAndCovered , document . getDocumentGraph ( ) ) ; } } return cachedMarkedAndCoveredNodes ; }
This map is used for calculating the colors of a matching node .
39,601
private List < Long > calculateOrderedMatchNumbersGlobally ( int [ ] [ ] adjacencyMatrix , boolean matrixIsFilled , Set < Long > singleMatches ) { List < Long > orderedMatchNumbers = new ArrayList < Long > ( ) ; if ( matrixIsFilled ) { int first = - 1 ; int second = - 1 ; outerFor : for ( int i = 0 ; i < adjacencyMatrix [ 0 ] . length ; i ++ ) { for ( int j = 0 ; j < adjacencyMatrix . length ; j ++ ) { if ( adjacencyMatrix [ j ] [ i ] == 1 ) { if ( adjacencyMatrix [ i ] [ j ] != 1 ) { first = j + 1 ; second = i + 1 ; if ( orderedMatchNumbers . contains ( ( long ) first ) ) { if ( ! orderedMatchNumbers . contains ( ( long ) second ) ) { orderedMatchNumbers . add ( ( long ) second ) ; } } else { if ( orderedMatchNumbers . contains ( ( long ) second ) ) { int index = orderedMatchNumbers . indexOf ( ( long ) second ) ; orderedMatchNumbers . add ( index , ( long ) first ) ; } else { orderedMatchNumbers . add ( ( long ) first ) ; orderedMatchNumbers . add ( ( long ) second ) ; } } } else { dataIsAlignable = false ; break outerFor ; } } } } if ( dataIsAlignable ) { for ( Long match : singleMatches ) { if ( ! orderedMatchNumbers . contains ( match ) ) { boolean matchIsMerged = false ; Iterator < Long > it = orderedMatchNumbers . iterator ( ) ; while ( it . hasNext ( ) ) { Long next = it . next ( ) ; if ( next > match ) { int index = orderedMatchNumbers . indexOf ( next ) ; orderedMatchNumbers . add ( index , match ) ; matchIsMerged = true ; break ; } } if ( ! matchIsMerged ) { orderedMatchNumbers . add ( match ) ; } } } } } else { for ( Long match : singleMatches ) { orderedMatchNumbers . add ( match ) ; } Collections . sort ( orderedMatchNumbers ) ; } if ( dataIsAlignable ) { return orderedMatchNumbers ; } else return new ArrayList < Long > ( ) ; }
This method determine a valid order of match numbers and returns them as a list . If the underlying result set is not alignable it returns an empty list .
39,602
public static < T > void runWithCallback ( Callable < T > job , final FutureCallback < T > callback ) { final UI ui = UI . getCurrent ( ) ; ListeningExecutorService exec = MoreExecutors . listeningDecorator ( Executors . newSingleThreadExecutor ( ) ) ; ListenableFuture < T > future = exec . submit ( job ) ; if ( callback != null ) { Futures . addCallback ( future , new FutureCallback < T > ( ) { public void onSuccess ( final T result ) { ui . access ( new Runnable ( ) { public void run ( ) { callback . onSuccess ( result ) ; } } ) ; } public void onFailure ( final Throwable t ) { ui . access ( new Runnable ( ) { public void run ( ) { callback . onFailure ( t ) ; } } ) ; } } ) ; } }
Execute the job in the background and provide a callback which is called when the job is finished .
39,603
public void delExampleQueries ( List < String > corpusNames ) { if ( corpusNames == null || corpusNames . isEmpty ( ) ) { log . info ( "delete all example queries" ) ; jdbcTemplate . execute ( "TRUNCATE example_queries" ) ; } else { List < Long > ids = queryDao . mapCorpusNamesToIds ( corpusNames ) ; for ( Long id : ids ) { delExampleQueries ( id ) ; } } }
Deletes all example queries for a given corpus list .
39,604
public void generateQueries ( Boolean overwrite ) { List < AnnisCorpus > corpora = queryDao . listCorpora ( ) ; for ( AnnisCorpus annisCorpus : corpora ) { generateQueries ( annisCorpus . getId ( ) , overwrite ) ; } }
Generates example queries for all imported corpora .
39,605
private URI buildSaltId ( List < String > path , String saltID ) { StringBuilder sb = new StringBuilder ( "salt:/" ) ; Iterator < String > itPath = path . iterator ( ) ; while ( itPath . hasNext ( ) ) { String dir = itPath . next ( ) ; sb . append ( pathEscaper . escape ( dir ) ) ; if ( itPath . hasNext ( ) ) { sb . append ( "/" ) ; } } sb . append ( "#" ) . append ( fragmentEscaper . escape ( saltID ) ) ; URI result ; try { result = new URI ( sb . toString ( ) ) ; return result ; } catch ( URISyntaxException ex ) { log . error ( "Could not generate valid ID from path " + path . toString ( ) + " and node name " + saltID , ex ) ; } return null ; }
Builds a proper salt ID .
39,606
public static String getVersion ( ) { String rev = getBuildRevision ( ) ; Date date = getBuildDate ( ) ; StringBuilder result = new StringBuilder ( ) ; result . append ( getReleaseName ( ) ) ; if ( ! "" . equals ( rev ) || date != null ) { result . append ( " (" ) ; boolean added = false ; if ( ! "" . equals ( rev ) ) { result . append ( "rev. " ) ; result . append ( rev ) ; added = true ; } if ( date != null ) { result . append ( added ? ", built " : "" ) ; SimpleDateFormat d = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ; result . append ( d . format ( date ) ) ; } result . append ( ")" ) ; } return result . toString ( ) ; }
Get a humand readable summary of the version of this build .
39,607
public static Date getBuildDate ( ) { Date result = null ; try { DateFormat format = new SimpleDateFormat ( "yyyy-MM-dd_HH-mm-ss" ) ; String raw = versionProperties . getProperty ( "build_date" ) ; if ( raw != null ) { result = format . parse ( raw ) ; } } catch ( ParseException ex ) { log . debug ( null , ex ) ; } return result ; }
Get the date when ANNIS was built .
39,608
private String mergeConfigValue ( String key , Set < String > corpora , CorpusConfigMap corpusConfigurations ) { Set < String > values = new TreeSet < > ( ) ; for ( String corpus : corpora ) { CorpusConfig config = corpusConfigurations . get ( corpus ) ; if ( config != null ) { String v = config . getConfig ( key ) ; if ( v != null ) { values . add ( v ) ; } } } if ( values . size ( ) > 1 || values . isEmpty ( ) ) { CorpusConfig defaultConfig = corpusConfigurations . get ( DEFAULT_CONFIG ) ; if ( defaultConfig != null && defaultConfig . containsKey ( key ) ) { return defaultConfig . getConfig ( key ) ; } } if ( ! values . isEmpty ( ) ) { return values . iterator ( ) . next ( ) ; } return null ; }
If all values of a specific corpus property have the same value this value is returned otherwise the value of the default configuration is choosen .
39,609
private CorpusConfig mergeConfigs ( Set < String > corpora , CorpusConfigMap corpusConfigurations ) { CorpusConfig corpusConfig = new CorpusConfig ( ) ; String leftCtx = mergeConfigValue ( KEY_MAX_CONTEXT_LEFT , corpora , corpusConfigurations ) ; String rightCtx = mergeConfigValue ( KEY_MAX_CONTEXT_RIGHT , corpora , corpusConfigurations ) ; corpusConfig . setConfig ( KEY_MAX_CONTEXT_LEFT , leftCtx ) ; corpusConfig . setConfig ( KEY_MAX_CONTEXT_RIGHT , rightCtx ) ; corpusConfig . setConfig ( KEY_CONTEXT_STEPS , mergeConfigValue ( KEY_CONTEXT_STEPS , corpora , corpusConfigurations ) ) ; corpusConfig . setConfig ( KEY_DEFAULT_CONTEXT , mergeConfigValue ( KEY_DEFAULT_CONTEXT , corpora , corpusConfigurations ) ) ; corpusConfig . setConfig ( KEY_RESULT_PER_PAGE , mergeConfigValue ( KEY_RESULT_PER_PAGE , corpora , corpusConfigurations ) ) ; corpusConfig . setConfig ( KEY_DEFAULT_CONTEXT_SEGMENTATION , checkSegments ( KEY_DEFAULT_CONTEXT_SEGMENTATION , corpora , corpusConfigurations ) ) ; corpusConfig . setConfig ( KEY_DEFAULT_BASE_TEXT_SEGMENTATION , checkSegments ( KEY_DEFAULT_BASE_TEXT_SEGMENTATION , corpora , corpusConfigurations ) ) ; return corpusConfig ; }
Builds a single config for selection of one or muliple corpora .
39,610
private String checkSegments ( String key , Set < String > corpora , CorpusConfigMap corpusConfigurations ) { String segmentation = null ; for ( String corpus : corpora ) { CorpusConfig c = null ; if ( corpusConfigurations . containsConfig ( corpus ) ) { c = corpusConfigurations . get ( corpus ) ; } else { c = corpusConfigurations . get ( DEFAULT_CONFIG ) ; } if ( c == null ) { continue ; } String tmpSegment = c . getConfig ( key ) ; if ( tmpSegment == null ) { return corpusConfigurations . get ( DEFAULT_CONFIG ) . getConfig ( key ) ; } if ( segmentation == null ) { segmentation = tmpSegment ; continue ; } if ( ! segmentation . equals ( tmpSegment ) ) { return corpusConfigurations . get ( DEFAULT_CONFIG ) . getConfig ( key ) ; } } if ( segmentation == null ) { return corpusConfigurations . get ( DEFAULT_CONFIG ) . getConfig ( key ) ; } else { return segmentation ; } }
Checks if all selected corpora have the same default segmentation layer . If not the tok layer is taken because every corpus has this one .
39,611
private void updateContext ( Container c , int maxCtx , int ctxSteps , boolean keepCustomValues ) { if ( ! keepCustomValues ) { c . removeAllItems ( ) ; } for ( Integer i : PREDEFINED_CONTEXTS ) { if ( i < maxCtx ) { c . addItem ( i ) ; } } for ( int step = ctxSteps ; step < maxCtx ; step += ctxSteps ) { c . addItem ( step ) ; } c . addItem ( maxCtx ) ; }
Updates context combo boxes .
39,612
@ Path ( "userconfig" ) @ Produces ( "application/xml" ) public UserConfig getUserConfig ( ) { Subject user = SecurityUtils . getSubject ( ) ; user . checkPermission ( "admin:read:userconfig" ) ; return adminDao . retrieveUserConfig ( ( String ) user . getPrincipal ( ) ) ; }
Get the user configuration for the currently logged in user .
39,613
@ Path ( "userconfig" ) @ Consumes ( "application/xml" ) public Response setUserConfig ( JAXBElement < UserConfig > config ) { Subject user = SecurityUtils . getSubject ( ) ; user . checkPermission ( "admin:write:userconfig" ) ; String userName = ( String ) user . getPrincipal ( ) ; adminDao . storeUserConfig ( userName , config . getValue ( ) ) ; return Response . ok ( ) . build ( ) ; }
Sets the user configuration for the currently logged in user .
39,614
public void setConfig ( String configName , String configValue ) { if ( config == null ) { config = new Properties ( ) ; } if ( configValue == null ) { config . remove ( configName ) ; } else { config . setProperty ( configName , configValue ) ; } }
Add a new configuration . If the config name already exists the config value is overwritten .
39,615
public static List < ContentRange > parseFromHeader ( String rawRange , long totalSize , int maxNum ) throws InvalidRangeException { List < ContentRange > result = new ArrayList < > ( ) ; if ( rawRange != null ) { if ( ! fullPattern . matcher ( rawRange ) . matches ( ) ) { throw new InvalidRangeException ( "invalid syntax" ) ; } rawRange = rawRange . substring ( "bytes=" . length ( ) , rawRange . length ( ) ) ; for ( String partRange : Splitter . on ( "," ) . omitEmptyStrings ( ) . trimResults ( ) . split ( rawRange ) ) { if ( result . size ( ) >= totalSize ) { throw new InvalidRangeException ( "more ranges than acceptable" ) ; } long from = 0 ; long to = totalSize - 1 ; Matcher m = partPattern . matcher ( partRange ) ; if ( ! m . find ( ) ) { throw new InvalidRangeException ( "invalid syntax for partial range" ) ; } String fromString = m . group ( 1 ) ; String toString = m . group ( 2 ) ; if ( fromString != null && ! fromString . isEmpty ( ) ) { from = Long . parseLong ( fromString ) ; } if ( toString != null && ! toString . isEmpty ( ) ) { to = Long . parseLong ( toString ) ; } if ( from > to ) { throw new InvalidRangeException ( "start is larger then end" ) ; } result . add ( new ContentRange ( from , to , totalSize ) ) ; } } return result ; }
Parses the header value of a HTTP Range request
39,616
protected List < String > getMatchesWithClause ( QueryData queryData , List < QueryNode > alternative , String indent ) { String indent2 = indent + TABSTOP ; String indent3 = indent2 + TABSTOP ; StringBuilder sbRaw = new StringBuilder ( ) ; sbRaw . append ( indent ) . append ( "matchesRaw AS\n" ) ; sbRaw . append ( indent ) . append ( "(\n" ) ; sbRaw . append ( indent ) . append ( getInnerQuerySqlGenerator ( ) . toSql ( queryData , indent2 ) ) ; sbRaw . append ( "\n" ) . append ( indent ) . append ( ")" ) ; StringBuilder sbMatches = new StringBuilder ( ) ; sbMatches . append ( indent ) . append ( "matches AS\n" ) ; sbMatches . append ( indent ) . append ( "(\n" ) ; int numOfNodes = queryData . getMaxWidth ( ) ; for ( int i = 1 ; i <= numOfNodes ; i ++ ) { sbMatches . append ( indent2 ) . append ( "SELECT\n" ) ; sbMatches . append ( indent3 ) . append ( "n" ) . append ( " AS n,\n" ) ; sbMatches . append ( indent3 ) . append ( i ) . append ( " AS nodeNr,\n" ) ; sbMatches . append ( indent3 ) . append ( "id" ) . append ( i ) . append ( " AS id,\n" ) ; sbMatches . append ( indent3 ) . append ( "text" ) . append ( i ) . append ( " AS \"text\",\n" ) ; sbMatches . append ( indent3 ) . append ( "min" ) . append ( i ) . append ( " AS min,\n" ) ; sbMatches . append ( indent3 ) . append ( "max" ) . append ( i ) . append ( " AS max,\n" ) ; sbMatches . append ( indent3 ) . append ( "corpus" ) . append ( i ) . append ( " AS corpus\n" ) ; sbMatches . append ( indent2 ) . append ( "FROM matchesRaw\n" ) ; if ( i < numOfNodes ) { sbMatches . append ( indent2 ) . append ( "\n" ) . append ( indent2 ) . append ( "UNION ALL\n\n" ) ; } } sbMatches . append ( "\n" ) . append ( indent ) . append ( ")" ) ; return Lists . newArrayList ( sbRaw . toString ( ) , sbMatches . toString ( ) ) ; }
Uses the inner SQL generator and provides an ordered and limited view on the matches with a match number .
39,617
protected String getSolutionFromMatchesWithClause ( IslandsPolicy . IslandPolicies islandPolicy , String matchesName , String indent ) { String indent2 = indent + TABSTOP ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( indent ) . append ( "solutions AS\n" ) ; sb . append ( indent ) . append ( "(\n" ) ; sb . append ( indent2 ) . append ( "SELECT " ) ; if ( islandPolicy == IslandsPolicy . IslandPolicies . none ) { sb . append ( "min(keys.key) AS key, " ) . append ( matchesName ) . append ( ".n AS n, " ) . append ( matchesName ) . append ( ".text, " ) . append ( matchesName ) . append ( ".corpus, " ) ; sb . append ( "min(" ) . append ( matchesName ) . append ( ".min" ) . append ( "), " ) ; sb . append ( "max(" ) . append ( matchesName ) . append ( ".max" ) . append ( ")" ) ; } else if ( islandPolicy == IslandsPolicy . IslandPolicies . context ) { sb . append ( "keys.key AS key, " ) . append ( matchesName ) . append ( ".n AS n, " ) . append ( matchesName ) . append ( ".text, " ) . append ( matchesName ) . append ( ".corpus, " ) ; sb . append ( matchesName ) . append ( ".min, " ) ; sb . append ( matchesName ) . append ( ".max" ) ; } else { throw new UnsupportedOperationException ( "No implementation for island policy " + islandsPolicy . toString ( ) ) ; } sb . append ( "\n" ) . append ( indent2 ) ; sb . append ( "FROM " ) . append ( matchesName ) . append ( ", keys\n" ) . append ( indent2 ) ; sb . append ( "WHERE keys.n = " ) . append ( matchesName ) . append ( ".n\n" ) ; if ( islandPolicy == IslandsPolicy . IslandPolicies . none ) { sb . append ( indent2 ) . append ( "GROUP BY " ) . append ( matchesName ) . append ( ".n, " ) . append ( matchesName ) . append ( ".text, " ) . append ( matchesName ) . append ( ".corpus" ) . append ( "\n" ) ; } sb . append ( indent ) . append ( ")" ) ; return sb . toString ( ) ; }
Breaks down the matches table so that each node of each match has it s own row .
39,618
public static String toAQL ( List < QueryNode > alternative ) { List < String > fragments = new LinkedList < > ( ) ; for ( QueryNode n : alternative ) { String frag = n . toAQLNodeFragment ( ) ; if ( frag != null && ! frag . isEmpty ( ) ) { fragments . add ( frag ) ; } } for ( QueryNode n : alternative ) { String frag = n . toAQLEdgeFragment ( ) ; if ( frag != null && ! frag . isEmpty ( ) ) { fragments . add ( frag ) ; } } return Joiner . on ( " & " ) . join ( fragments ) ; }
Outputs this alternative as an equivalent AQL query .
39,619
public String toAQL ( ) { StringBuilder sb = new StringBuilder ( ) ; Iterator < List < QueryNode > > itAlternative = alternatives . iterator ( ) ; while ( itAlternative . hasNext ( ) ) { List < QueryNode > alt = itAlternative . next ( ) ; if ( alternatives . size ( ) > 1 ) { sb . append ( "(" ) ; } sb . append ( toAQL ( alt ) ) ; if ( alternatives . size ( ) > 1 ) { sb . append ( ")" ) ; if ( itAlternative . hasNext ( ) ) { sb . append ( "\n|\n" ) ; } } } return sb . toString ( ) ; }
Outputs this normalized query data as an equivalent AQL query .
39,620
public boolean writeUser ( User user ) { if ( resourcePath != null ) { lock . writeLock ( ) . lock ( ) ; try { File userDir = new File ( resourcePath , "users" ) ; if ( userDir . isDirectory ( ) ) { File userFile = new File ( userDir . getAbsolutePath ( ) , user . getName ( ) ) ; Properties props = user . toProperties ( ) ; try ( FileOutputStream out = new FileOutputStream ( userFile ) ) { props . store ( out , "" ) ; return true ; } catch ( IOException ex ) { log . error ( "Could not write users file" , ex ) ; } } } finally { lock . writeLock ( ) . unlock ( ) ; } } return false ; }
Writes the user to the disk
39,621
public boolean deleteUser ( String userName ) { if ( resourcePath != null ) { lock . writeLock ( ) . lock ( ) ; try { File userDir = new File ( resourcePath , "users" ) ; if ( userDir . isDirectory ( ) ) { File userFile = new File ( userDir . getAbsolutePath ( ) , userName ) ; return userFile . delete ( ) ; } } finally { lock . writeLock ( ) . unlock ( ) ; } } return false ; }
Deletes the user from the disk
39,622
public boolean deleteGroup ( String groupName ) { if ( groupsFile != null ) { lock . writeLock ( ) . lock ( ) ; try { reloadGroupsFromFile ( ) ; groups . remove ( groupName ) ; return writeGroupFile ( ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } } return false ; }
Deletes the group from the disk
39,623
private User getUserFromFile ( File userFile ) { if ( userFile . isFile ( ) && userFile . canRead ( ) ) { try ( FileInputStream userFileIO = new FileInputStream ( userFile ) ; ) { Properties userProps = new Properties ( ) ; userProps . load ( userFileIO ) ; return new User ( userFile . getName ( ) , userProps ) ; } catch ( IOException ex ) { log . error ( null , ex ) ; } } return null ; }
Internal helper function to parse a user file . It assumes the calling function already has handled the locking .
39,624
@ Transactional ( readOnly = false , propagation = Propagation . REQUIRES_NEW , isolation = Isolation . READ_COMMITTED ) public void checkAndRemoveTopLevelCorpus ( String corpusName ) { if ( existConflictingTopLevelCorpus ( corpusName ) ) { log . info ( "delete conflicting corpus: {}" , corpusName ) ; List < String > corpusNames = new LinkedList < > ( ) ; corpusNames . add ( corpusName ) ; deleteCorpora ( getQueryDao ( ) . mapCorpusNamesToIds ( corpusNames ) , false ) ; } }
Deletes a top level corpus when it is already exists .
39,625
public Properties toProperties ( ) { Properties props = new Properties ( ) ; if ( passwordHash != null ) { props . put ( "password" , passwordHash ) ; } if ( groups != null && ! groups . isEmpty ( ) ) { props . put ( "groups" , Joiner . on ( ',' ) . join ( groups ) ) ; } if ( permissions != null && ! permissions . isEmpty ( ) ) { props . put ( "permissions" , Joiner . on ( ',' ) . join ( permissions ) ) ; } if ( expires != null ) { props . put ( "expires" , ISODateTimeFormat . date ( ) . print ( expires ) ) ; } return props ; }
Constructs a represention that is equal to the content of an ANNIS user file .
39,626
public static VisualizerInput createInput ( String corpus , String docName , Visualizer config , boolean isUsingRawText , List < String > nodeAnnoFilter ) { VisualizerInput input = new VisualizerInput ( ) ; input . setMappings ( parseMappings ( config ) ) ; input . setNamespace ( config . getNamespace ( ) ) ; String encodedToplevelCorpus = urlPathEscape . escape ( corpus ) ; String encodedDocument = urlPathEscape . escape ( docName ) ; if ( isUsingRawText ) { WebResource w = Helper . getAnnisWebResource ( ) ; w = w . path ( "query" ) . path ( "rawtext" ) . path ( encodedToplevelCorpus ) . path ( encodedDocument ) ; RawTextWrapper rawTextWrapper = w . get ( RawTextWrapper . class ) ; input . setRawText ( rawTextWrapper ) ; } else { SaltProject txt = null ; WebResource res = Helper . getAnnisWebResource ( ) . path ( "query" ) . path ( "graph" ) . path ( encodedToplevelCorpus ) . path ( encodedDocument ) ; if ( nodeAnnoFilter != null ) { res = res . queryParam ( "filternodeanno" , Joiner . on ( "," ) . join ( nodeAnnoFilter ) ) ; } txt = res . get ( SaltProject . class ) ; if ( txt != null ) { SDocument sDoc = txt . getCorpusGraphs ( ) . get ( 0 ) . getDocuments ( ) . get ( 0 ) ; input . setResult ( sDoc ) ; } } return input ; }
Creates the input . It only takes the salt project or the raw text from the text table never both since the increase the performance for large texts .
39,627
private Set < SNode > getMatchedNodes ( SDocumentGraph graph ) { Set < SNode > matchedNodes = new HashSet < > ( ) ; for ( SNode node : graph . getNodes ( ) ) { if ( node . getFeature ( AnnisConstants . ANNIS_NS , AnnisConstants . FEAT_MATCHEDNODE ) != null ) matchedNodes . add ( node ) ; } return matchedNodes ; }
Takes a match and returns the matched nodes .
39,628
public void outputText ( SDocumentGraph graph , boolean alignmc , int matchNumber , Writer out ) throws IOException , IllegalArgumentException { if ( matchNumber == 0 ) { List < String > headerLine = new ArrayList < > ( ) ; for ( Map . Entry < Integer , TreeSet < String > > match : annotationsForMatchedNodes . entrySet ( ) ) { int node_id = match . getKey ( ) ; headerLine . add ( String . valueOf ( node_id ) + "_id" ) ; headerLine . add ( String . valueOf ( node_id ) + "_span" ) ; for ( String annoName : match . getValue ( ) ) { headerLine . add ( String . valueOf ( node_id ) + "_anno_" + annoName ) ; } } for ( String key : metakeys ) { headerLine . add ( "meta_" + key ) ; } out . append ( StringUtils . join ( headerLine , "\t" ) ) ; out . append ( "\n" ) ; } SortedMap < Integer , String > contentLine = new TreeMap < > ( ) ; for ( SNode node : this . getMatchedNodes ( graph ) ) { List < String > nodeLine = new ArrayList < > ( ) ; RelannisNodeFeature feats = RelannisNodeFeature . extract ( node ) ; nodeLine . add ( String . valueOf ( feats . getInternalID ( ) ) ) ; String span = graph . getText ( node ) ; if ( span != null ) nodeLine . add ( graph . getText ( node ) ) ; else nodeLine . add ( "" ) ; int node_id = node . getFeature ( AnnisConstants . ANNIS_NS , AnnisConstants . FEAT_MATCHEDNODE ) . getValue_SNUMERIC ( ) . intValue ( ) ; for ( String annoName : annotationsForMatchedNodes . get ( node_id ) ) { SAnnotation anno = node . getAnnotation ( annoName ) ; if ( anno != null ) { nodeLine . add ( anno . getValue_STEXT ( ) ) ; } else nodeLine . add ( "'NULL'" ) ; } contentLine . put ( node_id , StringUtils . join ( nodeLine , "\t" ) ) ; } out . append ( StringUtils . join ( contentLine . values ( ) , "\t" ) ) ; if ( ! metakeys . isEmpty ( ) ) { String corpus_name = CommonHelper . getCorpusPath ( java . net . URI . create ( graph . getDocument ( ) . getId ( ) ) ) . get ( 0 ) ; List < Annotation > asList = Helper . getMetaData ( corpus_name , graph . getDocument ( ) . getName ( ) ) ; for ( Annotation anno : asList ) { if ( metakeys . contains ( anno . getName ( ) ) ) out . append ( "\t" + anno . getValue ( ) ) ; } } out . append ( "\n" ) ; }
Takes a match and outputs a csv - line
39,629
private boolean handleArtificialDominanceRelation ( SDocumentGraph graph , SNode source , SNode target , SRelation rel , SLayer layer , long componentID , long pre ) { List < SRelation < SNode , SNode > > mirrorRelations = graph . getRelations ( source . getId ( ) , target . getId ( ) ) ; if ( mirrorRelations != null && mirrorRelations . size ( ) > 0 ) { for ( Relation mirror : mirrorRelations ) { if ( mirror != rel && mirror instanceof SRelation ) { SRelation mirrorRel = ( SRelation ) mirror ; Set < SLayer > mirrorLayers = mirrorRel . getLayers ( ) ; if ( mirrorLayers != null ) { for ( SLayer mirrorLayer : mirrorLayers ) { if ( mirrorLayer == layer ) { RelannisEdgeFeature mirrorFeat = RelannisEdgeFeature . extract ( mirrorRel ) ; mirrorFeat . setArtificialDominanceComponent ( componentID ) ; mirrorFeat . setArtificialDominancePre ( pre ) ; mirrorRel . removeLabel ( ANNIS_NS , FEAT_RELANNIS_EDGE ) ; mirrorRel . createFeature ( ANNIS_NS , FEAT_RELANNIS_EDGE , mirrorFeat ) ; return true ; } } } } } } return false ; }
In ANNIS there is a special combined dominance component which has an empty name but which should not directly be included in the Salt graph .
39,630
private SLayer findOrAddSLayer ( String name , SDocumentGraph graph ) { List < SLayer > layerList = graph . getLayerByName ( name ) ; SLayer layer = ( layerList != null && layerList . size ( ) > 0 ) ? layerList . get ( 0 ) : null ; if ( layer == null ) { layer = SaltFactory . createSLayer ( ) ; layer . setName ( name ) ; graph . addLayer ( layer ) ; } return layer ; }
Retrieves an existing layer by it s name or creates and adds a new one if not existing yet
39,631
public String getPageAnnoForGridEvent ( SSpan span ) { int left = getLeftIndexFromSNode ( span ) ; int right = getRightIndexFromSNode ( span ) ; if ( sspans == null ) { log . warn ( "no page annos found" ) ; return null ; } int leftIdx = - 1 ; for ( Integer i : sspans . keySet ( ) ) { if ( i <= left ) { leftIdx = i ; } } if ( leftIdx == - 1 ) { log . debug ( "no left index found" ) ; return null ; } int rightIdx = - 1 ; for ( Integer i : sspans . get ( leftIdx ) . keySet ( ) ) { if ( i >= right ) { rightIdx = i ; } } if ( rightIdx == - 1 ) { log . debug ( "no right index found" ) ; return null ; } return getPageFromAnnotation ( span ) ; }
Returns a page annotation for a span if the span is overlapped by a page annotation .
39,632
public int getLeftIndexFromSNode ( SSpan s ) { RelannisNodeFeature feat = ( RelannisNodeFeature ) s . getFeature ( SaltUtil . createQName ( ANNIS_NS , FEAT_RELANNIS_NODE ) ) . getValue ( ) ; return ( int ) feat . getLeftToken ( ) ; }
Get the most left token index of a SSpan .
39,633
public int getRightIndexFromSNode ( SSpan s ) { RelannisNodeFeature feat = ( RelannisNodeFeature ) s . getFeature ( SaltUtil . createQName ( ANNIS_NS , FEAT_RELANNIS_NODE ) ) . getValue_SOBJECT ( ) ; return ( int ) feat . getRightToken ( ) ; }
Get the most right token index of a SSpan .
39,634
private void setUpTable ( ) { setSizeFull ( ) ; table . setSizeFull ( ) ; table . setSelectable ( false ) ; table . setImmediate ( true ) ; table . addStyleName ( "example-queries-table" ) ; table . addStyleName ( ChameleonTheme . TABLE_STRIPED ) ; table . addGeneratedColumn ( COLUMN_OPEN_CORPUS_BROWSER , new ShowCorpusBrowser ( ) ) ; table . addGeneratedColumn ( COLUMN_EXAMPLE_QUERY , new QueryColumn ( ) ) ; table . addGeneratedColumn ( COLUMN_DESCRIPTION , new Table . ColumnGenerator ( ) { public Object generateCell ( Table source , Object itemId , Object columnId ) { ExampleQuery eQ = ( ExampleQuery ) itemId ; Label l = new Label ( eQ . getDescription ( ) ) ; l . setContentMode ( ContentMode . TEXT ) ; l . addStyleName ( Helper . CORPUS_FONT_FORCE ) ; return l ; } } ) ; table . setVisibleColumns ( new Object [ ] { COLUMN_EXAMPLE_QUERY , COLUMN_DESCRIPTION , COLUMN_OPEN_CORPUS_BROWSER } ) ; table . setColumnExpandRatio ( table . getVisibleColumns ( ) [ 0 ] , 0.40f ) ; table . setColumnExpandRatio ( table . getVisibleColumns ( ) [ 1 ] , 0.40f ) ; table . setColumnHeader ( table . getVisibleColumns ( ) [ 0 ] , "Example Query" ) ; table . setColumnHeader ( table . getVisibleColumns ( ) [ 1 ] , "Description" ) ; table . setColumnHeader ( table . getVisibleColumns ( ) [ 2 ] , "open corpus browser" ) ; }
Sets some layout properties .
39,635
private void addItems ( List < ExampleQuery > examples ) { if ( examples != null && examples . size ( ) > 0 ) { egContainer . addAll ( examples ) ; showTab ( ) ; } else { hideTabSheet ( ) ; } }
Add items if there are any and put the example query tab in the foreground .
39,636
private void showTab ( ) { if ( parentTab != null ) { tab = parentTab . getTab ( this ) ; if ( tab != null ) { tab . setEnabled ( true ) ; if ( ! ( parentTab . getSelectedTab ( ) instanceof ResultViewPanel ) ) { parentTab . setSelectedTab ( tab ) ; } } } }
Shows the tab and put into the foreground if no query is executed yet .
39,637
private static List < ExampleQuery > loadExamplesFromRemote ( Set < String > corpusNames ) { List < ExampleQuery > result = new LinkedList < > ( ) ; WebResource service = Helper . getAnnisWebResource ( ) ; try { if ( corpusNames == null || corpusNames . isEmpty ( ) ) { result = service . path ( "query" ) . path ( "corpora" ) . path ( "example-queries" ) . get ( new GenericType < List < ExampleQuery > > ( ) { } ) ; } else { String concatedCorpusNames = StringUtils . join ( corpusNames , "," ) ; result = service . path ( "query" ) . path ( "corpora" ) . path ( "example-queries" ) . queryParam ( "corpora" , concatedCorpusNames ) . get ( new GenericType < List < ExampleQuery > > ( ) { } ) ; } } catch ( UniformInterfaceException ex ) { } catch ( ClientHandlerException ex ) { log . error ( "problems with getting example queries from remote for {}" , corpusNames , ex ) ; } return result ; }
Loads the available example queries for a specific corpus .
39,638
public void setSelectedCorpusInBackground ( final Set < String > selectedCorpora ) { loadingIndicator . setVisible ( true ) ; table . setVisible ( false ) ; Background . run ( new ExampleFetcher ( selectedCorpora , UI . getCurrent ( ) ) ) ; }
Sets the selected corpora and causes a reload
39,639
private List < File > unzipCorpus ( File outDir , ZipFile zip ) { List < File > rootDirs = new ArrayList < > ( ) ; Enumeration < ? extends ZipEntry > zipEnum = zip . entries ( ) ; while ( zipEnum . hasMoreElements ( ) ) { ZipEntry e = zipEnum . nextElement ( ) ; File outFile = new File ( outDir , e . getName ( ) . replaceAll ( "\\/" , "/" ) ) ; if ( e . isDirectory ( ) ) { if ( ! outFile . mkdirs ( ) ) { log . warn ( "Could not create output directory " + outFile . getAbsolutePath ( ) ) ; } } else { if ( "corpus.tab" . equals ( outFile . getName ( ) ) || "corpus.annis" . equals ( outFile . getName ( ) ) ) { rootDirs . add ( outFile . getParentFile ( ) ) ; } if ( ! outFile . getParentFile ( ) . isDirectory ( ) ) { if ( ! outFile . getParentFile ( ) . mkdirs ( ) ) { { log . warn ( "Could not create output directory for file " + outFile . getAbsolutePath ( ) ) ; } } } try ( FileOutputStream outStream = new FileOutputStream ( outFile ) ; ) { ByteStreams . copy ( zip . getInputStream ( e ) , outStream ) ; } catch ( FileNotFoundException ex ) { log . error ( null , ex ) ; } catch ( IOException ex ) { log . error ( null , ex ) ; } } } return rootDirs ; }
Extract the zipped ANNIS corpus files to an output directory .
39,640
public ImportStatus importCorporaSave ( boolean overwrite , String aliasName , String statusEmailAdress , boolean waitForOtherTasks , String ... paths ) { return importCorporaSave ( overwrite , aliasName , statusEmailAdress , waitForOtherTasks , Arrays . asList ( paths ) ) ; }
Imports several corpora .
39,641
private Long markCoveredTokens ( Map < SNode , Long > markedAndCovered , SNode tok ) { RelannisNodeFeature f = RelannisNodeFeature . extract ( tok ) ; if ( markedAndCovered . containsKey ( tok ) && f != null && f . getMatchedNode ( ) == null ) { return markedAndCovered . get ( tok ) ; } return f != null ? f . getMatchedNode ( ) : null ; }
Checks if a token is covered by a matched node but not a match by it self .
39,642
private Long tokenMatch ( SNode tok ) { SFeature featMatched = tok . getFeature ( ANNIS_NS , FEAT_MATCHEDNODE ) ; Long matchRaw = featMatched == null ? null : featMatched . getValue_SNUMERIC ( ) ; return matchRaw ; }
Checks if a token is a marked match
39,643
public String getBuildDescription ( ) { StringBuilder sb = new StringBuilder ( ) ; for ( String name : startParameter . getExcludedTaskNames ( ) ) { sb . append ( "-x " ) ; sb . append ( name ) ; sb . append ( " " ) ; } for ( String name : startParameter . getTaskNames ( ) ) { sb . append ( name ) ; sb . append ( " " ) ; } String tasks = sb . toString ( ) ; if ( tasks . length ( ) == 0 ) { tasks = "(no tasks specified)" ; } return "Profiled build: " + tasks ; }
Get a description of this profiled build . It contains info about tasks passed to gradle as targets from the command line .
39,644
public ProjectMetrics getProjectProfile ( String projectPath ) { ProjectMetrics result = projects . get ( projectPath ) ; if ( result == null ) { result = new ProjectMetrics ( projectPath ) ; projects . put ( projectPath , result ) ; } return result ; }
Get the profiling container for the specified project
39,645
public long getElapsedArtifactTransformTime ( ) { long result = 0 ; for ( FragmentedOperation transform : transforms . values ( ) ) { result += transform . getElapsedTime ( ) ; } return result ; }
Get the total artifact transformation time .
39,646
public long getElapsedTotalExecutionTime ( ) { long result = 0 ; for ( ProjectMetrics projectMetrics : projects . values ( ) ) { result += projectMetrics . getElapsedTime ( ) ; } return result ; }
Get the total task execution time from all projects .
39,647
private void shutdownIfComplete ( ) { if ( ! buildProfileComplete . get ( ) || ! buildResultComplete . get ( ) ) { return ; } MetricsDispatcher dispatcher = this . dispatcherSupplier . get ( ) ; logger . info ( "Shutting down dispatcher" ) ; try { dispatcher . stopAsync ( ) . awaitTerminated ( TIMEOUT_MS , TimeUnit . MILLISECONDS ) ; } catch ( TimeoutException e ) { logger . debug ( "Timed out after {}ms while waiting for metrics dispatcher to terminate" , TIMEOUT_MS ) ; } catch ( IllegalStateException e ) { logger . debug ( "Could not stop metrics dispatcher service (error message: {})" , getRootCauseMessage ( e ) ) ; } Optional < String > receipt = dispatcher . receipt ( ) ; if ( receipt . isPresent ( ) ) { logger . warn ( receipt . get ( ) ) ; } }
Conditionally shutdown the dispatcher because Gradle listener event order appears to be non - deterministic .
39,648
public TaskExecution getTaskProfile ( String taskPath ) { TaskExecution result = tasks . get ( taskPath ) ; if ( result == null ) { result = new TaskExecution ( taskPath ) ; tasks . put ( taskPath , result ) ; } return result ; }
Gets the task profiling container for the specified task .
39,649
public CompositeOperation < TaskExecution > getTasks ( ) { List < TaskExecution > taskExecutions = CollectionUtils . sort ( tasks . values ( ) , slowestFirst ( ) ) ; return new CompositeOperation < TaskExecution > ( taskExecutions ) ; }
Returns the task executions for this project .
39,650
public void close ( ) throws IOException { final List < IOException > exceptionList = new ArrayList < > ( ) ; for ( final Node node : nodeList ) { try { node . close ( ) ; } catch ( final IOException e ) { exceptionList . add ( e ) ; } } if ( exceptionList . isEmpty ( ) ) { print ( "Closed all nodes." ) ; } else { if ( useLogger && logger . isDebugEnabled ( ) ) { for ( final Exception e : exceptionList ) { logger . debug ( "Failed to close a node." , e ) ; } } throw new IOException ( exceptionList . toString ( ) ) ; } }
Close a cluster runner .
39,651
public void clean ( ) { final Path bPath = FileSystems . getDefault ( ) . getPath ( basePath ) ; for ( int i = 0 ; i < 3 ; i ++ ) { try { final CleanUpFileVisitor visitor = new CleanUpFileVisitor ( ) ; Files . walkFileTree ( bPath , visitor ) ; if ( ! visitor . hasErrors ( ) ) { print ( "Deleted " + basePath ) ; return ; } else if ( useLogger && logger . isDebugEnabled ( ) ) { for ( final Throwable t : visitor . getErrors ( ) ) { logger . debug ( "Could not delete files/directories." , t ) ; } } } catch ( final Exception e ) { print ( e . getMessage ( ) + " Retring to delete it." ) ; try { Thread . sleep ( 1000 ) ; } catch ( final InterruptedException ignore ) { } } } print ( "Failed to delete " + basePath + " in this process." ) ; }
Delete all configuration files and directories .
39,652
public void build ( final String ... args ) { if ( args != null ) { final CmdLineParser parser = new CmdLineParser ( this , ParserProperties . defaults ( ) . withUsageWidth ( 80 ) ) ; try { parser . parseArgument ( args ) ; } catch ( final CmdLineException e ) { throw new ClusterRunnerException ( "Failed to parse args: " + Strings . arrayToDelimitedString ( args , " " ) ) ; } } if ( basePath == null ) { try { basePath = Files . createTempDirectory ( "es-cluster" ) . toAbsolutePath ( ) . toString ( ) ; } catch ( final IOException e ) { throw new ClusterRunnerException ( "Could not create $ES_HOME." , e ) ; } } final Path esBasePath = Paths . get ( basePath ) ; createDir ( esBasePath ) ; final String [ ] types = moduleTypes == null ? MODULE_TYPES : moduleTypes . split ( "," ) ; for ( final String moduleType : types ) { Class < ? extends Plugin > clazz ; try { clazz = Class . forName ( moduleType ) . asSubclass ( Plugin . class ) ; pluginList . add ( clazz ) ; } catch ( final ClassNotFoundException e ) { logger . debug ( moduleType + " is not found." , e ) ; } } if ( pluginTypes != null ) { for ( final String value : pluginTypes . split ( "," ) ) { final String pluginType = value . trim ( ) ; if ( pluginType . length ( ) > 0 ) { Class < ? extends Plugin > clazz ; try { clazz = Class . forName ( pluginType ) . asSubclass ( Plugin . class ) ; pluginList . add ( clazz ) ; } catch ( final ClassNotFoundException e ) { throw new ClusterRunnerException ( pluginType + " is not found." , e ) ; } } } } print ( "Cluster Name: " + clusterName ) ; print ( "Base Path: " + basePath ) ; print ( "Num Of Node: " + numOfNode ) ; for ( int i = 0 ; i < numOfNode ; i ++ ) { execute ( i + 1 ) ; } }
Create and start Elasticsearch cluster with arguments .
39,653
public Node getNode ( final int i ) { if ( i < 0 || i >= nodeList . size ( ) ) { return null ; } return nodeList . get ( i ) ; }
Return a node by the node index .
39,654
@ SuppressWarnings ( "resource" ) public boolean startNode ( final int i ) { if ( i >= nodeList . size ( ) ) { return false ; } if ( ! nodeList . get ( i ) . isClosed ( ) ) { return false ; } final Node node = new ClusterRunnerNode ( envList . get ( i ) , pluginList ) ; try { node . start ( ) ; nodeList . set ( i , node ) ; return true ; } catch ( final NodeValidationException e ) { print ( e . getLocalizedMessage ( ) ) ; } return false ; }
Start a closed node .
39,655
public Node getNode ( final String name ) { if ( name == null ) { return null ; } for ( final Node node : nodeList ) { if ( name . equals ( node . settings ( ) . get ( NODE_NAME ) ) ) { return node ; } } return null ; }
Return a node by the name .
39,656
public int getNodeIndex ( final Node node ) { for ( int i = 0 ; i < nodeList . size ( ) ; i ++ ) { if ( nodeList . get ( i ) . equals ( node ) ) { return i ; } } return - 1 ; }
Return a node index .
39,657
public synchronized Node masterNode ( ) { final ClusterState state = client ( ) . admin ( ) . cluster ( ) . prepareState ( ) . execute ( ) . actionGet ( ) . getState ( ) ; final String name = state . nodes ( ) . getMasterNode ( ) . getName ( ) ; return getNode ( name ) ; }
Return a master node .
39,658
public synchronized Node nonMasterNode ( ) { final ClusterState state = client ( ) . admin ( ) . cluster ( ) . prepareState ( ) . execute ( ) . actionGet ( ) . getState ( ) ; final String name = state . nodes ( ) . getMasterNode ( ) . getName ( ) ; for ( final Node node : nodeList ) { if ( ! node . isClosed ( ) && ! name . equals ( node . settings ( ) . get ( NODE_NAME ) ) ) { return node ; } } return null ; }
Return a non - master node .
39,659
public ClusterHealthStatus ensureGreen ( final String ... indices ) { final ClusterHealthResponse actionGet = client ( ) . admin ( ) . cluster ( ) . health ( Requests . clusterHealthRequest ( indices ) . waitForGreenStatus ( ) . waitForEvents ( Priority . LANGUID ) . waitForNoRelocatingShards ( true ) ) . actionGet ( ) ; if ( actionGet . isTimedOut ( ) ) { onFailure ( "ensureGreen timed out, cluster state:\n" + client ( ) . admin ( ) . cluster ( ) . prepareState ( ) . get ( ) . getState ( ) + "\n" + client ( ) . admin ( ) . cluster ( ) . preparePendingClusterTasks ( ) . get ( ) , actionGet ) ; } return actionGet . getStatus ( ) ; }
Wait for green state of a cluster .
39,660
public void connect ( ) throws DBException { try { LOGGER . debug ( "Initializing MongoDB client" ) ; mongoClient = new MongoClient ( this . host , this . port ) ; } catch ( UnknownHostException e ) { throw new DBException ( e . toString ( ) ) ; } }
Connect to MongoDB Host .
39,661
public boolean exitsMongoDbDataBase ( String dataBaseName ) { List < String > dataBaseList = mongoClient . getDatabaseNames ( ) ; return dataBaseList . contains ( dataBaseName ) ; }
Checks if a database exists in MongoDB .
39,662
public void createMongoDBCollection ( String colectionName , DataTable options ) { BasicDBObject aux = new BasicDBObject ( ) ; List < List < String > > rowsOp = options . raw ( ) ; for ( int i = 0 ; i < rowsOp . size ( ) ; i ++ ) { List < String > rowOp = rowsOp . get ( i ) ; if ( rowOp . get ( 0 ) . equals ( "size" ) || rowOp . get ( 0 ) . equals ( "max" ) ) { int intproperty = Integer . parseInt ( rowOp . get ( 1 ) ) ; aux . append ( rowOp . get ( 0 ) , intproperty ) ; } else { Boolean boolProperty = Boolean . parseBoolean ( rowOp . get ( 1 ) ) ; aux . append ( rowOp . get ( 0 ) , boolProperty ) ; } } dataBase . createCollection ( colectionName , aux ) ; }
Create a MongoDB collection .
39,663
public void dropAllDataMongoDBCollection ( String collectionName ) { DBCollection db = getMongoDBCollection ( collectionName ) ; DBCursor objectsList = db . find ( ) ; try { while ( objectsList . hasNext ( ) ) { db . remove ( objectsList . next ( ) ) ; } } finally { objectsList . close ( ) ; } }
Drop all the data associated to a MongoDB Collection .
39,664
public void insertIntoMongoDBCollection ( String collection , DataTable table ) { List < String [ ] > colRel = coltoArrayList ( table ) ; for ( int i = 1 ; i < table . raw ( ) . size ( ) ; i ++ ) { BasicDBObject doc = new BasicDBObject ( ) ; List < String > row = table . raw ( ) . get ( i ) ; for ( int x = 0 ; x < row . size ( ) ; x ++ ) { String [ ] colNameType = colRel . get ( x ) ; Object data = castSTringTo ( colNameType [ 1 ] , row . get ( x ) ) ; doc . put ( colNameType [ 0 ] , data ) ; } this . dataBase . getCollection ( collection ) . insert ( doc ) ; } }
Insert data in a MongoDB Collection .
39,665
public void insertDocIntoMongoDBCollection ( String collection , String document ) { DBObject dbObject = ( DBObject ) JSON . parse ( document ) ; this . dataBase . getCollection ( collection ) . insert ( dbObject ) ; }
Insert document in a MongoDB Collection .
39,666
public List < DBObject > readFromMongoDBCollection ( String collection , DataTable table ) { List < DBObject > res = new ArrayList < DBObject > ( ) ; List < String [ ] > colRel = coltoArrayList ( table ) ; DBCollection aux = this . dataBase . getCollection ( collection ) ; for ( int i = 1 ; i < table . raw ( ) . size ( ) ; i ++ ) { BasicDBObject doc = new BasicDBObject ( ) ; List < String > row = table . raw ( ) . get ( i ) ; for ( int x = 0 ; x < row . size ( ) ; x ++ ) { String [ ] colNameType = colRel . get ( x ) ; Object data = castSTringTo ( colNameType [ 1 ] , row . get ( x ) ) ; doc . put ( colNameType [ 0 ] , data ) ; } DBCursor cursor = aux . find ( doc ) ; try { while ( cursor . hasNext ( ) ) { res . add ( cursor . next ( ) ) ; } } finally { cursor . close ( ) ; } } return res ; }
Read data from a MongoDB collection .
39,667
public void setSettings ( LinkedHashMap < String , Object > settings ) { Settings . Builder builder = Settings . settingsBuilder ( ) ; for ( Map . Entry < String , Object > entry : settings . entrySet ( ) ) { builder . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } this . settings = builder . build ( ) ; }
Set settings about ES connector .
39,668
public void connect ( ) throws java . net . UnknownHostException { this . client = TransportClient . builder ( ) . settings ( this . settings ) . build ( ) . addTransportAddress ( new InetSocketTransportAddress ( InetAddress . getByName ( this . es_host ) , this . es_native_port ) ) ; }
Connect to ES .
39,669
public boolean createSingleIndex ( String indexName ) throws ElasticsearchException { CreateIndexRequest indexRequest = new CreateIndexRequest ( indexName ) ; CreateIndexResponse res = this . client . admin ( ) . indices ( ) . create ( indexRequest ) . actionGet ( ) ; return indexExists ( indexName ) ; }
Create an ES Index .
39,670
public boolean dropSingleIndex ( String indexName ) throws ElasticsearchException { DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest ( indexName ) ; DeleteIndexResponse res = this . client . admin ( ) . indices ( ) . delete ( deleteIndexRequest ) . actionGet ( ) ; return indexExists ( indexName ) ; }
Drop an ES Index
39,671
public boolean indexExists ( String indexName ) { return this . client . admin ( ) . indices ( ) . prepareExists ( indexName ) . execute ( ) . actionGet ( ) . isExists ( ) ; }
Check if an index exists in ES
39,672
public void createMapping ( String indexName , String mappingName , ArrayList < XContentBuilder > mappingSource ) { IndicesExistsResponse existsResponse = this . client . admin ( ) . indices ( ) . prepareExists ( indexName ) . execute ( ) . actionGet ( ) ; if ( ! existsResponse . isExists ( ) ) { if ( ! createSingleIndex ( indexName ) ) { throw new ElasticsearchException ( "Failed to create " + indexName + " index." ) ; } } BulkRequestBuilder bulkRequest = this . client . prepareBulk ( ) ; for ( int i = 0 ; i < mappingSource . size ( ) ; i ++ ) { int aux = i + 1 ; IndexRequestBuilder res = this . client . prepareIndex ( indexName , mappingName , String . valueOf ( aux ) ) . setSource ( mappingSource . get ( i ) ) ; bulkRequest . add ( res ) ; } bulkRequest . execute ( ) ; }
Create a mapping over an index
39,673
public boolean existsMapping ( String indexName , String mappingName ) { ClusterStateResponse resp = this . client . admin ( ) . cluster ( ) . prepareState ( ) . execute ( ) . actionGet ( ) ; if ( resp . getState ( ) . getMetaData ( ) . index ( indexName ) == null ) { return false ; } ImmutableOpenMap < String , MappingMetaData > mappings = resp . getState ( ) . getMetaData ( ) . index ( indexName ) . getMappings ( ) ; if ( mappings . get ( mappingName ) != null ) { return true ; } return false ; }
Check if a mapping exists in an expecific index .
39,674
public void indexDocument ( String indexName , String mappingName , String id , XContentBuilder document ) throws Exception { client . prepareIndex ( indexName , mappingName , id ) . setSource ( document ) . get ( ) ; }
Indexes a document .
39,675
public void deleteDocument ( String indexName , String mappingName , String id ) { client . prepareDelete ( indexName , mappingName , id ) . get ( ) ; }
Deletes a document by its id .
39,676
@ After ( order = ORDER_20 , value = { "@mobile or @web" } ) public void seleniumTeardown ( ) { if ( commonspec . getDriver ( ) != null ) { commonspec . getLogger ( ) . debug ( "Shutdown Selenium client" ) ; commonspec . getDriver ( ) . close ( ) ; commonspec . getDriver ( ) . quit ( ) ; } }
Close selenium web driver .
39,677
public static void set ( String key , String value ) { PROPS . get ( ) . setProperty ( key , value ) ; }
Set a string to share in other class .
39,678
@ Given ( "^I connect to kafka at '(.+)' using path '(.+)'$" ) public void connectKafka ( String zkHost , String zkPath ) throws UnknownHostException { String zkPort = zkHost . split ( ":" ) [ 1 ] ; zkHost = zkHost . split ( ":" ) [ 0 ] ; commonspec . getKafkaUtils ( ) . setZkHost ( zkHost , zkPort , zkPath ) ; commonspec . getKafkaUtils ( ) . connect ( ) ; }
Connect to Kafka .
39,679
@ When ( "^I copy the kafka topic '(.*?)' to file '(.*?)' with headers '(.*?)'$" ) public void topicToFile ( String topic_name , String filename , String header ) throws Exception { commonspec . getKafkaUtils ( ) . resultsToFile ( topic_name , filename , header ) ; }
Copy Kafka Topic content to file
39,680
@ When ( "^I increase '(.+?)' partitions in a Kafka topic named '(.+?)'" ) public void modifyPartitions ( int numPartitions , String topic_name ) throws Exception { commonspec . getKafkaUtils ( ) . modifyTopicPartitioning ( topic_name , numPartitions ) ; }
Modify partitions in a Kafka topic .
39,681
@ When ( "^I send a message '(.+?)' to the kafka topic named '(.+?)'" ) public void sendAMessage ( String message , String topic_name ) throws Exception { commonspec . getKafkaUtils ( ) . sendMessage ( message , topic_name ) ; }
Sending a message in a Kafka topic .
39,682
@ Then ( "^A kafka topic named '(.+?)' exists" ) public void kafkaTopicExist ( String topic_name ) throws KeeperException , InterruptedException { assert commonspec . getKafkaUtils ( ) . getZkUtils ( ) . pathExists ( "/" + topic_name ) : "There is no topic with that name" ; }
Check that a kafka topic exist
39,683
@ Then ( "^The number of partitions in topic '(.+?)' should be '(.+?)''?$" ) public void checkNumberOfPartitions ( String topic_name , int numOfPartitions ) throws Exception { Assertions . assertThat ( commonspec . getKafkaUtils ( ) . getPartitions ( topic_name ) ) . isEqualTo ( numOfPartitions ) ; }
Check that the number of partitions is like expected .
39,684
@ Given ( "^I switch to iframe with '([^:]*?):(.+?)'$" ) public void seleniumIdFrame ( String method , String idframe ) throws IllegalAccessException , NoSuchFieldException , ClassNotFoundException { assertThat ( commonspec . locateElement ( method , idframe , 1 ) ) ; if ( method . equals ( "id" ) || method . equals ( "name" ) ) { commonspec . getDriver ( ) . switchTo ( ) . frame ( idframe ) ; } else { throw new ClassNotFoundException ( "Can not use this method to switch iframe" ) ; } }
Swith to the iFrame where id matches idframe
39,685
@ Given ( "^a new window is opened$" ) public void seleniumGetwindows ( ) { Set < String > wel = commonspec . getDriver ( ) . getWindowHandles ( ) ; Assertions . assertThat ( wel ) . as ( "Element count doesnt match" ) . hasSize ( 2 ) ; }
Get all opened windows and store it .
39,686
@ When ( "^I drag '([^:]*?):(.+?)' and drop it to '([^:]*?):(.+?)'$" ) public void seleniumDrag ( String smethod , String source , String dmethod , String destination ) throws ClassNotFoundException , NoSuchFieldException , SecurityException , IllegalArgumentException , IllegalAccessException { Actions builder = new Actions ( commonspec . getDriver ( ) ) ; List < WebElement > sourceElement = commonspec . locateElement ( smethod , source , 1 ) ; List < WebElement > destinationElement = commonspec . locateElement ( dmethod , destination , 1 ) ; builder . dragAndDrop ( sourceElement . get ( 0 ) , destinationElement . get ( 0 ) ) . perform ( ) ; }
Searchs for two webelements dragging the first one to the second
39,687
@ When ( "^I de-select every item on the element on index '(\\d+?)'$" ) public void elementDeSelect ( Integer index ) { Select sel = null ; sel = new Select ( commonspec . getPreviousWebElements ( ) . getPreviousWebElements ( ) . get ( index ) ) ; if ( sel . isMultiple ( ) ) { sel . deselectAll ( ) ; } }
Choose no option from a select webelement found previously
39,688
@ When ( "^I change active window$" ) public void seleniumChangeWindow ( ) { String originalWindowHandle = commonspec . getDriver ( ) . getWindowHandle ( ) ; Set < String > windowHandles = commonspec . getDriver ( ) . getWindowHandles ( ) ; for ( String window : windowHandles ) { if ( ! window . equals ( originalWindowHandle ) ) { commonspec . getDriver ( ) . switchTo ( ) . window ( window ) ; } } }
Change current window to another opened window .
39,689
@ Then ( "^this text exists '(.+?)'$" ) public void assertSeleniumTextInSource ( String text ) { assertThat ( this . commonspec , commonspec . getDriver ( ) ) . as ( "Expected text not found at page" ) . contains ( text ) ; }
Checks if a text exists in the source of an already loaded URL .
39,690
@ Then ( "^we are in page '(.+?)'$" ) public void checkURL ( String url ) throws Exception { if ( commonspec . getWebHost ( ) == null ) { throw new Exception ( "Web host has not been set" ) ; } if ( commonspec . getWebPort ( ) == null ) { throw new Exception ( "Web port has not been set" ) ; } String webURL = commonspec . getWebHost ( ) + commonspec . getWebPort ( ) ; assertThat ( commonspec . getDriver ( ) . getCurrentUrl ( ) ) . as ( "We are not in the expected url: " + webURL . toLowerCase ( ) + url ) . endsWith ( webURL . toLowerCase ( ) + url ) ; }
Checks that we are in the URL passed
39,691
@ Then ( "^I save selenium dcos acs auth cookie in variable '(.+?)'$" ) public void getDcosAcsAuthCookie ( String envVar ) throws Exception { if ( commonspec . getSeleniumCookies ( ) != null && commonspec . getSeleniumCookies ( ) . size ( ) != 0 ) { for ( Cookie cookie : commonspec . getSeleniumCookies ( ) ) { if ( cookie . getName ( ) . contains ( "dcos-acs-auth-cookie" ) ) { ThreadProperty . set ( envVar , cookie . getValue ( ) ) ; break ; } } } else { ThreadProperty . set ( envVar , null ) ; } }
Get dcos - auth - cookie
39,692
@ Then ( "^The cookie '(.+?)' exists in the saved cookies$" ) public void checkIfCookieExists ( String cookieName ) { Assertions . assertThat ( commonspec . cookieExists ( cookieName ) ) . isEqualTo ( true ) ; }
Check if a cookie exists
39,693
@ Then ( "^I have '(.+?)' selenium cookies saved$" ) public void getSeleniumCookiesSize ( int numberOfCookies ) throws Exception { Assertions . assertThat ( commonspec . getSeleniumCookies ( ) . size ( ) ) . isEqualTo ( numberOfCookies ) ; }
Check if the length of the cookie set match with the number of cookies thas must be saved
39,694
@ Then ( "^I save content of element in index '(\\d+?)' in environment variable '(.+?)'$" ) public void saveContentWebElementInEnvVar ( Integer index , String envVar ) { assertThat ( this . commonspec , commonspec . getPreviousWebElements ( ) ) . as ( "There are less found elements than required" ) . hasAtLeast ( index ) ; String text = commonspec . getPreviousWebElements ( ) . getPreviousWebElements ( ) . get ( index ) . getText ( ) ; ThreadProperty . set ( envVar , text ) ; }
Takes the content of a webElement and stores it in the thread environment variable passed as parameter
39,695
@ Given ( "^I save \'(.+?)\' in variable \'(.+?)\'$" ) public void saveInEnvironment ( String value , String envVar ) { ThreadProperty . set ( envVar , value ) ; }
Save value for future use .
39,696
@ When ( "^I sort elements in '(.+?)' by '(.+?)' criteria in '(.+?)' order$" ) public void sortElements ( String envVar , String criteria , String order ) { String value = ThreadProperty . get ( envVar ) ; JsonArray jsonArr = JsonValue . readHjson ( value ) . asArray ( ) ; List < JsonValue > jsonValues = new ArrayList < JsonValue > ( ) ; for ( int i = 0 ; i < jsonArr . size ( ) ; i ++ ) { jsonValues . add ( jsonArr . get ( i ) ) ; } Comparator < JsonValue > comparator ; switch ( criteria ) { case "alphabetical" : commonspec . getLogger ( ) . debug ( "Alphabetical criteria selected." ) ; comparator = new Comparator < JsonValue > ( ) { public int compare ( JsonValue json1 , JsonValue json2 ) { int res = String . CASE_INSENSITIVE_ORDER . compare ( json1 . toString ( ) , json2 . toString ( ) ) ; if ( res == 0 ) { res = json1 . toString ( ) . compareTo ( json2 . toString ( ) ) ; } return res ; } } ; break ; default : commonspec . getLogger ( ) . debug ( "No criteria selected." ) ; comparator = null ; } if ( "ascending" . equals ( order ) ) { Collections . sort ( jsonValues , comparator ) ; } else { Collections . sort ( jsonValues , comparator . reversed ( ) ) ; } ThreadProperty . set ( envVar , jsonValues . toString ( ) ) ; }
Sort elements in envVar by a criteria and order .
39,697
@ Then ( "^an exception '(.+?)' thrown( with class '(.+?)'( and message like '(.+?)')?)?" ) public void assertExceptionNotThrown ( String exception , String foo , String clazz , String bar , String exceptionMsg ) throws ClassNotFoundException { List < Exception > exceptions = commonspec . getExceptions ( ) ; if ( "IS NOT" . equals ( exception ) ) { assertThat ( exceptions ) . as ( "Captured exception list is not empty" ) . isEmpty ( ) ; } else { assertThat ( exceptions ) . as ( "Captured exception list is empty" ) . isNotEmpty ( ) ; Exception ex = exceptions . get ( exceptions . size ( ) - 1 ) ; if ( ( clazz != null ) && ( exceptionMsg != null ) ) { assertThat ( ex . toString ( ) ) . as ( "Unexpected last exception class" ) . contains ( clazz ) ; assertThat ( ex . toString ( ) ) . as ( "Unexpected last exception message" ) . contains ( exceptionMsg ) ; } else if ( clazz != null ) { assertThat ( exceptions . get ( exceptions . size ( ) - 1 ) . getClass ( ) . getSimpleName ( ) ) . as ( "Unexpected last exception class" ) . isEqualTo ( clazz ) ; } commonspec . getExceptions ( ) . clear ( ) ; } }
Checks if an exception has been thrown .
39,698
@ When ( "^I send a '(.+?)' request to '(.+?)'( with user and password '(.+:.+?)')? based on '([^:]+?)'( as '(json|string|gov)')? with:$" ) public void sendRequest ( String requestType , String endPoint , String foo , String loginInfo , String baseData , String baz , String type , DataTable modifications ) throws Exception { String retrievedData = commonspec . retrieveData ( baseData , type ) ; commonspec . getLogger ( ) . debug ( "Modifying data {} as {}" , retrievedData , type ) ; String modifiedData = commonspec . modifyData ( retrievedData , type , modifications ) . toString ( ) ; String user = null ; String password = null ; if ( loginInfo != null ) { user = loginInfo . substring ( 0 , loginInfo . indexOf ( ':' ) ) ; password = loginInfo . substring ( loginInfo . indexOf ( ':' ) + 1 , loginInfo . length ( ) ) ; } commonspec . getLogger ( ) . debug ( "Generating request {} to {} with data {} as {}" , requestType , endPoint , modifiedData , type ) ; Future < Response > response = commonspec . generateRequest ( requestType , false , user , password , endPoint , modifiedData , type , "" ) ; commonspec . getLogger ( ) . debug ( "Saving response" ) ; commonspec . setResponse ( requestType , response . get ( ) ) ; }
Send a request of the type specified
39,699
@ When ( "^I send a '(.+?)' request to '(.+?)'( with user and password '(.+:.+?)')?( based on '([^:]+?)')?( as '(json|string|gov)')?$" ) public void sendRequestNoDataTable ( String requestType , String endPoint , String foo , String loginInfo , String bar , String baseData , String baz , String type ) throws Exception { Future < Response > response ; String user = null ; String password = null ; if ( loginInfo != null ) { user = loginInfo . substring ( 0 , loginInfo . indexOf ( ':' ) ) ; password = loginInfo . substring ( loginInfo . indexOf ( ':' ) + 1 , loginInfo . length ( ) ) ; } if ( baseData != null ) { String retrievedData = commonspec . retrieveData ( baseData , type ) ; response = commonspec . generateRequest ( requestType , false , user , password , endPoint , retrievedData , type , "" ) ; } else { response = commonspec . generateRequest ( requestType , false , user , password , endPoint , "" , type , "" ) ; } commonspec . setResponse ( requestType , response . get ( ) ) ; }
Same sendRequest but in this case we do not receive a data table with modifications . Besides the data and request header are optional as well . In case we want to simulate sending a json request with empty data we just to avoid baseData