idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
14,400
protected ParserResults processSpecContents ( ParserData parserData , final boolean processProcesses ) { parserData . setCurrentLevel ( parserData . getContentSpec ( ) . getBaseLevel ( ) ) ; boolean error = false ; while ( parserData . getLines ( ) . peek ( ) != null ) { parserData . setLineCount ( parserData . getLineCount ( ) + 1 ) ; try { if ( ! parseLine ( parserData , parserData . getLines ( ) . poll ( ) , parserData . getLineCount ( ) ) ) { error = true ; } } catch ( IndentationException e ) { log . error ( e . getMessage ( ) ) ; return new ParserResults ( false , null ) ; } } if ( processProcesses ) { for ( final Process process : parserData . getProcesses ( ) ) { process . processTopics ( parserData . getSpecTopics ( ) , parserData . getTargetTopics ( ) , topicProvider , serverSettingsProvider ) ; } } processRelationships ( parserData ) ; return new ParserResults ( ! error , parserData . getContentSpec ( ) ) ; }
Process the contents of a content specification and parse it into a ContentSpec object .
14,401
protected boolean parseLine ( final ParserData parserData , final String line , int lineNumber ) throws IndentationException { assert line != null ; final String trimmedLine = line . trim ( ) ; if ( isBlankLine ( trimmedLine ) || isCommentLine ( trimmedLine ) ) { return parseEmptyOrCommentLine ( parserData , line ) ; } else { int lineIndentationLevel = calculateLineIndentationLevel ( parserData , line , lineNumber ) ; if ( lineIndentationLevel > parserData . getIndentationLevel ( ) ) { throw new IndentationException ( format ( ProcessorConstants . ERROR_INCORRECT_INDENTATION_MSG , lineNumber , trimmedLine ) ) ; } else if ( lineIndentationLevel < parserData . getIndentationLevel ( ) ) { Level newCurrentLevel = parserData . getCurrentLevel ( ) ; for ( int i = ( parserData . getIndentationLevel ( ) - lineIndentationLevel ) ; i > 0 ; i -- ) { if ( newCurrentLevel . getParent ( ) != null ) { newCurrentLevel = newCurrentLevel . getParent ( ) ; } } changeCurrentLevel ( parserData , newCurrentLevel , lineIndentationLevel ) ; } try { if ( isMetaDataLine ( parserData , trimmedLine ) ) { parseMetaDataLine ( parserData , line , lineNumber ) ; } else if ( isCommonContentLine ( trimmedLine ) ) { final CommonContent commonContent = parseCommonContentLine ( parserData , line , lineNumber ) ; parserData . getCurrentLevel ( ) . appendChild ( commonContent ) ; } else if ( isLevelInitialContentLine ( trimmedLine ) ) { final Level initialContent = parseLevelLine ( parserData , trimmedLine , lineNumber ) ; parserData . getCurrentLevel ( ) . appendChild ( initialContent ) ; changeCurrentLevel ( parserData , initialContent , parserData . getIndentationLevel ( ) + 1 ) ; } else if ( isLevelLine ( trimmedLine ) ) { final Level level = parseLevelLine ( parserData , trimmedLine , lineNumber ) ; if ( level instanceof Process ) { parserData . getProcesses ( ) . add ( ( Process ) level ) ; } parserData . getCurrentLevel ( ) . appendChild ( level ) ; changeCurrentLevel ( parserData , level , parserData . getIndentationLevel ( ) + 1 ) ; } else if ( StringUtilities . indexOf ( trimmedLine , '[' ) == 0 && parserData . getCurrentLevel ( ) . getLevelType ( ) == LevelType . BASE ) { parseGlobalOptionsLine ( parserData , line , lineNumber ) ; } else { final SpecTopic tempTopic = parseTopic ( parserData , trimmedLine , lineNumber ) ; parserData . getCurrentLevel ( ) . appendSpecTopic ( tempTopic ) ; } } catch ( ParsingException e ) { log . error ( e . getMessage ( ) ) ; return false ; } return true ; } }
Processes a line of the content specification and stores it in objects
14,402
protected int calculateLineIndentationLevel ( final ParserData parserData , final String line , int lineNumber ) throws IndentationException { char [ ] lineCharArray = line . toCharArray ( ) ; int indentationCount = 0 ; if ( Character . isWhitespace ( lineCharArray [ 0 ] ) ) { for ( char c : lineCharArray ) { if ( Character . isWhitespace ( c ) ) { indentationCount ++ ; } else { break ; } } if ( indentationCount % parserData . getIndentationSize ( ) != 0 ) { throw new IndentationException ( format ( ProcessorConstants . ERROR_INCORRECT_INDENTATION_MSG , lineNumber , line . trim ( ) ) ) ; } } return indentationCount / parserData . getIndentationSize ( ) ; }
Calculates the indentation level of a line using the amount of whitespace and the parsers indentation size setting .
14,403
protected boolean isMetaDataLine ( ParserData parserData , String line ) { return parserData . getCurrentLevel ( ) . getLevelType ( ) == LevelType . BASE && line . trim ( ) . matches ( "^\\w[\\w\\.\\s-]+=.*" ) ; }
Checks to see if a line is represents a Content Specifications Meta Data .
14,404
protected boolean isLevelInitialContentLine ( String line ) { final Matcher matcher = LEVEL_INITIAL_CONTENT_PATTERN . matcher ( line . trim ( ) . toUpperCase ( Locale . ENGLISH ) ) ; return matcher . find ( ) ; }
Checks to see if a line is represents a Content Specifications Level Front Matter .
14,405
protected boolean isLevelLine ( String line ) { final Matcher matcher = LEVEL_PATTERN . matcher ( line . trim ( ) . toUpperCase ( Locale . ENGLISH ) ) ; return matcher . find ( ) ; }
Checks to see if a line is represents a Content Specifications Level .
14,406
protected boolean parseEmptyOrCommentLine ( final ParserData parserData , final String line ) { if ( isBlankLine ( line ) ) { if ( parserData . getCurrentLevel ( ) . getLevelType ( ) == LevelType . BASE ) { parserData . getContentSpec ( ) . appendChild ( new TextNode ( "\n" ) ) ; } else { parserData . getCurrentLevel ( ) . appendChild ( new TextNode ( "\n" ) ) ; } return true ; } else { if ( parserData . getCurrentLevel ( ) . getLevelType ( ) == LevelType . BASE ) { parserData . getContentSpec ( ) . appendComment ( line ) ; } else { parserData . getCurrentLevel ( ) . appendComment ( line ) ; } return true ; } }
Processes a line that represents a comment or an empty line in a Content Specification .
14,407
protected Level parseLevelLine ( final ParserData parserData , final String line , int lineNumber ) throws ParsingException { String tempInput [ ] = StringUtilities . split ( line , ':' , 2 ) ; tempInput = CollectionUtilities . trimStringArray ( tempInput ) ; if ( tempInput . length >= 1 ) { final LevelType levelType = LevelType . getLevelType ( tempInput [ 0 ] ) ; Level retValue = null ; try { retValue = parseLevel ( parserData , lineNumber , levelType , line ) ; } catch ( ParsingException e ) { log . error ( e . getMessage ( ) ) ; retValue = createEmptyLevelFromType ( lineNumber , levelType , line ) ; retValue . setUniqueId ( "L" + lineNumber ) ; } parserData . getLevels ( ) . put ( retValue . getUniqueId ( ) , retValue ) ; return retValue ; } else { throw new ParsingException ( format ( ProcessorConstants . ERROR_LEVEL_FORMAT_MSG , lineNumber , line ) ) ; } }
Processes a line that represents the start of a Content Specification Level . This method creates the level based on the data in the line and then changes the current processing level to the new level .
14,408
private boolean isSpecTopicMetaData ( final String key , final String value ) { if ( ContentSpecUtilities . isSpecTopicMetaData ( key ) ) { if ( key . equalsIgnoreCase ( CommonConstants . CS_ABSTRACT_TITLE ) || key . equalsIgnoreCase ( CommonConstants . CS_ABSTRACT_ALTERNATE_TITLE ) ) { final String fixedValue = value . trim ( ) . replaceAll ( "(?i)^" + key + "\\s*" , "" ) ; return fixedValue . trim ( ) . startsWith ( "[" ) ; } else { return true ; } } else { return false ; } }
Checks if a metadata line is a spec topic .
14,409
private KeyValueNode < String > parseMultiLineMetaData ( final ParserData parserData , final String key , final String value , final int lineNumber ) throws ParsingException { int startingPos = StringUtilities . indexOf ( value , '[' ) ; if ( startingPos != - 1 ) { final StringBuilder multiLineValue = new StringBuilder ( value ) ; if ( StringUtilities . indexOf ( value , ']' ) == - 1 ) { multiLineValue . append ( "\n" ) ; String newLine = parserData . getLines ( ) . poll ( ) ; while ( newLine != null ) { multiLineValue . append ( newLine ) . append ( "\n" ) ; parserData . setLineCount ( parserData . getLineCount ( ) + 1 ) ; if ( StringUtilities . lastIndexOf ( multiLineValue . toString ( ) , ']' ) == - 1 ) { newLine = parserData . getLines ( ) . poll ( ) ; } else { break ; } } } final String finalMultiLineValue = multiLineValue . toString ( ) . trim ( ) ; if ( StringUtilities . lastIndexOf ( finalMultiLineValue , ']' ) == - 1 || StringUtilities . lastIndexOf ( finalMultiLineValue , '[' ) != startingPos ) { throw new ParsingException ( format ( ProcessorConstants . ERROR_INVALID_MULTILINE_METADATA_MSG , lineNumber , key + " = " + finalMultiLineValue . replaceAll ( "\n" , "\n " ) ) ) ; } else { final String finalValue = finalMultiLineValue . substring ( 1 , finalMultiLineValue . length ( ) - 1 ) ; return new KeyValueNode < String > ( key , finalValue ) ; } } else { return new KeyValueNode < String > ( key , value , lineNumber ) ; } }
Parses a multiple line metadata element .
14,410
protected boolean parseGlobalOptionsLine ( final ParserData parserData , final String line , int lineNumber ) throws ParsingException { final HashMap < ParserType , String [ ] > variableMap = getLineVariables ( parserData , line , lineNumber , '[' , ']' , ',' , false ) ; if ( ( variableMap . size ( ) > 1 && variableMap . containsKey ( ParserType . NONE ) ) || ( variableMap . size ( ) > 0 && ! variableMap . containsKey ( ParserType . NONE ) ) ) { throw new ParsingException ( format ( ProcessorConstants . ERROR_RELATIONSHIP_BASE_LEVEL_MSG , lineNumber , line ) ) ; } String [ ] variables = variableMap . get ( ParserType . NONE ) ; if ( variables . length > 0 ) { addOptions ( parserData , parserData . getCurrentLevel ( ) , variables , 0 , line , lineNumber ) ; } else { log . warn ( format ( ProcessorConstants . WARN_EMPTY_BRACKETS_MSG , lineNumber ) ) ; } return true ; }
Processes a line that represents the Global Options for the Content Specification .
14,411
protected void changeCurrentLevel ( ParserData parserData , final Level newLevel , int newIndentationLevel ) { parserData . setIndentationLevel ( newIndentationLevel ) ; parserData . setCurrentLevel ( newLevel ) ; }
Changes the current level that content is being processed for to a new level .
14,412
protected CommonContent parseCommonContentLine ( final ParserData parserData , final String line , int lineNumber ) throws ParsingException { final HashMap < ParserType , String [ ] > variableMap = getLineVariables ( parserData , line , lineNumber , '[' , ']' , ',' , false ) ; if ( ! variableMap . containsKey ( ParserType . NONE ) ) { throw new ParsingException ( format ( ProcessorConstants . ERROR_INVALID_TOPIC_FORMAT_MSG , lineNumber , line ) ) ; } final String title = ProcessorUtilities . replaceEscapeChars ( getTitle ( line , '[' ) ) ; final CommonContent commonContent = new CommonContent ( title , lineNumber , line ) ; commonContent . setUniqueId ( "L" + lineNumber + "-CommonContent" ) ; final String [ ] baseAttributes = variableMap . get ( ParserType . NONE ) ; if ( baseAttributes . length > 1 ) { log . warn ( format ( ProcessorConstants . WARN_IGNORE_COMMON_CONTENT_ATTRIBUTES_MSG , lineNumber , line ) ) ; } variableMap . remove ( ParserType . NONE ) ; if ( variableMap . size ( ) > 0 ) { throw new ParsingException ( format ( ProcessorConstants . ERROR_COMMON_CONTENT_CONTAINS_ILLEGAL_CONTENT , lineNumber , line ) ) ; } return commonContent ; }
Processes the input to create a new common content node .
14,413
protected SpecTopic parseTopic ( final ParserData parserData , final String line , int lineNumber ) throws ParsingException { final HashMap < ParserType , String [ ] > variableMap = getLineVariables ( parserData , line , lineNumber , '[' , ']' , ',' , false ) ; if ( ! variableMap . containsKey ( ParserType . NONE ) ) { throw new ParsingException ( format ( ProcessorConstants . ERROR_INVALID_TOPIC_FORMAT_MSG , lineNumber , line ) ) ; } final String title = ProcessorUtilities . replaceEscapeChars ( getTitle ( line , '[' ) ) ; final SpecTopic tempTopic = new SpecTopic ( title , lineNumber , line , null ) ; addTopicAttributes ( tempTopic , parserData , variableMap . get ( ParserType . NONE ) , lineNumber , line ) ; parserData . getSpecTopics ( ) . put ( tempTopic . getUniqueId ( ) , tempTopic ) ; processTopicRelationships ( parserData , tempTopic , variableMap , line , lineNumber ) ; if ( variableMap . containsKey ( ParserType . INFO ) ) { throw new ParsingException ( format ( ProcessorConstants . ERROR_TOPIC_WITH_INFO_TOPIC , lineNumber , line ) ) ; } return tempTopic ; }
Processes the input to create a new topic
14,414
private void processRelationshipList ( final ParserType parserType , final SpecNodeWithRelationships tempNode , final HashMap < ParserType , String [ ] > variableMap , final List < Relationship > relationships , int lineNumber ) throws ParsingException { final String uniqueId = tempNode . getUniqueId ( ) ; String errorMessageFormat = null ; RelationshipType relationshipType ; switch ( parserType ) { case REFER_TO : errorMessageFormat = ProcessorConstants . ERROR_INVALID_REFERS_TO_RELATIONSHIP ; relationshipType = RelationshipType . REFER_TO ; break ; case LINKLIST : errorMessageFormat = ProcessorConstants . ERROR_INVALID_LINK_LIST_RELATIONSHIP ; relationshipType = RelationshipType . LINKLIST ; break ; case PREREQUISITE : errorMessageFormat = ProcessorConstants . ERROR_INVALID_PREREQUISITE_RELATIONSHIP ; relationshipType = RelationshipType . PREREQUISITE ; break ; default : return ; } if ( variableMap . containsKey ( parserType ) ) { final String [ ] relationshipList = variableMap . get ( parserType ) ; for ( final String relationshipId : relationshipList ) { if ( relationshipId . matches ( ProcessorConstants . RELATION_ID_REGEX ) ) { relationships . add ( new Relationship ( uniqueId , relationshipId , relationshipType ) ) ; } else if ( relationshipId . matches ( ProcessorConstants . RELATION_ID_LONG_REGEX ) ) { final Matcher matcher = RELATION_ID_LONG_PATTERN . matcher ( relationshipId ) ; matcher . find ( ) ; final String id = matcher . group ( "TopicID" ) ; final String relationshipTitle = matcher . group ( "TopicTitle" ) ; final String cleanedTitle = ProcessorUtilities . cleanXMLCharacterReferences ( relationshipTitle . trim ( ) ) ; relationships . add ( new Relationship ( uniqueId , id , relationshipType , ProcessorUtilities . replaceEscapeChars ( cleanedTitle ) ) ) ; } else { if ( relationshipId . matches ( "^(" + ProcessorConstants . TARGET_BASE_REGEX + "|[0-9]+).*?(" + ProcessorConstants . TARGET_BASE_REGEX + "|[0-9]+).*" ) ) { throw new ParsingException ( format ( ProcessorConstants . ERROR_MISSING_SEPARATOR_MSG , lineNumber , ',' ) ) ; } else { throw new ParsingException ( format ( errorMessageFormat , lineNumber ) ) ; } } } } }
Processes a list of relationships for a specific relationship type from some line processed variables .
14,415
protected Level createEmptyLevelFromType ( final int lineNumber , final LevelType levelType , final String input ) { switch ( levelType ) { case APPENDIX : return new Appendix ( null , lineNumber , input ) ; case CHAPTER : return new Chapter ( null , lineNumber , input ) ; case SECTION : return new Section ( null , lineNumber , input ) ; case PART : return new Part ( null , lineNumber , input ) ; case PROCESS : return new Process ( null , lineNumber , input ) ; case INITIAL_CONTENT : return new InitialContent ( lineNumber , input ) ; default : return new Level ( null , lineNumber , input , levelType ) ; } }
Creates an empty Level using the LevelType to determine which Level subclass to instantiate .
14,416
protected ParserType getType ( final String variableString ) { final String uppercaseVarSet = variableString . trim ( ) . toUpperCase ( Locale . ENGLISH ) ; if ( uppercaseVarSet . matches ( ProcessorConstants . RELATED_REGEX ) ) { return ParserType . REFER_TO ; } else if ( uppercaseVarSet . matches ( ProcessorConstants . PREREQUISITE_REGEX ) ) { return ParserType . PREREQUISITE ; } else if ( uppercaseVarSet . matches ( ProcessorConstants . NEXT_REGEX ) ) { return ParserType . NEXT ; } else if ( uppercaseVarSet . matches ( ProcessorConstants . PREV_REGEX ) ) { return ParserType . PREVIOUS ; } else if ( uppercaseVarSet . matches ( ProcessorConstants . TARGET_REGEX ) ) { return ParserType . TARGET ; } else if ( uppercaseVarSet . matches ( ProcessorConstants . EXTERNAL_TARGET_REGEX ) ) { return ParserType . EXTERNAL_TARGET ; } else if ( uppercaseVarSet . matches ( ProcessorConstants . EXTERNAL_CSP_REGEX ) ) { return ParserType . EXTERNAL_CONTENT_SPEC ; } else if ( uppercaseVarSet . matches ( ProcessorConstants . LINK_LIST_REGEX ) ) { return ParserType . LINKLIST ; } else if ( uppercaseVarSet . matches ( ProcessorConstants . INFO_REGEX ) ) { return ParserType . INFO ; } else { return ParserType . NONE ; } }
Processes a string of variables to find the type that exists within the string .
14,417
protected void processRelationships ( final ParserData parserData ) { for ( final Map . Entry < String , List < Relationship > > entry : parserData . getLevelRelationships ( ) . entrySet ( ) ) { final String levelId = entry . getKey ( ) ; final Level level = parserData . getLevels ( ) . get ( levelId ) ; assert level != null ; for ( final Relationship relationship : entry . getValue ( ) ) { processRelationship ( parserData , level , relationship ) ; } } for ( final Map . Entry < String , List < Relationship > > entry : parserData . getTopicRelationships ( ) . entrySet ( ) ) { final String topicId = entry . getKey ( ) ; final SpecTopic specTopic = parserData . getSpecTopics ( ) . get ( topicId ) ; assert specTopic != null ; for ( final Relationship relationship : entry . getValue ( ) ) { processRelationship ( parserData , specTopic , relationship ) ; } } }
Process the relationships without logging any errors .
14,418
protected List < VariableSet > findVariableSets ( final ParserData parserData , final String input , final char startDelim , final char endDelim ) { final StringBuilder varLine = new StringBuilder ( input ) ; final List < VariableSet > retValue = new ArrayList < VariableSet > ( ) ; int startPos = 0 ; VariableSet set = ProcessorUtilities . findVariableSet ( input , startDelim , endDelim , startPos ) ; while ( set != null && set . getContents ( ) != null ) { if ( set . getEndPos ( ) != null ) { retValue . add ( set ) ; final String nextLine = parserData . getLines ( ) . peek ( ) ; startPos = set . getEndPos ( ) + 1 ; set = ProcessorUtilities . findVariableSet ( varLine . toString ( ) , startDelim , endDelim , startPos ) ; if ( ( set == null || set . getContents ( ) == null ) && ( nextLine != null && nextLine . trim ( ) . toUpperCase ( Locale . ENGLISH ) . matches ( "^\\" + startDelim + "[ ]*(R|L|P|T|B).*" ) ) ) { final String line = parserData . getLines ( ) . poll ( ) ; parserData . setLineCount ( parserData . getLineCount ( ) + 1 ) ; if ( line != null ) { varLine . append ( "\n" ) . append ( line ) ; set = ProcessorUtilities . findVariableSet ( varLine . toString ( ) , startDelim , endDelim , startPos ) ; } } } else { final String line = parserData . getLines ( ) . poll ( ) ; parserData . setLineCount ( parserData . getLineCount ( ) + 1 ) ; if ( line != null ) { varLine . append ( "\n" ) . append ( line ) ; set = ProcessorUtilities . findVariableSet ( varLine . toString ( ) , startDelim , endDelim , startPos ) ; } else { retValue . add ( set ) ; break ; } } } return retValue ; }
Finds a List of variable sets within a string . If the end of a set can t be determined then it will continue to parse the following lines until the end is found .
14,419
public static final < T > List < List < T > > split ( List < T > list , Predicate < T > predicate ) { if ( list . isEmpty ( ) ) { return Collections . EMPTY_LIST ; } List < List < T > > lists = new ArrayList < > ( ) ; boolean b = predicate . test ( list . get ( 0 ) ) ; int len = list . size ( ) ; int start = 0 ; for ( int ii = 1 ; ii < len ; ii ++ ) { boolean t = predicate . test ( list . get ( ii ) ) ; if ( b != t ) { lists . add ( list . subList ( start , ii ) ) ; start = ii ; b = t ; } } lists . add ( list . subList ( start , len ) ) ; return lists ; }
Splits list into several sub - lists according to predicate .
14,420
public static final void setFormat ( String format , Locale locale ) { threadFormat . set ( format ) ; threadLocale . set ( locale ) ; }
Set Format string and locale for calling thread . List items are formatted using these . It is good practice to call removeFormat after use .
14,421
public static final < T > List < T > create ( T ... items ) { List < T > list = new ArrayList < > ( ) ; Collections . addAll ( list , items ) ; return list ; }
Creates a list that is populated with items
14,422
public static final < T > void remove ( Collection < T > collection , T ... items ) { for ( T t : items ) { collection . remove ( t ) ; } }
Removes items from collection
14,423
public static final String print ( String delim , Collection < ? > collection ) { return print ( null , delim , null , null , null , collection ) ; }
Returns collection items delimited
14,424
public static final String print ( String start , String delim , String quotStart , String quotEnd , String end , Collection < ? > collection ) { try { StringBuilder out = new StringBuilder ( ) ; print ( out , start , delim , quotStart , quotEnd , end , collection ) ; return out . toString ( ) ; } catch ( IOException ex ) { throw new IllegalArgumentException ( ex ) ; } }
Returns collection items delimited with given strings . If any of delimiters is null it is ignored .
14,425
public static final String print ( String delim , Object ... array ) { return print ( null , delim , null , null , null , array ) ; }
Returns array items delimited
14,426
public static final String print ( String start , String delim , String quotStart , String quotEnd , String end , Object ... array ) { try { StringBuilder out = new StringBuilder ( ) ; print ( out , start , delim , quotStart , quotEnd , end , array ) ; return out . toString ( ) ; } catch ( IOException ex ) { throw new IllegalArgumentException ( ex ) ; } }
Returns array items delimited with given strings . If any of delimiters is null it is ignored .
14,427
public static < T > Collection < T > addAll ( Collection < T > list , T ... array ) { for ( T item : array ) { list . add ( item ) ; } return list ; }
Adds array members to list
14,428
public static < T > T [ ] toArray ( Collection < T > col , Class < T > cls ) { T [ ] arr = ( T [ ] ) Array . newInstance ( cls , col . size ( ) ) ; return col . toArray ( arr ) ; }
Converts Collection to array .
14,429
public static final VirtualCircuit create ( ByteChannel ch1 , ByteChannel ch2 , int capacity , boolean direct ) { if ( ( ch1 instanceof SelectableChannel ) && ( ch2 instanceof SelectableChannel ) ) { SelectableChannel sc1 = ( SelectableChannel ) ch1 ; SelectableChannel sc2 = ( SelectableChannel ) ch2 ; return new SelectableVirtualCircuit ( sc1 , sc2 , capacity , direct ) ; } else { if ( ( ch1 instanceof SelectableBySelector ) && ( ch2 instanceof SelectableBySelector ) ) { SelectableBySelector sbs1 = ( SelectableBySelector ) ch1 ; SelectableBySelector sbs2 = ( SelectableBySelector ) ch2 ; return new SelectableVirtualCircuit ( sbs1 . getSelector ( ) , sbs2 . getSelector ( ) , ch1 , ch2 , capacity , direct ) ; } else { return new ByteChannelVirtualCircuit ( ch1 , ch2 , capacity , direct ) ; } } }
Creates either SelectableVirtualCircuit or ByteChannelVirtualCircuit depending on channel .
14,430
public static List < String > checkTopicRootElement ( final ServerSettingsWrapper serverSettings , final BaseTopicWrapper < ? > topic , final Document doc ) { final List < String > xmlErrors = new ArrayList < String > ( ) ; final ServerEntitiesWrapper serverEntities = serverSettings . getEntities ( ) ; if ( isTopicANormalTopic ( topic , serverSettings ) ) { if ( ! doc . getDocumentElement ( ) . getNodeName ( ) . equals ( DocBookUtilities . TOPIC_ROOT_NODE_NAME ) ) { xmlErrors . add ( "Topics must be a <" + DocBookUtilities . TOPIC_ROOT_NODE_NAME + ">." ) ; } } else { if ( topic . hasTag ( serverEntities . getRevisionHistoryTagId ( ) ) ) { if ( ! doc . getDocumentElement ( ) . getNodeName ( ) . equals ( "appendix" ) ) { xmlErrors . add ( "Revision History topics must be an <appendix>." ) ; } final NodeList revHistoryList = doc . getElementsByTagName ( "revhistory" ) ; if ( revHistoryList . getLength ( ) == 0 ) { xmlErrors . add ( "No <revhistory> element found. A <revhistory> must exist for Revision Histories." ) ; } } else if ( topic . hasTag ( serverEntities . getLegalNoticeTagId ( ) ) ) { if ( ! doc . getDocumentElement ( ) . getNodeName ( ) . equals ( "legalnotice" ) ) { xmlErrors . add ( "Legal Notice topics must be a <legalnotice>." ) ; } } else if ( topic . hasTag ( serverEntities . getAuthorGroupTagId ( ) ) ) { if ( ! doc . getDocumentElement ( ) . getNodeName ( ) . equals ( "authorgroup" ) ) { xmlErrors . add ( "Author Group topics must be an <authorgroup>." ) ; } } else if ( topic . hasTag ( serverEntities . getAbstractTagId ( ) ) ) { if ( ! doc . getDocumentElement ( ) . getNodeName ( ) . equals ( "abstract" ) ) { xmlErrors . add ( "Abstract topics must be an <abstract>." ) ; } } else if ( topic . hasTag ( serverEntities . getInfoTagId ( ) ) ) { if ( DocBookVersion . DOCBOOK_50 . getId ( ) . equals ( topic . getXmlFormat ( ) ) ) { if ( ! doc . getDocumentElement ( ) . getNodeName ( ) . equals ( "info" ) ) { xmlErrors . add ( "Info topics must be an <info>." ) ; } } else { if ( ! doc . getDocumentElement ( ) . getNodeName ( ) . equals ( "sectioninfo" ) ) { xmlErrors . add ( "Info topics must be a <sectioninfo>." ) ; } } } } return xmlErrors ; }
Checks that the topics root element matches the topic type .
14,431
public static List < String > checkTopicContentBasedOnType ( final ServerSettingsWrapper serverSettings , final BaseTopicWrapper < ? > topic , final Document doc , boolean skipNestedSectionValidation ) { final ServerEntitiesWrapper serverEntities = serverSettings . getEntities ( ) ; final List < String > xmlErrors = new ArrayList < String > ( ) ; if ( topic . hasTag ( serverEntities . getRevisionHistoryTagId ( ) ) ) { final String revHistoryErrors = DocBookUtilities . validateRevisionHistory ( doc , DATE_FORMATS ) ; if ( revHistoryErrors != null ) { xmlErrors . add ( revHistoryErrors ) ; } } else if ( topic . hasTag ( serverEntities . getInfoTagId ( ) ) ) { if ( DocBookUtilities . checkForInvalidInfoElements ( doc ) ) { xmlErrors . add ( "Info topics cannot contain <title>, <subtitle> or <titleabbrev> elements." ) ; } } else if ( isTopicANormalTopic ( topic , serverSettings ) ) { final List < Node > subSections = XMLUtilities . getDirectChildNodes ( doc . getDocumentElement ( ) , "section" ) ; if ( subSections . size ( ) > 0 && ! skipNestedSectionValidation ) { xmlErrors . add ( "Nested sections cannot be used in topics. Please consider breaking the content into multiple topics." ) ; } } return xmlErrors ; }
Check a topic and return an error messages if the content doesn t match the topic type .
14,432
public static boolean isTopicANormalTopic ( final BaseTopicWrapper < ? > topic , final ServerSettingsWrapper serverSettings ) { return ! ( topic . hasTag ( serverSettings . getEntities ( ) . getRevisionHistoryTagId ( ) ) || topic . hasTag ( serverSettings . getEntities ( ) . getLegalNoticeTagId ( ) ) || topic . hasTag ( serverSettings . getEntities ( ) . getAuthorGroupTagId ( ) ) || topic . hasTag ( serverSettings . getEntities ( ) . getInfoTagId ( ) ) || topic . hasTag ( serverSettings . getEntities ( ) . getAbstractTagId ( ) ) ) ; }
Check to see if a Topic is a normal topic instead of a Revision History or Legal Notice
14,433
public static boolean doesTopicHaveValidXMLForInitialContent ( final SpecTopic specTopic , final BaseTopicWrapper < ? > topic ) { boolean valid = true ; final InitialContent initialContent = ( InitialContent ) specTopic . getParent ( ) ; final int numSpecTopics = initialContent . getNumberOfSpecTopics ( ) + initialContent . getNumberOfCommonContents ( ) ; final boolean isOnlyChild = initialContent . getParent ( ) . getNumberOfChildLevels ( ) == 1 && initialContent . getParent ( ) . getNumberOfSpecTopics ( ) == 0 && initialContent . getParent ( ) . getNumberOfCommonContents ( ) == 0 && numSpecTopics == 1 ; if ( numSpecTopics >= 1 ) { final String condition = specTopic . getConditionStatement ( true ) ; try { final Document doc = XMLUtilities . convertStringToDocument ( topic . getXml ( ) ) ; DocBookUtilities . processConditions ( condition , doc ) ; final List < org . w3c . dom . Node > invalidElements = XMLUtilities . getDirectChildNodes ( doc . getDocumentElement ( ) , "section" ) ; final List < org . w3c . dom . Node > invalidElementsIfMultipleChildren = XMLUtilities . getDirectChildNodes ( doc . getDocumentElement ( ) , "refentry" , "simplesect" ) ; final List < org . w3c . dom . Node > invalidInfoElements = XMLUtilities . getDirectChildNodes ( doc . getDocumentElement ( ) , "info" , "sectioninfo" ) ; if ( numSpecTopics > 1 && invalidElements . size ( ) > 0 ) { valid = false ; } else if ( ! isOnlyChild && invalidElementsIfMultipleChildren . size ( ) > 0 ) { valid = false ; } else if ( ( initialContent . getFirstSpecNode ( ) != specTopic && invalidInfoElements . size ( ) > 0 ) || ( initialContent . getParent ( ) . getInfoTopic ( ) != null && invalidInfoElements . size ( ) > 0 ) ) { valid = false ; } } catch ( Exception e ) { log . debug ( e . getMessage ( ) ) ; } } return valid ; }
Checks a topics XML to make sure it has content that can be used as front matter for a level .
14,434
public static RuntimeException propagate ( final Exception exception ) { if ( RuntimeException . class . isAssignableFrom ( exception . getClass ( ) ) ) { return ( RuntimeException ) exception ; } return new RuntimeException ( "Repropagated " + exception . getMessage ( ) , exception ) ; }
Propagate a Throwable as a RuntimeException . The Runtime exception bases it s message not the message of the Throwable and the Throwable is set as it s cause . This can be used to deal with exceptions in lambdas etc .
14,435
public void dispatch ( final NessEvent event ) { if ( event == null ) { LOG . trace ( "Dropping null event" ) ; } else { for ( final NessEventReceiver receiver : eventReceivers ) { try { if ( receiver . accept ( event ) ) { receiver . receive ( event ) ; } } catch ( Exception e ) { LOG . error ( e , "Exception during event handling by %s of event %s" , receiver , event ) ; } } } }
Dispatch an event for distribution to the local Event receivers .
14,436
public void onEvent ( final WatchEvent < Path > event ) { Kind kind = event . kind ( ) ; if ( StandardWatchEventKind . ENTRY_CREATE . equals ( kind ) ) { File file = new File ( event . context ( ) . toString ( ) ) ; listener . fileCreated ( file ) ; } else if ( StandardWatchEventKind . ENTRY_DELETE . equals ( kind ) ) { File file = new File ( event . context ( ) . toString ( ) ) ; listener . fileDeleted ( file ) ; } else if ( StandardWatchEventKind . ENTRY_MODIFY . equals ( kind ) ) { File file = new File ( event . context ( ) . toString ( ) ) ; listener . fileChanged ( file ) ; } }
Forwards watch events to the listener .
14,437
public String getBasePath ( ) { String basePath = DBConstants . BLANK ; basePath = this . getField ( ProgramControl . BASE_DIRECTORY ) . toString ( ) ; PropertyOwner propertyOwner = null ; if ( this . getOwner ( ) instanceof PropertyOwner ) propertyOwner = ( PropertyOwner ) this . getOwner ( ) ; try { basePath = Utility . replaceResources ( basePath , null , Utility . propertiesToMap ( System . getProperties ( ) ) , propertyOwner ) ; } catch ( SecurityException e ) { basePath = Utility . replaceResources ( basePath , null , null , propertyOwner ) ; } return basePath ; }
Get the base path . Replace all the params first .
14,438
private ResponseType getResponseType ( int code ) throws IOException { try { return ResponseType . values ( ) [ code ] ; } catch ( Exception e ) { throw new IOException ( "Unrecognized response code: " + code ) ; } }
Returns the response type from the status value .
14,439
public DataPoint add ( DataPoint another ) { if ( type == Type . NONE ) { _cloneFrom ( another ) ; } else { if ( another . type != Type . NONE ) { add ( another . value ( ) ) ; } } return this ; }
Adds value from another data point .
14,440
public DataPoint add ( long value ) { switch ( type ) { case MINIMUM : this . value = Math . min ( this . value , value ) ; break ; case MAXIMUM : this . value = Math . max ( this . value , value ) ; break ; case AVERAGE : case SUM : this . value += value ; this . numPoints ++ ; break ; default : throw new IllegalStateException ( "Unknown type [" + type + "]!" ) ; } return this ; }
Adds a value to the data point .
14,441
public DataPoint set ( DataPoint another ) { if ( type == Type . NONE ) { _cloneFrom ( another ) ; } else { if ( another . type != Type . NONE ) { set ( another . value ( ) ) ; } } return this ; }
Sets data point s value using another data point .
14,442
public long value ( ) { switch ( type ) { case AVERAGE : return numPoints != 0 ? value / numPoints : 0 ; case NONE : return 0 ; case MAXIMUM : case MINIMUM : case SUM : return value ; default : throw new IllegalStateException ( "Unknown type [" + type + "]!" ) ; } }
Gets the data point value .
14,443
public static synchronized String generateKey ( ) { String code = "" ; long nr = System . currentTimeMillis ( ) ; if ( nr <= lastnr ) { nr = lastnr + 1 ; } lastnr = nr ; String s = String . valueOf ( nr ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { code += codeArray [ randomizer . nextInt ( 6 ) ] [ s . charAt ( i ) - 48 ] ; } return code ; }
Generates a random key which is guaranteed to be unique within the application .
14,444
public void addServiceType ( DescriptionType descriptionType ) { String interfacens ; String interfacename ; QName qname ; String name ; ServiceType serviceType = wsdlFactory . createServiceType ( ) ; descriptionType . getImportOrIncludeOrTypes ( ) . add ( wsdlFactory . createService ( serviceType ) ) ; name = this . getControlProperty ( MessageControl . SERVICE_NAME ) ; serviceType . setName ( name ) ; interfacens = this . getNamespace ( ) ; ; interfacename = this . getControlProperty ( MessageControl . INTERFACE_NAME ) ; qname = new QName ( interfacens , interfacename ) ; serviceType . setInterface ( qname ) ; EndpointType endpointType = wsdlFactory . createEndpointType ( ) ; serviceType . getEndpointOrFeatureOrProperty ( ) . add ( wsdlFactory . createEndpoint ( endpointType ) ) ; String address = this . getURIValue ( this . getRecord ( MessageControl . MESSAGE_CONTROL_FILE ) . getField ( MessageControl . WEB_SERVICES_SERVER ) . toString ( ) ) ; endpointType . setAddress ( address ) ; interfacens = this . getNamespace ( ) ; ; interfacename = this . getControlProperty ( MessageControl . BINDING_NAME ) ; qname = new QName ( interfacens , interfacename ) ; endpointType . setBinding ( qname ) ; name = this . getControlProperty ( MessageControl . ENDPOINT_NAME ) ; endpointType . setName ( name ) ; }
AddServiceType Method .
14,445
public void addBindingType ( DescriptionType descriptionType ) { String interfacens ; String interfacename ; QName qname ; String value ; String name ; BindingType bindingType = wsdlFactory . createBindingType ( ) ; descriptionType . getImportOrIncludeOrTypes ( ) . add ( wsdlFactory . createBinding ( bindingType ) ) ; name = this . getControlProperty ( MessageControl . BINDING_NAME ) ; bindingType . setName ( name ) ; interfacens = this . getNamespace ( ) ; interfacename = this . getControlProperty ( MessageControl . INTERFACE_NAME ) ; qname = new QName ( interfacens , interfacename ) ; bindingType . setInterface ( qname ) ; bindingType . setType ( this . getControlProperty ( WSOAP_BINDING_URI ) ) ; interfacens = this . getControlProperty ( SOAP_SENDING_URI ) ; interfacename = "protocol" ; qname = new QName ( interfacens , interfacename ) ; value = this . getControlProperty ( SOAP_URI ) ; bindingType . getOtherAttributes ( ) . put ( qname , value ) ; this . addBindingOperationTypes ( bindingType ) ; }
AddBindingType Method .
14,446
public void addInterfaceType ( DescriptionType descriptionType ) { InterfaceType interfaceType = wsdlFactory . createInterfaceType ( ) ; descriptionType . getImportOrIncludeOrTypes ( ) . add ( wsdlFactory . createInterface ( interfaceType ) ) ; String interfaceName = this . getControlProperty ( MessageControl . INTERFACE_NAME ) ; interfaceType . setName ( interfaceName ) ; this . addInterfaceOperationTypes ( interfaceType ) ; }
AddInterfaceType Method .
14,447
private String format ( double fileSize , Units units ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( numberFormat . format ( fileSize ) ) ; builder . append ( ' ' ) ; builder . append ( units . name ( ) ) ; return builder . toString ( ) ; }
Build file size representation for given numeric value and units .
14,448
public boolean includeRecord ( Record recFileHdr , Record recClassInfo , String strPackage ) { String strProject = this . getProperty ( "project" ) ; String strType = this . getProperty ( "type" ) ; String [ ] classLists = null ; String classList = this . getProperty ( "classList" ) ; if ( classList != null ) classLists = classList . split ( "," ) ; String database = this . getProperty ( "database" ) ; if ( recClassInfo . getField ( ClassInfo . BASE_CLASS_NAME ) . toString ( ) . equalsIgnoreCase ( "QueryRecord" ) ) return false ; if ( recClassInfo . getField ( ClassInfo . BASE_CLASS_NAME ) . toString ( ) . indexOf ( "Query" ) != - 1 ) return false ; String strClassPackage = this . getFullPackageName ( recClassInfo . getField ( ClassInfo . CLASS_PROJECT_ID ) . toString ( ) , recClassInfo . getField ( ClassInfo . CLASS_PACKAGE ) . toString ( ) ) ; String strClassProject = classProjectIDs . get ( recClassInfo . getField ( ClassInfo . CLASS_PROJECT_ID ) . toString ( ) ) ; String strClassType = recFileHdr . getField ( FileHdr . TYPE ) . toString ( ) ; if ( strClassPackage != null ) if ( strPackage != null ) if ( ! strClassPackage . matches ( this . patternToRegex ( strPackage ) ) ) return false ; if ( strClassType != null ) if ( strType != null ) if ( ! strClassType . toUpperCase ( ) . contains ( strType . toUpperCase ( ) ) ) return false ; if ( classLists != null ) { String className = recClassInfo . getField ( ClassInfo . CLASS_NAME ) . toString ( ) ; boolean match = false ; for ( String classMatch : classLists ) { if ( className . equalsIgnoreCase ( classMatch ) ) match = true ; } if ( ! match ) return false ; } if ( strClassProject == null ) return false ; if ( strProject != null ) return strClassProject . matches ( this . patternToRegex ( strProject ) ) ; if ( database != null ) if ( ! database . equalsIgnoreCase ( recFileHdr . getField ( FileHdr . DATABASE_NAME ) . toString ( ) ) ) return false ; return true ; }
Include this record? .
14,449
public String patternToRegex ( String string ) { if ( string != null ) if ( ! string . contains ( "[" ) ) if ( ! string . contains ( "{" ) ) if ( ! string . contains ( "\\." ) ) { string = string . replace ( "." , "\\." ) ; string = string . replace ( "*" , ".*" ) ; } return string ; }
Kind of convert file filter to regex .
14,450
public String getFullPackageName ( String classProjectID , String classPackageName ) { if ( classProjectID == null ) return DBConstants . BLANK ; String packageName = classProjectPackages . get ( classProjectID ) ; if ( packageName == null ) return null ; if ( packageName . startsWith ( "." ) ) packageName = Constants . ROOT_PACKAGE . substring ( 0 , Constants . ROOT_PACKAGE . length ( ) - 1 ) + packageName ; if ( classPackageName == null ) classPackageName = DBConstants . BLANK ; if ( classPackageName . startsWith ( "." ) ) packageName = packageName + classPackageName ; else if ( classPackageName . length ( ) > 0 ) packageName = classPackageName ; return packageName ; }
GetFullPackageName Method .
14,451
public InputValidator < I > check ( Validation < I > validation , ValidationMessage message ) throws ValidationException { try { if ( ! validation . check ( this . input ) ) { throw new ValidationException ( message . format ( this . input ) ) ; } } catch ( ValidationException e ) { throw e ; } catch ( Exception e ) { throw new ValidationException ( message . format ( this . input ) , e ) ; } return this ; }
Checks the given validation .
14,452
public final List < String > positionalValues ( ) { return attributes . entrySet ( ) . stream ( ) . filter ( kv -> kv . getKey ( ) . startsWith ( "$" ) ) . map ( Map . Entry :: getValue ) . collect ( Collectors . toList ( ) ) ; }
Gets a list of any positional values .
14,453
private StringBuilder appendAttributeValue ( final String value , final StringBuilder buf ) { if ( value . contains ( "\"" ) ) { buf . append ( "\'" ) . append ( escapeAttribute ( value ) ) . append ( "\'" ) ; } else if ( value . contains ( " " ) || value . contains ( "\'" ) || value . contains ( "=" ) ) { buf . append ( "\"" ) . append ( escapeAttribute ( value ) ) . append ( "\"" ) ; } else { buf . append ( escapeAttribute ( value ) ) ; } return buf ; }
Appends an attribute value with appropriate quoting .
14,454
public static Shortcode parse ( final String shortcode ) throws ParseException { String exp = shortcode . trim ( ) ; if ( exp . length ( ) < 3 ) { throw new ParseException ( String . format ( "Invalid shortcode ('%s')" , exp ) , 0 ) ; } if ( exp . charAt ( 0 ) != '[' ) { throw new ParseException ( "Expecting '['" , 0 ) ; } int end = exp . indexOf ( ']' ) ; if ( end == - 1 ) { throw new ParseException ( "Expecting ']" , 0 ) ; } Shortcode startTag = ShortcodeParser . parseStart ( exp . substring ( 0 , end + 1 ) ) ; end = exp . lastIndexOf ( "[/" ) ; if ( end > 0 ) { if ( exp . endsWith ( "[/" + startTag . name + "]" ) ) { int start = shortcode . indexOf ( "]" ) ; return startTag . withContent ( exp . substring ( start + 1 , end ) ) ; } else { throw new ParseException ( "Invalid shortcode end" , 0 ) ; } } else { return startTag ; } }
Parses a shortcode
14,455
public static void parse ( final String str , final ShortcodeParser . Handler handler ) { ShortcodeParser . parse ( str , handler ) ; }
Parse an arbitrary string .
14,456
public void startDocument ( ) throws SAXException { LOG . info ( "BEGIN ContentImport" ) ; LOG . info ( "IMPORT USER: {}" , this . session . getUserID ( ) ) ; this . startTime = System . nanoTime ( ) ; }
Prints out information statements and sets the startTimer .
14,457
public void endDocument ( ) throws SAXException { LOG . info ( "Content Processing finished, saving..." ) ; try { this . session . save ( ) ; } catch ( final RepositoryException e ) { throw new AssertionError ( "Saving failed" , e ) ; } if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "Content imported in {} ms" , ( System . nanoTime ( ) - this . startTime ) / 1_000_000 ) ; LOG . info ( "END ContentImport" ) ; } }
Persists the changes in the repository and prints out information such as processing time .
14,458
public void endElement ( final String uri , final String localName , final String qName ) throws SAXException { LOG . trace ( "endElement uri={} localName={} qName={}" , uri , localName , qName ) ; if ( this . isNotInkstandNamespace ( uri ) ) { return ; } switch ( localName ) { case "rootNode" : LOG . debug ( "Closing rootNode" ) ; this . nodeStack . pop ( ) ; break ; case "node" : LOG . debug ( "Closing node" ) ; this . nodeStack . pop ( ) ; break ; case "mixin" : LOG . debug ( "Closing mixin" ) ; break ; case "property" : this . endElementProperty ( ) ; break ; default : break ; } }
Depending on the element which has to be in the correct namespace the method adds a property to the node or removes completed nodes from the node stack .
14,459
public void characters ( final char [ ] chr , final int start , final int length ) throws SAXException { final String text = new String ( chr ) . substring ( start , start + length ) ; LOG . trace ( "characters; '{}'" , text ) ; final String trimmedText = text . trim ( ) ; LOG . info ( "text: '{}'" , trimmedText ) ; this . textStack . push ( trimmedText ) ; }
Detects text by trimming the effective content of the char array .
14,460
private void startElementRootNode ( final Attributes attributes ) { LOG . debug ( "Found rootNode" ) ; try { this . rootNode = this . newNode ( null , attributes ) ; this . nodeStack . push ( this . rootNode ) ; } catch ( final RepositoryException e ) { throw new AssertionError ( "Could not create node" , e ) ; } }
Invoked on rootNode element .
14,461
private void startElementNode ( final Attributes attributes ) { LOG . debug ( "Found node" ) ; try { this . nodeStack . push ( this . newNode ( this . nodeStack . peek ( ) , attributes ) ) ; } catch ( final RepositoryException e ) { throw new AssertionError ( "Could not create node" , e ) ; } }
Invoked on node element .
14,462
private void startElementMixin ( final Attributes attributes ) { LOG . debug ( "Found mixin declaration" ) ; try { this . addMixin ( this . nodeStack . peek ( ) , attributes ) ; } catch ( final RepositoryException e ) { throw new AssertionError ( "Could not add mixin type" , e ) ; } }
Invoked on mixin element .
14,463
public static void storeByteArrayToFile ( final byte [ ] data , final File file ) throws IOException { try ( FileOutputStream fos = new FileOutputStream ( file ) ; BufferedOutputStream bos = new BufferedOutputStream ( fos ) ; ) { bos . write ( data ) ; bos . flush ( ) ; } }
Saves a byte array to the given file .
14,464
public static void readSourceFileAndWriteDestFile ( final String srcfile , final String destFile ) throws IOException { try ( FileInputStream fis = new FileInputStream ( srcfile ) ; FileOutputStream fos = new FileOutputStream ( destFile ) ; BufferedInputStream bis = new BufferedInputStream ( fis ) ; BufferedOutputStream bos = new BufferedOutputStream ( fos ) ; ) { final int availableLength = bis . available ( ) ; final byte [ ] totalBytes = new byte [ availableLength ] ; bis . read ( totalBytes , 0 , availableLength ) ; bos . write ( totalBytes , 0 , availableLength ) ; } }
Writes the source file with the best performance to the destination file .
14,465
public static void write ( final InputStream inputStream , final OutputStream outputStream ) throws FileNotFoundException , IOException { int counter ; final byte byteArray [ ] = new byte [ FileConst . BLOCKSIZE ] ; while ( ( counter = inputStream . read ( byteArray ) ) != - 1 ) { outputStream . write ( byteArray , 0 , counter ) ; } }
Writes the given input stream to the output stream .
14,466
public static void writeByteArrayToFile ( final File file , final byte [ ] byteArray ) throws IOException { try ( FileOutputStream fos = new FileOutputStream ( file ) ; BufferedOutputStream bos = new BufferedOutputStream ( fos ) ) { bos . write ( byteArray ) ; } catch ( final FileNotFoundException ex ) { throw ex ; } catch ( final IOException ex ) { throw ex ; } }
Writes the given byte array to the given file .
14,467
public static void writeByteArrayToFile ( final String filename , final byte [ ] byteArray ) throws IOException { final File file = new File ( filename ) ; writeByteArrayToFile ( file , byteArray ) ; }
Writes the given byte array to a file .
14,468
public boolean supports ( TherianContext context , Copy < ? extends Object , ? extends Map > copy ) { if ( ! super . supports ( context , copy ) ) { return false ; } final Type targetKeyType = getKeyType ( copy . getTargetPosition ( ) ) ; final Position . ReadWrite < ? > targetKey = Positions . readWrite ( targetKeyType ) ; return getProperties ( context , copy . getSourcePosition ( ) ) . anyMatch ( propertyName -> context . supports ( Convert . to ( targetKey , Positions . readOnly ( propertyName ) ) ) ) ; }
If at least one property name can be converted to an assignable key say the operation is supported and we ll give it a shot .
14,469
public JSONObject generateJSONRequest ( String sourceName , List < String > sourceNodes , String targetName , List < String > targetNodes ) throws JSONException { Context sourceContext = new Context ( "SourceContext" , sourceName , sourceNodes ) ; Context targetContext = new Context ( "TargetContext" , targetName , targetNodes ) ; JSONObject jRequest = new JSONObject ( ) ; JSONObject jContexts = new JSONObject ( ) ; JSONArray jContextList = new JSONArray ( ) ; JSONObject jsourceContext = sourceContext . toJsonObject ( ) ; JSONObject jtargetContext = targetContext . toJsonObject ( ) ; jContextList . put ( jsourceContext ) ; jContextList . put ( jtargetContext ) ; jContexts . put ( "Contexts" , jContextList ) ; jRequest . put ( "parameters" , jContexts ) ; return jRequest ; }
Generates JSON request from input parameters
14,470
public Correspondence convert ( JSONObject jResponse ) throws JSONException { Correspondence correspondence = null ; if ( jResponse . getJSONObject ( "response" ) . has ( "Correspondence" ) ) { JSONObject jResponseItem = jResponse . getJSONObject ( "response" ) ; JSONArray jcorrespondenceItems = jResponseItem . getJSONArray ( "Correspondence" ) ; List < CorrespondenceItem > correspondenceItems = new ArrayList < CorrespondenceItem > ( ) ; for ( int i = 0 ; i < jcorrespondenceItems . length ( ) ; i ++ ) { JSONObject jCorrespondenceItem = jcorrespondenceItems . getJSONObject ( i ) ; String relation = jCorrespondenceItem . optString ( "Relation" ) ; String source = jCorrespondenceItem . optString ( "Source" ) ; String target = jCorrespondenceItem . optString ( "Target" ) ; char cRelation = relation . charAt ( 0 ) ; try { correspondenceItems . add ( new CorrespondenceItem ( source , target , cRelation ) ) ; } catch ( UnknownRelationException ex ) { Logger . getLogger ( MatchMethods . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } correspondence = new Correspondence ( correspondenceItems ) ; } return correspondence ; }
Converts from JSON Correspondence to Java Correspondence
14,471
public void init ( RemoteTask server , BaseMessageQueue baseMessageQueue ) throws RemoteException { super . init ( baseMessageQueue ) ; m_sendQueue = server . createRemoteSendQueue ( baseMessageQueue . getQueueName ( ) , baseMessageQueue . getQueueType ( ) ) ; }
Creates new MessageSender .
14,472
public void setTransmitters ( Collection < Transmitter > transmitters ) { if ( transmitters == null ) { this . transmitters = null ; return ; } int size = transmitters . size ( ) ; if ( size == 0 ) { this . transmitters = null ; return ; } this . transmitters = transmitters . toArray ( new Transmitter [ ] { } ) ; }
Sets the transmitters for this rule . Any previous values are discarded .
14,473
public MDecimal getAh ( ) { MDecimal result = new MDecimal ( currentUnit . getConverterTo ( AMPERE_HOUR ) . convert ( doubleValue ( ) ) ) ; logger . trace ( MMarker . GETTER , "Converting from {} to Ampere hours : {}" , currentUnit , result ) ; return result ; }
Ampere - hours
14,474
public MDecimal getmAh ( ) { MDecimal result = new MDecimal ( currentUnit . getConverterTo ( MILLI_AMPERE_HOUR ) . convert ( doubleValue ( ) ) ) ; logger . trace ( MMarker . GETTER , "Converting from {} to milli Ampere hours : {}" , currentUnit , result ) ; return result ; }
Milli Ampere - hours
14,475
public void setOwner ( ListenerOwner owner ) { if ( owner == null ) { this . saveValue ( m_recordOwnerCache ) ; m_recordOwnerCache = null ; } super . setOwner ( owner ) ; if ( owner != null ) this . retrieveValue ( ) ; }
Set the field that owns this handler .
14,476
public void saveValue ( ComponentParent recordOwner ) { if ( recordOwner != null ) { BaseField field = this . getOwner ( ) ; String strCommand = ( ( ComponentParent ) recordOwner ) . getParentScreen ( ) . popHistory ( 1 , false ) ; if ( m_recordOwnerCache != null ) if ( strCommand != null ) if ( strCommand . indexOf ( m_recordOwnerCache . getClass ( ) . getName ( ) ) != - 1 ) { Map < String , Object > properties = new Hashtable < String , Object > ( ) ; Util . parseArgs ( properties , strCommand ) ; properties . put ( field . getFieldName ( ) , field . toString ( ) ) ; strCommand = Utility . propertiesToURL ( null , properties ) ; } ( ( ComponentParent ) recordOwner ) . getParentScreen ( ) . pushHistory ( strCommand , false ) ; } }
Save the current value of this field to the registration database . and change the URL on the push - down stack to take this into consideration .
14,477
public void copyProviderToCreator ( Resource . Provider provider , Resource . Creator creator ) { provider . stream ( ) . forEach ( ( ConsumerWithThrowable < Resource . Readable , IOException > ) resource -> copyResourceWithStreams ( resource , creator . create ( resource . getPath ( ) ) ) ) ; }
Copy all resource in provider over to some creator .
14,478
public static void writeResource ( final Resource . Writable resource , final CharSequence content ) throws IOException { resource . useWriter ( writer -> IOUtils . write ( content . toString ( ) , writer ) ) ; }
Write content to a Writable Resource .
14,479
public static void copyResource ( Resource . Readable readable , Resource . Writable writable ) throws IOException { readable . useReader ( reader -> writable . useWriter ( writer -> IOUtils . copy ( reader , writer ) ) ) ; }
Copy the content of one resources to another .
14,480
protected static String message ( Object message ) { if ( message == null ) { return null ; } if ( ! ( message instanceof Throwable ) ) { return message . toString ( ) ; } Throwable t = ( Throwable ) message ; if ( t . getCause ( ) == null ) { return t . toString ( ) ; } int nestingLevel = 0 ; StringBuilder sb = new StringBuilder ( ) ; for ( ; ; ) { sb . append ( t . getClass ( ) . getName ( ) ) ; sb . append ( ":" ) ; sb . append ( " " ) ; if ( ++ nestingLevel == 8 ) { sb . append ( "..." ) ; break ; } if ( t . getCause ( ) == null ) { String s = t . getMessage ( ) ; if ( s == null ) { t . getClass ( ) . getCanonicalName ( ) ; } sb . append ( s ) ; break ; } t = t . getCause ( ) ; } return sb . toString ( ) ; }
Normalize log message . This method returns message to string ; if message is a Throwable and has not null cause returns cause hierarchy formed from cause class name .
14,481
private static boolean isArrayLike ( Object object ) { return object != null && ( object . getClass ( ) . isArray ( ) || object instanceof Collection ) ; }
An object is array like if is an actual array or a collection .
14,482
public static < E extends Enum < E > > EnumSet < E > getSet ( Class < E > elementType , int flag ) { EnumSet < E > set = EnumSet . noneOf ( elementType ) ; E [ ] enumConstants = elementType . getEnumConstants ( ) ; if ( enumConstants . length > Integer . SIZE ) { throw new IllegalArgumentException ( elementType + " contains too many enums for int" ) ; } for ( int ii = 0 ; ii < enumConstants . length ; ii ++ ) { if ( ( flag & ( 1 << ii ) ) != 0 ) { set . add ( enumConstants [ ii ] ) ; } } return set ; }
Returns EnumSet constructed from bit flag . Bit flags bit position is according to Enum ordinal .
14,483
public static String getCaller ( ) { StackTraceElement [ ] stes = new Exception ( ) . getStackTrace ( ) ; String caller ; if ( stes . length > 2 ) { StackTraceElement callerSte = stes [ 2 ] ; caller = callerSte . getClassName ( ) + "." + callerSte . getMethodName ( ) ; } else { caller = "<unknown>" ; } return caller ; }
Gets the calling method s name .
14,484
public static String formatUsedMemory ( ) { Runtime runtime = Runtime . getRuntime ( ) ; long usedMemory = Math . max ( 0 , runtime . totalMemory ( ) - runtime . freeMemory ( ) ) ; return MemoryUnitFormat . getMemoryUnitInstance ( ) . format ( usedMemory ) ; }
Formats the currently used memory in human readable format .
14,485
public static void log ( Level level , String message ) { Logger . getLogger ( "LEX4J" ) . log ( level , message ) ; }
Convenience method for logging within the LEX4J library
14,486
public void accept ( double value ) { writeLock . lock ( ) ; try { eliminate ( ) ; int count = count ( ) ; if ( count >= size ) { grow ( ) ; } assign ( endMod ( ) , value ) ; endIncr ( ) ; } finally { writeLock . unlock ( ) ; } }
Adds new value to sliding average
14,487
public double average ( ) { readLock . lock ( ) ; try { double s = 0 ; PrimitiveIterator . OfInt it = modIterator ( ) ; while ( it . hasNext ( ) ) { s += ring [ it . nextInt ( ) ] ; } return s / ( count ( ) ) ; } finally { readLock . unlock ( ) ; } }
Returns average by calculating cell by cell
14,488
protected File createTempFile ( ) throws IOException { final File tempFile = newFile ( ) ; if ( forceContent && contentUrl == null ) { throw new AssertionError ( "ContentUrl is not set" ) ; } else if ( contentUrl == null ) { createEmptyFile ( tempFile ) ; } else { try ( InputStream inputStream = contentUrl . openStream ( ) ) { Files . copy ( inputStream , tempFile . toPath ( ) ) ; } } return tempFile ; }
Creates the file including content . Override this method to implement a custom mechanism to create the temporary file
14,489
public List < V > returnCollectionItemsWithState ( final List < Integer > states ) { if ( states == null ) throw new IllegalArgumentException ( "states cannot be null" ) ; final List < V > retValue = new ArrayList < V > ( ) ; for ( final V item : getItems ( ) ) { if ( states . contains ( item . getState ( ) ) ) retValue . add ( item ) ; } return retValue ; }
Get a collection of REST entities wrapped as collection items that have a particular state
14,490
public List < T > returnItemsWithState ( final List < Integer > states ) { if ( states == null ) throw new IllegalArgumentException ( "states cannot be null" ) ; final List < T > retValue = new ArrayList < T > ( ) ; for ( final V item : getItems ( ) ) { if ( states . contains ( item . getState ( ) ) ) retValue . add ( item . getItem ( ) ) ; } return retValue ; }
Get a collection of REST entities that have a particular state
14,491
public PropertyOwner retrieveUserProperties ( String strRegistrationKey ) { if ( this . getDefaultApplication ( ) != null ) if ( this . getDefaultApplication ( ) != null ) return this . getDefaultApplication ( ) . retrieveUserProperties ( strRegistrationKey ) ; return null ; }
Get the Environment properties object .
14,492
public void setDefaultApplication ( App application ) { m_applicationDefault = application ; if ( application != null ) if ( ( ! ( m_applicationDefault instanceof MainApplication ) ) || ( application == m_applicationDefault ) ) { if ( m_args != null ) Util . parseArgs ( m_properties , m_args ) ; if ( m_properties . get ( DBParams . LOCAL ) == null ) m_properties . put ( DBParams . LOCAL , ( application . getProperty ( DBParams . LOCAL ) != null ) ? application . getProperty ( DBParams . LOCAL ) : DEFAULT_LOCAL_DB ) ; if ( m_properties . get ( DBParams . REMOTE ) == null ) m_properties . put ( DBParams . REMOTE , ( application . getProperty ( DBParams . REMOTE ) != null ) ? application . getProperty ( DBParams . REMOTE ) : DEFAULT_REMOTE_DB ) ; if ( m_properties . get ( DBParams . TABLE ) == null ) m_properties . put ( DBParams . TABLE , ( application . getProperty ( DBParams . TABLE ) != null ) ? application . getProperty ( DBParams . TABLE ) : DEFAULT_TABLE_DB ) ; } }
Set the default application .
14,493
public void addApplication ( App application ) { Utility . getLogger ( ) . info ( "addApp: " + application ) ; m_vApplication . add ( application ) ; ( ( BaseApplication ) application ) . setEnvironment ( this ) ; if ( ( m_applicationDefault == null ) || ( ( ! ( m_applicationDefault instanceof MainApplication ) ) ) && ( application instanceof MainApplication ) ) this . setDefaultApplication ( application ) ; }
Add an Application to this environment . If there is no default application yet this is set to the default application .
14,494
public int removeApplication ( App application ) { Utility . getLogger ( ) . info ( "removeApp: " + application ) ; m_vApplication . remove ( application ) ; if ( m_applicationDefault == application ) m_applicationDefault = null ; return m_vApplication . size ( ) ; }
Remove this application from the Environment .
14,495
public MessageApp getMessageApplication ( String strDBPrefix , String strSubSystem ) { strSubSystem = Utility . getSystemSuffix ( strSubSystem , this . getProperty ( DBConstants . DEFAULT_SYSTEM_NAME ) ) ; MessageApp messageApplication = null ; for ( int i = 0 ; i < this . getApplicationCount ( ) ; i ++ ) { App app = this . getApplication ( i ) ; if ( app instanceof MessageApp ) { Map < String , Object > messageAppProperties = app . getProperties ( ) ; String strAppDBPrefix = ( messageAppProperties == null ) ? null : ( String ) messageAppProperties . get ( DBConstants . DB_USER_PREFIX ) ; String strAppSubSystem = ( messageAppProperties == null ) ? null : ( String ) messageAppProperties . get ( DBConstants . SYSTEM_NAME ) ; strAppSubSystem = Utility . getSystemSuffix ( strAppSubSystem , this . getProperty ( DBConstants . DEFAULT_SYSTEM_NAME ) ) ; boolean bDBMatch = false ; if ( ( strAppDBPrefix == null ) && ( strDBPrefix == null ) ) bDBMatch = true ; if ( strAppDBPrefix != null ) if ( strAppDBPrefix . equalsIgnoreCase ( strDBPrefix ) ) bDBMatch = true ; boolean bSubSystemMatch = false ; if ( ( strAppSubSystem == null ) && ( strSubSystem == null ) ) bSubSystemMatch = true ; if ( strAppSubSystem != null ) if ( strAppSubSystem . equalsIgnoreCase ( strSubSystem ) ) bSubSystemMatch = true ; if ( ( bDBMatch ) && ( bSubSystemMatch ) ) messageApplication = ( MessageApp ) app ; } } return messageApplication ; }
Find the message application .
14,496
public void cacheDatabaseProperties ( String strDBName , Map < String , String > map ) { m_mapDBProperties . put ( strDBName , map ) ; }
Set the initial database properties .
14,497
public DataSource getDataSource ( JdbcDatabase database ) { com . mysql . jdbc . jdbc2 . optional . MysqlDataSource dataSource = new com . mysql . jdbc . jdbc2 . optional . MysqlDataSource ( ) ; this . setDatasourceParams ( database , dataSource ) ; return dataSource ; }
Get and populate the data source object for this database .
14,498
public void init ( final InputStream inputStream ) { try ( final InputStream is = inputStream ) { final Manifest mf = new Manifest ( is ) ; final Attributes attr = mf . getMainAttributes ( ) ; commit = attr . getValue ( "git-commit" ) ; gitUrl = attr . getValue ( "git-url" ) ; version = attr . getValue ( "project-version" ) ; final long time = Long . parseLong ( attr . getValue ( "creation-date" ) ) ; creationDate = DateFormat . getDateTimeInstance ( DATEFORMAT , DATEFORMAT ) . format ( new Date ( time ) ) ; } catch ( Exception e ) { initBackToDefaults ( ) ; } }
Init with a given inputStream .
14,499
public static < E extends Comparable < E > > int search ( E [ ] array , E value ) { int start = 0 ; int end = array . length - 1 ; int middle = 0 ; while ( start <= end ) { middle = ( start + end ) >> 1 ; if ( value . equals ( array [ middle ] ) ) { return middle ; } if ( value . compareTo ( array [ middle ] ) < 0 ) { end = middle - 1 ; } else { start = middle + 1 ; } } return - 1 ; }
Search for the value in the sorted sorted array and return the index .