idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
25,700
private String getAttributeValue ( final String elemQName , final QName attQName , final String value ) { if ( StringUtils . isEmptyString ( value ) && ! defaultValueMap . isEmpty ( ) ) { final Map < String , String > defaultMap = defaultValueMap . get ( attQName ) ; if ( defaultMap != null ) { final String defaultValue = defaultMap . get ( elemQName ) ; if ( defaultValue != null ) { return defaultValue ; } } } return value ; }
Get attribute value or default if attribute is not defined
113
10
25,701
private URI replaceHREF ( final QName attName , final Attributes atts ) { URI attValue = toURI ( atts . getValue ( attName . getNamespaceURI ( ) , attName . getLocalPart ( ) ) ) ; if ( attValue != null ) { final String fragment = attValue . getFragment ( ) ; if ( fragment != null ) { attValue = stripFragment ( attValue ) ; } if ( attValue . toString ( ) . length ( ) != 0 ) { final URI current = currentFile . resolve ( attValue ) ; final FileInfo f = job . getFileInfo ( current ) ; if ( f != null ) { final FileInfo cfi = job . getFileInfo ( currentFile ) ; final URI currrentFileTemp = job . tempDirURI . resolve ( cfi . uri ) ; final URI targetTemp = job . tempDirURI . resolve ( f . uri ) ; attValue = getRelativePath ( currrentFileTemp , targetTemp ) ; } else if ( tempFileNameScheme != null ) { final URI currrentFileTemp = job . tempDirURI . resolve ( tempFileNameScheme . generateTempFileName ( currentFile ) ) ; final URI targetTemp = job . tempDirURI . resolve ( tempFileNameScheme . generateTempFileName ( current ) ) ; final URI relativePath = getRelativePath ( currrentFileTemp , targetTemp ) ; attValue = relativePath ; } else { attValue = getRelativePath ( currentFile , current ) ; } } if ( fragment != null ) { attValue = setFragment ( attValue , fragment ) ; } } else { return null ; } return attValue ; }
Relativize absolute references if possible .
370
9
25,702
public Alphabet getAlphabetForChar ( final char theChar ) { Alphabet result = null ; for ( final Alphabet alphabet : this . alphabets ) { if ( alphabet . isContain ( theChar ) ) { result = alphabet ; break ; } } return result ; }
Searches alphabets for a char
58
10
25,703
public static URL correct ( final File file ) throws MalformedURLException { if ( file == null ) { throw new MalformedURLException ( "The url is null" ) ; } return new URL ( correct ( file . toURI ( ) . toString ( ) , true ) ) ; }
Corrects the file to URL .
65
7
25,704
public static URL correct ( final URL url ) throws MalformedURLException { if ( url == null ) { throw new MalformedURLException ( "The url is null" ) ; } return new URL ( correct ( url . toString ( ) , false ) ) ; }
Corrects an URL .
60
5
25,705
public static File getCanonicalFileFromFileUrl ( final URL url ) { File file = null ; if ( url == null ) { throw new NullPointerException ( "The URL cannot be null." ) ; } if ( "file" . equals ( url . getProtocol ( ) ) ) { final String fileName = url . getFile ( ) ; final String path = URLUtils . uncorrect ( fileName ) ; file = new File ( path ) ; try { file = file . getCanonicalFile ( ) ; } catch ( final IOException e ) { // Does not exist. file = file . getAbsoluteFile ( ) ; } } return file ; }
On Windows names of files from network neighborhood must be corrected before open .
144
14
25,706
private static String correct ( String url , final boolean forceCorrection ) { if ( url == null ) { return null ; } final String initialUrl = url ; // If there is a % that means the URL was already corrected. if ( ! forceCorrection && url . contains ( "%" ) ) { return initialUrl ; } // Extract the reference (anchor) part from the URL. The '#' char identifying the anchor // must not be corrected. String reference = null ; if ( ! forceCorrection ) { final int refIndex = url . lastIndexOf ( ' ' ) ; if ( refIndex != - 1 ) { reference = FilePathToURI . filepath2URI ( url . substring ( refIndex + 1 ) ) ; url = url . substring ( 0 , refIndex ) ; } } // Buffer where eventual query string will be processed. StringBuilder queryBuffer = null ; if ( ! forceCorrection ) { final int queryIndex = url . indexOf ( ' ' ) ; if ( queryIndex != - 1 ) { // We have a query final String query = url . substring ( queryIndex + 1 ) ; url = url . substring ( 0 , queryIndex ) ; queryBuffer = new StringBuilder ( query . length ( ) ) ; // Tokenize by & final StringTokenizer st = new StringTokenizer ( query , "&" ) ; while ( st . hasMoreElements ( ) ) { String token = st . nextToken ( ) ; token = FilePathToURI . filepath2URI ( token ) ; // Correct token queryBuffer . append ( token ) ; if ( st . hasMoreElements ( ) ) { queryBuffer . append ( "&" ) ; } } } } String toReturn = FilePathToURI . filepath2URI ( url ) ; if ( queryBuffer != null ) { // Append to the end the corrected query. toReturn += "?" + queryBuffer . toString ( ) ; } if ( reference != null ) { // Append the reference to the end the corrected query. toReturn += "#" + reference ; } return toReturn ; }
Method introduced to correct the URLs in the default machine encoding .
442
12
25,707
public static String getURL ( final String fileName ) { if ( fileName . startsWith ( "file:/" ) ) { return fileName ; } else { final File file = new File ( fileName ) ; return file . toURI ( ) . toString ( ) ; } }
Convert a file name to url .
60
8
25,708
public static boolean isAbsolute ( final URI uri ) { final String p = uri . getPath ( ) ; return p != null && p . startsWith ( URI_SEPARATOR ) ; }
Test if URI path is absolute .
43
7
25,709
public static File toFile ( final URI filename ) { if ( filename == null ) { return null ; } final URI f = stripFragment ( filename ) ; if ( "file" . equals ( f . getScheme ( ) ) && f . getPath ( ) != null && f . isAbsolute ( ) ) { return new File ( f ) ; } else { return toFile ( f . toString ( ) ) ; } }
Convert URI reference to system file path .
92
9
25,710
public static File toFile ( final String filename ) { if ( filename == null ) { return null ; } String f ; try { f = URLDecoder . decode ( filename , UTF8 ) ; } catch ( final UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } f = f . replace ( WINDOWS_SEPARATOR , File . separator ) . replace ( UNIX_SEPARATOR , File . separator ) ; return new File ( f ) ; }
Convert URI or chimera references to file paths .
105
11
25,711
public static URI toURI ( final String file ) { if ( file == null ) { return null ; } if ( File . separatorChar == ' ' && file . indexOf ( ' ' ) != - 1 ) { return toURI ( new File ( file ) ) ; } try { return new URI ( file ) ; } catch ( final URISyntaxException e ) { try { return new URI ( clean ( file . replace ( WINDOWS_SEPARATOR , URI_SEPARATOR ) . trim ( ) , false ) ) ; } catch ( final URISyntaxException ex ) { throw new IllegalArgumentException ( ex . getMessage ( ) , ex ) ; } } }
Covert file reference to URI . Fixes directory separators and escapes characters .
146
15
25,712
public static URI setFragment ( final URI path , final String fragment ) { try { if ( path . getPath ( ) != null ) { return new URI ( path . getScheme ( ) , path . getUserInfo ( ) , path . getHost ( ) , path . getPort ( ) , path . getPath ( ) , path . getQuery ( ) , fragment ) ; } else { return new URI ( path . getScheme ( ) , path . getSchemeSpecificPart ( ) , fragment ) ; } } catch ( final URISyntaxException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } }
Create new URI with a given fragment .
139
8
25,713
public static URI setPath ( final URI orig , final String path ) { try { return new URI ( orig . getScheme ( ) , orig . getUserInfo ( ) , orig . getHost ( ) , orig . getPort ( ) , path , orig . getQuery ( ) , orig . getFragment ( ) ) ; } catch ( final URISyntaxException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } }
Create new URI with a given path .
98
8
25,714
public static URI setScheme ( final URI orig , final String scheme ) { try { return new URI ( scheme , orig . getUserInfo ( ) , orig . getHost ( ) , orig . getPort ( ) , orig . getPath ( ) , orig . getQuery ( ) , orig . getFragment ( ) ) ; } catch ( final URISyntaxException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } }
Create new URI with a given scheme .
98
8
25,715
public static URI getRelativePath ( final URI base , final URI ref ) { final String baseScheme = base . getScheme ( ) ; final String refScheme = ref . getScheme ( ) ; final String baseAuth = base . getAuthority ( ) ; final String refAuth = ref . getAuthority ( ) ; if ( ! ( ( ( baseScheme == null && refScheme == null ) || ( baseScheme != null && refScheme != null && baseScheme . equals ( refScheme ) ) ) && ( ( baseAuth == null && refAuth == null ) || ( baseAuth != null && refAuth != null && baseAuth . equals ( refAuth ) ) ) ) ) { return ref ; } URI rel ; if ( base . getPath ( ) . equals ( ref . getPath ( ) ) && ref . getFragment ( ) != null ) { rel = toURI ( "" ) ; } else { final StringBuilder upPathBuffer = new StringBuilder ( 128 ) ; final StringBuilder downPathBuffer = new StringBuilder ( 128 ) ; String basePath = base . normalize ( ) . getPath ( ) ; if ( basePath . endsWith ( "/" ) ) { basePath = basePath + "dummy" ; } String refPath = ref . normalize ( ) . getPath ( ) ; final StringTokenizer baseTokenizer = new StringTokenizer ( basePath , URI_SEPARATOR ) ; final StringTokenizer refTokenizer = new StringTokenizer ( refPath , URI_SEPARATOR ) ; while ( baseTokenizer . countTokens ( ) > 1 && refTokenizer . countTokens ( ) > 1 ) { final String baseToken = baseTokenizer . nextToken ( ) ; final String refToken = refTokenizer . nextToken ( ) ; //if OS is Windows, we need to ignore case when comparing path names. final boolean equals = OS_NAME . toLowerCase ( ) . contains ( OS_NAME_WINDOWS ) ? baseToken . equalsIgnoreCase ( refToken ) : baseToken . equals ( refToken ) ; if ( ! equals ) { if ( baseToken . endsWith ( COLON ) || refToken . endsWith ( COLON ) ) { //the two files are in different disks under Windows return ref ; } upPathBuffer . append ( ".." ) ; upPathBuffer . append ( URI_SEPARATOR ) ; downPathBuffer . append ( refToken ) ; downPathBuffer . append ( URI_SEPARATOR ) ; break ; } } while ( baseTokenizer . countTokens ( ) > 1 ) { baseTokenizer . nextToken ( ) ; upPathBuffer . append ( ".." ) ; upPathBuffer . append ( URI_SEPARATOR ) ; } while ( refTokenizer . hasMoreTokens ( ) ) { downPathBuffer . append ( refTokenizer . nextToken ( ) ) ; if ( refTokenizer . hasMoreTokens ( ) ) { downPathBuffer . append ( URI_SEPARATOR ) ; } } upPathBuffer . append ( downPathBuffer ) ; try { rel = new URI ( null , null , upPathBuffer . toString ( ) , null , null ) ; } catch ( final URISyntaxException e ) { throw new IllegalArgumentException ( e ) ; } } return setFragment ( rel , ref . getFragment ( ) ) ; }
Resolves absolute URI against another absolute URI .
721
9
25,716
public static URI setElementID ( final URI relativePath , final String id ) { String topic = getTopicID ( relativePath ) ; if ( topic != null ) { return setFragment ( relativePath , topic + ( id != null ? SLASH + id : "" ) ) ; } else if ( id == null ) { return stripFragment ( relativePath ) ; } else { throw new IllegalArgumentException ( relativePath . toString ( ) ) ; } }
Set the element ID from the path
98
7
25,717
public static String getElementID ( final String relativePath ) { final String fragment = FileUtils . getFragment ( relativePath ) ; if ( fragment != null ) { if ( fragment . lastIndexOf ( SLASH ) != - 1 ) { final String id = fragment . substring ( fragment . lastIndexOf ( SLASH ) + 1 ) ; return id . isEmpty ( ) ? null : id ; } } return null ; }
Retrieve the element ID from the path
92
8
25,718
public static String getTopicID ( final URI relativePath ) { final String fragment = relativePath . getFragment ( ) ; if ( fragment != null ) { final String id = fragment . lastIndexOf ( SLASH ) != - 1 ? fragment . substring ( 0 , fragment . lastIndexOf ( SLASH ) ) : fragment ; return id . isEmpty ( ) ? null : id ; } return null ; }
Retrieve the topic ID from the path
87
8
25,719
@ SuppressWarnings ( "rawtypes" ) public static String join ( final Collection coll , final String delim ) { final StringBuilder buff = new StringBuilder ( 256 ) ; Iterator iter ; if ( ( coll == null ) || coll . isEmpty ( ) ) { return "" ; } iter = coll . iterator ( ) ; while ( iter . hasNext ( ) ) { buff . append ( iter . next ( ) . toString ( ) ) ; if ( iter . hasNext ( ) ) { buff . append ( delim ) ; } } return buff . toString ( ) ; }
Assemble all elements in collection to a string .
124
10
25,720
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public static String join ( final Map value , final String delim ) { if ( value == null || value . isEmpty ( ) ) { return "" ; } final StringBuilder buf = new StringBuilder ( ) ; for ( final Iterator < Map . Entry < String , String > > i = value . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { final Map . Entry < String , String > e = i . next ( ) ; buf . append ( e . getKey ( ) ) . append ( EQUAL ) . append ( e . getValue ( ) ) ; if ( i . hasNext ( ) ) { buf . append ( delim ) ; } } return buf . toString ( ) ; }
Assemble all elements in map to a string .
172
10
25,721
public static String replaceAll ( final String input , final String pattern , final String replacement ) { final StringBuilder result = new StringBuilder ( ) ; int startIndex = 0 ; int newIndex ; while ( ( newIndex = input . indexOf ( pattern , startIndex ) ) >= 0 ) { result . append ( input , startIndex , newIndex ) ; result . append ( replacement ) ; startIndex = newIndex + pattern . length ( ) ; } result . append ( input . substring ( startIndex ) ) ; return result . toString ( ) ; }
Replaces each substring of this string that matches the given string with the given replacement . Differ from the JDK String . replaceAll function this method does not support regular expression based replacement on purpose .
117
41
25,722
public static String setOrAppend ( final String target , final String value , final boolean withSpace ) { if ( target == null ) { return value ; } if ( value == null ) { return target ; } else { if ( withSpace && ! target . endsWith ( STRING_BLANK ) ) { return target + STRING_BLANK + value ; } else { return target + value ; } } }
If target is null return the value ; else append value to target . If withSpace is true insert a blank between them .
87
25
25,723
public static Locale getLocale ( final String anEncoding ) { Locale aLocale = null ; String country = null ; String language = null ; String variant ; //Tokenize the string using "-" as the token string as per IETF RFC4646 (superceeds RFC3066). final StringTokenizer tokenizer = new StringTokenizer ( anEncoding , "-" ) ; //We need to know how many tokens we have so we can create a Locale object with the proper constructor. final int numberOfTokens = tokenizer . countTokens ( ) ; if ( numberOfTokens == 1 ) { final String tempString = tokenizer . nextToken ( ) . toLowerCase ( ) ; //Note: Newer XML parsers should throw an error if the xml:lang value contains //underscore. But this is not guaranteed. //Check to see if some one used "en_US" instead of "en-US". //If so, the first token will contain "en_US" or "xxx_YYYYYYYY". In this case, //we will only grab the value for xxx. final int underscoreIndex = tempString . indexOf ( "_" ) ; if ( underscoreIndex == - 1 ) { language = tempString ; } else if ( underscoreIndex == 2 || underscoreIndex == 3 ) { //check is first subtag is two or three characters in length. language = tempString . substring ( 0 , underscoreIndex ) ; } aLocale = new Locale ( language ) ; } else if ( numberOfTokens == 2 ) { language = tokenizer . nextToken ( ) . toLowerCase ( ) ; final String subtag2 = tokenizer . nextToken ( ) ; //All country tags should be three characters or less. //If the subtag is longer than three characters, it assumes that //is a dialect or variant. if ( subtag2 . length ( ) <= 3 ) { country = subtag2 . toUpperCase ( ) ; aLocale = new Locale ( language , country ) ; } else if ( subtag2 . length ( ) > 3 && subtag2 . length ( ) <= 8 ) { variant = subtag2 ; aLocale = new Locale ( language , "" , variant ) ; } else if ( subtag2 . length ( ) > 8 ) { //return an error! } } else if ( numberOfTokens >= 3 ) { language = tokenizer . nextToken ( ) . toLowerCase ( ) ; final String subtag2 = tokenizer . nextToken ( ) ; if ( subtag2 . length ( ) <= 3 ) { country = subtag2 . toUpperCase ( ) ; } else if ( subtag2 . length ( ) > 3 && subtag2 . length ( ) <= 8 ) { } else if ( subtag2 . length ( ) > 8 ) { //return an error! } variant = tokenizer . nextToken ( ) ; aLocale = new Locale ( language , country , variant ) ; } else { //return an warning or do nothing. //The xml:lang attribute is empty. aLocale = new Locale ( LANGUAGE_EN , COUNTRY_US ) ; } return aLocale ; }
Return a Java Locale object .
684
7
25,724
public static String escapeRegExp ( final String value ) { final StringBuilder buff = new StringBuilder ( ) ; if ( value == null || value . length ( ) == 0 ) { return "" ; } int index = 0 ; // $( )+.[^{\ while ( index < value . length ( ) ) { final char current = value . charAt ( index ) ; switch ( current ) { case ' ' : buff . append ( "\\." ) ; break ; // case '/': // case '|': case ' ' : buff . append ( "[\\\\|/]" ) ; break ; case ' ' : buff . append ( "\\(" ) ; break ; case ' ' : buff . append ( "\\)" ) ; break ; case ' ' : buff . append ( "\\[" ) ; break ; case ' ' : buff . append ( "\\]" ) ; break ; case ' ' : buff . append ( "\\{" ) ; break ; case ' ' : buff . append ( "\\}" ) ; break ; case ' ' : buff . append ( "\\^" ) ; break ; case ' ' : buff . append ( "\\+" ) ; break ; case ' ' : buff . append ( "\\$" ) ; break ; default : buff . append ( current ) ; } index ++ ; } return buff . toString ( ) ; }
Escape regular expression special characters .
284
7
25,725
public static void normalizeAndCollapseWhitespace ( final StringBuilder strBuffer ) { WhiteSpaceState currentState = WhiteSpaceState . WORD ; for ( int i = strBuffer . length ( ) - 1 ; i >= 0 ; i -- ) { final char currentChar = strBuffer . charAt ( i ) ; if ( Character . isWhitespace ( currentChar ) ) { if ( currentState == WhiteSpaceState . SPACE ) { strBuffer . delete ( i , i + 1 ) ; } else if ( currentChar != ' ' ) { strBuffer . replace ( i , i + 1 , " " ) ; } currentState = WhiteSpaceState . SPACE ; } else { currentState = WhiteSpaceState . WORD ; } } }
Normalize and collapse whitespaces from string buffer .
158
10
25,726
public static Collection < String > split ( final String value ) { if ( value == null ) { return Collections . emptyList ( ) ; } final String [ ] tokens = value . trim ( ) . split ( "\\s+" ) ; return asList ( tokens ) ; }
Split string by whitespace .
58
6
25,727
@ Override public AbstractPipelineOutput execute ( final AbstractPipelineInput input ) throws DITAOTException { if ( logger == null ) { throw new IllegalStateException ( "Logger not set" ) ; } final Collection < FileInfo > images = job . getFileInfo ( f -> ATTR_FORMAT_VALUE_IMAGE . equals ( f . format ) || ATTR_FORMAT_VALUE_HTML . equals ( f . format ) ) ; if ( ! images . isEmpty ( ) ) { final File outputDir = new File ( input . getAttribute ( ANT_INVOKER_EXT_PARAM_OUTPUTDIR ) ) ; final ImageMetadataFilter writer = new ImageMetadataFilter ( outputDir , job ) ; writer . setLogger ( logger ) ; writer . setJob ( job ) ; final Predicate < FileInfo > filter = fileInfoFilter != null ? fileInfoFilter : f -> ! f . isResourceOnly && ATTR_FORMAT_VALUE_DITA . equals ( f . format ) ; for ( final FileInfo f : job . getFileInfo ( filter ) ) { writer . write ( new File ( job . tempDir , f . file . getPath ( ) ) . getAbsoluteFile ( ) ) ; } storeImageFormat ( writer . getImages ( ) , outputDir ) ; try { job . write ( ) ; } catch ( IOException e ) { throw new DITAOTException ( "Failed to serialize job configuration: " + e . getMessage ( ) , e ) ; } } return null ; }
Entry point of image metadata ModuleElem .
340
9
25,728
public static final String idFromName ( String name ) { Transliterator tr = Transliterator . getInstance ( "Any-Latin; Latin-ASCII" ) ; //$NON-NLS-1$ return removeNonWord ( tr . transliterate ( name ) ) ; }
Creates a bean id from the given bean name .
62
11
25,729
private HttpEngine getResponse ( ) throws IOException { initHttpEngine ( ) ; if ( httpEngine . hasResponse ( ) ) { return httpEngine ; } while ( true ) { if ( ! execute ( true ) ) { continue ; } Response response = httpEngine . getResponse ( ) ; Request followUp = httpEngine . followUpRequest ( ) ; if ( followUp == null ) { httpEngine . releaseConnection ( ) ; return httpEngine ; } if ( ++ followUpCount > HttpEngine . MAX_FOLLOW_UPS ) { throw new ProtocolException ( "Too many follow-up requests: " + followUpCount ) ; } // The first request was insufficient. Prepare for another... url = followUp . url ( ) ; requestHeaders = followUp . headers ( ) . newBuilder ( ) ; // Although RFC 2616 10.3.2 specifies that a HTTP_MOVED_PERM redirect // should keep the same method, Chrome, Firefox and the RI all issue GETs // when following any redirect. Sink requestBody = httpEngine . getRequestBody ( ) ; if ( ! followUp . method ( ) . equals ( method ) ) { requestBody = null ; } if ( requestBody != null && ! ( requestBody instanceof RetryableSink ) ) { throw new HttpRetryException ( "Cannot retry streamed HTTP body" , responseCode ) ; } if ( ! httpEngine . sameConnection ( followUp . url ( ) ) ) { httpEngine . releaseConnection ( ) ; } Connection connection = httpEngine . close ( ) ; httpEngine = newHttpEngine ( followUp . method ( ) , connection , ( RetryableSink ) requestBody , response ) ; } }
Aggressively tries to get the final HTTP response potentially making many HTTP requests in the process in order to cope with redirects and authentication .
366
28
25,730
private boolean execute ( boolean readResponse ) throws IOException { try { httpEngine . sendRequest ( ) ; route = httpEngine . getRoute ( ) ; handshake = httpEngine . getConnection ( ) != null ? httpEngine . getConnection ( ) . getHandshake ( ) : null ; if ( readResponse ) { httpEngine . readResponse ( ) ; } return true ; } catch ( RequestException e ) { // An attempt to interpret a request failed. IOException toThrow = e . getCause ( ) ; httpEngineFailure = toThrow ; throw toThrow ; } catch ( RouteException e ) { // The attempt to connect via a route failed. The request will not have been sent. HttpEngine retryEngine = httpEngine . recover ( e ) ; if ( retryEngine != null ) { httpEngine = retryEngine ; return false ; } // Give up; recovery is not possible. IOException toThrow = e . getLastConnectException ( ) ; httpEngineFailure = toThrow ; throw toThrow ; } catch ( IOException e ) { // An attempt to communicate with a server failed. The request may have been sent. HttpEngine retryEngine = httpEngine . recover ( e ) ; if ( retryEngine != null ) { httpEngine = retryEngine ; return false ; } // Give up; recovery is not possible. httpEngineFailure = e ; throw e ; } }
Sends a request and optionally reads a response . Returns true if the request was successfully executed and false if the request can be retried . Throws an exception if the request failed permanently .
293
38
25,731
@ Override public void close ( IAsyncResultHandler < Void > result ) { vertx . executeBlocking ( blocking -> { super . close ( result ) ; } , res -> { if ( res . failed ( ) ) result . handle ( AsyncResultImpl . create ( res . cause ( ) ) ) ; } ) ; }
Indicates whether connection was successfully closed .
70
8
25,732
public static void reloadData ( IAsyncHandler < Void > doneHandler ) { synchronized ( URILoadingRegistry . class ) { if ( instance == null ) { doneHandler . handle ( ( Void ) null ) ; return ; } Map < URILoadingRegistry , IAsyncResultHandler < Void > > regs = instance . handlers ; Vertx vertx = instance . vertx ; URI uri = instance . uri ; Map < String , String > config = instance . config ; AtomicInteger ctr = new AtomicInteger ( regs . size ( ) ) ; OneShotURILoader newLoader = new OneShotURILoader ( vertx , uri , config ) ; regs . entrySet ( ) . stream ( ) . forEach ( pair -> { // Clear the registrys' internal maps to prepare for reload. // NB: If we add production hot reloading, we'll need to work around this (e.g. clone?). pair . getKey ( ) . getMap ( ) . clear ( ) ; // Re-subscribe the registry. newLoader . subscribe ( pair . getKey ( ) , result -> { checkAndFlip ( ctr . decrementAndGet ( ) , newLoader , doneHandler ) ; } ) ; } ) ; checkAndFlip ( ctr . get ( ) , newLoader , doneHandler ) ; } }
For testing only . Reloads rather than full restart .
291
11
25,733
protected void doQuotaExceededFailure ( final IPolicyContext context , final TransferQuotaConfig config , final IPolicyChain < ? > chain , RateLimitResponse rtr ) { Map < String , String > responseHeaders = RateLimitingPolicy . responseHeaders ( config , rtr , defaultLimitHeader ( ) , defaultRemainingHeader ( ) , defaultResetHeader ( ) ) ; IPolicyFailureFactoryComponent failureFactory = context . getComponent ( IPolicyFailureFactoryComponent . class ) ; PolicyFailure failure = limitExceededFailure ( failureFactory ) ; failure . getHeaders ( ) . putAll ( responseHeaders ) ; chain . doFailure ( failure ) ; }
Called to send a quota exceeded failure .
145
9
25,734
public static boolean isConstraintViolation ( Exception e ) { Throwable cause = e ; while ( cause != cause . getCause ( ) && cause . getCause ( ) != null ) { if ( cause . getClass ( ) . getSimpleName ( ) . equals ( "ConstraintViolationException" ) ) //$NON-NLS-1$ return true ; cause = cause . getCause ( ) ; } return false ; }
Returns true if the given exception is a unique constraint violation . This is useful to detect whether someone is trying to persist an entity that already exists . It allows us to simply assume that persisting a new entity will work without first querying the DB for the existence of that entity .
95
56
25,735
public static void rollbackQuietly ( EntityManager entityManager ) { if ( entityManager . getTransaction ( ) . isActive ( ) /* && entityManager.getTransaction().getRollbackOnly()*/ ) { try { entityManager . getTransaction ( ) . rollback ( ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } } }
Rolls back a transaction . Tries to be smart and quiet about it .
84
16
25,736
public String getConfigProperty ( String propertyName , String defaultValue ) { return getConfig ( ) . getString ( propertyName , defaultValue ) ; }
Returns the given configuration property name or the provided default value if not found .
32
15
25,737
private IndexedPermissions loadPermissions ( ) { String userId = getCurrentUser ( ) ; try { return new IndexedPermissions ( getQuery ( ) . getPermissions ( userId ) ) ; } catch ( StorageException e ) { logger . error ( Messages . getString ( "AbstractSecurityContext.ErrorLoadingPermissions" ) + userId , e ) ; //$NON-NLS-1$ return new IndexedPermissions ( new HashSet <> ( ) ) ; } }
Loads the current user s permissions into a thread local variable .
107
13
25,738
@ SuppressWarnings ( "nls" ) protected DataSource datasourceFromConfig ( JdbcOptionsBean config ) { Properties props = new Properties ( ) ; props . putAll ( config . getDsProperties ( ) ) ; setConfigProperty ( props , "jdbcUrl" , config . getJdbcUrl ( ) ) ; setConfigProperty ( props , "username" , config . getUsername ( ) ) ; setConfigProperty ( props , "password" , config . getPassword ( ) ) ; setConfigProperty ( props , "connectionTimeout" , config . getConnectionTimeout ( ) ) ; setConfigProperty ( props , "idleTimeout" , config . getIdleTimeout ( ) ) ; setConfigProperty ( props , "maxPoolSize" , config . getMaximumPoolSize ( ) ) ; setConfigProperty ( props , "maxLifetime" , config . getMaxLifetime ( ) ) ; setConfigProperty ( props , "minIdle" , config . getMinimumIdle ( ) ) ; setConfigProperty ( props , "poolName" , config . getPoolName ( ) ) ; setConfigProperty ( props , "autoCommit" , config . isAutoCommit ( ) ) ; HikariConfig hikariConfig = new HikariConfig ( props ) ; return new HikariDataSource ( hikariConfig ) ; }
Creates a datasource from the given jdbc config info .
295
14
25,739
private void setConfigProperty ( Properties props , String propName , Object value ) { if ( value != null ) { props . setProperty ( propName , String . valueOf ( value ) ) ; } }
Sets a configuration property but only if it s not null .
43
13
25,740
private ResourceBundle getBundle ( ) { String bundleKey = getBundleKey ( ) ; if ( bundles . containsKey ( bundleKey ) ) { return bundles . get ( bundleKey ) ; } else { ResourceBundle bundle = loadBundle ( ) ; bundles . put ( bundleKey , bundle ) ; return bundle ; } }
Gets a bundle . First tries to find one in the cache then loads it if it can t find one .
71
23
25,741
private ResourceBundle loadBundle ( ) { String pkg = clazz . getPackage ( ) . getName ( ) ; Locale locale = getLocale ( ) ; return PropertyResourceBundle . getBundle ( pkg + ".messages" , locale , clazz . getClassLoader ( ) , new ResourceBundle . Control ( ) { //$NON-NLS-1$ @ Override public List < String > getFormats ( String baseName ) { return FORMATS ; } } ) ; }
Loads the resource bundle .
111
6
25,742
public String format ( String key , Object ... params ) { ResourceBundle bundle = getBundle ( ) ; if ( bundle . containsKey ( key ) ) { String msg = bundle . getString ( key ) ; return MessageFormat . format ( msg , params ) ; } else { return MessageFormat . format ( "!!{0}!!" , key ) ; //$NON-NLS-1$ } }
Look up a message in the i18n resource message bundle by key then format the message with the given params and return the result .
87
27
25,743
@ SuppressWarnings ( "nls" ) public void listDatabases ( final IAsyncResultHandler < List < String > > handler ) { IHttpClientRequest request = httpClient . request ( queryUrl . toString ( ) , HttpMethod . GET , result -> { try { if ( result . isError ( ) || result . getResult ( ) . getResponseCode ( ) != 200 ) { handleError ( result , handler ) ; return ; } List < String > results = new ArrayList <> ( ) ; // {"results": JsonNode arrNode = objectMapper . readTree ( result . getResult ( ) . getBody ( ) ) . path ( "results" ) . elements ( ) . next ( ) // results: [ first-elem . path ( "series" ) . elements ( ) . next ( ) ; // series: [ first-elem // values: [[db1], [db2], [...]] => db1, db2 flattenArrays ( arrNode . get ( "values" ) , results ) ; // send results handler . handle ( AsyncResultImpl . create ( results ) ) ; } catch ( IOException e ) { AsyncResultImpl . create ( new RuntimeException ( "Unable to parse Influx JSON response" , e ) ) ; } } ) ; request . end ( ) ; }
List all databases
289
3
25,744
@ SuppressWarnings ( "unchecked" ) private static < T > T createCustomComponent ( Class < T > componentType , Class < ? > componentClass , Map < String , String > configProperties ) throws Exception { if ( componentClass == null ) { throw new IllegalArgumentException ( "Invalid component spec (class not found)." ) ; //$NON-NLS-1$ } try { Constructor < ? > constructor = componentClass . getConstructor ( Map . class ) ; return ( T ) constructor . newInstance ( configProperties ) ; } catch ( Exception e ) { } return ( T ) componentClass . getConstructor ( ) . newInstance ( ) ; }
Creates a custom component from a loaded class .
148
10
25,745
private static DataSource lookupDS ( String dsJndiLocation ) { DataSource ds ; try { InitialContext ctx = new InitialContext ( ) ; ds = ( DataSource ) ctx . lookup ( dsJndiLocation ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } if ( ds == null ) { throw new RuntimeException ( "Datasource not found: " + dsJndiLocation ) ; //$NON-NLS-1$ } return ds ; }
Lookup the datasource in JNDI .
116
10
25,746
protected File createWorkDir ( File pluginArtifactFile ) throws IOException { File tempDir = File . createTempFile ( pluginArtifactFile . getName ( ) , "" ) ; tempDir . delete ( ) ; tempDir . mkdirs ( ) ; return tempDir ; }
Creates a work directory into which various resources discovered in the plugin artifact can be extracted .
60
18
25,747
private void indexPluginArtifact ( ) throws IOException { dependencyZips = new ArrayList <> ( ) ; Enumeration < ? extends ZipEntry > entries = this . pluginArtifactZip . entries ( ) ; while ( entries . hasMoreElements ( ) ) { ZipEntry zipEntry = entries . nextElement ( ) ; if ( zipEntry . getName ( ) . startsWith ( "WEB-INF/lib/" ) && zipEntry . getName ( ) . toLowerCase ( ) . endsWith ( ".jar" ) ) { ZipFile dependencyZipFile = extractDependency ( zipEntry ) ; if ( dependencyZipFile != null ) { dependencyZips . add ( dependencyZipFile ) ; } } } }
Indexes the content of the plugin artifact . This includes discovering all of the dependency JARs as well as any configuration resources such as plugin definitions .
156
30
25,748
protected InputStream findClassContent ( String className ) throws IOException { String primaryArtifactEntryName = "WEB-INF/classes/" + className . replace ( ' ' , ' ' ) + ".class" ; String dependencyEntryName = className . replace ( ' ' , ' ' ) + ".class" ; ZipEntry entry = this . pluginArtifactZip . getEntry ( primaryArtifactEntryName ) ; if ( entry != null ) { return this . pluginArtifactZip . getInputStream ( entry ) ; } for ( ZipFile zipFile : this . dependencyZips ) { entry = zipFile . getEntry ( dependencyEntryName ) ; if ( entry != null ) { return zipFile . getInputStream ( entry ) ; } } return null ; }
Searches the plugin artifact ZIP and all dependency ZIPs for a zip entry for the given fully qualified class name .
164
24
25,749
public void close ( ) throws IOException { if ( closed ) { return ; } this . pluginArtifactZip . close ( ) ; for ( ZipFile zipFile : this . dependencyZips ) { zipFile . close ( ) ; } closed = true ; }
Closes any resources the plugin classloader is holding open .
55
12
25,750
protected PluginClassLoader createPluginClassLoader ( final File pluginFile ) throws IOException { return new PluginClassLoader ( pluginFile , Thread . currentThread ( ) . getContextClassLoader ( ) ) { @ Override protected File createWorkDir ( File pluginArtifactFile ) throws IOException { File workDir = new File ( pluginFile . getParentFile ( ) , ".work" ) ; //$NON-NLS-1$ workDir . mkdirs ( ) ; return workDir ; } } ; }
Creates a plugin classloader for the given plugin file .
109
12
25,751
protected Client getClientInternal ( String idx ) { Client client ; synchronized ( mutex ) { client = ( Client ) getMap ( ) . get ( idx ) ; } return client ; }
Gets the client and returns it .
41
8
25,752
private String getClientIndex ( Client client ) { return getClientIndex ( client . getOrganizationId ( ) , client . getClientId ( ) , client . getVersion ( ) ) ; }
Generates an in - memory key for an client used to index the client for later quick retrieval .
41
20
25,753
protected List < ContractSummaryBean > getClientContractsInternal ( String organizationId , String clientId , String version ) throws StorageException { List < ContractSummaryBean > rval = new ArrayList <> ( ) ; EntityManager entityManager = getActiveEntityManager ( ) ; String jpql = "SELECT c from ContractBean c " + " JOIN c.client clientv " + " JOIN clientv.client client " + " JOIN client.organization aorg" + " WHERE client.id = :clientId " + " AND aorg.id = :orgId " + " AND clientv.version = :version " + " ORDER BY aorg.id, client.id ASC" ; Query query = entityManager . createQuery ( jpql ) ; query . setParameter ( "orgId" , organizationId ) ; //$NON-NLS-1$ query . setParameter ( "clientId" , clientId ) ; //$NON-NLS-1$ query . setParameter ( "version" , version ) ; //$NON-NLS-1$ List < ContractBean > contracts = query . getResultList ( ) ; for ( ContractBean contractBean : contracts ) { ClientBean client = contractBean . getClient ( ) . getClient ( ) ; ApiBean api = contractBean . getApi ( ) . getApi ( ) ; PlanBean plan = contractBean . getPlan ( ) . getPlan ( ) ; OrganizationBean clientOrg = entityManager . find ( OrganizationBean . class , client . getOrganization ( ) . getId ( ) ) ; OrganizationBean apiOrg = entityManager . find ( OrganizationBean . class , api . getOrganization ( ) . getId ( ) ) ; ContractSummaryBean csb = new ContractSummaryBean ( ) ; csb . setClientId ( client . getId ( ) ) ; csb . setClientOrganizationId ( client . getOrganization ( ) . getId ( ) ) ; csb . setClientOrganizationName ( clientOrg . getName ( ) ) ; csb . setClientName ( client . getName ( ) ) ; csb . setClientVersion ( contractBean . getClient ( ) . getVersion ( ) ) ; csb . setContractId ( contractBean . getId ( ) ) ; csb . setCreatedOn ( contractBean . getCreatedOn ( ) ) ; csb . setPlanId ( plan . getId ( ) ) ; csb . setPlanName ( plan . getName ( ) ) ; csb . setPlanVersion ( contractBean . getPlan ( ) . getVersion ( ) ) ; csb . setApiDescription ( api . getDescription ( ) ) ; csb . setApiId ( api . getId ( ) ) ; csb . setApiName ( api . getName ( ) ) ; csb . setApiOrganizationId ( apiOrg . getId ( ) ) ; csb . setApiOrganizationName ( apiOrg . getName ( ) ) ; csb . setApiVersion ( contractBean . getApi ( ) . getVersion ( ) ) ; rval . add ( csb ) ; } return rval ; }
Returns a list of all contracts for the given client .
707
11
25,754
public static void main ( String [ ] args ) { File from ; File to ; if ( args . length < 2 ) { System . out . println ( "Usage: DataMigrator <pathToSourceFile> <pathToDestFile>" ) ; //$NON-NLS-1$ return ; } String frompath = args [ 0 ] ; String topath = args [ 1 ] ; from = new File ( frompath ) ; to = new File ( topath ) ; System . out . println ( "Starting data migration." ) ; //$NON-NLS-1$ System . out . println ( " From: " + from ) ; //$NON-NLS-1$ System . out . println ( " To: " + to ) ; //$NON-NLS-1$ DataMigrator migrator = new DataMigrator ( ) ; migrator . setLogger ( new SystemOutLogger ( ) ) ; Version version = new Version ( ) ; version . postConstruct ( ) ; migrator . setVersion ( version ) ; migrator . migrate ( from , to ) ; }
Main method - used when running the data migrator in standalone mode .
238
14
25,755
public static Object readPrimitive ( Class < ? > clazz , String value ) throws Exception { if ( clazz == String . class ) { return value ; } else if ( clazz == Long . class ) { return Long . parseLong ( value ) ; } else if ( clazz == Integer . class ) { return Integer . parseInt ( value ) ; } else if ( clazz == Double . class ) { return Double . parseDouble ( value ) ; } else if ( clazz == Boolean . class ) { return Boolean . parseBoolean ( value ) ; } else if ( clazz == Byte . class ) { return Byte . parseByte ( value ) ; } else if ( clazz == Short . class ) { return Short . parseShort ( value ) ; } else if ( clazz == Float . class ) { return Float . parseFloat ( value ) ; } else { throw new Exception ( "Unsupported primitive: " + clazz ) ; //$NON-NLS-1$ } }
Parses the String value as a primitive or a String depending on its type .
211
17
25,756
protected Object readPrimitive ( JestResult result ) throws Exception { PrimitiveBean pb = result . getSourceAsObject ( PrimitiveBean . class ) ; String value = pb . getValue ( ) ; Class < ? > c = Class . forName ( pb . getType ( ) ) ; return BackingStoreUtil . readPrimitive ( c , value ) ; }
Reads a stored primitive .
84
6
25,757
private void connect ( ) { try { URL url = new URL ( this . endpoint ) ; connection = ( HttpURLConnection ) url . openConnection ( ) ; connection . setReadTimeout ( this . readTimeoutMs ) ; connection . setConnectTimeout ( this . connectTimeoutMs ) ; connection . setRequestMethod ( this . method . name ( ) ) ; if ( method == HttpMethod . POST || method == HttpMethod . PUT ) { connection . setDoOutput ( true ) ; } else { connection . setDoOutput ( false ) ; } connection . setDoInput ( true ) ; connection . setUseCaches ( false ) ; for ( String headerName : headers . keySet ( ) ) { String headerValue = headers . get ( headerName ) ; connection . setRequestProperty ( headerName , headerValue ) ; } connection . connect ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Connect to the remote server .
199
6
25,758
private static String convertPattern ( ProxyRule bean ) { String str = bean . getPattern ( ) . replaceAll ( "\\{.+?\\}" , "([^/&?]*)" ) ; // /foo/{bar}/{baz} => /foo/([^\/&?]*)/([^/&?]*).* return str . endsWith ( "$" ) ? str : str + ".*" ; // Implicitly other stuff on end unless $ explicitly specified (see description) }
slash ampersand or question mark .
109
9
25,759
public static final void validateSearchCriteria ( SearchCriteriaBean criteria ) throws InvalidSearchCriteriaException { if ( criteria . getPaging ( ) != null ) { if ( criteria . getPaging ( ) . getPage ( ) < 1 ) { throw new InvalidSearchCriteriaException ( Messages . i18n . format ( "SearchCriteriaUtil.MissingPage" ) ) ; //$NON-NLS-1$ } if ( criteria . getPaging ( ) . getPageSize ( ) < 1 ) { throw new InvalidSearchCriteriaException ( Messages . i18n . format ( "SearchCriteriaUtil.MissingPageSize" ) ) ; //$NON-NLS-1$ } } int count = 1 ; for ( SearchCriteriaFilterBean filter : criteria . getFilters ( ) ) { if ( filter . getName ( ) == null || filter . getName ( ) . trim ( ) . length ( ) == 0 ) { throw new InvalidSearchCriteriaException ( Messages . i18n . format ( "SearchCriteriaUtil.MissingSearchFilterName" , count ) ) ; //$NON-NLS-1$ } if ( filter . getValue ( ) == null || filter . getValue ( ) . trim ( ) . length ( ) == 0 ) { throw new InvalidSearchCriteriaException ( Messages . i18n . format ( "SearchCriteriaUtil.MissingSearchFilterValue" , count ) ) ; //$NON-NLS-1$ } if ( filter . getOperator ( ) == null || ! validOperators . contains ( filter . getOperator ( ) ) ) { throw new InvalidSearchCriteriaException ( Messages . i18n . format ( "SearchCriteriaUtil.MissingSearchFilterOperator" , count ) ) ; //$NON-NLS-1$ } count ++ ; } if ( criteria . getOrderBy ( ) != null && ( criteria . getOrderBy ( ) . getName ( ) == null || criteria . getOrderBy ( ) . getName ( ) . trim ( ) . length ( ) == 0 ) ) { throw new InvalidSearchCriteriaException ( Messages . i18n . format ( "SearchCriteriaUtil.MissingOrderByName" ) ) ; //$NON-NLS-1$ } }
Validates that the search criteria bean is complete and makes sense .
499
13
25,760
public static < T > void callIfExists ( T object , String methodName ) throws SecurityException , IllegalAccessException , IllegalArgumentException , InvocationTargetException { try { Method method = object . getClass ( ) . getMethod ( methodName ) ; method . invoke ( object ) ; } catch ( NoSuchMethodException e ) { } }
Call a method if it exists . Use very sparingly and generally prefer interfaces .
74
16
25,761
public static Class < ? > loadClass ( String classname ) { Class < ? > c = null ; // First try a simple Class.forName() try { c = Class . forName ( classname ) ; } catch ( ClassNotFoundException e ) { } // Didn't work? Try using this class's classloader. if ( c == null ) { try { c = ReflectionUtils . class . getClassLoader ( ) . loadClass ( classname ) ; } catch ( ClassNotFoundException e ) { } } // Still didn't work? Try the thread's context classloader. if ( c == null ) { try { c = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( classname ) ; } catch ( ClassNotFoundException e ) { } } return c ; }
Loads a class .
174
5
25,762
public static Method findSetter ( Class < ? > onClass , Class < ? > targetClass ) { Method [ ] methods = onClass . getMethods ( ) ; for ( Method method : methods ) { Class < ? > [ ] ptypes = method . getParameterTypes ( ) ; if ( method . getName ( ) . startsWith ( "set" ) && ptypes . length == 1 && ptypes [ 0 ] == targetClass ) { //$NON-NLS-1$ return method ; } } return null ; }
Squishy way to find a setter method .
113
10
25,763
private IJdbcClient createClient ( IPolicyContext context , JDBCIdentitySource config ) throws Throwable { IJdbcComponent jdbcComponent = context . getComponent ( IJdbcComponent . class ) ; if ( config . getType ( ) == JDBCType . datasource || config . getType ( ) == null ) { DataSource ds = lookupDatasource ( config ) ; return jdbcComponent . create ( ds ) ; } if ( config . getType ( ) == JDBCType . url ) { JdbcOptionsBean options = new JdbcOptionsBean ( ) ; options . setJdbcUrl ( config . getJdbcUrl ( ) ) ; options . setUsername ( config . getUsername ( ) ) ; options . setPassword ( config . getPassword ( ) ) ; options . setAutoCommit ( true ) ; return jdbcComponent . createStandalone ( options ) ; } throw new Exception ( "Unknown JDBC options." ) ; //$NON-NLS-1$ }
Creates the appropriate jdbc client .
230
9
25,764
@ SuppressWarnings ( "javadoc" ) public static < T > T getSingleService ( Class < T > serviceInterface ) throws IllegalStateException { // Cached single service values are derived from the values cached when checking // for multiple services T rval = null ; Set < T > services = getServices ( serviceInterface ) ; if ( services . size ( ) > 1 ) { throw new IllegalStateException ( "Multiple implementations found of " + serviceInterface ) ; //$NON-NLS-1$ } else if ( ! services . isEmpty ( ) ) { rval = services . iterator ( ) . next ( ) ; } return rval ; }
Gets a single service by its interface .
143
9
25,765
@ SuppressWarnings ( "unchecked" ) public static < T > Set < T > getServices ( Class < T > serviceInterface ) { synchronized ( servicesCache ) { if ( servicesCache . containsKey ( serviceInterface ) ) { return ( Set < T > ) servicesCache . get ( serviceInterface ) ; } Set < T > services = new LinkedHashSet <> ( ) ; try { for ( T service : ServiceLoader . load ( serviceInterface ) ) { services . add ( service ) ; } } catch ( ServiceConfigurationError sce ) { // No services found - don't check again. } servicesCache . put ( serviceInterface , services ) ; return services ; } }
Get a set of service implementations for a given interface .
146
11
25,766
protected static URL findConfigUrlInDirectory ( File directory , String configName ) { if ( directory . isDirectory ( ) ) { File cfile = new File ( directory , configName ) ; if ( cfile . isFile ( ) ) { try { return cfile . toURI ( ) . toURL ( ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } } return null ; }
Returns a URL to a file with the given name inside the given directory .
94
15
25,767
private boolean canProcessRequest ( TimeRestrictedAccessConfig config , String destination ) { if ( destination == null || destination . trim ( ) . length ( ) == 0 ) { destination = "/" ; //$NON-NLS-1$ } List < TimeRestrictedAccess > rulesEnabledForPath = getRulesMatchingPath ( config , destination ) ; if ( rulesEnabledForPath . size ( ) != 0 ) { DateTime currentTime = new DateTime ( DateTimeZone . UTC ) ; for ( TimeRestrictedAccess rule : rulesEnabledForPath ) { boolean matchesDay = matchesDay ( currentTime , rule ) ; if ( matchesDay ) { boolean matchesTime = matchesTime ( rule ) ; if ( matchesTime ) { return true ; } } } return false ; } return true ; }
Evaluates whether the destination provided matches any of the configured pathsToIgnore and matches specified time range .
168
22
25,768
protected String getRemoteAddr ( ApiRequest request , IPListConfig config ) { String httpHeader = config . getHttpHeader ( ) ; if ( httpHeader != null && httpHeader . trim ( ) . length ( ) > 0 ) { String value = ( String ) request . getHeaders ( ) . get ( httpHeader ) ; if ( value != null ) { return value ; } } return request . getRemoteAddr ( ) ; }
Gets the remote address for comparison .
94
8
25,769
protected boolean isMatch ( IPListConfig config , String remoteAddr ) { if ( config . getIpList ( ) . contains ( remoteAddr ) ) { return true ; } try { String [ ] remoteAddrSplit = remoteAddr . split ( "\\." ) ; //$NON-NLS-1$ for ( String ip : config . getIpList ( ) ) { String [ ] ipSplit = ip . split ( "\\." ) ; //$NON-NLS-1$ if ( remoteAddrSplit . length == ipSplit . length ) { int numParts = ipSplit . length ; boolean matches = true ; for ( int idx = 0 ; idx < numParts ; idx ++ ) { if ( ipSplit [ idx ] . equals ( "*" ) || ipSplit [ idx ] . equals ( remoteAddrSplit [ idx ] ) ) { //$NON-NLS-1$ // This component matches! } else { matches = false ; break ; } } if ( matches ) { return true ; } } } } catch ( Throwable t ) { // eat it } return false ; }
Returns true if the remote address is a match for the configured values in the IP List .
247
18
25,770
private static File getPluginDir ( ) { String dataDirPath = System . getProperty ( "catalina.home" ) ; //$NON-NLS-1$ File dataDir = new File ( dataDirPath , "data" ) ; //$NON-NLS-1$ if ( ! dataDir . getParentFile ( ) . isDirectory ( ) ) { throw new RuntimeException ( "Failed to find Tomcat home at: " + dataDirPath ) ; //$NON-NLS-1$ } if ( ! dataDir . exists ( ) ) { dataDir . mkdir ( ) ; } File pluginsDir = new File ( dataDir , "apiman/plugins" ) ; //$NON-NLS-1$ return pluginsDir ; }
Creates the directory to use for the plugin registry . The location of the plugin registry is in the tomcat data directory .
168
25
25,771
private IAsyncResultHandler < IEngineResult > wrapResultHandler ( final IAsyncResultHandler < IEngineResult > handler ) { return ( IAsyncResult < IEngineResult > result ) -> { boolean doRecord = true ; if ( result . isError ( ) ) { recordErrorMetrics ( result . getError ( ) ) ; } else { IEngineResult engineResult = result . getResult ( ) ; if ( engineResult . isFailure ( ) ) { recordFailureMetrics ( engineResult . getPolicyFailure ( ) ) ; } else { recordSuccessMetrics ( engineResult . getApiResponse ( ) ) ; doRecord = false ; // don't record the metric now because we need to record # of bytes downloaded, which hasn't happened yet } } requestMetric . setRequestEnd ( new Date ( ) ) ; if ( doRecord ) { metrics . record ( requestMetric ) ; } handler . handle ( result ) ; } ; }
Wraps the result handler so that metrics can be properly recorded .
200
13
25,772
protected void recordSuccessMetrics ( ApiResponse response ) { requestMetric . setResponseCode ( response . getCode ( ) ) ; requestMetric . setResponseMessage ( response . getMessage ( ) ) ; }
Record success metrics
46
3
25,773
protected void recordFailureMetrics ( PolicyFailure failure ) { requestMetric . setResponseCode ( failure . getResponseCode ( ) ) ; requestMetric . setFailure ( true ) ; requestMetric . setFailureCode ( failure . getFailureCode ( ) ) ; requestMetric . setFailureReason ( failure . getMessage ( ) ) ; }
Record failure metrics
73
3
25,774
protected void resolvePropertyReplacements ( Api api ) { if ( api == null ) { return ; } String endpoint = api . getEndpoint ( ) ; endpoint = resolveProperties ( endpoint ) ; api . setEndpoint ( endpoint ) ; Map < String , String > properties = api . getEndpointProperties ( ) ; for ( Entry < String , String > entry : properties . entrySet ( ) ) { String value = entry . getValue ( ) ; value = resolveProperties ( value ) ; entry . setValue ( value ) ; } resolvePropertyReplacements ( api . getApiPolicies ( ) ) ; }
Response API property replacements
133
4
25,775
protected void resolvePropertyReplacements ( ApiContract apiContract ) { if ( apiContract == null ) { return ; } Api api = apiContract . getApi ( ) ; if ( api != null ) { resolvePropertyReplacements ( api ) ; } resolvePropertyReplacements ( apiContract . getPolicies ( ) ) ; }
Resolve contract property replacements
71
5
25,776
private void resolvePropertyReplacements ( List < Policy > apiPolicies ) { if ( apiPolicies != null ) { for ( Policy policy : apiPolicies ) { String config = policy . getPolicyJsonConfig ( ) ; config = resolveProperties ( config ) ; policy . setPolicyJsonConfig ( config ) ; } } }
Resolve property replacements for list of policies
74
8
25,777
private String resolveProperties ( String value ) { if ( value . contains ( "${" ) ) { //$NON-NLS-1$ return PROPERTY_SUBSTITUTOR . replace ( value ) ; } else { return value ; } }
Resolve a property
56
4
25,778
protected void validateRequest ( ApiRequest request ) throws InvalidContractException { ApiContract contract = request . getContract ( ) ; boolean matches = true ; if ( ! contract . getApi ( ) . getOrganizationId ( ) . equals ( request . getApiOrgId ( ) ) ) { matches = false ; } if ( ! contract . getApi ( ) . getApiId ( ) . equals ( request . getApiId ( ) ) ) { matches = false ; } if ( ! contract . getApi ( ) . getVersion ( ) . equals ( request . getApiVersion ( ) ) ) { matches = false ; } if ( ! matches ) { throw new InvalidContractException ( Messages . i18n . format ( "EngineImpl.InvalidContractForApi" , //$NON-NLS-1$ request . getApiOrgId ( ) , request . getApiId ( ) , request . getApiVersion ( ) ) ) ; } }
Validates that the contract being used for the request is valid against the api information included in the request . Basically the request includes information indicating which specific api is being invoked . This method ensures that the api information in the contract matches the requested api .
212
49
25,779
private IAsyncResultHandler < IApiConnectionResponse > createApiConnectionResponseHandler ( ) { return ( IAsyncResult < IApiConnectionResponse > result ) -> { if ( result . isSuccess ( ) ) { requestMetric . setApiEnd ( new Date ( ) ) ; // The result came back. NB: still need to put it through the response chain. apiConnectionResponse = result . getResult ( ) ; ApiResponse apiResponse = apiConnectionResponse . getHead ( ) ; context . setAttribute ( "apiman.engine.apiResponse" , apiResponse ) ; //$NON-NLS-1$ // Execute the response chain to evaluate the response. responseChain = createResponseChain ( ( ApiResponse response ) -> { // Send the api response to the caller. final EngineResultImpl engineResult = new EngineResultImpl ( response ) ; engineResult . setConnectorResponseStream ( apiConnectionResponse ) ; resultHandler . handle ( AsyncResultImpl . create ( engineResult ) ) ; // We've come all the way through the response chain successfully responseChain . bodyHandler ( buffer -> { requestMetric . setBytesDownloaded ( requestMetric . getBytesDownloaded ( ) + buffer . length ( ) ) ; engineResult . write ( buffer ) ; } ) ; responseChain . endHandler ( isEnd -> { engineResult . end ( ) ; finished = true ; metrics . record ( requestMetric ) ; } ) ; // Signal to the connector that it's safe to start transmitting data. apiConnectionResponse . transmit ( ) ; } ) ; // Write data from the back-end response into the response chain. apiConnectionResponse . bodyHandler ( buffer -> responseChain . write ( buffer ) ) ; // Indicate back-end response is finished to the response chain. apiConnectionResponse . endHandler ( isEnd -> responseChain . end ( ) ) ; responseChain . doApply ( apiResponse ) ; } else { resultHandler . handle ( AsyncResultImpl . create ( result . getError ( ) ) ) ; } } ; }
Creates a response handler that is called by the api connector once a connection to the back end api has been made and a response received .
432
28
25,780
protected void handleStream ( ) { inboundStreamHandler . handle ( new ISignalWriteStream ( ) { boolean streamFinished = false ; @ Override public void write ( IApimanBuffer buffer ) { if ( streamFinished ) { throw new IllegalStateException ( "Attempted write after #end() was called." ) ; //$NON-NLS-1$ } requestChain . write ( buffer ) ; } @ Override public void end ( ) { requestChain . end ( ) ; streamFinished = true ; } /** * @see io.apiman.gateway.engine.io.IAbortable#abort() */ @ Override public void abort ( Throwable t ) { // If this is called, it means that something went wrong on the inbound // side of things - so we need to make sure we abort and cleanup the // api connector resources. We'll also call handle() on the result // handler so that the caller knows something went wrong. streamFinished = true ; apiConnection . abort ( t ) ; resultHandler . handle ( AsyncResultImpl . < IEngineResult > create ( new RequestAbortedException ( t ) ) ) ; } @ Override public boolean isFinished ( ) { return streamFinished ; } @ Override public void drainHandler ( IAsyncHandler < Void > drainHandler ) { apiConnection . drainHandler ( drainHandler ) ; } @ Override public boolean isFull ( ) { return apiConnection . isFull ( ) ; } } ) ; }
Called when the api connector is ready to receive data from the inbound client request .
320
18
25,781
private Chain < ApiRequest > createRequestChain ( IAsyncHandler < ApiRequest > requestHandler ) { RequestChain chain = new RequestChain ( policyImpls , context ) ; chain . headHandler ( requestHandler ) ; chain . policyFailureHandler ( failure -> { // Jump straight to the response leg. // It will likely not have been initialised, so create one. if ( responseChain == null ) { // Its response will not be used as we take the failure path only, so we just use an empty lambda. responseChain = createResponseChain ( ( ignored ) - > { } ) ; } responseChain . doFailure ( failure ) ; } ) ; chain . policyErrorHandler ( policyErrorHandler ) ; return chain ; }
Creates the chain used to apply policies in order to the api request .
153
15
25,782
private Chain < ApiResponse > createResponseChain ( IAsyncHandler < ApiResponse > responseHandler ) { ResponseChain chain = new ResponseChain ( policyImpls , context ) ; chain . headHandler ( responseHandler ) ; chain . policyFailureHandler ( result -> { if ( apiConnectionResponse != null ) { apiConnectionResponse . abort ( ) ; } policyFailureHandler . handle ( result ) ; } ) ; chain . policyErrorHandler ( result -> { if ( apiConnectionResponse != null ) { apiConnectionResponse . abort ( ) ; } policyErrorHandler . handle ( result ) ; } ) ; return chain ; }
Creates the chain used to apply policies in reverse order to the api response .
129
16
25,783
private IAsyncHandler < PolicyFailure > createPolicyFailureHandler ( ) { return policyFailure -> { // One of the policies has triggered a failure. At this point we should stop processing and // send the failure to the client for appropriate handling. EngineResultImpl engineResult = new EngineResultImpl ( policyFailure ) ; resultHandler . handle ( AsyncResultImpl . < IEngineResult > create ( engineResult ) ) ; } ; }
Creates the handler to use when a policy failure occurs during processing of a chain .
89
17
25,784
private IAsyncHandler < Throwable > createPolicyErrorHandler ( ) { return error -> resultHandler . handle ( AsyncResultImpl . < IEngineResult > create ( error ) ) ; }
Creates the handler to use when an error is detected during the processing of a chain .
40
18
25,785
private static File getDataDir ( ) { File rval = null ; // First check to see if a data directory has been explicitly configured via system property String dataDir = System . getProperty ( "apiman.bootstrap.data_dir" ) ; //$NON-NLS-1$ if ( dataDir != null ) { rval = new File ( dataDir ) ; } // If that wasn't set, then check to see if we're running in wildfly/eap if ( rval == null ) { dataDir = System . getProperty ( "jboss.server.data.dir" ) ; //$NON-NLS-1$ if ( dataDir != null ) { rval = new File ( dataDir , "bootstrap" ) ; //$NON-NLS-1$ } } // If that didn't work, try to locate a tomcat data directory if ( rval == null ) { dataDir = System . getProperty ( "catalina.home" ) ; //$NON-NLS-1$ if ( dataDir != null ) { rval = new File ( dataDir , "data/bootstrap" ) ; //$NON-NLS-1$ } } // If all else fails, just let it return null return rval ; }
Get the data directory
279
4
25,786
protected void configureBasicAuth ( HttpRequest request ) { try { String username = getConfig ( ) . getUsername ( ) ; String password = getConfig ( ) . getPassword ( ) ; String up = username + ":" + password ; //$NON-NLS-1$ String base64 = new String ( Base64 . encodeBase64 ( up . getBytes ( "UTF-8" ) ) ) ; //$NON-NLS-1$ String authHeader = "Basic " + base64 ; //$NON-NLS-1$ request . setHeader ( "Authorization" , authHeader ) ; //$NON-NLS-1$ } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Configures BASIC authentication for the request .
165
9
25,787
public void addFilter ( String name , String value , SearchCriteriaFilterOperator operator ) { SearchCriteriaFilterBean filter = new SearchCriteriaFilterBean ( ) ; filter . setName ( name ) ; filter . setValue ( value ) ; filter . setOperator ( operator ) ; filters . add ( filter ) ; }
Adds a single filter to the criteria .
71
8
25,788
public static Map < String , String > getSubmap ( Map < String , String > mapIn , String subkey ) { if ( mapIn == null || mapIn . isEmpty ( ) ) { return Collections . emptyMap ( ) ; } // Get map sub-element. return mapIn . entrySet ( ) . stream ( ) . filter ( entry -> entry . getKey ( ) . toLowerCase ( ) . startsWith ( subkey . toLowerCase ( ) ) ) . map ( entry -> { String newKey = entry . getKey ( ) . substring ( subkey . length ( ) , entry . getKey ( ) . length ( ) ) ; return new AbstractMap . SimpleImmutableEntry <> ( newKey , entry . getValue ( ) ) ; } ) . collect ( Collectors . toMap ( Entry :: getKey , Entry :: getValue ) ) ; }
Takes map and produces a submap using a key .
187
12
25,789
public static boolean valueChanged ( Set < ? > before , Set < ? > after ) { if ( ( before == null && after == null ) || after == null ) { return false ; } if ( before == null ) { if ( after . isEmpty ( ) ) { return false ; } else { return true ; } } else { if ( before . size ( ) != after . size ( ) ) { return true ; } for ( Object bean : after ) { if ( ! before . contains ( bean ) ) { return true ; } } } return false ; }
Returns true only if the set has changed .
118
9
25,790
public static boolean valueChanged ( Map < String , String > before , Map < String , String > after ) { if ( ( before == null && after == null ) || after == null ) { return false ; } if ( before == null ) { if ( after . isEmpty ( ) ) { return false ; } else { return true ; } } else { if ( before . size ( ) != after . size ( ) ) { return true ; } for ( Entry < String , String > entry : after . entrySet ( ) ) { String key = entry . getKey ( ) ; String afterValue = entry . getValue ( ) ; if ( ! before . containsKey ( key ) ) { return true ; } String beforeValue = before . get ( key ) ; if ( valueChanged ( beforeValue , afterValue ) ) { return true ; } } } return false ; }
Returns true only if the map has changed .
182
9
25,791
public static AuditEntryBean organizationUpdated ( OrganizationBean bean , EntityUpdatedData data , ISecurityContext securityContext ) { if ( data . getChanges ( ) . isEmpty ( ) ) { return null ; } AuditEntryBean entry = newEntry ( bean . getId ( ) , AuditEntityType . Organization , securityContext ) ; entry . setEntityId ( null ) ; entry . setEntityVersion ( null ) ; entry . setWhat ( AuditEntryType . Update ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the organization updated event .
118
11
25,792
public static AuditEntryBean membershipGranted ( String organizationId , MembershipData data , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( organizationId , AuditEntityType . Organization , securityContext ) ; entry . setEntityId ( null ) ; entry . setEntityVersion ( null ) ; entry . setWhat ( AuditEntryType . Grant ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the membership granted even .
94
11
25,793
public static AuditEntryBean apiCreated ( ApiBean bean , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( bean . getOrganization ( ) . getId ( ) , AuditEntityType . Api , securityContext ) ; entry . setEntityId ( bean . getId ( ) ) ; entry . setEntityVersion ( null ) ; entry . setData ( null ) ; entry . setWhat ( AuditEntryType . Create ) ; return entry ; }
Creates an audit entry for the API created event .
103
11
25,794
public static AuditEntryBean apiUpdated ( ApiBean bean , EntityUpdatedData data , ISecurityContext securityContext ) { if ( data . getChanges ( ) . isEmpty ( ) ) { return null ; } AuditEntryBean entry = newEntry ( bean . getOrganization ( ) . getId ( ) , AuditEntityType . Api , securityContext ) ; entry . setEntityId ( bean . getId ( ) ) ; entry . setEntityVersion ( null ) ; entry . setWhat ( AuditEntryType . Update ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the API updated event .
131
11
25,795
public static AuditEntryBean apiVersionUpdated ( ApiVersionBean bean , EntityUpdatedData data , ISecurityContext securityContext ) { if ( data . getChanges ( ) . isEmpty ( ) ) { return null ; } AuditEntryBean entry = newEntry ( bean . getApi ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Api , securityContext ) ; entry . setEntityId ( bean . getApi ( ) . getId ( ) ) ; entry . setEntityVersion ( bean . getVersion ( ) ) ; entry . setWhat ( AuditEntryType . Update ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the API version updated event .
150
12
25,796
public static AuditEntryBean clientCreated ( ClientBean bean , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( bean . getOrganization ( ) . getId ( ) , AuditEntityType . Client , securityContext ) ; entry . setEntityId ( bean . getId ( ) ) ; entry . setEntityVersion ( null ) ; entry . setData ( null ) ; entry . setWhat ( AuditEntryType . Create ) ; return entry ; }
Creates an audit entry for the client created event .
101
11
25,797
public static AuditEntryBean clientUpdated ( ClientBean bean , EntityUpdatedData data , ISecurityContext securityContext ) { if ( data . getChanges ( ) . isEmpty ( ) ) { return null ; } AuditEntryBean entry = newEntry ( bean . getOrganization ( ) . getId ( ) , AuditEntityType . Client , securityContext ) ; entry . setEntityId ( bean . getId ( ) ) ; entry . setEntityVersion ( null ) ; entry . setWhat ( AuditEntryType . Update ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the client updated event .
129
11
25,798
public static AuditEntryBean clientVersionUpdated ( ClientVersionBean bean , EntityUpdatedData data , ISecurityContext securityContext ) { if ( data . getChanges ( ) . isEmpty ( ) ) { return null ; } AuditEntryBean entry = newEntry ( bean . getClient ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Client , securityContext ) ; entry . setEntityId ( bean . getClient ( ) . getId ( ) ) ; entry . setEntityVersion ( bean . getVersion ( ) ) ; entry . setWhat ( AuditEntryType . Update ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the client version updated event .
146
12
25,799
public static AuditEntryBean contractCreatedToApi ( ContractBean bean , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( bean . getApi ( ) . getApi ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Api , securityContext ) ; // Ensure the order of contract-created events are deterministic by adding 1 ms to this one entry . setCreatedOn ( new Date ( entry . getCreatedOn ( ) . getTime ( ) + 1 ) ) ; entry . setWhat ( AuditEntryType . CreateContract ) ; entry . setEntityId ( bean . getApi ( ) . getApi ( ) . getId ( ) ) ; entry . setEntityVersion ( bean . getApi ( ) . getVersion ( ) ) ; ContractData data = new ContractData ( bean ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the contract created event .
201
11