idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
13,000
public static Image getScaledInstance ( Image img , int targetWidth , int targetHeight ) { final int type = BufferedImage . TYPE_INT_ARGB ; Image ret = img ; final int width = ret . getWidth ( null ) ; final int height = ret . getHeight ( null ) ; if ( width != targetWidth && height != targetHeight ) { final BufferedImage scratchImage = new BufferedImage ( targetWidth , targetHeight , type ) ; final Graphics2D g2 = scratchImage . createGraphics ( ) ; g2 . setRenderingHint ( RenderingHints . KEY_INTERPOLATION , RenderingHints . VALUE_INTERPOLATION_BILINEAR ) ; g2 . drawImage ( ret , 0 , 0 , targetWidth , targetHeight , 0 , 0 , width , height , null ) ; g2 . dispose ( ) ; ret = scratchImage ; } return ret ; }
Redimensionne une image .
13,001
public static void writeXml ( Serializable serializable , OutputStream output ) throws IOException { TransportFormat . XML . writeSerializableTo ( serializable , output ) ; }
Export XML .
13,002
public static void writeJson ( Serializable serializable , OutputStream output ) throws IOException { TransportFormat . JSON . writeSerializableTo ( serializable , output ) ; }
Export JSON .
13,003
private static void initLookAndFeel ( ) { for ( final LookAndFeelInfo info : UIManager . getInstalledLookAndFeels ( ) ) { if ( "Nimbus" . equals ( info . getName ( ) ) ) { try { UIManager . setLookAndFeel ( info . getClassName ( ) ) ; break ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } } } }
Initialisation du L&F .
13,004
public static ResourceBundle getResourceBundle ( ) { final Locale currentLocale = getCurrentLocale ( ) ; if ( Locale . ENGLISH . getLanguage ( ) . equals ( currentLocale . getLanguage ( ) ) ) { return ResourceBundle . getBundle ( RESOURCE_BUNDLE_BASE_NAME , ROOT_LOCALE ) ; } return ResourceBundle . getBundle ( RESOURCE_BUNDLE_BASE_NAME , currentLocale ) ; }
Retourne les traductions pour la locale courante .
13,005
public static String getStringForJavascript ( String key ) { final String string = getString ( key ) ; return string . replace ( "\\" , "\\\\" ) . replace ( "\n" , "\\n" ) . replace ( "\"" , "\\\"" ) . replace ( "'" , "\\'" ) ; }
Retourne une traduction dans la locale courante et l encode pour affichage en javascript .
13,006
public static String htmlEncode ( String text , boolean encodeSpace ) { String result = text . replaceAll ( "[&]" , "&amp;" ) . replaceAll ( "[<]" , "&lt;" ) . replaceAll ( "[>]" , "&gt;" ) . replaceAll ( "[\n]" , "<br/>" ) ; if ( encodeSpace ) { result = result . replaceAll ( " " , "&nbsp;" ) ; } return result ; }
Encode pour affichage en html .
13,007
void readFromFile ( ) throws IOException { final Counter counter = new CounterStorage ( this ) . readFromFile ( ) ; if ( counter != null ) { final Counter newCounter = clone ( ) ; startDate = counter . getStartDate ( ) ; requests . clear ( ) ; for ( final CounterRequest request : counter . getRequests ( ) ) { requests . put ( request . getName ( ) , request ) ; } if ( errors != null ) { errors . clear ( ) ; errors . addAll ( counter . getErrors ( ) ) ; } addRequestsAndErrors ( newCounter ) ; } }
Lecture du counter depuis son fichier .
13,008
protected File chooseFile ( final JTable table , final String extension ) throws IOException { final JFileChooser myFileChooser = getFileChooser ( ) ; final MExtensionFileFilter filter = new MExtensionFileFilter ( extension ) ; myFileChooser . addChoosableFileFilter ( filter ) ; String title = buildTitle ( table ) ; if ( title != null ) { final String notAllowed = "\\/:*?\"<>|" ; final int notAllowedLength = notAllowed . length ( ) ; for ( int i = 0 ; i < notAllowedLength ; i ++ ) { title = title . replace ( notAllowed . charAt ( i ) , ' ' ) ; } myFileChooser . setSelectedFile ( new File ( title ) ) ; } try { final Component parent = table . getParent ( ) != null ? table . getParent ( ) : table ; if ( myFileChooser . showSaveDialog ( parent ) == JFileChooser . APPROVE_OPTION ) { String fileName = myFileChooser . getSelectedFile ( ) . getCanonicalPath ( ) ; if ( ! fileName . endsWith ( '.' + extension ) ) { fileName += '.' + extension ; } return new File ( fileName ) ; } return null ; } finally { myFileChooser . removeChoosableFileFilter ( filter ) ; } }
Choix du fichier pour un export .
13,009
public void restore ( ) { if ( window instanceof RootPaneContainer ) { final Component glassPane = ( ( RootPaneContainer ) window ) . getGlassPane ( ) ; glassPane . setVisible ( windowGlassPaneVisible ) ; glassPane . setCursor ( oldWindowCursor ) ; } if ( window != null ) { window . setCursor ( oldWindowCursor ) ; } }
Restore l ancien curseur en fin de traitement .
13,010
protected String getRequestName ( MethodInvocation invocation ) { final String classPart = getClassPart ( invocation ) ; final String methodPart = getMethodPart ( invocation ) ; return classPart + '.' + methodPart ; }
Determine request name for a method invocation .
13,011
protected synchronized void write ( long offset , byte [ ] b ) throws IOException { if ( byteBuffer != null ) { byteBuffer . position ( ( int ) offset ) ; byteBuffer . put ( b ) ; } else { throw new IOException ( "Write failed, file " + getPath ( ) + " not mapped for I/O" ) ; } }
Writes bytes to the underlying RRD file on the disk
13,012
protected synchronized void read ( long offset , byte [ ] b ) throws IOException { if ( byteBuffer != null ) { byteBuffer . position ( ( int ) offset ) ; byteBuffer . get ( b ) ; } else { throw new IOException ( "Read failed, file " + getPath ( ) + " not mapped for I/O" ) ; } }
Reads a number of bytes from the RRD file on the disk
13,013
public synchronized void close ( ) throws IOException { try { if ( syncTask != null ) { syncTask . cancel ( ) ; } sync ( ) ; unmapFile ( ) ; } finally { super . close ( ) ; } }
Closes the underlying RRD file .
13,014
public static void uninstall ( ) { final PopupFactory factory = PopupFactory . getSharedInstance ( ) ; if ( ! ( factory instanceof ShadowPopupFactory ) ) { return ; } final PopupFactory stored = ( ( ShadowPopupFactory ) factory ) . storedFactory ; PopupFactory . setSharedInstance ( stored ) ; }
Uninstalls the ShadowPopupFactory and restores the original popup factory as the new shared popup factory .
13,015
void report ( boolean includeLastValue ) throws IOException { reportOnMemoryInformations ( javaInformations . getMemoryInformations ( ) ) ; reportOnJavaInformations ( ) ; if ( javaInformations . getTomcatInformationsList ( ) != null ) { reportOnTomcatInformations ( ) ; } if ( javaInformations . isCacheEnabled ( ) ) { reportOnCacheInformations ( ) ; } reportOnCollector ( ) ; if ( includeLastValue ) { reportOnLastValues ( ) ; } }
Produce the full report .
13,016
private void reportOnCollector ( ) { for ( final Counter counter : collector . getCounters ( ) ) { if ( ! counter . isDisplayed ( ) ) { continue ; } final List < CounterRequest > requests = counter . getRequests ( ) ; long hits = 0 ; long duration = 0 ; long errors = 0 ; for ( final CounterRequest cr : requests ) { hits += cr . getHits ( ) ; duration += cr . getDurationsSum ( ) ; errors += cr . getSystemErrors ( ) ; } final String sanitizedName = sanitizeName ( counter . getName ( ) ) ; printLong ( MetricType . COUNTER , sanitizedName + "_hits_count" , "javamelody counter" , hits ) ; if ( ! counter . isErrorCounter ( ) || counter . isJobCounter ( ) ) { printLong ( MetricType . COUNTER , sanitizedName + "_errors_count" , "javamelody counter" , errors ) ; } if ( duration >= 0 ) { printLong ( MetricType . COUNTER , sanitizedName + "_duration_millis" , "javamelody counter" , duration ) ; } } }
Reports on hits errors and duration sum for all counters in the collector .
13,017
private void reportOnLastValues ( ) throws IOException { Collection < JRobin > jrobins = collector . getDisplayedCounterJRobins ( ) ; for ( final JRobin jrobin : jrobins ) { printDouble ( MetricType . GAUGE , "last_value_" + camelToSnake ( jrobin . getName ( ) ) , "javamelody value per minute" , jrobin . getLastValue ( ) ) ; } jrobins = collector . getDisplayedOtherJRobins ( ) ; for ( final JRobin jrobin : jrobins ) { printDouble ( MetricType . GAUGE , "last_value_" + camelToSnake ( jrobin . getName ( ) ) , "javamelody value per minute" , jrobin . getLastValue ( ) ) ; } }
Includes the traditional graph fields from the lastValue API .
13,018
private static String camelToSnake ( String camel ) { return CAMEL_TO_SNAKE_PATTERN . matcher ( camel ) . replaceAll ( "$1_$2" ) . toLowerCase ( Locale . US ) ; }
Converts a camelCase or CamelCase string to camel_case
13,019
private static String sanitizeName ( String name ) { final String lowerCaseName = name . toLowerCase ( Locale . US ) ; final String separatorReplacedName = SANITIZE_TO_UNDERSCORE_PATTERN . matcher ( lowerCaseName ) . replaceAll ( UNDERSCORE ) ; return SANITIZE_REMOVE_PATTERN . matcher ( separatorReplacedName ) . replaceAll ( EMPTY_STRING ) ; }
converts to lowercase replaces common separators with underscores and strips all remaining non - alpha - numeric characters .
13,020
private void printLong ( MetricType metricType , String name , String description , long value ) { printHeader ( metricType , name , description ) ; printLongWithFields ( name , null , value ) ; }
prints a long metric value including HELP and TYPE rows
13,021
private void printDouble ( MetricType metricType , String name , String description , double value ) { printHeader ( metricType , name , description ) ; printDoubleWithFields ( name , null , value ) ; }
prints a double metric value including HELP and TYPE rows
13,022
private void printLongWithFields ( String name , String fields , long value ) { print ( METRIC_PREFIX ) ; print ( name ) ; if ( fields != null ) { print ( fields ) ; } print ( ' ' ) ; println ( String . valueOf ( value ) ) ; }
prints a long metric value with optional fields
13,023
private void printDoubleWithFields ( String name , String fields , double value ) { print ( METRIC_PREFIX ) ; print ( name ) ; if ( fields != null ) { print ( fields ) ; } print ( ' ' ) ; println ( decimalFormat . format ( value ) ) ; }
prints a double metric value with optional fields
13,024
private void printHeader ( MetricType metricType , String name , String description ) { print ( "# HELP " ) ; print ( METRIC_PREFIX ) ; print ( name ) ; print ( ' ' ) ; println ( description ) ; print ( "# TYPE " ) ; print ( METRIC_PREFIX ) ; print ( name ) ; print ( ' ' ) ; println ( metricType . getCode ( ) ) ; }
prints the HELP and TYPE rows
13,025
private void unregisterJmxExpose ( ) { if ( jmxNames . isEmpty ( ) ) { return ; } try { final MBeanServer platformMBeanServer = MBeans . getPlatformMBeanServer ( ) ; for ( final ObjectName name : jmxNames ) { platformMBeanServer . unregisterMBean ( name ) ; } } catch ( final JMException e ) { LOG . warn ( "failed to unregister JMX beans" , e ) ; } }
Unregisters CounterRequestMXBean beans .
13,026
public void onGenericTag ( final PdfWriter writer , final Document document , final Rectangle rect , final String text ) { }
we override the onGenericTag method .
13,027
public void onOpenDocument ( final PdfWriter writer , final Document document ) { try { bf = BaseFont . createFont ( BaseFont . HELVETICA , BaseFont . CP1252 , BaseFont . NOT_EMBEDDED ) ; cb = writer . getDirectContent ( ) ; template = cb . createTemplate ( 50 , 50 ) ; } catch ( final DocumentException de ) { throw new IllegalStateException ( de ) ; } catch ( final IOException ioe ) { throw new IllegalStateException ( ioe ) ; } }
we override the onOpenDocument method .
13,028
public void onEndPage ( final PdfWriter writer , final Document document ) { final int pageN = writer . getPageNumber ( ) ; final String text = pageN + " / " ; final float len = bf . getWidthPoint ( text , 8 ) ; cb . beginText ( ) ; cb . setFontAndSize ( bf , 8 ) ; final float width = document . getPageSize ( ) . getWidth ( ) ; cb . setTextMatrix ( width / 2 , 30 ) ; cb . showText ( text ) ; cb . endText ( ) ; cb . addTemplate ( template , width / 2 + len , 30 ) ; }
we override the onEndPage method .
13,029
public void onCloseDocument ( final PdfWriter writer , final Document document ) { template . beginText ( ) ; template . setFontAndSize ( bf , 8 ) ; template . showText ( String . valueOf ( writer . getPageNumber ( ) - 1 ) ) ; template . endText ( ) ; }
we override the onCloseDocument method .
13,030
public static void initBackendFactory ( Timer timer ) throws IOException { RrdNioBackend . setFileSyncTimer ( timer ) ; try { if ( ! RrdBackendFactory . getDefaultFactory ( ) . getFactoryName ( ) . equals ( RrdNioBackendFactory . FACTORY_NAME ) ) { RrdBackendFactory . registerAndSetAsDefaultFactory ( new RrdNioBackendFactory ( ) ) ; } } catch ( final RrdException e ) { throw createIOException ( e ) ; } }
JavaMelody uses a custom RrdNioBackendFactory in order to use its own and cancelable file sync timer .
13,031
protected String formatCsv ( final String text , final char csvSeparator ) { String result = text ; if ( result . indexOf ( '\n' ) != - 1 ) { result = result . replace ( '\n' , ' ' ) ; } int index = result . indexOf ( '"' ) ; while ( index != - 1 ) { result = new StringBuilder ( result ) . insert ( index , '"' ) . toString ( ) ; index = result . indexOf ( '"' , index + 2 ) ; } if ( text . indexOf ( csvSeparator ) != - 1 || text . indexOf ( '"' ) != - 1 ) { final String tmp = '"' + result + '"' ; result = tmp ; } return result ; }
Encode un texte pour l export au format csv ou csv local .
13,032
protected void writeCsvHeader ( final JTable table , final Writer out , final char csvSeparator ) throws IOException { final int columnCount = table . getColumnModel ( ) . getColumnCount ( ) ; final String eol = System . getProperty ( "line.separator" ) ; if ( table . getName ( ) != null ) { String title = formatCsv ( table . getName ( ) , csvSeparator ) ; if ( title . startsWith ( "ID" ) ) { final String tmp = '"' + title + '"' ; title = tmp ; } out . write ( title ) ; out . write ( eol ) ; } String text ; for ( int i = 0 ; i < columnCount ; i ++ ) { text = String . valueOf ( table . getColumnModel ( ) . getColumn ( i ) . getHeaderValue ( ) ) ; text = formatCsv ( text , csvSeparator ) ; if ( i == 0 && text . startsWith ( "ID" ) ) { out . write ( '"' + text + '"' ) ; } else { out . write ( text ) ; } if ( i < columnCount - 1 ) { out . write ( csvSeparator ) ; } } out . write ( eol ) ; }
Exporte les headers csv d une JTable ..
13,033
public void close ( ) throws IOException { if ( writer != null ) { writer . close ( ) ; } else if ( stream != null ) { stream . close ( ) ; } }
Ferme le flux .
13,034
protected DocWriter createWriter ( final MBasicTable table , final Document document , final OutputStream out ) { final RtfWriter2 writer = RtfWriter2 . getInstance ( document , out ) ; final String title = buildTitle ( table ) ; if ( title != null ) { final HeaderFooter header = new RtfHeaderFooter ( new Paragraph ( title ) ) ; header . setAlignment ( Element . ALIGN_LEFT ) ; header . setBorder ( Rectangle . NO_BORDER ) ; document . setHeader ( header ) ; document . addTitle ( title ) ; } final Paragraph footerParagraph = new Paragraph ( ) ; final Font font = FontFactory . getFont ( FontFactory . TIMES_ROMAN , 12 , Font . NORMAL ) ; footerParagraph . add ( new RtfPageNumber ( font ) ) ; footerParagraph . add ( new Phrase ( " / " , font ) ) ; footerParagraph . add ( new RtfTotalPageNumber ( font ) ) ; footerParagraph . setAlignment ( Element . ALIGN_CENTER ) ; final HeaderFooter footer = new RtfHeaderFooter ( footerParagraph ) ; footer . setBorder ( Rectangle . TOP ) ; document . setFooter ( footer ) ; return writer ; }
We create a writer that listens to the document and directs a RTF - stream to out
13,035
public Object invoke ( MethodInvocation invocation ) throws Throwable { if ( DISABLED || ! SPRING_COUNTER . isDisplayed ( ) ) { return invocation . proceed ( ) ; } final String requestName = getRequestName ( invocation ) ; boolean systemError = false ; try { SPRING_COUNTER . bindContextIncludingCpu ( requestName ) ; return invocation . proceed ( ) ; } catch ( final Error e ) { systemError = true ; throw e ; } finally { SPRING_COUNTER . addRequestForCurrentContext ( systemError ) ; } }
Performs method invocation .
13,036
public static Object invokeTarget ( Object target , Method method , Object [ ] args , final String requestName ) throws IllegalAccessException , InvocationTargetException { boolean systemError = false ; try { SERVICES_COUNTER . bindContextIncludingCpu ( requestName ) ; return method . invoke ( target , args ) ; } catch ( final InvocationTargetException e ) { if ( e . getCause ( ) instanceof Error ) { systemError = true ; } throw e ; } finally { SERVICES_COUNTER . addRequestForCurrentContext ( systemError ) ; } }
Invoke target .
13,037
private URLConnection openConnection ( ) throws IOException { final URLConnection connection = url . openConnection ( ) ; connection . setUseCaches ( false ) ; if ( CONNECTION_TIMEOUT > 0 ) { connection . setConnectTimeout ( CONNECTION_TIMEOUT ) ; } if ( READ_TIMEOUT > 0 ) { connection . setReadTimeout ( READ_TIMEOUT ) ; } connection . setRequestProperty ( "Accept-Encoding" , "gzip" ) ; if ( headers != null ) { for ( final Map . Entry < String , String > entry : headers . entrySet ( ) ) { connection . setRequestProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } if ( url . getUserInfo ( ) != null ) { final String authorization = Base64Coder . encodeString ( url . getUserInfo ( ) ) ; connection . setRequestProperty ( "Authorization" , "Basic " + authorization ) ; } return connection ; }
Ouvre la connection http .
13,038
@ SuppressWarnings ( "unchecked" ) private < T > T createMockResultOfCall ( ) throws IOException { final Object result ; final String request = url . toString ( ) ; if ( ! request . contains ( HttpParameter . PART . getName ( ) + '=' ) && ! request . contains ( HttpParameter . JMX_VALUE . getName ( ) ) || request . contains ( HttpPart . DEFAULT_WITH_CURRENT_REQUESTS . getName ( ) ) ) { final String message = request . contains ( "/test2" ) ? null : "ceci est message pour le rapport" ; result = Arrays . asList ( new Counter ( Counter . HTTP_COUNTER_NAME , null ) , new Counter ( "services" , null ) , new Counter ( Counter . ERROR_COUNTER_NAME , null ) , new JavaInformations ( null , true ) , message ) ; } else { result = LabradorMock . createMockResultOfPartCall ( request ) ; } return ( T ) result ; }
bouchon pour tests unitaires
13,039
public boolean accept ( final File file ) { if ( file != null ) { if ( file . isDirectory ( ) ) { return true ; } final String extension = getExtension ( file ) ; if ( extension != null && filters . containsKey ( extension ) ) { return true ; } } return false ; }
Return true if this file should be shown in the directory pane false if it shouldn t .
13,040
public String getExtension ( final File file ) { if ( file != null ) { final String fileName = file . getName ( ) ; final int i = fileName . lastIndexOf ( '.' ) ; if ( i > 0 && i < fileName . length ( ) - 1 ) { return fileName . substring ( i + 1 ) . toLowerCase ( Locale . getDefault ( ) ) ; } } return null ; }
Return the extension portion of the file s name .
13,041
private static File extractFromJar ( String resource , String fileName , String suffix ) throws IOException { final URL res = Main . class . getResource ( resource ) ; final File tmp ; try { tmp = File . createTempFile ( fileName , suffix ) ; } catch ( final IOException e ) { final String tmpdir = System . getProperty ( "java.io.tmpdir" ) ; throw new IllegalStateException ( "JavaMelody has failed to create a temporary file in " + tmpdir , e ) ; } final InputStream is = res . openStream ( ) ; try { final OutputStream os = new FileOutputStream ( tmp ) ; try { copyStream ( is , os ) ; } finally { os . close ( ) ; } } finally { is . close ( ) ; } tmp . deleteOnExit ( ) ; return tmp ; }
Extract a resource from jar mark it for deletion upon exit and return its location .
13,042
public static void start ( int port , Map < Parameter , String > parameters ) throws Exception { final Server server = new Server ( port ) ; final ContextHandlerCollection contexts = new ContextHandlerCollection ( ) ; final ServletContextHandler context = new ServletContextHandler ( contexts , "/" , ServletContextHandler . SESSIONS ) ; final net . bull . javamelody . MonitoringFilter monitoringFilter = new net . bull . javamelody . MonitoringFilter ( ) ; monitoringFilter . setApplicationType ( "Standalone" ) ; final FilterHolder filterHolder = new FilterHolder ( monitoringFilter ) ; if ( parameters != null ) { for ( final Map . Entry < Parameter , String > entry : parameters . entrySet ( ) ) { final net . bull . javamelody . Parameter parameter = entry . getKey ( ) ; final String value = entry . getValue ( ) ; filterHolder . setInitParameter ( parameter . getCode ( ) , value ) ; } } context . addFilter ( filterHolder , "/*" , EnumSet . of ( DispatcherType . INCLUDE , DispatcherType . REQUEST ) ) ; final RequestLogHandler requestLogHandler = new RequestLogHandler ( ) ; contexts . addHandler ( requestLogHandler ) ; final HandlerCollection handlers = new HandlerCollection ( ) ; handlers . setHandlers ( new Handler [ ] { contexts } ) ; server . setHandler ( handlers ) ; server . start ( ) ; }
Start the server with a http port and optional javamelody parameters .
13,043
private boolean isUserAuthorized ( HttpServletRequest httpRequest ) { if ( authorizedUsers == null ) { return true ; } final String auth = httpRequest . getHeader ( "Authorization" ) ; if ( auth == null ) { return false ; } if ( ! auth . toUpperCase ( Locale . ENGLISH ) . startsWith ( "BASIC " ) ) { return false ; } final String userpassEncoded = auth . substring ( "BASIC " . length ( ) ) ; final String userpassDecoded = Base64Coder . decodeString ( userpassEncoded ) ; final boolean authOk = authorizedUsers . contains ( userpassDecoded ) ; return checkLockAgainstBruteForceAttack ( authOk ) ; }
Check if the user is authorized when using the authorized - users parameter
13,044
public static void invalidateAllSessionsExceptCurrentSession ( HttpSession currentSession ) { for ( final HttpSession session : SESSION_MAP_BY_ID . values ( ) ) { try { if ( currentSession != null && currentSession . getId ( ) . equals ( session . getId ( ) ) ) { continue ; } session . invalidate ( ) ; } catch ( final Exception e ) { continue ; } } }
since 1 . 49
13,045
public static String encodeLines ( byte [ ] in , int iOff , int iLen , int lineLen , String lineSeparator ) { final int blockLen = lineLen * 3 / 4 ; if ( blockLen <= 0 ) { throw new IllegalArgumentException ( ) ; } final int lines = ( iLen + blockLen - 1 ) / blockLen ; final int bufLen = ( iLen + 2 ) / 3 * 4 + lines * lineSeparator . length ( ) ; final StringBuilder buf = new StringBuilder ( bufLen ) ; int ip = 0 ; while ( ip < iLen ) { final int l = Math . min ( iLen - ip , blockLen ) ; buf . append ( encode ( in , iOff + ip , l ) ) ; buf . append ( lineSeparator ) ; ip += l ; } return buf . toString ( ) ; }
Encodes a byte array into Base 64 format and breaks the output into lines .
13,046
public static char [ ] encode ( byte [ ] in , int iOff , int iLen ) { final int oDataLen = ( iLen * 4 + 2 ) / 3 ; final int oLen = ( iLen + 2 ) / 3 * 4 ; final char [ ] out = new char [ oLen ] ; int ip = iOff ; final int iEnd = iOff + iLen ; int op = 0 ; while ( ip < iEnd ) { final int i0 = in [ ip ++ ] & 0xff ; final int i1 = ip < iEnd ? in [ ip ++ ] & 0xff : 0 ; final int i2 = ip < iEnd ? in [ ip ++ ] & 0xff : 0 ; final int o0 = i0 >>> 2 ; final int o1 = ( i0 & 3 ) << 4 | i1 >>> 4 ; final int o2 = ( i1 & 0xf ) << 2 | i2 >>> 6 ; final int o3 = i2 & 0x3F ; out [ op ++ ] = MAP1 [ o0 ] ; out [ op ++ ] = MAP1 [ o1 ] ; out [ op ] = op < oDataLen ? MAP1 [ o2 ] : '=' ; op ++ ; out [ op ] = op < oDataLen ? MAP1 [ o3 ] : '=' ; op ++ ; } return out ; }
Encodes a byte array into Base64 format . No blanks or line breaks are inserted in the output .
13,047
@ ConditionalOnMissingBean ( DefaultAdvisorAutoProxyCreator . class ) @ ConditionalOnProperty ( prefix = JavaMelodyConfigurationProperties . PREFIX , name = "advisor-auto-proxy-creator-enabled" , matchIfMissing = false ) public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator ( ) { return new DefaultAdvisorAutoProxyCreator ( ) ; }
Now disabled by default since dependency spring - boot - starter - aop was added in 1 . 76 .
13,048
@ SuppressWarnings ( "unchecked" ) @ ConditionalOnClass ( name = "org.springframework.cloud.openfeign.FeignClient" ) @ ConditionalOnProperty ( prefix = JavaMelodyConfigurationProperties . PREFIX , name = "spring-monitoring-enabled" , matchIfMissing = true ) @ ConditionalOnMissingBean ( DefaultAdvisorAutoProxyCreator . class ) public MonitoringSpringAdvisor monitoringFeignClientAdvisor ( ) throws ClassNotFoundException { final Class < ? extends Annotation > feignClientClass = ( Class < ? extends Annotation > ) Class . forName ( "org.springframework.cloud.openfeign.FeignClient" ) ; final MonitoringSpringAdvisor advisor = new MonitoringSpringAdvisor ( new AnnotationMatchingPointcut ( feignClientClass , true ) ) ; advisor . setAdvice ( new MonitoringSpringInterceptor ( ) { private static final long serialVersionUID = 1L ; protected String getRequestName ( MethodInvocation invocation ) { final StringBuilder sb = new StringBuilder ( ) ; final Method method = invocation . getMethod ( ) ; final RequestMapping requestMapping = method . getAnnotation ( RequestMapping . class ) ; if ( requestMapping != null ) { String [ ] path = requestMapping . value ( ) ; if ( path . length == 0 ) { path = requestMapping . path ( ) ; } if ( path . length > 0 ) { sb . append ( path [ 0 ] ) ; sb . append ( ' ' ) ; if ( requestMapping . method ( ) . length > 0 ) { sb . append ( requestMapping . method ( ) [ 0 ] . name ( ) ) ; } else { sb . append ( "GET" ) ; } sb . append ( '\n' ) ; } } final Class < ? > declaringClass = method . getDeclaringClass ( ) ; final String classPart = declaringClass . getSimpleName ( ) ; final String methodPart = method . getName ( ) ; sb . append ( classPart ) . append ( '.' ) . append ( methodPart ) ; return sb . toString ( ) ; } } ) ; return advisor ; }
Monitoring of Feign clients .
13,049
protected RrdBackend open ( String path , boolean readOnly ) throws IOException { return new RrdNioBackend ( path , readOnly , syncPeriod ) ; }
Creates RrdNioBackend object for the given file path .
13,050
public static void registerApplicationNodeInCollectServer ( String applicationName , URL collectServerUrl , URL applicationNodeUrl ) { if ( collectServerUrl == null || applicationNodeUrl == null ) { throw new IllegalArgumentException ( "collectServerUrl and applicationNodeUrl must not be null" ) ; } final String appName ; if ( applicationName == null ) { appName = Parameters . getCurrentApplication ( ) ; } else { appName = applicationName ; } final URL registerUrl ; try { registerUrl = new URL ( collectServerUrl . toExternalForm ( ) + "?appName=" + URLEncoder . encode ( appName , "UTF-8" ) + "&appUrls=" + URLEncoder . encode ( applicationNodeUrl . toExternalForm ( ) , "UTF-8" ) + "&action=registerNode" ) ; unregisterApplicationNodeInCollectServerUrl = new URL ( registerUrl . toExternalForm ( ) . replace ( "registerNode" , "unregisterNode" ) ) ; } catch ( final IOException e ) { throw new IllegalArgumentException ( e ) ; } final Thread thread = new Thread ( "javamelody registerApplicationNodeInCollectServer" ) { public void run ( ) { try { Thread . sleep ( 10000 ) ; } catch ( final InterruptedException e ) { throw new IllegalStateException ( e ) ; } try { new LabradorRetriever ( registerUrl ) . post ( null ) ; LOG . info ( "application node added to the collect server" ) ; } catch ( final IOException e ) { LOG . warn ( "Unable to register application's node in the collect server ( " + e + ')' , e ) ; } } } ; thread . setDaemon ( true ) ; thread . start ( ) ; }
Asynchronously calls the optional collect server to register this application s node to be monitored .
13,051
public static void unregisterApplicationNodeInCollectServer ( ) throws IOException { if ( unregisterApplicationNodeInCollectServerUrl != null ) { new LabradorRetriever ( unregisterApplicationNodeInCollectServerUrl ) . post ( null ) ; LOG . info ( "application node removed from the collect server" ) ; } }
Call the optional collect server to unregister this application s node .
13,052
public void send ( String toAddress , String subject , String message , List < File > attachments , boolean highPriority ) throws NamingException , MessagingException { assert toAddress != null ; assert subject != null ; assert message != null ; final InternetAddress [ ] toAddresses = InternetAddress . parse ( toAddress , false ) ; final Message msg = new MimeMessage ( getSession ( ) ) ; msg . setRecipients ( Message . RecipientType . TO , toAddresses ) ; msg . setSubject ( subject ) ; msg . setSentDate ( new Date ( ) ) ; msg . setFrom ( fromAddress ) ; if ( highPriority ) { msg . setHeader ( "X-Priority" , "1" ) ; msg . setHeader ( "x-msmail-priority" , "high" ) ; } final MimeBodyPart mbp = new MimeBodyPart ( ) ; mbp . setText ( message ) ; final Multipart multipart = new MimeMultipart ( ) ; multipart . addBodyPart ( mbp ) ; if ( attachments != null && ! attachments . isEmpty ( ) ) { for ( final File attachment : attachments ) { final DataSource source = new FileDataSource ( attachment ) ; final MimeBodyPart messageBodyPart = new MimeBodyPart ( ) ; messageBodyPart . setDataHandler ( new DataHandler ( source ) ) ; messageBodyPart . setFileName ( attachment . getName ( ) ) ; multipart . addBodyPart ( messageBodyPart ) ; } } msg . setContent ( multipart ) ; String protocol = session . getProperty ( "mail.transport.protocol" ) ; if ( protocol == null ) { protocol = "smtp" ; } if ( Boolean . parseBoolean ( session . getProperty ( "mail." + protocol + ".auth" ) ) ) { final Transport tr = session . getTransport ( protocol ) ; try { tr . connect ( session . getProperty ( "mail." + protocol + ".user" ) , session . getProperty ( "mail." + protocol + ".password" ) ) ; msg . saveChanges ( ) ; tr . sendMessage ( msg , msg . getAllRecipients ( ) ) ; } finally { tr . close ( ) ; } } else { Transport . send ( msg ) ; } }
Envoie un mail .
13,053
protected void writeXml ( MListTable < ? > table , OutputStream outputStream ) throws IOException { final List < ? > list = table . getList ( ) ; TransportFormatAdapter . writeXml ( ( Serializable ) list , outputStream ) ; }
Exporte une MListTable dans un fichier au format xml .
13,054
private void createWriter ( Document document , String title ) throws DocumentException , IOException { final PdfWriter writer = PdfWriter . getInstance ( document , output ) ; final HeaderFooter header = new HeaderFooter ( new Phrase ( title ) , false ) ; header . setAlignment ( Element . ALIGN_LEFT ) ; header . setBorder ( Rectangle . NO_BORDER ) ; document . setHeader ( header ) ; writer . setPageEvent ( new PdfAdvancedPageNumberEvents ( ) ) ; }
We create a writer that listens to the document and directs a PDF - stream to output
13,055
protected void writePdf ( final MBasicTable table , final OutputStream out ) throws IOException { try { final Rectangle pageSize = landscape ? PageSize . A4 . rotate ( ) : PageSize . A4 ; final Document document = new Document ( pageSize , 50 , 50 , 50 , 50 ) ; createWriter ( table , document , out ) ; document . addAuthor ( System . getProperty ( "user.name" ) ) ; document . addCreator ( "JavaMelody" ) ; final String title = buildTitle ( table ) ; if ( title != null ) { document . addTitle ( title ) ; } document . open ( ) ; final Table datatable = new Table ( table . getColumnCount ( ) ) ; datatable . setCellsFitPage ( true ) ; datatable . setPadding ( 4 ) ; datatable . setSpacing ( 0 ) ; renderHeaders ( table , datatable ) ; renderList ( table , datatable ) ; document . add ( datatable ) ; document . close ( ) ; } catch ( final DocumentException e ) { throw new IOException ( e ) ; } }
Ecrit le pdf .
13,056
protected DocWriter createWriter ( final MBasicTable table , final Document document , final OutputStream out ) throws DocumentException { final PdfWriter writer = PdfWriter . getInstance ( document , out ) ; if ( table . getName ( ) != null ) { final HeaderFooter header = new HeaderFooter ( new Phrase ( table . getName ( ) ) , false ) ; header . setAlignment ( Element . ALIGN_LEFT ) ; header . setBorder ( Rectangle . NO_BORDER ) ; document . setHeader ( header ) ; document . addTitle ( table . getName ( ) ) ; } writer . setPageEvent ( new AdvancedPageNumberEvents ( ) ) ; return writer ; }
We create a writer that listens to the document and directs a PDF - stream to out
13,057
protected void renderHeaders ( final MBasicTable table , final Table datatable ) throws BadElementException { final int columnCount = table . getColumnCount ( ) ; final TableColumnModel columnModel = table . getColumnModel ( ) ; float totalWidth = 0 ; for ( int i = 0 ; i < columnCount ; i ++ ) { totalWidth += columnModel . getColumn ( i ) . getWidth ( ) ; } final float [ ] headerwidths = new float [ columnCount ] ; for ( int i = 0 ; i < columnCount ; i ++ ) { headerwidths [ i ] = 100f * columnModel . getColumn ( i ) . getWidth ( ) / totalWidth ; } datatable . setWidths ( headerwidths ) ; datatable . setWidth ( 100f ) ; final Font font = FontFactory . getFont ( FontFactory . HELVETICA , 12 , Font . BOLD ) ; datatable . getDefaultCell ( ) . setBorderWidth ( 2 ) ; datatable . getDefaultCell ( ) . setHorizontalAlignment ( Element . ALIGN_CENTER ) ; String text ; Object value ; for ( int i = 0 ; i < columnCount ; i ++ ) { value = columnModel . getColumn ( i ) . getHeaderValue ( ) ; text = value != null ? value . toString ( ) : "" ; datatable . addCell ( new Phrase ( text , font ) ) ; } datatable . endHeaders ( ) ; }
Effectue le rendu des headers .
13,058
protected void renderList ( final MBasicTable table , final Table datatable ) throws BadElementException { final int columnCount = table . getColumnCount ( ) ; final int rowCount = table . getRowCount ( ) ; final Font font = FontFactory . getFont ( FontFactory . HELVETICA , 10 , Font . NORMAL ) ; datatable . getDefaultCell ( ) . setBorderWidth ( 1 ) ; datatable . getDefaultCell ( ) . setHorizontalAlignment ( Element . ALIGN_LEFT ) ; Object value ; String text ; int horizontalAlignment ; for ( int k = 0 ; k < rowCount ; k ++ ) { for ( int i = 0 ; i < columnCount ; i ++ ) { value = getValueAt ( table , k , i ) ; if ( value instanceof Number || value instanceof Date ) { horizontalAlignment = Element . ALIGN_RIGHT ; } else if ( value instanceof Boolean ) { horizontalAlignment = Element . ALIGN_CENTER ; } else { horizontalAlignment = Element . ALIGN_LEFT ; } datatable . getDefaultCell ( ) . setHorizontalAlignment ( horizontalAlignment ) ; text = getTextAt ( table , k , i ) ; datatable . addCell ( new Phrase ( 8 , text != null ? text : "" , font ) ) ; } } }
Effectue le rendu de la liste .
13,059
Counter getWeekCounter ( ) { final Counter weekCounter = createPeriodCounter ( "yyyyWW" , currentDayCounter . getStartDate ( ) ) ; addRequestsAndErrorsForRange ( weekCounter , Period . SEMAINE . getRange ( ) ) ; return weekCounter ; }
compteur des 7 derniers jours
13,060
Counter getYearCounter ( ) throws IOException { final Counter yearCounter = createPeriodCounter ( "yyyy" , currentDayCounter . getStartDate ( ) ) ; yearCounter . addRequestsAndErrors ( currentDayCounter ) ; final Calendar dayCalendar = Calendar . getInstance ( ) ; final int currentMonth = dayCalendar . get ( Calendar . MONTH ) ; dayCalendar . setTime ( currentDayCounter . getStartDate ( ) ) ; dayCalendar . add ( Calendar . DAY_OF_YEAR , - Period . ANNEE . getDurationDays ( ) + 1 ) ; yearCounter . setStartDate ( dayCalendar . getTime ( ) ) ; for ( int i = 1 ; i < Period . ANNEE . getDurationDays ( ) ; i ++ ) { if ( dayCalendar . get ( Calendar . DAY_OF_MONTH ) == 1 && dayCalendar . get ( Calendar . MONTH ) != currentMonth ) { yearCounter . addRequestsAndErrors ( getMonthCounterAtDate ( dayCalendar . getTime ( ) ) ) ; final int nbDaysInMonth = dayCalendar . getActualMaximum ( Calendar . DAY_OF_MONTH ) ; dayCalendar . add ( Calendar . DAY_OF_YEAR , nbDaysInMonth - 1 ) ; i += nbDaysInMonth - 1 ; } else { yearCounter . addRequestsAndErrors ( getDayCounterAtDate ( dayCalendar . getTime ( ) ) ) ; } dayCalendar . add ( Calendar . DAY_OF_YEAR , 1 ) ; } return yearCounter ; }
compteur des 366 derniers jours
13,061
public Cat get ( Integer id ) { if ( DB . isEmpty ( ) ) { addExampleCats ( ) ; } return DB . get ( id ) ; }
Get the Cat for a given id .
13,062
public static boolean isRetryable ( KeeperException e ) { Objects . requireNonNull ( e ) ; switch ( e . code ( ) ) { case CONNECTIONLOSS : case SESSIONEXPIRED : case SESSIONMOVED : case OPERATIONTIMEOUT : return true ; case RUNTIMEINCONSISTENCY : case DATAINCONSISTENCY : case MARSHALLINGERROR : case BADARGUMENTS : case NONODE : case NOAUTH : case BADVERSION : case NOCHILDRENFOREPHEMERALS : case NODEEXISTS : case NOTEMPTY : case INVALIDCALLBACK : case INVALIDACL : case AUTHFAILED : case UNIMPLEMENTED : case SYSTEMERROR : case APIERROR : case OK : default : return false ; } }
Returns true if the given exception indicates an error that can be resolved by retrying the operation without modification .
13,063
public static String checkNotBlank ( String argument ) { Objects . requireNonNull ( argument , ARG_NOT_BLANK_MSG ) ; if ( StringUtils . isBlank ( argument ) ) { throw new IllegalArgumentException ( ARG_NOT_BLANK_MSG ) ; } return argument ; }
Checks that a string is both non - null and non - empty .
13,064
public static byte [ ] toBytes ( Object value ) { try { return mapper . writeValueAsBytes ( value ) ; } catch ( Exception e ) { System . out . println ( e . getMessage ( ) ) ; throw new IllegalArgumentException ( String . format ( "Could not transform to bytes: %s" , e . getMessage ( ) ) ) ; } }
Convert an Object to an array of bytes .
13,065
public static Credentials digestCredentials ( String username , String password ) { MorePreconditions . checkNotBlank ( username ) ; Objects . requireNonNull ( password ) ; return credentials ( "digest" , ( username + ":" + password ) . getBytes ( ) ) ; }
Creates a set of credentials for the zoo keeper digest authentication mechanism .
13,066
public synchronized ZooKeeper get ( Duration connectionTimeout ) throws ZooKeeperConnectionException , InterruptedException , TimeoutException { if ( zooKeeper == null ) { final CountDownLatch connected = new CountDownLatch ( 1 ) ; Watcher watcher = new Watcher ( ) { public void process ( WatchedEvent event ) { switch ( event . getType ( ) ) { case None : switch ( event . getState ( ) ) { case Expired : LOG . info ( "Zookeeper session expired. Event: " + event ) ; close ( ) ; break ; case SyncConnected : connected . countDown ( ) ; break ; default : break ; } break ; default : break ; } eventQueue . offer ( event ) ; } } ; try { zooKeeper = ( sessionState != null ) ? new ZooKeeper ( connectString , sessionTimeoutMs , watcher , sessionState . sessionId , sessionState . sessionPasswd ) : new ZooKeeper ( connectString , sessionTimeoutMs , watcher ) ; } catch ( IOException e ) { throw new ZooKeeperConnectionException ( "Problem connecting to servers: " + zooKeeperServers , e ) ; } if ( connectionTimeout . inMillis ( ) > 0 ) { if ( ! connected . await ( connectionTimeout . inMillis ( ) , TimeUnit . MILLISECONDS ) ) { close ( ) ; throw new TimeoutException ( "Timed out waiting for a ZK connection after " + connectionTimeout ) ; } } else { try { connected . await ( ) ; } catch ( InterruptedException ex ) { LOG . info ( "Interrupted while waiting to connect to zooKeeper" ) ; close ( ) ; throw ex ; } } credentials . authenticate ( zooKeeper ) ; sessionState = new SessionState ( zooKeeper . getSessionId ( ) , zooKeeper . getSessionPasswd ( ) ) ; } return zooKeeper ; }
Returns the current active ZK connection or establishes a new one if none has yet been established or a previous connection was disconnected or had its session time out . This method will attempt to re - use sessions when possible .
13,067
public String getMemberId ( String nodePath ) { MorePreconditions . checkNotBlank ( nodePath ) ; if ( ! nodePath . startsWith ( path + "/" ) ) { throw new IllegalArgumentException ( String . format ( "Not a member of this group[%s]: %s" , path , nodePath ) ) ; } String memberId = StringUtils . substringAfterLast ( nodePath , "/" ) ; if ( ! nodeScheme . isMember ( memberId ) ) { throw new IllegalArgumentException ( String . format ( "Not a group member: %s" , memberId ) ) ; } return memberId ; }
Returns the member id given a node path .
13,068
public Iterable < String > getMemberIds ( ) throws ZooKeeperConnectionException , KeeperException , InterruptedException { return zkClient . get ( ) . getChildren ( path , false ) . stream ( ) . filter ( nodeNameFilter ) . collect ( Collectors . toList ( ) ) ; }
Returns the current list of group member ids by querying ZooKeeper synchronously .
13,069
public byte [ ] getMemberData ( String memberId ) throws ZooKeeperConnectionException , KeeperException , InterruptedException { return zkClient . get ( ) . getData ( getMemberPath ( memberId ) , false , null ) ; }
Gets the data for one of this groups members by querying ZooKeeper synchronously .
13,070
public < T , E extends Exception > T doUntilResult ( ExceptionalSupplier < T , E > task ) throws InterruptedException , BackoffStoppedException , E { T result = task . get ( ) ; return ( result != null ) ? result : retryWork ( task ) ; }
Executes the given task using the configured backoff strategy until the task succeeds as indicated by returning a non - null value .
13,071
public static < T > JsonCodec < T > create ( Class < T > clazz ) { return new JsonCodec < T > ( clazz , DefaultGsonHolder . INSTANCE ) ; }
Creates a new JSON codec instance for objects of the specified class .
13,072
public static < T > JsonCodec < T > create ( Class < T > clazz , Gson gson ) { return new JsonCodec < T > ( clazz , gson ) ; }
Creates a new JSON codec instance for objects of the specified class and the specified Gson instance . You can use this method if you need to customize the behavior of the Gson serializer .
13,073
public static byte [ ] serializeServiceInstance ( ServiceInstance serviceInstance , Codec < ServiceInstance > codec ) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; codec . serialize ( serviceInstance , output ) ; return output . toByteArray ( ) ; }
Returns a serialized Thrift service instance object with given endpoints and codec .
13,074
public static ServiceInstance deserializeServiceInstance ( byte [ ] data , Codec < ServiceInstance > codec ) throws IOException { return codec . deserialize ( new ByteArrayInputStream ( data ) ) ; }
Creates a service instance object deserialized from byte array .
13,075
public static < E > ProxyChannel < E > createProxy ( int capacity , Class < E > iFace , WaitStrategy waitStrategy , Class < ? extends ProxyChannelRingBuffer > backendType ) { if ( ! iFace . isInterface ( ) ) { throw new IllegalArgumentException ( "Not an interface: " + iFace ) ; } String generatedName = Type . getInternalName ( iFace ) + "$JCTools$ProxyChannel$" + backendType . getSimpleName ( ) ; Class < ? > preExisting = findExisting ( generatedName , iFace ) ; if ( preExisting != null ) { return instantiate ( preExisting , capacity , waitStrategy ) ; } List < Method > relevantMethods = findRelevantMethods ( iFace ) ; if ( relevantMethods . isEmpty ( ) ) { throw new IllegalArgumentException ( "Does not declare any abstract methods: " + iFace ) ; } int referenceMessageSize = 0 ; int primitiveMessageSize = 0 ; for ( Method method : relevantMethods ) { int primitiveMethodSize = 0 ; int referenceCount = 0 ; for ( Class < ? > parameterType : method . getParameterTypes ( ) ) { if ( parameterType . isPrimitive ( ) ) { primitiveMethodSize += primitiveMemorySize ( parameterType ) ; } else { referenceCount ++ ; } } primitiveMessageSize = Math . max ( primitiveMessageSize , primitiveMethodSize ) ; referenceMessageSize = Math . max ( referenceMessageSize , referenceCount ) ; } primitiveMessageSize += primitiveMemorySize ( int . class ) ; ClassWriter classWriter = new ClassWriter ( ClassWriter . COMPUTE_MAXS ) ; classWriter . visit ( Opcodes . V1_4 , Opcodes . ACC_SYNTHETIC | Opcodes . ACC_PUBLIC | Opcodes . ACC_FINAL , generatedName , null , Type . getInternalName ( backendType ) , new String [ ] { Type . getInternalName ( ProxyChannel . class ) , Type . getInternalName ( iFace ) } ) ; implementInstanceFields ( classWriter ) ; implementConstructor ( classWriter , backendType , generatedName , primitiveMessageSize , referenceMessageSize ) ; implementProxyInstance ( classWriter , iFace , generatedName ) ; implementProxy ( classWriter , iFace , generatedName ) ; implementUserMethods ( classWriter , relevantMethods , generatedName , backendType ) ; implementProcess ( classWriter , backendType , relevantMethods , iFace , generatedName ) ; classWriter . visitEnd ( ) ; synchronized ( ProxyChannelFactory . class ) { preExisting = findExisting ( generatedName , iFace ) ; if ( preExisting != null ) { return instantiate ( preExisting , capacity , waitStrategy ) ; } byte [ ] byteCode = classWriter . toByteArray ( ) ; printClassBytes ( byteCode ) ; Class < ? > definedClass = UnsafeAccess . UNSAFE . defineClass ( generatedName , byteCode , 0 , byteCode . length , iFace . getClassLoader ( ) , null ) ; return instantiate ( definedClass , capacity , waitStrategy ) ; } }
Create a proxy channel using a user supplied back end .
13,076
public static long align ( final long value , final int alignment ) { if ( ! isPowerOfTwo ( alignment ) ) { throw new IllegalArgumentException ( "alignment must be a power of 2:" + alignment ) ; } return ( value + ( alignment - 1 ) ) & ~ ( alignment - 1 ) ; }
Align a value to the next multiple up of alignment . If the value equals an alignment multiple then it is returned unchanged .
13,077
private boolean isFull ( final long producerPosition ) { final long consumerPosition = lvConsumerPosition ( ) ; final long producerLimit = consumerPosition + this . cycleLength ; if ( producerPosition < producerLimit ) { soProducerLimit ( producerLimit ) ; return false ; } else { return true ; } }
Given the nature of getAndAdd progress on producerPosition and given the potential risk for over claiming it is quite possible for this method to report a queue which is not full as full .
13,078
private boolean fixProducerOverClaim ( final int activeCycleIndex , final long producerCycleClaim , final boolean slowProducer ) { final long expectedProducerCycleClaim = producerCycleClaim + 1 ; if ( ! casProducerCycleClaim ( activeCycleIndex , expectedProducerCycleClaim , producerCycleClaim ) ) { final long currentProducerCycleClaim = lvProducerCycleClaim ( activeCycleIndex ) ; if ( currentProducerCycleClaim <= producerCycleClaim ) { return false ; } if ( slowProducer ) { validateSlowProducerOverClaim ( activeCycleIndex , producerCycleClaim ) ; return true ; } else { return true ; } } return false ; }
It tries to fix a producer overclaim .
13,079
protected void writeReference ( long offset , Object reference ) { assert referenceMessageSize != 0 : "References are not in use" ; UnsafeRefArrayAccess . spElement ( references , UnsafeRefArrayAccess . calcElementOffset ( offset ) , reference ) ; }
Write a reference to the given position
13,080
protected Object readReference ( long offset ) { assert referenceMessageSize != 0 : "References are not in use" ; return UnsafeRefArrayAccess . lpElement ( references , UnsafeRefArrayAccess . calcElementOffset ( offset ) ) ; }
Read a reference at the given position
13,081
private int probe ( ) { if ( PROBE != - 1 ) { int probe ; if ( ( probe = UNSAFE . getInt ( Thread . currentThread ( ) , PROBE ) ) == 0 ) { ThreadLocalRandom . current ( ) ; probe = UNSAFE . getInt ( Thread . currentThread ( ) , PROBE ) ; } return probe ; } int probe = ( int ) ( ( Thread . currentThread ( ) . getId ( ) * 0x9e3779b9 ) & Integer . MAX_VALUE ) ; probe ^= probe << 13 ; probe ^= probe >>> 17 ; probe ^= probe << 5 ; return probe ; }
Returns the probe value for the current thread . If target JDK version is 7 or higher than ThreadLocalRandom - specific value will be used xorshift with thread id otherwise .
13,082
public void set ( long x ) { CAT newcat = new CAT ( null , 4 , x ) ; while ( ! CAS_cat ( _cat , newcat ) ) { } }
Atomically set the sum of the striped counters to specified value . Rather more expensive than a simple store in order to remain atomic .
13,083
private void replaceParentClassesForAtomics ( ClassOrInterfaceDeclaration n ) { for ( ClassOrInterfaceType parent : n . getExtendedTypes ( ) ) { if ( "ConcurrentCircularArrayQueue" . equals ( parent . getNameAsString ( ) ) ) { parent . setName ( "AtomicReferenceArrayQueue" ) ; } else if ( "ConcurrentSequencedCircularArrayQueue" . equals ( parent . getNameAsString ( ) ) ) { parent . setName ( "SequencedAtomicReferenceArrayQueue" ) ; } else { parent . setName ( translateQueueName ( parent . getNameAsString ( ) ) ) ; } } }
Searches all extended or implemented super classes or interfaces for special classes that differ with the atomics version and replaces them with the appropriate class .
13,084
public static ServiceInfo of ( String serviceName , ServiceAcl ... acls ) { return new ServiceInfo ( serviceName , TreePVector . from ( Arrays . asList ( acls ) ) ) ; }
Factory method to create ServiceInfo instances that contain a single locatable service .
13,085
public MessageProtocol withContentType ( String contentType ) { return new MessageProtocol ( Optional . ofNullable ( contentType ) , charset , version ) ; }
Return a copy of this message protocol with the content type set to the given content type .
13,086
public MessageProtocol withCharset ( String charset ) { return new MessageProtocol ( contentType , Optional . ofNullable ( charset ) , version ) ; }
Return a copy of this message protocol with the charset set to the given charset .
13,087
public MessageProtocol withVersion ( String version ) { return new MessageProtocol ( contentType , charset , Optional . ofNullable ( version ) ) ; }
Return a copy of this message protocol with the version set to the given version .
13,088
public boolean isText ( ) { boolean isJson = contentType . map ( contentType -> "application/json" . equals ( contentType ) ) . orElse ( false ) ; boolean isPlainText = contentType . map ( contentType -> "text/plain" . equals ( contentType ) ) . orElse ( false ) ; return charset . isPresent ( ) || isJson || isPlainText ; }
Whether this message protocol is a text based protocol .
13,089
public boolean isUtf8 ( ) { if ( charset . isPresent ( ) ) { return utf8Charset . equals ( Charset . forName ( charset . get ( ) ) ) ; } else { return false ; } }
Whether the protocol uses UTF - 8 .
13,090
public Optional < String > toContentTypeHeader ( ) { return contentType . map ( ct -> { if ( charset . isPresent ( ) ) { return ct + "; charset=" + charset . get ( ) ; } else { return ct ; } } ) ; }
Convert this message protocol to a content type header if the content type is defined .
13,091
public static MessageProtocol fromContentTypeHeader ( Optional < String > contentType ) { return contentType . map ( ct -> { String [ ] parts = ct . split ( ";" ) ; String justContentType = parts [ 0 ] ; Optional < String > charset = Optional . empty ( ) ; for ( int i = 1 ; i < parts . length ; i ++ ) { String toTest = parts [ i ] . trim ( ) ; if ( toTest . startsWith ( "charset=" ) ) { charset = Optional . of ( toTest . split ( "=" , 2 ) [ 1 ] ) ; break ; } } return new MessageProtocol ( Optional . of ( justContentType ) , charset , Optional . empty ( ) ) ; } ) . orElse ( new MessageProtocol ( ) ) ; }
Parse a message protocol from a content type header if defined .
13,092
public static < Param > PathParamSerializer < Param > required ( String name , Function < String , Param > deserialize , Function < Param , String > serialize ) { return new NamedPathParamSerializer < Param > ( name ) { public PSequence < String > serialize ( Param parameter ) { return TreePVector . singleton ( serialize . apply ( parameter ) ) ; } public Param deserialize ( PSequence < String > parameters ) { if ( parameters . isEmpty ( ) ) { throw new IllegalArgumentException ( name + " parameter is required" ) ; } else { return deserialize . apply ( parameters . get ( 0 ) ) ; } } } ; }
Create a PathParamSerializer for required parameters .
13,093
public static < Param > PathParamSerializer < Optional < Param > > optional ( String name , Function < String , Param > deserialize , Function < Param , String > serialize ) { return new NamedPathParamSerializer < Optional < Param > > ( "Optional(" + name + ")" ) { public PSequence < String > serialize ( Optional < Param > parameter ) { return parameter . map ( p -> TreePVector . singleton ( serialize . apply ( p ) ) ) . orElse ( TreePVector . empty ( ) ) ; } public Optional < Param > deserialize ( PSequence < String > parameters ) { if ( parameters . isEmpty ( ) ) { return Optional . empty ( ) ; } else { return Optional . of ( deserialize . apply ( parameters . get ( 0 ) ) ) ; } } } ; }
Create a PathParamSerializer for optional parameters .
13,094
public static < Param > PathParamSerializer < List < Param > > list ( String name , Function < PSequence < String > , Param > deserialize , Function < Param , PSequence < String > > serialize ) { return new NamedPathParamSerializer < List < Param > > ( "List(" + name + ")" ) { public PSequence < String > serialize ( List < Param > parameter ) { List < String > serializedParams = serializeCollection ( parameter , serialize ) . collect ( Collectors . toList ( ) ) ; return TreePVector . from ( serializedParams ) ; } public List < Param > deserialize ( PSequence < String > parameters ) { return deserializeCollection ( parameters , deserialize ) . collect ( Collectors . toList ( ) ) ; } } ; }
Create a PathParamSerializer for List parameters .
13,095
public static < Param > PathParamSerializer < Set < Param > > set ( String name , Function < PSequence < String > , Param > deserialize , Function < Param , PSequence < String > > serialize ) { return new NamedPathParamSerializer < Set < Param > > ( "Set(" + name + ")" ) { public PSequence < String > serialize ( Set < Param > parameter ) { Set < String > serializedParams = serializeCollection ( parameter , serialize ) . collect ( Collectors . toSet ( ) ) ; return TreePVector . from ( serializedParams ) ; } public Set < Param > deserialize ( PSequence < String > parameters ) { return deserializeCollection ( parameters , deserialize ) . collect ( Collectors . toSet ( ) ) ; } } ; }
Create a PathParamSerializer for Set parameters .
13,096
public String messageAsText ( ) { if ( protocol . charset ( ) . isPresent ( ) ) { return message . decodeString ( protocol . charset ( ) . get ( ) ) ; } else { return Base64 . getEncoder ( ) . encodeToString ( message . toArray ( ) ) ; } }
Get the message as text .
13,097
@ SuppressWarnings ( "unchecked" ) public static < Message > Descriptor . Properties . Property < Message , PartitionKeyStrategy < Message > > partitionKeyStrategy ( ) { return PARTITION_KEY_STRATEGY ; }
A PartitionKeyStrategy produces a key for each message published to a Kafka topic .
13,098
protected < T > CompletionStage < Optional < T > > doWithServiceImpl ( String name , Descriptor . Call < ? , ? > serviceCall , Function < URI , CompletionStage < T > > block ) { return locate ( name , serviceCall ) . thenCompose ( uri -> { return uri . map ( u -> block . apply ( u ) . thenApply ( Optional :: of ) ) . orElseGet ( ( ) -> CompletableFuture . completedFuture ( Optional . empty ( ) ) ) ; } ) ; }
Do the given block with the given service looked up .
13,099
public RequestHeader withMethod ( Method method ) { return new RequestHeader ( method , uri , protocol , acceptedResponseProtocols , principal , headers , lowercaseHeaders ) ; }
Return a copy of this request header with the given method set .