idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
24,700
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 .
24,701
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
24,702
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
24,703
static String from ( Class < ? > entryClass ) { List < String > tokens = tokenOf ( entryClass ) ; return fromTokens ( tokens ) ; }
Infer app name from entry class
24,704
static String fromPackageName ( String packageName ) { List < String > tokens = tokenOf ( packageName ) ; return fromTokens ( tokens ) ; }
Infer app name from scan package
24,705
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 .
24,706
private final String getHeader ( Map 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 .
24,707
public ProgressBar stop ( ) { target . kill ( ) ; try { thread . join ( ) ; target . consoleStream . print ( "\n" ) ; target . consoleStream . flush ( ) ; } catch ( InterruptedException ex ) { } return this ; }
Stops this progress bar .
24,708
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
24,709
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
24,710
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
24,711
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
24,712
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
24,713
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
24,714
public void sendToTagged ( String message , String ... labels ) { for ( String label : labels ) { sendToTagged ( message , label ) ; } }
Send message to all connections tagged with all given tags
24,715
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
24,716
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
24,717
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
24,718
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 .
24,719
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 .
24,720
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 .
24,721
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 '\t' : case '\b' : 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
24,722
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 .
24,723
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 .
24,724
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
24,725
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
24,726
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 .
24,727
public ActionContext applyContentType ( Result result ) { if ( ! result . status ( ) . isError ( ) ) { return applyContentType ( ) ; } return applyContentType ( contentTypeForErrorResult ( req ( ) ) ) ; }
Apply content type to response with result provided .
24,728
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
24,729
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
24,730
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
24,731
public void evictCache ( String key ) { H . Session sess = session ( ) ; if ( null != sess ) { sess . evict ( key ) ; } else { app ( ) . cache ( ) . evict ( key ) ; } }
Evict cached object
24,732
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
24,733
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 .
24,734
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
24,735
public static void init ( String jobId ) { JobContext parent = current_ . get ( ) ; JobContext ctx = new JobContext ( parent ) ; current_ . set ( ctx ) ; ctx . jobId = jobId ; if ( null == parent ) { Act . eventBus ( ) . trigger ( new JobContextInitialized ( ctx ) ) ; } }
make it public for CLI interaction to reuse JobContext
24,736
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
24,737
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
24,738
static JobContext copy ( ) { JobContext current = current_ . get ( ) ; JobContext ctxt = new JobContext ( null ) ; if ( null != current ) { ctxt . bag_ . putAll ( current . bag_ ) ; } return ctxt ; }
Make a copy of JobContext of current thread
24,739
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
24,740
public String getToken ( ) { String id = null == answer ? text : answer ; return Act . app ( ) . crypto ( ) . generateToken ( id ) ; }
Returns an encrypted token combined with answer .
24,741
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 .
24,742
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 .
24,743
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
24,744
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
24,745
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
24,746
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 .
24,747
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
24,748
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 .
24,749
public void signOff ( WebSocketConnection connection ) { for ( ConcurrentMap < WebSocketConnection , WebSocketConnection > connections : registry . values ( ) ) { connections . remove ( connection ) ; } }
Remove a connection from all keys .
24,750
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
24,751
public int count ( ) { int n = 0 ; for ( ConcurrentMap < ? , ? > bag : registry . values ( ) ) { n += bag . size ( ) ; } return n ; }
Returns the connection count in this registry .
24,752
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
24,753
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
24,754
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
24,755
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
24,756
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
24,757
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 .
24,758
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
24,759
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
24,760
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 .
24,761
public WebSocketContext sendToUser ( String message , String username ) { return sendToConnections ( message , username , manager . usernameRegistry ( ) , true ) ; }
Send message to all connections of a certain user
24,762
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
24,763
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
24,764
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 ( 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 < > ( ) ) ; } 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 .
24,765
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
24,766
protected void generateRoutes ( ) { try { TypeSpec . Builder typeBuilder = TypeSpec . classBuilder ( className ) . addModifiers ( Modifier . PUBLIC ) . addSuperinterface ( ParameterizedTypeName . get ( Supplier . class , RoutingHandler . class ) ) ; ClassName extractorClass = ClassName . get ( "io.sinistral.proteus.server" , "Extractors" ) ; ClassName injectClass = ClassName . get ( "com.google.inject" , "Inject" ) ; MethodSpec . Builder constructor = MethodSpec . constructorBuilder ( ) . addModifiers ( Modifier . PUBLIC ) . addAnnotation ( injectClass ) ; String className = this . controllerClass . getSimpleName ( ) . toLowerCase ( ) + "Controller" ; typeBuilder . addField ( this . controllerClass , className , Modifier . PROTECTED , Modifier . FINAL ) ; ClassName wrapperClass = ClassName . get ( "io.undertow.server" , "HandlerWrapper" ) ; ClassName stringClass = ClassName . get ( "java.lang" , "String" ) ; ClassName mapClass = ClassName . get ( "java.util" , "Map" ) ; TypeName mapOfWrappers = ParameterizedTypeName . get ( mapClass , stringClass , wrapperClass ) ; TypeName annotatedMapOfWrappers = mapOfWrappers . annotated ( AnnotationSpec . builder ( com . google . inject . name . Named . class ) . addMember ( "value" , "$S" , "registeredHandlerWrappers" ) . build ( ) ) ; typeBuilder . addField ( mapOfWrappers , "registeredHandlerWrappers" , Modifier . PROTECTED , Modifier . FINAL ) ; constructor . addParameter ( this . controllerClass , className ) ; constructor . addParameter ( annotatedMapOfWrappers , "registeredHandlerWrappers" ) ; constructor . addStatement ( "this.$N = $N" , className , className ) ; constructor . addStatement ( "this.$N = $N" , "registeredHandlerWrappers" , "registeredHandlerWrappers" ) ; addClassMethodHandlers ( typeBuilder , this . controllerClass ) ; typeBuilder . addMethod ( constructor . build ( ) ) ; JavaFile javaFile = JavaFile . builder ( packageName , typeBuilder . build ( ) ) . addStaticImport ( extractorClass , "*" ) . build ( ) ; StringBuilder sb = new StringBuilder ( ) ; javaFile . writeTo ( sb ) ; this . sourceString = sb . toString ( ) ; } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; } }
Generates the routing Java source code
24,767
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
24,768
public ProteusApplication setServerConfigurationFunction ( Function < Undertow . Builder , Undertow . Builder > serverConfigurationFunction ) { this . serverConfigurationFunction = serverConfigurationFunction ; return this ; }
Allows direct access to the Undertow . Builder for custom configuration
24,769
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
24,770
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
24,771
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
24,772
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
24,773
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
24,774
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
24,775
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
24,776
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 .
24,777
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 ++ ; } 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
24,778
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
24,779
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 .
24,780
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
24,781
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 .
24,782
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 .
24,783
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
24,784
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 .
24,785
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
24,786
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
24,787
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
24,788
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 .
24,789
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 .
24,790
static String replaceCheckDigit ( final String iban , final String checkDigit ) { return getCountryCode ( iban ) + checkDigit + getBban ( iban ) ; }
Returns an iban with replaced check digit .
24,791
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 .
24,792
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 .
24,793
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 .
24,794
public < X > X getScreenshotAs ( OutputType < X > target ) { String base64 = ( String ) execute ( DriverCommand . SCREENSHOT ) . getValue ( ) ; return target . convertFromBase64Png ( base64 ) ; }
Take screenshot of the current window .
24,795
public PayloadBuilder sound ( final String sound ) { if ( sound != null ) { aps . put ( "sound" , sound ) ; } else { aps . remove ( "sound" ) ; } return this ; }
Sets the alert sound to be played .
24,796
public PayloadBuilder category ( final String category ) { if ( category != null ) { aps . put ( "category" , category ) ; } else { aps . remove ( "category" ) ; } return this ; }
Sets the category of the notification for iOS8 notification actions . See 13 minutes into What s new in iOS Notifications
24,797
public PayloadBuilder customField ( final String key , final Object value ) { root . put ( key , value ) ; return this ; }
Sets any application - specific custom fields . The values are presented to the application and the iPhone doesn t display them automatically .
24,798
public PayloadBuilder resizeAlertBody ( final int payloadLength , final String postfix ) { int currLength = length ( ) ; if ( currLength <= payloadLength ) { return this ; } String body = ( String ) customAlert . get ( "body" ) ; final int acceptableSize = Utilities . toUTF8Bytes ( body ) . length - ( currLength - payloadLength + Utilities . toUTF8Bytes ( postfix ) . length ) ; body = Utilities . truncateWhenUTF8 ( body , acceptableSize ) + postfix ; customAlert . put ( "body" , body ) ; currLength = length ( ) ; if ( currLength > payloadLength ) { customAlert . remove ( "body" ) ; } return this ; }
Shrinks the alert message body so that the resulting payload message fits within the passed expected payload length .
24,799
public String build ( ) { if ( ! root . containsKey ( "mdm" ) ) { insertCustomAlert ( ) ; root . put ( "aps" , aps ) ; } try { return mapper . writeValueAsString ( root ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } }
Returns the JSON String representation of the payload according to Apple APNS specification