idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
31,300
public void setStop ( final double STOP ) { if ( null == stop ) { _stop = STOP ; fireSectionEvent ( UPDATE_EVENT ) ; } else { stop . set ( STOP ) ; } }
Defines the value where the section ends .
31,301
public void setText ( final String TEXT ) { if ( null == text ) { _text = TEXT ; fireSectionEvent ( UPDATE_EVENT ) ; } else { text . set ( TEXT ) ; } }
Defines a text for the section .
31,302
public void setColor ( final Color COLOR ) { if ( null == color ) { _color = COLOR ; fireSectionEvent ( UPDATE_EVENT ) ; } else { color . set ( COLOR ) ; } }
Defines the color that will be used to colorize the section in a gauge .
31,303
public void setTextColor ( final Color COLOR ) { if ( null == textColor ) { _textColor = COLOR ; fireSectionEvent ( UPDATE_EVENT ) ; } else { textColor . set ( COLOR ) ; } }
Defines the color that will be used to colorize the section text .
31,304
private Path [ ] getPaths ( final Series < X , Y > SERIES ) { if ( ! getData ( ) . contains ( SERIES ) ) { return null ; } Node seriesNode = SERIES . getNode ( ) ; if ( null == seriesNode ) { return null ; } Group seriesGroup = ( Group ) seriesNode ; if ( seriesGroup . getChildren ( ) . isEmpty ( ) || seriesGroup . getChildren ( ) . size ( ) < 2 ) { return null ; } return new Path [ ] { ( Path ) ( seriesGroup ) . getChildren ( ) . get ( 0 ) , ( Path ) ( seriesGroup ) . getChildren ( ) . get ( 1 ) } ; }
Returns an array of paths where the first entry represents the fill path and the second entry represents the stroke path
31,305
public void setStart ( final LocalTime START ) { if ( null == start ) { _start = START ; } else { start . set ( START ) ; } }
Defines the time when the section starts .
31,306
public void setStop ( final LocalTime STOP ) { if ( null == stop ) { _stop = STOP ; } else { stop . set ( STOP ) ; } }
Defines the time when the section ends
31,307
public void setText ( final String TEXT ) { if ( null == text ) { _text = TEXT ; } else { text . set ( TEXT ) ; } }
Defines the text for the section
31,308
public void setIcon ( final Image IMAGE ) { if ( null == icon ) { _icon = IMAGE ; } else { icon . set ( IMAGE ) ; } }
Defines an image for the section .
31,309
public void setColor ( final Color COLOR ) { if ( null == color ) { _color = COLOR ; } else { color . set ( COLOR ) ; } }
Defines the color that will be used to colorize the section in a clock .
31,310
public void setVisibleData ( final VisibleData VISIBLE_DATA ) { if ( null == visibleData ) { _visibleData = VISIBLE_DATA ; redraw ( ) ; } else { visibleData . set ( VISIBLE_DATA ) ; } }
Defines the data that should be visualized in the chart segments
31,311
public void setTextOrientation ( final TextOrientation ORIENTATION ) { if ( null == textOrientation ) { _textOrientation = ORIENTATION ; redraw ( ) ; } else { textOrientation . set ( ORIENTATION ) ; } }
Defines the orientation the text will be drawn in the segments
31,312
public void setTextColor ( final Color COLOR ) { if ( null == textColor ) { _textColor = COLOR ; redraw ( ) ; } else { textColor . set ( COLOR ) ; } }
Defines the color that will be used to draw text in segments if useChartDataTextColor == false
31,313
public void setUseColorFromParent ( final boolean USE ) { if ( null == useColorFromParent ) { _useColorFromParent = USE ; redraw ( ) ; } else { useColorFromParent . set ( USE ) ; } }
Defines if tthe color of all chart segments in one group should be filled with the color of the groups root node or by the color defined in the chart data elements
31,314
public void setDecimals ( final int DECIMALS ) { if ( null == decimals ) { _decimals = clamp ( 0 , 5 , DECIMALS ) ; formatString = new StringBuilder ( "%." ) . append ( _decimals ) . append ( "f" ) . toString ( ) ; redraw ( ) ; } else { decimals . set ( DECIMALS ) ; } }
Defines the number of decimals that will be used to format the values in the tooltip
31,315
public void setInteractive ( final boolean INTERACTIVE ) { if ( null == interactive ) { _interactive = INTERACTIVE ; redraw ( ) ; } else { interactive . set ( INTERACTIVE ) ; } }
Defines if the chart should be drawn using Path elements fire ChartDataEvents and shows tooltips on segments or if the the chart should be drawn using one Canvas node .
31,316
public void setAutoTextColor ( final boolean AUTOMATIC ) { if ( null == autoTextColor ) { _autoTextColor = AUTOMATIC ; adjustTextColors ( ) ; redraw ( ) ; } else { autoTextColor . set ( AUTOMATIC ) ; } }
Defines if the text color of the chart data should be adjusted according to the chart data fill color
31,317
public void setBrightTextColor ( final Color COLOR ) { if ( null == brightTextColor ) { _brightTextColor = COLOR ; if ( isAutoTextColor ( ) ) { adjustTextColors ( ) ; redraw ( ) ; } } else { brightTextColor . set ( COLOR ) ; } }
Defines the color that will be used by the autoTextColor feature as the bright text on dark segment fill colors
31,318
public void setDarkTextColor ( final Color COLOR ) { if ( null == darkTextColor ) { _darkTextColor = COLOR ; if ( isAutoTextColor ( ) ) { adjustTextColors ( ) ; redraw ( ) ; } } else { darkTextColor . set ( COLOR ) ; } }
Defines the color that will be used by the autoTextColor feature as the dark text on bright segment fill colors
31,319
public void setUseChartDataTextColor ( final boolean USE ) { if ( null == useChartDataTextColor ) { _useChartDataTextColor = USE ; redraw ( ) ; } else { useChartDataTextColor . set ( USE ) ; } }
Defines if the text color of the segments should be taken from the ChartData elements
31,320
public void setTree ( final TreeNode < ChartData > TREE ) { if ( null != tree ) { getTreeNode ( ) . flattened ( ) . forEach ( node -> node . removeAllTreeNodeEventListeners ( ) ) ; } tree . set ( TREE ) ; getTreeNode ( ) . flattened ( ) . forEach ( node -> node . setOnTreeNodeEvent ( e -> redraw ( ) ) ) ; prepareData ( ) ; if ( isAutoTextColor ( ) ) { adjustTextColors ( ) ; } drawChart ( ) ; }
Defines the root element of the tree
31,321
public static final double [ ] getNiceScale ( final double MIN , final double MAX , final int MAX_NO_OF_TICKS ) { double minimum = MIN ; double maximum = MAX ; double epsilon = ( MAX - MIN ) / 1e6 ; maximum += epsilon ; minimum -= epsilon ; double range = maximum - minimum ; int stepCount = MAX_NO_OF_TICKS ; double roughStep = range / ( stepCount - 1 ) ; double [ ] goodNormalizedSteps = { 1 , 2 , 5 , 10 } ; double stepPower = Math . pow ( 10 , - Math . floor ( Math . log10 ( Math . abs ( roughStep ) ) ) ) ; double normalizedStep = roughStep * stepPower ; double goodNormalizedStep = Arrays . stream ( goodNormalizedSteps ) . filter ( n -> Double . compare ( n , normalizedStep ) >= 0 ) . findFirst ( ) . getAsDouble ( ) ; double niceStep = goodNormalizedStep / stepPower ; double niceMin = minimum < 0 ? Math . floor ( minimum / niceStep ) * niceStep : Math . ceil ( minimum / niceStep ) * niceStep ; double niceMax = maximum < 0 ? Math . floor ( maximum / niceStep ) * niceStep : Math . ceil ( maximum / niceStep ) * niceStep ; if ( MIN % niceStep == 0 ) { niceMin = MIN ; } if ( MAX % niceStep == 0 ) { niceMax = MAX ; } double niceRange = niceMax - niceMin ; return new double [ ] { niceMin , niceMax , niceRange , niceStep } ; }
Calculates nice minValue maxValue and stepSize for given MIN and MAX values
31,322
public static final double calcNiceNumber ( final double RANGE , final boolean ROUND ) { double niceFraction ; double exponent = Math . floor ( Math . log10 ( RANGE ) ) ; double fraction = RANGE / Math . pow ( 10 , exponent ) ; if ( ROUND ) { if ( Double . compare ( fraction , 1.5 ) < 0 ) { niceFraction = 1 ; } else if ( Double . compare ( fraction , 3 ) < 0 ) { niceFraction = 2 ; } else if ( Double . compare ( fraction , 7 ) < 0 ) { niceFraction = 5 ; } else { niceFraction = 10 ; } } else { if ( Double . compare ( fraction , 1 ) <= 0 ) { niceFraction = 1 ; } else if ( Double . compare ( fraction , 2 ) <= 0 ) { niceFraction = 2 ; } else if ( Double . compare ( fraction , 5 ) <= 0 ) { niceFraction = 5 ; } else { niceFraction = 10 ; } } return niceFraction * Math . pow ( 10 , exponent ) ; }
Returns a niceScaling number approximately equal to the range . Rounds the number if ROUND == true . Takes the ceiling if ROUND = false .
31,323
public static final Path smoothPath ( final ObservableList < PathElement > ELEMENTS , final boolean FILLED ) { if ( ELEMENTS . isEmpty ( ) ) { return new Path ( ) ; } final Point [ ] dataPoints = new Point [ ELEMENTS . size ( ) ] ; for ( int i = 0 ; i < ELEMENTS . size ( ) ; i ++ ) { final PathElement element = ELEMENTS . get ( i ) ; if ( element instanceof MoveTo ) { MoveTo move = ( MoveTo ) element ; dataPoints [ i ] = new Point ( move . getX ( ) , move . getY ( ) ) ; } else if ( element instanceof LineTo ) { LineTo line = ( LineTo ) element ; dataPoints [ i ] = new Point ( line . getX ( ) , line . getY ( ) ) ; } } double zeroY = ( ( MoveTo ) ELEMENTS . get ( 0 ) ) . getY ( ) ; List < PathElement > smoothedElements = new ArrayList < > ( ) ; Pair < Point [ ] , Point [ ] > result = calcCurveControlPoints ( dataPoints ) ; Point [ ] firstControlPoints = result . getKey ( ) ; Point [ ] secondControlPoints = result . getValue ( ) ; if ( FILLED ) { smoothedElements . add ( new MoveTo ( dataPoints [ 0 ] . getX ( ) , zeroY ) ) ; smoothedElements . add ( new LineTo ( dataPoints [ 0 ] . getX ( ) , dataPoints [ 0 ] . getY ( ) ) ) ; } else { smoothedElements . add ( new MoveTo ( dataPoints [ 0 ] . getX ( ) , dataPoints [ 0 ] . getY ( ) ) ) ; } for ( int i = 2 ; i < dataPoints . length ; i ++ ) { final int ci = i - 1 ; smoothedElements . add ( new CubicCurveTo ( firstControlPoints [ ci ] . getX ( ) , firstControlPoints [ ci ] . getY ( ) , secondControlPoints [ ci ] . getX ( ) , secondControlPoints [ ci ] . getY ( ) , dataPoints [ i ] . getX ( ) , dataPoints [ i ] . getY ( ) ) ) ; } if ( FILLED ) { smoothedElements . add ( new LineTo ( dataPoints [ dataPoints . length - 1 ] . getX ( ) , zeroY ) ) ; smoothedElements . add ( new ClosePath ( ) ) ; } return new Path ( smoothedElements ) ; }
Smooth given path defined by it s list of path elements
31,324
private static ClassLoader getContextClassLoader ( ) { ClassLoader classLoader = null ; if ( classLoader == null ) { try { Method method = Thread . class . getMethod ( "getContextClassLoader" ) ; try { classLoader = ( ClassLoader ) method . invoke ( Thread . currentThread ( ) ) ; } catch ( IllegalAccessException e ) { ; } catch ( InvocationTargetException e ) { if ( e . getTargetException ( ) instanceof SecurityException ) { ; } else { throw new LogConfigurationException ( "Unexpected InvocationTargetException" , e . getTargetException ( ) ) ; } } } catch ( NoSuchMethodException e ) { ; } } if ( classLoader == null ) { classLoader = SimpleLog . class . getClassLoader ( ) ; } return classLoader ; }
Return the thread context class loader if available . Otherwise return null .
31,325
public void clear ( ) { Map < String , String > map = inheritableThreadLocal . get ( ) ; if ( map != null ) { map . clear ( ) ; inheritableThreadLocal . remove ( ) ; } }
Clear all entries in the MDC .
31,326
public static RuleSet getMatcherImpl ( int conversionType ) { switch ( conversionType ) { case Constant . JCL_TO_SLF4J : return new JCLRuleSet ( ) ; case Constant . LOG4J_TO_SLF4J : return new Log4jRuleSet ( ) ; case Constant . JUL_TO_SLF4J : return new JULRuleSet ( ) ; case Constant . NOP_TO_SLF4J : return new EmptyRuleSet ( ) ; default : return null ; } }
Return matcher implementation depending on the conversion mode
31,327
private static boolean methodReturnsValue ( CtBehavior method ) throws NotFoundException { if ( method instanceof CtMethod == false ) { return false ; } CtClass returnType = ( ( CtMethod ) method ) . getReturnType ( ) ; String returnTypeName = returnType . getName ( ) ; boolean isVoidMethod = "void" . equals ( returnTypeName ) ; boolean methodReturnsValue = isVoidMethod == false ; return methodReturnsValue ; }
determine if the given method returns a value and return true if so . false otherwise .
31,328
public static String getSignature ( CtBehavior method ) throws NotFoundException { CtClass [ ] parameterTypes = method . getParameterTypes ( ) ; CodeAttribute codeAttribute = method . getMethodInfo ( ) . getCodeAttribute ( ) ; LocalVariableAttribute locals = null ; if ( codeAttribute != null ) { AttributeInfo attribute ; attribute = codeAttribute . getAttribute ( "LocalVariableTable" ) ; locals = ( LocalVariableAttribute ) attribute ; } String methodName = method . getName ( ) ; StringBuilder sb = new StringBuilder ( methodName ) . append ( "(\" " ) ; for ( int i = 0 ; i < parameterTypes . length ; i ++ ) { if ( i > 0 ) { sb . append ( " + \", \" " ) ; } CtClass parameterType = parameterTypes [ i ] ; boolean isArray = parameterType . isArray ( ) ; CtClass arrayType = parameterType . getComponentType ( ) ; if ( isArray ) { while ( arrayType . isArray ( ) ) { arrayType = arrayType . getComponentType ( ) ; } } sb . append ( " + \"" ) ; try { sb . append ( parameterNameFor ( method , locals , i ) ) ; } catch ( Exception e ) { sb . append ( i + 1 ) ; } sb . append ( "\" + \"=" ) ; if ( parameterType . isPrimitive ( ) ) { sb . append ( "\"+ $" ) . append ( i + 1 ) ; } else { String s = "org.slf4j.instrumentation.ToStringHelper.render" ; sb . append ( "\"+ " ) . append ( s ) . append ( "($" ) . append ( i + 1 ) . append ( ')' ) ; } } sb . append ( "+\")" ) ; String signature = sb . toString ( ) ; return signature ; }
Return javassist source snippet which lists all the parameters and their values . If available the source names are extracted from the debug information and used otherwise just a number is shown .
31,329
private void readObject ( final ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; level = s . readInt ( ) ; syslogEquivalent = s . readInt ( ) ; levelStr = s . readUTF ( ) ; if ( levelStr == null ) { levelStr = "" ; } }
Custom deserialization of Level .
31,330
private void writeObject ( final ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; s . writeInt ( level ) ; s . writeInt ( syslogEquivalent ) ; s . writeUTF ( levelStr ) ; }
Serialize level .
31,331
private String createMessage ( ServiceReference sr , String message ) { StringBuilder output = new StringBuilder ( ) ; if ( sr != null ) { output . append ( '[' ) . append ( sr . toString ( ) ) . append ( ']' ) ; } else { output . append ( UNKNOWN ) ; } output . append ( message ) ; return output . toString ( ) ; }
Formats the log message to indicate the service sending it if known .
31,332
public static Map < String , String > getCopyOfContextMap ( ) { if ( mdcAdapter == null ) { throw new IllegalStateException ( "MDCAdapter cannot be null. See also " + NULL_MDCA_URL ) ; } return mdcAdapter . getCopyOfContextMap ( ) ; }
Return a copy of the current thread s context map with keys and values of type String . Returned value may be null .
31,333
public static void setContextMap ( Map < String , String > contextMap ) { if ( mdcAdapter == null ) { throw new IllegalStateException ( "MDCAdapter cannot be null. See also " + NULL_MDCA_URL ) ; } mdcAdapter . setContextMap ( contextMap ) ; }
Set the current thread s context map by first clearing any existing map and then copying the map passed as parameter . The context map passed as parameter must only contain keys and values of type String .
31,334
protected static LogFactory newFactory ( final String factoryClass , final ClassLoader classLoader , final ClassLoader contextClassLoader ) { throw new UnsupportedOperationException ( "Operation [logRawDiagnostic] is not supported in jcl-over-slf4j. See also " + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J ) ; }
This method exists to ensure signature compatibility .
31,335
public static Class < ? > getCallingClass ( ) { ClassContextSecurityManager securityManager = getSecurityManager ( ) ; if ( securityManager == null ) return null ; Class < ? > [ ] trace = securityManager . getClassContext ( ) ; String thisClassName = Util . class . getName ( ) ; int i ; for ( i = 0 ; i < trace . length ; i ++ ) { if ( thisClassName . equals ( trace [ i ] . getName ( ) ) ) break ; } if ( i >= trace . length || i + 2 >= trace . length ) { throw new IllegalStateException ( "Failed to find org.slf4j.helpers.Util or its caller in the stack; " + "this should not happen" ) ; } return trace [ i + 2 ] ; }
Returns the name of the class which called the invoking method .
31,336
public void start ( String name ) { stopLastTimeInstrument ( ) ; StopWatch childSW = new StopWatch ( name ) ; childTimeInstrumentList . add ( childSW ) ; }
Starts a child stop watch and stops any previously started time instruments .
31,337
void sanityCheck ( ) throws IllegalStateException { if ( getStatus ( ) != TimeInstrumentStatus . STOPPED ) { throw new IllegalStateException ( "time instrument [" + getName ( ) + " is not stopped" ) ; } long totalElapsed = globalStopWatch . elapsedTime ( ) ; long childTotal = 0 ; for ( TimeInstrument ti : childTimeInstrumentList ) { childTotal += ti . elapsedTime ( ) ; if ( ti . getStatus ( ) != TimeInstrumentStatus . STOPPED ) { throw new IllegalStateException ( "time instrument [" + ti . getName ( ) + " is not stopped" ) ; } if ( ti instanceof Profiler ) { Profiler nestedProfiler = ( Profiler ) ti ; nestedProfiler . sanityCheck ( ) ; } } if ( totalElapsed < childTotal ) { throw new IllegalStateException ( "children have a higher accumulated elapsed time" ) ; } }
This method is used in tests .
31,338
public List < TimeInstrument > getCopyOfChildTimeInstruments ( ) { List < TimeInstrument > copy = new ArrayList < TimeInstrument > ( childTimeInstrumentList ) ; return copy ; }
Return a copy of the child instrument list for this Profiler instance .
31,339
public void trace ( String msg ) { logger . log ( FQCN , traceCapable ? Level . TRACE : Level . DEBUG , msg , null ) ; }
Log a message object at level TRACE .
31,340
public void debug ( String format , Object arg ) { if ( logger . isDebugEnabled ( ) ) { FormattingTuple ft = MessageFormatter . format ( format , arg ) ; logger . log ( FQCN , Level . DEBUG , ft . getMessage ( ) , ft . getThrowable ( ) ) ; } }
Log a message at level DEBUG according to the specified format and argument .
31,341
public void info ( String format , Object arg ) { if ( logger . isInfoEnabled ( ) ) { FormattingTuple ft = MessageFormatter . format ( format , arg ) ; logger . log ( FQCN , Level . INFO , ft . getMessage ( ) , ft . getThrowable ( ) ) ; } }
Log a message at level INFO according to the specified format and argument .
31,342
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public static Hashtable getContext ( ) { Map map = org . slf4j . MDC . getCopyOfContextMap ( ) ; if ( map != null ) { return new Hashtable ( map ) ; } else { return new Hashtable ( ) ; } }
This method is not part of the Log4J public API . However it has been called by other projects . This method is here temporarily until projects who are depending on this method release fixes .
31,343
public String [ ] getReplacement ( String text ) { ConversionRule conversionRule ; Pattern pattern ; Matcher matcher ; Iterator < ConversionRule > conversionRuleIterator = ruleSet . iterator ( ) ; String additionalLine = null ; while ( conversionRuleIterator . hasNext ( ) ) { conversionRule = conversionRuleIterator . next ( ) ; pattern = conversionRule . getPattern ( ) ; matcher = pattern . matcher ( text ) ; if ( matcher . find ( ) ) { atLeastOneMatchOccured = true ; String replacementText = conversionRule . replace ( matcher ) ; text = matcher . replaceAll ( replacementText ) ; if ( conversionRule . getAdditionalLine ( ) != null ) { additionalLine = conversionRule . getAdditionalLine ( ) ; } } } if ( additionalLine == null ) { return new String [ ] { text } ; } else { return new String [ ] { text , additionalLine } ; } }
Check if the specified text is matching some conversions rules . If a rule matches ask for line replacement .
31,344
public void trace ( Enum < ? > key , Object ... args ) { if ( ! logger . isTraceEnabled ( ) ) { return ; } String translatedMsg = imc . getMessage ( key , args ) ; MessageParameterObj mpo = new MessageParameterObj ( key , args ) ; if ( instanceofLAL ) { ( ( LocationAwareLogger ) logger ) . log ( LOCALIZED , FQCN , LocationAwareLogger . TRACE_INT , translatedMsg , args , null ) ; } else { logger . trace ( LOCALIZED , translatedMsg , mpo ) ; } }
Log a localized message at the TRACE level .
31,345
public void debug ( Enum < ? > key , Object ... args ) { if ( ! logger . isDebugEnabled ( ) ) { return ; } String translatedMsg = imc . getMessage ( key , args ) ; MessageParameterObj mpo = new MessageParameterObj ( key , args ) ; if ( instanceofLAL ) { ( ( LocationAwareLogger ) logger ) . log ( LOCALIZED , FQCN , LocationAwareLogger . DEBUG_INT , translatedMsg , args , null ) ; } else { logger . debug ( LOCALIZED , translatedMsg , mpo ) ; } }
Log a localized message at the DEBUG level .
31,346
public void info ( Enum < ? > key , Object ... args ) { if ( ! logger . isInfoEnabled ( ) ) { return ; } String translatedMsg = imc . getMessage ( key , args ) ; MessageParameterObj mpo = new MessageParameterObj ( key , args ) ; if ( instanceofLAL ) { ( ( LocationAwareLogger ) logger ) . log ( LOCALIZED , FQCN , LocationAwareLogger . INFO_INT , translatedMsg , args , null ) ; } else { logger . info ( LOCALIZED , translatedMsg , mpo ) ; } }
Log a localized message at the INFO level .
31,347
public void warn ( Enum < ? > key , Object ... args ) { if ( ! logger . isWarnEnabled ( ) ) { return ; } String translatedMsg = imc . getMessage ( key , args ) ; MessageParameterObj mpo = new MessageParameterObj ( key , args ) ; if ( instanceofLAL ) { ( ( LocationAwareLogger ) logger ) . log ( LOCALIZED , FQCN , LocationAwareLogger . WARN_INT , translatedMsg , args , null ) ; } else { logger . warn ( LOCALIZED , translatedMsg , mpo ) ; } }
Log a localized message at the WARN level .
31,348
public void error ( Enum < ? > key , Object ... args ) { if ( ! logger . isErrorEnabled ( ) ) { return ; } String translatedMsg = imc . getMessage ( key , args ) ; MessageParameterObj mpo = new MessageParameterObj ( key , args ) ; if ( instanceofLAL ) { ( ( LocationAwareLogger ) logger ) . log ( LOCALIZED , FQCN , LocationAwareLogger . ERROR_INT , translatedMsg , args , null ) ; } else { logger . error ( LOCALIZED , translatedMsg , mpo ) ; } }
Log a localized message at the ERROR level .
31,349
public void entry ( Object ... argArray ) { if ( instanceofLAL && logger . isTraceEnabled ( ENTRY_MARKER ) ) { String messagePattern = null ; if ( argArray . length < ENTRY_MESSAGE_ARRAY_LEN ) { messagePattern = ENTRY_MESSAGE_ARRAY [ argArray . length ] ; } else { messagePattern = buildMessagePattern ( argArray . length ) ; } FormattingTuple tp = MessageFormatter . arrayFormat ( messagePattern , argArray ) ; ( ( LocationAwareLogger ) logger ) . log ( ENTRY_MARKER , FQCN , LocationAwareLogger . TRACE_INT , tp . getMessage ( ) , argArray , tp . getThrowable ( ) ) ; } }
Log method entry .
31,350
public < T extends Throwable > T throwing ( T throwable ) { if ( instanceofLAL ) { ( ( LocationAwareLogger ) logger ) . log ( THROWING_MARKER , FQCN , LocationAwareLogger . ERROR_INT , "throwing" , null , throwable ) ; } return throwable ; }
Log an exception being thrown . The generated log event uses Level ERROR .
31,351
public < T extends Throwable > T throwing ( Level level , T throwable ) { if ( instanceofLAL ) { ( ( LocationAwareLogger ) logger ) . log ( THROWING_MARKER , FQCN , level . level , "throwing" , null , throwable ) ; } return throwable ; }
Log an exception being thrown allowing the log level to be specified .
31,352
public void catching ( Throwable throwable ) { if ( instanceofLAL ) { ( ( LocationAwareLogger ) logger ) . log ( CATCHING_MARKER , FQCN , LocationAwareLogger . ERROR_INT , "catching" , null , throwable ) ; } }
Log an exception being caught . The generated log event uses Level ERROR .
31,353
public void catching ( Level level , Throwable throwable ) { if ( instanceofLAL ) { ( ( LocationAwareLogger ) logger ) . log ( CATCHING_MARKER , FQCN , level . level , "catching" , null , throwable ) ; } }
Log an exception being caught allowing the log level to be specified .
31,354
private void formatAndLog ( int level , String format , Object arg1 , Object arg2 ) { if ( ! isLevelEnabled ( level ) ) { return ; } FormattingTuple tp = MessageFormatter . format ( format , arg1 , arg2 ) ; log ( level , tp . getMessage ( ) , tp . getThrowable ( ) ) ; }
For formatted messages first substitute arguments and then log .
31,355
public void trace ( String format , Object param1 ) { formatAndLog ( LOG_LEVEL_TRACE , format , param1 , null ) ; }
Perform single parameter substitution before logging the message of level TRACE according to the format outlined above .
31,356
public void trace ( String format , Object param1 , Object param2 ) { formatAndLog ( LOG_LEVEL_TRACE , format , param1 , param2 ) ; }
Perform double parameter substitution before logging the message of level TRACE according to the format outlined above .
31,357
public void debug ( String format , Object param1 ) { formatAndLog ( LOG_LEVEL_DEBUG , format , param1 , null ) ; }
Perform single parameter substitution before logging the message of level DEBUG according to the format outlined above .
31,358
public void debug ( String format , Object param1 , Object param2 ) { formatAndLog ( LOG_LEVEL_DEBUG , format , param1 , param2 ) ; }
Perform double parameter substitution before logging the message of level DEBUG according to the format outlined above .
31,359
public void info ( String format , Object arg ) { formatAndLog ( LOG_LEVEL_INFO , format , arg , null ) ; }
Perform single parameter substitution before logging the message of level INFO according to the format outlined above .
31,360
public void info ( String format , Object arg1 , Object arg2 ) { formatAndLog ( LOG_LEVEL_INFO , format , arg1 , arg2 ) ; }
Perform double parameter substitution before logging the message of level INFO according to the format outlined above .
31,361
public void warn ( String format , Object arg ) { formatAndLog ( LOG_LEVEL_WARN , format , arg , null ) ; }
Perform single parameter substitution before logging the message of level WARN according to the format outlined above .
31,362
public void warn ( String format , Object arg1 , Object arg2 ) { formatAndLog ( LOG_LEVEL_WARN , format , arg1 , arg2 ) ; }
Perform double parameter substitution before logging the message of level WARN according to the format outlined above .
31,363
public void error ( String format , Object arg ) { formatAndLog ( LOG_LEVEL_ERROR , format , arg , null ) ; }
Perform single parameter substitution before logging the message of level ERROR according to the format outlined above .
31,364
public void error ( String format , Object arg1 , Object arg2 ) { formatAndLog ( LOG_LEVEL_ERROR , format , arg1 , arg2 ) ; }
Perform double parameter substitution before logging the message of level ERROR according to the format outlined above .
31,365
public static boolean isInstalled ( ) throws SecurityException { java . util . logging . Logger rootLogger = getRootLogger ( ) ; Handler [ ] handlers = rootLogger . getHandlers ( ) ; for ( int i = 0 ; i < handlers . length ; i ++ ) { if ( handlers [ i ] instanceof SLF4JBridgeHandler ) { return true ; } } return false ; }
Returns true if SLF4JBridgeHandler has been previously installed returns false otherwise .
31,366
protected Logger getSLF4JLogger ( LogRecord record ) { String name = record . getLoggerName ( ) ; if ( name == null ) { name = UNKNOWN_LOGGER_NAME ; } return LoggerFactory . getLogger ( name ) ; }
Return the Logger instance that will be used for logging .
31,367
private String getMessageI18N ( LogRecord record ) { String message = record . getMessage ( ) ; if ( message == null ) { return null ; } ResourceBundle bundle = record . getResourceBundle ( ) ; if ( bundle != null ) { try { message = bundle . getString ( message ) ; } catch ( MissingResourceException e ) { } } Object [ ] params = record . getParameters ( ) ; if ( params != null && params . length > 0 ) { try { message = MessageFormat . format ( message , params ) ; } catch ( IllegalArgumentException e ) { return message ; } } return message ; }
Get the record s message possibly via a resource bundle .
31,368
private static void printStartStopTimes ( ) { final long start = System . currentTimeMillis ( ) ; System . err . println ( "Start at " + new Date ( ) ) ; Thread hook = new Thread ( ) { public void run ( ) { long timePassed = System . currentTimeMillis ( ) - start ; System . err . println ( "Stop at " + new Date ( ) + ", execution time = " + timePassed + " ms" ) ; } } ; Runtime . getRuntime ( ) . addShutdownHook ( hook ) ; }
Print the start message to System . err with the time NOW and register a shutdown hook which will print the stop message to System . err with the time then and the number of milliseconds passed since .
31,369
public boolean isEnabledFor ( Priority p ) { switch ( p . level ) { case Level . TRACE_INT : return slf4jLogger . isTraceEnabled ( ) ; case Level . DEBUG_INT : return slf4jLogger . isDebugEnabled ( ) ; case Level . INFO_INT : return slf4jLogger . isInfoEnabled ( ) ; case Level . WARN_INT : return slf4jLogger . isWarnEnabled ( ) ; case Level . ERROR_INT : return slf4jLogger . isErrorEnabled ( ) ; case Priority . FATAL_INT : return slf4jLogger . isErrorEnabled ( ) ; } return false ; }
Determines whether the priority passed as parameter is enabled in the underlying SLF4J logger . Each log4j priority is mapped directly to its SLF4J equivalent except for FATAL which is mapped as ERROR .
31,370
private void scanFileList ( List < File > lstFiles ) { progressListener . onFileScanBegin ( ) ; Iterator < File > itFile = lstFiles . iterator ( ) ; while ( itFile . hasNext ( ) ) { File currentFile = itFile . next ( ) ; progressListener . onFileScan ( currentFile ) ; scanFile ( currentFile ) ; } }
Convert a list of files
31,371
private void scanFile ( File file ) { try { InplaceFileConverter fc = new InplaceFileConverter ( ruleSet , progressListener ) ; fc . convert ( file ) ; } catch ( IOException exc ) { addException ( new ConversionException ( exc . toString ( ) ) ) ; } }
Convert the specified file Read each line and ask matcher implementation for conversion Rewrite the line returned by matcher
31,372
public void trace ( String msg ) { if ( logger . isLoggable ( Level . FINEST ) ) { log ( SELF , Level . FINEST , msg , null ) ; } }
Log a message object at level FINEST .
31,373
public void info ( String msg ) { if ( logger . isLoggable ( Level . INFO ) ) { log ( SELF , Level . INFO , msg , null ) ; } }
Log a message object at the INFO level .
31,374
public void warn ( String msg ) { if ( logger . isLoggable ( Level . WARNING ) ) { log ( SELF , Level . WARNING , msg , null ) ; } }
Log a message object at the WARNING level .
31,375
public boolean isRunning ( int attempts , long timeout , TimeUnit timeUnit ) { try { HttpResponse httpResponse = sendRequest ( request ( ) . withMethod ( "PUT" ) . withPath ( calculatePath ( "status" ) ) ) ; if ( httpResponse . getStatusCode ( ) == HttpStatusCode . OK_200 . code ( ) ) { return true ; } else if ( attempts == 0 ) { return false ; } else { try { timeUnit . sleep ( timeout ) ; } catch ( InterruptedException e ) { } return isRunning ( attempts - 1 , timeout , timeUnit ) ; } } catch ( SocketConnectionException sce ) { return false ; } }
Returns whether server MockServer is running by polling the MockServer a configurable amount of times
31,376
public List < Integer > bind ( Integer ... ports ) { String boundPorts = sendRequest ( request ( ) . withMethod ( "PUT" ) . withPath ( calculatePath ( "bind" ) ) . withBody ( portBindingSerializer . serialize ( portBinding ( ports ) ) , StandardCharsets . UTF_8 ) ) . getBodyAsString ( ) ; return portBindingSerializer . deserialize ( boundPorts ) . getPorts ( ) ; }
Bind new ports to listen on
31,377
public MockServerClient reset ( ) { MockServerEventBus . getInstance ( ) . publish ( EventType . RESET ) ; sendRequest ( request ( ) . withMethod ( "PUT" ) . withPath ( calculatePath ( "reset" ) ) ) ; return clientClass . cast ( this ) ; }
Reset MockServer by clearing all expectations
31,378
public MockServerClient clear ( HttpRequest httpRequest ) { sendRequest ( request ( ) . withMethod ( "PUT" ) . withPath ( calculatePath ( "clear" ) ) . withBody ( httpRequest != null ? httpRequestSerializer . serialize ( httpRequest ) : "" , StandardCharsets . UTF_8 ) ) ; return clientClass . cast ( this ) ; }
Clear all expectations and logs that match the http
31,379
public MockServerClient clear ( HttpRequest httpRequest , ClearType type ) { sendRequest ( request ( ) . withMethod ( "PUT" ) . withPath ( calculatePath ( "clear" ) ) . withQueryStringParameter ( "type" , type . name ( ) . toLowerCase ( ) ) . withBody ( httpRequest != null ? httpRequestSerializer . serialize ( httpRequest ) : "" , StandardCharsets . UTF_8 ) ) ; return clientClass . cast ( this ) ; }
Clear expectations logs or both that match the http
31,380
public MockServerClient verifyZeroInteractions ( ) throws AssertionError { Verification verification = verification ( ) . withRequest ( request ( ) ) . withTimes ( exactly ( 0 ) ) ; String result = sendRequest ( request ( ) . withMethod ( "PUT" ) . withPath ( calculatePath ( "verify" ) ) . withBody ( verificationSerializer . serialize ( verification ) , StandardCharsets . UTF_8 ) ) . getBodyAsString ( ) ; if ( result != null && ! result . isEmpty ( ) ) { throw new AssertionError ( result ) ; } return clientClass . cast ( this ) ; }
Verify no requests have been have been sent .
31,381
public Expectation [ ] retrieveRecordedExpectations ( HttpRequest httpRequest ) { String recordedExpectations = retrieveRecordedExpectations ( httpRequest , Format . JSON ) ; if ( ! Strings . isNullOrEmpty ( recordedExpectations ) && ! recordedExpectations . equals ( "[]" ) ) { return expectationSerializer . deserializeArray ( recordedExpectations ) ; } else { return new Expectation [ 0 ] ; } }
Retrieve the request - response combinations that have been recorded as a list of expectations only those that match the httpRequest parameter are returned use null to retrieve all requests
31,382
public String retrieveLogMessages ( HttpRequest httpRequest ) { HttpResponse httpResponse = sendRequest ( request ( ) . withMethod ( "PUT" ) . withPath ( calculatePath ( "retrieve" ) ) . withQueryStringParameter ( "type" , RetrieveType . LOGS . name ( ) ) . withBody ( httpRequest != null ? httpRequestSerializer . serialize ( httpRequest ) : "" , StandardCharsets . UTF_8 ) ) ; return httpResponse . getBodyAsString ( ) ; }
Retrieve the logs associated to a specific requests this shows all logs for expectation matching verification clearing etc
31,383
public Expectation [ ] retrieveActiveExpectations ( HttpRequest httpRequest ) { String activeExpectations = retrieveActiveExpectations ( httpRequest , Format . JSON ) ; if ( ! Strings . isNullOrEmpty ( activeExpectations ) && ! activeExpectations . equals ( "[]" ) ) { return expectationSerializer . deserializeArray ( activeExpectations ) ; } else { return new Expectation [ 0 ] ; } }
Retrieve the active expectations match the httpRequest parameter use null for the parameter to retrieve all expectations
31,384
public static void main ( String ... arguments ) { try { Map < String , String > parsedArguments = parseArguments ( arguments ) ; MOCK_SERVER_LOGGER . debug ( SERVER_CONFIGURATION , "Using command line options: {}" , Joiner . on ( ", " ) . withKeyValueSeparator ( "=" ) . join ( parsedArguments ) ) ; if ( parsedArguments . size ( ) > 0 && parsedArguments . containsKey ( serverPort . name ( ) ) ) { if ( parsedArguments . containsKey ( logLevel . name ( ) ) ) { ConfigurationProperties . logLevel ( parsedArguments . get ( logLevel . name ( ) ) ) ; } Integer [ ] localPorts = INTEGER_STRING_LIST_PARSER . toArray ( parsedArguments . get ( serverPort . name ( ) ) ) ; if ( parsedArguments . containsKey ( proxyRemotePort . name ( ) ) ) { String remoteHost = parsedArguments . get ( proxyRemoteHost . name ( ) ) ; if ( Strings . isNullOrEmpty ( remoteHost ) ) { remoteHost = "localhost" ; } new MockServer ( Integer . parseInt ( parsedArguments . get ( proxyRemotePort . name ( ) ) ) , remoteHost , localPorts ) ; } else { new MockServer ( localPorts ) ; } } else { showUsage ( ) ; } } catch ( IllegalArgumentException iae ) { showUsage ( ) ; } }
Run the MockServer directly providing the arguments as specified below .
31,385
private static KeyStore saveCertificateAsKeyStore ( KeyStore existingKeyStore , boolean deleteOnExit , String keyStoreFileName , String certificationAlias , Key privateKey , char [ ] keyStorePassword , Certificate [ ] chain , X509Certificate caCert ) { try { KeyStore keyStore = existingKeyStore ; if ( keyStore == null ) { keyStore = KeyStore . getInstance ( KeyStore . getDefaultType ( ) ) ; keyStore . load ( null , keyStorePassword ) ; } try { keyStore . deleteEntry ( certificationAlias ) ; } catch ( KeyStoreException kse ) { } keyStore . setKeyEntry ( certificationAlias , privateKey , keyStorePassword , chain ) ; try { keyStore . deleteEntry ( KEY_STORE_CA_ALIAS ) ; } catch ( KeyStoreException kse ) { } keyStore . setCertificateEntry ( KEY_STORE_CA_ALIAS , caCert ) ; String keyStoreFileAbsolutePath = new File ( keyStoreFileName ) . getAbsolutePath ( ) ; try ( FileOutputStream fileOutputStream = new FileOutputStream ( keyStoreFileAbsolutePath ) ) { keyStore . store ( fileOutputStream , keyStorePassword ) ; MOCK_SERVER_LOGGER . trace ( "Saving key store to file [" + keyStoreFileAbsolutePath + "]" ) ; } if ( deleteOnExit ) { new File ( keyStoreFileAbsolutePath ) . deleteOnExit ( ) ; } return keyStore ; } catch ( Exception e ) { throw new RuntimeException ( "Exception while saving KeyStore" , e ) ; } }
Save X509Certificate in KeyStore file .
31,386
public HttpRequest withBody ( String body , Charset charset ) { if ( body != null ) { this . body = new StringBody ( body , charset ) ; } return this ; }
The exact string body to match on such as this is an exact string body
31,387
public static boolean shouldNotIgnoreException ( Throwable cause ) { String message = String . valueOf ( cause . getMessage ( ) ) . toLowerCase ( ) ; if ( cause . getCause ( ) instanceof SSLException || cause instanceof DecoderException | cause instanceof NotSslRecordException ) { return false ; } if ( IGNORABLE_ERROR_MESSAGE . matcher ( message ) . matches ( ) ) { return false ; } StackTraceElement [ ] elements = cause . getStackTrace ( ) ; for ( StackTraceElement element : elements ) { String classname = element . getClassName ( ) ; String methodname = element . getMethodName ( ) ; if ( classname . startsWith ( "io.netty." ) ) { continue ; } if ( ! "read" . equals ( methodname ) ) { continue ; } if ( IGNORABLE_CLASS_IN_STACK . matcher ( classname ) . matches ( ) ) { return false ; } try { Class < ? > clazz = PlatformDependent . getClassLoader ( ExceptionHandler . class ) . loadClass ( classname ) ; if ( SocketChannel . class . isAssignableFrom ( clazz ) || DatagramChannel . class . isAssignableFrom ( clazz ) ) { return false ; } if ( PlatformDependent . javaVersion ( ) >= 7 && "com.sun.nio.sctp.SctpChannel" . equals ( clazz . getSuperclass ( ) . getName ( ) ) ) { return false ; } } catch ( ClassNotFoundException e ) { } } return true ; }
returns true is the exception was caused by the connection being closed
31,388
public static void logLevel ( String level ) { if ( ! Arrays . asList ( "TRACE" , "DEBUG" , "INFO" , "WARN" , "ERROR" , "OFF" ) . contains ( level ) ) { throw new IllegalArgumentException ( "log level \"" + level + "\" is not legal it must be one of \"TRACE\", \"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"OFF\"" ) ; } System . setProperty ( MOCKSERVER_LOG_LEVEL , level ) ; MockServerLogger . initialiseLogLevels ( ) ; }
Override the default logging level of INFO
31,389
KeyPair generateKeyPair ( int keySize ) throws Exception { KeyPairGenerator generator = KeyPairGenerator . getInstance ( KEY_GENERATION_ALGORITHM , PROVIDER_NAME ) ; generator . initialize ( keySize , new SecureRandom ( ) ) ; return generator . generateKeyPair ( ) ; }
Create a random 2048 bit RSA key pair with the given length
31,390
private X509Certificate createCACert ( PublicKey publicKey , PrivateKey privateKey ) throws Exception { X500Name issuerName = new X500Name ( "CN=www.mockserver.com, O=MockServer, L=London, ST=England, C=UK" ) ; X500Name subjectName = issuerName ; BigInteger serial = BigInteger . valueOf ( new Random ( ) . nextInt ( Integer . MAX_VALUE ) ) ; X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder ( issuerName , serial , NOT_BEFORE , NOT_AFTER , subjectName , publicKey ) ; builder . addExtension ( Extension . subjectKeyIdentifier , false , createSubjectKeyIdentifier ( publicKey ) ) ; builder . addExtension ( Extension . basicConstraints , true , new BasicConstraints ( true ) ) ; KeyUsage usage = new KeyUsage ( KeyUsage . keyCertSign | KeyUsage . digitalSignature | KeyUsage . keyEncipherment | KeyUsage . dataEncipherment | KeyUsage . cRLSign ) ; builder . addExtension ( Extension . keyUsage , false , usage ) ; ASN1EncodableVector purposes = new ASN1EncodableVector ( ) ; purposes . add ( KeyPurposeId . id_kp_serverAuth ) ; purposes . add ( KeyPurposeId . id_kp_clientAuth ) ; purposes . add ( KeyPurposeId . anyExtendedKeyUsage ) ; builder . addExtension ( Extension . extendedKeyUsage , false , new DERSequence ( purposes ) ) ; X509Certificate cert = signCertificate ( builder , privateKey ) ; cert . checkValidity ( new Date ( ) ) ; cert . verify ( publicKey ) ; return cert ; }
Create a certificate to use by a Certificate Authority signed by a self signed certificate .
31,391
private X509Certificate createCASignedCert ( PublicKey publicKey , X509Certificate certificateAuthorityCert , PrivateKey certificateAuthorityPrivateKey , PublicKey certificateAuthorityPublicKey , String domain , String [ ] subjectAlternativeNameDomains , String [ ] subjectAlternativeNameIps ) throws Exception { X500Name issuer = new X509CertificateHolder ( certificateAuthorityCert . getEncoded ( ) ) . getSubject ( ) ; X500Name subject = new X500Name ( "CN=" + domain + ", O=MockServer, L=London, ST=England, C=UK" ) ; BigInteger serial = BigInteger . valueOf ( new Random ( ) . nextInt ( Integer . MAX_VALUE ) ) ; X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder ( issuer , serial , NOT_BEFORE , NOT_AFTER , subject , publicKey ) ; builder . addExtension ( Extension . subjectKeyIdentifier , false , createSubjectKeyIdentifier ( publicKey ) ) ; builder . addExtension ( Extension . basicConstraints , false , new BasicConstraints ( false ) ) ; List < ASN1Encodable > subjectAlternativeNames = new ArrayList < ASN1Encodable > ( ) ; if ( subjectAlternativeNameDomains != null ) { subjectAlternativeNames . add ( new GeneralName ( GeneralName . dNSName , domain ) ) ; for ( String subjectAlternativeNameDomain : subjectAlternativeNameDomains ) { subjectAlternativeNames . add ( new GeneralName ( GeneralName . dNSName , subjectAlternativeNameDomain ) ) ; } } if ( subjectAlternativeNameIps != null ) { for ( String subjectAlternativeNameIp : subjectAlternativeNameIps ) { if ( IPAddress . isValidIPv6WithNetmask ( subjectAlternativeNameIp ) || IPAddress . isValidIPv6 ( subjectAlternativeNameIp ) || IPAddress . isValidIPv4WithNetmask ( subjectAlternativeNameIp ) || IPAddress . isValidIPv4 ( subjectAlternativeNameIp ) ) { subjectAlternativeNames . add ( new GeneralName ( GeneralName . iPAddress , subjectAlternativeNameIp ) ) ; } } } if ( subjectAlternativeNames . size ( ) > 0 ) { DERSequence subjectAlternativeNamesExtension = new DERSequence ( subjectAlternativeNames . toArray ( new ASN1Encodable [ subjectAlternativeNames . size ( ) ] ) ) ; builder . addExtension ( Extension . subjectAlternativeName , false , subjectAlternativeNamesExtension ) ; } X509Certificate cert = signCertificate ( builder , certificateAuthorityPrivateKey ) ; cert . checkValidity ( new Date ( ) ) ; cert . verify ( certificateAuthorityPublicKey ) ; return cert ; }
Create a server certificate for the given domain and subject alternative names signed by the given Certificate Authority .
31,392
private String saveCertificateAsPEMFile ( Object x509Certificate , String filename , boolean deleteOnExit ) throws IOException { File pemFile = File . createTempFile ( filename , null ) ; try ( FileWriter pemfileWriter = new FileWriter ( pemFile ) ) { try ( JcaPEMWriter jcaPEMWriter = new JcaPEMWriter ( pemfileWriter ) ) { jcaPEMWriter . writeObject ( x509Certificate ) ; } } if ( deleteOnExit ) { pemFile . deleteOnExit ( ) ; } return pemFile . getAbsolutePath ( ) ; }
Saves X509Certificate as Base - 64 encoded PEM file .
31,393
private RSAPrivateKey loadPrivateKeyFromPEMFile ( String filename ) { try { String publicKeyFile = FileReader . readFileFromClassPathOrPath ( filename ) ; byte [ ] publicKeyBytes = DatatypeConverter . parseBase64Binary ( publicKeyFile . replace ( "-----BEGIN RSA PRIVATE KEY-----" , "" ) . replace ( "-----END RSA PRIVATE KEY-----" , "" ) ) ; return ( RSAPrivateKey ) KeyFactory . getInstance ( "RSA" ) . generatePrivate ( new PKCS8EncodedKeySpec ( publicKeyBytes ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "Exception reading private key from PEM file" , e ) ; } }
Load PrivateKey from PEM file .
31,394
private X509Certificate loadX509FromPEMFile ( String filename ) { try { return ( X509Certificate ) CertificateFactory . getInstance ( "X.509" ) . generateCertificate ( FileReader . openStreamToFileFromClassPathOrPath ( filename ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "Exception reading X509 from PEM file" , e ) ; } }
Load X509 from PEM file .
31,395
public static HttpResponse response ( String body ) { return new HttpResponse ( ) . withStatusCode ( OK_200 . code ( ) ) . withReasonPhrase ( OK_200 . reasonPhrase ( ) ) . withBody ( body ) ; }
Static builder to create a response with a 200 status code and the string response body .
31,396
public HttpResponse replaceHeader ( String name , String ... values ) { this . headers . replaceEntry ( name , values ) ; return this ; }
Update header to return as a Header object if a header with the same name already exists it will be modified
31,397
public HttpResponse withCookie ( String name , String value ) { this . cookies . withEntry ( name , value ) ; return this ; }
Add cookie to return as Set - Cookie header
31,398
public static HttpTemplate template ( TemplateType type , String template ) { return new HttpTemplate ( type ) . withTemplate ( template ) ; }
Static builder to create an template for responding or forwarding requests .
31,399
public static String weightingToFileName ( Weighting w , boolean edgeBased ) { return toLowerCase ( w . toString ( ) ) . replaceAll ( "\\|" , "_" ) + ( edgeBased ? "_edge" : "_node" ) ; }
Replaces all characters which are not numbers characters or underscores with underscores