idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
2,300
public static BigDecimal decimalPart ( final BigDecimal val ) { return BigDecimalUtil . subtract ( val , val . setScale ( 0 , BigDecimal . ROUND_DOWN ) ) ; }
Return the decimal part of the value .
2,301
private static BigDecimal sqrtNewtonRaphson ( final BigDecimal c , final BigDecimal xn , final BigDecimal precision ) { BigDecimal fx = xn . pow ( 2 ) . add ( c . negate ( ) ) ; BigDecimal fpx = xn . multiply ( new BigDecimal ( 2 ) ) ; BigDecimal xn1 = fx . divide ( fpx , 2 * SQRT_DIG . intValue ( ) , RoundingMode . HALF_DOWN ) ; xn1 = xn . add ( xn1 . negate ( ) ) ; BigDecimal currentSquare = xn1 . pow ( 2 ) ; BigDecimal currentPrecision = currentSquare . subtract ( c ) ; currentPrecision = currentPrecision . abs ( ) ; if ( currentPrecision . compareTo ( precision ) <= - 1 ) { return xn1 ; } return sqrtNewtonRaphson ( c , xn1 , precision ) ; }
Private utility method used to compute the square root of a BigDecimal .
2,302
public static BigDecimal bigSqrt ( final BigDecimal c ) { if ( c == null ) { return null ; } return c . signum ( ) == 0 ? BigDecimal . ZERO : sqrtNewtonRaphson ( c , BigDecimal . ONE , BigDecimal . ONE . divide ( SQRT_PRE ) ) ; }
Uses Newton Raphson to compute the square root of a BigDecimal .
2,303
public void addMenuItem ( final String menuDisplay , final String methodName , final boolean repeat ) { menu . add ( menuDisplay ) ; methods . add ( methodName ) ; askForRepeat . add ( Boolean . valueOf ( repeat ) ) ; }
add an entry in the menu sequentially
2,304
public void displayMenu ( ) { while ( true ) { ConsoleMenu . println ( "" ) ; ConsoleMenu . println ( "Menu Options" ) ; final int size = menu . size ( ) ; displayMenu ( size ) ; int opt ; do { opt = ConsoleMenu . getInt ( "Enter your choice:" , - 1 ) ; } while ( ( opt <= 0 || opt > methods . size ( ) ) && opt != EXIT_CODE ) ; if ( opt == EXIT_CODE ) { callTearDownIfRequired ( ) ; return ; } callMenuOption ( opt ) ; } }
display the menu the application goes into a loop which provides the menu and fires the entries selected . It automatically adds an entry to exit .
2,305
public static int getInt ( final String title , final int defaultValue ) { int opt ; do { try { final String val = ConsoleMenu . getString ( title + DEFAULT_TITLE + defaultValue + ")" ) ; if ( val . length ( ) == 0 ) { opt = defaultValue ; } else { opt = Integer . parseInt ( val ) ; } } catch ( final NumberFormatException e ) { opt = - 1 ; } } while ( opt == - 1 ) ; return opt ; }
Gets an int from the System . in
2,306
public static boolean getBoolean ( final String title , final boolean defaultValue ) { final String val = ConsoleMenu . selectOne ( title , new String [ ] { "Yes" , "No" } , new String [ ] { Boolean . TRUE . toString ( ) , Boolean . FALSE . toString ( ) } , defaultValue ? 1 : 2 ) ; return Boolean . valueOf ( val ) ; }
Gets a boolean from the System . in
2,307
public static BigDecimal getBigDecimal ( final String title , final BigDecimal defaultValue ) { BigDecimal opt ; do { try { final String val = ConsoleMenu . getString ( title + DEFAULT_TITLE + defaultValue + ")" ) ; if ( val . length ( ) == 0 ) { opt = defaultValue ; } else { opt = new BigDecimal ( val ) ; } } catch ( final NumberFormatException e ) { opt = null ; } } while ( opt == null && defaultValue != null ) ; return opt ; }
Gets an BigDecimal from the System . in
2,308
public static String getString ( final String msg ) { ConsoleMenu . print ( msg ) ; BufferedReader bufReader = null ; String opt = null ; try { bufReader = new BufferedReader ( new InputStreamReader ( System . in ) ) ; opt = bufReader . readLine ( ) ; } catch ( final IOException ex ) { log ( ex ) ; System . exit ( 1 ) ; } return opt ; }
Gets a String from the System . in .
2,309
public static String getString ( final String msg , final String defaultVal ) { String s = getString ( msg + "(default:" + defaultVal + "):" ) ; if ( StringUtils . isBlank ( s ) ) { s = defaultVal ; } return s ; }
Gets a String from the System . in
2,310
public static String selectOne ( final String title , final String [ ] optionNames , final String [ ] optionValues , final int defaultOption ) { if ( optionNames . length != optionValues . length ) { throw new IllegalArgumentException ( "option names and values must have same length" ) ; } ConsoleMenu . println ( "Please chose " + title + DEFAULT_TITLE + defaultOption + ")" ) ; for ( int i = 0 ; i < optionNames . length ; i ++ ) { ConsoleMenu . println ( i + 1 + ") " + optionNames [ i ] ) ; } int choice ; do { choice = ConsoleMenu . getInt ( "Your Choice 1-" + optionNames . length + ": " , defaultOption ) ; } while ( choice <= 0 || choice > optionNames . length ) ; return optionValues [ choice - 1 ] ; }
Generates a menu with a list of options and return the value selected .
2,311
public String selectMajorCurrency ( final String ccy1 , final String ccy2 ) { return ranks . getOrDefault ( StringUtil . toUpperCase ( ccy1 ) , DEFAULT_UNRANKED_VALUE ) . intValue ( ) <= ranks . getOrDefault ( StringUtil . toUpperCase ( ccy2 ) , DEFAULT_UNRANKED_VALUE ) . intValue ( ) ? ccy1 : ccy2 ; }
Given 2 currencies return the major one if there is one otherwise returns the first currency .
2,312
public String selectMajorCurrency ( final CurrencyPair pair ) { return selectMajorCurrency ( pair . getCcy1 ( ) , pair . getCcy2 ( ) ) ; }
Given a CurrencyPair return the major Currency if there is one otherwise returns the first currency .
2,313
public boolean isMarketConvention ( final String ccy1 , final String ccy2 ) { return selectMajorCurrency ( ccy1 , ccy2 ) . equals ( ccy1 ) ; }
returns true if the ccy1 is the major one for the given currency pair .
2,314
public void setCurrenciesSubjectToCrossCcyForT1 ( final Map < String , Set < String > > currenciesSubjectToCrossCcyForT1 ) { final Map < String , Set < String > > copy = new HashMap < > ( ) ; if ( currenciesSubjectToCrossCcyForT1 != null ) { copy . putAll ( currenciesSubjectToCrossCcyForT1 ) ; } this . currenciesSubjectToCrossCcyForT1 = copy ; }
Will take a copy of a non null set but doing so by replacing the internal one in one go for consistency .
2,315
public void setWorkingWeeks ( final Map < String , WorkingWeek > workingWeeks ) { final Map < String , WorkingWeek > ww = new HashMap < > ( ) ; ww . putAll ( workingWeeks ) ; this . workingWeeks = ww ; }
Will take a copy of a non null map but doing so by replacing the internal one in one go for consistency .
2,316
public WorkingWeek withWorkingDayFromCalendar ( final boolean working , final int dayOfWeek ) { final int day = adjustDay ( dayOfWeek ) ; WorkingWeek ret = this ; if ( working && ! isWorkingDayFromCalendar ( dayOfWeek ) ) { ret = new WorkingWeek ( ( byte ) ( workingDays + WORKING_WEEK_DAYS_OFFSET [ day ] ) ) ; } else if ( ! working && isWorkingDayFromCalendar ( dayOfWeek ) ) { ret = new WorkingWeek ( ( byte ) ( workingDays - WORKING_WEEK_DAYS_OFFSET [ day ] ) ) ; } return ret ; }
If the value for the given day has changed return a NEW WorkingWeek .
2,317
public static boolean anyNull ( final Object ... o1s ) { if ( o1s != null && o1s . length > 0 ) { for ( final Object o1 : o1s ) { if ( o1 == null ) { return true ; } } } else { return true ; } return false ; }
Return true if any of the given objects are null .
2,318
public static boolean allNull ( final Object ... o1s ) { if ( o1s != null && o1s . length > 0 ) { for ( final Object o1 : o1s ) { if ( o1 != null ) { return false ; } } } return true ; }
Return true if ALL of the given objects are null .
2,319
public static boolean atLeastOneNotNull ( final Object ... o1s ) { if ( o1s != null && o1s . length > 0 ) { for ( final Object o1 : o1s ) { if ( o1 != null ) { return true ; } } } return false ; }
Return true if at least one of the given objects is not null .
2,320
protected void setHolidays ( final String name , final DateCalculator < E > dc ) { if ( name != null ) { dc . setHolidayCalendar ( holidays . get ( name ) ) ; } }
Used by extensions to set holidays in a DateCalculator .
2,321
protected CurrencyDateCalculatorBuilder < E > configureCurrencyCalculatorBuilder ( final CurrencyDateCalculatorBuilder < E > builder ) { return builder . ccy1Calendar ( getHolidayCalendar ( builder . getCcy1 ( ) ) ) . ccy1Week ( getCurrencyCalculatorConfig ( ) . getWorkingWeek ( builder . getCcy1 ( ) ) ) . ccy2Calendar ( getHolidayCalendar ( builder . getCcy2 ( ) ) ) . ccy2Week ( getCurrencyCalculatorConfig ( ) . getWorkingWeek ( builder . getCcy2 ( ) ) ) . crossCcyCalendar ( getHolidayCalendar ( builder . getCrossCcy ( ) ) ) . crossCcyWeek ( getCurrencyCalculatorConfig ( ) . getWorkingWeek ( builder . getCrossCcy ( ) ) ) . currencyCalculatorConfig ( getCurrencyCalculatorConfig ( ) ) ; }
Method that may be called by the specialised factory methods and will fetch the registered holidayCalendar for all 3 currencies and the working weeks via the currencyCalculatorConfig and assigning currencyCalculatorConfig to the builder using the DefaultCurrencyCalculatorConfig if not modified .
2,322
public static FxRate calculateCross ( final CurrencyPair targetPair , final FxRate fx1 , final FxRate fx2 , final int precision , final int precisionForInverseFxRate , final MajorCurrencyRanking ranking , final int bidRounding , final int askRounding , CurrencyProvider currencyProvider ) { final Optional < String > crossCcy = fx1 . getCurrencyPair ( ) . findCommonCcy ( fx2 . getCurrencyPair ( ) ) ; final String xCcy = crossCcy . orElseThrow ( ( ) -> new IllegalArgumentException ( "The 2 FXRates do not share a ccy " + fx1 . getCurrencyPair ( ) + " " + fx2 . getCurrencyPair ( ) ) ) ; if ( crossCcy . isPresent ( ) && targetPair . containsCcy ( crossCcy . get ( ) ) ) { throw new IllegalArgumentException ( "The target currency pair " + targetPair + " contains the common ccy " + crossCcy . get ( ) ) ; } final String fx1Ccy1 = fx1 . getCurrencyPair ( ) . getCcy1 ( ) ; final String fx2Ccy1 = fx2 . getCurrencyPair ( ) . getCcy1 ( ) ; final String fx1Ccy2 = fx1 . getCurrencyPair ( ) . getCcy2 ( ) ; final String fx2Ccy2 = fx2 . getCurrencyPair ( ) . getCcy2 ( ) ; final boolean shouldDivide = fx1Ccy1 . equals ( xCcy ) && fx2Ccy1 . equals ( xCcy ) || fx1Ccy2 . equals ( xCcy ) && fx2Ccy2 . equals ( xCcy ) ; FxRateImpl crossRate = null ; if ( shouldDivide ) { final FxRate numeratorFx = targetPair . getCcy1 ( ) . equals ( fx2Ccy2 ) || targetPair . getCcy1 ( ) . equals ( fx1Ccy1 ) ? fx1 : fx2 ; final FxRate denominatorFx = numeratorFx == fx1 ? fx2 : fx1 ; LOG . debug ( "CALC {} / {}" , numeratorFx , denominatorFx ) ; BigDecimal bid = BigDecimalUtil . divide ( precision , numeratorFx . getBid ( ) , denominatorFx . getAsk ( ) , bidRounding ) ; BigDecimal ask = BigDecimalUtil . divide ( precision , numeratorFx . getAsk ( ) , denominatorFx . getBid ( ) , askRounding ) ; crossRate = new FxRateImpl ( targetPair , xCcy , ranking . isMarketConvention ( targetPair ) , bid , ask , currencyProvider ) ; } else { crossRate = calculateWithDivide ( targetPair , fx1 , fx2 , precision , precisionForInverseFxRate , ranking , bidRounding , askRounding , currencyProvider , xCcy , fx1Ccy2 , fx2Ccy2 ) ; } LOG . debug ( "X RATE {}" , crossRate ) ; LOG . debug ( crossRate . getDescription ( ) ) ; return crossRate ; }
Calculate the cross rate use this only if required .
2,323
public static String buildStackTraceString ( final Throwable ex ) { final StringBuilder context = new StringBuilder ( ex . toString ( ) ) ; final StringWriter sw = new StringWriter ( ) ; ex . printStackTrace ( new PrintWriter ( sw , true ) ) ; context . append ( '\n' ) ; context . append ( sw . toString ( ) ) ; return context . toString ( ) ; }
finds out the stack trace up to where the exception was thrown .
2,324
public static String dumpThreads ( ) { final StringWriter sout = new StringWriter ( ) ; final PrintWriter out = new PrintWriter ( sout ) ; Util . listAllThreads ( out ) ; out . flush ( ) ; return sout . toString ( ) ; }
Finds information about the threads and dumps them into a String .
2,325
private static void listAllThreads ( final PrintWriter out ) { final ThreadGroup currentThreadGroup = Thread . currentThread ( ) . getThreadGroup ( ) ; ThreadGroup rootThreadGroup = currentThreadGroup ; ThreadGroup parent = rootThreadGroup . getParent ( ) ; while ( parent != null ) { rootThreadGroup = parent ; parent = parent . getParent ( ) ; } Util . printGroupInfo ( out , rootThreadGroup , "" ) ; }
Find the root thread group and list it recursively
2,326
private static void printGroupInfo ( final PrintWriter out , final ThreadGroup group , final String indent ) { if ( group == null ) { return ; } final int numThreads = group . activeCount ( ) ; final int numGroups = group . activeGroupCount ( ) ; final Thread [ ] threads = new Thread [ numThreads ] ; final ThreadGroup [ ] groups = new ThreadGroup [ numGroups ] ; group . enumerate ( threads , false ) ; group . enumerate ( groups , false ) ; out . println ( indent + "Thread Group: " + group . getName ( ) + " Max Priority: " + group . getMaxPriority ( ) + ( group . isDaemon ( ) ? " Daemon" : "" ) ) ; for ( int i = 0 ; i < numThreads ; i ++ ) { Util . printThreadInfo ( out , threads [ i ] , indent + " " ) ; } for ( int i = 0 ; i < numGroups ; i ++ ) { Util . printGroupInfo ( out , groups [ i ] , indent + " " ) ; } }
Display info about a thread group and its threads and groups
2,327
public static String replaceToken ( final String original , final String token , final String replacement ) { final StringBuilder tok = new StringBuilder ( TOKEN ) ; tok . append ( token ) . append ( TOKEN ) ; final String toReplace = replaceCRToken ( original ) ; return StringUtil . replace ( tok . toString ( ) , replacement , toReplace ) ; }
Replaces the token surrounded by % within a string with new value . Also replaces any %CR% tokens with the newline character .
2,328
public static String replaceCRToken ( final String original ) { String toReplace = original ; if ( original != null && original . indexOf ( NEWLINE_TOKEN ) >= 0 ) { toReplace = StringUtil . replace ( NEWLINE_TOKEN , NEW_LINE , original ) ; } return toReplace ; }
Replaces any %CR% tokens with the newline character .
2,329
public static String wrapText ( final String inString , final String newline , final int wrapColumn ) { if ( inString == null ) { return null ; } final StringTokenizer lineTokenizer = new StringTokenizer ( inString , newline , true ) ; final StringBuilder builder = new StringBuilder ( ) ; while ( lineTokenizer . hasMoreTokens ( ) ) { try { String nextLine = lineTokenizer . nextToken ( ) ; if ( nextLine . length ( ) > wrapColumn ) { nextLine = wrapLine ( nextLine , newline , wrapColumn ) ; } builder . append ( nextLine ) ; } catch ( final NoSuchElementException nsee ) { break ; } } return builder . toString ( ) ; }
Takes a block of text which might have long lines in it and wraps the long lines based on the supplied wrapColumn parameter . It was initially implemented for use by VelocityEmail . If there are tabs in inString you are going to get results that are a bit strange since tabs are a single character but are displayed as 4 or 8 spaces . Remove the tabs .
2,330
public static String singleQuote ( final String text ) { final StringBuilder b = new StringBuilder ( ( text != null ? text . length ( ) : 0 ) + 2 ) ; b . append ( SINGLE_QUOTE ) ; if ( text != null ) { b . append ( text ) ; } b . append ( SINGLE_QUOTE ) ; return b . toString ( ) ; }
Add single quotes around the text .
2,331
public static boolean allEquals ( final String value , final String ... strings ) { if ( strings != null ) { for ( final String s : strings ) { if ( s == null && value != null || s != null && ! s . equals ( value ) ) { return false ; } } } else { return value == null ; } return true ; }
Return true if all strings are the same .
2,332
public static String prepareForNumericParsing ( final String inputStr ) { if ( inputStr == null ) { return EMPTY ; } final Matcher matcher = PATTERN_FOR_NUM_PARSING_PREP . matcher ( inputStr ) ; return matcher . replaceAll ( "" ) ; }
Remove and spaces from the input string .
2,333
public static int compareTo ( final String s1 , final String s2 ) { int ret ; if ( s1 != null && s2 != null ) { ret = s1 . compareTo ( s2 ) ; } else if ( s1 == null && s2 == null ) { ret = 0 ; } else if ( s2 == null ) { ret = 1 ; } else { ret = - 1 ; } return ret ; }
Handle null .
2,334
public static String boxify ( final char boxing , final String text ) { if ( boxing != 0 && StringUtils . isNotBlank ( text ) ) { final StringBuilder b = new StringBuilder ( ) ; b . append ( NEW_LINE ) ; final String line = StringUtils . repeat ( String . valueOf ( boxing ) , text . length ( ) + 4 ) ; b . append ( line ) . append ( NEW_LINE ) ; b . append ( boxing ) . append ( SPACE ) . append ( text ) . append ( SPACE ) . append ( boxing ) . append ( NEW_LINE ) ; b . append ( line ) . append ( NEW_LINE ) ; return b . toString ( ) ; } return EMPTY ; }
Returns a String which is surrounded by a box made of boxing char .
2,335
public static Integer assign ( final Integer value , final Integer defaultValueIfNull ) { return value != null ? value : defaultValueIfNull ; }
Return the value unless it is null in which case it returns the default value .
2,336
public static void setInternalComments ( Node node , ParserRuleContext parserRuleContext , AdapterParameters adapterParameters ) { BufferedTokenStream tokens = adapterParameters . getTokens ( ) ; if ( node == null || parserRuleContext == null || tokens == null ) { throw new IllegalArgumentException ( "Parameters must not be null" ) ; } Token startToken = parserRuleContext . getStart ( ) ; Token stopToken = parserRuleContext . getStop ( ) ; List < Token > commentTokens ; List < Comment > internalCommentList = new LinkedList < Comment > ( ) ; commentTokens = tokens . getHiddenTokensToRight ( startToken . getTokenIndex ( ) , Java7Lexer . COMMENTS ) ; if ( commentTokens != null ) { for ( Token commentToken : commentTokens ) { if ( adapterParameters . isCommentTokenClaimed ( commentToken . getTokenIndex ( ) ) ) { continue ; } else { adapterParameters . claimCommentToken ( commentToken . getTokenIndex ( ) ) ; } if ( commentToken . getText ( ) . startsWith ( "/**" ) ) { JavadocComment javadocComment = new JavadocComment ( commentToken . getText ( ) ) ; internalCommentList . add ( javadocComment ) ; } else if ( commentToken . getText ( ) . startsWith ( "/*" ) ) { BlockComment blockComment = new BlockComment ( commentToken . getText ( ) ) ; internalCommentList . add ( blockComment ) ; } else if ( commentToken . getText ( ) . startsWith ( "//" ) ) { LineComment lineComment = new LineComment ( commentToken . getText ( ) ) ; internalCommentList . add ( lineComment ) ; } } } if ( internalCommentList . size ( ) > 0 ) { if ( node . getInternalComments ( ) != null ) { node . getInternalComments ( ) . addAll ( internalCommentList ) ; } else { node . setInternalComments ( internalCommentList ) ; } } }
If there are no statements within a block we need a special method to grab any comments that might exist between braces .
2,337
public static CompilationUnit parse ( String javaSource ) throws IOException , ParseException { ByteArrayInputStream inputStream = new ByteArrayInputStream ( javaSource . getBytes ( "UTF-8" ) ) ; return parse ( inputStream ) ; }
Parses a UTF - 8 encoded string as java source .
2,338
public String format ( Comment comment , int indentLevel , CommentLocation commentLocation ) { if ( comment == null || comment . getContent ( ) == null ) { return null ; } return format ( comment . getContent ( ) , indentLevel , commentLocation ) ; }
Format a given comment with the indent level specified .
2,339
public String format ( String comment , int indentLevel , CommentLocation commentLocation ) { if ( comment == null ) { return null ; } final StringBuilder indentString = new StringBuilder ( ) ; for ( int i = 0 ; i < indentLevel ; i ++ ) { indentString . append ( " " ) ; } boolean endsWithNewline = ( comment . endsWith ( "\r\n" ) || comment . endsWith ( "\n" ) ) ; List < String > matchList = new ArrayList < String > ( ) ; Matcher regexMatcher = commentFormattingRegex . matcher ( comment ) ; while ( regexMatcher . find ( ) ) { matchList . add ( regexMatcher . group ( ) ) ; } StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < matchList . size ( ) ; i ++ ) { String indent ; String newline ; if ( commentLocation . equals ( CommentLocation . END ) ) { indent = " " ; newline = "" ; } else { indent = indentString . toString ( ) ; newline = "\n" ; } if ( i == 0 ) { builder . append ( indent + matchList . get ( i ) . trim ( ) + newline ) ; } else if ( i == matchList . size ( ) - 1 ) { builder . append ( indent + " " + matchList . get ( i ) . trim ( ) + ( endsWithNewline ? newline : "" ) ) ; } else { builder . append ( indent + " " + matchList . get ( i ) . trim ( ) + newline ) ; } } return builder . toString ( ) ; }
Format a given comment string with the indent level specified .
2,340
public void animateOpen ( ) { prepareContent ( ) ; if ( onDrawerScrollListener != null ) { onDrawerScrollListener . onScrollStarted ( ) ; } animateOpen ( vertical ? viewHandle . getTop ( ) : viewHandle . getLeft ( ) ) ; sendAccessibilityEvent ( AccessibilityEvent . TYPE_WINDOW_STATE_CHANGED ) ; if ( onDrawerScrollListener != null ) { onDrawerScrollListener . onScrollEnded ( ) ; } }
Opens the drawer with an animation .
2,341
public void animateClose ( ) { prepareContent ( ) ; if ( onDrawerScrollListener != null ) { onDrawerScrollListener . onScrollStarted ( ) ; } animateClose ( vertical ? viewHandle . getTop ( ) : viewHandle . getLeft ( ) ) ; if ( onDrawerScrollListener != null ) { onDrawerScrollListener . onScrollEnded ( ) ; } }
Closes the drawer with an animation .
2,342
public static ManifestBuilder builder ( ClassLoader classLoader , KnowledgeComponentImplementationModel implementationModel ) { ManifestModel manifestModel = implementationModel != null ? implementationModel . getManifest ( ) : null ; return new ManifestBuilder ( classLoader , manifestModel ) ; }
Creates a ManifestBuilder .
2,343
public static void registerOperations ( KnowledgeComponentImplementationModel model , Map < String , KnowledgeOperation > operations , KnowledgeOperation defaultOperation ) { OperationsModel operationsModel = model . getOperations ( ) ; if ( operationsModel != null ) { for ( OperationModel operationModel : operationsModel . getOperations ( ) ) { String name = Strings . trimToNull ( operationModel . getName ( ) ) ; if ( name == null ) { name = DEFAULT ; } KnowledgeOperationType type = operationModel . getType ( ) ; if ( type == null ) { type = defaultOperation . getType ( ) ; } String eventId = operationModel . getEventId ( ) ; if ( eventId == null ) { eventId = defaultOperation . getEventId ( ) ; } KnowledgeOperation operation = new KnowledgeOperation ( type , eventId ) ; mapExpressions ( operationModel , operation ) ; if ( operations . containsKey ( name ) ) { throw CommonKnowledgeMessages . MESSAGES . cannotRegisterOperation ( type . toString ( ) , name ) ; } operations . put ( name , operation ) ; } } if ( ! operations . containsKey ( DEFAULT ) ) { operations . put ( DEFAULT , defaultOperation ) ; } }
Registers operations .
2,344
public static void setGlobals ( Message message , KnowledgeOperation operation , KnowledgeRuntimeEngine runtime , boolean singleton ) { Globals globals = runtime . getSessionGlobals ( ) ; if ( globals != null ) { Map < String , Object > globalsMap = new HashMap < String , Object > ( ) ; globalsMap . put ( GLOBALS , new ConcurrentHashMap < String , Object > ( ) ) ; Map < String , Object > expressionMap = getMap ( message , operation . getGlobalExpressionMappings ( ) , null ) ; if ( expressionMap != null ) { globalsMap . putAll ( expressionMap ) ; } for ( Entry < String , Object > globalsEntry : globalsMap . entrySet ( ) ) { if ( ! singleton ) { globals . set ( globalsEntry . getKey ( ) , globalsEntry . getValue ( ) ) ; } else { if ( globals . get ( globalsEntry . getKey ( ) ) == null || ( globalsEntry . getValue ( ) != null && ( globalsEntry . getValue ( ) instanceof Map && ! ( ( Map ) globalsEntry . getValue ( ) ) . isEmpty ( ) ) ) ) { globals . set ( globalsEntry . getKey ( ) , globalsEntry . getValue ( ) ) ; } } } } }
Sets the globals .
2,345
public static boolean containsGlobals ( Message message , KnowledgeOperation operation , KnowledgeRuntimeEngine runtime ) { Map < String , Object > expressionMap = getMap ( message , operation . getGlobalExpressionMappings ( ) , null ) ; return expressionMap != null && expressionMap . size ( ) > 0 ; }
Contains the globals .
2,346
public static Object getInput ( Message message , KnowledgeOperation operation , KnowledgeRuntimeEngine runtime ) { List < Object > list = getList ( message , operation . getInputExpressionMappings ( ) ) ; switch ( list . size ( ) ) { case 0 : return filterRemoteDefaultInputContent ( message . getContent ( ) , runtime ) ; case 1 : return list . get ( 0 ) ; default : return list ; } }
Gets the input .
2,347
public static List < Object > getInputOnlyList ( Message message , KnowledgeOperation operation , KnowledgeRuntimeEngine runtime ) { return getInputList ( message , operation . getInputOnlyExpressionMappings ( ) , runtime ) ; }
Gets an input - only list .
2,348
public static Map < String , Object > getInputOutputMap ( Message message , KnowledgeOperation operation , KnowledgeRuntimeEngine runtime ) { Map < String , Object > map = new LinkedHashMap < String , Object > ( ) ; Map < String , ExpressionMapping > inputs = operation . getInputOutputExpressionMappings ( ) ; for ( Entry < String , ExpressionMapping > entry : inputs . entrySet ( ) ) { List < Object > list = getList ( message , Collections . singletonList ( entry . getValue ( ) ) ) ; final Object output ; switch ( list . size ( ) ) { case 0 : output = null ; break ; case 1 : output = list . get ( 0 ) ; break ; default : output = list ; } map . put ( entry . getKey ( ) , output ) ; } return map ; }
Gets an input - output map .
2,349
public static Map < String , Object > getInputMap ( Message message , KnowledgeOperation operation , KnowledgeRuntimeEngine runtime ) { Map < String , Object > map = new HashMap < String , Object > ( ) ; List < ExpressionMapping > inputs = operation . getInputExpressionMappings ( ) ; if ( inputs . size ( ) > 0 ) { map . putAll ( getMap ( message , inputs , null ) ) ; } else { Object content = filterRemoteDefaultInputContent ( message . getContent ( ) , runtime ) ; if ( content != null ) { map . put ( PARAMETER , content ) ; } } return map ; }
Gets an input map .
2,350
public static void setOutputs ( Message message , KnowledgeOperation operation , Map < String , Object > contextOverrides ) { try { setOutputsOrFaults ( message , operation . getOutputExpressionMappings ( ) , contextOverrides , RESULT , false ) ; } catch ( Exception e ) { setOutputsOrFaults ( message , operation . getOutputExpressionMappings ( ) , contextOverrides , RESULT , true ) ; } }
Sets the outputs .
2,351
public static void setFaults ( Message message , KnowledgeOperation operation , Map < String , Object > contextOverrides ) { setOutputsOrFaults ( message , operation . getFaultExpressionMappings ( ) , contextOverrides , FAULT , false ) ; }
Sets the faults .
2,352
public static Map < String , List < Object > > getListMap ( Message message , List < ExpressionMapping > expressionMappings , boolean expand , String undefinedVariable ) { return getListMap ( message , expressionMappings , expand , undefinedVariable , null ) ; }
Gets a list map .
2,353
@ Transformer ( to = "{urn:switchyard-quickstart-demo:helpdesk:1.0}openTicketResponse" ) public Element transformToElement ( TicketAck ticketAck ) { StringBuilder ackXml = new StringBuilder ( ) . append ( "<helpdesk:openTicketResponse xmlns:helpdesk=\"urn:switchyard-quickstart-demo:helpdesk:1.0\">" ) . append ( "<ticketAck>" ) . append ( "<id>" + ticketAck . getId ( ) + "</id>" ) . append ( "<received>" + ticketAck . isReceived ( ) + "</received>" ) . append ( "</ticketAck>" ) . append ( "</helpdesk:openTicketResponse>" ) ; return toElement ( ackXml . toString ( ) ) ; }
Transform to element .
2,354
public Ticket transformToTicket ( TicketAck ticketAck ) { Ticket ticket = new Ticket ( ) ; ticket . setId ( ticketAck . getId ( ) ) ; return ticket ; }
Transform to ticket .
2,355
private String getElementValue ( Element parent , String elementName ) { String value = null ; NodeList nodes = parent . getElementsByTagName ( elementName ) ; if ( nodes . getLength ( ) > 0 ) { value = nodes . item ( 0 ) . getChildNodes ( ) . item ( 0 ) . getNodeValue ( ) ; } return value ; }
Gets the element value .
2,356
private Element toElement ( String xml ) { DOMResult dom = new DOMResult ( ) ; try { TransformerFactory . newInstance ( ) . newTransformer ( ) . transform ( new StreamSource ( new StringReader ( xml ) ) , dom ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return ( ( Document ) dom . getNode ( ) ) . getDocumentElement ( ) ; }
To element .
2,357
public void generateCommand ( Exchange exchange ) throws Exception { System . out . println ( ">> We will fire all rules commands" ) ; FireAllRulesCommand fireAllRulesCommand = new FireAllRulesCommand ( ) ; exchange . getIn ( ) . setBody ( fireAllRulesCommand ) ; }
Generate command .
2,358
public void insertAndFireAll ( Exchange exchange ) { final Message in = exchange . getIn ( ) ; final Object body = in . getBody ( ) ; BatchExecutionCommandImpl command = new BatchExecutionCommandImpl ( ) ; final List < GenericCommand < ? > > commands = command . getCommands ( ) ; commands . add ( new InsertObjectCommand ( body , "obj1" ) ) ; commands . add ( new FireAllRulesCommand ( ) ) ; in . setBody ( command ) ; }
Insert and fire all .
2,359
@ Transformer ( from = "{urn:switchyard-quickstart:rules-interview-dtable:0.1.0}verify" ) public Applicant transformVerifyToApplicant ( Element e ) { String name = getElementValue ( e , "name" ) ; int age = Integer . valueOf ( getElementValue ( e , "age" ) ) . intValue ( ) ; return new Applicant ( name , age ) ; }
Transform verify to applicant .
2,360
public ExtendedRegisterableItemsFactory build ( ) { return new NoopExtendedRegisterableItemsFactory ( ) { private RuntimeEngine _runtime ; private List < EventListener > _listeners = new ArrayList < EventListener > ( ) ; private synchronized List < EventListener > listeners ( RuntimeEngine runtime ) { if ( _runtime != runtime ) { _runtime = runtime ; _listeners . clear ( ) ; KieRuntimeEventManager runtimeEventManager = _runtime . getKieSession ( ) ; for ( ListenerBuilder builder : _listenerBuilders ) { EventListener listener = builder . build ( runtimeEventManager ) ; if ( listener != null && ! builder . wasAutomaticRegistration ( ) ) { _listeners . add ( listener ) ; } } } return new ArrayList < EventListener > ( _listeners ) ; } public List < AgendaEventListener > getAgendaEventListeners ( RuntimeEngine runtime ) { List < AgendaEventListener > list = new ArrayList < AgendaEventListener > ( ) ; for ( EventListener listener : listeners ( runtime ) ) { if ( listener instanceof AgendaEventListener ) { list . add ( ( AgendaEventListener ) listener ) ; } } return list ; } public List < ProcessEventListener > getProcessEventListeners ( RuntimeEngine runtime ) { List < ProcessEventListener > list = new ArrayList < ProcessEventListener > ( ) ; if ( _bpm ) { list . add ( new EventPublisherProcessEventListener ( getServiceDomain ( ) . getEventPublisher ( ) ) ) ; } for ( EventListener listener : listeners ( runtime ) ) { if ( listener instanceof ProcessEventListener ) { list . add ( ( ProcessEventListener ) listener ) ; } } return list ; } public List < RuleRuntimeEventListener > getRuleRuntimeEventListeners ( RuntimeEngine runtime ) { List < RuleRuntimeEventListener > list = new ArrayList < RuleRuntimeEventListener > ( ) ; for ( EventListener listener : listeners ( runtime ) ) { if ( listener instanceof RuleRuntimeEventListener ) { list . add ( ( RuleRuntimeEventListener ) listener ) ; } } return list ; } public Map < String , WorkItemHandler > getWorkItemHandlers ( RuntimeEngine runtime ) { Map < String , WorkItemHandler > map = new LinkedHashMap < String , WorkItemHandler > ( ) ; for ( WorkItemHandlerBuilder builder : _workItemHandlerBuilders ) { ProcessRuntime processRuntime = runtime . getKieSession ( ) ; RuntimeManager runtimeManager = null ; if ( runtime instanceof RuntimeEngineImpl ) { runtimeManager = ( ( RuntimeEngineImpl ) runtime ) . getManager ( ) ; } String name = builder . getWorkItemHandlerName ( ) ; WorkItemHandler handler = builder . build ( processRuntime , runtimeManager ) ; map . put ( name , handler ) ; } return map ; } public List < KieBaseEventListener > getKieBaseEventListeners ( RuntimeEngine runtime ) { List < KieBaseEventListener > list = new ArrayList < KieBaseEventListener > ( ) ; for ( EventListener listener : listeners ( runtime ) ) { if ( listener instanceof KieBaseEventListener ) { list . add ( ( KieBaseEventListener ) listener ) ; } } return list ; } } ; }
Builds a ExtendedRegisterableItemsFactory .
2,361
public UserGroupCallback build ( ) { UserGroupCallback callback = null ; Properties properties = _propertiesBuilder . build ( ) ; if ( _userGroupCallbackClass != null ) { callback = construct ( properties ) ; } if ( callback == null && USER_CALLBACK_IMPL != null ) { try { if ( "props" . equalsIgnoreCase ( USER_CALLBACK_IMPL ) ) { callback = new JBossUserGroupCallbackImpl ( properties ) ; } else { callback = UserDataServiceProvider . getUserGroupCallback ( ) ; } } catch ( Throwable t ) { t . getMessage ( ) ; } } if ( callback == null ) { callback = new PropertiesUserGroupCallback ( properties ) ; } return callback ; }
Builds a UserGroupCallback .
2,362
public static UserGroupCallbackBuilder builder ( ClassLoader classLoader , KnowledgeComponentImplementationModel implementationModel ) { UserGroupCallbackModel userGroupCallbackModel = implementationModel != null ? implementationModel . getUserGroupCallback ( ) : null ; return new UserGroupCallbackBuilder ( classLoader , userGroupCallbackModel ) ; }
Creates a UserGroupCallbackBuilder .
2,363
public static final synchronized BPMTaskService getTaskService ( QName serviceDomainName , QName serviceName ) { KnowledgeRuntimeManager runtimeManager = KnowledgeRuntimeManagerRegistry . getRuntimeManager ( serviceDomainName , serviceName ) ; if ( runtimeManager != null ) { RuntimeEngine runtimeEngine = runtimeManager . getRuntimeEngine ( ) ; if ( runtimeEngine != null ) { final TaskService taskService = runtimeEngine . getTaskService ( ) ; if ( taskService != null ) { InvocationHandler ih = new InvocationHandler ( ) { public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { return method . invoke ( taskService , args ) ; } } ; return ( BPMTaskService ) Proxy . newProxyInstance ( BPMTaskService . class . getClassLoader ( ) , new Class [ ] { BPMTaskService . class } , ih ) ; } } } return null ; }
Gets a task service .
2,364
@ Transformer ( to = "{urn:switchyard-quickstart:rules-interview:0.1.0}verifyResponse" ) public Element transformBooleanToVerifyResponse ( boolean b ) { String xml = new StringBuilder ( ) . append ( "<urn:verifyResponse xmlns:urn='urn:switchyard-quickstart:rules-interview:0.1.0'>" ) . append ( "<return>" ) . append ( b ) . append ( "</return>" ) . append ( "</urn:verifyResponse>" ) . toString ( ) ; return toElement ( xml ) ; }
Transform boolean to verify response .
2,365
public SwitchYardServiceResponse invoke ( SwitchYardServiceRequest request ) { Map < String , Object > contextOut = new HashMap < String , Object > ( ) ; Object contentOut = null ; Object fault = null ; try { QName serviceName = request . getServiceName ( ) ; if ( serviceName == null ) { throw CommonKnowledgeMessages . MESSAGES . serviceNameNull ( ) ; } else if ( Strings . trimToNull ( serviceName . getNamespaceURI ( ) ) == null ) { String tns = getTargetNamespace ( ) ; if ( tns != null ) { serviceName = XMLHelper . createQName ( tns , serviceName . getLocalPart ( ) ) ; } } ServiceDomain serviceDomain = getServiceDomain ( ) ; if ( serviceDomain == null ) { throw CommonKnowledgeMessages . MESSAGES . serviceDomainNull ( ) ; } ServiceReference serviceReference = serviceDomain . getServiceReference ( serviceName ) ; if ( serviceReference == null ) { throw CommonKnowledgeMessages . MESSAGES . serviceReferenceNull ( serviceName . toString ( ) ) ; } final Exchange exchangeIn ; FaultHandler handler = new FaultHandler ( ) ; String operationName = request . getOperationName ( ) ; if ( operationName != null ) { exchangeIn = serviceReference . createExchange ( operationName , handler ) ; } else { exchangeIn = serviceReference . createExchange ( handler ) ; } Message messageIn = exchangeIn . createMessage ( ) ; Context contextIn = exchangeIn . getContext ( messageIn ) ; for ( Map . Entry < String , Object > entry : request . getContext ( ) . entrySet ( ) ) { contextIn . setProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } Object contentIn = request . getContent ( ) ; if ( contentIn != null ) { messageIn . setContent ( contentIn ) ; } exchangeIn . send ( messageIn ) ; if ( ExchangePattern . IN_OUT . equals ( exchangeIn . getContract ( ) . getConsumerOperation ( ) . getExchangePattern ( ) ) ) { Exchange exchangeOut = handler . waitForOut ( ) ; Message messageOut = exchangeOut . getMessage ( ) ; contentOut = messageOut . getContent ( ) ; for ( Property property : exchangeOut . getContext ( messageOut ) . getProperties ( ) ) { contextOut . put ( property . getName ( ) , property . getValue ( ) ) ; } } fault = handler . getFault ( ) ; } catch ( Throwable t ) { fault = t ; } return new SwitchYardServiceResponse ( contentOut , contextOut , fault ) ; }
Invokes the request and returns the response .
2,366
public static final synchronized KnowledgeRuntimeManager getRuntimeManager ( QName serviceDomainName , QName serviceName ) { if ( serviceDomainName == null ) { serviceDomainName = ROOT_DOMAIN ; } Map < QName , KnowledgeRuntimeManager > reg = REGISTRY . get ( serviceDomainName ) ; return reg != null ? reg . get ( serviceName ) : null ; }
Gets a runtime manager .
2,367
public static final synchronized void putRuntimeManager ( QName serviceDomainName , QName serviceName , KnowledgeRuntimeManager runtimeManager ) { if ( serviceDomainName == null ) { serviceDomainName = ROOT_DOMAIN ; } Map < QName , KnowledgeRuntimeManager > reg = REGISTRY . get ( serviceDomainName ) ; if ( reg == null ) { reg = Collections . synchronizedMap ( new HashMap < QName , KnowledgeRuntimeManager > ( ) ) ; REGISTRY . put ( serviceDomainName , reg ) ; } if ( runtimeManager == null ) { reg . remove ( serviceName ) ; } else { reg . put ( serviceName , runtimeManager ) ; } }
Puts a runtime manager .
2,368
public WorkItemHandler build ( ProcessRuntime processRuntime , RuntimeManager runtimeManager ) { WorkItemHandler workItemHandler = construct ( processRuntime , runtimeManager ) ; if ( workItemHandler instanceof SwitchYardServiceTaskHandler ) { SwitchYardServiceTaskHandler systh = ( SwitchYardServiceTaskHandler ) workItemHandler ; systh . setComponentName ( _componentName ) ; systh . setInvoker ( new SwitchYardServiceInvoker ( getServiceDomain ( ) , _targetNamespace ) ) ; systh . setProcessRuntime ( processRuntime ) ; } return workItemHandler ; }
Builds a WorkItemHandler .
2,369
public static List < WorkItemHandlerBuilder > builders ( ClassLoader classLoader , ServiceDomain serviceDomain , KnowledgeComponentImplementationModel implementationModel ) { List < WorkItemHandlerBuilder > builders = new ArrayList < WorkItemHandlerBuilder > ( ) ; Set < String > registeredNames = new HashSet < String > ( ) ; if ( implementationModel != null ) { WorkItemHandlersModel workItemHandlersModel = implementationModel . getWorkItemHandlers ( ) ; if ( workItemHandlersModel != null ) { for ( WorkItemHandlerModel workItemHandlerModel : workItemHandlersModel . getWorkItemHandlers ( ) ) { if ( workItemHandlerModel != null ) { WorkItemHandlerBuilder builder = new WorkItemHandlerBuilder ( classLoader , serviceDomain , workItemHandlerModel ) ; builders . add ( builder ) ; String name = builder . getWorkItemHandlerName ( ) ; if ( name != null ) { registeredNames . add ( name ) ; } } } } for ( Entry < String , Class < ? extends WorkItemHandler > > entry : DEFAULT_HANDLERS . entrySet ( ) ) { String name = entry . getKey ( ) ; if ( ! registeredNames . contains ( name ) ) { WorkItemHandlerBuilder builder = new WorkItemHandlerBuilder ( classLoader , serviceDomain , implementationModel , entry . getValue ( ) , name ) ; builders . add ( builder ) ; registeredNames . add ( name ) ; } } } return builders ; }
Creates WorkItemHandlerBuilders .
2,370
public KieRuntimeLogger build ( KieRuntimeEventManager runtimeEventManager ) { KieRuntimeLogger logger = null ; if ( _loggerType != null && runtimeEventManager != null ) { KieLoggers loggers = KieServices . Factory . get ( ) . getLoggers ( ) ; switch ( _loggerType ) { case CONSOLE : logger = loggers . newConsoleLogger ( runtimeEventManager ) ; break ; case FILE : logger = loggers . newFileLogger ( runtimeEventManager , _log ) ; break ; case THREADED_FILE : logger = loggers . newThreadedFileLogger ( runtimeEventManager , _log , _interval ) ; break ; } } return logger ; }
Builds a KieRuntimeLogger .
2,371
public static List < LoggerBuilder > builders ( ClassLoader classLoader , KnowledgeComponentImplementationModel implementationModel ) { List < LoggerBuilder > builders = new ArrayList < LoggerBuilder > ( ) ; if ( implementationModel != null ) { LoggersModel loggersModel = implementationModel . getLoggers ( ) ; if ( loggersModel != null ) { for ( LoggerModel loggerModel : loggersModel . getLoggers ( ) ) { if ( loggerModel != null ) { builders . add ( new LoggerBuilder ( classLoader , loggerModel ) ) ; } } } } return builders ; }
Creates LoggerBuilders .
2,372
public String getFaultMessage ( ) { String fmsg = null ; Object fault = getFault ( ) ; if ( fault != null ) { if ( fault instanceof Throwable ) { fmsg = String . format ( CommonKnowledgeMessages . MESSAGES . faultEncountered ( ) + " [%s(message=%s)]: %s" , fault . getClass ( ) . getName ( ) , ( ( Throwable ) fault ) . getMessage ( ) , fault ) ; } else { fmsg = String . format ( CommonKnowledgeMessages . MESSAGES . faultEncountered ( ) + " [%s]: %s" , fault . getClass ( ) . getName ( ) , fault ) ; } } return fmsg ; }
Gets a fault message if a fault exists .
2,373
public String getGroupId ( ) { List < String > groups = USERS_GROUPS . get ( _userId ) ; return ( groups != null && groups . size ( ) > 0 ) ? groups . get ( 0 ) : null ; }
Gets the group id .
2,374
public Map < String , String > getUsersGroups ( ) { Map < String , String > usersGroups = new LinkedHashMap < String , String > ( ) ; for ( Map . Entry < String , List < String > > entry : USERS_GROUPS . entrySet ( ) ) { String key = entry . getKey ( ) ; usersGroups . put ( key + " (" + entry . getValue ( ) . get ( 0 ) + ")" , key ) ; } return usersGroups ; }
Gets the users groups .
2,375
private void fetchTasks ( ) { synchronized ( _userTasks ) { _userTasks . clear ( ) ; _userTickets . clear ( ) ; List < TaskSummary > tasks = _taskService . getTasksAssignedAsPotentialOwner ( _userId , EN_UK ) ; for ( TaskSummary task : tasks ) { _userTasks . add ( task ) ; Map < String , Object > params = _taskService . getTaskContent ( task . getId ( ) ) ; Ticket ticket = ( Ticket ) params . get ( TICKET ) ; _userTickets . put ( task . getProcessInstanceId ( ) , ticket ) ; } } }
Fetch tasks .
2,376
private void completeTasks ( ) { synchronized ( _userTasks ) { if ( _userTasks . size ( ) > 0 ) { for ( TaskSummary task : _userTasks ) { _taskService . claim ( task . getId ( ) , _userId ) ; _taskService . start ( task . getId ( ) , _userId ) ; Map < String , Object > results = new HashMap < String , Object > ( ) ; Ticket ticket = _userTickets . get ( task . getProcessInstanceId ( ) ) ; results . put ( TICKET , ticket ) ; _taskService . complete ( task . getId ( ) , _userId , results ) ; } } } }
Complete tasks .
2,377
public PropertiesBuilder setModelProperties ( PropertiesModel propertiesModel ) { _modelProperties = propertiesModel != null ? propertiesModel . toProperties ( ) : null ; return this ; }
Sets the model properties .
2,378
public Properties build ( ) { Properties buildProperties = new Properties ( ) ; merge ( _defaultProperties , buildProperties ) ; merge ( _modelProperties , buildProperties ) ; merge ( _overrideProperties , buildProperties ) ; return buildProperties ; }
Builds a Properties .
2,379
public static PropertiesBuilder builder ( KnowledgeComponentImplementationModel implementationModel ) { PropertiesModel propertiesModel = null ; if ( implementationModel != null ) { propertiesModel = implementationModel . getProperties ( ) ; } return new PropertiesBuilder ( propertiesModel ) ; }
Creates a PropertiesBuilder .
2,380
public List < Resource > buildResources ( ) { List < Resource > resources = new ArrayList < Resource > ( ) ; for ( ResourceBuilder builder : _resourceBuilders ) { Resource resource = builder . build ( ) ; if ( resource != null ) { resources . add ( resource ) ; } } return resources ; }
Builds the Resources .
2,381
public Channel build ( ) { Channel channel = null ; if ( _channelClass != null ) { channel = Construction . construct ( _channelClass ) ; if ( channel instanceof SwitchYardServiceChannel ) { SwitchYardServiceChannel sysc = ( SwitchYardServiceChannel ) channel ; sysc . setServiceName ( _serviceName ) ; sysc . setOperationName ( _operationName ) ; sysc . setInvoker ( new SwitchYardServiceInvoker ( getServiceDomain ( ) , _targetNamespace ) ) ; } } return channel ; }
Builds a Channel .
2,382
public static List < ChannelBuilder > builders ( ClassLoader classLoader , ServiceDomain serviceDomain , KnowledgeComponentImplementationModel implementationModel ) { List < ChannelBuilder > builders = new ArrayList < ChannelBuilder > ( ) ; if ( implementationModel != null ) { ChannelsModel channelsModel = implementationModel . getChannels ( ) ; if ( channelsModel != null ) { for ( ChannelModel channelModel : channelsModel . getChannels ( ) ) { if ( channelModel != null ) { builders . add ( new ChannelBuilder ( classLoader , serviceDomain , channelModel ) ) ; } } } } return builders ; }
Creates ChannelBuilders .
2,383
private void addBook ( String isbn , String title , String synopsis , int quantity ) { Book book = new Book ( ) ; book . setIsbn ( isbn ) ; book . setTitle ( title ) ; book . setSynopsis ( synopsis ) ; isbns_to_books . put ( isbn , book ) ; isbns_to_quantities . put ( isbn , quantity ) ; }
Adds the book .
2,384
public Collection < Book > getAvailableBooks ( ) { synchronized ( librarian ) { Collection < Book > books = new LinkedList < Book > ( ) ; for ( Entry < String , Integer > entry : isbns_to_quantities . entrySet ( ) ) { if ( entry . getValue ( ) > 0 ) { books . add ( getBook ( entry . getKey ( ) ) ) ; } } return books ; } }
Gets the available books .
2,385
public Loan attemptLoan ( String isbn , String loanId ) { Loan loan = new Loan ( ) ; loan . setId ( loanId ) ; Book book = getBook ( isbn ) ; if ( book != null ) { synchronized ( librarian ) { int quantity = getQuantity ( book ) ; if ( quantity > 0 ) { quantity -- ; isbns_to_quantities . put ( isbn , quantity ) ; loan . setApproved ( true ) ; loan . setNotes ( "Happy reading! Remaining copies: " + quantity ) ; loan . setBook ( book ) ; } else { loan . setApproved ( false ) ; loan . setNotes ( "Book has no copies available." ) ; } } } else { loan . setApproved ( false ) ; loan . setNotes ( "No book matching isbn: " + isbn ) ; } return loan ; }
Attempt loan .
2,386
public boolean returnLoan ( Loan loan ) { if ( loan != null ) { Book book = loan . getBook ( ) ; if ( book != null ) { String isbn = book . getIsbn ( ) ; if ( isbn != null ) { synchronized ( librarian ) { Integer quantity = isbns_to_quantities . get ( isbn ) ; if ( quantity != null ) { quantity = new Integer ( quantity . intValue ( ) + 1 ) ; isbns_to_quantities . put ( isbn , quantity ) ; return true ; } } } } } return false ; }
Return loan .
2,387
public Resource build ( ) { Resource resource = null ; if ( _url != null ) { resource = _kieResources . newUrlResource ( _url ) ; if ( resource != null ) { if ( _resourceType != null ) { resource . setResourceType ( _resourceType ) ; } if ( _resourceConfiguration != null ) { resource . setConfiguration ( _resourceConfiguration ) ; } } } return resource ; }
Builds a Resource .
2,388
public RuntimeEnvironmentBuilder entityManagerFactory ( Object emf ) { if ( emf == null ) { return this ; } if ( ! ( emf instanceof EntityManagerFactory ) ) { throw new IllegalArgumentException ( "Argument is not of type EntityManagerFactory" ) ; } _runtimeEnvironment . setEmf ( ( EntityManagerFactory ) emf ) ; return this ; }
Sets entityManagerFactory .
2,389
public RuntimeEnvironmentBuilder addAsset ( Resource asset , ResourceType type ) { if ( asset == null || type == null ) { return this ; } _runtimeEnvironment . addAsset ( asset , type ) ; return this ; }
Adds and asset .
2,390
public RuntimeEnvironmentBuilder schedulerService ( Object globalScheduler ) { if ( globalScheduler == null ) { return this ; } if ( ! ( globalScheduler instanceof GlobalSchedulerService ) ) { throw new IllegalArgumentException ( "Argument is not of type GlobalSchedulerService" ) ; } _runtimeEnvironment . setSchedulerService ( ( GlobalSchedulerService ) globalScheduler ) ; return this ; }
Sets the schedulerService .
2,391
public KnowledgeRuntimeManager newRuntimeManager ( KnowledgeRuntimeManagerType type ) { RuntimeManager runtimeManager ; final String identifier = _identifierRoot + IDENTIFIER_COUNT . incrementAndGet ( ) ; final ClassLoader origTCCL = Classes . setTCCL ( _classLoader ) ; try { runtimeManager = _runtimeManagerBuilder . build ( type , identifier ) ; } finally { Classes . setTCCL ( origTCCL ) ; } return new KnowledgeRuntimeManager ( _classLoader , type , _serviceDomainName , _serviceName , runtimeManager , _persistent , _channelBuilders , _loggerBuilders ) ; }
Creates a new KnowledgeRuntimeManager .
2,392
public static List < ListenerBuilder > builders ( ClassLoader classLoader , KnowledgeComponentImplementationModel implementationModel ) { List < ListenerBuilder > builders = new ArrayList < ListenerBuilder > ( ) ; if ( implementationModel != null ) { ListenersModel listenersModel = implementationModel . getListeners ( ) ; if ( listenersModel != null ) { for ( ListenerModel listenerModel : listenersModel . getListeners ( ) ) { if ( listenerModel != null ) { builders . add ( new ListenerBuilder ( classLoader , listenerModel ) ) ; } } } } return builders ; }
Creates ListenerBuilders .
2,393
protected boolean isBoolean ( Exchange exchange , Message message , String name ) { Boolean b = getBoolean ( exchange , message , name ) ; return b != null && b . booleanValue ( ) ; }
Gets a primitive boolean context property .
2,394
protected Boolean getBoolean ( Exchange exchange , Message message , String name ) { Object value = getObject ( exchange , message , name ) ; if ( value instanceof Boolean ) { return ( Boolean ) value ; } else if ( value instanceof String ) { return Boolean . valueOf ( ( ( String ) value ) . trim ( ) ) ; } return false ; }
Gets a Boolean context property .
2,395
protected Integer getInteger ( Exchange exchange , Message message , String name ) { Object value = getObject ( exchange , message , name ) ; if ( value instanceof Integer ) { return ( Integer ) value ; } else if ( value instanceof Number ) { return Integer . valueOf ( ( ( Number ) value ) . intValue ( ) ) ; } else if ( value instanceof String ) { return Integer . valueOf ( ( ( String ) value ) . trim ( ) ) ; } return null ; }
Gets an Integer context property .
2,396
protected Long getLong ( Exchange exchange , Message message , String name ) { Object value = getObject ( exchange , message , name ) ; if ( value instanceof Long ) { return ( Long ) value ; } else if ( value instanceof Number ) { return Long . valueOf ( ( ( Number ) value ) . longValue ( ) ) ; } else if ( value instanceof String ) { return Long . valueOf ( ( ( String ) value ) . trim ( ) ) ; } return null ; }
Gets a Long context property .
2,397
protected String getString ( Exchange exchange , Message message , String name ) { Object value = getObject ( exchange , message , name ) ; if ( value instanceof String ) { return ( String ) value ; } else if ( value != null ) { return String . valueOf ( value ) ; } return null ; }
Gets a String context property .
2,398
protected Object getObject ( Exchange exchange , Message message , String name ) { Context context = message != null ? exchange . getContext ( message ) : exchange . getContext ( ) ; return context . getPropertyValue ( name ) ; }
Gets an Object context property .
2,399
protected Map < String , Object > getGlobalVariables ( KnowledgeRuntimeEngine runtimeEngine ) { Map < String , Object > globalVariables = new HashMap < String , Object > ( ) ; if ( runtimeEngine != null ) { Globals globals = runtimeEngine . getSessionGlobals ( ) ; if ( globals != null ) { for ( String key : globals . getGlobalKeys ( ) ) { Object value = globals . get ( key ) ; globalVariables . put ( key , value ) ; } } } return globalVariables ; }
Gets the global variables from the knowledge runtime engine .