idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
148,100
public static String common ( ) { String common = SysProps . get ( KEY_COMMON_CONF_TAG ) ; if ( S . blank ( common ) ) { common = "common" ; } return common ; }
Return the common configuration set name . By default it is common
49
12
148,101
public static String confSetName ( ) { String profile = SysProps . get ( AppConfigKey . PROFILE . key ( ) ) ; if ( S . blank ( profile ) ) { profile = Act . mode ( ) . name ( ) . toLowerCase ( ) ; } return profile ; }
Return the name of the current conf set
64
8
148,102
private static Map < String , Object > processConf ( Map < String , ? > conf ) { Map < String , Object > m = new HashMap < String , Object > ( conf . size ( ) ) ; for ( String s : conf . keySet ( ) ) { Object o = conf . get ( s ) ; if ( s . startsWith ( "act." ) ) s = s . substring ( 4 ) ; m . put ( s , o ) ; m . put ( Config . canonical ( s ) , o ) ; } return m ; }
trim act . from conf keys
117
7
148,103
public File curDir ( ) { File file = session ( ) . attribute ( ATTR_PWD ) ; if ( null == file ) { file = new File ( System . getProperty ( "user.dir" ) ) ; session ( ) . attribute ( ATTR_PWD , file ) ; } return file ; }
Return the current working directory
68
5
148,104
private String getRowLineBuf ( int colCount , List < Integer > colMaxLenList , String [ ] [ ] data ) { S . Buffer rowBuilder = S . buffer ( ) ; int colWidth ; for ( int i = 0 ; i < colCount ; i ++ ) { colWidth = colMaxLenList . get ( i ) + 3 ; for ( int j = 0 ; j < colWidth ; j ++ ) { if ( j == 0 ) { rowBuilder . append ( "+" ) ; } else if ( ( i + 1 == colCount && j + 1 == colWidth ) ) { //for last column close the border rowBuilder . append ( "-+" ) ; } else { rowBuilder . append ( "-" ) ; } } } return rowBuilder . append ( "\n" ) . toString ( ) ; }
Each string item rendering requires the border and a space on both sides .
178
14
148,105
public byte [ ] toByteArray ( ) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( baos ) ; oos . writeObject ( this ) ; return baos . toByteArray ( ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } }
Serialize this AppDescriptor and output byte array
80
11
148,106
public static AppDescriptor of ( String appName , Class < ? > entryClass ) { System . setProperty ( "osgl.version.suppress-var-found-warning" , "true" ) ; return of ( appName , entryClass , Version . of ( entryClass ) ) ; }
Create an AppDescriptor with appName and entry class specified .
65
14
148,107
public static AppDescriptor of ( String appName , String packageName ) { String [ ] packages = packageName . split ( S . COMMON_SEP ) ; return of ( appName , packageName , Version . ofPackage ( packages [ 0 ] ) ) ; }
Create an AppDescriptor with appName and package name specified
58
13
148,108
public static AppDescriptor deserializeFrom ( byte [ ] bytes ) { try { ByteArrayInputStream bais = new ByteArrayInputStream ( bytes ) ; ObjectInputStream ois = new ObjectInputStream ( bais ) ; return ( AppDescriptor ) ois . readObject ( ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } catch ( ClassNotFoundException e ) { throw E . unexpected ( e ) ; } }
Deserialize an AppDescriptor from byte array
102
11
148,109
static String from ( Class < ? > entryClass ) { List < String > tokens = tokenOf ( entryClass ) ; return fromTokens ( tokens ) ; }
Infer app name from entry class
33
7
148,110
static String fromPackageName ( String packageName ) { List < String > tokens = tokenOf ( packageName ) ; return fromTokens ( tokens ) ; }
Infer app name from scan package
32
7
148,111
public static String nextWord ( String string ) { int index = 0 ; while ( index < string . length ( ) && ! Character . isWhitespace ( string . charAt ( index ) ) ) { index ++ ; } return string . substring ( 0 , index ) ; }
Return the next word of the string in other words it stops when a space is encountered .
59
18
148,112
private final String getHeader ( Map /* String, String */ headers , String name ) { return ( String ) headers . get ( name . toLowerCase ( ) ) ; }
Returns the header with the specified name from the supplied map . The header lookup is case - insensitive .
36
20
148,113
public ProgressBar stop ( ) { target . kill ( ) ; try { thread . join ( ) ; target . consoleStream . print ( "\n" ) ; target . consoleStream . flush ( ) ; } catch ( InterruptedException ex ) { } return this ; }
Stops this progress bar .
56
6
148,114
public synchronized List < String > propertyListOf ( Class < ? > c ) { String cn = c . getName ( ) ; List < String > ls = repo . get ( cn ) ; if ( ls != null ) { return ls ; } Set < Class < ? > > circularReferenceDetector = new HashSet <> ( ) ; ls = propertyListOf ( c , circularReferenceDetector , null ) ; repo . put ( c . getName ( ) , ls ) ; return ls ; }
Returns the complete property list of a class
107
8
148,115
public ClassNode parent ( String name ) { this . parent = infoBase . node ( name ) ; this . parent . addChild ( this ) ; for ( ClassNode intf : parent . interfaces . values ( ) ) { addInterface ( intf ) ; } return this ; }
Specify the class represented by this ClassNode extends a class with the name specified
59
16
148,116
public ClassNode addInterface ( String name ) { ClassNode intf = infoBase . node ( name ) ; addInterface ( intf ) ; return this ; }
Specify the class represented by this ClassNode implements an interface specified by the given name
34
17
148,117
public ClassNode annotatedWith ( String name ) { ClassNode anno = infoBase . node ( name ) ; this . annotations . add ( anno ) ; anno . annotated . add ( this ) ; return this ; }
Specify the class represented by this ClassNode is annotated by an annotation class specified by the name
49
20
148,118
public static int timezoneOffset ( H . Session session ) { String s = null != session ? session . get ( SESSION_KEY ) : null ; return S . notBlank ( s ) ? Integer . parseInt ( s ) : serverTimezoneOffset ( ) ; }
Returns timezone offset from a session instance . The offset is in minutes to UTC time
58
17
148,119
public void sendJsonToUrl ( Object data , String url ) { sendToUrl ( JSON . toJSONString ( data ) , url ) ; }
Send JSON representation of given data object to all connections connected to given URL
32
14
148,120
public void sendToTagged ( String message , String ... labels ) { for ( String label : labels ) { sendToTagged ( message , label ) ; } }
Send message to all connections tagged with all given tags
35
10
148,121
public void sendJsonToTagged ( Object data , String label ) { sendToTagged ( JSON . toJSONString ( data ) , label ) ; }
Send JSON representation of given data object to all connections tagged with given label
34
14
148,122
public void sendJsonToTagged ( Object data , String ... labels ) { for ( String label : labels ) { sendJsonToTagged ( data , label ) ; } }
Send JSON representation of given data object to all connections tagged with all give tag labels
39
16
148,123
public void sendJsonToUser ( Object data , String username ) { sendToUser ( JSON . toJSONString ( data ) , username ) ; }
Send JSON representation of given data object to all connections of a user
32
13
148,124
private static boolean isBinary ( InputStream in ) { try { int size = in . available ( ) ; if ( size > 1024 ) size = 1024 ; byte [ ] data = new byte [ size ] ; in . read ( data ) ; in . close ( ) ; int ascii = 0 ; int other = 0 ; for ( int i = 0 ; i < data . length ; i ++ ) { byte b = data [ i ] ; if ( b < 0x09 ) return true ; if ( b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D ) ascii ++ ; else if ( b >= 0x20 && b <= 0x7E ) ascii ++ ; else other ++ ; } return other != 0 && 100 * other / ( ascii + other ) > 95 ; } catch ( IOException e ) { throw E . ioException ( e ) ; } }
Guess whether given file is binary . Just checks for anything under 0x09 .
203
17
148,125
public String toText ( ) { StringBuilder sb = new StringBuilder ( ) ; if ( ! description . isEmpty ( ) ) { sb . append ( description . toText ( ) ) ; sb . append ( EOL ) ; } if ( ! blockTags . isEmpty ( ) ) { sb . append ( EOL ) ; } for ( JavadocBlockTag tag : blockTags ) { sb . append ( tag . toText ( ) ) . append ( EOL ) ; } return sb . toString ( ) ; }
Return the text content of the document . It does not containing trailing spaces and asterisks at the start of the line .
117
24
148,126
public JavadocComment toComment ( String indentation ) { for ( char c : indentation . toCharArray ( ) ) { if ( ! Character . isWhitespace ( c ) ) { throw new IllegalArgumentException ( "The indentation string should be composed only by whitespace characters" ) ; } } StringBuilder sb = new StringBuilder ( ) ; sb . append ( EOL ) ; final String text = toText ( ) ; if ( ! text . isEmpty ( ) ) { for ( String line : text . split ( EOL ) ) { sb . append ( indentation ) ; sb . append ( " * " ) ; sb . append ( line ) ; sb . append ( EOL ) ; } } sb . append ( indentation ) ; sb . append ( " " ) ; return new JavadocComment ( sb . toString ( ) ) ; }
Create a JavadocComment by formatting the text of the Javadoc using the given indentation .
194
21
148,127
public static boolean isTemplatePath ( String string ) { int sz = string . length ( ) ; if ( sz == 0 ) { return true ; } for ( int i = 0 ; i < sz ; ++ i ) { char c = string . charAt ( i ) ; switch ( c ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : return false ; } } return true ; }
Check if a given string is a template path or template content
166
12
148,128
public static PasswordSpec parse ( String spec ) { char [ ] ca = spec . toCharArray ( ) ; int len = ca . length ; illegalIf ( 0 == len , spec ) ; Builder builder = new Builder ( ) ; StringBuilder minBuf = new StringBuilder ( ) ; StringBuilder maxBuf = new StringBuilder ( ) ; boolean lenSpecStart = false ; boolean minPart = false ; for ( int i = 0 ; i < len ; ++ i ) { char c = ca [ i ] ; switch ( c ) { case SPEC_LOWERCASE : illegalIf ( lenSpecStart , spec ) ; builder . requireLowercase ( ) ; break ; case SPEC_UPPERCASE : illegalIf ( lenSpecStart , spec ) ; builder . requireUppercase ( ) ; break ; case SPEC_SPECIAL_CHAR : illegalIf ( lenSpecStart , spec ) ; builder . requireSpecialChar ( ) ; break ; case SPEC_LENSPEC_START : lenSpecStart = true ; minPart = true ; break ; case SPEC_LENSPEC_CLOSE : illegalIf ( minPart , spec ) ; lenSpecStart = false ; break ; case SPEC_LENSPEC_SEP : minPart = false ; break ; case SPEC_DIGIT : if ( ! lenSpecStart ) { builder . requireDigit ( ) ; } else { if ( minPart ) { minBuf . append ( c ) ; } else { maxBuf . append ( c ) ; } } break ; default : illegalIf ( ! lenSpecStart || ! isDigit ( c ) , spec ) ; if ( minPart ) { minBuf . append ( c ) ; } else { maxBuf . append ( c ) ; } } } illegalIf ( lenSpecStart , spec ) ; if ( minBuf . length ( ) != 0 ) { builder . minLength ( Integer . parseInt ( minBuf . toString ( ) ) ) ; } if ( maxBuf . length ( ) != 0 ) { builder . maxLength ( Integer . parseInt ( maxBuf . toString ( ) ) ) ; } return builder ; }
Parse a string representation of password spec .
456
9
148,129
protected final void _onConnect ( WebSocketContext context ) { if ( null != connectionListener ) { connectionListener . onConnect ( context ) ; } connectionListenerManager . notifyFreeListeners ( context , false ) ; Act . eventBus ( ) . emit ( new WebSocketConnectEvent ( context ) ) ; }
Called by implementation class once websocket connection established at networking layer .
65
14
148,130
public String genId ( ) { S . Buffer sb = S . newBuffer ( ) ; sb . a ( longEncoder . longToStr ( nodeIdProvider . nodeId ( ) ) ) . a ( longEncoder . longToStr ( startIdProvider . startId ( ) ) ) . a ( longEncoder . longToStr ( sequenceProvider . seqId ( ) ) ) ; return sb . toString ( ) ; }
Generate a unique ID across the cluster
95
8
148,131
synchronized void bulkRegisterSingleton ( ) { for ( Map . Entry < Class < ? extends AppService > , AppService > entry : registry . entrySet ( ) ) { if ( isSingletonService ( entry . getKey ( ) ) ) { app . registerSingleton ( entry . getKey ( ) , entry . getValue ( ) ) ; } } }
Called when app s singleton registry has been initialized
78
11
148,132
@ Override public Set < String > paramKeys ( ) { Set < String > set = new HashSet < String > ( ) ; set . addAll ( C . < String > list ( request . paramNames ( ) ) ) ; set . addAll ( extraParams . keySet ( ) ) ; set . addAll ( bodyParams ( ) . keySet ( ) ) ; set . remove ( "_method" ) ; set . remove ( "_body" ) ; return set ; }
Get all parameter keys .
103
5
148,133
public ActionContext applyContentType ( Result result ) { if ( ! result . status ( ) . isError ( ) ) { return applyContentType ( ) ; } return applyContentType ( contentTypeForErrorResult ( req ( ) ) ) ; }
Apply content type to response with result provided .
52
9
148,134
public < T > T cached ( String key ) { H . Session sess = session ( ) ; if ( null != sess ) { return sess . cached ( key ) ; } else { return app ( ) . cache ( ) . get ( key ) ; } }
Return cached object by key . The key will be concatenated with current session id when fetching the cached object
57
23
148,135
public void cache ( String key , Object obj ) { H . Session sess = session ( ) ; if ( null != sess ) { sess . cache ( key , obj ) ; } else { app ( ) . cache ( ) . put ( key , obj ) ; } }
Add an object into cache by key . The key will be used in conjunction with session id if there is a session instance
59
24
148,136
public void cache ( String key , Object obj , int expiration ) { H . Session session = this . session ; if ( null != session ) { session . cache ( key , obj , expiration ) ; } else { app ( ) . cache ( ) . put ( key , obj , expiration ) ; } }
Add an object into cache by key with expiration time specified
63
11
148,137
public void evictCache ( String key ) { H . Session sess = session ( ) ; if ( null != sess ) { sess . evict ( key ) ; } else { app ( ) . cache ( ) . evict ( key ) ; } }
Evict cached object
53
4
148,138
public void login ( Object userIdentifier ) { session ( ) . put ( config ( ) . sessionKeyUsername ( ) , userIdentifier ) ; app ( ) . eventBus ( ) . trigger ( new LoginEvent ( userIdentifier . toString ( ) ) ) ; }
Update the context session to mark a user logged in
59
10
148,139
public void loginAndRedirectBack ( Object userIdentifier , String defaultLandingUrl ) { login ( userIdentifier ) ; RedirectToLoginUrl . redirectToOriginalUrl ( this , defaultLandingUrl ) ; }
Login the user and redirect back to original URL . If no original URL found then redirect to defaultLandingUrl .
47
23
148,140
public void logout ( ) { String userIdentifier = session . get ( config ( ) . sessionKeyUsername ( ) ) ; SessionManager sessionManager = app ( ) . sessionManager ( ) ; sessionManager . logout ( session ) ; if ( S . notBlank ( userIdentifier ) ) { app ( ) . eventBus ( ) . trigger ( new LogoutEvent ( userIdentifier ) ) ; } }
Logout the current session . After calling this method the session will be cleared
89
15
148,141
public static void init ( String jobId ) { JobContext parent = current_ . get ( ) ; JobContext ctx = new JobContext ( parent ) ; current_ . set ( ctx ) ; // don't call setJobId(String) // as it will trigger listeners -- TODO fix me ctx . jobId = jobId ; if ( null == parent ) { Act . eventBus ( ) . trigger ( new JobContextInitialized ( ctx ) ) ; } }
make it public for CLI interaction to reuse JobContext
100
10
148,142
public static void clear ( ) { JobContext ctx = current_ . get ( ) ; if ( null != ctx ) { ctx . bag_ . clear ( ) ; JobContext parent = ctx . parent ; if ( null != parent ) { current_ . set ( parent ) ; ctx . parent = null ; } else { current_ . remove ( ) ; Act . eventBus ( ) . trigger ( new JobContextDestroyed ( ctx ) ) ; } } }
Clear JobContext of current thread
101
6
148,143
public static < T > T get ( String key , Class < T > clz ) { return ( T ) m ( ) . get ( key ) ; }
Generic version of getting value by key from the JobContext of current thread
33
14
148,144
static JobContext copy ( ) { JobContext current = current_ . get ( ) ; //JobContext ctxt = new JobContext(keepParent ? current : null); JobContext ctxt = new JobContext ( null ) ; if ( null != current ) { ctxt . bag_ . putAll ( current . bag_ ) ; } return ctxt ; }
Make a copy of JobContext of current thread
75
9
148,145
static void loadFromOrigin ( JobContext origin ) { if ( origin . bag_ . isEmpty ( ) ) { return ; } ActContext < ? > actContext = ActContext . Base . currentContext ( ) ; if ( null != actContext ) { Locale locale = ( Locale ) origin . bag_ . get ( "locale" ) ; if ( null != locale ) { actContext . locale ( locale ) ; } H . Session session = ( H . Session ) origin . bag_ . get ( "session" ) ; if ( null != session ) { actContext . attribute ( "__session" , session ) ; } } }
Initialize current thread s JobContext using specified copy
135
10
148,146
public String getToken ( ) { String id = null == answer ? text : answer ; return Act . app ( ) . crypto ( ) . generateToken ( id ) ; }
Returns an encrypted token combined with answer .
36
8
148,147
public String expand ( String macro ) { if ( ! isMacro ( macro ) ) { return macro ; } String definition = macros . get ( Config . canonical ( macro ) ) ; if ( null == definition ) { warn ( "possible missing definition of macro[%s]" , macro ) ; } return null == definition ? macro : definition ; }
Expand a macro .
73
5
148,148
public static boolean isPackageOrClassName ( String s ) { if ( S . blank ( s ) ) { return false ; } S . List parts = S . fastSplit ( s , "." ) ; if ( parts . size ( ) < 2 ) { return false ; } for ( String part : parts ) { if ( ! Character . isJavaIdentifierStart ( part . charAt ( 0 ) ) ) { return false ; } for ( int i = 1 , len = part . length ( ) ; i < len ; ++ i ) { if ( ! Character . isJavaIdentifierPart ( part . charAt ( i ) ) ) { return false ; } } } return true ; }
Check if a given string is a valid java package or class name .
145
14
148,149
public static String packageNameOf ( Class < ? > clazz ) { String name = clazz . getName ( ) ; int pos = name . lastIndexOf ( ' ' ) ; E . unexpectedIf ( pos < 0 , "Class does not have package: " + name ) ; return name . substring ( 0 , pos ) ; }
Returns package name of a class
72
6
148,150
public static RouteInfo of ( ActionContext context ) { H . Method m = context . req ( ) . method ( ) ; String path = context . req ( ) . url ( ) ; RequestHandler handler = context . handler ( ) ; if ( null == handler ) { handler = UNKNOWN_HANDLER ; } return new RouteInfo ( m , path , handler ) ; }
used by Error template
79
4
148,151
public List < WebSocketConnection > get ( String key ) { final List < WebSocketConnection > retList = new ArrayList <> ( ) ; accept ( key , C . F . addTo ( retList ) ) ; return retList ; }
Return a list of websocket connection by key
52
9
148,152
public void signIn ( String key , WebSocketConnection connection ) { ConcurrentMap < WebSocketConnection , WebSocketConnection > bag = ensureConnectionList ( key ) ; bag . put ( connection , connection ) ; }
Sign in a connection to the registry by key .
45
10
148,153
public void signIn ( String key , Collection < WebSocketConnection > connections ) { if ( connections . isEmpty ( ) ) { return ; } Map < WebSocketConnection , WebSocketConnection > newMap = new HashMap <> ( ) ; for ( WebSocketConnection conn : connections ) { newMap . put ( conn , conn ) ; } ConcurrentMap < WebSocketConnection , WebSocketConnection > bag = ensureConnectionList ( key ) ; bag . putAll ( newMap ) ; }
Sign in a group of connections to the registry by key
103
11
148,154
public void signOff ( String key , WebSocketConnection connection ) { ConcurrentMap < WebSocketConnection , WebSocketConnection > connections = registry . get ( key ) ; if ( null == connections ) { return ; } connections . remove ( connection ) ; }
Detach a connection from a key .
53
8
148,155
public void signOff ( WebSocketConnection connection ) { for ( ConcurrentMap < WebSocketConnection , WebSocketConnection > connections : registry . values ( ) ) { connections . remove ( connection ) ; } }
Remove a connection from all keys .
43
7
148,156
public void signOff ( String key , Collection < WebSocketConnection > connections ) { if ( connections . isEmpty ( ) ) { return ; } ConcurrentMap < WebSocketConnection , WebSocketConnection > bag = ensureConnectionList ( key ) ; bag . keySet ( ) . removeAll ( connections ) ; }
Sign off a group of connections from the registry by key
65
11
148,157
public int count ( ) { int n = 0 ; for ( ConcurrentMap < ? , ? > bag : registry . values ( ) ) { n += bag . size ( ) ; } return n ; }
Returns the connection count in this registry .
43
8
148,158
public int count ( String key ) { ConcurrentMap < WebSocketConnection , WebSocketConnection > bag = registry . get ( key ) ; return null == bag ? 0 : bag . size ( ) ; }
Returns the connection count by key specified in this registry
43
10
148,159
public static Object tryGetSingleton ( Class < ? > invokerClass , App app ) { Object singleton = app . singleton ( invokerClass ) ; if ( null == singleton ) { if ( isGlobalOrStateless ( invokerClass , new HashSet < Class > ( ) ) ) { singleton = app . getInstance ( invokerClass ) ; } } if ( null != singleton ) { app . registerSingleton ( singleton ) ; } return singleton ; }
If the invokerClass specified is singleton or without field or all fields are stateless then return an instance of the invoker class . Otherwise return null
104
31
148,160
private static final void writeJson ( Writer os , // Object object , // SerializeConfig config , // SerializeFilter [ ] filters , // DateFormat dateFormat , // int defaultFeatures , // SerializerFeature ... features ) { SerializeWriter writer = new SerializeWriter ( os , defaultFeatures , features ) ; try { JSONSerializer serializer = new JSONSerializer ( writer , config ) ; if ( dateFormat != null ) { serializer . setDateFormat ( dateFormat ) ; serializer . config ( SerializerFeature . WriteDateUseDateFormat , true ) ; } if ( filters != null ) { for ( SerializeFilter filter : filters ) { serializer . addFilter ( filter ) ; } } serializer . write ( object ) ; } finally { writer . close ( ) ; } }
FastJSON does not provide the API so we have to create our own
169
14
148,161
public Set < Class > entityClasses ( ) { EntityMetaInfoRepo repo = app ( ) . entityMetaInfoRepo ( ) . forDb ( id ) ; return null == repo ? C . < Class > set ( ) : repo . entityClasses ( ) ; }
Returns all model classes registered on this datasource
59
9
148,162
public WebSocketContext messageReceived ( String receivedMessage ) { this . stringMessage = S . string ( receivedMessage ) . trim ( ) ; isJson = stringMessage . startsWith ( "{" ) || stringMessage . startsWith ( "]" ) ; tryParseQueryParams ( ) ; return this ; }
Called when remote end send a message to this connection
67
11
148,163
public WebSocketContext reTag ( String label ) { WebSocketConnectionRegistry registry = manager . tagRegistry ( ) ; registry . signOff ( connection ) ; registry . signIn ( label , connection ) ; return this ; }
Re - Tag the websocket connection hold by this context with label specified . This method will remove all previous tags on the websocket connection and then tag it with the new label .
48
36
148,164
public WebSocketContext sendToPeers ( String message , boolean excludeSelf ) { return sendToConnections ( message , url , manager . urlRegistry ( ) , excludeSelf ) ; }
Send message to all connections connected to the same URL of this context
40
13
148,165
public WebSocketContext sendToTagged ( String message , String tag ) { return sendToTagged ( message , tag , false ) ; }
Send message to all connections labeled with tag specified with self connection excluded
30
13
148,166
public WebSocketContext sendToTagged ( String message , String tag , boolean excludeSelf ) { return sendToConnections ( message , tag , manager . tagRegistry ( ) , excludeSelf ) ; }
Send message to all connections labeled with tag specified .
43
10
148,167
public WebSocketContext sendToUser ( String message , String username ) { return sendToConnections ( message , username , manager . usernameRegistry ( ) , true ) ; }
Send message to all connections of a certain user
37
9
148,168
public WebSocketContext sendJsonToUser ( Object data , String username ) { return sendToTagged ( JSON . toJSONString ( data ) , username ) ; }
Send JSON representation of a data object to all connections of a certain user
36
14
148,169
public void bindMappers ( ) { JacksonXmlModule xmlModule = new JacksonXmlModule ( ) ; xmlModule . setDefaultUseWrapper ( false ) ; XmlMapper xmlMapper = new XmlMapper ( xmlModule ) ; xmlMapper . enable ( ToXmlGenerator . Feature . WRITE_XML_DECLARATION ) ; this . bind ( XmlMapper . class ) . toInstance ( xmlMapper ) ; ObjectMapper objectMapper = new ObjectMapper ( ) ; objectMapper . configure ( DeserializationFeature . FAIL_ON_UNKNOWN_PROPERTIES , false ) ; objectMapper . configure ( DeserializationFeature . ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT , true ) ; objectMapper . configure ( DeserializationFeature . ACCEPT_EMPTY_STRING_AS_NULL_OBJECT , true ) ; objectMapper . configure ( DeserializationFeature . EAGER_DESERIALIZER_FETCH , true ) ; objectMapper . configure ( DeserializationFeature . ACCEPT_SINGLE_VALUE_AS_ARRAY , true ) ; objectMapper . configure ( DeserializationFeature . USE_BIG_DECIMAL_FOR_FLOATS , true ) ; objectMapper . registerModule ( new AfterburnerModule ( ) ) ; objectMapper . registerModule ( new Jdk8Module ( ) ) ; this . bind ( ObjectMapper . class ) . toInstance ( objectMapper ) ; this . requestStaticInjection ( Extractors . class ) ; this . requestStaticInjection ( ServerResponse . class ) ; }
Override for customizing XmlMapper and ObjectMapper
365
12
148,170
public Swagger read ( Set < Class < ? > > classes ) { Set < Class < ? > > sortedClasses = new TreeSet <> ( ( class1 , class2 ) -> { if ( class1 . equals ( class2 ) ) { return 0 ; } else if ( class1 . isAssignableFrom ( class2 ) ) { return - 1 ; } else if ( class2 . isAssignableFrom ( class1 ) ) { return 1 ; } return class1 . getName ( ) . compareTo ( class2 . getName ( ) ) ; } ) ; sortedClasses . addAll ( classes ) ; Map < Class < ? > , ReaderListener > listeners = new HashMap < Class < ? > , ReaderListener > ( ) ; for ( Class < ? > cls : sortedClasses ) { if ( ReaderListener . class . isAssignableFrom ( cls ) && ! listeners . containsKey ( cls ) ) { try { listeners . put ( cls , ( ReaderListener ) cls . newInstance ( ) ) ; } catch ( Exception e ) { LOGGER . error ( "Failed to create ReaderListener" , e ) ; } } } // for (ReaderListener listener : listeners.values()) { // try { // listener.beforeScan(this, swagger); // } catch (Exception e) { // LOGGER.error("Unexpected error invoking beforeScan listener [" + listener.getClass().getName() + "]", e); // } // } // process SwaggerDefinitions first - so we get tags in desired order for ( Class < ? > cls : sortedClasses ) { SwaggerDefinition swaggerDefinition = cls . getAnnotation ( SwaggerDefinition . class ) ; if ( swaggerDefinition != null ) { readSwaggerConfig ( cls , swaggerDefinition ) ; } } for ( Class < ? > cls : sortedClasses ) { read ( cls , "" , null , false , new String [ 0 ] , new String [ 0 ] , new LinkedHashMap <> ( ) , new ArrayList <> ( ) , new HashSet <> ( ) ) ; } // for (ReaderListener listener : listeners.values()) { // try { // listener.afterScan(this, swagger); // } catch (Exception e) { // LOGGER.error("Unexpected error invoking afterScan listener [" + listener.getClass().getName() + "]", e); // } // } return swagger ; }
Scans a set of classes for both ReaderListeners and Swagger annotations . All found listeners will be instantiated before any of the classes are scanned for Swagger annotations - so they can be invoked accordingly .
530
42
148,171
public Swagger read ( Class < ? > cls ) { SwaggerDefinition swaggerDefinition = cls . getAnnotation ( SwaggerDefinition . class ) ; if ( swaggerDefinition != null ) { readSwaggerConfig ( cls , swaggerDefinition ) ; } return read ( cls , "" , null , false , new String [ 0 ] , new String [ 0 ] , new LinkedHashMap <> ( ) , new ArrayList <> ( ) , new HashSet <> ( ) ) ; }
Scans a single class for Swagger annotations - does not invoke ReaderListeners
109
16
148,172
public ProteusApplication addDefaultRoutes ( RoutingHandler router ) { if ( config . hasPath ( "health.statusPath" ) ) { try { final String statusPath = config . getString ( "health.statusPath" ) ; router . add ( Methods . GET , statusPath , ( final HttpServerExchange exchange ) -> { exchange . getResponseHeaders ( ) . add ( Headers . CONTENT_TYPE , MediaType . TEXT_PLAIN ) ; exchange . getResponseSender ( ) . send ( "OK" ) ; } ) ; this . registeredEndpoints . add ( EndpointInfo . builder ( ) . withConsumes ( "*/*" ) . withProduces ( "text/plain" ) . withPathTemplate ( statusPath ) . withControllerName ( "Internal" ) . withMethod ( Methods . GET ) . build ( ) ) ; } catch ( Exception e ) { log . error ( "Error adding health status route." , e . getMessage ( ) ) ; } } if ( config . hasPath ( "application.favicon" ) ) { try { final ByteBuffer faviconImageBuffer ; final File faviconFile = new File ( config . getString ( "application.favicon" ) ) ; if ( ! faviconFile . exists ( ) ) { try ( final InputStream stream = this . getClass ( ) . getResourceAsStream ( config . getString ( "application.favicon" ) ) ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte [ ] buffer = new byte [ 4096 ] ; int read = 0 ; while ( read != - 1 ) { read = stream . read ( buffer ) ; if ( read > 0 ) { baos . write ( buffer , 0 , read ) ; } } faviconImageBuffer = ByteBuffer . wrap ( baos . toByteArray ( ) ) ; } } else { try ( final InputStream stream = Files . newInputStream ( Paths . get ( config . getString ( "application.favicon" ) ) ) ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte [ ] buffer = new byte [ 4096 ] ; int read = 0 ; while ( read != - 1 ) { read = stream . read ( buffer ) ; if ( read > 0 ) { baos . write ( buffer , 0 , read ) ; } } faviconImageBuffer = ByteBuffer . wrap ( baos . toByteArray ( ) ) ; } } router . add ( Methods . GET , "favicon.ico" , ( final HttpServerExchange exchange ) -> { exchange . getResponseHeaders ( ) . add ( Headers . CONTENT_TYPE , io . sinistral . proteus . server . MediaType . IMAGE_X_ICON . toString ( ) ) ; exchange . getResponseSender ( ) . send ( faviconImageBuffer ) ; } ) ; } catch ( Exception e ) { log . error ( "Error adding favicon route." , e . getMessage ( ) ) ; } } return this ; }
Add utility routes the router
662
5
148,173
public ProteusApplication setServerConfigurationFunction ( Function < Undertow . Builder , Undertow . Builder > serverConfigurationFunction ) { this . serverConfigurationFunction = serverConfigurationFunction ; return this ; }
Allows direct access to the Undertow . Builder for custom configuration
43
13
148,174
static DisplayMetrics getDisplayMetrics ( final Context context ) { final WindowManager windowManager = ( WindowManager ) context . getSystemService ( Context . WINDOW_SERVICE ) ; final DisplayMetrics metrics = new DisplayMetrics ( ) ; windowManager . getDefaultDisplay ( ) . getMetrics ( metrics ) ; return metrics ; }
Returns a valid DisplayMetrics object
73
7
148,175
private static Bitmap crop ( Bitmap srcBmp , View canvasView , int downsampling ) { float scale = 1f / downsampling ; return Bitmap . createBitmap ( srcBmp , ( int ) Math . floor ( ( ViewCompat . getX ( canvasView ) ) * scale ) , ( int ) Math . floor ( ( ViewCompat . getY ( canvasView ) ) * scale ) , ( int ) Math . floor ( ( canvasView . getWidth ( ) ) * scale ) , ( int ) Math . floor ( ( canvasView . getHeight ( ) ) * scale ) ) ; }
crops the srcBmp with the canvasView bounds and returns the cropped bitmap
130
17
148,176
public void startTask ( int id , String taskName ) { if ( isActivated ) { durations . add ( new Duration ( id , taskName , BenchmarkUtil . elapsedRealTimeNanos ( ) ) ) ; } }
Start a task . The id is needed to end the task
50
12
148,177
public double getDurationMs ( ) { double durationMs = 0 ; for ( Duration duration : durations ) { if ( duration . taskFinished ( ) ) { durationMs += duration . getDurationMS ( ) ; } } return durationMs ; }
Returns the duration of the measured tasks in ms
52
9
148,178
public static void setViewBackground ( View v , Drawable d ) { if ( Build . VERSION . SDK_INT >= 16 ) { v . setBackground ( d ) ; } else { v . setBackgroundDrawable ( d ) ; } }
legacy helper for setting background
52
6
148,179
public static int byteSizeOf ( Bitmap bitmap ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . KITKAT ) { return bitmap . getAllocationByteCount ( ) ; } else if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB_MR1 ) { return bitmap . getByteCount ( ) ; } else { return bitmap . getRowBytes ( ) * bitmap . getHeight ( ) ; } }
returns the bytesize of the give bitmap
115
10
148,180
public static String getCacheDir ( Context ctx ) { return Environment . MEDIA_MOUNTED . equals ( Environment . getExternalStorageState ( ) ) || ( ! Environment . isExternalStorageRemovable ( ) && ctx . getExternalCacheDir ( ) != null ) ? ctx . getExternalCacheDir ( ) . getPath ( ) : ctx . getCacheDir ( ) . getPath ( ) ; }
Gets the appropriate cache dir
89
6
148,181
public Point measureImage ( Resources resources ) { BitmapFactory . Options justBoundsOptions = new BitmapFactory . Options ( ) ; justBoundsOptions . inJustDecodeBounds = true ; if ( bitmap != null ) { return new Point ( bitmap . getWidth ( ) , bitmap . getHeight ( ) ) ; } else if ( resId != null ) { BitmapFactory . decodeResource ( resources , resId , justBoundsOptions ) ; float scale = ( float ) justBoundsOptions . inTargetDensity / justBoundsOptions . inDensity ; return new Point ( ( int ) ( justBoundsOptions . outWidth * scale + 0.5f ) , ( int ) ( justBoundsOptions . outHeight * scale + 0.5f ) ) ; } else if ( fileToBitmap != null ) { BitmapFactory . decodeFile ( fileToBitmap . getAbsolutePath ( ) , justBoundsOptions ) ; } else if ( inputStream != null ) { BitmapFactory . decodeStream ( inputStream , null , justBoundsOptions ) ; try { inputStream . reset ( ) ; } catch ( IOException ignored ) { } } else if ( view != null ) { return new Point ( view . getWidth ( ) , view . getHeight ( ) ) ; } return new Point ( justBoundsOptions . outWidth , justBoundsOptions . outHeight ) ; }
If the not a bitmap itself this will read the file s meta data .
303
16
148,182
public synchronized int cancelByTag ( String tagToCancel ) { int i = 0 ; if ( taskList . containsKey ( tagToCancel ) ) { removeDoneTasks ( ) ; for ( Future < BlurWorker . Result > future : taskList . get ( tagToCancel ) ) { BuilderUtil . logVerbose ( Dali . getConfig ( ) . logTag , "Canceling task with tag " + tagToCancel , Dali . getConfig ( ) . debugMode ) ; future . cancel ( true ) ; i ++ ; } //remove all canceled tasks Iterator < Future < BlurWorker . Result > > iter = taskList . get ( tagToCancel ) . iterator ( ) ; while ( iter . hasNext ( ) ) { if ( iter . next ( ) . isCancelled ( ) ) { iter . remove ( ) ; } } } return i ; }
Cancel all task with this tag and returns the canceled task count
197
13
148,183
public static Bitmap flip ( Bitmap src ) { Matrix m = new Matrix ( ) ; m . preScale ( - 1 , 1 ) ; return Bitmap . createBitmap ( src , 0 , 0 , src . getWidth ( ) , src . getHeight ( ) , m , false ) ; }
Mirrors the given bitmap
64
6
148,184
public void purge ( String cacheKey ) { try { if ( useMemoryCache ) { if ( memoryCache != null ) { memoryCache . remove ( cacheKey ) ; } } if ( useDiskCache ) { if ( diskLruCache != null ) { diskLruCache . remove ( cacheKey ) ; } } } catch ( Exception e ) { Log . w ( TAG , "Could not remove entry in cache purge" , e ) ; } }
Removes the value connected to the given key from all levels of the cache . Will not throw an exception on fail .
95
24
148,185
public RenderScript getRenderScript ( ) { if ( renderScript == null ) { renderScript = RenderScript . create ( context , renderScriptContextType ) ; } return renderScript ; }
Syncronously creates a Renderscript context if none exists . Creating a Renderscript context takes about 20 ms in Nexus 5
39
26
148,186
private void renderBlurLayer ( float slideOffset ) { if ( enableBlur ) { if ( slideOffset == 0 || forceRedraw ) { clearBlurView ( ) ; } if ( slideOffset > 0f && blurView == null ) { if ( drawerLayout . getChildCount ( ) == 2 ) { blurView = new ImageView ( drawerLayout . getContext ( ) ) ; blurView . setLayoutParams ( new ViewGroup . LayoutParams ( ViewGroup . LayoutParams . MATCH_PARENT , ViewGroup . LayoutParams . MATCH_PARENT ) ) ; blurView . setScaleType ( ImageView . ScaleType . FIT_CENTER ) ; drawerLayout . addView ( blurView , 1 ) ; } if ( BuilderUtil . isOnUiThread ( ) ) { if ( cacheMode . equals ( CacheMode . AUTO ) || forceRedraw ) { dali . load ( drawerLayout . getChildAt ( 0 ) ) . blurRadius ( blurRadius ) . downScale ( downSample ) . noFade ( ) . error ( Dali . NO_RESID ) . concurrent ( ) . skipCache ( ) . into ( blurView ) ; forceRedraw = false ; } else { dali . load ( drawerLayout . getChildAt ( 0 ) ) . blurRadius ( blurRadius ) . downScale ( downSample ) . noFade ( ) . error ( Dali . NO_RESID ) . concurrent ( ) . into ( blurView ) ; } } } if ( slideOffset > 0f && slideOffset < 1f ) { int alpha = ( int ) Math . ceil ( ( double ) slideOffset * 255d ) ; LegacySDKUtil . setImageAlpha ( blurView , alpha ) ; } } }
This will blur the view behind it and set it in a imageview over the content with a alpha value that corresponds to slideOffset .
384
27
148,187
public void onDrawerOpened ( View drawerView ) { super . onDrawerOpened ( drawerView ) ; if ( listener != null ) listener . onDrawerClosed ( drawerView ) ; }
Called when a drawer has settled in a completely open state .
44
13
148,188
public static IBlur getIBlurAlgorithm ( EBlurAlgorithm algorithm , ContextWrapper contextWrapper ) { RenderScript rs = contextWrapper . getRenderScript ( ) ; Context ctx = contextWrapper . getContext ( ) ; switch ( algorithm ) { case RS_GAUSS_FAST : return new RenderScriptGaussianBlur ( rs ) ; case RS_BOX_5x5 : return new RenderScriptBox5x5Blur ( rs ) ; case RS_GAUSS_5x5 : return new RenderScriptGaussian5x5Blur ( rs ) ; case RS_STACKBLUR : return new RenderScriptStackBlur ( rs , ctx ) ; case STACKBLUR : return new StackBlur ( ) ; case GAUSS_FAST : return new GaussianFastBlur ( ) ; case BOX_BLUR : return new BoxBlur ( ) ; default : return new IgnoreBlur ( ) ; } }
Creates an IBlur instance for the given algorithm enum
207
12
148,189
public BlurBuilder downScale ( int scaleInSample ) { data . options . inSampleSize = Math . min ( Math . max ( 1 , scaleInSample ) , 16384 ) ; return this ; }
Will scale the image down before processing for performance enhancement and less memory usage sacrificing image quality .
44
18
148,190
public BlurBuilder brightness ( float brightness ) { data . preProcessors . add ( new RenderscriptBrightnessProcessor ( data . contextWrapper . getRenderScript ( ) , brightness , data . contextWrapper . getResources ( ) ) ) ; return this ; }
Set brightness to eg . darken the resulting image for use as background
58
14
148,191
public BlurBuilder contrast ( float contrast ) { data . preProcessors . add ( new ContrastProcessor ( data . contextWrapper . getRenderScript ( ) , Math . max ( Math . min ( 1500.f , contrast ) , - 1500.f ) ) ) ; return this ; }
Change contrast of the image
62
5
148,192
public static synchronized void resetAndSetNewConfig ( Context ctx , Config config ) { GLOBAL_CONFIG = config ; if ( DISK_CACHE_MANAGER != null ) { DISK_CACHE_MANAGER . clear ( ) ; DISK_CACHE_MANAGER = null ; createCache ( ctx ) ; } if ( EXECUTOR_MANAGER != null ) { EXECUTOR_MANAGER . shutDown ( ) ; EXECUTOR_MANAGER = null ; } Log . i ( TAG , "New config set" ) ; }
Sets a new config and clears the previous cache
133
10
148,193
public static int getIbanLength ( final CountryCode countryCode ) { final BbanStructure structure = getBbanStructure ( countryCode ) ; return COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH + structure . getBbanLength ( ) ; }
Returns iban length for the specified country .
62
9
148,194
public static String getCountryCodeAndCheckDigit ( final String iban ) { return iban . substring ( COUNTRY_CODE_INDEX , COUNTRY_CODE_INDEX + COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH ) ; }
Returns iban s country code and check digit .
63
10
148,195
static String replaceCheckDigit ( final String iban , final String checkDigit ) { return getCountryCode ( iban ) + checkDigit + getBban ( iban ) ; }
Returns an iban with replaced check digit .
41
9
148,196
static String toFormattedString ( final String iban ) { final StringBuilder ibanBuffer = new StringBuilder ( iban ) ; final int length = ibanBuffer . length ( ) ; for ( int i = 0 ; i < length / 4 ; i ++ ) { ibanBuffer . insert ( ( i + 1 ) * 4 + i , ' ' ) ; } return ibanBuffer . toString ( ) . trim ( ) ; }
Returns formatted version of Iban .
93
7
148,197
public static Bic valueOf ( final String bic ) throws BicFormatException , UnsupportedCountryException { BicUtil . validate ( bic ) ; return new Bic ( bic ) ; }
Returns a Bic object holding the value of the specified String .
44
13
148,198
public static void validate ( final String bic ) throws BicFormatException , UnsupportedCountryException { try { validateEmpty ( bic ) ; validateLength ( bic ) ; validateCase ( bic ) ; validateBankCode ( bic ) ; validateCountryCode ( bic ) ; validateLocationCode ( bic ) ; if ( hasBranchCode ( bic ) ) { validateBranchCode ( bic ) ; } } catch ( UnsupportedCountryException e ) { throw e ; } catch ( RuntimeException e ) { throw new BicFormatException ( UNKNOWN , e . getMessage ( ) ) ; } }
Validates bic .
131
5
148,199
@ Override public < X > X getScreenshotAs ( OutputType < X > target ) { // Get the screenshot as base64 and convert it to the requested type (i.e. OutputType<T>) String base64 = ( String ) execute ( DriverCommand . SCREENSHOT ) . getValue ( ) ; return target . convertFromBase64Png ( base64 ) ; }
Take screenshot of the current window .
83
7