idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
15,100 | public void cleanupParams ( int size , long interval ) { timer . cancel ( ) ; timer . schedule ( new Cleanup ( content , size ) , interval , interval ) ; } | Reset the Cleanup size and interval |
15,101 | public Content load ( LogTarget logTarget , String dataRoot , String key , String mediaType , long _timeCheck ) throws IOException { long timeCheck = _timeCheck ; if ( timeCheck < 0 ) { timeCheck = checkInterval ; } String fileName = dataRoot + '/' + key ; Content c = content . get ( key ) ; long systime = System . currentTimeMillis ( ) ; File f = null ; if ( c != null ) { if ( c . date < systime + timeCheck ) { f = new File ( fileName ) ; if ( f . lastModified ( ) > c . date ) { c = null ; } } } if ( c == null ) { if ( logTarget != null ) { logTarget . log ( "File Read: " , key ) ; } if ( f == null ) { f = new File ( fileName ) ; } boolean cacheMe ; if ( f . exists ( ) ) { if ( f . length ( ) > maxItemSize ) { c = new DirectFileContent ( f ) ; cacheMe = false ; } else { c = new CachedContent ( f ) ; cacheMe = checkInterval > 0 ; } if ( mediaType == null ) { int idx = key . lastIndexOf ( '.' ) ; String subkey = key . substring ( ++ idx ) ; if ( ( c . contentType = idx < 0 ? null : typeMap . get ( subkey ) ) == null ) { c . contentType = "application/octet-stream" ; } c . attachmentOnly = attachOnly . contains ( subkey ) ; } else { c . contentType = mediaType ; c . attachmentOnly = false ; } c . date = f . lastModified ( ) ; if ( cacheMe ) { content . put ( key , c ) ; } } else { c = NULL ; } } else { if ( logTarget != null ) logTarget . log ( "Cache Read: " , key ) ; } c . access = systime ; return c ; } | Load a file first checking cache |
15,102 | public < T > Future < Void > update ( String pathinfo ) throws APIException , CadiException { final int idx = pathinfo . indexOf ( '?' ) ; final String qp ; if ( idx >= 0 ) { qp = pathinfo . substring ( idx + 1 ) ; pathinfo = pathinfo . substring ( 0 , idx ) ; } else { qp = queryParams ; } EClient < CT > client = client ( ) ; client . setMethod ( PUT ) ; client . addHeader ( CONTENT_TYPE , typeString ( Void . class ) ) ; client . setQueryParams ( qp ) ; client . setFragment ( fragment ) ; client . setPathInfo ( pathinfo ) ; client . send ( ) ; queryParams = fragment = null ; return client . future ( null ) ; } | A method to update with a VOID |
15,103 | private static JaxInfo [ ] buildFields ( Class < ? > clazz , String defaultNS ) throws SecurityException , NoSuchFieldException , ClassNotFoundException { ArrayList < JaxInfo > fields = null ; Class < ? > cls = clazz ; XmlType xt ; while ( ( xt = cls . getAnnotation ( XmlType . class ) ) != null ) { if ( fields == null ) fields = new ArrayList < JaxInfo > ( ) ; for ( String field : xt . propOrder ( ) ) { if ( "" . equals ( field ) ) break ; Field rf = cls . getDeclaredField ( field ) ; Class < ? > ft = rf . getType ( ) ; boolean required = false ; boolean nillable = false ; String xmlName = field ; String namespace = defaultNS ; XmlElement xe = rf . getAnnotation ( XmlElement . class ) ; if ( xe != null ) { xmlName = xe . name ( ) ; required = xe . required ( ) ; nillable = false ; if ( DEFAULT . equals ( xmlName ) ) { xmlName = field ; } namespace = xe . namespace ( ) ; if ( DEFAULT . equals ( namespace ) ) { namespace = defaultNS ; } } if ( ft . isAssignableFrom ( List . class ) ) { Type t = rf . getGenericType ( ) ; String classname = t . toString ( ) ; int start = classname . indexOf ( '<' ) ; int end = classname . indexOf ( '>' ) ; Class < ? > genClass = Class . forName ( classname . substring ( start + 1 , end ) ) ; xe = genClass . getAnnotation ( XmlElement . class ) ; if ( xe != null && ! DEFAULT . equals ( xe . namespace ( ) ) ) { namespace = xe . namespace ( ) ; } fields . add ( new JaxInfo ( xmlName , namespace , genClass , buildFields ( genClass , namespace ) , genClass . equals ( String . class ) , true , required , nillable ) ) ; } else { boolean isString = ft . equals ( String . class ) || ft . equals ( XMLGregorianCalendar . class ) ; fields . add ( new JaxInfo ( xmlName , namespace , ft , buildFields ( ft , namespace ) , isString , false , required , nillable ) ) ; } } cls = cls . getSuperclass ( ) ; } ; if ( fields != null ) { JaxInfo [ ] rv = new JaxInfo [ fields . size ( ) ] ; fields . toArray ( rv ) ; return rv ; } else { return null ; } } | This is recursive if a member is a JAXB Object as well . |
15,104 | public Result < List < Data > > readByUserRole ( AuthzTrans trans , String user , String role ) { return psUserInRole . read ( trans , R_TEXT + " by User " + user + " and Role " + role , new Object [ ] { user , role } ) ; } | Direct Lookup of User Role Don t forget to check for Expiration |
15,105 | public static byte [ ] encryptMD5 ( byte [ ] input ) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; md . update ( input ) ; return md . digest ( ) ; } | Encrypt MD5 from Byte Array to Byte Array |
15,106 | public static boolean isEqual ( byte ba1 [ ] , byte ba2 [ ] ) { if ( ba1 . length != ba2 . length ) return false ; for ( int i = 0 ; i < ba1 . length ; ++ i ) { if ( ba1 [ i ] != ba2 [ i ] ) return false ; } return true ; } | Compare two byte arrays for equivalency |
15,107 | public static String readString ( DataInputStream is , byte [ ] _buff ) throws IOException { int l = is . readInt ( ) ; byte [ ] buff = _buff ; switch ( l ) { case - 1 : return null ; case 0 : return "" ; default : if ( l > buff . length ) { buff = new byte [ l ] ; } is . read ( buff , 0 , l ) ; return new String ( buff , 0 , l ) ; } } | We use bytes here to set a Maximum |
15,108 | public static void writeStringSet ( DataOutputStream os , Collection < String > set ) throws IOException { if ( set == null ) { os . writeInt ( - 1 ) ; } else { os . writeInt ( set . size ( ) ) ; for ( String s : set ) { writeString ( os , s ) ; } } } | Write a set with proper sizing |
15,109 | public static void writeStringMap ( DataOutputStream os , Map < String , String > map ) throws IOException { if ( map == null ) { os . writeInt ( - 1 ) ; } else { Set < Entry < String , String > > es = map . entrySet ( ) ; os . writeInt ( es . size ( ) ) ; for ( Entry < String , String > e : es ) { writeString ( os , e . getKey ( ) ) ; writeString ( os , e . getValue ( ) ) ; } } } | Write a map |
15,110 | public final static StringBuilder buildLine ( Level level , StringBuilder sb , Object [ ] elements ) { sb . append ( level . name ( ) ) ; return buildLine ( sb , elements ) ; } | Add the Level to the Buildline for Logging types that don t specify or straight Streams etc . Then buildline |
15,111 | public void log ( Level level , Object ... elements ) { if ( willWrite . compareTo ( level ) <= 0 ) { StringBuilder sb = buildLine ( level , new StringBuilder ( ) , elements ) ; if ( context == null ) { System . out . println ( sb . toString ( ) ) ; } else { context . log ( sb . toString ( ) ) ; } } } | Standard mechanism for logging given being within a Servlet Context |
15,112 | public void log ( Exception e , Object ... elements ) { if ( willWrite . compareTo ( Level . ERROR ) <= 0 ) { StringBuilder sb = buildLine ( Level . ERROR , new StringBuilder ( ) , elements ) ; if ( context == null ) { sb . append ( e . toString ( ) ) ; System . out . println ( sb . toString ( ) ) ; } else { context . log ( sb . toString ( ) , e ) ; } } } | Standard mechanism for logging an Exception given being within a Servlet Context etc |
15,113 | public String getProperty ( String string , String def ) { String rv = null ; if ( props != null ) rv = props . getProperty ( string , def ) ; if ( rv == null ) { rv = context . getInitParameter ( string ) ; } return rv == null ? def : rv ; } | Get the Property from Context |
15,114 | public void prime ( LogTarget lt , int prime ) throws APIException { for ( int i = 0 ; i < prime ; ++ i ) { Pooled < T > pt = new Pooled < T > ( creator . create ( ) , this , lt ) ; synchronized ( list ) { list . addFirst ( pt ) ; ++ count ; } } } | Preallocate a certain number of T Objects . Useful for services so that the first transactions don t get hit with all the Object creation costs |
15,115 | public void drain ( ) { synchronized ( list ) { for ( int i = 0 ; i < list . size ( ) ; ++ i ) { Pooled < T > pt = list . remove ( ) ; creator . destroy ( pt . content ) ; pt . logTarget . log ( "Pool drained " , creator . toString ( ) ) ; } count = spares = 0 ; } } | Destroy and remove all remaining objects . This is valuable for closing down all Allocated objects cleanly for exiting . It is also a good method for removing objects when for instance all Objects are invalid because of broken connections etc . |
15,116 | public boolean validate ( ) { boolean rv = true ; synchronized ( list ) { for ( Pooled < T > t : list ) { if ( ! creator . isValid ( t . content ) ) { rv = false ; t . toss ( ) ; list . remove ( t ) ; } } } return rv ; } | This function will validate whether the Objects are still in a usable state . If not they are tossed from the Pool . This is valuable to have when Remote Connections go down and there is a question on whether the Pooled Objects are still functional . |
15,117 | public T get ( Env env ) throws APIException { Thread t = Thread . currentThread ( ) ; T obj = objs . get ( t ) ; if ( obj == null || refreshed > obj . created ( ) ) { try { obj = cnst . newInstance ( new Object [ ] { env } ) ; } catch ( InvocationTargetException e ) { throw new APIException ( e . getTargetException ( ) ) ; } catch ( Exception e ) { throw new APIException ( e ) ; } T destroyMe = objs . put ( t , obj ) ; if ( destroyMe != null ) { destroyMe . destroy ( env ) ; } } return obj ; } | Get the T class from the current thread |
15,118 | public void remove ( Env env ) { T obj = objs . remove ( Thread . currentThread ( ) ) ; if ( obj != null ) obj . destroy ( env ) ; } | Remove the object from the Thread instances |
15,119 | public Result < List < Data > > readByUser ( AuthzTrans trans , final String user ) { DAOGetter getter = new DAOGetter ( trans , dao ( ) ) { public Result < List < Data > > call ( ) { if ( user != null && user . equals ( trans . user ( ) ) ) { Result < List < Data > > transLD = trans . get ( transURSlot , null ) ; if ( transLD == null ) { transLD = dao . readByUser ( trans , user ) ; } return transLD ; } else { return dao . readByUser ( trans , user ) ; } } } ; Result < List < Data > > lurd = get ( trans , user , getter ) ; if ( lurd . isOK ( ) && lurd . isEmpty ( ) ) { return Result . err ( Status . ERR_UserRoleNotFound , "UserRole not found for [%s]" , user ) ; } return lurd ; } | Special Case . User Roles by User are very likely to be called many times in a Transaction to validate May User do ... Pull result and make accessible by the Trans which is always keyed by User . |
15,120 | public Rcli < CLIENT > clientAs ( String apiVersion , ServletRequest req ) throws CadiException { Rcli < CLIENT > cl = client ( apiVersion ) ; return cl . forUser ( transferSS ( ( ( HttpServletRequest ) req ) . getUserPrincipal ( ) ) ) ; } | Use this API when you have permission to have your call act as the end client s ID . |
15,121 | public static final AAFCon < ? > obtain ( Object servletRequest ) { if ( servletRequest instanceof CadiWrap ) { Lur lur = ( ( CadiWrap ) servletRequest ) . getLur ( ) ; if ( lur != null ) { if ( lur instanceof EpiLur ) { AbsAAFLur < ? > aal = ( AbsAAFLur < ? > ) ( ( EpiLur ) lur ) . subLur ( AbsAAFLur . class ) ; if ( aal != null ) { return aal . aaf ; } } else { if ( lur instanceof AbsAAFLur ) { return ( ( AbsAAFLur < ? > ) lur ) . aaf ; } } } } return null ; } | Return the backing AAFCon if there is a Lur Setup that is AAF . |
15,122 | public static String reverseDomain ( String user ) { StringBuilder sb = null ; String [ ] split = Split . split ( '.' , user ) ; int at ; for ( int i = split . length - 1 ; i >= 0 ; -- i ) { if ( sb == null ) { sb = new StringBuilder ( ) ; } else { sb . append ( '.' ) ; } if ( ( at = split [ i ] . indexOf ( '@' ) ) > 0 ) { sb . append ( split [ i ] . subSequence ( at + 1 , split [ i ] . length ( ) ) ) ; } else { sb . append ( split [ i ] ) ; } } return sb == null ? "" : sb . toString ( ) ; } | Take a Fully Qualified User and get a Namespace from it . |
15,123 | public static synchronized boolean denyIP ( String ip ) { boolean rv = false ; if ( deniedIP == null ) { deniedIP = new HashMap < String , Counter > ( ) ; deniedIP . put ( ip , new Counter ( ip ) ) ; rv = true ; } else if ( deniedIP . get ( ip ) == null ) { deniedIP . put ( ip , new Counter ( ip ) ) ; rv = true ; } if ( rv ) { writeIP ( ) ; } return rv ; } | Return of True means IP has been added . Return of False means IP already added . |
15,124 | public static synchronized boolean removeDenyIP ( String ip ) { if ( deniedIP != null && deniedIP . remove ( ip ) != null ) { writeIP ( ) ; if ( deniedIP . isEmpty ( ) ) { deniedIP = null ; } return true ; } return false ; } | Return of True means IP has was removed . Return of False means IP wasn t being denied . |
15,125 | public static synchronized boolean denyID ( String id ) { boolean rv = false ; if ( deniedID == null ) { deniedID = new HashMap < String , Counter > ( ) ; deniedID . put ( id , new Counter ( id ) ) ; 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 . |
15,126 | 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 . |
15,127 | 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" ) ; aafResponse = aafAuthn . validate ( fullName , password ) ; if ( aafResponse != null ) { access . log ( Level . AUDIT , "AAF reports " , fullName , ":" , aafResponse ) ; throw new AuthenticationException ( aafResponse ) ; } access . log ( Level . AUDIT , fullName , "is authenticated" ) ; 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 |
15,128 | 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 |
15,129 | public Result < Void > addDescription ( AuthzTrans trans , String ns , String type , String instance , String action , String description ) { return dao ( ) . addDescription ( trans , ns , type , instance , action , description ) ; } | Add desciption to this permission |
15,130 | public static void xmlEscape ( StringBuilder sb , Reader r ) throws ParseException { try { int c ; StringBuilder esc = new StringBuilder ( ) ; for ( int cnt = 0 ; cnt < 9 ; ++ cnt ) { if ( ( c = r . read ( ) ) < 0 ) throw new ParseException ( "Invalid Data: Unfinished Escape Sequence" ) ; if ( c != ';' ) { esc . append ( ( char ) c ) ; } else { Integer i = charMap . get ( esc . toString ( ) ) ; if ( i == null ) { 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 |
15,131 | private Set < Permission > checkPermissions ( AAFAuthenticatedUser aau , String type , String instance ) { String fullName = aau . getFullName ( ) ; PermHolder ph = new PermHolder ( aau ) ; aafLur . fishOneOf ( fullName , ph , type , instance , actions ) ; return ph . permissions ; } | Check remoted AAF Permissions |
15,132 | 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 |
15,133 | public boolean match ( Permission p ) { if ( p instanceof AAFPermission ) { AAFPermission ap = ( AAFPermission ) p ; if ( type . equals ( ap . getName ( ) ) ) if ( PermEval . evalInstance ( instance , ap . getInstance ( ) ) ) if ( PermEval . evalAction ( action , ap . getAction ( ) ) ) return true ; } else { 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 | |
15,134 | 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 ; } 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 ( ) ) ; } } String delP1 = pdd . ns ; NsSplit nss = new NsSplit ( parent , pdd . fullType ( ) ) ; pdd . ns = nss . ns ; pdd . type = nss . name ; if ( ( pd = q . permDAO . create ( trans , pdd ) ) . isOK ( ) ) { 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 ( '\n' ) ; } } else { sb . append ( pd . details ) ; sb . append ( '\n' ) ; } } } } | Helper function that moves permissions from a namespace being deleted to its parent namespace |
15,135 | 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 ; } 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 ( ) ) ; } } String delP1 = rdd . ns ; NsSplit nss = new NsSplit ( parent , rdd . fullName ( ) ) ; rdd . ns = nss . ns ; rdd . name = nss . name ; if ( ( rd = q . roleDAO . create ( trans , rdd ) ) . isOK ( ) ) { 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 ( '\n' ) ; } } else { sb . append ( rd . details ) ; sb . append ( '\n' ) ; } } } } | Helper function that moves roles from a namespace being deleted to its parent namespace |
15,136 | 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 ; } 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 |
15,137 | public Result < Void > extendUserRole ( AuthzTrans trans , UserRoleDAO . Data urData , boolean checkForExist ) { 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 ) ; } urData . expires = trans . org ( ) . expiration ( null , Expiration . UserInRole ) . getTime ( ) ; return q . userRoleDAO . update ( trans , urData ) ; } | Extend User Role . |
15,138 | 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 |
15,139 | 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 |
15,140 | 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 ) ; 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 . |
15,141 | 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 ; |
15,142 | 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 |
15,143 | public Result < FutureDAO . Data > create ( AuthzTrans trans , FutureDAO . Data data , String id ) { 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 |
15,144 | 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 { synchronized ( XMLConstants . W3C_XML_SCHEMA_NS_URI ) { 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 ) { } } } } | Generate a Schema Object for use in validation based on FileNames . |
15,145 | public int read ( byte [ ] array , int offset , int length ) { if ( curr == null ) return - 1 ; int len ; int count = 0 ; while ( length > 0 ) { if ( ( len = curr . remaining ( ) ) > length ) { curr . get ( array , offset , length ) ; count += length ; length = 0 ; } else { curr . get ( array , offset , len ) ; count += len ; offset += len ; length -= len ; if ( idx < bbs . size ( ) ) { curr = bbs . get ( idx ++ ) ; } else { length = 0 ; } } } return count ; } | read into an array like Streams |
15,146 | 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 { curr . put ( array , offset , len ) ; length -= len ; offset += len ; curr = ringGet ( ) ; bbs . add ( curr ) ; } } } | Put an array of data into Capacitor |
15,147 | 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 |
15,148 | public void done ( ) { for ( ByteBuffer bb : bbs ) { ringPut ( bb ) ; } bbs . clear ( ) ; curr = null ; } | reuse all the buffers |
15,149 | 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 |
15,150 | 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 . |
15,151 | 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 |
15,152 | 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 . |
15,153 | public void destroy ( ) { synchronized ( CadiHTTPManip . noAdditional ) { if ( -- count <= 0 && httpChecker != null ) { httpChecker . destroy ( ) ; httpChecker = null ; access = null ; pathExceptions = null ; } } } | Containers call destroy when time to cleanup |
15,154 | private boolean noAuthn ( HttpServletRequest hreq ) { if ( pathExceptions != null ) { String pi = hreq . getPathInfo ( ) ; if ( pi == null ) return false ; for ( String pe : pathExceptions ) { if ( pi . startsWith ( pe ) ) return true ; } } return false ; } | If PathExceptions exist report if these should not have Authn applied . |
15,155 | 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 |
15,156 | 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 |
15,157 | public Result < List < CertDAO . Data > > readID ( AuthzTrans trans , final String id ) { return dao ( ) . readID ( trans , id ) ; } | Pass through Cert ID Lookup |
15,158 | 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 |
15,159 | @ 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 |
15,160 | 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 |
15,161 | 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" ) ) { 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 |
15,162 | 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 . |
15,163 | 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 |
15,164 | 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 . |
15,165 | 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 |
15,166 | 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 |
15,167 | 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 ) { 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 |
15,168 | public Result < List < CredDAO . Data > > readNS ( AuthzTrans trans , final String ns ) { return dao ( ) . readNS ( trans , ns ) ; } | Pass through Cred Lookup |
15,169 | public Result < Void > addDescription ( AuthzTrans trans , String ns , String name , String description ) { return dao ( ) . addDescription ( trans , ns , name , description ) ; } | Add description to this role |
15,170 | 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 |
15,171 | 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 |
15,172 | 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 ) ; 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 ; |
15,173 | 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 |
15,174 | 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 |
15,175 | 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 |
15,176 | 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 |
15,177 | 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 |
15,178 | public static < R > Result < R > err ( Exception e ) { return new Result < R > ( null , ERR_General , e . getMessage ( ) , EMPTY_VARS ) ; } | Create General Error from Exception |
15,179 | 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 |
15,180 | 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 |
15,181 | 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 |
15,182 | public String encode ( String str ) throws IOException { byte [ ] array ; try { array = str . getBytes ( encoding ) ; } catch ( IOException e ) { array = str . getBytes ( ) ; } ByteArrayOutputStream baos = new ByteArrayOutputStream ( ( int ) ( array . length * 1.363 ) ) ; encode ( new ByteArrayInputStream ( array ) , baos ) ; return baos . toString ( encoding ) ; } | Helper function for String API of Encode use getBytes with appropriate char encoding etc . |
15,183 | public void encode ( InputStream is , OutputStream os ) throws IOException { int prev = 0 ; int read , idx = 0 , line = 0 ; boolean go ; do { read = is . read ( ) ; if ( go = read >= 0 ) { if ( line >= splitLinesAt ) { os . write ( '\n' ) ; line = 0 ; } switch ( ++ idx ) { case 1 : os . write ( codeset [ read >> 2 ] ) ; prev = read ; break ; case 2 : os . write ( codeset [ ( ( prev & 0x03 ) << 4 ) | ( read >> 4 ) ] ) ; prev = read ; break ; default : os . write ( codeset [ ( ( ( prev & 0xF ) << 2 ) | ( read >> 6 ) ) ] ) ; if ( line == splitLinesAt ) { os . write ( '\n' ) ; line = 0 ; } os . write ( codeset [ ( read & 0x3F ) ] ) ; ++ line ; idx = 0 ; prev = 0 ; } ++ line ; } else { switch ( idx ) { case 1 : os . write ( codeset [ ( prev & 0x03 ) << 4 ] ) ; if ( endEquals ) os . write ( DOUBLE_EQ ) ; break ; case 2 : os . write ( codeset [ ( prev & 0xF ) << 2 ] ) ; if ( endEquals ) os . write ( '=' ) ; break ; } idx = 0 ; } } while ( go ) ; } | encode InputStream onto Output Stream |
15,184 | 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 ) { case 1 : prev = index << 2 ; break ; case 2 : os . write ( ( byte ) ( prev | ( index >> 4 ) ) ) ; prev = index << 4 ; break ; case 3 : os . write ( ( byte ) ( prev | ( index >> 2 ) ) ) ; prev = index << 6 ; break ; default : os . write ( ( byte ) ( prev | ( index & 0x3F ) ) ) ; idx = prev = 0 ; } } } ; os . flush ( ) ; } | Decode InputStream onto OutputStream |
15,185 | 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 |
15,186 | public static Symm obtain ( InputStream is ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; try { base64url . decode ( is , baos ) ; } catch ( IOException e ) { throw new IOException ( "Invalid Key" ) ; } byte [ ] bkey = baos . toByteArray ( ) ; if ( bkey . length < 0x88 ) { throw new IOException ( "Invalid key" ) ; } return baseCrypt ( ) . obtain ( bkey ) ; } | Obtain a Symm from 2048 key from a Stream |
15,187 | 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 |
15,188 | public String enpass ( String password ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; enpass ( password , baos ) ; return new String ( baos . toByteArray ( ) ) ; } | Decrypt into a String |
15,189 | 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" ) ) { 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 ) ; if ( bytes . length < 0x9 ) { for ( int i = 0 ; i < bytes . length ; ++ i ) { dos . writeByte ( r . nextInt ( ) ) ; dos . writeByte ( bytes [ i ] ) ; } for ( int i = bytes . length ; i < 0x9 ; ++ i ) { dos . writeByte ( r . nextInt ( ) ) ; } } else { dos . write ( bytes ) ; } } exec ( new AESExec ( ) { 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 . |
15,190 | 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 |
15,191 | 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 ( ) { public void exec ( AES aes ) throws IOException { CipherOutputStream cos = aes . outputStream ( baos , false ) ; decode ( bais , cos ) ; cos . close ( ) ; } } ) ; byte [ ] bytes = baos . toByteArray ( ) ; DataInputStream dis = new DataInputStream ( new ByteArrayInputStream ( bytes ) ) ; long time ; if ( this . getClass ( ) . getSimpleName ( ) . startsWith ( "base64" ) ) { 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 |
15,192 | 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 ) { 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 . |
15,193 | private boolean nob ( String str , Pattern p ) { return str == null || ! p . matcher ( str ) . matches ( ) ; } | nob = Null Or Not match Pattern |
15,194 | public static void start ( RestClient client , String root , boolean merge , boolean force ) throws Exception { logger . info ( "starting automatic settings/mappings discovery" ) ; List < String > templateNames = TemplateFinder . findTemplates ( root ) ; for ( String templateName : templateNames ) { createTemplate ( client , root , templateName , force ) ; } 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 . |
15,195 | 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 + "/" ) ; 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 |
15,196 | 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 |
15,197 | 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 . |
15,198 | 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 . |
15,199 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.