idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
15,100 | public static synchronized boolean denyID ( String id ) { boolean rv = false ; if ( deniedID == null ) { deniedID = new HashMap < String , Counter > ( ) ; deniedID . put ( id , new Counter ( id ) ) ; // Noted duplicated for minimum time spent rv = true ; } else if ( deniedID . get ( id ) == null ) { deniedID . put ( id , new Counter ( id ) ) ; rv = true ; } if ( rv ) { writeID ( ) ; } return rv ; } | Return of True means ID has been added . Return of False means ID already added . | 119 | 17 |
15,101 | public static synchronized boolean removeDenyID ( String id ) { if ( deniedID != null && deniedID . remove ( id ) != null ) { writeID ( ) ; if ( deniedID . isEmpty ( ) ) { deniedID = null ; } return true ; } return false ; } | Return of True means ID has was removed . Return of False means ID wasn t being denied . | 61 | 19 |
15,102 | public AuthenticatedUser authenticate ( Map < String , String > credentials ) throws AuthenticationException { String username = ( String ) credentials . get ( "username" ) ; if ( username == null ) { throw new AuthenticationException ( "'username' is missing" ) ; } AAFAuthenticatedUser aau = new AAFAuthenticatedUser ( access , username ) ; String fullName = aau . getFullName ( ) ; access . log ( Level . DEBUG , "Authenticating" , aau . getName ( ) , "(" , fullName , ")" ) ; String password = ( String ) credentials . get ( "password" ) ; if ( password == null ) { throw new AuthenticationException ( "'password' is missing" ) ; } else if ( password . startsWith ( "bsf:" ) ) { try { password = Symm . base64noSplit . depass ( password ) ; } catch ( IOException e ) { throw new AuthenticationException ( "AAF bnf: Password cannot be decoded" ) ; } } else if ( password . startsWith ( "enc:???" ) ) { try { password = access . decrypt ( password , true ) ; } catch ( IOException e ) { throw new AuthenticationException ( "AAF Encrypted Password cannot be decrypted" ) ; } } if ( localLur != null ) { access . log ( Level . DEBUG , "Validating" , fullName , "with LocalTaf" , password ) ; if ( localLur . validate ( fullName , Type . PASSWORD , password . getBytes ( ) ) ) { aau . setAnonymous ( true ) ; aau . setLocal ( true ) ; access . log ( Level . DEBUG , fullName , "is authenticated locally" ) ; return aau ; } } String aafResponse ; try { access . log ( Level . DEBUG , "Validating" , fullName , "with AAF" ) ; //, password); aafResponse = aafAuthn . validate ( fullName , password ) ; if ( aafResponse != null ) { // Reason for failing. access . log ( Level . AUDIT , "AAF reports " , fullName , ":" , aafResponse ) ; throw new AuthenticationException ( aafResponse ) ; } access . log ( Level . AUDIT , fullName , "is authenticated" ) ; //,password); // This tells Cassandra to skip checking it's own tables for User Entries. aau . setAnonymous ( true ) ; } catch ( AuthenticationException ex ) { throw ex ; } catch ( Exception ex ) { access . log ( ex , "Exception validating user" ) ; throw new AuthenticationException ( "Exception validating user" ) ; } return aau ; } | Invoked to authenticate an user | 577 | 7 |
15,103 | public Result < List < Data > > readByUser ( AuthzTrans trans , String user , int ... yyyymm ) { if ( yyyymm . length == 0 ) { return Result . err ( Status . ERR_BadData , "No or invalid yyyymm specified" ) ; } Result < ResultSet > rs = readByUser . exec ( trans , "user" , user ) ; if ( rs . notOK ( ) ) { return Result . err ( rs ) ; } return extract ( defLoader , rs . value , null , yyyymm . length > 0 ? new YYYYMM ( yyyymm ) : dflt ) ; } | Gets the history for a user in the specified year and month year - the year in yyyy format month - the month in a year ... values 1 - 12 | 140 | 34 |
15,104 | public Result < Void > addDescription ( AuthzTrans trans , String ns , String type , String instance , String action , String description ) { //TODO Invalidate? return dao ( ) . addDescription ( trans , ns , type , instance , action , description ) ; } | Add desciption to this permission | 59 | 7 |
15,105 | public static void xmlEscape ( StringBuilder sb , Reader r ) throws ParseException { try { int c ; StringBuilder esc = new StringBuilder ( ) ; for ( int cnt = 0 ; cnt < 9 /*max*/ ; ++ cnt ) { if ( ( c = r . read ( ) ) < 0 ) throw new ParseException ( "Invalid Data: Unfinished Escape Sequence" ) ; if ( c != ' ' ) { esc . append ( ( char ) c ) ; } else { // evaluate Integer i = charMap . get ( esc . toString ( ) ) ; if ( i == null ) { // leave in nasty XML format for now. sb . append ( ' ' ) ; sb . append ( esc ) ; sb . append ( ' ' ) ; } else { sb . append ( ( char ) i . intValue ( ) ) ; } break ; } } } catch ( IOException e ) { throw new ParseException ( e ) ; } } | see initialization at end | 211 | 4 |
15,106 | private Set < Permission > checkPermissions ( AAFAuthenticatedUser aau , String type , String instance ) { // Can perform ALL actions String fullName = aau . getFullName ( ) ; PermHolder ph = new PermHolder ( aau ) ; aafLur . fishOneOf ( fullName , ph , type , instance , actions ) ; return ph . permissions ; } | Check remoted AAF Permissions | 87 | 7 |
15,107 | public static double calc ( String ... coords ) { try { String [ ] array ; switch ( coords . length ) { case 1 : array = Split . split ( ' ' , coords [ 0 ] ) ; if ( array . length != 4 ) return - 1 ; return calc ( Double . parseDouble ( array [ 0 ] ) , Double . parseDouble ( array [ 1 ] ) , Double . parseDouble ( array [ 2 ] ) , Double . parseDouble ( array [ 3 ] ) ) ; case 2 : array = Split . split ( ' ' , coords [ 0 ] ) ; String [ ] array2 = Split . split ( ' ' , coords [ 1 ] ) ; if ( array . length != 2 || array2 . length != 2 ) return - 1 ; return calc ( Double . parseDouble ( array [ 0 ] ) , Double . parseDouble ( array [ 1 ] ) , Double . parseDouble ( array2 [ 0 ] ) , Double . parseDouble ( array2 [ 1 ] ) ) ; case 4 : return calc ( Double . parseDouble ( coords [ 0 ] ) , Double . parseDouble ( coords [ 1 ] ) , Double . parseDouble ( coords [ 2 ] ) , Double . parseDouble ( coords [ 3 ] ) ) ; default : return - 1 ; } } catch ( NumberFormatException e ) { return - 1 ; } } | Convert from Lat Long Lat Long String format Lat Long Lat Long Format or all four entries Lat Long Lat Long | 290 | 22 |
15,108 | public boolean match ( Permission p ) { if ( p instanceof AAFPermission ) { AAFPermission ap = ( AAFPermission ) p ; // Note: In AAF > 1.0, Accepting "*" from name would violate multi-tenancy // Current solution is only allow direct match on Type. // 8/28/2014 - added REGEX ability if ( type . equals ( ap . getName ( ) ) ) if ( PermEval . evalInstance ( instance , ap . getInstance ( ) ) ) if ( PermEval . evalAction ( action , ap . getAction ( ) ) ) return true ; } else { // Permission is concatenated together: separated by | String [ ] aaf = p . getKey ( ) . split ( "[\\s]*\\|[\\s]*" , 3 ) ; if ( aaf . length > 0 && type . equals ( aaf [ 0 ] ) ) if ( PermEval . evalInstance ( instance , aaf . length > 1 ? aaf [ 1 ] : "*" ) ) if ( PermEval . evalAction ( action , aaf . length > 2 ? aaf [ 2 ] : "*" ) ) return true ; } return false ; } | Match a Permission if Permission is Fielded type Permission we use the fields otherwise we split the Permission with | | 272 | 25 |
15,109 | private void movePerms ( AuthzTrans trans , NsDAO . Data parent , StringBuilder sb , Result < List < PermDAO . Data > > rpdc ) { Result < Void > rv ; Result < PermDAO . Data > pd ; if ( rpdc . isOKhasData ( ) ) { for ( PermDAO . Data pdd : rpdc . value ) { String delP2 = pdd . type ; if ( "access" . equals ( delP2 ) ) { continue ; } // Remove old Perm from Roles, save them off List < RoleDAO . Data > lrdd = new ArrayList < RoleDAO . Data > ( ) ; for ( String rl : pdd . roles ( false ) ) { Result < RoleDAO . Data > rrdd = RoleDAO . Data . decode ( trans , q , rl ) ; if ( rrdd . isOKhasData ( ) ) { RoleDAO . Data rdd = rrdd . value ; lrdd . add ( rdd ) ; q . roleDAO . delPerm ( trans , rdd , pdd ) ; } else { trans . error ( ) . log ( rrdd . errorString ( ) ) ; } } // Save off Old keys String delP1 = pdd . ns ; NsSplit nss = new NsSplit ( parent , pdd . fullType ( ) ) ; pdd . ns = nss . ns ; pdd . type = nss . name ; // Use direct Create/Delete, because switching namespaces if ( ( pd = q . permDAO . create ( trans , pdd ) ) . isOK ( ) ) { // Put Role back into Perm, with correct info for ( RoleDAO . Data rdd : lrdd ) { q . roleDAO . addPerm ( trans , rdd , pdd ) ; } pdd . ns = delP1 ; pdd . type = delP2 ; if ( ( rv = q . permDAO . delete ( trans , pdd , false ) ) . notOK ( ) ) { sb . append ( rv . details ) ; sb . append ( ' ' ) ; // } else { // Need to invalidate directly, because we're switching // places in NS, not normal cache behavior // q.permDAO.invalidate(trans,pdd); } } else { sb . append ( pd . details ) ; sb . append ( ' ' ) ; } } } } | Helper function that moves permissions from a namespace being deleted to its parent namespace | 555 | 14 |
15,110 | private void moveRoles ( AuthzTrans trans , NsDAO . Data parent , StringBuilder sb , Result < List < RoleDAO . Data > > rrdc ) { Result < Void > rv ; Result < RoleDAO . Data > rd ; if ( rrdc . isOKhasData ( ) ) { for ( RoleDAO . Data rdd : rrdc . value ) { String delP2 = rdd . name ; if ( "admin" . equals ( delP2 ) || "owner" . equals ( delP2 ) ) { continue ; } // Remove old Role from Perms, save them off List < PermDAO . Data > lpdd = new ArrayList < PermDAO . Data > ( ) ; for ( String p : rdd . perms ( false ) ) { Result < PermDAO . Data > rpdd = PermDAO . Data . decode ( trans , q , p ) ; if ( rpdd . isOKhasData ( ) ) { PermDAO . Data pdd = rpdd . value ; lpdd . add ( pdd ) ; q . permDAO . delRole ( trans , pdd , rdd ) ; } else { trans . error ( ) . log ( rpdd . errorString ( ) ) ; } } // Save off Old keys String delP1 = rdd . ns ; NsSplit nss = new NsSplit ( parent , rdd . fullName ( ) ) ; rdd . ns = nss . ns ; rdd . name = nss . name ; // Use direct Create/Delete, because switching namespaces if ( ( rd = q . roleDAO . create ( trans , rdd ) ) . isOK ( ) ) { // Put Role back into Perm, with correct info for ( PermDAO . Data pdd : lpdd ) { q . permDAO . addRole ( trans , pdd , rdd ) ; } rdd . ns = delP1 ; rdd . name = delP2 ; if ( ( rv = q . roleDAO . delete ( trans , rdd , true ) ) . notOK ( ) ) { sb . append ( rv . details ) ; sb . append ( ' ' ) ; // } else { // Need to invalidate directly, because we're switching // places in NS, not normal cache behavior // q.roleDAO.invalidate(trans,rdd); } } else { sb . append ( rd . details ) ; sb . append ( ' ' ) ; } } } } | Helper function that moves roles from a namespace being deleted to its parent namespace | 565 | 14 |
15,111 | public Result < Void > addUserRole ( AuthzTrans trans , UserRoleDAO . Data urData ) { Result < Void > rv ; if ( Question . ADMIN . equals ( urData . rname ) ) { rv = mayAddAdmin ( trans , urData . ns , urData . user ) ; } else if ( Question . OWNER . equals ( urData . rname ) ) { rv = mayAddOwner ( trans , urData . ns , urData . user ) ; } else { rv = checkValidID ( trans , new Date ( ) , urData . user ) ; } if ( rv . notOK ( ) ) { return rv ; } // Check if record exists if ( q . userRoleDAO . read ( trans , urData ) . isOKhasData ( ) ) { return Result . err ( Status . ERR_ConflictAlreadyExists , "User Role exists" ) ; } if ( q . roleDAO . read ( trans , urData . ns , urData . rname ) . notOKorIsEmpty ( ) ) { return Result . err ( Status . ERR_RoleNotFound , "Role [%s.%s] does not exist" , urData . ns , urData . rname ) ; } urData . expires = trans . org ( ) . expiration ( null , Expiration . UserInRole , urData . user ) . getTime ( ) ; Result < UserRoleDAO . Data > udr = q . userRoleDAO . create ( trans , urData ) ; switch ( udr . status ) { case OK : return Result . ok ( ) ; default : return Result . err ( udr ) ; } } | Add a User to Role | 366 | 5 |
15,112 | public Result < Void > extendUserRole ( AuthzTrans trans , UserRoleDAO . Data urData , boolean checkForExist ) { // Check if record still exists if ( checkForExist && q . userRoleDAO . read ( trans , urData ) . notOKorIsEmpty ( ) ) { return Result . err ( Status . ERR_UserRoleNotFound , "User Role does not exist" ) ; } if ( q . roleDAO . read ( trans , urData . ns , urData . rname ) . notOKorIsEmpty ( ) ) { return Result . err ( Status . ERR_RoleNotFound , "Role [%s.%s] does not exist" , urData . ns , urData . rname ) ; } // Special case for "Admin" roles. Issue brought forward with Prod // problem 9/26 urData . expires = trans . org ( ) . expiration ( null , Expiration . UserInRole ) . getTime ( ) ; // get // Full // time // starting // today return q . userRoleDAO . update ( trans , urData ) ; } | Extend User Role . | 241 | 5 |
15,113 | public Lur get ( int idx ) { if ( idx >= 0 && idx < lurs . length ) { return lurs [ idx ] ; } return null ; } | Get Lur for index . Returns null if out of range | 38 | 11 |
15,114 | public boolean fish ( String bait , Permission pond ) { if ( isDebug ( bait ) ) { boolean rv = false ; StringBuilder sb = new StringBuilder ( "Log for " ) ; sb . append ( bait ) ; if ( supports ( bait ) ) { User < PERM > user = getUser ( bait ) ; if ( user == null ) { sb . append ( "\n\tUser is not in Cache" ) ; } else { if ( user . noPerms ( ) ) sb . append ( "\n\tUser has no Perms" ) ; if ( user . permExpired ( ) ) { sb . append ( "\n\tUser's perm expired [" ) ; sb . append ( new Date ( user . permExpires ( ) ) ) ; sb . append ( ' ' ) ; } else { sb . append ( "\n\tUser's perm expires [" ) ; sb . append ( new Date ( user . permExpires ( ) ) ) ; sb . append ( ' ' ) ; } } if ( user == null || ( user . noPerms ( ) && user . permExpired ( ) ) ) { user = loadUser ( bait ) ; sb . append ( "\n\tloadUser called" ) ; } if ( user == null ) { sb . append ( "\n\tUser was not Loaded" ) ; } else if ( user . contains ( pond ) ) { sb . append ( "\n\tUser contains " ) ; sb . append ( pond . getKey ( ) ) ; rv = true ; } else { sb . append ( "\n\tUser does not contain " ) ; sb . append ( pond . getKey ( ) ) ; List < Permission > perms = new ArrayList < Permission > ( ) ; user . copyPermsTo ( perms ) ; for ( Permission p : perms ) { sb . append ( "\n\t\t" ) ; sb . append ( p . getKey ( ) ) ; } } } else { sb . append ( "AAF Lur does not support [" ) ; sb . append ( bait ) ; sb . append ( "]" ) ; } aaf . access . log ( Level . INFO , sb ) ; return rv ; } else { if ( supports ( bait ) ) { User < PERM > user = getUser ( bait ) ; if ( user == null || ( user . noPerms ( ) && user . permExpired ( ) ) ) { user = loadUser ( bait ) ; } return user == null ? false : user . contains ( pond ) ; } return false ; } } | This is where you build AAF CLient Code . Answer the question Is principal bait in the pond | 575 | 20 |
15,115 | public < A > void fishOneOf ( String bait , A obj , String type , String instance , List < Action < A > > actions ) { User < PERM > user = getUser ( bait ) ; if ( user == null || ( user . noPerms ( ) && user . permExpired ( ) ) ) user = loadUser ( bait ) ; // return user==null?false:user.contains(pond); if ( user != null ) { ReuseAAFPermission perm = new ReuseAAFPermission ( type , instance ) ; for ( Action < A > action : actions ) { perm . setAction ( action . getName ( ) ) ; if ( user . contains ( perm ) ) { if ( action . exec ( obj ) ) return ; } } } } | This special case minimizes loops avoids multiple Set hits and calls all the appropriate Actions found . | 169 | 18 |
15,116 | public int cacheIdx ( String key ) { int h = 0 ; for ( int i = 0 ; i < key . length ( ) ; i ++ ) { h = 31 * h + key . charAt ( i ) ; } if ( h < 0 ) h *= - 1 ; return h % segSize ; } | Taken from String Hash but coded to ensure consistent across Java versions . Also covers negative case ; | 69 | 19 |
15,117 | public static void startCleansing ( AuthzEnv env , CachedDAO < ? , ? , ? > ... dao ) { for ( CachedDAO < ? , ? , ? > d : dao ) { for ( int i = 0 ; i < d . segSize ; ++ i ) { startCleansing ( env , d . table ( ) + i ) ; } } } | Each Cached object has multiple Segments that need cleaning . Derive each and add to Cleansing Thread | 87 | 22 |
15,118 | public Result < FutureDAO . Data > create ( AuthzTrans trans , FutureDAO . Data data , String id ) { // If ID is not set (typical), create one. if ( data . id == null ) { StringBuilder sb = new StringBuilder ( trans . user ( ) ) ; sb . append ( data . target ) ; sb . append ( System . currentTimeMillis ( ) ) ; data . id = UUID . nameUUIDFromBytes ( sb . toString ( ) . getBytes ( ) ) ; } Result < ResultSet > rs = createPS . exec ( trans , C_TEXT , data ) ; if ( rs . notOK ( ) ) { return Result . err ( rs ) ; } wasModified ( trans , CRUD . create , data , null , id ) ; return Result . ok ( data ) ; } | Override create to add secondary ID to Subject in History and create Data . ID if it is null | 185 | 19 |
15,119 | public static Schema genSchema ( Store env , String ... filenames ) throws APIException { String schemaDir = env . get ( env . staticSlot ( EnvFactory . SCHEMA_DIR ) , EnvFactory . DEFAULT_SCHEMA_DIR ) ; File dir = new File ( schemaDir ) ; if ( ! dir . exists ( ) ) throw new APIException ( "Schema Directory " + schemaDir + " does not exist. You can set this with " + EnvFactory . SCHEMA_DIR + " property" ) ; FileInputStream [ ] fis = new FileInputStream [ filenames . length ] ; Source [ ] sources = new Source [ filenames . length ] ; File f ; for ( int i = 0 ; i < filenames . length ; ++ i ) { if ( ! ( f = new File ( schemaDir + File . separatorChar + filenames [ i ] ) ) . exists ( ) ) { if ( ! f . exists ( ) ) throw new APIException ( "Cannot find " + f . getName ( ) + " for schema validation" ) ; } try { fis [ i ] = new FileInputStream ( f ) ; } catch ( FileNotFoundException e ) { throw new APIException ( e ) ; } sources [ i ] = new StreamSource ( fis [ i ] ) ; } try { //Note: SchemaFactory is not reentrant or very thread safe either... see docs synchronized ( XMLConstants . W3C_XML_SCHEMA_NS_URI ) { // SchemaFactory is not reentrant return SchemaFactory . newInstance ( XMLConstants . W3C_XML_SCHEMA_NS_URI ) . newSchema ( sources ) ; } } catch ( SAXException e ) { throw new APIException ( e ) ; } finally { for ( FileInputStream d : fis ) { try { d . close ( ) ; } catch ( IOException e ) { // Never mind... we did our best } } } } | Generate a Schema Object for use in validation based on FileNames . | 440 | 15 |
15,120 | public int read ( byte [ ] array , int offset , int length ) { if ( curr == null ) return - 1 ; int len ; int count = 0 ; while ( length > 0 ) { // loop through while there's data needed if ( ( len = curr . remaining ( ) ) > length ) { // if enough data in curr buffer, use this code curr . get ( array , offset , length ) ; count += length ; length = 0 ; } else { // get data from curr, mark how much is needed to fulfil, and loop for next curr. curr . get ( array , offset , len ) ; count += len ; offset += len ; length -= len ; if ( idx < bbs . size ( ) ) { curr = bbs . get ( idx ++ ) ; } else { length = 0 ; // stop, and return the count of how many we were able to load } } } return count ; } | read into an array like Streams | 202 | 7 |
15,121 | public void put ( byte [ ] array , int offset , int length ) { if ( curr == null || curr . remaining ( ) == 0 ) { curr = ringGet ( ) ; bbs . add ( curr ) ; } int len ; while ( length > 0 ) { if ( ( len = curr . remaining ( ) ) > length ) { curr . put ( array , offset , length ) ; length = 0 ; } else { // System.out.println(new String(array)); curr . put ( array , offset , len ) ; length -= len ; offset += len ; curr = ringGet ( ) ; bbs . add ( curr ) ; } } } | Put an array of data into Capacitor | 148 | 9 |
15,122 | public void setForRead ( ) { for ( ByteBuffer bb : bbs ) { bb . flip ( ) ; } if ( bbs . isEmpty ( ) ) { curr = null ; idx = 0 ; } else { curr = bbs . get ( 0 ) ; idx = 1 ; } } | Move state from Storage mode into Read mode changing all internal buffers to read mode etc | 69 | 16 |
15,123 | public void done ( ) { for ( ByteBuffer bb : bbs ) { ringPut ( bb ) ; } bbs . clear ( ) ; curr = null ; } | reuse all the buffers | 38 | 5 |
15,124 | public long skip ( long n ) { long skipped = 0L ; int skip ; while ( n > 0 ) { if ( n < ( skip = curr . remaining ( ) ) ) { curr . position ( curr . position ( ) + ( int ) n ) ; skipped += skip ; n = 0 ; } else { curr . position ( curr . limit ( ) ) ; skipped -= skip ; if ( idx < bbs . size ( ) ) { curr = bbs . get ( idx ++ ) ; n -= skip ; } else { n = 0 ; } } } return skipped ; } | Returns how many are left that were not skipped | 130 | 9 |
15,125 | public void reset ( ) { for ( ByteBuffer bb : bbs ) { bb . position ( 0 ) ; } if ( bbs . isEmpty ( ) ) { curr = null ; idx = 0 ; } else { curr = bbs . get ( 0 ) ; idx = 1 ; } } | Be able to re - read data that is stored that has already been re - read . This is not a standard Stream behavior but can be useful in a standalone mode . | 68 | 34 |
15,126 | public String pathParam ( HttpServletRequest req , String key ) { return match . param ( req . getPathInfo ( ) , key ) ; } | Get the variable element out of the Path Parameter as set by initial Code | 33 | 15 |
15,127 | public boolean isAuthorized ( HttpServletRequest req ) { if ( all ) return true ; if ( roles != null ) { for ( String srole : roles ) { if ( req . isUserInRole ( srole ) ) return true ; } } return false ; } | Check for Authorization when set . | 59 | 6 |
15,128 | public void destroy ( ) { // Synchronize, in case multiCadiFilters are used. synchronized ( CadiHTTPManip . noAdditional ) { if ( -- count <= 0 && httpChecker != null ) { httpChecker . destroy ( ) ; httpChecker = null ; access = null ; pathExceptions = null ; } } } | Containers call destroy when time to cleanup | 74 | 8 |
15,129 | private boolean noAuthn ( HttpServletRequest hreq ) { if ( pathExceptions != null ) { String pi = hreq . getPathInfo ( ) ; if ( pi == null ) return false ; // JBoss sometimes leaves null for ( String pe : pathExceptions ) { if ( pi . startsWith ( pe ) ) return true ; } } return false ; } | If PathExceptions exist report if these should not have Authn applied . | 80 | 15 |
15,130 | private PermConverter getConverter ( HttpServletRequest hreq ) { if ( mapPairs != null ) { String pi = hreq . getPathInfo ( ) ; if ( pi != null ) { for ( Pair p : mapPairs ) { if ( pi . startsWith ( p . name ) ) return p . pc ; } } } return NullPermConverter . singleton ( ) ; } | Get Converter by Path | 92 | 5 |
15,131 | synchronized Route < TRANS > findOrCreate ( HttpMethods meth , String path ) { Route < TRANS > rv = null ; for ( int i = 0 ; i < end ; ++ i ) { if ( routes [ i ] . resolvesTo ( meth , path ) ) rv = routes [ i ] ; } if ( rv == null ) { if ( end >= routes . length ) { @ SuppressWarnings ( "unchecked" ) Route < TRANS > [ ] temp = new Route [ end + 10 ] ; System . arraycopy ( routes , 0 , temp , 0 , routes . length ) ; routes = temp ; } routes [ end ++ ] = rv = new Route < TRANS > ( meth , path ) ; } return rv ; } | Package on purpose | 162 | 3 |
15,132 | public Result < List < CertDAO . Data > > readID ( AuthzTrans trans , final String id ) { return dao ( ) . readID ( trans , id ) ; } | Pass through Cert ID Lookup | 40 | 6 |
15,133 | public void run ( Cache < G > cache , Code < G > code ) throws APIException , IOException { code . code ( cache , xgen ) ; } | Normal case of building up Cached HTML without transaction info | 34 | 11 |
15,134 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public void run ( State < Env > state , Trans trans , Cache cache , DynamicCode code ) throws APIException , IOException { code . code ( state , trans , cache , xgen ) ; } | Special Case where code is dynamic so give access to State and Trans info | 62 | 14 |
15,135 | public void code ( Cache < G > cache , G xgen ) throws APIException , IOException { code ( null , null , cache , xgen ) ; } | We expect not to have this section of the code engaged at any time | 34 | 14 |
15,136 | public static BROWSER browser ( AuthzTrans trans , Slot slot ) { BROWSER br = trans . get ( slot , null ) ; if ( br == null ) { String agent = trans . agent ( ) ; int msie ; if ( agent . contains ( "iPhone" ) /* other phones? */ ) { br = BROWSER . iPhone ; } else if ( ( msie = agent . indexOf ( "MSIE" ) ) >= 0 ) { msie += 5 ; int end = agent . indexOf ( ";" , msie ) ; float ver ; try { ver = Float . valueOf ( agent . substring ( msie , end ) ) ; br = ver < 8f ? BROWSER . ieOld : BROWSER . ie ; } catch ( Exception e ) { br = BROWSER . ie ; } } else { br = BROWSER . html5 ; } trans . put ( slot , br ) ; } return br ; } | It s IE if int > = 0 | 205 | 8 |
15,137 | public void processJobChangeDataFile ( String fileName , String falloutFileName , Date validDate ) throws Exception { BufferedWriter writer = null ; try { env . info ( ) . log ( "Reading file: " + fileName ) ; FileInputStream fstream = new FileInputStream ( fileName ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( fstream ) ) ; String strLine ; while ( ( strLine = br . readLine ( ) ) != null ) { processLine ( strLine , writer ) ; } br . close ( ) ; } catch ( IOException e ) { env . error ( ) . log ( "Error while reading from the input data file: " + e ) ; throw e ; } } | Processes the specified JobChange data file obtained from Webphone . Each line is read and processed and any fallout is written to the specified fallout file . If fallout file already exists it is deleted and a new one is created . A comparison of the supervisor id in the job data file is done against the one returned by the authz service and if the supervisor Id has changed then the record is updated using the authz service . An email is sent to the new supervisor to approve the roles assigned to the user . | 159 | 102 |
15,138 | public Result < Void > addDescription ( AuthzTrans trans , String ns , String type , String instance , String action , String description ) { try { getSession ( trans ) . execute ( UPDATE_SP + TABLE + " SET description = '" + description + "' WHERE ns = '" + ns + "' AND type = '" + type + "'" + "AND instance = '" + instance + "' AND action = '" + action + "';" ) ; } catch ( DriverException | APIException | IOException e ) { reportPerhapsReset ( trans , e ) ; return Result . err ( Result . ERR_Backend , CassAccess . ERR_ACCESS_MSG ) ; } Data data = new Data ( ) ; data . ns = ns ; data . type = type ; data . instance = instance ; data . action = action ; wasModified ( trans , CRUD . update , data , "Added description " + description + " to permission " + data . encode ( ) , null ) ; return Result . ok ( ) ; } | Add description to this permission | 223 | 5 |
15,139 | @ Override public List < Identity > getApprovers ( AuthzTrans trans , String user ) throws OrganizationException { Identity orgIdentity = getIdentity ( trans , user ) ; List < Identity > orgIdentitys = new ArrayList < Identity > ( ) ; if ( orgIdentity != null ) { String supervisorID = orgIdentity . responsibleTo ( ) ; if ( supervisorID . indexOf ( ' ' ) < 0 ) { supervisorID += getDomain ( ) ; } Identity supervisor = getIdentity ( trans , supervisorID ) ; orgIdentitys . add ( supervisor ) ; } return orgIdentitys ; } | Assume the Supervisor is the Approver . | 133 | 9 |
15,140 | private Address [ ] getAddresses ( List < String > strAddresses , String delimiter ) throws OrganizationException { Address [ ] addressArray = new Address [ strAddresses . size ( ) ] ; int count = 0 ; for ( String addr : strAddresses ) { try { addressArray [ count ] = new InternetAddress ( addr ) ; count ++ ; } catch ( Exception e ) { throw new OrganizationException ( "Failed to parse the email address " + addr + ": " + e . getMessage ( ) ) ; } } return addressArray ; } | Convert the delimiter String into Internet addresses with the delimiter of provided | 118 | 15 |
15,141 | public TypedCode < TRANS > add ( HttpCode < TRANS , ? > code , String ... others ) { StringBuilder sb = new StringBuilder ( ) ; boolean first = true ; for ( String str : others ) { if ( first ) { first = false ; } else { sb . append ( ' ' ) ; } sb . append ( str ) ; } parse ( code , sb . toString ( ) ) ; return this ; } | Construct Typed Code based on ContentType parameters passed in | 96 | 11 |
15,142 | public StringBuilder relatedTo ( HttpCode < TRANS , ? > code , StringBuilder sb ) { boolean first = true ; for ( Pair < String , Pair < HttpCode < TRANS , ? > , List < Pair < String , Object > > > > pair : types ) { if ( code == null || pair . y . x == code ) { if ( first ) { first = false ; } else { sb . append ( ' ' ) ; } sb . append ( pair . x ) ; for ( Pair < String , Object > prop : pair . y . y ) { // Don't print "Q". it's there for internal use, but it is only meaningful for "Accepts" if ( ! prop . x . equals ( Q ) || ! prop . y . equals ( 1f ) ) { sb . append ( ' ' ) ; sb . append ( prop . x ) ; sb . append ( ' ' ) ; sb . append ( prop . y ) ; } } } } return sb ; } | Print on String Builder content related to specific Code | 219 | 9 |
15,143 | public Result < List < CredDAO . Data > > readNS ( AuthzTrans trans , final String ns ) { return dao ( ) . readNS ( trans , ns ) ; } | Pass through Cred Lookup | 41 | 6 |
15,144 | public Result < Void > addDescription ( AuthzTrans trans , String ns , String name , String description ) { //TODO Invalidate? return dao ( ) . addDescription ( trans , ns , name , description ) ; } | Add description to this role | 49 | 5 |
15,145 | public static String domain2ns ( String id ) { int at = id . indexOf ( ' ' ) ; if ( at >= 0 ) { String [ ] domain = id . substring ( at + 1 ) . split ( "\\." ) ; StringBuilder ns = new StringBuilder ( id . length ( ) ) ; boolean first = true ; for ( int i = domain . length - 1 ; i >= 0 ; -- i ) { if ( first ) { first = false ; } else { ns . append ( ' ' ) ; } ns . append ( domain [ i ] ) ; } return ns . toString ( ) ; } else { return "" ; } } | Translate an ID into it s domain | 139 | 8 |
15,146 | public boolean canMove ( NsType nsType ) { boolean rv ; switch ( nsType ) { case DOT : case ROOT : case COMPANY : case UNKNOWN : rv = false ; break ; default : rv = true ; } return rv ; } | canMove Which Types can be moved | 57 | 7 |
15,147 | public String validate ( String user , String password ) throws IOException , CadiException { User < AAFPermission > usr = getUser ( user ) ; if ( password . startsWith ( "enc:???" ) ) { password = access . decrypt ( password , true ) ; } byte [ ] bytes = password . getBytes ( ) ; if ( usr != null && usr . principal != null && usr . principal . getName ( ) . equals ( user ) && usr . principal instanceof GetCred ) { if ( Hash . isEqual ( ( ( GetCred ) usr . principal ) . getCred ( ) , bytes ) ) { return null ; } else { remove ( usr ) ; usr = null ; } } AAFCachedPrincipal cp = new AAFCachedPrincipal ( this , con . app , user , bytes , con . cleanInterval ) ; // Since I've relocated the Validation piece in the Principal, just revalidate, then do Switch // Statement switch ( cp . revalidate ( ) ) { case REVALIDATED : if ( usr != null ) { usr . principal = cp ; } else { addUser ( new User < AAFPermission > ( cp , con . timeout ) ) ; } return null ; case INACCESSIBLE : return "AAF Inaccessible" ; case UNVALIDATED : return "User/Pass combo invalid for " + user ; case DENIED : return "AAF denies API for " + user ; default : return "AAFAuthn doesn't handle Principal " + user ; } } | Returns null if ok or an Error String ; | 338 | 9 |
15,148 | public static String convert ( final String text , final List < String > vars ) { String [ ] array = new String [ vars . size ( ) ] ; StringBuilder sb = new StringBuilder ( ) ; convert ( sb , text , vars . toArray ( array ) ) ; return sb . toString ( ) ; } | Simplified Conversion based on typical use of getting AT&T style RESTful Error Messages | 72 | 18 |
15,149 | public static < R > Result < R > ok ( R value ) { return new Result < R > ( value , OK , SUCCESS , null ) ; } | Create a Result class with OK status and Success for details | 34 | 11 |
15,150 | public static < R > Result < R [ ] > ok ( R value [ ] ) { return new Result < R [ ] > ( value , OK , SUCCESS , null ) . emptyList ( value . length == 0 ) ; } | Accept Arrays and mark as empty or not | 50 | 9 |
15,151 | public static < R > Result < List < R > > ok ( List < R > value ) { return new Result < List < R > > ( value , OK , SUCCESS , null ) . emptyList ( value . size ( ) == 0 ) ; } | Accept Lists and mark as empty or not | 55 | 8 |
15,152 | public static < R > Result < R > err ( int status , String details , String ... variables ) { return new Result < R > ( null , status , details , variables ) ; } | Create a Status ( usually non OK with a details statement and variables supported | 39 | 14 |
15,153 | public static < R > Result < R > err ( Exception e ) { return new Result < R > ( null , ERR_General , e . getMessage ( ) , EMPTY_VARS ) ; } | Create General Error from Exception | 44 | 5 |
15,154 | public static < R > Result < R > create ( R value , int status , String details , String ... vars ) { return new Result < R > ( value , status , details , vars ) ; } | Create a Status ( usually non OK with a details statement | 44 | 11 |
15,155 | public RosettaDF < T > out ( Data . TYPE type ) { outType = type ; defaultOut = getOut ( type == Data . TYPE . DEFAULT ? Data . TYPE . JSON : type ) ; return this ; } | If exists first option is Pretty second is Fragment | 48 | 10 |
15,156 | public RosettaDF < T > rootMarshal ( Marshal < T > marshal ) { if ( marshal instanceof DocMarshal ) { this . marshal = marshal ; } else { this . marshal = DocMarshal . root ( marshal ) ; } return this ; } | Assigning Root Marshal Object | 61 | 5 |
15,157 | public String encode ( String str ) throws IOException { byte [ ] array ; try { array = str . getBytes ( encoding ) ; } catch ( IOException e ) { array = str . getBytes ( ) ; // take default } // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code ByteArrayOutputStream baos = new ByteArrayOutputStream ( ( int ) ( array . length * 1.363 ) ) ; // account for 4 bytes for 3 and a byte or two more encode ( new ByteArrayInputStream ( array ) , baos ) ; return baos . toString ( encoding ) ; } | Helper function for String API of Encode use getBytes with appropriate char encoding etc . | 132 | 17 |
15,158 | public void encode ( InputStream is , OutputStream os ) throws IOException { // StringBuilder sb = new StringBuilder((int)(estimate*1.255)); // try to get the right size of StringBuilder from start.. slightly more than 1.25 times int prev = 0 ; int read , idx = 0 , line = 0 ; boolean go ; do { read = is . read ( ) ; if ( go = read >= 0 ) { if ( line >= splitLinesAt ) { os . write ( ' ' ) ; line = 0 ; } switch ( ++ idx ) { // 1 based reading, slightly faster ++ case 1 : // ptr is the first 6 bits of read os . write ( codeset [ read >> 2 ] ) ; prev = read ; break ; case 2 : // ptr is the last 2 bits of prev followed by the first 4 bits of read os . write ( codeset [ ( ( prev & 0x03 ) << 4 ) | ( read >> 4 ) ] ) ; prev = read ; break ; default : //(3+) // Char 1 is last 4 bits of prev plus the first 2 bits of read // Char 2 is the last 6 bits of read os . write ( codeset [ ( ( ( prev & 0xF ) << 2 ) | ( read >> 6 ) ) ] ) ; if ( line == splitLinesAt ) { // deal with line splitting for two characters os . write ( ' ' ) ; line = 0 ; } os . write ( codeset [ ( read & 0x3F ) ] ) ; ++ line ; idx = 0 ; prev = 0 ; } ++ line ; } else { // deal with any remaining bits from Prev, then pad switch ( idx ) { case 1 : // just the last 2 bits of prev os . write ( codeset [ ( prev & 0x03 ) << 4 ] ) ; if ( endEquals ) os . write ( DOUBLE_EQ ) ; break ; case 2 : // just the last 4 bits of prev os . write ( codeset [ ( prev & 0xF ) << 2 ] ) ; if ( endEquals ) os . write ( ' ' ) ; break ; } idx = 0 ; } } while ( go ) ; } | encode InputStream onto Output Stream | 472 | 7 |
15,159 | public void decode ( InputStream is , OutputStream os ) throws IOException { int read , idx = 0 ; int prev = 0 , index ; while ( ( read = is . read ( ) ) >= 0 ) { index = convert . convert ( read ) ; if ( index >= 0 ) { switch ( ++ idx ) { // 1 based cases, slightly faster ++ case 1 : // index goes into first 6 bits of prev prev = index << 2 ; break ; case 2 : // write second 2 bits of into prev, write byte, last 4 bits go into prev os . write ( ( byte ) ( prev | ( index >> 4 ) ) ) ; prev = index << 4 ; break ; case 3 : // first 4 bits of index goes into prev, write byte, last 2 bits go into prev os . write ( ( byte ) ( prev | ( index >> 2 ) ) ) ; prev = index << 6 ; break ; default : // (3+) | prev and last six of index os . write ( ( byte ) ( prev | ( index & 0x3F ) ) ) ; idx = prev = 0 ; } } } ; os . flush ( ) ; } | Decode InputStream onto OutputStream | 244 | 7 |
15,160 | public byte [ ] keygen ( ) throws IOException { byte inkey [ ] = new byte [ 0x600 ] ; new SecureRandom ( ) . nextBytes ( inkey ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( 0x800 ) ; base64url . encode ( new ByteArrayInputStream ( inkey ) , baos ) ; return baos . toByteArray ( ) ; } | Generate a 2048 based Key from which we extract our code base | 88 | 13 |
15,161 | public static Symm obtain ( InputStream is ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; try { base64url . decode ( is , baos ) ; } catch ( IOException e ) { // don't give clue throw new IOException ( "Invalid Key" ) ; } byte [ ] bkey = baos . toByteArray ( ) ; if ( bkey . length < 0x88 ) { // 2048 bit key throw new IOException ( "Invalid key" ) ; } return baseCrypt ( ) . obtain ( bkey ) ; } | Obtain a Symm from 2048 key from a Stream | 124 | 11 |
15,162 | public static Symm obtain ( File f ) throws IOException { FileInputStream fis = new FileInputStream ( f ) ; try { return obtain ( fis ) ; } finally { fis . close ( ) ; } } | Convenience for picking up Keyfile | 48 | 8 |
15,163 | public String enpass ( String password ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; enpass ( password , baos ) ; return new String ( baos . toByteArray ( ) ) ; } | Decrypt into a String | 51 | 5 |
15,164 | public void enpass ( final String password , final OutputStream os ) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; DataOutputStream dos = new DataOutputStream ( baos ) ; byte [ ] bytes = password . getBytes ( ) ; if ( this . getClass ( ) . getSimpleName ( ) . startsWith ( "base64" ) ) { // don't expose randomization dos . write ( bytes ) ; } else { Random r = new SecureRandom ( ) ; int start = 0 ; byte b ; for ( int i = 0 ; i < 3 ; ++ i ) { dos . writeByte ( b = ( byte ) r . nextInt ( ) ) ; start += Math . abs ( b ) ; } start %= 0x7 ; for ( int i = 0 ; i < start ; ++ i ) { dos . writeByte ( r . nextInt ( ) ) ; } dos . writeInt ( ( int ) System . currentTimeMillis ( ) ) ; int minlength = Math . min ( 0x9 , bytes . length ) ; dos . writeByte ( minlength ) ; // expect truncation if ( bytes . length < 0x9 ) { for ( int i = 0 ; i < bytes . length ; ++ i ) { dos . writeByte ( r . nextInt ( ) ) ; dos . writeByte ( bytes [ i ] ) ; } // make sure it's long enough for ( int i = bytes . length ; i < 0x9 ; ++ i ) { dos . writeByte ( r . nextInt ( ) ) ; } } else { dos . write ( bytes ) ; } } // 7/21/2016 jg add AES Encryption to the mix exec ( new AESExec ( ) { @ Override public void exec ( AES aes ) throws IOException { CipherInputStream cis = aes . inputStream ( new ByteArrayInputStream ( baos . toByteArray ( ) ) , true ) ; try { encode ( cis , os ) ; } finally { os . flush ( ) ; cis . close ( ) ; } } } ) ; synchronized ( ENC ) { } } | Create an encrypted password making sure that even short passwords have a minimum length . | 455 | 15 |
15,165 | public String depass ( String password ) throws IOException { if ( password == null ) return null ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; depass ( password , baos ) ; return new String ( baos . toByteArray ( ) ) ; } | Decrypt a password into a String | 60 | 7 |
15,166 | public long depass ( final String password , final OutputStream os ) throws IOException { int offset = password . startsWith ( ENC ) ? 4 : 0 ; final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; final ByteArrayInputStream bais = new ByteArrayInputStream ( password . getBytes ( ) , offset , password . length ( ) - offset ) ; exec ( new AESExec ( ) { @ Override public void exec ( AES aes ) throws IOException { CipherOutputStream cos = aes . outputStream ( baos , false ) ; decode ( bais , cos ) ; cos . close ( ) ; // flush } } ) ; byte [ ] bytes = baos . toByteArray ( ) ; DataInputStream dis = new DataInputStream ( new ByteArrayInputStream ( bytes ) ) ; long time ; if ( this . getClass ( ) . getSimpleName ( ) . startsWith ( "base64" ) ) { // don't expose randomization os . write ( bytes ) ; time = 0L ; } else { int start = 0 ; for ( int i = 0 ; i < 3 ; ++ i ) { start += Math . abs ( dis . readByte ( ) ) ; } start %= 0x7 ; for ( int i = 0 ; i < start ; ++ i ) { dis . readByte ( ) ; } time = ( dis . readInt ( ) & 0xFFFF ) | ( System . currentTimeMillis ( ) & 0xFFFF0000 ) ; int minlength = dis . readByte ( ) ; if ( minlength < 0x9 ) { DataOutputStream dos = new DataOutputStream ( os ) ; for ( int i = 0 ; i < minlength ; ++ i ) { dis . readByte ( ) ; dos . writeByte ( dis . readByte ( ) ) ; } } else { int pre = ( ( Byte . SIZE * 3 + Integer . SIZE + Byte . SIZE ) / Byte . SIZE ) + start ; os . write ( bytes , pre , bytes . length - pre ) ; } } return time ; } | Decrypt a password | 447 | 4 |
15,167 | public Symm obtain ( byte [ ] key ) throws IOException { try { byte [ ] bytes = new byte [ AES . AES_KEY_SIZE / 8 ] ; int offset = ( Math . abs ( key [ ( 47 % key . length ) ] ) + 137 ) % ( key . length - bytes . length ) ; for ( int i = 0 ; i < bytes . length ; ++ i ) { bytes [ i ] = key [ i + offset ] ; } aes = new AES ( bytes , 0 , bytes . length ) ; } catch ( Exception e ) { throw new IOException ( e ) ; } int filled = codeset . length ; char [ ] seq = new char [ filled ] ; int end = filled -- ; boolean right = true ; int index ; Obtain o = new Obtain ( this , key ) ; while ( filled >= 0 ) { index = o . next ( ) ; if ( index < 0 || index >= codeset . length ) { System . out . println ( "uh, oh" ) ; } if ( right ) { // alternate going left or right to find the next open slot (keeps it from taking too long to hit something) for ( int j = index ; j < end ; ++ j ) { if ( seq [ j ] == 0 ) { seq [ j ] = codeset [ filled ] ; -- filled ; break ; } } right = false ; } else { for ( int j = index ; j >= 0 ; -- j ) { if ( seq [ j ] == 0 ) { seq [ j ] = codeset [ filled ] ; -- filled ; break ; } } right = true ; } } return new Symm ( seq , this ) ; } | quick recreation when the official stream is actually obtained . | 357 | 10 |
15,168 | private boolean nob ( String str , Pattern p ) { return str == null || ! p . matcher ( str ) . matches ( ) ; } | nob = Null Or Not match Pattern | 30 | 7 |
15,169 | public static void start ( RestClient client , String root , boolean merge , boolean force ) throws Exception { logger . info ( "starting automatic settings/mappings discovery" ) ; // create templates List < String > templateNames = TemplateFinder . findTemplates ( root ) ; for ( String templateName : templateNames ) { createTemplate ( client , root , templateName , force ) ; } // create indices Collection < String > indexNames = IndexFinder . findIndexNames ( root ) ; for ( String indexName : indexNames ) { createIndex ( client , root , indexName , force ) ; updateSettings ( client , root , indexName ) ; } logger . info ( "start done. Rock & roll!" ) ; } | Automatically scan classpath and create indices mappings templates and other settings . | 152 | 15 |
15,170 | public static List < String > findIndexNames ( final String root ) throws IOException , URISyntaxException { if ( root == null ) { return findIndexNames ( ) ; } logger . debug ( "Looking for indices in classpath under [{}]." , root ) ; final List < String > indexNames = new ArrayList <> ( ) ; final Set < String > keys = new HashSet <> ( ) ; String [ ] resources = ResourceList . getResources ( root + "/" ) ; // "es/" or "a/b/c/" for ( String resource : resources ) { if ( ! resource . isEmpty ( ) ) { logger . trace ( " - resource [{}]." , resource ) ; String key ; if ( resource . contains ( "/" ) ) { key = resource . substring ( 0 , resource . indexOf ( "/" ) ) ; } else { key = resource ; } if ( ! key . equals ( Defaults . TemplateDir ) && ! keys . contains ( key ) ) { logger . trace ( " - found [{}]." , key ) ; keys . add ( key ) ; indexNames . add ( key ) ; } } } return indexNames ; } | Find all indices existing in a given classpath dir | 255 | 10 |
15,171 | public static String readTemplate ( String root , String template ) throws IOException { if ( root == null ) { return readTemplate ( template ) ; } String settingsFile = root + "/" + Defaults . TemplateDir + "/" + template + Defaults . JsonFileExtension ; return readFileFromClasspath ( settingsFile ) ; } | Read a template | 72 | 3 |
15,172 | @ Deprecated public static void createTemplate ( Client client , String root , String template , boolean force ) throws Exception { String json = TemplateSettingsReader . readTemplate ( root , template ) ; createTemplateWithJson ( client , template , json , force ) ; } | Create a template in Elasticsearch . | 55 | 7 |
15,173 | public static void createTemplate ( RestClient client , String template , boolean force ) throws Exception { String json = TemplateSettingsReader . readTemplate ( template ) ; createTemplateWithJson ( client , template , json , force ) ; } | Create a template in Elasticsearch . Read read content from default classpath dir . | 48 | 16 |
15,174 | public static void createTemplateWithJson ( RestClient client , String template , String json , boolean force ) throws Exception { if ( isTemplateExist ( client , template ) ) { if ( force ) { logger . debug ( "Template [{}] already exists. Force is set. Removing it." , template ) ; removeTemplate ( client , template ) ; } else { logger . debug ( "Template [{}] already exists." , template ) ; } } if ( ! isTemplateExist ( client , template ) ) { logger . debug ( "Template [{}] doesn't exist. Creating it." , template ) ; createTemplateWithJsonInElasticsearch ( client , template , json ) ; } } | Create a new template in Elasticsearch | 152 | 7 |
15,175 | public static String readFileFromClasspath ( String file ) { logger . trace ( "Reading file [{}]..." , file ) ; String content = null ; try ( InputStream asStream = SettingsReader . class . getClassLoader ( ) . getResourceAsStream ( file ) ) { if ( asStream == null ) { logger . trace ( "Can not find [{}] in class loader." , file ) ; return null ; } content = IOUtils . toString ( asStream , "UTF-8" ) ; } catch ( IOException e ) { logger . warn ( "Can not read [{}]." , file ) ; } return content ; } | Read a file content from the classpath | 142 | 8 |
15,176 | public static String [ ] getResources ( final String root ) throws URISyntaxException , IOException { logger . trace ( "Reading classpath resources from {}" , root ) ; URL dirURL = ResourceList . class . getClassLoader ( ) . getResource ( root ) ; if ( dirURL != null && dirURL . getProtocol ( ) . equals ( "file" ) ) { /* A file path: easy enough */ logger . trace ( "found a file resource: {}" , dirURL ) ; String [ ] resources = new File ( dirURL . toURI ( ) ) . list ( ) ; Arrays . sort ( resources ) ; return resources ; } if ( dirURL == null ) { /* * In case of a jar file, we can't actually find a directory. * Have to assume the same jar as clazz. */ String me = ResourceList . class . getName ( ) . replace ( "." , "/" ) + ".class" ; dirURL = ResourceList . class . getClassLoader ( ) . getResource ( me ) ; } if ( dirURL == null ) { throw new RuntimeException ( "can not get resource file " + root ) ; } if ( dirURL . getProtocol ( ) . equals ( "jar" ) ) { /* A JAR path */ logger . trace ( "found a jar file resource: {}" , dirURL ) ; String jarPath = dirURL . getPath ( ) . substring ( 5 , dirURL . getPath ( ) . indexOf ( "!" ) ) ; //strip out only the JAR file String prefix = dirURL . getPath ( ) . substring ( 5 + jarPath . length ( ) ) // remove any ! that a class loader (e.g. from spring boot) could have added . replaceAll ( "!" , "" ) // remove leading slash that is not part of the JarEntry::getName . substring ( 1 ) ; Set < String > result = new HashSet <> ( ) ; //avoid duplicates in case it is a subdirectory try ( JarFile jar = new JarFile ( URLDecoder . decode ( jarPath , "UTF-8" ) ) ) { Enumeration < JarEntry > entries = jar . entries ( ) ; //gives ALL entries in jar while ( entries . hasMoreElements ( ) ) { String name = entries . nextElement ( ) . getName ( ) ; if ( name . startsWith ( prefix ) ) { //filter according to the path String entry = name . substring ( prefix . length ( ) ) ; int checkSubdir = entry . indexOf ( "/" ) ; if ( checkSubdir >= 0 ) { // if it is a subdirectory, we just return the directory name entry = entry . substring ( 0 , checkSubdir ) ; } result . add ( entry ) ; } } } String [ ] resources = result . toArray ( new String [ result . size ( ) ] ) ; Arrays . sort ( resources ) ; return resources ; } // Resource does not exist. We can return an empty list logger . trace ( "did not find any resource. returning empty array" ) ; return NO_RESOURCE ; } | List directory contents for a resource folder . Not recursive . This is basically a brute - force implementation . Works for regular files and also JARs . | 673 | 30 |
15,177 | public static List < String > findTemplates ( String root ) throws IOException , URISyntaxException { if ( root == null ) { return findTemplates ( ) ; } logger . debug ( "Looking for templates in classpath under [{}]." , root ) ; final List < String > templateNames = new ArrayList <> ( ) ; String [ ] resources = ResourceList . getResources ( root + "/" + Defaults . TemplateDir + "/" ) ; // "es/_template/" for ( String resource : resources ) { if ( ! resource . isEmpty ( ) ) { String withoutIndex = resource . substring ( resource . indexOf ( "/" ) + 1 ) ; String template = withoutIndex . substring ( 0 , withoutIndex . indexOf ( Defaults . JsonFileExtension ) ) ; logger . trace ( " - found [{}]." , template ) ; templateNames . add ( template ) ; } } return templateNames ; } | Find all templates | 204 | 3 |
15,178 | @ Deprecated public static void createIndex ( Client client , String root , String index , boolean force ) throws Exception { String settings = IndexSettingsReader . readSettings ( root , index ) ; createIndexWithSettings ( client , index , settings , force ) ; } | Create a new index in Elasticsearch . Read also _settings . json if exists . | 54 | 17 |
15,179 | public static void createIndex ( RestClient client , String index , boolean force ) throws Exception { String settings = IndexSettingsReader . readSettings ( index ) ; createIndexWithSettings ( client , index , settings , force ) ; } | Create a new index in Elasticsearch . Read also _settings . json if exists in default classpath dir . | 47 | 22 |
15,180 | private void inflateWidgetLayout ( Context context , int layoutId ) { inflate ( context , layoutId , this ) ; floatingLabel = ( TextView ) findViewById ( R . id . flw_floating_label ) ; if ( floatingLabel == null ) { throw new RuntimeException ( "Your layout must have a TextView whose ID is @id/flw_floating_label" ) ; } View iw = findViewById ( R . id . flw_input_widget ) ; if ( iw == null ) { throw new RuntimeException ( "Your layout must have an input widget whose ID is @id/flw_input_widget" ) ; } try { inputWidget = ( InputWidgetT ) iw ; } catch ( ClassCastException e ) { throw new RuntimeException ( "The input widget is not of the expected type" ) ; } } | Inflate the widget layout and make sure we have everything in there | 187 | 14 |
15,181 | public B css ( String ... classes ) { if ( classes != null ) { List < String > failSafeClasses = new ArrayList <> ( ) ; for ( String c : classes ) { if ( c != null ) { if ( c . contains ( " " ) ) { failSafeClasses . addAll ( asList ( c . split ( " " ) ) ) ; } else { failSafeClasses . add ( c ) ; } } } for ( String failSafeClass : failSafeClasses ) { get ( ) . classList . add ( failSafeClass ) ; } } return that ( ) ; } | Adds the specified CSS classes to the class list of the element . | 132 | 13 |
15,182 | public B attr ( String name , String value ) { get ( ) . setAttribute ( name , value ) ; return that ( ) ; } | Sets the specified attribute of the element . | 30 | 9 |
15,183 | public < V extends Event > B on ( EventType < V , ? > type , EventCallbackFn < V > callback ) { bind ( get ( ) , type , callback ) ; return that ( ) ; } | Adds the given callback to the element . | 45 | 8 |
15,184 | public void setInputWidgetText ( CharSequence text , TextView . BufferType type ) { getInputWidget ( ) . setText ( text , type ) ; } | Delegate method for the input widget | 35 | 7 |
15,185 | protected void onTextChanged ( String s ) { if ( ! isFloatOnFocusEnabled ( ) ) { if ( s . length ( ) == 0 ) { anchorLabel ( ) ; } else { floatLabel ( ) ; } } if ( editTextListener != null ) editTextListener . onTextChanged ( this , s ) ; } | Called when the text within the input widget is updated | 70 | 11 |
15,186 | public static Bitmap applyColor ( Bitmap bitmap , int accentColor ) { int r = Color . red ( accentColor ) ; int g = Color . green ( accentColor ) ; int b = Color . blue ( accentColor ) ; int width = bitmap . getWidth ( ) ; int height = bitmap . getHeight ( ) ; int [ ] pixels = new int [ width * height ] ; bitmap . getPixels ( pixels , 0 , width , 0 , 0 , width , height ) ; for ( int i = 0 ; i < pixels . length ; i ++ ) { int color = pixels [ i ] ; int alpha = Color . alpha ( color ) ; pixels [ i ] = Color . argb ( alpha , r , g , b ) ; } return Bitmap . createBitmap ( pixels , width , height , Bitmap . Config . ARGB_8888 ) ; } | Creates a copy of the bitmap by replacing the color of every pixel by accentColor while keeping the alpha value . | 189 | 24 |
15,187 | public static Bitmap changeTintColor ( Bitmap bitmap , int originalColor , int destinationColor ) { // original tint color int [ ] o = new int [ ] { Color . red ( originalColor ) , Color . green ( originalColor ) , Color . blue ( originalColor ) } ; // destination tint color int [ ] d = new int [ ] { Color . red ( destinationColor ) , Color . green ( destinationColor ) , Color . blue ( destinationColor ) } ; int width = bitmap . getWidth ( ) ; int height = bitmap . getHeight ( ) ; int [ ] pixels = new int [ width * height ] ; bitmap . getPixels ( pixels , 0 , width , 0 , 0 , width , height ) ; int maxIndex = getMaxIndex ( o ) ; int mintIndex = getMinIndex ( o ) ; for ( int i = 0 ; i < pixels . length ; i ++ ) { int color = pixels [ i ] ; // pixel color int [ ] p = new int [ ] { Color . red ( color ) , Color . green ( color ) , Color . blue ( color ) } ; int alpha = Color . alpha ( color ) ; float [ ] transformation = calculateTransformation ( o [ maxIndex ] , o [ mintIndex ] , p [ maxIndex ] , p [ mintIndex ] ) ; pixels [ i ] = applyTransformation ( d , alpha , transformation ) ; } return Bitmap . createBitmap ( pixels , width , height , Bitmap . Config . ARGB_8888 ) ; } | Creates a copy of the bitmap by calculating the transformation based on the original color and applying it to the the destination color . | 328 | 26 |
15,188 | public static Bitmap processTintTransformationMap ( Bitmap transformationMap , int tintColor ) { // tint color int [ ] t = new int [ ] { Color . red ( tintColor ) , Color . green ( tintColor ) , Color . blue ( tintColor ) } ; int width = transformationMap . getWidth ( ) ; int height = transformationMap . getHeight ( ) ; int [ ] pixels = new int [ width * height ] ; transformationMap . getPixels ( pixels , 0 , width , 0 , 0 , width , height ) ; float [ ] transformation = new float [ 2 ] ; for ( int i = 0 ; i < pixels . length ; i ++ ) { int color = pixels [ i ] ; int alpha = Color . alpha ( color ) ; transformation [ 0 ] = Color . red ( color ) / 255f ; transformation [ 1 ] = Color . green ( color ) / 255f ; pixels [ i ] = applyTransformation ( t , alpha , transformation ) ; } return Bitmap . createBitmap ( pixels , width , height , Bitmap . Config . ARGB_8888 ) ; } | Apply the given tint color to the transformation map . | 236 | 10 |
15,189 | public static void writeToFile ( Bitmap bitmap , String dir , String filename ) throws FileNotFoundException , IOException { File sdCard = Environment . getExternalStorageDirectory ( ) ; File dirFile = new File ( sdCard . getAbsolutePath ( ) + "/" + dir ) ; dirFile . mkdirs ( ) ; File f = new File ( dirFile , filename ) ; FileOutputStream fos = new FileOutputStream ( f , false ) ; bitmap . compress ( CompressFormat . PNG , 100 /*ignored for PNG*/ , fos ) ; fos . flush ( ) ; fos . close ( ) ; } | Write the given bitmap to a file in the external storage . Requires android . permission . WRITE_EXTERNAL_STORAGE permission . | 138 | 29 |
15,190 | public static int getIdentifier ( String name ) { Resources res = Resources . getSystem ( ) ; return res . getIdentifier ( name , TYPE_ID , NATIVE_PACKAGE ) ; } | Get a native identifier by name as in R . id . name . | 43 | 14 |
15,191 | public static int getStringIdentifier ( String name ) { Resources res = Resources . getSystem ( ) ; return res . getIdentifier ( name , TYPE_STRING , NATIVE_PACKAGE ) ; } | Get a native string id by name as in R . string . name . | 45 | 15 |
15,192 | public static int getDrawableIdentifier ( String name ) { Resources res = Resources . getSystem ( ) ; return res . getIdentifier ( name , TYPE_DRAWABLE , NATIVE_PACKAGE ) ; } | Get a native drawable id by name as in R . drawable . name . | 47 | 17 |
15,193 | static TodoItemElement create ( Provider < ApplicationElement > application , TodoItemRepository repository ) { return new Templated_TodoItemElement ( application , repository ) ; } | Don t use ApplicationElement directly as this will lead to a dependency cycle in the generated GIN code! | 38 | 21 |
15,194 | public void addTintResourceId ( int resId ) { if ( mCustomTintDrawableIds == null ) mCustomTintDrawableIds = new ArrayList < Integer > ( ) ; mCustomTintDrawableIds . add ( resId ) ; } | Add a drawable resource to which to apply the tint technique . | 60 | 13 |
15,195 | public void addTintTransformationResourceId ( int resId ) { if ( mCustomTransformationDrawableIds == null ) mCustomTransformationDrawableIds = new ArrayList < Integer > ( ) ; mCustomTransformationDrawableIds . add ( resId ) ; } | Add a drawable resource to which to apply the tint transformation technique . | 62 | 14 |
15,196 | private InputStream getTintendResourceStream ( int id , TypedValue value , int color ) { Bitmap bitmap = getBitmapFromResource ( id , value ) ; bitmap = BitmapUtils . applyColor ( bitmap , color ) ; return getStreamFromBitmap ( bitmap ) ; } | Get a reference to a resource that is equivalent to the one requested but with the accent color applied to it . | 66 | 22 |
15,197 | private InputStream getTintTransformationResourceStream ( int id , TypedValue value , int color ) { Bitmap bitmap = getBitmapFromResource ( id , value ) ; bitmap = BitmapUtils . processTintTransformationMap ( bitmap , color ) ; return getStreamFromBitmap ( bitmap ) ; } | Get a reference to a resource that is equivalent to the one requested but changing the tint from the original red to the given color . | 72 | 26 |
15,198 | public Collection < ItemT > getSelectedItems ( ) { if ( availableItems == null || selectedIndices == null || selectedIndices . length == 0 ) { return new ArrayList < ItemT > ( 0 ) ; } ArrayList < ItemT > items = new ArrayList < ItemT > ( selectedIndices . length ) ; for ( int index : selectedIndices ) { items . add ( availableItems . get ( index ) ) ; } return items ; } | Get the items currently selected | 99 | 5 |
15,199 | protected static Bundle buildCommonArgsBundle ( int pickerId , String title , String positiveButtonText , String negativeButtonText , boolean enableMultipleSelection , int [ ] selectedItemIndices ) { Bundle args = new Bundle ( ) ; args . putInt ( ARG_PICKER_ID , pickerId ) ; args . putString ( ARG_TITLE , title ) ; args . putString ( ARG_POSITIVE_BUTTON_TEXT , positiveButtonText ) ; args . putString ( ARG_NEGATIVE_BUTTON_TEXT , negativeButtonText ) ; args . putBoolean ( ARG_ENABLE_MULTIPLE_SELECTION , enableMultipleSelection ) ; args . putIntArray ( ARG_SELECTED_ITEMS_INDICES , selectedItemIndices ) ; return args ; } | Utility method for implementations to create the base argument bundle | 181 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.