idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
10,800
public final FieldTextInfo createFieldInfo ( final Field field , final Locale locale , final Class < ? extends Annotation > annotationClasz ) { Contract . requireArgNotNull ( "field" , field ) ; Contract . requireArgNotNull ( "locale" , locale ) ; Contract . requireArgNotNull ( "annotationClasz" , annotationClasz ) ; final Annotation annotation = field . getAnnotation ( annotationClasz ) ; if ( annotation == null ) { return null ; } try { final ResourceBundle bundle = getResourceBundle ( annotation , locale , field . getDeclaringClass ( ) ) ; final String text = getText ( bundle , annotation , field . getName ( ) + "." + annotationClasz . getSimpleName ( ) ) ; return new FieldTextInfo ( field , text ) ; } catch ( final MissingResourceException ex ) { return new FieldTextInfo ( field , toNullableString ( getValue ( annotation ) ) ) ; } }
Returns the text information for a given field of a class .
10,801
@ SuppressWarnings ( "unchecked" ) private static < T > T invoke ( final Object obj , final String methodName ) { return ( T ) invoke ( obj , methodName , null , null ) ; }
Calls a method with no arguments using reflection and maps all errors into a runtime exception .
10,802
private static Object invoke ( final Object obj , final String methodName , final Class < ? > [ ] argTypes , final Object [ ] args ) { Contract . requireArgNotNull ( "obj" , obj ) ; Contract . requireArgNotNull ( "methodName" , methodName ) ; final Class < ? > [ ] argTypesIntern ; final Object [ ] argsIntern ; if ( argTypes == null ) { argTypesIntern = new Class [ ] { } ; if ( args != null ) { throw new IllegalArgumentException ( "The argument 'argTypes' is null but " + "'args' containes values!" ) ; } argsIntern = new Object [ ] { } ; } else { argTypesIntern = argTypes ; if ( args == null ) { throw new IllegalArgumentException ( "The argument 'argTypes' contains classes " + "but 'args' is null!" ) ; } argsIntern = args ; } checkSameLength ( argTypesIntern , argsIntern ) ; Class < ? > returnType = UNKNOWN_CLASS . class ; try { final Method method = obj . getClass ( ) . getMethod ( methodName , argTypesIntern ) ; if ( method . getReturnType ( ) == null ) { returnType = void . class ; } else { returnType = method . getReturnType ( ) ; } return method . invoke ( obj , argsIntern ) ; } catch ( final SecurityException ex ) { throw new RuntimeException ( "Security problem with '" + getMethodSignature ( returnType , methodName , argTypesIntern ) + "'! [" + obj . getClass ( ) . getName ( ) + "]" , ex ) ; } catch ( final NoSuchMethodException ex ) { throw new RuntimeException ( "Method '" + getMethodSignature ( returnType , methodName , argTypesIntern ) + "' not found! [" + obj . getClass ( ) . getName ( ) + "]" , ex ) ; } catch ( final IllegalArgumentException ex ) { throw new RuntimeException ( "Argument problem with '" + getMethodSignature ( returnType , methodName , argTypesIntern ) + "'! [" + obj . getClass ( ) . getName ( ) + "]" , ex ) ; } catch ( final IllegalAccessException ex ) { throw new RuntimeException ( "Access problem with '" + getMethodSignature ( returnType , methodName , argTypesIntern ) + "'! [" + obj . getClass ( ) . getName ( ) + "]" , ex ) ; } catch ( final InvocationTargetException ex ) { throw new RuntimeException ( "Got an exception when calling '" + getMethodSignature ( returnType , methodName , argTypesIntern ) + "'! [" + obj . getClass ( ) . getName ( ) + "]" , ex ) ; } }
Calls a method with reflection and maps all errors into a runtime exception .
10,803
public final List < Change > diff ( final DayOpeningHours toOther ) { Contract . requireArgNotNull ( "toOther" , toOther ) ; if ( dayOfTheWeek != toOther . dayOfTheWeek ) { throw new ConstraintViolationException ( "Expected same day (" + dayOfTheWeek + ") for argument 'toOther', but was: " + toOther . dayOfTheWeek ) ; } final List < DayOpeningHours > fromDays = normalize ( ) ; final List < DayOpeningHours > toDays = toOther . normalize ( ) ; final List < Change > changes = new ArrayList < > ( ) ; if ( fromDays . size ( ) == 1 ) { if ( toDays . size ( ) == 1 ) { final DayOpeningHours from = fromDays . get ( 0 ) ; final DayOpeningHours to = toDays . get ( 0 ) ; changes . addAll ( changes ( this . dayOfTheWeek , from . hourRanges , to . hourRanges ) ) ; } else { final DayOpeningHours from = fromDays . get ( 0 ) ; final DayOpeningHours to1 = toDays . get ( 0 ) ; final DayOpeningHours to2 = toDays . get ( 1 ) ; changes . addAll ( changes ( this . dayOfTheWeek , from . hourRanges , to1 . hourRanges ) ) ; changes . addAll ( changes ( ChangeType . ADDED , to2 . dayOfTheWeek , to2 . hourRanges ) ) ; } } else { if ( toDays . size ( ) == 1 ) { final DayOpeningHours from1 = fromDays . get ( 0 ) ; final DayOpeningHours from2 = fromDays . get ( 1 ) ; final DayOpeningHours to = toDays . get ( 0 ) ; changes . addAll ( changes ( this . dayOfTheWeek , from1 . hourRanges , to . hourRanges ) ) ; changes . addAll ( changes ( ChangeType . REMOVED , from2 . dayOfTheWeek , from2 . hourRanges ) ) ; } else { final DayOpeningHours from1 = fromDays . get ( 0 ) ; final DayOpeningHours from2 = fromDays . get ( 1 ) ; final DayOpeningHours to1 = toDays . get ( 0 ) ; final DayOpeningHours to2 = toDays . get ( 1 ) ; changes . addAll ( changes ( from1 . dayOfTheWeek , from1 . hourRanges , to1 . hourRanges ) ) ; changes . addAll ( changes ( from2 . dayOfTheWeek , from2 . hourRanges , to2 . hourRanges ) ) ; } } return changes ; }
Returns the difference when changing this opening hours to the other one . The day of the week must be equal for both compared instances .
10,804
public List < Change > asRemovedChanges ( ) { final List < Change > changes = new ArrayList < > ( ) ; for ( final HourRange hr : hourRanges ) { changes . add ( new Change ( ChangeType . REMOVED , dayOfTheWeek , hr ) ) ; } return changes ; }
Returns all hour ranges of this day as if they were removed .
10,805
public List < Change > asAddedChanges ( ) { final List < Change > changes = new ArrayList < > ( ) ; for ( final HourRange hr : hourRanges ) { changes . add ( new Change ( ChangeType . ADDED , dayOfTheWeek , hr ) ) ; } return changes ; }
Returns all hour ranges of this day as if they were added .
10,806
public static boolean isValid ( final String dayOpeningHours ) { if ( dayOpeningHours == null ) { return true ; } final int p = dayOpeningHours . indexOf ( ' ' ) ; if ( p < 0 ) { return false ; } final String dayOfTheWeekStr = dayOpeningHours . substring ( 0 , p ) ; final String hourRangesStr = dayOpeningHours . substring ( p + 1 ) ; return DayOfTheWeek . isValid ( dayOfTheWeekStr ) && HourRanges . isValid ( hourRangesStr ) ; }
Verifies if the string can be converted into an instance of this class .
10,807
public Document runAtServer ( String containerUrl , String testClassName , String testDisplayName ) { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder ; try { String url = containerUrl + String . format ( "?%s=%s&%s=%s" , TEST_CLASS_NAME_PARAM , testClassName , TEST_NAME_PARAM , URLEncoder . encode ( testDisplayName , ENCODING ) ) ; builder = factory . newDocumentBuilder ( ) ; Document document = builder . parse ( url ) ; return document ; } catch ( FileNotFoundException fe ) { throw new RuntimeException ( "Could not find the test WAR at the server. Make sure jicunit.url points to the correct context root." , fe ) ; } catch ( ConnectException ce ) { throw new RuntimeException ( "Could not connect to the server. Make sure jicunit.url points to the correct host and port." , ce ) ; } catch ( ParserConfigurationException | SAXException | IOException e ) { throw new RuntimeException ( "Could not run the test. Check the jicunit.url so it is correct." , e ) ; } }
Execute the test at the server
10,808
public void processResults ( Document document ) throws Throwable { Element root = document . getDocumentElement ( ) ; root . normalize ( ) ; NamedNodeMap attributes = root . getAttributes ( ) ; String statusAsStr = attributes . getNamedItem ( "status" ) . getNodeValue ( ) ; Status status = Status . valueOf ( statusAsStr ) ; if ( status . equals ( Status . Error ) || status . equals ( Status . Failure ) ) { throw getException ( root , status ) ; } }
Processes the actual XML result and generate exceptions in case there was an issue on the server side .
10,809
protected HttpRequestFactory buildHttpRequestFactory ( ) { HttpRequestFactory request = this . getGloboDns ( ) . getHttpTransport ( ) . createRequestFactory ( new HttpRequestInitializer ( ) { public void initialize ( HttpRequest request ) throws IOException { request . setNumberOfRetries ( AbstractAPI . this . globoDns . getNumberOfRetries ( ) ) ; request . setConnectTimeout ( AbstractAPI . this . globoDns . getConnectionTimeout ( ) ) ; request . setReadTimeout ( AbstractAPI . this . globoDns . getReadTimeout ( ) ) ; request . setThrowExceptionOnExecuteError ( false ) ; request . setParser ( parser ) ; request . setLoggingEnabled ( true ) ; request . getHeaders ( ) . setUserAgent ( "GloboDNS-Client" ) ; request . setCurlLoggingEnabled ( true ) ; request . setUnsuccessfulResponseHandler ( new HttpUnsuccessfulResponseHandler ( ) { public boolean handleResponse ( HttpRequest request , HttpResponse response , boolean supportsRetry ) throws IOException { if ( response . getStatusCode ( ) == 401 ) { getGloboDns ( ) . clearToken ( ) ; if ( supportsRetry ) { insertAuthenticationHeaders ( request ) ; return true ; } } return false ; } } ) ; request . setResponseInterceptor ( new HttpResponseInterceptor ( ) { public void interceptResponse ( HttpResponse response ) throws IOException { AbstractAPI . this . interceptResponse ( response ) ; } } ) ; interceptRequest ( request ) ; } } ) ; return request ; }
Customize HttpRequestFactory with authentication and error handling .
10,810
protected Map < String , Object > bytesMapToDocument ( Map < String , byte [ ] > data ) { if ( data == null || data . size ( ) == 0 ) { return null ; } Map < String , Object > doc = new HashMap < > ( ) ; data . forEach ( ( k , v ) -> { Object value = SerializationUtils . fromByteArrayFst ( v ) ; if ( value != null ) { doc . put ( k , value ) ; } } ) ; return doc ; }
De - serialize byte - array map to document .
10,811
@ SuppressWarnings ( "unchecked" ) protected Map < String , byte [ ] > documentToBytesMap ( Map < String , Object > doc ) { if ( doc == null || doc . size ( ) == 0 ) { return Collections . EMPTY_MAP ; } Map < String , byte [ ] > data = new HashMap < > ( ) ; doc . forEach ( ( k , v ) -> { byte [ ] value = SerializationUtils . toByteArrayFst ( v ) ; if ( value != null ) { data . put ( k , value ) ; } } ) ; return data ; }
Sereialize document to byte - array map .
10,812
public final int toPixel ( ) { if ( unit == FontSizeUnit . PIXEL ) { return Math . round ( size ) ; } if ( unit == FontSizeUnit . EM ) { return Math . round ( 16 * size ) ; } if ( unit == FontSizeUnit . PERCENT ) { return Math . round ( size / 100 * 16 ) ; } if ( unit == FontSizeUnit . POINT ) { return Math . round ( size / 3 * 4 ) ; } throw new IllegalStateException ( "Unknown unit: " + unit ) ; }
Returns the font size expressed in pixels .
10,813
public final float toPoint ( ) { if ( unit == FontSizeUnit . PIXEL ) { return ( size / 4 * 3 ) ; } if ( unit == FontSizeUnit . EM ) { return ( size * 12 ) ; } if ( unit == FontSizeUnit . PERCENT ) { return ( size / 100 * 12 ) ; } if ( unit == FontSizeUnit . POINT ) { return size ; } throw new IllegalStateException ( "Unknown unit: " + unit ) ; }
Returns the font size expressed in points .
10,814
protected List < Runner > getChildren ( ) { List < Runner > runners = super . getChildren ( ) ; List < Runner > proxyRunners = new ArrayList < > ( runners . size ( ) ) ; for ( Runner runner : runners ) { BlockJUnit4ClassRunner blockJUnit4ClassRunner = ( BlockJUnit4ClassRunner ) runner ; Description description = blockJUnit4ClassRunner . getDescription ( ) ; String name = description . getDisplayName ( ) ; try { proxyRunners . add ( new ProxyTestClassRunnerForParameters ( mTestClass , mContainerUrl , name ) ) ; } catch ( InitializationError e ) { throw new RuntimeException ( "Could not create runner for paramamter " + name , e ) ; } } return proxyRunners ; }
replace the runners with slightly modified BasicProxyRunner
10,815
public static boolean registerJdbcDataSource ( String name , DataSource dataSource ) { return jdbcDataSources . putIfAbsent ( name , dataSource ) == null ; }
Registers a named JDBC datasource .
10,816
public static boolean startTransaction ( Connection conn ) throws SQLException { if ( conn == null ) { return false ; } String dsName = openConnDsName . get ( ) . get ( conn ) ; OpenConnStats connStats = dsName != null ? openConnStats . get ( ) . get ( dsName ) : null ; if ( connStats != null && ! connStats . inTransaction ) { conn . setAutoCommit ( false ) ; connStats . inTransaction = true ; return true ; } return false ; }
Starts a transaction . Has no effect if already in a transaction .
10,817
public static DatabaseVendor detectDbVendor ( Connection conn ) throws SQLException { DatabaseMetaData dmd = conn . getMetaData ( ) ; String dpn = dmd . getDatabaseProductName ( ) ; if ( StringUtils . equalsAnyIgnoreCase ( "MySQL" , dpn ) ) { return DatabaseVendor . MYSQL ; } if ( StringUtils . equalsAnyIgnoreCase ( "PostgreSQL" , dpn ) ) { return DatabaseVendor . POSTGRESQL ; } if ( StringUtils . equalsAnyIgnoreCase ( "Microsoft SQL Server" , dpn ) ) { return DatabaseVendor . MSSQL ; } return DatabaseVendor . UNKNOWN ; }
Detect database vender info .
10,818
public static String getSolrAddDocument ( Map < String , String > values ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "<add><doc>" ) ; for ( Map . Entry < String , String > pair : values . entrySet ( ) ) { XMLUtils . addSolrField ( builder , pair ) ; } builder . append ( "</doc></add>" ) ; return builder . toString ( ) ; }
Returns Apache Solr add command .
10,819
public static String filterdStackTrace ( String stackTrace ) { boolean skip = false ; StringBuilder filteredStackTrace = new StringBuilder ( ) ; String [ ] segments = stackTrace . split ( "\n" ) ; for ( int i = 0 ; i < segments . length ; i ++ ) { String segment = segments [ i ] ; if ( skip ) { if ( segment . startsWith ( "Caused by:" ) ) { skip = false ; filteredStackTrace . append ( segment ) . append ( "\n" ) ; } } else { if ( segment . startsWith ( "\tat sun.reflect.NativeMethodAccessorImpl" ) ) { skip = true ; } else if ( segment . startsWith ( "\tat org.junit." ) || segment . startsWith ( "\tat junit.framework." ) ) { } else { filteredStackTrace . append ( segment ) . append ( "\n" ) ; } } } filteredStackTrace . delete ( filteredStackTrace . length ( ) - 1 , filteredStackTrace . length ( ) ) ; return filteredStackTrace . toString ( ) ; }
Removes all entries that has to do with the internal way of running the test method .
10,820
@ SuppressWarnings ( "unchecked" ) protected static < T > Map < String , T > cloneData ( Map < String , T > data ) { return SerializationUtils . fromByteArray ( SerializationUtils . toByteArray ( data ) , Map . class ) ; }
Deep - clone data .
10,821
public Map < String , Object > getAttributes ( ) { if ( attributes == null ) { return null ; } Lock lock = lockForRead ( ) ; try { return cloneData ( attributes ) ; } finally { lock . unlock ( ) ; } }
Get all BO s attributes as a map .
10,822
public String getAttributesAsJsonString ( ) { if ( attributes == null ) { return "null" ; } Lock lock = lockForRead ( ) ; try { return SerializationUtils . toJsonString ( attributes ) ; } finally { lock . unlock ( ) ; } }
Get all BO s attributes as a JSON - string .
10,823
protected BaseBo removeAttribute ( String attrName , boolean triggerChange ) { Lock lock = lockForWrite ( ) ; try { attributes . remove ( attrName ) ; if ( triggerChange ) { triggerChange ( attrName ) ; } markDirty ( ) ; return this ; } finally { lock . unlock ( ) ; } }
Remove a BO s attribute .
10,824
protected Lock tryLockForRead ( long time , TimeUnit unit ) throws InterruptedException { if ( time < 0 || unit == null ) { return tryLockForRead ( ) ; } Lock lock = readLock ( ) ; return lock . tryLock ( time , unit ) ? lock : null ; }
Try to lock the BO for read .
10,825
protected Lock tryLockForWrite ( long time , TimeUnit unit ) throws InterruptedException { if ( time < 0 || unit == null ) { return tryLockForWrite ( ) ; } Lock lock = writeLock ( ) ; return lock . tryLock ( time , unit ) ? lock : null ; }
Try to lock the BO for write .
10,826
public Map < String , Object > toMap ( ) { Lock lock = lockForWrite ( ) ; try { Map < String , Object > data = new HashMap < > ( ) ; data . put ( SER_FIELD_DIRTY , dirty ) ; data . put ( SER_FIELD_ATTRS , attributes != null ? cloneData ( attributes ) : new HashMap < > ( ) ) ; return data ; } finally { lock . unlock ( ) ; } }
Serialize the BO to a Java map .
10,827
public String toJson ( ) { Map < String , Object > data = toMap ( ) ; return SerializationUtils . toJsonString ( data ) ; }
Serialize the BO to JSON string .
10,828
public static boolean acquireLock ( Context context ) { if ( wl != null && wl . isHeld ( ) ) { return true ; } powerManager = ( PowerManager ) context . getSystemService ( Context . POWER_SERVICE ) ; wl = powerManager . newWakeLock ( PowerManager . SCREEN_BRIGHT_WAKE_LOCK , TAG ) ; if ( wl == null ) { return false ; } wl . acquire ( ) ; return wl . isHeld ( ) ; }
if the keep light has been opened will default exit .
10,829
public String get ( String key ) { if ( properties . get ( key ) != null ) { return properties . get ( key ) ; } else { return getConfigurationValue ( key ) ; } }
Return property value for a given name .
10,830
public void checkRequired ( String key ) throws InitializationFailedException { if ( properties . get ( key ) == null && getConfigurationValue ( key ) == null ) { throw new InitializationFailedException ( "Missing required property in config: " + key ) ; } }
Checks if a property value for a given key exists .
10,831
public final Set < ConstraintViolation < Object > > getConstraintViolations ( ) { if ( constraintViolations == null ) { return null ; } return Collections . unmodifiableSet ( constraintViolations ) ; }
Returns the constraint violations .
10,832
private void invokeDestroy ( String method , String name ) { Class clazz = this . jmsServerManager ( ) . getClass ( ) ; Method destroy = null ; for ( Method each : clazz . getMethods ( ) ) { if ( method . equals ( each . getName ( ) ) ) { destroy = each ; break ; } } if ( destroy == null ) { throw new IllegalStateException ( String . format ( "Class %s has no %s method" , clazz , method ) ) ; } try { if ( destroy . getParameterTypes ( ) . length == 1 ) { destroy . invoke ( this . jmsServerManager ( ) , name ) ; } else { destroy . invoke ( this . jmsServerManager ( ) , name , true ) ; } } catch ( IllegalAccessException | InvocationTargetException e ) { throw new RuntimeException ( "Failed to destroy destination " + name , e ) ; } }
HornetQ 2 . 3 has single - arity destroy functions 2 . 4 has double - arity
10,833
public static int CopyAssets ( Context context , String srcFile , String dstFile ) { int result = COPY_SUCCESS ; InputStream in = null ; OutputStream out = null ; try { File fi ; if ( dstFile . equals ( FileUtils . getFileName ( dstFile ) ) ) { fi = new File ( context . getFilesDir ( ) , dstFile ) ; } else { fi = new File ( dstFile ) ; } in = context . getAssets ( ) . open ( srcFile , AssetManager . ACCESS_STREAMING ) ; if ( fi . exists ( ) && in . available ( ) <= fi . length ( ) ) { result = COPY_DST_EXIST ; } else { out = new FileOutputStream ( fi ) ; byte [ ] buffer = new byte [ 10240 ] ; int read ; while ( ( read = in . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , read ) ; } buffer = null ; } } catch ( IOException e ) { Log . e ( TAG , "" , e ) ; result = COPY_ERROR ; } finally { if ( in != null ) try { in . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } in = null ; if ( out != null ) { try { out . flush ( ) ; out . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } out = null ; } return result ; }
copy assets file to destinations .
10,834
public static boolean isLauncherActivity ( Intent intent ) { if ( intent == null ) return false ; if ( StringUtils . isNullOrEmpty ( intent . getAction ( ) ) ) { return false ; } if ( intent . getCategories ( ) == null ) return false ; return Intent . ACTION_MAIN . equals ( intent . getAction ( ) ) && intent . getCategories ( ) . contains ( Intent . CATEGORY_LAUNCHER ) ; }
check whether is launcher or not .
10,835
public static boolean isValid ( final String value ) { if ( value == null ) { return true ; } final String uuidPattern = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-" + "[0-9a-f]{4}-[0-9a-f]{12}$" ; return Pattern . matches ( uuidPattern , value ) ; }
Verifies that a given string is a valid UUID .
10,836
protected Object extractSpecificConfig ( String key ) { if ( this . specificConfig == null ) { return null ; } Object result = this . specificConfig . get ( key ) ; return result ; }
Get config value from specific config .
10,837
protected Map < String , Object > getSpecificConfig ( ) { if ( this . specificConfig == null ) { return null ; } Map < String , Object > result = Collections . unmodifiableMap ( this . specificConfig ) ; return result ; }
Get unmodifiable specific config .
10,838
public static Step step ( String stepName ) { Root root = PROFILER_STEPS . get ( ) ; if ( root != null ) { Profile data = new Profile ( root . nextId ( ) , stepName ) ; return new Step ( root , data ) ; } else { return new Step ( null , null ) ; } }
Start a profiling step .
10,839
static public MessageHandler . Whole < String > createTextHandler ( final MessageHandler . Whole proxy ) { return new MessageHandler . Whole < String > ( ) { public void onMessage ( String msg ) { proxy . onMessage ( msg ) ; } } ; }
generics and Undertow s dependence on ParameterizedType
10,840
static public MessageHandler . Whole < byte [ ] > createBinaryHandler ( final MessageHandler . Whole proxy ) { return new MessageHandler . Whole < byte [ ] > ( ) { public void onMessage ( byte [ ] msg ) { proxy . onMessage ( msg ) ; } } ; }
The binary version of createTextHandler
10,841
public < T > boolean remove ( Class < T > eventClass , Listener < T > listener ) { return remove ( eventClass , listener , HIDDEN_STATION ) ; }
Removes the given listener listening on the given event from the hidden station hiding the station abstraction .
10,842
public void setAction ( final Runnable action ) { super . setAction ( new Runnable ( ) { public void run ( ) { if ( ! isRunning ) { thread = new Thread ( wrappedAction ( action ) , "wunderboss-daemon-thread[" + name + "]" ) ; thread . start ( ) ; isRunning = true ; } } } ) ; }
Wraps the given action in a Runnable that starts a supervised thread .
10,843
protected boolean register ( String path , List < String > vhosts , HttpHandler handler ) { return pathology . add ( path , vhosts , handler ) ; }
For the WF subclass
10,844
public static TextFieldInfo create ( final Field field , final Locale locale ) { final TextField textField = field . getAnnotation ( TextField . class ) ; if ( textField == null ) { return null ; } return new TextFieldInfo ( field , textField . width ( ) ) ; }
Return the text field information for a given field .
10,845
protected int getDepth ( final WebdavRequest req ) { int depth = INFINITY ; final String depthStr = req . getHeader ( "Depth" ) ; if ( depthStr != null ) { if ( depthStr . equals ( "0" ) ) { depth = 0 ; } else if ( depthStr . equals ( "1" ) ) { depth = 1 ; } } return depth ; }
reads the depth header from the request and returns it as a int
10,846
protected String getETag ( final StoredObject so ) { String resourceLength = "" ; String lastModified = "" ; if ( so != null && so . isResource ( ) ) { resourceLength = new Long ( so . getResourceLength ( ) ) . toString ( ) ; lastModified = new Long ( so . getLastModified ( ) . getTime ( ) ) . toString ( ) ; } return "W/\"" + resourceLength + "-" + lastModified + "\"" ; }
Get the ETag associated with a file .
10,847
protected void sendReport ( final WebdavRequest req , final WebdavResponse resp , final Hashtable < String , WebdavStatus > errorList ) throws IOException { resp . setStatus ( WebdavStatus . SC_MULTI_STATUS ) ; final String absoluteUri = req . getRequestURI ( ) ; final HashMap < String , String > namespaces = new HashMap < String , String > ( ) ; namespaces . put ( "DAV:" , "D" ) ; final XMLWriter generatedXML = new XMLWriter ( namespaces ) ; generatedXML . writeXMLHeader ( ) ; generatedXML . writeElement ( "DAV::multistatus" , XMLWriter . OPENING ) ; final Enumeration < String > pathList = errorList . keys ( ) ; while ( pathList . hasMoreElements ( ) ) { final String errorPath = pathList . nextElement ( ) ; final int errorCode = errorList . get ( errorPath ) . code ( ) ; generatedXML . writeElement ( "DAV::response" , XMLWriter . OPENING ) ; generatedXML . writeElement ( "DAV::href" , XMLWriter . OPENING ) ; String toAppend = null ; if ( absoluteUri . endsWith ( errorPath ) ) { toAppend = absoluteUri ; } else if ( absoluteUri . contains ( errorPath ) ) { final int endIndex = absoluteUri . indexOf ( errorPath ) + errorPath . length ( ) ; toAppend = absoluteUri . substring ( 0 , endIndex ) ; } if ( ! toAppend . startsWith ( "/" ) && ! toAppend . startsWith ( "http:" ) ) { toAppend = "/" + toAppend ; } generatedXML . writeText ( errorPath ) ; generatedXML . writeElement ( "DAV::href" , XMLWriter . CLOSING ) ; generatedXML . writeElement ( "DAV::status" , XMLWriter . OPENING ) ; generatedXML . writeText ( "HTTP/1.1 " + errorCode + " " + WebdavStatus . getStatusText ( errorCode ) ) ; generatedXML . writeElement ( "DAV::status" , XMLWriter . CLOSING ) ; generatedXML . writeElement ( "DAV::response" , XMLWriter . CLOSING ) ; } generatedXML . writeElement ( "DAV::multistatus" , XMLWriter . CLOSING ) ; final Writer writer = resp . getWriter ( ) ; writer . write ( generatedXML . toString ( ) ) ; writer . close ( ) ; }
Send a multistatus element containing a complete error report to the client .
10,848
public static boolean setIfPossible ( final Ruby ruby , final Object target , final String name , final Object value ) { boolean success = false ; if ( defined ( ruby , target , name + "=" ) ) { JavaEmbedUtils . invokeMethod ( ruby , target , name + "=" , new Object [ ] { value } , void . class ) ; success = true ; } return success ; }
Set a property on a Ruby object if possible .
10,849
public static boolean requireIfAvailable ( Ruby ruby , String requirement , boolean logErrors ) { boolean success = false ; try { StringBuilder script = new StringBuilder ( ) ; script . append ( "require %q(" ) ; script . append ( requirement ) ; script . append ( ")\n" ) ; evalScriptlet ( ruby , script . toString ( ) , false ) ; success = true ; } catch ( Throwable t ) { success = false ; if ( logErrors ) { log . debug ( "Error encountered. Unable to require file: " + requirement , t ) ; } } return success ; }
Calls require requirement in the Ruby provided .
10,850
public static Locale asLocale ( final String value ) { final Locale locale ; final int p = value . indexOf ( "__" ) ; if ( p > - 1 ) { locale = new Locale ( value . substring ( 0 , p ) , null , value . substring ( p + 2 ) ) ; } else { final StringTokenizer tok = new StringTokenizer ( value , "_" ) ; if ( tok . countTokens ( ) == 1 ) { locale = new Locale ( value ) ; } else if ( tok . countTokens ( ) == 2 ) { locale = new Locale ( tok . nextToken ( ) , tok . nextToken ( ) ) ; } else if ( tok . countTokens ( ) == 3 ) { locale = new Locale ( tok . nextToken ( ) , tok . nextToken ( ) , tok . nextToken ( ) ) ; } else { throw new IllegalArgumentException ( "Cannot convert: '" + value + "'" ) ; } } return locale ; }
Returns the given string as locale . The locale is NOT checked against the Java list of avilable locales .
10,851
public static boolean validLocale ( final Locale locale ) { for ( final Locale found : Locale . getAvailableLocales ( ) ) { if ( found . equals ( locale ) ) { return true ; } } return false ; }
Verifies if the give locale is in the Java list of known locales .
10,852
public static Kernel createKernel ( KernelConfiguration configuration ) { KernelCoreFactory factory = new KernelCoreFactory ( ) ; return factory . create ( configuration ) ; }
Creates a kernel with the given configuration .
10,853
protected static byte [ ] toArray ( ByteBuffer ... payload ) { if ( payload . length == 1 ) { ByteBuffer buf = payload [ 0 ] ; if ( buf . hasArray ( ) && buf . arrayOffset ( ) == 0 && buf . position ( ) == 0 ) { return buf . array ( ) ; } } int size = ( int ) Buffers . remaining ( payload ) ; byte [ ] data = new byte [ size ] ; for ( ByteBuffer buf : payload ) { buf . get ( data ) ; } return data ; }
Lifted from Undertow s FrameHandler . java
10,854
public final boolean overlaps ( final HourRange other ) { Contract . requireArgNotNull ( "other" , other ) ; if ( this . equals ( other ) ) { return true ; } final int otherFrom = other . from . toMinutes ( ) ; final int thisFrom = from . toMinutes ( ) ; final int otherTo = other . to . toMinutes ( ) ; final int thisTo = to . toMinutes ( ) ; if ( otherFrom <= thisTo && otherFrom >= thisFrom ) { return true ; } if ( otherTo <= thisTo && otherTo >= thisFrom ) { return true ; } if ( thisFrom <= otherTo && thisFrom >= otherFrom ) { return true ; } return ( thisTo <= otherTo && thisTo >= otherFrom ) ; }
Determines if this range and the given range overlap .
10,855
public static boolean isValid ( final String hourRange ) { if ( hourRange == null ) { return true ; } final int p = hourRange . indexOf ( '-' ) ; if ( p != 5 ) { return false ; } final String fromStr = hourRange . substring ( 0 , 5 ) ; final String toStr = hourRange . substring ( 6 ) ; if ( ! ( Hour . isValid ( fromStr ) && Hour . isValid ( toStr ) ) ) { return false ; } final Hour from = new Hour ( fromStr ) ; final Hour to = new Hour ( toStr ) ; if ( from . equals ( to ) ) { return false ; } if ( from . equals ( new Hour ( 24 , 0 ) ) ) { return false ; } return ! to . equals ( new Hour ( 0 , 0 ) ) ; }
Verifies if the string is a valid hour range .
10,856
public void onDeleteResponseEvent ( ResponseEvent event , ActivityContextInterface aci ) { if ( event . getException ( ) != null ) { if ( tracer . isInfoEnabled ( ) ) { tracer . info ( "Failed to delete " + event . getURI ( ) , event . getException ( ) ) ; } getParent ( ) . deleteResponse ( event . getURI ( ) , 500 , null , null ) ; } else { final XcapResponse response = event . getResponse ( ) ; if ( tracer . isInfoEnabled ( ) ) { if ( response . getCode ( ) == 200 ) { tracer . info ( "Deleted " + event . getURI ( ) + ". ETag:" + response . getETag ( ) ) ; } else { tracer . info ( "Failed to delete " + event . getURI ( ) + ". Response: " + response ) ; } } getParent ( ) . deleteResponse ( event . getURI ( ) , response . getCode ( ) , response . getEntity ( ) . getContentAsString ( ) , response . getETag ( ) ) ; } }
Handles XCAP DELETE response events .
10,857
public void unsubscribeFailed ( int arg0 , SubscriptionClientChildSbbLocalObject subscriptionChild ) { try { final String notifier = subscriptionChild . getSubscriptionData ( ) . getNotifierURI ( ) ; subscriptionChild . remove ( ) ; getParent ( ) . unsubscribeFailed ( arg0 , ( XDMClientChildSbbLocalObject ) this . sbbContext . getSbbLocalObject ( ) , notifier ) ; } catch ( Exception e ) { tracer . severe ( "Unexpected exception on callback!" , e ) ; } }
two easy cases .
10,858
@ SuppressWarnings ( "unchecked" ) protected < T > IGenericBoDao < T > lookupDelegateDao ( Class < T > clazz ) throws DelegateDaoNotFound { IGenericBoDao < ? > result = delegateDaos . get ( clazz ) ; if ( result == null ) { throw new DelegateDaoNotFound ( "Delegate dao for [" + clazz + "] not found!" ) ; } return ( IGenericBoDao < T > ) result ; }
Lookup the delegate dao .
10,859
public GenericMultiBoJdbcDao setDelegateDaos ( Map < ? , IGenericBoDao < ? > > daoMappings ) throws ClassNotFoundException { delegateDaos . clear ( ) ; for ( Entry < ? , IGenericBoDao < ? > > entry : daoMappings . entrySet ( ) ) { Object cl = entry . getKey ( ) ; IGenericBoDao < ? > dao = entry . getValue ( ) ; if ( cl instanceof Class ) { delegateDaos . put ( ( Class < ? > ) cl , dao ) ; } else { addDelegateDao ( cl . toString ( ) , dao ) ; } } return this ; }
Set delegate dao mappings .
10,860
public void initializing ( ) { for ( KernelExtension kernelExtension : kernelExtensions . keySet ( ) ) { Collection < Plugin > plugins = kernelExtensions . get ( kernelExtension ) ; kernelExtension . initializing ( plugins ) ; } }
Notifies the extensions that the kernel is initializing
10,861
public void initialized ( ) { for ( KernelExtension kernelExtension : kernelExtensions . keySet ( ) ) { kernelExtension . initialized ( kernelExtensions . get ( kernelExtension ) ) ; } }
Notifies the extensions that the kernel is initialized
10,862
public void starting ( ) { for ( KernelExtension kernelExtension : kernelExtensions . keySet ( ) ) { kernelExtension . starting ( kernelExtensions . get ( kernelExtension ) ) ; } }
Notifies the extensions that the kernel is starting
10,863
public void started ( ) { for ( KernelExtension kernelExtension : kernelExtensions . keySet ( ) ) { kernelExtension . started ( kernelExtensions . get ( kernelExtension ) ) ; } }
Notifies the extensions that the kernel is started
10,864
public void stopping ( ) { for ( KernelExtension kernelExtension : kernelExtensions . keySet ( ) ) { kernelExtension . stopping ( kernelExtensions . get ( kernelExtension ) ) ; } }
Notifies the extensions that the kernel is stopping
10,865
public void stopped ( ) { for ( KernelExtension kernelExtension : kernelExtensions . keySet ( ) ) { kernelExtension . stopped ( kernelExtensions . get ( kernelExtension ) ) ; } }
Notifies the extensions that the kernel is stopped
10,866
void assertDependencies ( final Plugin plugin ) { Collection < Class < ? > > expectedDependencies = new ArrayList < > ( ) ; Collection < Class < ? > > requiredPlugins = plugin . requiredPlugins ( ) ; if ( requiredPlugins != null ) { expectedDependencies . addAll ( requiredPlugins ) ; } Collection < Class < ? > > dependentPlugins = plugin . dependentPlugins ( ) ; if ( dependentPlugins != null ) { expectedDependencies . addAll ( dependentPlugins ) ; } for ( Class < ? > dependencyClass : expectedDependencies ) { List < ? > facets = facetRegistry . getFacets ( dependencyClass ) ; if ( facets . isEmpty ( ) ) { throw new KernelException ( "Plugin %s misses the following dependency: %s" , plugin . name ( ) , dependencyClass . getCanonicalName ( ) ) ; } } }
Verifies that the plugin dependencies are present in the plugin list . The list should contains both dependent and required plugins .
10,867
public < T > CompletableFuture < T > submit ( final Supplier < T > supplier ) { requireNonNull ( supplier , "A non-null supplier expected" ) ; CompletableFuture < T > future = null ; if ( isRunning . get ( ) ) { future = supplyAsync ( supplier , executor ) ; } else { future = new CompletableFuture < > ( ) ; future . completeExceptionally ( new IllegalStateException ( "This task runner is not active" ) ) ; } return future ; }
Submits a new task for execution to the pool of threads managed by this class .
10,868
public static String encodePath ( String path ) throws NullPointerException { return new String ( encode ( path , UriComponentEncoderBitSets . allowed_abs_path ) ) ; }
Encodes an HTTP URI Path .
10,869
public static String encodeQuery ( String query ) throws NullPointerException { return new String ( encode ( query , UriComponentEncoderBitSets . allowed_query ) ) ; }
Encodes an HTTP URI Query .
10,870
public static boolean isValid ( final String hour ) { if ( hour == null ) { return true ; } return PATTERN . matcher ( hour ) . matches ( ) ; }
Verifies if the string is a valid hour .
10,871
public static Object get ( String filePath , String configKey ) { if ( propertiesMap . containsKey ( filePath ) == false ) { loadProperty ( filePath ) ; } Properties properties = propertiesMap . get ( filePath ) ; if ( properties == null ) { return null ; } Object resultConfig = properties . getProperty ( configKey ) ; return resultConfig ; }
Get from config defined property files in classpath .
10,872
private static void loadProperty ( String filePath ) { try ( InputStream propertyStream = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( filePath ) ; Reader propertyReader = new InputStreamReader ( propertyStream , DEFAULT_CHARSET ) ; ) { Properties properties = new Properties ( ) ; properties . load ( propertyReader ) ; propertiesMap . put ( filePath , properties ) ; } catch ( Exception ex ) { String errorPattern = "Property file load failed. Skip load. : PropertyFile={0}" ; logger . warn ( MessageFormat . format ( errorPattern , filePath ) , ex ) ; } }
Load property file .
10,873
private static Object [ ] buildBindValues ( Object bindValue ) { if ( bindValue instanceof boolean [ ] ) { boolean [ ] bools = ( boolean [ ] ) bindValue ; return bools . length > 0 ? ArrayUtils . toObject ( bools ) : null ; } else if ( bindValue instanceof short [ ] ) { short [ ] shorts = ( short [ ] ) bindValue ; return shorts . length > 0 ? ArrayUtils . toObject ( shorts ) : null ; } else if ( bindValue instanceof int [ ] ) { int [ ] ints = ( int [ ] ) bindValue ; return ints . length > 0 ? ArrayUtils . toObject ( ints ) : null ; } else if ( bindValue instanceof long [ ] ) { long [ ] longs = ( long [ ] ) bindValue ; return longs . length > 0 ? ArrayUtils . toObject ( longs ) : null ; } else if ( bindValue instanceof float [ ] ) { float [ ] floats = ( float [ ] ) bindValue ; return floats . length > 0 ? ArrayUtils . toObject ( floats ) : null ; } else if ( bindValue instanceof double [ ] ) { double [ ] doubles = ( double [ ] ) bindValue ; return doubles . length > 0 ? ArrayUtils . toObject ( doubles ) : null ; } else if ( bindValue instanceof char [ ] ) { char [ ] chars = ( char [ ] ) bindValue ; return chars . length > 0 ? ArrayUtils . toObject ( chars ) : null ; } else if ( bindValue instanceof Object [ ] ) { Object [ ] objs = ( Object [ ] ) bindValue ; return objs . length > 0 ? objs : null ; } else if ( bindValue instanceof List < ? > ) { List < ? > list = ( List < ? > ) bindValue ; return list . size ( ) > 0 ? list . toArray ( ) : null ; } return new Object [ ] { bindValue } ; }
Build array of final build values according the supplied build value .
10,874
protected int calcFetchSizeForStream ( int hintFetchSize , Connection conn ) throws SQLException { DatabaseVendor dbVendor = DbcHelper . detectDbVendor ( conn ) ; switch ( dbVendor ) { case MYSQL : return Integer . MIN_VALUE ; default : return hintFetchSize < 0 ? 1 : hintFetchSize ; } }
Calculate fetch size used for streaming .
10,875
public String generateSqlSelect ( String tableName ) { try { return cacheSQLs . get ( "SELECT:" + tableName , ( ) -> { return MessageFormat . format ( "SELECT {2} FROM {0} WHERE {1}" , tableName , strWherePkClause , strAllColumns ) ; } ) ; } catch ( ExecutionException e ) { throw new DaoException ( e ) ; } }
Generate SELECT statement to select a BO .
10,876
public String generateSqlSelectAll ( String tableName ) { try { return cacheSQLs . get ( "SELECT-ALL:" + tableName , ( ) -> { return MessageFormat . format ( "SELECT {2} FROM {0} ORDER BY {1}" , tableName , strPkColumns , strAllColumns ) ; } ) ; } catch ( ExecutionException e ) { throw new DaoException ( e ) ; } }
Generate SELECT statement to SELECT all BOs ordered by promary keys .
10,877
public String generateSqlInsert ( String tableName ) { try { return cacheSQLs . get ( "INSERT:" + tableName , ( ) -> { return MessageFormat . format ( "INSERT INTO {0} ({1}) VALUES ({2})" , tableName , strAllColumns , StringUtils . repeat ( "?" , "," , getAllColumns ( ) . length ) ) ; } ) ; } catch ( ExecutionException e ) { throw new DaoException ( e ) ; } }
Generate INSERT statement to insert a BO .
10,878
public String generateSqlDelete ( String tableName ) { try { return cacheSQLs . get ( "DELETE:" + tableName , ( ) -> { return MessageFormat . format ( "DELETE FROM {0} WHERE {1}" , tableName , strWherePkClause ) ; } ) ; } catch ( ExecutionException e ) { throw new DaoException ( e ) ; } }
Generate DELETE statement to delete an existing BO .
10,879
public String generateSqlUpdate ( String tableName ) { try { return cacheSQLs . get ( "UPDATE:" + tableName , ( ) -> { return MessageFormat . format ( "UPDATE {0} SET {2} WHERE {1}" , tableName , strWherePkClause , strUpdateSetClause ) ; } ) ; } catch ( ExecutionException e ) { throw new RuntimeException ( e ) ; } }
Generate UPDATE statement to update an existing BO .
10,880
public Object [ ] valuesForColumns ( T bo , String ... columns ) { Map < String , ColAttrMapping > columnAttributeMappings = getColumnAttributeMappings ( ) ; Object [ ] result = new Object [ columns . length ] ; for ( int i = 0 ; i < columns . length ; i ++ ) { ColAttrMapping colAttrMapping = columnAttributeMappings . get ( columns [ i ] ) ; try { result [ i ] = colAttrMapping != null ? colAttrMapping . extractAttrValue ( bo ) : null ; } catch ( Exception e ) { throw e instanceof RuntimeException ? ( RuntimeException ) e : new RuntimeException ( e ) ; } } return result ; }
Extract attribute values from a BO for corresponding DB table columns
10,881
public String [ ] getAllColumns ( ) { if ( cachedAllColumns == null ) { cachedAllColumns = new ArrayList < String > ( getColumnAttributeMappings ( ) . keySet ( ) ) . toArray ( ArrayUtils . EMPTY_STRING_ARRAY ) ; } return cachedAllColumns ; }
Get all DB table column names .
10,882
private void checkForest ( Set < Sensor > sensors ) { if ( ! sensors . add ( this ) ) throw new IllegalArgumentException ( "Circular dependency in sensors: " + name ( ) + " is its own parent." ) ; for ( int i = 0 ; i < parents . length ; i ++ ) parents [ i ] . checkForest ( sensors ) ; }
Validate that this sensor doesn t end up referencing itself
10,883
private void checkQuotas ( long timeMs , boolean preCheck , double requestedValue ) { for ( int i = 0 ; i < this . metrics . size ( ) ; i ++ ) { TehutiMetric metric = this . metrics . get ( i ) ; MetricConfig config = metric . config ( ) ; if ( config != null ) { Quota quota = config . quota ( ) ; if ( quota != null ) { if ( quota . isCheckQuotaBeforeRecording ( ) ^ preCheck ) { continue ; } double value = preCheck ? metric . extraValue ( timeMs , requestedValue ) : metric . value ( timeMs ) ; if ( ! quota . acceptable ( value ) ) { throw new QuotaViolationException ( "Metric " + metric . name ( ) + " is in violation of its " + quota . toString ( ) , value ) ; } } } } }
Check if we have violated our quota for any metric that has a configured quota
10,884
public synchronized Metric add ( String name , String description , MeasurableStat stat , MetricConfig config ) { MetricConfig statConfig = ( config == null ? this . config : config ) ; TehutiMetric metric = new TehutiMetric ( this , Utils . notNull ( name ) , Utils . notNull ( description ) , Utils . notNull ( stat ) , statConfig , time ) ; this . registry . registerMetric ( metric ) ; this . metrics . add ( metric ) ; this . stats . add ( stat ) ; this . statConfigs . put ( stat , statConfig ) ; return metric ; }
Register a metric with this sensor
10,885
private void trim ( ) throws IOException { if ( isTrimShouldBeExecuted ( ) ) { final Deque < byte [ ] > tmpBuffer = new LinkedList < > ( ) ; int available ; while ( ( available = is . available ( ) ) > 0 ) { final byte [ ] buf = new byte [ available ] ; int read = is . read ( buf ) ; assert read == available : "Read not enough bytes from buffer." ; tmpBuffer . add ( buf ) ; } try { ignoreSafeWrite = true ; while ( ! tmpBuffer . isEmpty ( ) ) { os . write ( tmpBuffer . pollFirst ( ) ) ; } } finally { ignoreSafeWrite = false ; } } }
This method trims the buffer . This method can be invoked after every write operation . The method checks itself if the buffer should be trimmed or not .
10,886
private long tryWaitForEnoughBytes ( final long bytes ) throws IOException { assert bytes > 0 : "Number of bytes are negative or zero : " + bytes ; while ( bytes > availableBytes ) { try { if ( streamClosed ) { return availableBytes ; } signalModification . acquire ( ) ; } catch ( InterruptedException ex ) { throw new IOException ( ex ) ; } } return availableBytes ; }
This method blocks until the stream is closed or enough bytes are available which can be read from the buffer .
10,887
protected Field createIndexField ( String key , Object value ) { if ( key == null || value == null ) { return null ; } if ( value instanceof Boolean ) { return new IntPoint ( key , ( ( Boolean ) value ) . booleanValue ( ) ? 1 : 0 ) ; } if ( value instanceof Character ) { return new StringField ( key , value . toString ( ) , Store . NO ) ; } if ( value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long ) { Number v = ( Number ) value ; return new LongPoint ( key , v . longValue ( ) ) ; } if ( value instanceof Float || value instanceof Double ) { Number v = ( Number ) value ; return new DoublePoint ( key , v . doubleValue ( ) ) ; } if ( value instanceof Date ) { return new StringField ( key , DateFormatUtils . toString ( ( Date ) value , DATETIME_FORMAT ) , Store . NO ) ; } if ( value instanceof String ) { String v = value . toString ( ) . trim ( ) ; return v . indexOf ( ' ' ) >= 0 ? new TextField ( key , v , Store . NO ) : new StringField ( key , v , Store . NO ) ; } return null ; }
Create index field for a document s field value .
10,888
public synchronized void init ( int serverPort ) { if ( this . initialized ) { return ; } String hostname = null ; try { hostname = InetAddress . getLocalHost ( ) . getHostName ( ) ; } catch ( UnknownHostException ex ) { logger . warn ( "Get host failed. Use localhost." , ex ) ; } logger . info ( "WebSocket server initialize. : HostName={}, Port={}, Path={}, Object={}" , hostname , serverPort , "/" , this . toString ( ) ) ; this . server = new Server ( hostname , serverPort , "/" , null , AmLogServerEndPoint . class ) ; try { this . server . start ( ) ; } catch ( DeploymentException ex ) { logger . warn ( "WebSocket server initialize failed. Skip initialize." , ex ) ; } this . initialized = true ; }
Initialize WebSocket server .
10,889
public void emit ( ComponentInfo componentInfo , EmitInfo info ) { if ( this . sessions . size ( ) == 0 ) { return ; } Date nowTime = new Date ( ) ; DateFormat format = new SimpleDateFormat ( DATE_PATTERN ) ; String nowTimeStr = format . format ( nowTime ) ; Map < String , Object > objectMap = Maps . newHashMap ( ) ; objectMap . put ( "time" , nowTimeStr ) ; objectMap . put ( "component" , componentInfo ) ; objectMap . put ( "emitinfo" , info ) ; String logInfo ; try { logInfo = this . mapper . writeValueAsString ( objectMap ) ; } catch ( JsonProcessingException ex ) { String msgFormat = "Event convert failed. Skip log output. : ComponentInfo={0}, EmitInfo={1}" ; String message = MessageFormat . format ( msgFormat , componentInfo , ToStringBuilder . reflectionToString ( info , ToStringStyle . SHORT_PREFIX_STYLE ) ) ; logger . warn ( message , ex ) ; return ; } for ( Entry < String , Session > entry : this . sessions . entrySet ( ) ) { entry . getValue ( ) . getAsyncRemote ( ) . sendText ( logInfo , this . handler ) ; } }
Log emit info .
10,890
public static < F extends Fragment > FragmentBundlerCompat < F > create ( F fragment ) { return new FragmentBundlerCompat < F > ( fragment ) ; }
Constructs a FragmentBundlerCompat for the provided Fragment instance
10,891
private static byte convertHexDigit ( final byte b ) { if ( ( b >= '0' ) && ( b <= '9' ) ) { return ( byte ) ( b - '0' ) ; } if ( ( b >= 'a' ) && ( b <= 'f' ) ) { return ( byte ) ( b - 'a' + 10 ) ; } if ( ( b >= 'A' ) && ( b <= 'F' ) ) { return ( byte ) ( b - 'A' + 10 ) ; } return 0 ; }
Convert a byte character value to hexidecimal digit value .
10,892
private static void putMapEntry ( final Map < String , String [ ] > map , final String name , final String value ) { String [ ] newValues = null ; final String [ ] oldValues = map . get ( name ) ; if ( oldValues == null ) { newValues = new String [ 1 ] ; newValues [ 0 ] = value ; } else { newValues = new String [ oldValues . length + 1 ] ; System . arraycopy ( oldValues , 0 , newValues , 0 , oldValues . length ) ; newValues [ oldValues . length ] = value ; } map . put ( name , newValues ) ; }
Put name and value pair in map . When name already exist add value to array of values .
10,893
protected String getBulkData ( List < SimpleDataEvent > events ) { StringBuilder builder = new StringBuilder ( ) ; for ( SimpleDataEvent event : events ) { builder . append ( JSONUtils . getElasticSearchBulkHeader ( event , this . indexName , this . typeName ) ) ; builder . append ( "\n" ) ; builder . append ( JSONUtils . getElasticSearchAddDocument ( event . pairs ( ) ) ) ; builder . append ( "\n" ) ; } return builder . toString ( ) ; }
Returns ES bulk data .
10,894
public BaseDataJsonFieldBo setDataAttr ( String dPath , Object value ) { if ( value == null ) { return removeDataAttr ( dPath ) ; } Lock lock = lockForWrite ( ) ; try { if ( dataJson == null || dataJson instanceof MissingNode || dataJson instanceof NullNode ) { String [ ] paths = DPathUtils . splitDpath ( dPath ) ; if ( paths [ 0 ] . matches ( "^\\[(.*?)\\]$" ) ) { dataJson = JsonNodeFactory . instance . arrayNode ( ) ; } else { dataJson = JsonNodeFactory . instance . objectNode ( ) ; } } JacksonUtils . setValue ( dataJson , dPath , value , true ) ; return ( BaseDataJsonFieldBo ) setAttribute ( ATTR_DATA , SerializationUtils . toJsonString ( dataJson ) , false ) ; } finally { lock . unlock ( ) ; } }
Set a data s sub - attribute using d - path .
10,895
public BaseDataJsonFieldBo removeDataAttr ( String dPath ) { Lock lock = lockForWrite ( ) ; try { JacksonUtils . deleteValue ( dataJson , dPath ) ; return ( BaseDataJsonFieldBo ) setAttribute ( ATTR_DATA , SerializationUtils . toJsonString ( dataJson ) , false ) ; } finally { lock . unlock ( ) ; } }
Remove a data s sub - attribute using d - path .
10,896
private void checkInit ( MetricConfig config , long now ) { if ( samples . size ( ) == 0 ) { this . samples . add ( newSample ( now ) ) ; this . samples . add ( newSample ( now - config . timeWindowMs ( ) ) ) ; } }
Checks that the sample windows are properly initialized .
10,897
protected void purgeObsoleteSamples ( MetricConfig config , long now ) { long expireAge = config . samples ( ) * config . timeWindowMs ( ) ; for ( int i = 0 ; i < samples . size ( ) ; i ++ ) { Sample sample = this . samples . get ( i ) ; if ( now - sample . lastWindowMs >= expireAge ) { int rank = current - i ; if ( rank < 0 ) { rank += samples . size ( ) ; } sample . reset ( now - rank * config . timeWindowMs ( ) ) ; } } }
Timeout any windows that have expired in the absence of any events
10,898
public static List < TableColumnInfo > create ( final Class < ? > clasz , final Locale locale ) { Contract . requireArgNotNull ( "clasz" , clasz ) ; Contract . requireArgNotNull ( "locale" , locale ) ; final List < TableColumnInfo > list = new ArrayList < TableColumnInfo > ( ) ; final Field [ ] fields = clasz . getDeclaredFields ( ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { final TableColumnInfo tableColumnInfo = create ( fields [ i ] , locale ) ; if ( tableColumnInfo != null ) { list . add ( tableColumnInfo ) ; } } Collections . sort ( list ) ; return list ; }
Return a list of table column informations for the given class .
10,899
public static TableColumnInfo create ( final Field field , final Locale locale ) { Contract . requireArgNotNull ( "field" , field ) ; Contract . requireArgNotNull ( "locale" , locale ) ; final TableColumn tableColumn = field . getAnnotation ( TableColumn . class ) ; if ( tableColumn == null ) { return null ; } final AnnotationAnalyzer analyzer = new AnnotationAnalyzer ( ) ; final FieldTextInfo labelInfo = analyzer . createFieldInfo ( field , locale , Label . class ) ; final FieldTextInfo shortLabelInfo = analyzer . createFieldInfo ( field , locale , ShortLabel . class ) ; final FieldTextInfo tooltipInfo = analyzer . createFieldInfo ( field , locale , Tooltip . class ) ; final int pos = tableColumn . pos ( ) ; final FontSize fontSize = new FontSize ( tableColumn . width ( ) , tableColumn . unit ( ) ) ; final String getter = getGetter ( tableColumn , field . getName ( ) ) ; final String labelText ; if ( labelInfo == null ) { labelText = null ; } else { labelText = labelInfo . getTextOrField ( ) ; } final String shortLabelText ; if ( shortLabelInfo == null ) { shortLabelText = null ; } else { shortLabelText = shortLabelInfo . getText ( ) ; } final String tooltipText ; if ( tooltipInfo == null ) { tooltipText = null ; } else { tooltipText = tooltipInfo . getText ( ) ; } return new TableColumnInfo ( field , labelText , shortLabelText , tooltipText , pos , fontSize , getter ) ; }
Return the table column information for a given field .